import { T as ThemeService, t as toBigIntAwareJson } from './main.js';

/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
var UpdateSource = /* @__PURE__ */(UpdateSource2 => {
  UpdateSource2["MAIN_NET_DCL"] = "main-net-dcl";
  UpdateSource2["TEST_NET_DCL"] = "test-net-dcl";
  UpdateSource2["LOCAL"] = "local";
  return UpdateSource2;
})(UpdateSource || {});
const TEST_NODE_START = 0xfffffffe00000000n;
function isTestNodeId(nodeId) {
  const bigId = typeof nodeId === "bigint" ? nodeId : BigInt(nodeId);
  return bigId >= TEST_NODE_START;
}

/**
 * @license
 * Copyright 2021 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
let s$6 = class s extends Event {
  constructor(s, t, e, o) {
    super("context-request", {
      bubbles: true,
      composed: true
    }), this.context = s, this.contextTarget = t, this.callback = e, this.subscribe = o ?? false;
  }
};

/**
 * @license
 * Copyright 2021 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
function n$9(n) {
  return n;
}

/**
 * @license
 * Copyright 2021 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
let s$5 = class s {
  constructor(t, s, i, h) {
    if (this.subscribe = false, this.provided = false, this.value = void 0, this.t = (t, s) => {
      this.unsubscribe && (this.unsubscribe !== s && (this.provided = false, this.unsubscribe()), this.subscribe || this.unsubscribe()), this.value = t, this.host.requestUpdate(), this.provided && !this.subscribe || (this.provided = true, this.callback && this.callback(t, s)), this.unsubscribe = s;
    }, this.host = t, void 0 !== s.context) {
      const t = s;
      this.context = t.context, this.callback = t.callback, this.subscribe = t.subscribe ?? false;
    } else this.context = s, this.callback = i, this.subscribe = h ?? false;
    this.host.addController(this);
  }
  hostConnected() {
    this.dispatchRequest();
  }
  hostDisconnected() {
    this.unsubscribe && (this.unsubscribe(), this.unsubscribe = void 0);
  }
  dispatchRequest() {
    this.host.dispatchEvent(new s$6(this.context, this.host, this.t, this.subscribe));
  }
};

/**
 * @license
 * Copyright 2021 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
let s$4 = class s {
  get value() {
    return this.o;
  }
  set value(s) {
    this.setValue(s);
  }
  setValue(s, t = false) {
    const i = t || !Object.is(s, this.o);
    this.o = s, i && this.updateObservers();
  }
  constructor(s) {
    this.subscriptions = new Map(), this.updateObservers = () => {
      for (const [s, {
        disposer: t
      }] of this.subscriptions) s(this.o, t);
    }, void 0 !== s && (this.value = s);
  }
  addCallback(s, t, i) {
    if (!i) return void s(this.value);
    this.subscriptions.has(s) || this.subscriptions.set(s, {
      disposer: () => {
        this.subscriptions.delete(s);
      },
      consumerHost: t
    });
    const {
      disposer: h
    } = this.subscriptions.get(s);
    s(this.value, h);
  }
  clearCallbacks() {
    this.subscriptions.clear();
  }
};

/**
 * @license
 * Copyright 2021 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
let e$c = class e extends Event {
  constructor(t, s) {
    super("context-provider", {
      bubbles: true,
      composed: true
    }), this.context = t, this.contextTarget = s;
  }
};
let i$8 = class i extends s$4 {
  constructor(s, e, i) {
    super(void 0 !== e.context ? e.initialValue : i), this.onContextRequest = t => {
      if (t.context !== this.context) return;
      const s = t.contextTarget ?? t.composedPath()[0];
      s !== this.host && (t.stopPropagation(), this.addCallback(t.callback, s, t.subscribe));
    }, this.onProviderRequest = s => {
      if (s.context !== this.context) return;
      if ((s.contextTarget ?? s.composedPath()[0]) === this.host) return;
      const e = new Set();
      for (const [s, {
        consumerHost: i
      }] of this.subscriptions) e.has(s) || (e.add(s), i.dispatchEvent(new s$6(this.context, i, s, true)));
      s.stopPropagation();
    }, this.host = s, void 0 !== e.context ? this.context = e.context : this.context = e, this.attachListeners(), this.host.addController?.(this);
  }
  attachListeners() {
    this.host.addEventListener("context-request", this.onContextRequest), this.host.addEventListener("context-provider", this.onProviderRequest);
  }
  hostConnected() {
    this.host.dispatchEvent(new e$c(this.context, this.host));
  }
};

/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
function e$b({
  context: e
}) {
  return (n, i) => {
    const r = new WeakMap();
    if ("object" == typeof i) return {
      get() {
        return n.get.call(this);
      },
      set(t) {
        return r.get(this).setValue(t), n.set.call(this, t);
      },
      init(n) {
        return r.set(this, new i$8(this, {
          context: e,
          initialValue: n
        })), n;
      }
    };
    {
      n.constructor.addInitializer(n => {
        r.set(n, new i$8(n, {
          context: e
        }));
      });
      const o = Object.getOwnPropertyDescriptor(n, i);
      let s;
      if (void 0 === o) {
        const t = new WeakMap();
        s = {
          get() {
            return t.get(this);
          },
          set(e) {
            r.get(this).setValue(e), t.set(this, e);
          },
          configurable: true,
          enumerable: true
        };
      } else {
        const t = o.set;
        s = {
          ...o,
          set(e) {
            r.get(this).setValue(e), t?.call(this, e);
          }
        };
      }
      return void Object.defineProperty(n, i, s);
    }
  };
}

/**
 * @license
 * Copyright 2022 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
function c$5({
  context: c,
  subscribe: e
}) {
  return (o, n) => {
    "object" == typeof n ? n.addInitializer(function () {
      new s$5(this, {
        context: c,
        callback: t => {
          o.set.call(this, t);
        },
        subscribe: e
      });
    }) : o.constructor.addInitializer(o => {
      new s$5(o, {
        context: c,
        callback: t => {
          o[n] = t;
        },
        subscribe: e
      });
    });
  };
}

// Material Design Icons v7.4.47
var mdiAccessPoint="M4.93,4.93C3.12,6.74 2,9.24 2,12C2,14.76 3.12,17.26 4.93,19.07L6.34,17.66C4.89,16.22 4,14.22 4,12C4,9.79 4.89,7.78 6.34,6.34L4.93,4.93M19.07,4.93L17.66,6.34C19.11,7.78 20,9.79 20,12C20,14.22 19.11,16.22 17.66,17.66L19.07,19.07C20.88,17.26 22,14.76 22,12C22,9.24 20.88,6.74 19.07,4.93M7.76,7.76C6.67,8.85 6,10.35 6,12C6,13.65 6.67,15.15 7.76,16.24L9.17,14.83C8.45,14.11 8,13.11 8,12C8,10.89 8.45,9.89 9.17,9.17L7.76,7.76M16.24,7.76L14.83,9.17C15.55,9.89 16,10.89 16,12C16,13.11 15.55,14.11 14.83,14.83L16.24,16.24C17.33,15.15 18,13.65 18,12C18,10.35 17.33,8.85 16.24,7.76M12,10A2,2 0 0,0 10,12A2,2 0 0,0 12,14A2,2 0 0,0 14,12A2,2 0 0,0 12,10Z";var mdiAirConditioner="M6.59,0.66C8.93,-1.15 11.47,1.06 12.04,4.5C12.47,4.5 12.89,4.62 13.27,4.84C13.79,4.24 14.25,3.42 14.07,2.5C13.65,0.35 16.06,-1.39 18.35,1.58C20.16,3.92 17.95,6.46 14.5,7.03C14.5,7.46 14.39,7.89 14.16,8.27C14.76,8.78 15.58,9.24 16.5,9.06C18.63,8.64 20.38,11.04 17.41,13.34C15.07,15.15 12.53,12.94 11.96,9.5C11.53,9.5 11.11,9.37 10.74,9.15C10.22,9.75 9.75,10.58 9.93,11.5C10.35,13.64 7.94,15.39 5.65,12.42C3.83,10.07 6.05,7.53 9.5,6.97C9.5,6.54 9.63,6.12 9.85,5.74C9.25,5.23 8.43,4.76 7.5,4.94C5.37,5.36 3.62,2.96 6.59,0.66M5,16H7A2,2 0 0,1 9,18V24H7V22H5V24H3V18A2,2 0 0,1 5,16M5,18V20H7V18H5M12.93,16H15L12.07,24H10L12.93,16M18,16H21V18H18V22H21V24H18A2,2 0 0,1 16,22V18A2,2 0 0,1 18,16Z";var mdiAirFilter="M19,18.31V20A2,2 0 0,1 17,22H7A2,2 0 0,1 5,20V16.3C4.54,16.12 3.95,16 3,16A1,1 0 0,1 2,15A1,1 0 0,1 3,14C3.82,14 4.47,14.08 5,14.21V12.3C4.54,12.12 3.95,12 3,12A1,1 0 0,1 2,11A1,1 0 0,1 3,10C3.82,10 4.47,10.08 5,10.21V8.3C4.54,8.12 3.95,8 3,8A1,1 0 0,1 2,7A1,1 0 0,1 3,6C3.82,6 4.47,6.08 5,6.21V4A2,2 0 0,1 7,2H17A2,2 0 0,1 19,4V6.16C20.78,6.47 21.54,7.13 21.71,7.29C22.1,7.68 22.1,8.32 21.71,8.71C21.32,9.1 20.8,9.09 20.29,8.71V8.71C20.29,8.71 19.25,8 17,8C15.74,8 14.91,8.41 13.95,8.9C12.91,9.41 11.74,10 10,10C9.64,10 9.31,10 9,9.96V7.95C9.3,8 9.63,8 10,8C11.26,8 12.09,7.59 13.05,7.11C14.09,6.59 15.27,6 17,6V4H7V20H17V18C18.5,18 18.97,18.29 19,18.31M17,10C15.27,10 14.09,10.59 13.05,11.11C12.09,11.59 11.26,12 10,12C9.63,12 9.3,12 9,11.95V13.96C9.31,14 9.64,14 10,14C11.74,14 12.91,13.41 13.95,12.9C14.91,12.42 15.74,12 17,12C19.25,12 20.29,12.71 20.29,12.71V12.71C20.8,13.1 21.32,13.1 21.71,12.71C22.1,12.32 22.1,11.69 21.71,11.29C21.5,11.08 20.25,10 17,10M17,14C15.27,14 14.09,14.59 13.05,15.11C12.09,15.59 11.26,16 10,16C9.63,16 9.3,16 9,15.95V17.96C9.31,18 9.64,18 10,18C11.74,18 12.91,17.41 13.95,16.9C14.91,16.42 15.74,16 17,16C19.25,16 20.29,16.71 20.29,16.71V16.71C20.8,17.1 21.32,17.1 21.71,16.71C22.1,16.32 22.1,15.69 21.71,15.29C21.5,15.08 20.25,14 17,14Z";var mdiAirPurifier="M11,9A4,4 0 0,1 15,13A4,4 0 0,1 11,17A4,4 0 0,1 7,13A4,4 0 0,1 11,9M11,11A2,2 0 0,0 9,13A2,2 0 0,0 11,15A2,2 0 0,0 13,13A2,2 0 0,0 11,11M7,4H14A4,4 0 0,1 18,8V9H16V8A2,2 0 0,0 14,6H7A2,2 0 0,0 5,8V20H16V18H18V22H3V8A4,4 0 0,1 7,4M16,11C18.5,11 18.5,9 21,9V11C18.5,11 18.5,13 16,13V11M16,15C18.5,15 18.5,13 21,13V15C18.5,15 18.5,17 16,17V15Z";var mdiAlert="M13 14H11V9H13M13 18H11V16H13M1 21H23L12 2L1 21Z";var mdiAlertCircleOutline="M11,15H13V17H11V15M11,7H13V13H11V7M12,2C6.47,2 2,6.5 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M12,20A8,8 0 0,1 4,12A8,8 0 0,1 12,4A8,8 0 0,1 20,12A8,8 0 0,1 12,20Z";var mdiArrowDown="M11,4H13V16L18.5,10.5L19.92,11.92L12,19.84L4.08,11.92L5.5,10.5L11,16V4Z";var mdiArrowLeft="M20,11V13H8L13.5,18.5L12.08,19.92L4.16,12L12.08,4.08L13.5,5.5L8,11H20Z";var mdiArrowRight="M4,11V13H16L10.5,18.5L11.92,19.92L19.84,12L11.92,4.08L10.5,5.5L16,11H4Z";var mdiArrowUp="M13,20H11V8L5.5,13.5L4.08,12.08L12,4.16L19.92,12.08L18.5,13.5L13,8V20Z";var mdiBell="M21,19V20H3V19L5,17V11C5,7.9 7.03,5.17 10,4.29C10,4.19 10,4.1 10,4A2,2 0 0,1 12,2A2,2 0 0,1 14,4C14,4.1 14,4.19 14,4.29C16.97,5.17 19,7.9 19,11V17L21,19M14,21A2,2 0 0,1 12,23A2,2 0 0,1 10,21";var mdiBlindsHorizontal="M20 19V3H4V19H2V21H22V19H20M16 9H18V11H16V9M14 11H6V9H14V11M18 7H16V5H18V7M14 5V7H6V5H14M6 19V13H14V14.82C13.55 15.14 13.25 15.66 13.25 16.25C13.25 17.22 14.03 18 15 18S16.75 17.22 16.75 16.25C16.75 15.66 16.45 15.13 16 14.82V13H18V19H6Z";var mdiBrightnessAuto="M14.3,16L13.6,14H10.4L9.7,16H7.8L11,7H13L16.2,16H14.3M20,8.69V4H15.31L12,0.69L8.69,4H4V8.69L0.69,12L4,15.31V20H8.69L12,23.31L15.31,20H20V15.31L23.31,12L20,8.69M10.85,12.65H13.15L12,9L10.85,12.65Z";var mdiBrightnessPercent="M20.04,8.71V4H15.34L12,0.69L8.71,4H4V8.71L0.69,12L4,15.34V20.04H8.71L12,23.35L15.34,20.04H20.04V15.34L23.35,12L20.04,8.71M8.83,7.05C9.81,7.05 10.6,7.84 10.6,8.83A1.77,1.77 0 0,1 8.83,10.6C7.84,10.6 7.05,9.81 7.05,8.83C7.05,7.84 7.84,7.05 8.83,7.05M15.22,17C14.24,17 13.45,16.2 13.45,15.22A1.77,1.77 0 0,1 15.22,13.45C16.2,13.45 17,14.24 17,15.22A1.78,1.78 0 0,1 15.22,17M8.5,17.03L7,15.53L15.53,7L17.03,8.5L8.5,17.03Z";var mdiCamera="M4,4H7L9,2H15L17,4H20A2,2 0 0,1 22,6V18A2,2 0 0,1 20,20H4A2,2 0 0,1 2,18V6A2,2 0 0,1 4,4M12,7A5,5 0 0,0 7,12A5,5 0 0,0 12,17A5,5 0 0,0 17,12A5,5 0 0,0 12,7M12,9A3,3 0 0,1 15,12A3,3 0 0,1 12,15A3,3 0 0,1 9,12A3,3 0 0,1 12,9Z";var mdiCast="M1,10V12A9,9 0 0,1 10,21H12C12,14.92 7.07,10 1,10M1,14V16A5,5 0 0,1 6,21H8A7,7 0 0,0 1,14M1,18V21H4A3,3 0 0,0 1,18M21,3H3C1.89,3 1,3.89 1,5V8H3V5H21V19H14V21H21A2,2 0 0,0 23,19V5C23,3.89 22.1,3 21,3Z";var mdiCctv="M6.03 12.03L8.03 15.5L5.5 18.68L2 12.62L6.03 12.03M17 18V15.29C17.88 14.9 18.5 14.03 18.5 13C18.5 12.43 18.3 11.9 17.97 11.5L19.94 10.35C20.95 9.76 21.3 8.47 20.71 7.46L19.33 5.06C18.74 4.05 17.45 3.7 16.44 4.28L8.31 9C7.36 9.53 7.03 10.75 7.58 11.71L9.08 14.31C9.63 15.26 10.86 15.59 11.81 15.04L13.69 13.96C13.94 14.55 14.41 15.03 15 15.29V18C15 19.1 15.9 20 17 20H22V18H17Z";var mdiChatProcessing="M12,3C17.5,3 22,6.58 22,11C22,15.42 17.5,19 12,19C10.76,19 9.57,18.82 8.47,18.5C5.55,21 2,21 2,21C4.33,18.67 4.7,17.1 4.75,16.5C3.05,15.07 2,13.13 2,11C2,6.58 6.5,3 12,3M17,12V10H15V12H17M13,12V10H11V12H13M9,12V10H7V12H9Z";var mdiChevronDown="M7.41,8.58L12,13.17L16.59,8.58L18,10L12,16L6,10L7.41,8.58Z";var mdiChevronRight="M8.59,16.58L13.17,12L8.59,7.41L10,6L16,12L10,18L8.59,16.58Z";var mdiChip="M6,4H18V5H21V7H18V9H21V11H18V13H21V15H18V17H21V19H18V20H6V19H3V17H6V15H3V13H6V11H3V9H6V7H3V5H6V4M11,15V18H12V15H11M13,15V18H14V15H13M15,15V18H16V15H15Z";var mdiCircleMedium="M12,8A4,4 0 0,0 8,12A4,4 0 0,0 12,16A4,4 0 0,0 16,12A4,4 0 0,0 12,8Z";var mdiClose="M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z";var mdiCog="M12,15.5A3.5,3.5 0 0,1 8.5,12A3.5,3.5 0 0,1 12,8.5A3.5,3.5 0 0,1 15.5,12A3.5,3.5 0 0,1 12,15.5M19.43,12.97C19.47,12.65 19.5,12.33 19.5,12C19.5,11.67 19.47,11.34 19.43,11L21.54,9.37C21.73,9.22 21.78,8.95 21.66,8.73L19.66,5.27C19.54,5.05 19.27,4.96 19.05,5.05L16.56,6.05C16.04,5.66 15.5,5.32 14.87,5.07L14.5,2.42C14.46,2.18 14.25,2 14,2H10C9.75,2 9.54,2.18 9.5,2.42L9.13,5.07C8.5,5.32 7.96,5.66 7.44,6.05L4.95,5.05C4.73,4.96 4.46,5.05 4.34,5.27L2.34,8.73C2.21,8.95 2.27,9.22 2.46,9.37L4.57,11C4.53,11.34 4.5,11.67 4.5,12C4.5,12.33 4.53,12.65 4.57,12.97L2.46,14.63C2.27,14.78 2.21,15.05 2.34,15.27L4.34,18.73C4.46,18.95 4.73,19.03 4.95,18.95L7.44,17.94C7.96,18.34 8.5,18.68 9.13,18.93L9.5,21.58C9.54,21.82 9.75,22 10,22H14C14.25,22 14.46,21.82 14.5,21.58L14.87,18.93C15.5,18.67 16.04,18.34 16.56,17.94L19.05,18.95C19.27,19.03 19.54,18.95 19.66,18.73L21.66,15.27C21.78,15.05 21.73,14.78 21.54,14.63L19.43,12.97Z";var mdiContentSaveOutline="M17 3H5C3.89 3 3 3.9 3 5V19C3 20.1 3.89 21 5 21H19C20.1 21 21 20.1 21 19V7L17 3M19 19H5V5H16.17L19 7.83V19M12 12C10.34 12 9 13.34 9 15S10.34 18 12 18 15 16.66 15 15 13.66 12 12 12M6 6H15V10H6V6Z";var mdiCrown="M5 16L3 5L8.5 10L12 4L15.5 10L21 5L19 16H5M19 19C19 19.6 18.6 20 18 20H6C5.4 20 5 19.6 5 19V18H19V19Z";var mdiDishwasher="M18,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V4A2,2 0 0,0 18,2M10,4A1,1 0 0,1 11,5A1,1 0 0,1 10,6A1,1 0 0,1 9,5A1,1 0 0,1 10,4M7,4A1,1 0 0,1 8,5A1,1 0 0,1 7,6A1,1 0 0,1 6,5A1,1 0 0,1 7,4M18,20H6V8H18V20M14.67,15.33C14.69,16.03 14.41,16.71 13.91,17.21C12.86,18.26 11.15,18.27 10.09,17.21C9.59,16.71 9.31,16.03 9.33,15.33C9.4,14.62 9.63,13.94 10,13.33C10.37,12.5 10.81,11.73 11.33,11L12,10C13.79,12.59 14.67,14.36 14.67,15.33";var mdiDoorOpen="M12,3C10.89,3 10,3.89 10,5H3V19H2V21H22V19H21V5C21,3.89 20.11,3 19,3H12M12,5H19V19H12V5M5,11H7V13H5V11Z";var mdiDoorbell="M12 10C10.9 10 10 10.9 10 12S10.9 14 12 14 14 13.1 14 12 13.1 10 12 10M16 2H8C6.9 2 6 2.9 6 4V20C6 21.1 6.9 22 8 22H16C17.1 22 18 21.1 18 20V4C18 2.9 17.1 2 16 2M16 20H8V4H16V20Z";var mdiDoorbellVideo="M14 15C14 16.11 13.11 17 12 17S10 16.11 10 15 10.9 13 12 13 14 13.9 14 15M18 4V20C18 21.1 17.11 22 16 22H8C6.9 22 6 21.11 6 20V4C6 2.9 6.9 2 8 2H16C17.11 2 18 2.9 18 4M10.5 7C10.5 7.83 11.17 8.5 12 8.5S13.5 7.83 13.5 7 12.83 5.5 12 5.5 10.5 6.17 10.5 7M16 10H8V20H16V10Z";var mdiEthernet="M7,15H9V18H11V15H13V18H15V15H17V18H19V9H15V6H9V9H5V18H7V15M4.38,3H19.63C20.94,3 22,4.06 22,5.38V19.63A2.37,2.37 0 0,1 19.63,22H4.38C3.06,22 2,20.94 2,19.63V5.38C2,4.06 3.06,3 4.38,3Z";var mdiEvStation="M19.77,7.23L19.78,7.22L16.06,3.5L15,4.56L17.11,6.67C16.17,7.03 15.5,7.93 15.5,9A2.5,2.5 0 0,0 18,11.5C18.36,11.5 18.69,11.42 19,11.29V18.5A1,1 0 0,1 18,19.5A1,1 0 0,1 17,18.5V14A2,2 0 0,0 15,12H14V5A2,2 0 0,0 12,3H6A2,2 0 0,0 4,5V21H14V13.5H15.5V18.5A2.5,2.5 0 0,0 18,21A2.5,2.5 0 0,0 20.5,18.5V9C20.5,8.31 20.22,7.68 19.77,7.23M18,10A1,1 0 0,1 17,9A1,1 0 0,1 18,8A1,1 0 0,1 19,9A1,1 0 0,1 18,10M8,18V13.5H6L10,6V11H12L8,18Z";var mdiEye="M12,9A3,3 0 0,0 9,12A3,3 0 0,0 12,15A3,3 0 0,0 15,12A3,3 0 0,0 12,9M12,17A5,5 0 0,1 7,12A5,5 0 0,1 12,7A5,5 0 0,1 17,12A5,5 0 0,1 12,17M12,4.5C7,4.5 2.73,7.61 1,12C2.73,16.39 7,19.5 12,19.5C17,19.5 21.27,16.39 23,12C21.27,7.61 17,4.5 12,4.5Z";var mdiEyeOff="M11.83,9L15,12.16C15,12.11 15,12.05 15,12A3,3 0 0,0 12,9C11.94,9 11.89,9 11.83,9M7.53,9.8L9.08,11.35C9.03,11.56 9,11.77 9,12A3,3 0 0,0 12,15C12.22,15 12.44,14.97 12.65,14.92L14.2,16.47C13.53,16.8 12.79,17 12,17A5,5 0 0,1 7,12C7,11.21 7.2,10.47 7.53,9.8M2,4.27L4.28,6.55L4.73,7C3.08,8.3 1.78,10 1,12C2.73,16.39 7,19.5 12,19.5C13.55,19.5 15.03,19.2 16.38,18.66L16.81,19.08L19.73,22L21,20.73L3.27,3M12,7A5,5 0 0,1 17,12C17,12.64 16.87,13.26 16.64,13.82L19.57,16.75C21.07,15.5 22.27,13.86 23,12C21.27,7.61 17,4.5 12,4.5C10.6,4.5 9.26,4.75 8,5.2L10.17,7.35C10.74,7.13 11.35,7 12,7Z";var mdiFan="M12,11A1,1 0 0,0 11,12A1,1 0 0,0 12,13A1,1 0 0,0 13,12A1,1 0 0,0 12,11M12.5,2C17,2 17.11,5.57 14.75,6.75C13.76,7.24 13.32,8.29 13.13,9.22C13.61,9.42 14.03,9.73 14.35,10.13C18.05,8.13 22.03,8.92 22.03,12.5C22.03,17 18.46,17.1 17.28,14.73C16.78,13.74 15.72,13.3 14.79,13.11C14.59,13.59 14.28,14 13.88,14.34C15.87,18.03 15.08,22 11.5,22C7,22 6.91,18.42 9.27,17.24C10.25,16.75 10.69,15.71 10.89,14.79C10.4,14.59 9.97,14.27 9.65,13.87C5.96,15.85 2,15.07 2,11.5C2,7 5.56,6.89 6.74,9.26C7.24,10.25 8.29,10.68 9.22,10.87C9.41,10.39 9.73,9.97 10.14,9.65C8.15,5.96 8.94,2 12.5,2Z";var mdiFile="M13,9V3.5L18.5,9M6,2C4.89,2 4,2.89 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2H6Z";var mdiFitToScreen="M17 4H20C21.1 4 22 4.9 22 6V8H20V6H17V4M4 8V6H7V4H4C2.9 4 2 4.9 2 6V8H4M20 16V18H17V20H20C21.1 20 22 19.1 22 18V16H20M7 18H4V16H2V18C2 19.1 2.9 20 4 20H7V18M18 8H6V16H18V8Z";var mdiFridge="M7,2H17A2,2 0 0,1 19,4V9H5V4A2,2 0 0,1 7,2M19,19A2,2 0 0,1 17,21V22H15V21H9V22H7V21A2,2 0 0,1 5,19V10H19V19M8,5V7H10V5H8M8,12V15H10V12H8Z";var mdiGauge="M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M12,4A8,8 0 0,1 20,12C20,14.4 19,16.5 17.3,18C15.9,16.7 14,16 12,16C10,16 8.2,16.7 6.7,18C5,16.5 4,14.4 4,12A8,8 0 0,1 12,4M14,5.89C13.62,5.9 13.26,6.15 13.1,6.54L11.81,9.77L11.71,10C11,10.13 10.41,10.6 10.14,11.26C9.73,12.29 10.23,13.45 11.26,13.86C12.29,14.27 13.45,13.77 13.86,12.74C14.12,12.08 14,11.32 13.57,10.76L13.67,10.5L14.96,7.29L14.97,7.26C15.17,6.75 14.92,6.17 14.41,5.96C14.28,5.91 14.15,5.89 14,5.89M10,6A1,1 0 0,0 9,7A1,1 0 0,0 10,8A1,1 0 0,0 11,7A1,1 0 0,0 10,6M7,9A1,1 0 0,0 6,10A1,1 0 0,0 7,11A1,1 0 0,0 8,10A1,1 0 0,0 7,9M17,9A1,1 0 0,0 16,10A1,1 0 0,0 17,11A1,1 0 0,0 18,10A1,1 0 0,0 17,9Z";var mdiGraphOutline="M19.5 17C19.36 17 19.24 17 19.11 17.04L17.5 13.8C17.95 13.35 18.25 12.71 18.25 12C18.25 10.62 17.13 9.5 15.75 9.5C15.61 9.5 15.5 9.5 15.35 9.54L13.74 6.3C14.21 5.84 14.5 5.21 14.5 4.5C14.5 3.12 13.38 2 12 2S9.5 3.12 9.5 4.5C9.5 5.2 9.79 5.84 10.26 6.29L8.65 9.54C8.5 9.5 8.39 9.5 8.25 9.5C6.87 9.5 5.75 10.62 5.75 12C5.75 12.71 6.04 13.34 6.5 13.79L4.89 17.04C4.76 17 4.64 17 4.5 17C3.12 17 2 18.12 2 19.5C2 20.88 3.12 22 4.5 22S7 20.88 7 19.5C7 18.8 6.71 18.16 6.24 17.71L7.86 14.46C8 14.5 8.12 14.5 8.25 14.5C8.38 14.5 8.5 14.5 8.63 14.46L10.26 17.71C9.79 18.16 9.5 18.8 9.5 19.5C9.5 20.88 10.62 22 12 22S14.5 20.88 14.5 19.5C14.5 18.12 13.38 17 12 17C11.87 17 11.74 17 11.61 17.04L10 13.8C10.45 13.35 10.75 12.71 10.75 12C10.75 11.3 10.46 10.67 10 10.21L11.61 6.96C11.74 7 11.87 7 12 7C12.13 7 12.26 7 12.39 6.96L14 10.21C13.54 10.66 13.25 11.3 13.25 12C13.25 13.38 14.37 14.5 15.75 14.5C15.88 14.5 16 14.5 16.13 14.46L17.76 17.71C17.29 18.16 17 18.8 17 19.5C17 20.88 18.12 22 19.5 22S22 20.88 22 19.5C22 18.12 20.88 17 19.5 17M4.5 20.5C3.95 20.5 3.5 20.05 3.5 19.5S3.95 18.5 4.5 18.5 5.5 18.95 5.5 19.5 5.05 20.5 4.5 20.5M13 19.5C13 20.05 12.55 20.5 12 20.5S11 20.05 11 19.5 11.45 18.5 12 18.5 13 18.95 13 19.5M7.25 12C7.25 11.45 7.7 11 8.25 11S9.25 11.45 9.25 12 8.8 13 8.25 13 7.25 12.55 7.25 12M11 4.5C11 3.95 11.45 3.5 12 3.5S13 3.95 13 4.5 12.55 5.5 12 5.5 11 5.05 11 4.5M14.75 12C14.75 11.45 15.2 11 15.75 11S16.75 11.45 16.75 12 16.3 13 15.75 13 14.75 12.55 14.75 12M19.5 20.5C18.95 20.5 18.5 20.05 18.5 19.5S18.95 18.5 19.5 18.5 20.5 18.95 20.5 19.5 20.05 20.5 19.5 20.5Z";var mdiHeatPump="M19 3H5C3.9 3 3 3.9 3 5V19C3 20.1 3.9 21 5 21H19C20.1 21 21 20.1 21 19V5C21 3.9 20.1 3 19 3M12.75 7.08C13.57 7.2 14.32 7.5 14.95 8L12.75 10.19V7.08M11.25 7.08V10.19L9.05 8C9.68 7.5 10.43 7.2 11.25 7.08M8 9.05L10.19 11.25H7.08C7.2 10.43 7.5 9.68 8 9.05M7.08 12.75H10.19L8 14.95C7.5 14.32 7.2 13.57 7.08 12.75M11.25 16.92C10.43 16.8 9.68 16.5 9.05 16L11.25 13.81V16.92M12 13C11.45 13 11 12.55 11 12S11.45 11 12 11 13 11.45 13 12 12.55 13 12 13M12.75 16.92V13.81L14.95 16C14.32 16.5 13.57 16.8 12.75 16.92M16 14.95L13.81 12.75H16.92C16.8 13.57 16.5 14.32 16 14.95M13.81 11.25L16 9.05C16.5 9.69 16.8 10.44 16.92 11.25H13.81Z";var mdiHelp="M10,19H13V22H10V19M12,2C17.35,2.22 19.68,7.62 16.5,11.67C15.67,12.67 14.33,13.33 13.67,14.17C13,15 13,16 13,17H10C10,15.33 10,13.92 10.67,12.92C11.33,11.92 12.67,11.33 13.5,10.67C15.92,8.43 15.32,5.26 12,5A3,3 0 0,0 9,8H6A6,6 0 0,1 12,2Z";var mdiHome="M10,20V14H14V20H19V12H22L12,3L2,12H5V20H10Z";var mdiLeaf="M17,8C8,10 5.9,16.17 3.82,21.34L5.71,22L6.66,19.7C7.14,19.87 7.64,20 8,20C19,20 22,3 22,3C21,5 14,5.25 9,6.25C4,7.25 2,11.5 2,13.5C2,15.5 3.75,17.25 3.75,17.25C7,8 17,8 17,8Z";var mdiLightbulb="M12,2A7,7 0 0,0 5,9C5,11.38 6.19,13.47 8,14.74V17A1,1 0 0,0 9,18H15A1,1 0 0,0 16,17V14.74C17.81,13.47 19,11.38 19,9A7,7 0 0,0 12,2M9,21A1,1 0 0,0 10,22H14A1,1 0 0,0 15,21V20H9V21Z";var mdiLink="M3.9,12C3.9,10.29 5.29,8.9 7,8.9H11V7H7A5,5 0 0,0 2,12A5,5 0 0,0 7,17H11V15.1H7C5.29,15.1 3.9,13.71 3.9,12M8,13H16V11H8V13M17,7H13V8.9H17C18.71,8.9 20.1,10.29 20.1,12C20.1,13.71 18.71,15.1 17,15.1H13V17H17A5,5 0 0,0 22,12A5,5 0 0,0 17,7Z";var mdiLinkVariantOff="M2,5.27L3.28,4L20,20.72L18.73,22L13.9,17.17L11.29,19.78C9.34,21.73 6.17,21.73 4.22,19.78C2.27,17.83 2.27,14.66 4.22,12.71L5.71,11.22C5.7,12.04 5.83,12.86 6.11,13.65L5.64,14.12C4.46,15.29 4.46,17.19 5.64,18.36C6.81,19.54 8.71,19.54 9.88,18.36L12.5,15.76L10.88,14.15C10.87,14.39 10.77,14.64 10.59,14.83C10.2,15.22 9.56,15.22 9.17,14.83C8.12,13.77 7.63,12.37 7.72,11L2,5.27M12.71,4.22C14.66,2.27 17.83,2.27 19.78,4.22C21.73,6.17 21.73,9.34 19.78,11.29L18.29,12.78C18.3,11.96 18.17,11.14 17.89,10.36L18.36,9.88C19.54,8.71 19.54,6.81 18.36,5.64C17.19,4.46 15.29,4.46 14.12,5.64L10.79,8.97L9.38,7.55L12.71,4.22M13.41,9.17C13.8,8.78 14.44,8.78 14.83,9.17C16.2,10.54 16.61,12.5 16.06,14.23L14.28,12.46C14.23,11.78 13.94,11.11 13.41,10.59C13,10.2 13,9.56 13.41,9.17Z";var mdiLoading="M12,4V2A10,10 0 0,0 2,12H4A8,8 0 0,1 12,4Z";var mdiLock="M12,17A2,2 0 0,0 14,15C14,13.89 13.1,13 12,13A2,2 0 0,0 10,15A2,2 0 0,0 12,17M18,8A2,2 0 0,1 20,10V20A2,2 0 0,1 18,22H6A2,2 0 0,1 4,20V10C4,8.89 4.9,8 6,8H7V6A5,5 0 0,1 12,1A5,5 0 0,1 17,6V8H18M12,3A3,3 0 0,0 9,6V8H15V6A3,3 0 0,0 12,3Z";var mdiLogout="M17 7L15.59 8.41L18.17 11H8V13H18.17L15.59 15.58L17 17L22 12M4 5H12V3H4C2.9 3 2 3.9 2 5V19C2 20.1 2.9 21 4 21H12V19H4V5Z";var mdiMagnifyMinus="M9,2A7,7 0 0,1 16,9C16,10.57 15.5,12 14.61,13.19L15.41,14H16L22,20L20,22L14,16V15.41L13.19,14.61C12,15.5 10.57,16 9,16A7,7 0 0,1 2,9A7,7 0 0,1 9,2M5,8V10H13V8H5Z";var mdiMagnifyPlus="M9,2A7,7 0 0,1 16,9C16,10.57 15.5,12 14.61,13.19L15.41,14H16L22,20L20,22L14,16V15.41L13.19,14.61C12,15.5 10.57,16 9,16A7,7 0 0,1 2,9A7,7 0 0,1 9,2M8,5V8H5V10H8V13H10V10H13V8H10V5H8Z";var mdiMeterElectric="M12 2C7.04 2 3 6.04 3 11C3 14.91 5.5 18.24 9 19.47V22H11V19.94C11.33 20 11.66 20 12 20S12.67 20 13 19.94V22H15V19.47C18.5 18.23 21 14.9 21 11C21 6.04 16.96 2 12 2M14.25 14L11.25 17L9.75 15.5L11 14.25L9.75 13L12.75 10L14.25 11.5L13 12.75L14.25 14M16 9H8V7H16V9Z";var mdiMicrowave="M4,5A2,2 0 0,0 2,7V17A2,2 0 0,0 4,19H20A2,2 0 0,0 22,17V7A2,2 0 0,0 20,5H4M4,7H16V17H4V7M19,7A1,1 0 0,1 20,8A1,1 0 0,1 19,9A1,1 0 0,1 18,8A1,1 0 0,1 19,7M13,9V15H15V9H13M19,11A1,1 0 0,1 20,12A1,1 0 0,1 19,13A1,1 0 0,1 18,12A1,1 0 0,1 19,11Z";var mdiMinus="M19,13H5V11H19V13Z";var mdiMotionSensor="M10,0.2C9,0.2 8.2,1 8.2,2C8.2,3 9,3.8 10,3.8C11,3.8 11.8,3 11.8,2C11.8,1 11,0.2 10,0.2M15.67,1A7.33,7.33 0 0,0 23,8.33V7A6,6 0 0,1 17,1H15.67M18.33,1C18.33,3.58 20.42,5.67 23,5.67V4.33C21.16,4.33 19.67,2.84 19.67,1H18.33M21,1A2,2 0 0,0 23,3V1H21M7.92,4.03C7.75,4.03 7.58,4.06 7.42,4.11L2,5.8V11H3.8V7.33L5.91,6.67L2,22H3.8L6.67,13.89L9,17V22H10.8V15.59L8.31,11.05L9.04,8.18L10.12,10H15V8.2H11.38L9.38,4.87C9.08,4.37 8.54,4.03 7.92,4.03Z";var mdiPause="M14,19H18V5H14M6,19H10V5H6V19Z";var mdiPencil="M20.71,7.04C21.1,6.65 21.1,6 20.71,5.63L18.37,3.29C18,2.9 17.35,2.9 16.96,3.29L15.12,5.12L18.87,8.87M3,17.25V21H6.75L17.81,9.93L14.06,6.18L3,17.25Z";var mdiPlay="M8,5.14V19.14L19,12.14L8,5.14Z";var mdiPlus="M19,13H13V19H11V13H5V11H11V5H13V11H19V13Z";var mdiPowerPlug="M16,7V3H14V7H10V3H8V7H8C7,7 6,8 6,9V14.5L9.5,18V21H14.5V18L18,14.5V9C18,8 17,7 16,7Z";var mdiPump="M2 21V15H3.5C3.18 14.06 3 13.05 3 12C3 7.03 7.03 3 12 3H22V9H20.5C20.82 9.94 21 10.95 21 12C21 16.97 16.97 21 12 21H2M5 12C5 13.28 5.34 14.47 5.94 15.5L9.4 13.5C9.15 13.06 9 12.55 9 12C9 11.35 9.21 10.75 9.56 10.26L6.3 7.93C5.5 9.08 5 10.5 5 12M12 19C14.59 19 16.85 17.59 18.06 15.5L14.6 13.5C14.08 14.4 13.11 15 12 15L11.71 15L11.33 18.97L12 19M12 9C13.21 9 14.26 9.72 14.73 10.76L18.37 9.1C17.27 6.68 14.83 5 12 5V9M12 11C11.45 11 11 11.45 11 12C11 12.55 11.45 13 12 13C12.55 13 13 12.55 13 12C13 11.45 12.55 11 12 11Z";var mdiRefresh="M17.65,6.35C16.2,4.9 14.21,4 12,4A8,8 0 0,0 4,12A8,8 0 0,0 12,20C15.73,20 18.84,17.45 19.73,14H17.65C16.83,16.33 14.61,18 12,18A6,6 0 0,1 6,12A6,6 0 0,1 12,6C13.66,6 15.14,6.69 16.22,7.78L13,11H20V4L17.65,6.35Z";var mdiRemote="M12,0C8.96,0 6.21,1.23 4.22,3.22L5.63,4.63C7.26,3 9.5,2 12,2C14.5,2 16.74,3 18.36,4.64L19.77,3.23C17.79,1.23 15.04,0 12,0M7.05,6.05L8.46,7.46C9.37,6.56 10.62,6 12,6C13.38,6 14.63,6.56 15.54,7.46L16.95,6.05C15.68,4.78 13.93,4 12,4C10.07,4 8.32,4.78 7.05,6.05M12,15A2,2 0 0,1 10,13A2,2 0 0,1 12,11A2,2 0 0,1 14,13A2,2 0 0,1 12,15M15,9H9A1,1 0 0,0 8,10V22A1,1 0 0,0 9,23H15A1,1 0 0,0 16,22V10A1,1 0 0,0 15,9Z";var mdiRobotVacuum="M12,2C14.65,2 17.19,3.06 19.07,4.93L17.65,6.35C16.15,4.85 14.12,4 12,4C9.88,4 7.84,4.84 6.35,6.35L4.93,4.93C6.81,3.06 9.35,2 12,2M3.66,6.5L5.11,7.94C4.39,9.17 4,10.57 4,12A8,8 0 0,0 12,20A8,8 0 0,0 20,12C20,10.57 19.61,9.17 18.88,7.94L20.34,6.5C21.42,8.12 22,10.04 22,12A10,10 0 0,1 12,22A10,10 0 0,1 2,12C2,10.04 2.58,8.12 3.66,6.5M12,6A6,6 0 0,1 18,12C18,13.59 17.37,15.12 16.24,16.24L14.83,14.83C14.08,15.58 13.06,16 12,16C10.94,16 9.92,15.58 9.17,14.83L7.76,16.24C6.63,15.12 6,13.59 6,12A6,6 0 0,1 12,6M12,8A1,1 0 0,0 11,9A1,1 0 0,0 12,10A1,1 0 0,0 13,9A1,1 0 0,0 12,8Z";var mdiRouter="M12 2C6.5 2 2 6.5 2 12C2 17.5 6.5 22 12 22C17.5 22 22 17.5 22 12C22 6.5 17.5 2 12 2M12 20C7.58 20 4 16.42 4 12C4 7.58 7.58 4 12 4C16.42 4 20 7.58 20 12C20 16.42 16.42 20 12 20M13 13V16H15L12 19L9 16H11V13M5 13H8V15L11 12L8 9V11H5M11 11V8H9L12 5L15 8H13V11M19 11H16V9L13 12L16 15V13H19";var mdiRouterWireless="M20.2,5.9L21,5.1C19.6,3.7 17.8,3 16,3C14.2,3 12.4,3.7 11,5.1L11.8,5.9C13,4.8 14.5,4.2 16,4.2C17.5,4.2 19,4.8 20.2,5.9M19.3,6.7C18.4,5.8 17.2,5.3 16,5.3C14.8,5.3 13.6,5.8 12.7,6.7L13.5,7.5C14.2,6.8 15.1,6.5 16,6.5C16.9,6.5 17.8,6.8 18.5,7.5L19.3,6.7M19,13H17V9H15V13H5A2,2 0 0,0 3,15V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V15A2,2 0 0,0 19,13M8,18H6V16H8V18M11.5,18H9.5V16H11.5V18M15,18H13V16H15V18Z";var mdiShareVariant="M18,16.08C17.24,16.08 16.56,16.38 16.04,16.85L8.91,12.7C8.96,12.47 9,12.24 9,12C9,11.76 8.96,11.53 8.91,11.3L15.96,7.19C16.5,7.69 17.21,8 18,8A3,3 0 0,0 21,5A3,3 0 0,0 18,2A3,3 0 0,0 15,5C15,5.24 15.04,5.47 15.09,5.7L8.04,9.81C7.5,9.31 6.79,9 6,9A3,3 0 0,0 3,12A3,3 0 0,0 6,15C6.79,15 7.5,14.69 8.04,14.19L15.16,18.34C15.11,18.55 15.08,18.77 15.08,19C15.08,20.61 16.39,21.91 18,21.91C19.61,21.91 20.92,20.61 20.92,19A2.92,2.92 0 0,0 18,16.08Z";var mdiSignalCellular1="M19.5,5.5V18.5H17.5V5.5H19.5M12.5,10.5V18.5H10.5V10.5H12.5M21,4H16V20H21V4M14,9H9V20H14V9M7,14H2V20H7V14Z";var mdiSignalCellular2="M19.5,5.5V18.5H17.5V5.5H19.5M21,4H16V20H21V4M14,9H9V20H14V9M7,14H2V20H7V14Z";var mdiSignalCellular3="M21,4H16V20H21V4M14,9H9V20H14V9M7,14H2V20H7V14Z";var mdiSleep="M23,12H17V10L20.39,6H17V4H23V6L19.62,10H23V12M15,16H9V14L12.39,10H9V8H15V10L11.62,14H15V16M7,20H1V18L4.39,14H1V12H7V14L3.62,18H7V20Z";var mdiSmokeDetector="M12,18A6,6 0 0,0 18,12C18,8.68 15.31,6 12,6C8.68,6 6,8.68 6,12A6,6 0 0,0 12,18M19,3A2,2 0 0,1 21,5V19A2,2 0 0,1 19,21H5C3.89,21 3,20.1 3,19V5C3,3.89 3.89,3 5,3H19M8,12A4,4 0 0,1 12,8A4,4 0 0,1 16,12A4,4 0 0,1 12,16A4,4 0 0,1 8,12Z";var mdiSnowflakeAlert="M16.46,9.41L13,7.38V5.12L14.71,3.41L13.29,2L12,3.29L10.71,2L9.29,3.41L11,5.12V7.38L8.5,8.82L6.5,7.69L5.92,5.36L4,5.88L4.47,7.65L2.7,8.12L3.22,10.05L5.55,9.43L7.55,10.56V13.45L5.55,14.58L3.22,13.96L2.7,15.89L4.47,16.36L4,18.12L5.93,18.64L6.55,16.31L8.55,15.18L11,16.62V18.88L9.29,20.59L10.71,22L12,20.71L13.29,22L14.7,20.59L13,18.88V16.62L16.46,14.61M9.5,10.56L12,9.11L14.5,10.56V13.44L12,14.89L9.5,13.44M19,13V7H21V13H19M19,17V15H21V17H19Z";var mdiSolarPower="M11.45,2V5.55L15,3.77L11.45,2M10.45,8L8,10.46L11.75,11.71L10.45,8M2,11.45L3.77,15L5.55,11.45H2M10,2H2V10C2.57,10.17 3.17,10.25 3.77,10.25C7.35,10.26 10.26,7.35 10.27,3.75C10.26,3.16 10.17,2.57 10,2M17,22V16H14L19,7V13H22L17,22Z";var mdiSpeaker="M12,12A3,3 0 0,0 9,15A3,3 0 0,0 12,18A3,3 0 0,0 15,15A3,3 0 0,0 12,12M12,20A5,5 0 0,1 7,15A5,5 0 0,1 12,10A5,5 0 0,1 17,15A5,5 0 0,1 12,20M12,4A2,2 0 0,1 14,6A2,2 0 0,1 12,8C10.89,8 10,7.1 10,6C10,4.89 10.89,4 12,4M17,2H7C5.89,2 5,2.89 5,4V20A2,2 0 0,0 7,22H17A2,2 0 0,0 19,20V4C19,2.89 18.1,2 17,2Z";var mdiSprinkler="M11 7H13V9H11V7M5 22H9V10H5V22M14 11H16V9H14V11M17 10H19V8H17V10M17 5V7H19V5H17M14 8H16V6H14V8M17 13H19V11H17V13M5 7H5.33L6 9H8L8.67 7H9V6H5V7Z";var mdiStar="M12,17.27L18.18,21L16.54,13.97L22,9.24L14.81,8.62L12,2L9.19,8.62L2,9.24L7.45,13.97L5.82,21L12,17.27Z";var mdiStove="M6,14H8L11,17H9L6,14M4,4H5V3A1,1 0 0,1 6,2H10A1,1 0 0,1 11,3V4H13V3A1,1 0 0,1 14,2H18A1,1 0 0,1 19,3V4H20A2,2 0 0,1 22,6V19A2,2 0 0,1 20,21V22H17V21H7V22H4V21A2,2 0 0,1 2,19V6A2,2 0 0,1 4,4M18,7A1,1 0 0,1 19,8A1,1 0 0,1 18,9A1,1 0 0,1 17,8A1,1 0 0,1 18,7M14,7A1,1 0 0,1 15,8A1,1 0 0,1 14,9A1,1 0 0,1 13,8A1,1 0 0,1 14,7M20,6H4V10H20V6M4,19H20V12H4V19M6,7A1,1 0 0,1 7,8A1,1 0 0,1 6,9A1,1 0 0,1 5,8A1,1 0 0,1 6,7M13,14H15L18,17H16L13,14Z";var mdiSwapHorizontal="M21,9L17,5V8H10V10H17V13M7,11L3,15L7,19V16H14V14H7V11Z";var mdiTelevision="M21,17H3V5H21M21,3H3A2,2 0 0,0 1,5V17A2,2 0 0,0 3,19H8V21H16V19H21A2,2 0 0,0 23,17V5A2,2 0 0,0 21,3Z";var mdiThermometer="M15 13V5A3 3 0 0 0 9 5V13A5 5 0 1 0 15 13M12 4A1 1 0 0 1 13 5V8H11V5A1 1 0 0 1 12 4Z";var mdiToggleSwitch="M17,7H7A5,5 0 0,0 2,12A5,5 0 0,0 7,17H17A5,5 0 0,0 22,12A5,5 0 0,0 17,7M17,15A3,3 0 0,1 14,12A3,3 0 0,1 17,9A3,3 0 0,1 20,12A3,3 0 0,1 17,15Z";var mdiTrashCan="M9,3V4H4V6H5V19A2,2 0 0,0 7,21H17A2,2 0 0,0 19,19V6H20V4H15V3H9M9,8H11V17H9V8M13,8H15V17H13V8Z";var mdiTumbleDryer="M6,2H18A2,2 0 0,1 20,4V20A2,2 0 0,1 18,22H6A2,2 0 0,1 4,20V4A2,2 0 0,1 6,2M7,4A1,1 0 0,0 6,5A1,1 0 0,0 7,6A1,1 0 0,0 8,5A1,1 0 0,0 7,4M10,4A1,1 0 0,0 9,5A1,1 0 0,0 10,6A1,1 0 0,0 11,5A1,1 0 0,0 10,4M12,8A6,6 0 0,0 6,14A6,6 0 0,0 12,20A6,6 0 0,0 18,14A6,6 0 0,0 12,8M8.11,10.5H10C9.76,11.88 10,12.67 10.58,13.29C11.68,14.36 12.16,15.71 11.89,17.5H10C10.24,16.12 10,15.33 9.42,14.71C8.32,13.64 7.85,12.29 8.11,10.5M12.11,10.5H14C13.76,11.88 14,12.67 14.58,13.29C15.68,14.36 16.16,15.71 15.89,17.5H14C14.24,16.12 14,15.33 13.42,14.71C12.32,13.64 11.85,12.29 12.11,10.5Z";var mdiUpdate="M21,10.12H14.22L16.96,7.3C14.23,4.6 9.81,4.5 7.08,7.2C4.35,9.91 4.35,14.28 7.08,17C9.81,19.7 14.23,19.7 16.96,17C18.32,15.65 19,14.08 19,12.1H21C21,14.08 20.12,16.65 18.36,18.39C14.85,21.87 9.15,21.87 5.64,18.39C2.14,14.92 2.11,9.28 5.62,5.81C9.13,2.34 14.76,2.34 18.27,5.81L21,3V10.12M12.5,8V12.25L16,14.33L15.28,15.54L11,13V8H12.5Z";var mdiVideo="M17,10.5V7A1,1 0 0,0 16,6H4A1,1 0 0,0 3,7V17A1,1 0 0,0 4,18H16A1,1 0 0,0 17,17V13.5L21,17.5V6.5L17,10.5Z";var mdiVideoOutline="M15,8V16H5V8H15M16,6H4A1,1 0 0,0 3,7V17A1,1 0 0,0 4,18H16A1,1 0 0,0 17,17V13.5L21,17.5V6.5L17,10.5V7A1,1 0 0,0 16,6Z";var mdiVolumeHigh="M14,3.23V5.29C16.89,6.15 19,8.83 19,12C19,15.17 16.89,17.84 14,18.7V20.77C18,19.86 21,16.28 21,12C21,7.72 18,4.14 14,3.23M16.5,12C16.5,10.23 15.5,8.71 14,7.97V16C15.5,15.29 16.5,13.76 16.5,12M3,9V15H7L12,20V4L7,9H3Z";var mdiVolumeOff="M12,4L9.91,6.09L12,8.18M4.27,3L3,4.27L7.73,9H3V15H7L12,20V13.27L16.25,17.53C15.58,18.04 14.83,18.46 14,18.7V20.77C15.38,20.45 16.63,19.82 17.68,18.96L19.73,21L21,19.73L12,10.73M19,12C19,12.94 18.8,13.82 18.46,14.64L19.97,16.15C20.62,14.91 21,13.5 21,12C21,7.72 18,4.14 14,3.23V5.29C16.89,6.15 19,8.83 19,12M16.5,12C16.5,10.23 15.5,8.71 14,7.97V10.18L16.45,12.63C16.5,12.43 16.5,12.21 16.5,12Z";var mdiWashingMachine="M14.83,11.17C16.39,12.73 16.39,15.27 14.83,16.83C13.27,18.39 10.73,18.39 9.17,16.83L14.83,11.17M6,2H18A2,2 0 0,1 20,4V20A2,2 0 0,1 18,22H6A2,2 0 0,1 4,20V4A2,2 0 0,1 6,2M7,4A1,1 0 0,0 6,5A1,1 0 0,0 7,6A1,1 0 0,0 8,5A1,1 0 0,0 7,4M10,4A1,1 0 0,0 9,5A1,1 0 0,0 10,6A1,1 0 0,0 11,5A1,1 0 0,0 10,4M12,8A6,6 0 0,0 6,14A6,6 0 0,0 12,20A6,6 0 0,0 18,14A6,6 0 0,0 12,8Z";var mdiWater="M12,20A6,6 0 0,1 6,14C6,10 12,3.25 12,3.25C12,3.25 18,10 18,14A6,6 0 0,1 12,20Z";var mdiWaterBoiler="M8 2C6.89 2 6 2.89 6 4V16C6 17.11 6.89 18 8 18H9V20H6V22H9C10.11 22 11 21.11 11 20V18H13V20C13 21.11 13.89 22 15 22H18V20H15V18H16C17.11 18 18 17.11 18 16V4C18 2.89 17.11 2 16 2H8M12 4.97A2 2 0 0 1 14 6.97A2 2 0 0 1 12 8.97A2 2 0 0 1 10 6.97A2 2 0 0 1 12 4.97M10 14.5H14V16H10V14.5Z";var mdiWaterPercent="M12,3.25C12,3.25 6,10 6,14C6,17.32 8.69,20 12,20A6,6 0 0,0 18,14C18,10 12,3.25 12,3.25M14.47,9.97L15.53,11.03L9.53,17.03L8.47,15.97M9.75,10A1.25,1.25 0 0,1 11,11.25A1.25,1.25 0 0,1 9.75,12.5A1.25,1.25 0 0,1 8.5,11.25A1.25,1.25 0 0,1 9.75,10M14.25,14.5A1.25,1.25 0 0,1 15.5,15.75A1.25,1.25 0 0,1 14.25,17A1.25,1.25 0 0,1 13,15.75A1.25,1.25 0 0,1 14.25,14.5Z";var mdiWeatherNight="M17.75,4.09L15.22,6.03L16.13,9.09L13.5,7.28L10.87,9.09L11.78,6.03L9.25,4.09L12.44,4L13.5,1L14.56,4L17.75,4.09M21.25,11L19.61,12.25L20.2,14.23L18.5,13.06L16.8,14.23L17.39,12.25L15.75,11L17.81,10.95L18.5,9L19.19,10.95L21.25,11M18.97,15.95C19.8,15.87 20.69,17.05 20.16,17.8C19.84,18.25 19.5,18.67 19.08,19.07C15.17,23 8.84,23 4.94,19.07C1.03,15.17 1.03,8.83 4.94,4.93C5.34,4.53 5.76,4.17 6.21,3.85C6.96,3.32 8.14,4.21 8.06,5.04C7.79,7.9 8.75,10.87 10.95,13.06C13.14,15.26 16.1,16.22 18.97,15.95M17.33,17.97C14.5,17.81 11.7,16.64 9.53,14.5C7.36,12.31 6.2,9.5 6.04,6.68C3.23,9.82 3.34,14.64 6.35,17.66C9.37,20.67 14.19,20.78 17.33,17.97Z";var mdiWeatherRainy="M6,14.03A1,1 0 0,1 7,15.03C7,15.58 6.55,16.03 6,16.03C3.24,16.03 1,13.79 1,11.03C1,8.27 3.24,6.03 6,6.03C7,3.68 9.3,2.03 12,2.03C15.43,2.03 18.24,4.69 18.5,8.06L19,8.03A4,4 0 0,1 23,12.03C23,14.23 21.21,16.03 19,16.03H18C17.45,16.03 17,15.58 17,15.03C17,14.47 17.45,14.03 18,14.03H19A2,2 0 0,0 21,12.03A2,2 0 0,0 19,10.03H17V9.03C17,6.27 14.76,4.03 12,4.03C9.5,4.03 7.45,5.84 7.06,8.21C6.73,8.09 6.37,8.03 6,8.03A3,3 0 0,0 3,11.03A3,3 0 0,0 6,14.03M12,14.15C12.18,14.39 12.37,14.66 12.56,14.94C13,15.56 14,17.03 14,18C14,19.11 13.1,20 12,20A2,2 0 0,1 10,18C10,17.03 11,15.56 11.44,14.94C11.63,14.66 11.82,14.4 12,14.15M12,11.03L11.5,11.59C11.5,11.59 10.65,12.55 9.79,13.81C8.93,15.06 8,16.56 8,18A4,4 0 0,0 12,22A4,4 0 0,0 16,18C16,16.56 15.07,15.06 14.21,13.81C13.35,12.55 12.5,11.59 12.5,11.59";var mdiWeatherSunny="M12,7A5,5 0 0,1 17,12A5,5 0 0,1 12,17A5,5 0 0,1 7,12A5,5 0 0,1 12,7M12,9A3,3 0 0,0 9,12A3,3 0 0,0 12,15A3,3 0 0,0 15,12A3,3 0 0,0 12,9M12,2L14.39,5.42C13.65,5.15 12.84,5 12,5C11.16,5 10.35,5.15 9.61,5.42L12,2M3.34,7L7.5,6.65C6.9,7.16 6.36,7.78 5.94,8.5C5.5,9.24 5.25,10 5.11,10.79L3.34,7M3.36,17L5.12,13.23C5.26,14 5.53,14.78 5.95,15.5C6.37,16.24 6.91,16.86 7.5,17.37L3.36,17M20.65,7L18.88,10.79C18.74,10 18.47,9.23 18.05,8.5C17.63,7.78 17.1,7.15 16.5,6.64L20.65,7M20.64,17L16.5,17.36C17.09,16.85 17.62,16.22 18.04,15.5C18.46,14.77 18.73,14 18.87,13.21L20.64,17M12,22L9.59,18.56C10.33,18.83 11.14,19 12,19C12.82,19 13.63,18.83 14.37,18.56L12,22Z";var mdiWifi="M12,21L15.6,16.2C14.6,15.45 13.35,15 12,15C10.65,15 9.4,15.45 8.4,16.2L12,21M12,3C7.95,3 4.21,4.34 1.2,6.6L3,9C5.5,7.12 8.62,6 12,6C15.38,6 18.5,7.12 21,9L22.8,6.6C19.79,4.34 16.05,3 12,3M12,9C9.3,9 6.81,9.89 4.8,11.4L6.6,13.8C8.1,12.67 9.97,12 12,12C14.03,12 15.9,12.67 17.4,13.8L19.2,11.4C17.19,9.89 14.7,9 12,9Z";

/**
 * @license
 * Copyright 2019 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
const t$3 = globalThis,
  e$a = t$3.ShadowRoot && (void 0 === t$3.ShadyCSS || t$3.ShadyCSS.nativeShadow) && "adoptedStyleSheets" in Document.prototype && "replace" in CSSStyleSheet.prototype,
  s$3 = Symbol(),
  o$a = new WeakMap();
let n$8 = class n {
  constructor(t, e, o) {
    if (this._$cssResult$ = true, o !== s$3) throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");
    this.cssText = t, this.t = e;
  }
  get styleSheet() {
    let t = this.o;
    const s = this.t;
    if (e$a && void 0 === t) {
      const e = void 0 !== s && 1 === s.length;
      e && (t = o$a.get(s)), void 0 === t && ((this.o = t = new CSSStyleSheet()).replaceSync(this.cssText), e && o$a.set(s, t));
    }
    return t;
  }
  toString() {
    return this.cssText;
  }
};
const r$7 = t => new n$8("string" == typeof t ? t : t + "", void 0, s$3),
  i$7 = (t, ...e) => {
    const o = 1 === t.length ? t[0] : e.reduce((e, s, o) => e + (t => {
      if (true === t._$cssResult$) return t.cssText;
      if ("number" == typeof t) return t;
      throw Error("Value passed to 'css' function must be a 'css' function result: " + t + ". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.");
    })(s) + t[o + 1], t[0]);
    return new n$8(o, t, s$3);
  },
  S$1 = (s, o) => {
    if (e$a) s.adoptedStyleSheets = o.map(t => t instanceof CSSStyleSheet ? t : t.styleSheet);else for (const e of o) {
      const o = document.createElement("style"),
        n = t$3.litNonce;
      void 0 !== n && o.setAttribute("nonce", n), o.textContent = e.cssText, s.appendChild(o);
    }
  },
  c$4 = e$a ? t => t : t => t instanceof CSSStyleSheet ? (t => {
    let e = "";
    for (const s of t.cssRules) e += s.cssText;
    return r$7(e);
  })(t) : t;

/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
const {
    is: i$6,
    defineProperty: e$9,
    getOwnPropertyDescriptor: h$3,
    getOwnPropertyNames: r$6,
    getOwnPropertySymbols: o$9,
    getPrototypeOf: n$7
  } = Object,
  a$2 = globalThis,
  c$3 = a$2.trustedTypes,
  l$3 = c$3 ? c$3.emptyScript : "",
  p$2 = a$2.reactiveElementPolyfillSupport,
  d$1 = (t, s) => t,
  u$2 = {
    toAttribute(t, s) {
      switch (s) {
        case Boolean:
          t = t ? l$3 : null;
          break;
        case Object:
        case Array:
          t = null == t ? t : JSON.stringify(t);
      }
      return t;
    },
    fromAttribute(t, s) {
      let i = t;
      switch (s) {
        case Boolean:
          i = null !== t;
          break;
        case Number:
          i = null === t ? null : Number(t);
          break;
        case Object:
        case Array:
          try {
            i = JSON.parse(t);
          } catch (t) {
            i = null;
          }
      }
      return i;
    }
  },
  f$2 = (t, s) => !i$6(t, s),
  b$1 = {
    attribute: true,
    type: String,
    converter: u$2,
    reflect: false,
    useDefault: false,
    hasChanged: f$2
  };
Symbol.metadata ?? (Symbol.metadata = Symbol("metadata")), a$2.litPropertyMetadata ?? (a$2.litPropertyMetadata = new WeakMap());
let y$1 = class y extends HTMLElement {
  static addInitializer(t) {
    this._$Ei(), (this.l ?? (this.l = [])).push(t);
  }
  static get observedAttributes() {
    return this.finalize(), this._$Eh && [...this._$Eh.keys()];
  }
  static createProperty(t, s = b$1) {
    if (s.state && (s.attribute = false), this._$Ei(), this.prototype.hasOwnProperty(t) && ((s = Object.create(s)).wrapped = true), this.elementProperties.set(t, s), !s.noAccessor) {
      const i = Symbol(),
        h = this.getPropertyDescriptor(t, i, s);
      void 0 !== h && e$9(this.prototype, t, h);
    }
  }
  static getPropertyDescriptor(t, s, i) {
    const {
      get: e,
      set: r
    } = h$3(this.prototype, t) ?? {
      get() {
        return this[s];
      },
      set(t) {
        this[s] = t;
      }
    };
    return {
      get: e,
      set(s) {
        const h = e?.call(this);
        r?.call(this, s), this.requestUpdate(t, h, i);
      },
      configurable: true,
      enumerable: true
    };
  }
  static getPropertyOptions(t) {
    return this.elementProperties.get(t) ?? b$1;
  }
  static _$Ei() {
    if (this.hasOwnProperty(d$1("elementProperties"))) return;
    const t = n$7(this);
    t.finalize(), void 0 !== t.l && (this.l = [...t.l]), this.elementProperties = new Map(t.elementProperties);
  }
  static finalize() {
    if (this.hasOwnProperty(d$1("finalized"))) return;
    if (this.finalized = true, this._$Ei(), this.hasOwnProperty(d$1("properties"))) {
      const t = this.properties,
        s = [...r$6(t), ...o$9(t)];
      for (const i of s) this.createProperty(i, t[i]);
    }
    const t = this[Symbol.metadata];
    if (null !== t) {
      const s = litPropertyMetadata.get(t);
      if (void 0 !== s) for (const [t, i] of s) this.elementProperties.set(t, i);
    }
    this._$Eh = new Map();
    for (const [t, s] of this.elementProperties) {
      const i = this._$Eu(t, s);
      void 0 !== i && this._$Eh.set(i, t);
    }
    this.elementStyles = this.finalizeStyles(this.styles);
  }
  static finalizeStyles(s) {
    const i = [];
    if (Array.isArray(s)) {
      const e = new Set(s.flat(1 / 0).reverse());
      for (const s of e) i.unshift(c$4(s));
    } else void 0 !== s && i.push(c$4(s));
    return i;
  }
  static _$Eu(t, s) {
    const i = s.attribute;
    return false === i ? void 0 : "string" == typeof i ? i : "string" == typeof t ? t.toLowerCase() : void 0;
  }
  constructor() {
    super(), this._$Ep = void 0, this.isUpdatePending = false, this.hasUpdated = false, this._$Em = null, this._$Ev();
  }
  _$Ev() {
    this._$ES = new Promise(t => this.enableUpdating = t), this._$AL = new Map(), this._$E_(), this.requestUpdate(), this.constructor.l?.forEach(t => t(this));
  }
  addController(t) {
    (this._$EO ?? (this._$EO = new Set())).add(t), void 0 !== this.renderRoot && this.isConnected && t.hostConnected?.();
  }
  removeController(t) {
    this._$EO?.delete(t);
  }
  _$E_() {
    const t = new Map(),
      s = this.constructor.elementProperties;
    for (const i of s.keys()) this.hasOwnProperty(i) && (t.set(i, this[i]), delete this[i]);
    t.size > 0 && (this._$Ep = t);
  }
  createRenderRoot() {
    const t = this.shadowRoot ?? this.attachShadow(this.constructor.shadowRootOptions);
    return S$1(t, this.constructor.elementStyles), t;
  }
  connectedCallback() {
    this.renderRoot ?? (this.renderRoot = this.createRenderRoot()), this.enableUpdating(true), this._$EO?.forEach(t => t.hostConnected?.());
  }
  enableUpdating(t) {}
  disconnectedCallback() {
    this._$EO?.forEach(t => t.hostDisconnected?.());
  }
  attributeChangedCallback(t, s, i) {
    this._$AK(t, i);
  }
  _$ET(t, s) {
    const i = this.constructor.elementProperties.get(t),
      e = this.constructor._$Eu(t, i);
    if (void 0 !== e && true === i.reflect) {
      const h = (void 0 !== i.converter?.toAttribute ? i.converter : u$2).toAttribute(s, i.type);
      this._$Em = t, null == h ? this.removeAttribute(e) : this.setAttribute(e, h), this._$Em = null;
    }
  }
  _$AK(t, s) {
    const i = this.constructor,
      e = i._$Eh.get(t);
    if (void 0 !== e && this._$Em !== e) {
      const t = i.getPropertyOptions(e),
        h = "function" == typeof t.converter ? {
          fromAttribute: t.converter
        } : void 0 !== t.converter?.fromAttribute ? t.converter : u$2;
      this._$Em = e;
      const r = h.fromAttribute(s, t.type);
      this[e] = r ?? this._$Ej?.get(e) ?? r, this._$Em = null;
    }
  }
  requestUpdate(t, s, i, e = false, h) {
    if (void 0 !== t) {
      const r = this.constructor;
      if (false === e && (h = this[t]), i ?? (i = r.getPropertyOptions(t)), !((i.hasChanged ?? f$2)(h, s) || i.useDefault && i.reflect && h === this._$Ej?.get(t) && !this.hasAttribute(r._$Eu(t, i)))) return;
      this.C(t, s, i);
    }
    false === this.isUpdatePending && (this._$ES = this._$EP());
  }
  C(t, s, {
    useDefault: i,
    reflect: e,
    wrapped: h
  }, r) {
    i && !(this._$Ej ?? (this._$Ej = new Map())).has(t) && (this._$Ej.set(t, r ?? s ?? this[t]), true !== h || void 0 !== r) || (this._$AL.has(t) || (this.hasUpdated || i || (s = void 0), this._$AL.set(t, s)), true === e && this._$Em !== t && (this._$Eq ?? (this._$Eq = new Set())).add(t));
  }
  async _$EP() {
    this.isUpdatePending = true;
    try {
      await this._$ES;
    } catch (t) {
      Promise.reject(t);
    }
    const t = this.scheduleUpdate();
    return null != t && (await t), !this.isUpdatePending;
  }
  scheduleUpdate() {
    return this.performUpdate();
  }
  performUpdate() {
    if (!this.isUpdatePending) return;
    if (!this.hasUpdated) {
      if (this.renderRoot ?? (this.renderRoot = this.createRenderRoot()), this._$Ep) {
        for (const [t, s] of this._$Ep) this[t] = s;
        this._$Ep = void 0;
      }
      const t = this.constructor.elementProperties;
      if (t.size > 0) for (const [s, i] of t) {
        const {
            wrapped: t
          } = i,
          e = this[s];
        true !== t || this._$AL.has(s) || void 0 === e || this.C(s, void 0, i, e);
      }
    }
    let t = false;
    const s = this._$AL;
    try {
      t = this.shouldUpdate(s), t ? (this.willUpdate(s), this._$EO?.forEach(t => t.hostUpdate?.()), this.update(s)) : this._$EM();
    } catch (s) {
      throw t = false, this._$EM(), s;
    }
    t && this._$AE(s);
  }
  willUpdate(t) {}
  _$AE(t) {
    this._$EO?.forEach(t => t.hostUpdated?.()), this.hasUpdated || (this.hasUpdated = true, this.firstUpdated(t)), this.updated(t);
  }
  _$EM() {
    this._$AL = new Map(), this.isUpdatePending = false;
  }
  get updateComplete() {
    return this.getUpdateComplete();
  }
  getUpdateComplete() {
    return this._$ES;
  }
  shouldUpdate(t) {
    return true;
  }
  update(t) {
    this._$Eq && (this._$Eq = this._$Eq.forEach(t => this._$ET(t, this[t]))), this._$EM();
  }
  updated(t) {}
  firstUpdated(t) {}
};
y$1.elementStyles = [], y$1.shadowRootOptions = {
  mode: "open"
}, y$1[d$1("elementProperties")] = new Map(), y$1[d$1("finalized")] = new Map(), p$2?.({
  ReactiveElement: y$1
}), (a$2.reactiveElementVersions ?? (a$2.reactiveElementVersions = [])).push("2.1.2");

/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
const t$2 = globalThis,
  i$5 = t => t,
  s$2 = t$2.trustedTypes,
  e$8 = s$2 ? s$2.createPolicy("lit-html", {
    createHTML: t => t
  }) : void 0,
  h$2 = "$lit$",
  o$8 = `lit$${Math.random().toFixed(9).slice(2)}$`,
  n$6 = "?" + o$8,
  r$5 = `<${n$6}>`,
  l$2 = document,
  c$2 = () => l$2.createComment(""),
  a$1 = t => null === t || "object" != typeof t && "function" != typeof t,
  u$1 = Array.isArray,
  d = t => u$1(t) || "function" == typeof t?.[Symbol.iterator],
  f$1 = "[ \t\n\f\r]",
  v = /<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,
  _ = /-->/g,
  m$1 = />/g,
  p$1 = RegExp(`>|${f$1}(?:([^\\s"'>=/]+)(${f$1}*=${f$1}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`, "g"),
  g = /'/g,
  $ = /"/g,
  y = /^(?:script|style|textarea|title)$/i,
  x = t => (i, ...s) => ({
    _$litType$: t,
    strings: i,
    values: s
  }),
  b = x(1),
  w = x(2),
  E = Symbol.for("lit-noChange"),
  A = Symbol.for("lit-nothing"),
  C = new WeakMap(),
  P = l$2.createTreeWalker(l$2, 129);
function V(t, i) {
  if (!u$1(t) || !t.hasOwnProperty("raw")) throw Error("invalid template strings array");
  return void 0 !== e$8 ? e$8.createHTML(i) : i;
}
const N = (t, i) => {
  const s = t.length - 1,
    e = [];
  let n,
    l = 2 === i ? "<svg>" : 3 === i ? "<math>" : "",
    c = v;
  for (let i = 0; i < s; i++) {
    const s = t[i];
    let a,
      u,
      d = -1,
      f = 0;
    for (; f < s.length && (c.lastIndex = f, u = c.exec(s), null !== u);) f = c.lastIndex, c === v ? "!--" === u[1] ? c = _ : void 0 !== u[1] ? c = m$1 : void 0 !== u[2] ? (y.test(u[2]) && (n = RegExp("</" + u[2], "g")), c = p$1) : void 0 !== u[3] && (c = p$1) : c === p$1 ? ">" === u[0] ? (c = n ?? v, d = -1) : void 0 === u[1] ? d = -2 : (d = c.lastIndex - u[2].length, a = u[1], c = void 0 === u[3] ? p$1 : '"' === u[3] ? $ : g) : c === $ || c === g ? c = p$1 : c === _ || c === m$1 ? c = v : (c = p$1, n = void 0);
    const x = c === p$1 && t[i + 1].startsWith("/>") ? " " : "";
    l += c === v ? s + r$5 : d >= 0 ? (e.push(a), s.slice(0, d) + h$2 + s.slice(d) + o$8 + x) : s + o$8 + (-2 === d ? i : x);
  }
  return [V(t, l + (t[s] || "<?>") + (2 === i ? "</svg>" : 3 === i ? "</math>" : "")), e];
};
class S {
  constructor({
    strings: t,
    _$litType$: i
  }, e) {
    let r;
    this.parts = [];
    let l = 0,
      a = 0;
    const u = t.length - 1,
      d = this.parts,
      [f, v] = N(t, i);
    if (this.el = S.createElement(f, e), P.currentNode = this.el.content, 2 === i || 3 === i) {
      const t = this.el.content.firstChild;
      t.replaceWith(...t.childNodes);
    }
    for (; null !== (r = P.nextNode()) && d.length < u;) {
      if (1 === r.nodeType) {
        if (r.hasAttributes()) for (const t of r.getAttributeNames()) if (t.endsWith(h$2)) {
          const i = v[a++],
            s = r.getAttribute(t).split(o$8),
            e = /([.?@])?(.*)/.exec(i);
          d.push({
            type: 1,
            index: l,
            name: e[2],
            strings: s,
            ctor: "." === e[1] ? I : "?" === e[1] ? L : "@" === e[1] ? z : H
          }), r.removeAttribute(t);
        } else t.startsWith(o$8) && (d.push({
          type: 6,
          index: l
        }), r.removeAttribute(t));
        if (y.test(r.tagName)) {
          const t = r.textContent.split(o$8),
            i = t.length - 1;
          if (i > 0) {
            r.textContent = s$2 ? s$2.emptyScript : "";
            for (let s = 0; s < i; s++) r.append(t[s], c$2()), P.nextNode(), d.push({
              type: 2,
              index: ++l
            });
            r.append(t[i], c$2());
          }
        }
      } else if (8 === r.nodeType) if (r.data === n$6) d.push({
        type: 2,
        index: l
      });else {
        let t = -1;
        for (; -1 !== (t = r.data.indexOf(o$8, t + 1));) d.push({
          type: 7,
          index: l
        }), t += o$8.length - 1;
      }
      l++;
    }
  }
  static createElement(t, i) {
    const s = l$2.createElement("template");
    return s.innerHTML = t, s;
  }
}
function M(t, i, s = t, e) {
  if (i === E) return i;
  let h = void 0 !== e ? s._$Co?.[e] : s._$Cl;
  const o = a$1(i) ? void 0 : i._$litDirective$;
  return h?.constructor !== o && (h?._$AO?.(false), void 0 === o ? h = void 0 : (h = new o(t), h._$AT(t, s, e)), void 0 !== e ? (s._$Co ?? (s._$Co = []))[e] = h : s._$Cl = h), void 0 !== h && (i = M(t, h._$AS(t, i.values), h, e)), i;
}
class R {
  constructor(t, i) {
    this._$AV = [], this._$AN = void 0, this._$AD = t, this._$AM = i;
  }
  get parentNode() {
    return this._$AM.parentNode;
  }
  get _$AU() {
    return this._$AM._$AU;
  }
  u(t) {
    const {
        el: {
          content: i
        },
        parts: s
      } = this._$AD,
      e = (t?.creationScope ?? l$2).importNode(i, true);
    P.currentNode = e;
    let h = P.nextNode(),
      o = 0,
      n = 0,
      r = s[0];
    for (; void 0 !== r;) {
      if (o === r.index) {
        let i;
        2 === r.type ? i = new k(h, h.nextSibling, this, t) : 1 === r.type ? i = new r.ctor(h, r.name, r.strings, this, t) : 6 === r.type && (i = new Z(h, this, t)), this._$AV.push(i), r = s[++n];
      }
      o !== r?.index && (h = P.nextNode(), o++);
    }
    return P.currentNode = l$2, e;
  }
  p(t) {
    let i = 0;
    for (const s of this._$AV) void 0 !== s && (void 0 !== s.strings ? (s._$AI(t, s, i), i += s.strings.length - 2) : s._$AI(t[i])), i++;
  }
}
class k {
  get _$AU() {
    return this._$AM?._$AU ?? this._$Cv;
  }
  constructor(t, i, s, e) {
    this.type = 2, this._$AH = A, this._$AN = void 0, this._$AA = t, this._$AB = i, this._$AM = s, this.options = e, this._$Cv = e?.isConnected ?? true;
  }
  get parentNode() {
    let t = this._$AA.parentNode;
    const i = this._$AM;
    return void 0 !== i && 11 === t?.nodeType && (t = i.parentNode), t;
  }
  get startNode() {
    return this._$AA;
  }
  get endNode() {
    return this._$AB;
  }
  _$AI(t, i = this) {
    t = M(this, t, i), a$1(t) ? t === A || null == t || "" === t ? (this._$AH !== A && this._$AR(), this._$AH = A) : t !== this._$AH && t !== E && this._(t) : void 0 !== t._$litType$ ? this.$(t) : void 0 !== t.nodeType ? this.T(t) : d(t) ? this.k(t) : this._(t);
  }
  O(t) {
    return this._$AA.parentNode.insertBefore(t, this._$AB);
  }
  T(t) {
    this._$AH !== t && (this._$AR(), this._$AH = this.O(t));
  }
  _(t) {
    this._$AH !== A && a$1(this._$AH) ? this._$AA.nextSibling.data = t : this.T(l$2.createTextNode(t)), this._$AH = t;
  }
  $(t) {
    const {
        values: i,
        _$litType$: s
      } = t,
      e = "number" == typeof s ? this._$AC(t) : (void 0 === s.el && (s.el = S.createElement(V(s.h, s.h[0]), this.options)), s);
    if (this._$AH?._$AD === e) this._$AH.p(i);else {
      const t = new R(e, this),
        s = t.u(this.options);
      t.p(i), this.T(s), this._$AH = t;
    }
  }
  _$AC(t) {
    let i = C.get(t.strings);
    return void 0 === i && C.set(t.strings, i = new S(t)), i;
  }
  k(t) {
    u$1(this._$AH) || (this._$AH = [], this._$AR());
    const i = this._$AH;
    let s,
      e = 0;
    for (const h of t) e === i.length ? i.push(s = new k(this.O(c$2()), this.O(c$2()), this, this.options)) : s = i[e], s._$AI(h), e++;
    e < i.length && (this._$AR(s && s._$AB.nextSibling, e), i.length = e);
  }
  _$AR(t = this._$AA.nextSibling, s) {
    for (this._$AP?.(false, true, s); t !== this._$AB;) {
      const s = i$5(t).nextSibling;
      i$5(t).remove(), t = s;
    }
  }
  setConnected(t) {
    void 0 === this._$AM && (this._$Cv = t, this._$AP?.(t));
  }
}
class H {
  get tagName() {
    return this.element.tagName;
  }
  get _$AU() {
    return this._$AM._$AU;
  }
  constructor(t, i, s, e, h) {
    this.type = 1, this._$AH = A, this._$AN = void 0, this.element = t, this.name = i, this._$AM = e, this.options = h, s.length > 2 || "" !== s[0] || "" !== s[1] ? (this._$AH = Array(s.length - 1).fill(new String()), this.strings = s) : this._$AH = A;
  }
  _$AI(t, i = this, s, e) {
    const h = this.strings;
    let o = false;
    if (void 0 === h) t = M(this, t, i, 0), o = !a$1(t) || t !== this._$AH && t !== E, o && (this._$AH = t);else {
      const e = t;
      let n, r;
      for (t = h[0], n = 0; n < h.length - 1; n++) r = M(this, e[s + n], i, n), r === E && (r = this._$AH[n]), o || (o = !a$1(r) || r !== this._$AH[n]), r === A ? t = A : t !== A && (t += (r ?? "") + h[n + 1]), this._$AH[n] = r;
    }
    o && !e && this.j(t);
  }
  j(t) {
    t === A ? this.element.removeAttribute(this.name) : this.element.setAttribute(this.name, t ?? "");
  }
}
class I extends H {
  constructor() {
    super(...arguments), this.type = 3;
  }
  j(t) {
    this.element[this.name] = t === A ? void 0 : t;
  }
}
class L extends H {
  constructor() {
    super(...arguments), this.type = 4;
  }
  j(t) {
    this.element.toggleAttribute(this.name, !!t && t !== A);
  }
}
class z extends H {
  constructor(t, i, s, e, h) {
    super(t, i, s, e, h), this.type = 5;
  }
  _$AI(t, i = this) {
    if ((t = M(this, t, i, 0) ?? A) === E) return;
    const s = this._$AH,
      e = t === A && s !== A || t.capture !== s.capture || t.once !== s.once || t.passive !== s.passive,
      h = t !== A && (s === A || e);
    e && this.element.removeEventListener(this.name, this, s), h && this.element.addEventListener(this.name, this, t), this._$AH = t;
  }
  handleEvent(t) {
    "function" == typeof this._$AH ? this._$AH.call(this.options?.host ?? this.element, t) : this._$AH.handleEvent(t);
  }
}
class Z {
  constructor(t, i, s) {
    this.element = t, this.type = 6, this._$AN = void 0, this._$AM = i, this.options = s;
  }
  get _$AU() {
    return this._$AM._$AU;
  }
  _$AI(t) {
    M(this, t);
  }
}
const B = t$2.litHtmlPolyfillSupport;
B?.(S, k), (t$2.litHtmlVersions ?? (t$2.litHtmlVersions = [])).push("3.3.3");
const D = (t, i, s) => {
  const e = s?.renderBefore ?? i;
  let h = e._$litPart$;
  if (void 0 === h) {
    const t = s?.renderBefore ?? null;
    e._$litPart$ = h = new k(i.insertBefore(c$2(), t), t, void 0, s ?? {});
  }
  return h._$AI(t), h;
};

/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
const s$1 = globalThis;
let i$4 = class i extends y$1 {
  constructor() {
    super(...arguments), this.renderOptions = {
      host: this
    }, this._$Do = void 0;
  }
  createRenderRoot() {
    var _this$renderOptions;
    const t = super.createRenderRoot();
    return (_this$renderOptions = this.renderOptions).renderBefore ?? (_this$renderOptions.renderBefore = t.firstChild), t;
  }
  update(t) {
    const r = this.render();
    this.hasUpdated || (this.renderOptions.isConnected = this.isConnected), super.update(t), this._$Do = D(r, this.renderRoot, this.renderOptions);
  }
  connectedCallback() {
    super.connectedCallback(), this._$Do?.setConnected(true);
  }
  disconnectedCallback() {
    super.disconnectedCallback(), this._$Do?.setConnected(false);
  }
  render() {
    return E;
  }
};
i$4._$litElement$ = true, i$4["finalized"] = true, s$1.litElementHydrateSupport?.({
  LitElement: i$4
});
const o$7 = s$1.litElementPolyfillSupport;
o$7?.({
  LitElement: i$4
});
(s$1.litElementVersions ?? (s$1.litElementVersions = [])).push("4.2.2");

/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
const t$1 = t => (e, o) => {
  void 0 !== o ? o.addInitializer(() => {
    customElements.define(t, e);
  }) : customElements.define(t, e);
};

/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
const o$6 = {
    attribute: true,
    type: String,
    converter: u$2,
    reflect: false,
    hasChanged: f$2
  },
  r$4 = (t = o$6, e, r) => {
    const {
      kind: n,
      metadata: i
    } = r;
    let s = globalThis.litPropertyMetadata.get(i);
    if (void 0 === s && globalThis.litPropertyMetadata.set(i, s = new Map()), "setter" === n && ((t = Object.create(t)).wrapped = true), s.set(r.name, t), "accessor" === n) {
      const {
        name: o
      } = r;
      return {
        set(r) {
          const n = e.get.call(this);
          e.set.call(this, r), this.requestUpdate(o, n, t, true, r);
        },
        init(e) {
          return void 0 !== e && this.C(o, void 0, t, e), e;
        }
      };
    }
    if ("setter" === n) {
      const {
        name: o
      } = r;
      return function (r) {
        const n = this[o];
        e.call(this, r), this.requestUpdate(o, n, t, true, r);
      };
    }
    throw Error("Unsupported decorator location: " + n);
  };
function n$5(t) {
  return (e, o) => "object" == typeof o ? r$4(t, e, o) : ((t, e, o) => {
    const r = e.hasOwnProperty(o);
    return e.constructor.createProperty(o, t), r ? Object.getOwnPropertyDescriptor(e, o) : void 0;
  })(t, e, o);
}

/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
function r$3(r) {
  return n$5({
    ...r,
    state: true,
    attribute: false
  });
}

/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
const e$7 = (e, t, c) => (c.configurable = true, c.enumerable = true, Reflect.decorate && "object" != typeof t && Object.defineProperty(e, t, c), c);

/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
function e$6(e, r) {
  return (n, s, i) => {
    const o = t => t.renderRoot?.querySelector(e) ?? null;
    return e$7(n, s, {
      get() {
        return o(this);
      }
    });
  };
}

/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
let e$5;
function r$2(r) {
  return (n, o) => e$7(n, o, {
    get() {
      return (this.renderRoot ?? e$5 ?? (e$5 = document.createDocumentFragment())).querySelectorAll(r);
    }
  });
}

/**
 * @license
 * Copyright 2021 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
function o$5(o) {
  return (e, n) => {
    const {
        slot: r,
        selector: s
      } = o ?? {},
      c = "slot" + (r ? `[name=${r}]` : ":not([name])");
    return e$7(e, n, {
      get() {
        const t = this.renderRoot?.querySelector(c),
          e = t?.assignedElements(o) ?? [];
        return void 0 === s ? e : e.filter(t => t.matches(s));
      }
    });
  };
}

/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
function n$4(n) {
  return (o, r) => {
    const {
        slot: e
      } = n ?? {},
      s = "slot" + (e ? `[name=${e}]` : ":not([name])");
    return e$7(o, r, {
      get() {
        const t = this.renderRoot?.querySelector(s);
        return t?.assignedNodes(n) ?? [];
      }
    });
  };
}

/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
const clientContext = n$9("client");
const tickContext = n$9("client-tick");

var __defProp$o = Object.defineProperty;
var __getOwnPropDesc$p = Object.getOwnPropertyDescriptor;
var __decorateClass$r = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$p(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp$o(target, key, result);
  return result;
};
let HaSvgIcon = class extends i$4 {
  render() {
    return w`
    <svg
      viewBox=${this.viewBox ?? "0 0 24 24"}
      preserveAspectRatio="xMidYMid meet"
      focusable="false"
      aria-hidden="true"
    >
      <g>
        ${this.path ? w`<path class="primary-path" d=${this.path}></path>` : A}
        ${this.secondaryPath ? w`<path class="secondary-path" d=${this.secondaryPath}></path>` : A}
      </g>
    </svg>`;
  }
  static get styles() {
    return i$7`
            :host {
                display: var(--ha-icon-display, inline-flex);
                align-items: center;
                justify-content: center;
                position: relative;
                vertical-align: middle;
                fill: var(--icon-primary-color, currentcolor);
                width: var(--mdc-icon-size, 24px);
                height: var(--mdc-icon-size, 24px);
            }
            svg {
                width: 100%;
                height: 100%;
                pointer-events: none;
                display: block;
            }
            path.primary-path {
                opacity: var(--icon-primary-opactity, 1);
            }
            path.secondary-path {
                fill: var(--icon-secondary-color, currentcolor);
                opacity: var(--icon-secondary-opactity, 0.5);
            }
        `;
  }
};
__decorateClass$r([n$5()], HaSvgIcon.prototype, "path", 2);
__decorateClass$r([n$5()], HaSvgIcon.prototype, "secondaryPath", 2);
__decorateClass$r([n$5()], HaSvgIcon.prototype, "viewBox", 2);
HaSvgIcon = __decorateClass$r([t$1("ha-svg-icon")], HaSvgIcon);

/******************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */

function __decorate(decorators, target, key, desc) {
  var c = arguments.length,
    r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
    d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
}
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
  var e = new Error(message);
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * A key to retrieve an `Attachable` element's `AttachableController` from a
 * global `MutationObserver`.
 */
const ATTACHABLE_CONTROLLER = Symbol('attachableController');
let FOR_ATTRIBUTE_OBSERVER;
{
  /**
   * A global `MutationObserver` that reacts to `for` attribute changes on
   * `Attachable` elements. If the `for` attribute changes, the controller will
   * re-attach to the new referenced element.
   */
  FOR_ATTRIBUTE_OBSERVER = new MutationObserver(records => {
    for (const record of records) {
      // When a control's `for` attribute changes, inform its
      // `AttachableController` to update to a new control.
      record.target[ATTACHABLE_CONTROLLER]?.hostConnected();
    }
  });
}
/**
 * A controller that provides an implementation for `Attachable` elements.
 *
 * @example
 * ```ts
 * class MyElement extends LitElement implements Attachable {
 *   get control() { return this.attachableController.control; }
 *
 *   private readonly attachableController = new AttachableController(
 *     this,
 *     (previousControl, newControl) => {
 *       previousControl?.removeEventListener('click', this.handleClick);
 *       newControl?.addEventListener('click', this.handleClick);
 *     }
 *   );
 *
 *   // Implement remaining `Attachable` properties/methods that call the
 *   // controller's properties/methods.
 * }
 * ```
 */
class AttachableController {
  get htmlFor() {
    return this.host.getAttribute('for');
  }
  set htmlFor(htmlFor) {
    if (htmlFor === null) {
      this.host.removeAttribute('for');
    } else {
      this.host.setAttribute('for', htmlFor);
    }
  }
  get control() {
    if (this.host.hasAttribute('for')) {
      if (!this.htmlFor || !this.host.isConnected) {
        return null;
      }
      return this.host.getRootNode().querySelector(`#${this.htmlFor}`);
    }
    return this.currentControl || this.host.parentElement;
  }
  set control(control) {
    if (control) {
      this.attach(control);
    } else {
      this.detach();
    }
  }
  /**
   * Creates a new controller for an `Attachable` element.
   *
   * @param host The `Attachable` element.
   * @param onControlChange A callback with two parameters for the previous and
   *     next control. An `Attachable` element may perform setup or teardown
   *     logic whenever the control changes.
   */
  constructor(host, onControlChange) {
    this.host = host;
    this.onControlChange = onControlChange;
    this.currentControl = null;
    host.addController(this);
    host[ATTACHABLE_CONTROLLER] = this;
    FOR_ATTRIBUTE_OBSERVER?.observe(host, {
      attributeFilter: ['for']
    });
  }
  attach(control) {
    if (control === this.currentControl) {
      return;
    }
    this.setCurrentControl(control);
    // When imperatively attaching, remove the `for` attribute so
    // that the attached control is used instead of a referenced one.
    this.host.removeAttribute('for');
  }
  detach() {
    this.setCurrentControl(null);
    // When imperatively detaching, add an empty `for=""` attribute. This will
    // ensure the control is `null` rather than the `parentElement`.
    this.host.setAttribute('for', '');
  }
  /** @private */
  hostConnected() {
    this.setCurrentControl(this.control);
  }
  /** @private */
  hostDisconnected() {
    this.setCurrentControl(null);
  }
  setCurrentControl(control) {
    this.onControlChange(this.currentControl, control);
    this.currentControl = control;
  }
}

/**
 * @license
 * Copyright 2021 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * Events that the focus ring listens to.
 */
const EVENTS$1 = ['focusin', 'focusout', 'pointerdown'];
/**
 * A focus ring component.
 *
 * @fires visibility-changed {Event} Fired whenever `visible` changes.
 */
class FocusRing extends i$4 {
  constructor() {
    super(...arguments);
    /**
     * Makes the focus ring visible.
     */
    this.visible = false;
    /**
     * Makes the focus ring animate inwards instead of outwards.
     */
    this.inward = false;
    this.attachableController = new AttachableController(this, this.onControlChange.bind(this));
  }
  get htmlFor() {
    return this.attachableController.htmlFor;
  }
  set htmlFor(htmlFor) {
    this.attachableController.htmlFor = htmlFor;
  }
  get control() {
    return this.attachableController.control;
  }
  set control(control) {
    this.attachableController.control = control;
  }
  attach(control) {
    this.attachableController.attach(control);
  }
  detach() {
    this.attachableController.detach();
  }
  connectedCallback() {
    super.connectedCallback();
    // Needed for VoiceOver, which will create a "group" if the element is a
    // sibling to other content.
    this.setAttribute('aria-hidden', 'true');
  }
  /** @private */
  handleEvent(event) {
    if (event[HANDLED_BY_FOCUS_RING]) {
      // This ensures the focus ring does not activate when multiple focus rings
      // are used within a single component.
      return;
    }
    switch (event.type) {
      default:
        return;
      case 'focusin':
        this.visible = this.control?.matches(':focus-visible') ?? false;
        break;
      case 'focusout':
      case 'pointerdown':
        this.visible = false;
        break;
    }
    event[HANDLED_BY_FOCUS_RING] = true;
  }
  onControlChange(prev, next) {
    for (const event of EVENTS$1) {
      prev?.removeEventListener(event, this);
      next?.addEventListener(event, this);
    }
  }
  update(changed) {
    if (changed.has('visible')) {
      // This logic can be removed once the `:has` selector has been introduced
      // to Firefox. This is necessary to allow correct submenu styles.
      this.dispatchEvent(new Event('visibility-changed'));
    }
    super.update(changed);
  }
}
__decorate([n$5({
  type: Boolean,
  reflect: true
})], FocusRing.prototype, "visible", void 0);
__decorate([n$5({
  type: Boolean,
  reflect: true
})], FocusRing.prototype, "inward", void 0);
const HANDLED_BY_FOCUS_RING = Symbol('handledByFocusRing');

/**
 * @license
 * Copyright 2024 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Generated stylesheet for ./focus/internal/focus-ring-styles.css.
const styles$p = i$7`:host{animation-delay:0s,calc(var(--md-focus-ring-duration, 600ms)*.25);animation-duration:calc(var(--md-focus-ring-duration, 600ms)*.25),calc(var(--md-focus-ring-duration, 600ms)*.75);animation-timing-function:cubic-bezier(0.2, 0, 0, 1);box-sizing:border-box;color:var(--md-focus-ring-color, var(--md-sys-color-secondary, #625b71));display:none;pointer-events:none;position:absolute}:host([visible]){display:flex}:host(:not([inward])){animation-name:outward-grow,outward-shrink;border-end-end-radius:calc(var(--md-focus-ring-shape-end-end, var(--md-focus-ring-shape, var(--md-sys-shape-corner-full, 9999px))) + var(--md-focus-ring-outward-offset, 2px));border-end-start-radius:calc(var(--md-focus-ring-shape-end-start, var(--md-focus-ring-shape, var(--md-sys-shape-corner-full, 9999px))) + var(--md-focus-ring-outward-offset, 2px));border-start-end-radius:calc(var(--md-focus-ring-shape-start-end, var(--md-focus-ring-shape, var(--md-sys-shape-corner-full, 9999px))) + var(--md-focus-ring-outward-offset, 2px));border-start-start-radius:calc(var(--md-focus-ring-shape-start-start, var(--md-focus-ring-shape, var(--md-sys-shape-corner-full, 9999px))) + var(--md-focus-ring-outward-offset, 2px));inset:calc(-1*var(--md-focus-ring-outward-offset, 2px));outline:var(--md-focus-ring-width, 3px) solid currentColor}:host([inward]){animation-name:inward-grow,inward-shrink;border-end-end-radius:calc(var(--md-focus-ring-shape-end-end, var(--md-focus-ring-shape, var(--md-sys-shape-corner-full, 9999px))) - var(--md-focus-ring-inward-offset, 0px));border-end-start-radius:calc(var(--md-focus-ring-shape-end-start, var(--md-focus-ring-shape, var(--md-sys-shape-corner-full, 9999px))) - var(--md-focus-ring-inward-offset, 0px));border-start-end-radius:calc(var(--md-focus-ring-shape-start-end, var(--md-focus-ring-shape, var(--md-sys-shape-corner-full, 9999px))) - var(--md-focus-ring-inward-offset, 0px));border-start-start-radius:calc(var(--md-focus-ring-shape-start-start, var(--md-focus-ring-shape, var(--md-sys-shape-corner-full, 9999px))) - var(--md-focus-ring-inward-offset, 0px));border:var(--md-focus-ring-width, 3px) solid currentColor;inset:var(--md-focus-ring-inward-offset, 0px)}@keyframes outward-grow{from{outline-width:0}to{outline-width:var(--md-focus-ring-active-width, 8px)}}@keyframes outward-shrink{from{outline-width:var(--md-focus-ring-active-width, 8px)}}@keyframes inward-grow{from{border-width:0}to{border-width:var(--md-focus-ring-active-width, 8px)}}@keyframes inward-shrink{from{border-width:var(--md-focus-ring-active-width, 8px)}}@media(prefers-reduced-motion){:host{animation:none}}
`;

/**
 * @license
 * Copyright 2021 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * TODO(b/267336424): add docs
 *
 * @final
 * @suppress {visibility}
 */
let MdFocusRing = class MdFocusRing extends FocusRing {};
MdFocusRing.styles = [styles$p];
MdFocusRing = __decorate([t$1('md-focus-ring')], MdFocusRing);

/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
const t = {
    ATTRIBUTE: 1,
    CHILD: 2,
    PROPERTY: 3,
    BOOLEAN_ATTRIBUTE: 4},
  e$4 = t => (...e) => ({
    _$litDirective$: t,
    values: e
  });
let i$3 = class i {
  constructor(t) {}
  get _$AU() {
    return this._$AM._$AU;
  }
  _$AT(t, e, i) {
    this._$Ct = t, this._$AM = e, this._$Ci = i;
  }
  _$AS(t, e) {
    return this.update(t, e);
  }
  update(t, e) {
    return this.render(...e);
  }
};

/**
 * @license
 * Copyright 2018 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
const e$3 = e$4(class extends i$3 {
  constructor(t$1) {
    if (super(t$1), t$1.type !== t.ATTRIBUTE || "class" !== t$1.name || t$1.strings?.length > 2) throw Error("`classMap()` can only be used in the `class` attribute and must be the only part in the attribute.");
  }
  render(t) {
    return " " + Object.keys(t).filter(s => t[s]).join(" ") + " ";
  }
  update(s, [i]) {
    if (void 0 === this.st) {
      this.st = new Set(), void 0 !== s.strings && (this.nt = new Set(s.strings.join(" ").split(/\s/).filter(t => "" !== t)));
      for (const t in i) i[t] && !this.nt?.has(t) && this.st.add(t);
      return this.render(i);
    }
    const r = s.element.classList;
    for (const t of this.st) t in i || (r.remove(t), this.st.delete(t));
    for (const t in i) {
      const s = !!i[t];
      s === this.st.has(t) || this.nt?.has(t) || (s ? (r.add(t), this.st.add(t)) : (r.remove(t), this.st.delete(t)));
    }
    return E;
  }
});

/**
 * @license
 * Copyright 2021 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * Easing functions to use for web animations.
 *
 * **NOTE:** `EASING.EMPHASIZED` is approximated with unknown accuracy.
 *
 * TODO(b/241113345): replace with tokens
 */
const EASING = {
  STANDARD: 'cubic-bezier(0.2, 0, 0, 1)',
  EMPHASIZED: 'cubic-bezier(.3,0,0,1)',
  EMPHASIZED_ACCELERATE: 'cubic-bezier(.3,0,.8,.15)'};
/**
 * Creates an `AnimationSignal` that can be used to cancel a previous task.
 *
 * @example
 * class MyClass {
 *   private labelAnimationSignal = createAnimationSignal();
 *
 *   private async animateLabel() {
 *     // Start of the task. Previous tasks will be canceled.
 *     const signal = this.labelAnimationSignal.start();
 *
 *     // Do async work...
 *     if (signal.aborted) {
 *       // Use AbortSignal to check if a request was made to abort after some
 *       // asynchronous work.
 *       return;
 *     }
 *
 *     const animation = this.animate(...);
 *     // Add event listeners to be notified when the task should be canceled.
 *     signal.addEventListener('abort', () => {
 *       animation.cancel();
 *     });
 *
 *     animation.addEventListener('finish', () => {
 *       // Tell the signal that the current task is finished.
 *       this.labelAnimationSignal.finish();
 *     });
 *   }
 * }
 *
 * @return An `AnimationSignal`.
 */
function createAnimationSignal() {
  // The current animation's AbortController
  let animationAbortController = null;
  return {
    start() {
      // Tell the previous animation to cancel.
      animationAbortController?.abort();
      // Set up a new AbortController for the current animation.
      animationAbortController = new AbortController();
      // Provide the AbortSignal so that the caller can check aborted status
      // and add listeners.
      return animationAbortController.signal;
    },
    finish() {
      animationAbortController = null;
    }
  };
}

/**
 * @license
 * Copyright 2022 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
const PRESS_GROW_MS = 450;
const MINIMUM_PRESS_MS = 225;
const INITIAL_ORIGIN_SCALE = 0.2;
const PADDING = 10;
const SOFT_EDGE_MINIMUM_SIZE = 75;
const SOFT_EDGE_CONTAINER_RATIO = 0.35;
const PRESS_PSEUDO = '::after';
const ANIMATION_FILL = 'forwards';
/**
 * Interaction states for the ripple.
 *
 * On Touch:
 *  - `INACTIVE -> TOUCH_DELAY -> WAITING_FOR_CLICK -> INACTIVE`
 *  - `INACTIVE -> TOUCH_DELAY -> HOLDING -> WAITING_FOR_CLICK -> INACTIVE`
 *
 * On Mouse or Pen:
 *   - `INACTIVE -> WAITING_FOR_CLICK -> INACTIVE`
 */
var State;
(function (State) {
  /**
   * Initial state of the control, no touch in progress.
   *
   * Transitions:
   *   - on touch down: transition to `TOUCH_DELAY`.
   *   - on mouse down: transition to `WAITING_FOR_CLICK`.
   */
  State[State["INACTIVE"] = 0] = "INACTIVE";
  /**
   * Touch down has been received, waiting to determine if it's a swipe or
   * scroll.
   *
   * Transitions:
   *   - on touch up: begin press; transition to `WAITING_FOR_CLICK`.
   *   - on cancel: transition to `INACTIVE`.
   *   - after `TOUCH_DELAY_MS`: begin press; transition to `HOLDING`.
   */
  State[State["TOUCH_DELAY"] = 1] = "TOUCH_DELAY";
  /**
   * A touch has been deemed to be a press
   *
   * Transitions:
   *  - on up: transition to `WAITING_FOR_CLICK`.
   */
  State[State["HOLDING"] = 2] = "HOLDING";
  /**
   * The user touch has finished, transition into rest state.
   *
   * Transitions:
   *   - on click end press; transition to `INACTIVE`.
   */
  State[State["WAITING_FOR_CLICK"] = 3] = "WAITING_FOR_CLICK";
})(State || (State = {}));
/**
 * Events that the ripple listens to.
 */
const EVENTS = ['click', 'contextmenu', 'pointercancel', 'pointerdown', 'pointerenter', 'pointerleave', 'pointerup'];
/**
 * Delay reacting to touch so that we do not show the ripple for a swipe or
 * scroll interaction.
 */
const TOUCH_DELAY_MS = 150;
/**
 * Used to detect if HCM is active. Events do not process during HCM when the
 * ripple is not displayed.
 */
const FORCED_COLORS = window.matchMedia('(forced-colors: active)');
/**
 * A ripple component.
 */
class Ripple extends i$4 {
  constructor() {
    super(...arguments);
    /**
     * Disables the ripple.
     */
    this.disabled = false;
    this.hovered = false;
    this.pressed = false;
    this.rippleSize = '';
    this.rippleScale = '';
    this.initialSize = 0;
    this.state = State.INACTIVE;
    this.attachableController = new AttachableController(this, this.onControlChange.bind(this));
  }
  get htmlFor() {
    return this.attachableController.htmlFor;
  }
  set htmlFor(htmlFor) {
    this.attachableController.htmlFor = htmlFor;
  }
  get control() {
    return this.attachableController.control;
  }
  set control(control) {
    this.attachableController.control = control;
  }
  attach(control) {
    this.attachableController.attach(control);
  }
  detach() {
    this.attachableController.detach();
  }
  connectedCallback() {
    super.connectedCallback();
    // Needed for VoiceOver, which will create a "group" if the element is a
    // sibling to other content.
    this.setAttribute('aria-hidden', 'true');
  }
  render() {
    const classes = {
      'hovered': this.hovered,
      'pressed': this.pressed
    };
    return b`<div class="surface ${e$3(classes)}"></div>`;
  }
  update(changedProps) {
    if (changedProps.has('disabled') && this.disabled) {
      this.hovered = false;
      this.pressed = false;
    }
    super.update(changedProps);
  }
  /**
   * TODO(b/269799771): make private
   * @private only public for slider
   */
  handlePointerenter(event) {
    if (!this.shouldReactToEvent(event)) {
      return;
    }
    this.hovered = true;
  }
  /**
   * TODO(b/269799771): make private
   * @private only public for slider
   */
  handlePointerleave(event) {
    if (!this.shouldReactToEvent(event)) {
      return;
    }
    this.hovered = false;
    // release a held mouse or pen press that moves outside the element
    if (this.state !== State.INACTIVE) {
      this.endPressAnimation();
    }
  }
  handlePointerup(event) {
    if (!this.shouldReactToEvent(event)) {
      return;
    }
    if (this.state === State.HOLDING) {
      this.state = State.WAITING_FOR_CLICK;
      return;
    }
    if (this.state === State.TOUCH_DELAY) {
      this.state = State.WAITING_FOR_CLICK;
      this.startPressAnimation(this.rippleStartEvent);
      return;
    }
  }
  async handlePointerdown(event) {
    if (!this.shouldReactToEvent(event)) {
      return;
    }
    this.rippleStartEvent = event;
    if (!this.isTouch(event)) {
      this.state = State.WAITING_FOR_CLICK;
      this.startPressAnimation(event);
      return;
    }
    // Wait for a hold after touch delay
    this.state = State.TOUCH_DELAY;
    await new Promise(resolve => {
      setTimeout(resolve, TOUCH_DELAY_MS);
    });
    if (this.state !== State.TOUCH_DELAY) {
      return;
    }
    this.state = State.HOLDING;
    this.startPressAnimation(event);
  }
  handleClick() {
    // Click is a MouseEvent in Firefox and Safari, so we cannot use
    // `shouldReactToEvent`
    if (this.disabled) {
      return;
    }
    if (this.state === State.WAITING_FOR_CLICK) {
      this.endPressAnimation();
      return;
    }
    if (this.state === State.INACTIVE) {
      // keyboard synthesized click event
      this.startPressAnimation();
      this.endPressAnimation();
    }
  }
  handlePointercancel(event) {
    if (!this.shouldReactToEvent(event)) {
      return;
    }
    this.endPressAnimation();
  }
  handleContextmenu() {
    if (this.disabled) {
      return;
    }
    this.endPressAnimation();
  }
  determineRippleSize() {
    const {
      height,
      width
    } = this.getBoundingClientRect();
    const maxDim = Math.max(height, width);
    const softEdgeSize = Math.max(SOFT_EDGE_CONTAINER_RATIO * maxDim, SOFT_EDGE_MINIMUM_SIZE);
    // `?? 1` may be removed once `currentCSSZoom` is widely available.
    const zoom = this.currentCSSZoom ?? 1;
    const initialSize = Math.floor(maxDim * INITIAL_ORIGIN_SCALE / zoom);
    const hypotenuse = Math.sqrt(width ** 2 + height ** 2);
    const maxRadius = hypotenuse + PADDING;
    this.initialSize = initialSize;
    // The dimensions may be altered by CSS `zoom`, which needs to be
    // compensated for in the final scale() value.
    const maybeZoomedScale = (maxRadius + softEdgeSize) / initialSize;
    this.rippleScale = `${maybeZoomedScale / zoom}`;
    this.rippleSize = `${initialSize}px`;
  }
  getNormalizedPointerEventCoords(pointerEvent) {
    const {
      scrollX,
      scrollY
    } = window;
    const {
      left,
      top
    } = this.getBoundingClientRect();
    const documentX = scrollX + left;
    const documentY = scrollY + top;
    const {
      pageX,
      pageY
    } = pointerEvent;
    // `?? 1` may be removed once `currentCSSZoom` is widely available.
    const zoom = this.currentCSSZoom ?? 1;
    return {
      x: (pageX - documentX) / zoom,
      y: (pageY - documentY) / zoom
    };
  }
  getTranslationCoordinates(positionEvent) {
    const {
      height,
      width
    } = this.getBoundingClientRect();
    // `?? 1` may be removed once `currentCSSZoom` is widely available.
    const zoom = this.currentCSSZoom ?? 1;
    // end in the center
    const endPoint = {
      x: (width / zoom - this.initialSize) / 2,
      y: (height / zoom - this.initialSize) / 2
    };
    let startPoint;
    if (positionEvent instanceof PointerEvent) {
      startPoint = this.getNormalizedPointerEventCoords(positionEvent);
    } else {
      startPoint = {
        x: width / zoom / 2,
        y: height / zoom / 2
      };
    }
    // center around start point
    startPoint = {
      x: startPoint.x - this.initialSize / 2,
      y: startPoint.y - this.initialSize / 2
    };
    return {
      startPoint,
      endPoint
    };
  }
  startPressAnimation(positionEvent) {
    if (!this.mdRoot) {
      return;
    }
    this.pressed = true;
    this.growAnimation?.cancel();
    this.determineRippleSize();
    const {
      startPoint,
      endPoint
    } = this.getTranslationCoordinates(positionEvent);
    const translateStart = `${startPoint.x}px, ${startPoint.y}px`;
    const translateEnd = `${endPoint.x}px, ${endPoint.y}px`;
    this.growAnimation = this.mdRoot.animate({
      top: [0, 0],
      left: [0, 0],
      height: [this.rippleSize, this.rippleSize],
      width: [this.rippleSize, this.rippleSize],
      transform: [`translate(${translateStart}) scale(1)`, `translate(${translateEnd}) scale(${this.rippleScale})`]
    }, {
      pseudoElement: PRESS_PSEUDO,
      duration: PRESS_GROW_MS,
      easing: EASING.STANDARD,
      fill: ANIMATION_FILL
    });
  }
  async endPressAnimation() {
    this.rippleStartEvent = undefined;
    this.state = State.INACTIVE;
    const animation = this.growAnimation;
    let pressAnimationPlayState = Infinity;
    if (typeof animation?.currentTime === 'number') {
      pressAnimationPlayState = animation.currentTime;
    } else if (animation?.currentTime) {
      pressAnimationPlayState = animation.currentTime.to('ms').value;
    }
    if (pressAnimationPlayState >= MINIMUM_PRESS_MS) {
      this.pressed = false;
      return;
    }
    await new Promise(resolve => {
      setTimeout(resolve, MINIMUM_PRESS_MS - pressAnimationPlayState);
    });
    if (this.growAnimation !== animation) {
      // A new press animation was started. The old animation was canceled and
      // should not finish the pressed state.
      return;
    }
    this.pressed = false;
  }
  /**
   * Returns `true` if
   *  - the ripple element is enabled
   *  - the pointer is primary for the input type
   *  - the pointer is the pointer that started the interaction, or will start
   * the interaction
   *  - the pointer is a touch, or the pointer state has the primary button
   * held, or the pointer is hovering
   */
  shouldReactToEvent(event) {
    if (this.disabled || !event.isPrimary) {
      return false;
    }
    if (this.rippleStartEvent && this.rippleStartEvent.pointerId !== event.pointerId) {
      return false;
    }
    if (event.type === 'pointerenter' || event.type === 'pointerleave') {
      return !this.isTouch(event);
    }
    const isPrimaryButton = event.buttons === 1;
    return this.isTouch(event) || isPrimaryButton;
  }
  isTouch({
    pointerType
  }) {
    return pointerType === 'touch';
  }
  /** @private */
  async handleEvent(event) {
    if (FORCED_COLORS?.matches) {
      // Skip event logic since the ripple is `display: none`.
      return;
    }
    switch (event.type) {
      case 'click':
        this.handleClick();
        break;
      case 'contextmenu':
        this.handleContextmenu();
        break;
      case 'pointercancel':
        this.handlePointercancel(event);
        break;
      case 'pointerdown':
        await this.handlePointerdown(event);
        break;
      case 'pointerenter':
        this.handlePointerenter(event);
        break;
      case 'pointerleave':
        this.handlePointerleave(event);
        break;
      case 'pointerup':
        this.handlePointerup(event);
        break;
    }
  }
  onControlChange(prev, next) {
    for (const event of EVENTS) {
      prev?.removeEventListener(event, this);
      next?.addEventListener(event, this);
    }
  }
}
__decorate([n$5({
  type: Boolean,
  reflect: true
})], Ripple.prototype, "disabled", void 0);
__decorate([r$3()], Ripple.prototype, "hovered", void 0);
__decorate([r$3()], Ripple.prototype, "pressed", void 0);
__decorate([e$6('.surface')], Ripple.prototype, "mdRoot", void 0);

/**
 * @license
 * Copyright 2024 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Generated stylesheet for ./ripple/internal/ripple-styles.css.
const styles$o = i$7`:host{display:flex;margin:auto;pointer-events:none}:host([disabled]){display:none}@media(forced-colors: active){:host{display:none}}:host,.surface{border-radius:inherit;position:absolute;inset:0;overflow:hidden}.surface{-webkit-tap-highlight-color:rgba(0,0,0,0)}.surface::before,.surface::after{content:"";opacity:0;position:absolute}.surface::before{background-color:var(--md-ripple-hover-color, var(--md-sys-color-on-surface, #1d1b20));inset:0;transition:opacity 15ms linear,background-color 15ms linear}.surface::after{background:radial-gradient(closest-side, var(--md-ripple-pressed-color, var(--md-sys-color-on-surface, #1d1b20)) max(100% - 70px, 65%), transparent 100%);transform-origin:center center;transition:opacity 375ms linear}.hovered::before{background-color:var(--md-ripple-hover-color, var(--md-sys-color-on-surface, #1d1b20));opacity:var(--md-ripple-hover-opacity, 0.08)}.pressed::after{opacity:var(--md-ripple-pressed-opacity, 0.12);transition-duration:105ms}
`;

/**
 * @license
 * Copyright 2022 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @summary Ripples, also known as state layers, are visual indicators used to
 * communicate the status of a component or interactive element.
 *
 * @description A state layer is a semi-transparent covering on an element that
 * indicates its state. State layers provide a systematic approach to
 * visualizing states by using opacity. A layer can be applied to an entire
 * element or in a circular shape and only one state layer can be applied at a
 * given time.
 *
 * @final
 * @suppress {visibility}
 */
let MdRipple = class MdRipple extends Ripple {};
MdRipple.styles = [styles$o];
MdRipple = __decorate([t$1('md-ripple')], MdRipple);

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * Accessibility Object Model reflective aria properties.
 */
const ARIA_PROPERTIES = ['role', 'ariaAtomic', 'ariaAutoComplete', 'ariaBusy', 'ariaChecked', 'ariaColCount', 'ariaColIndex', 'ariaColSpan', 'ariaCurrent', 'ariaDisabled', 'ariaExpanded', 'ariaHasPopup', 'ariaHidden', 'ariaInvalid', 'ariaKeyShortcuts', 'ariaLabel', 'ariaLevel', 'ariaLive', 'ariaModal', 'ariaMultiLine', 'ariaMultiSelectable', 'ariaOrientation', 'ariaPlaceholder', 'ariaPosInSet', 'ariaPressed', 'ariaReadOnly', 'ariaRequired', 'ariaRoleDescription', 'ariaRowCount', 'ariaRowIndex', 'ariaRowSpan', 'ariaSelected', 'ariaSetSize', 'ariaSort', 'ariaValueMax', 'ariaValueMin', 'ariaValueNow', 'ariaValueText'];
/**
 * Accessibility Object Model aria attributes.
 */
const ARIA_ATTRIBUTES = ARIA_PROPERTIES.map(ariaPropertyToAttribute);
/**
 * Checks if an attribute is one of the AOM aria attributes.
 *
 * @example
 * isAriaAttribute('aria-label'); // true
 *
 * @param attribute The attribute to check.
 * @return True if the attribute is an aria attribute, or false if not.
 */
function isAriaAttribute(attribute) {
  return ARIA_ATTRIBUTES.includes(attribute);
}
/**
 * Converts an AOM aria property into its corresponding attribute.
 *
 * @example
 * ariaPropertyToAttribute('ariaLabel'); // 'aria-label'
 *
 * @param property The aria property.
 * @return The aria attribute.
 */
function ariaPropertyToAttribute(property) {
  return property.replace('aria', 'aria-')
  // IDREF attributes also include an "Element" or "Elements" suffix
  .replace(/Elements?/g, '').toLowerCase();
}

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Private symbols
const privateIgnoreAttributeChangesFor = Symbol('privateIgnoreAttributeChangesFor');
/**
 * Mixes in aria delegation for elements that delegate focus and aria to inner
 * shadow root elements.
 *
 * This mixin fixes invalid aria announcements with shadow roots, caused by
 * duplicate aria attributes on both the host and the inner shadow root element.
 *
 * Note: this mixin **does not yet support** ID reference attributes, such as
 * `aria-labelledby` or `aria-controls`.
 *
 * @example
 * ```ts
 * class MyButton extends mixinDelegatesAria(LitElement) {
 *   static shadowRootOptions = {mode: 'open', delegatesFocus: true};
 *
 *   render() {
 *     return html`
 *       <button aria-label=${this.ariaLabel || nothing}>
 *         <slot></slot>
 *       </button>
 *     `;
 *   }
 * }
 * ```
 * ```html
 * <my-button aria-label="Plus one">+1</my-button>
 * ```
 *
 * Use `ARIAMixinStrict` for lit analyzer strict types, such as the "role"
 * attribute.
 *
 * @example
 * ```ts
 * return html`
 *   <button role=${(this as ARIAMixinStrict).role || nothing}>
 *     <slot></slot>
 *   </button>
 * `;
 * ```
 *
 * In the future, updates to the Accessibility Object Model (AOM) will provide
 * built-in aria delegation features that will replace this mixin.
 *
 * @param base The class to mix functionality into.
 * @return The provided class with aria delegation mixed in.
 */
function mixinDelegatesAria(base) {
  var _a;
  class WithDelegatesAriaElement extends base {
    constructor() {
      super(...arguments);
      this[_a] = new Set();
    }
    attributeChangedCallback(name, oldValue, newValue) {
      if (!isAriaAttribute(name)) {
        super.attributeChangedCallback(name, oldValue, newValue);
        return;
      }
      if (this[privateIgnoreAttributeChangesFor].has(name)) {
        return;
      }
      // Don't trigger another `attributeChangedCallback` once we remove the
      // aria attribute from the host. We check the explicit name of the
      // attribute to ignore since `attributeChangedCallback` can be called
      // multiple times out of an expected order when hydrating an element with
      // multiple attributes.
      this[privateIgnoreAttributeChangesFor].add(name);
      this.removeAttribute(name);
      this[privateIgnoreAttributeChangesFor].delete(name);
      const dataProperty = ariaAttributeToDataProperty(name);
      if (newValue === null) {
        delete this.dataset[dataProperty];
      } else {
        this.dataset[dataProperty] = newValue;
      }
      this.requestUpdate(ariaAttributeToDataProperty(name), oldValue);
    }
    getAttribute(name) {
      if (isAriaAttribute(name)) {
        return super.getAttribute(ariaAttributeToDataAttribute(name));
      }
      return super.getAttribute(name);
    }
    removeAttribute(name) {
      super.removeAttribute(name);
      if (isAriaAttribute(name)) {
        super.removeAttribute(ariaAttributeToDataAttribute(name));
        // Since `aria-*` attributes are already removed`, we need to request
        // an update because `attributeChangedCallback` will not be called.
        this.requestUpdate();
      }
    }
  }
  _a = privateIgnoreAttributeChangesFor;
  setupDelegatesAriaProperties(WithDelegatesAriaElement);
  return WithDelegatesAriaElement;
}
/**
 * Overrides the constructor's native `ARIAMixin` properties to ensure that
 * aria properties reflect the values that were shifted to a data attribute.
 *
 * @param ctor The `ReactiveElement` constructor to patch.
 */
function setupDelegatesAriaProperties(ctor) {
  for (const ariaProperty of ARIA_PROPERTIES) {
    // The casing between ariaProperty and the dataProperty may be different.
    // ex: aria-haspopup -> ariaHasPopup
    const ariaAttribute = ariaPropertyToAttribute(ariaProperty);
    // ex: aria-haspopup -> data-aria-haspopup
    const dataAttribute = ariaAttributeToDataAttribute(ariaAttribute);
    // ex: aria-haspopup -> dataset.ariaHaspopup
    const dataProperty = ariaAttributeToDataProperty(ariaAttribute);
    // Call `ReactiveElement.createProperty()` so that the `aria-*` and `data-*`
    // attributes are added to the `static observedAttributes` array. This
    // triggers `attributeChangedCallback` for the delegates aria mixin to
    // handle.
    ctor.createProperty(ariaProperty, {
      attribute: ariaAttribute,
      noAccessor: true
    });
    ctor.createProperty(Symbol(dataAttribute), {
      attribute: dataAttribute,
      noAccessor: true
    });
    // Re-define the `ARIAMixin` properties to handle data attribute shifting.
    // It is safe to use `Object.defineProperty` here because the properties
    // are native and not renamed.
    // tslint:disable-next-line:ban-unsafe-reflection
    Object.defineProperty(ctor.prototype, ariaProperty, {
      configurable: true,
      enumerable: true,
      get() {
        return this.dataset[dataProperty] ?? null;
      },
      set(value) {
        const prevValue = this.dataset[dataProperty] ?? null;
        if (value === prevValue) {
          return;
        }
        if (value === null) {
          delete this.dataset[dataProperty];
        } else {
          this.dataset[dataProperty] = value;
        }
        this.requestUpdate(ariaProperty, prevValue);
      }
    });
  }
}
function ariaAttributeToDataAttribute(ariaAttribute) {
  // aria-haspopup -> data-aria-haspopup
  return `data-${ariaAttribute}`;
}
function ariaAttributeToDataProperty(ariaAttribute) {
  // aria-haspopup -> dataset.ariaHaspopup
  return ariaAttribute.replace(/-\w/, dashLetter => dashLetter[1].toUpperCase());
}

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * A unique symbol used for protected access to an instance's
 * `ElementInternals`.
 *
 * @example
 * ```ts
 * class MyElement extends mixinElementInternals(LitElement) {
 *   constructor() {
 *     super();
 *     this[internals].role = 'button';
 *   }
 * }
 * ```
 */
const internals = Symbol('internals');
// Private symbols
const privateInternals = Symbol('privateInternals');
/**
 * Mixes in an attached `ElementInternals` instance.
 *
 * This mixin is only needed when other shared code needs access to a
 * component's `ElementInternals`, such as form-associated mixins.
 *
 * @param base The class to mix functionality into.
 * @return The provided class with `WithElementInternals` mixed in.
 */
function mixinElementInternals(base) {
  class WithElementInternalsElement extends base {
    get [internals]() {
      // Create internals in getter so that it can be used in methods called on
      // construction in `ReactiveElement`, such as `requestUpdate()`.
      if (!this[privateInternals]) {
        // Cast needed for closure
        this[privateInternals] = this.attachInternals();
      }
      return this[privateInternals];
    }
  }
  return WithElementInternalsElement;
}

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * Sets up an element's constructor to enable form submission. The element
 * instance should be form associated and have a `type` property.
 *
 * A click listener is added to each element instance. If the click is not
 * default prevented, it will submit the element's form, if any.
 *
 * @example
 * ```ts
 * class MyElement extends mixinElementInternals(LitElement) {
 *   static {
 *     setupFormSubmitter(MyElement);
 *   }
 *
 *   static formAssociated = true;
 *
 *   type: FormSubmitterType = 'submit';
 * }
 * ```
 *
 * @param ctor The form submitter element's constructor.
 */
function setupFormSubmitter(ctor) {
  ctor.addInitializer(instance => {
    const submitter = instance;
    submitter.addEventListener('click', async event => {
      const {
        type,
        [internals]: elementInternals
      } = submitter;
      const {
        form
      } = elementInternals;
      if (!form || type === 'button') {
        return;
      }
      // Wait a full task for event bubbling to complete.
      await new Promise(resolve => {
        setTimeout(resolve);
      });
      if (event.defaultPrevented) {
        return;
      }
      if (type === 'reset') {
        form.reset();
        return;
      }
      // form.requestSubmit(submitter) does not work with form associated custom
      // elements. This patches the dispatched submit event to add the correct
      // `submitter`.
      // See https://github.com/WICG/webcomponents/issues/814
      form.addEventListener('submit', submitEvent => {
        Object.defineProperty(submitEvent, 'submitter', {
          configurable: true,
          enumerable: true,
          get: () => submitter
        });
      }, {
        capture: true,
        once: true
      });
      elementInternals.setFormValue(submitter.value);
      form.requestSubmit();
    });
  });
}

/**
 * @license
 * Copyright 2021 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * Dispatches a click event to the given element that triggers a native action,
 * but is not composed and therefore is not seen outside the element.
 *
 * This is useful for responding to an external click event on the host element
 * that should trigger an internal action like a button click.
 *
 * Note, a helper is provided because setting this up correctly is a bit tricky.
 * In particular, calling `click` on an element creates a composed event, which
 * is not desirable, and a manually dispatched event must specifically be a
 * `MouseEvent` to trigger a native action.
 *
 * @example
 * hostClickListener = (event: MouseEvent) {
 *   if (isActivationClick(event)) {
 *     this.dispatchActivationClick(this.buttonElement);
 *   }
 * }
 *
 */
function dispatchActivationClick(element) {
  const event = new MouseEvent('click', {
    bubbles: true
  });
  element.dispatchEvent(event);
  return event;
}
/**
 * Returns true if the click event should trigger an activation behavior. The
 * behavior is defined by the element and is whatever it should do when
 * clicked.
 *
 * Typically when an element needs to handle a click, the click is generated
 * from within the element and an event listener within the element implements
 * the needed behavior; however, it's possible to fire a click directly
 * at the element that the element should handle. This method helps
 * distinguish these "external" clicks.
 *
 * An "external" click can be triggered in a number of ways: via a click
 * on an associated label for a form  associated element, calling
 * `element.click()`, or calling
 * `element.dispatchEvent(new MouseEvent('click', ...))`.
 *
 * Also works around Firefox issue
 * https://bugzilla.mozilla.org/show_bug.cgi?id=1804576 by squelching
 * events for a microtask after called.
 *
 * @example
 * hostClickListener = (event: MouseEvent) {
 *   if (isActivationClick(event)) {
 *     this.dispatchActivationClick(this.buttonElement);
 *   }
 * }
 *
 */
function isActivationClick(event) {
  // Event must start at the event target.
  if (event.currentTarget !== event.target) {
    return false;
  }
  // Event must not be retargeted from shadowRoot.
  if (event.composedPath()[0] !== event.target) {
    return false;
  }
  // Target must not be disabled; this should only occur for a synthetically
  // dispatched click.
  if (event.target.disabled) {
    return false;
  }
  // This is an activation if the event should not be squelched.
  return !squelchEvent(event);
}
// TODO(https://bugzilla.mozilla.org/show_bug.cgi?id=1804576)
//  Remove when Firefox bug is addressed.
function squelchEvent(event) {
  const squelched = isSquelchingEvents;
  if (squelched) {
    event.preventDefault();
    event.stopImmediatePropagation();
  }
  squelchEventsForMicrotask();
  return squelched;
}
// Ignore events for one microtask only.
let isSquelchingEvents = false;
async function squelchEventsForMicrotask() {
  isSquelchingEvents = true;
  // Need to pause for just one microtask.
  // tslint:disable-next-line
  await null;
  isSquelchingEvents = false;
}

/**
 * @license
 * Copyright 2019 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Separate variable needed for closure.
const buttonBaseClass = mixinDelegatesAria(mixinElementInternals(i$4));
/**
 * A button component.
 */
class Button extends buttonBaseClass {
  get name() {
    return this.getAttribute('name') ?? '';
  }
  set name(name) {
    this.setAttribute('name', name);
  }
  /**
   * The associated form element with which this element's value will submit.
   */
  get form() {
    return this[internals].form;
  }
  constructor() {
    super();
    /**
     * Whether or not the button is disabled.
     */
    this.disabled = false;
    /**
     * Whether or not the button is "soft-disabled" (disabled but still
     * focusable).
     *
     * Use this when a button needs increased visibility when disabled. See
     * https://www.w3.org/WAI/ARIA/apg/practices/keyboard-interface/#kbd_disabled_controls
     * for more guidance on when this is needed.
     */
    this.softDisabled = false;
    /**
     * The URL that the link button points to.
     */
    this.href = '';
    /**
     * The filename to use when downloading the linked resource.
     * If not specified, the browser will determine a filename.
     * This is only applicable when the button is used as a link (`href` is set).
     */
    this.download = '';
    /**
     * Where to display the linked `href` URL for a link button. Common options
     * include `_blank` to open in a new tab.
     */
    this.target = '';
    /**
     * Whether to render the icon at the inline end of the label rather than the
     * inline start.
     *
     * _Note:_ Link buttons cannot have trailing icons.
     */
    this.trailingIcon = false;
    /**
     * Whether to display the icon or not.
     */
    this.hasIcon = false;
    /**
     * The default behavior of the button. May be "button", "reset", or "submit"
     * (default).
     */
    this.type = 'submit';
    /**
     * The value added to a form with the button's name when the button submits a
     * form.
     */
    this.value = '';
    {
      this.addEventListener('click', this.handleClick.bind(this));
    }
  }
  focus() {
    this.buttonElement?.focus();
  }
  blur() {
    this.buttonElement?.blur();
  }
  render() {
    const isRippleDisabled = this.disabled || this.softDisabled;
    const buttonOrLink = this.href ? this.renderLink() : this.renderButton();
    // TODO(b/310046938): due to a limitation in focus ring/ripple, we can't use
    // the same ID for different elements, so we change the ID instead.
    const buttonId = this.href ? 'link' : 'button';
    return b`
      ${this.renderElevationOrOutline?.()}
      <div class="background"></div>
      <md-focus-ring part="focus-ring" for=${buttonId}></md-focus-ring>
      <md-ripple
        part="ripple"
        for=${buttonId}
        ?disabled="${isRippleDisabled}"></md-ripple>
      ${buttonOrLink}
    `;
  }
  renderButton() {
    // Needed for closure conformance
    const {
      ariaLabel,
      ariaHasPopup,
      ariaExpanded
    } = this;
    return b`<button
      id="button"
      class="button"
      ?disabled=${this.disabled}
      aria-disabled=${this.softDisabled || A}
      aria-label="${ariaLabel || A}"
      aria-haspopup="${ariaHasPopup || A}"
      aria-expanded="${ariaExpanded || A}">
      ${this.renderContent()}
    </button>`;
  }
  renderLink() {
    // Needed for closure conformance
    const {
      ariaLabel,
      ariaHasPopup,
      ariaExpanded
    } = this;
    return b`<a
      id="link"
      class="button"
      aria-label="${ariaLabel || A}"
      aria-haspopup="${ariaHasPopup || A}"
      aria-expanded="${ariaExpanded || A}"
      aria-disabled=${this.disabled || this.softDisabled || A}
      tabindex="${this.disabled && !this.softDisabled ? -1 : A}"
      href=${this.href}
      download=${this.download || A}
      target=${this.target || A}
      >${this.renderContent()}
    </a>`;
  }
  renderContent() {
    const icon = b`<slot
      name="icon"
      @slotchange="${this.handleSlotChange}"></slot>`;
    return b`
      <span class="touch"></span>
      ${this.trailingIcon ? A : icon}
      <span class="label"><slot></slot></span>
      ${this.trailingIcon ? icon : A}
    `;
  }
  handleClick(event) {
    // If the button is soft-disabled or a disabled link, we need to explicitly
    // prevent the click from propagating to other event listeners as well as
    // prevent the default action.
    if (this.softDisabled || this.disabled && this.href) {
      event.stopImmediatePropagation();
      event.preventDefault();
      return;
    }
    if (!isActivationClick(event) || !this.buttonElement) {
      return;
    }
    this.focus();
    dispatchActivationClick(this.buttonElement);
  }
  handleSlotChange() {
    this.hasIcon = this.assignedIcons.length > 0;
  }
}
(() => {
  setupFormSubmitter(Button);
})();
/** @nocollapse */
Button.formAssociated = true;
/** @nocollapse */
Button.shadowRootOptions = {
  mode: 'open',
  delegatesFocus: true
};
__decorate([n$5({
  type: Boolean,
  reflect: true
})], Button.prototype, "disabled", void 0);
__decorate([n$5({
  type: Boolean,
  attribute: 'soft-disabled',
  reflect: true
})], Button.prototype, "softDisabled", void 0);
__decorate([n$5()], Button.prototype, "href", void 0);
__decorate([n$5()], Button.prototype, "download", void 0);
__decorate([n$5()], Button.prototype, "target", void 0);
__decorate([n$5({
  type: Boolean,
  attribute: 'trailing-icon',
  reflect: true
})], Button.prototype, "trailingIcon", void 0);
__decorate([n$5({
  type: Boolean,
  attribute: 'has-icon',
  reflect: true
})], Button.prototype, "hasIcon", void 0);
__decorate([n$5()], Button.prototype, "type", void 0);
__decorate([n$5({
  reflect: true
})], Button.prototype, "value", void 0);
__decorate([e$6('.button')], Button.prototype, "buttonElement", void 0);
__decorate([o$5({
  slot: 'icon',
  flatten: true
})], Button.prototype, "assignedIcons", void 0);

/**
 * @license
 * Copyright 2021 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * An outlined button component.
 */
class OutlinedButton extends Button {
  renderElevationOrOutline() {
    return b`<div class="outline"></div>`;
  }
}

/**
 * @license
 * Copyright 2024 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Generated stylesheet for ./button/internal/outlined-styles.css.
const styles$n = i$7`:host{--_container-height: var(--md-outlined-button-container-height, 40px);--_disabled-label-text-color: var(--md-outlined-button-disabled-label-text-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-label-text-opacity: var(--md-outlined-button-disabled-label-text-opacity, 0.38);--_disabled-outline-color: var(--md-outlined-button-disabled-outline-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-outline-opacity: var(--md-outlined-button-disabled-outline-opacity, 0.12);--_focus-label-text-color: var(--md-outlined-button-focus-label-text-color, var(--md-sys-color-primary, #6750a4));--_hover-label-text-color: var(--md-outlined-button-hover-label-text-color, var(--md-sys-color-primary, #6750a4));--_hover-state-layer-color: var(--md-outlined-button-hover-state-layer-color, var(--md-sys-color-primary, #6750a4));--_hover-state-layer-opacity: var(--md-outlined-button-hover-state-layer-opacity, 0.08);--_label-text-color: var(--md-outlined-button-label-text-color, var(--md-sys-color-primary, #6750a4));--_label-text-font: var(--md-outlined-button-label-text-font, var(--md-sys-typescale-label-large-font, var(--md-ref-typeface-plain, Roboto)));--_label-text-line-height: var(--md-outlined-button-label-text-line-height, var(--md-sys-typescale-label-large-line-height, 1.25rem));--_label-text-size: var(--md-outlined-button-label-text-size, var(--md-sys-typescale-label-large-size, 0.875rem));--_label-text-weight: var(--md-outlined-button-label-text-weight, var(--md-sys-typescale-label-large-weight, var(--md-ref-typeface-weight-medium, 500)));--_outline-color: var(--md-outlined-button-outline-color, var(--md-sys-color-outline, #79747e));--_outline-width: var(--md-outlined-button-outline-width, 1px);--_pressed-label-text-color: var(--md-outlined-button-pressed-label-text-color, var(--md-sys-color-primary, #6750a4));--_pressed-outline-color: var(--md-outlined-button-pressed-outline-color, var(--md-sys-color-outline, #79747e));--_pressed-state-layer-color: var(--md-outlined-button-pressed-state-layer-color, var(--md-sys-color-primary, #6750a4));--_pressed-state-layer-opacity: var(--md-outlined-button-pressed-state-layer-opacity, 0.12);--_disabled-icon-color: var(--md-outlined-button-disabled-icon-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-icon-opacity: var(--md-outlined-button-disabled-icon-opacity, 0.38);--_focus-icon-color: var(--md-outlined-button-focus-icon-color, var(--md-sys-color-primary, #6750a4));--_hover-icon-color: var(--md-outlined-button-hover-icon-color, var(--md-sys-color-primary, #6750a4));--_icon-color: var(--md-outlined-button-icon-color, var(--md-sys-color-primary, #6750a4));--_icon-size: var(--md-outlined-button-icon-size, 18px);--_pressed-icon-color: var(--md-outlined-button-pressed-icon-color, var(--md-sys-color-primary, #6750a4));--_container-shape-start-start: var(--md-outlined-button-container-shape-start-start, var(--md-outlined-button-container-shape, var(--md-sys-shape-corner-full, 9999px)));--_container-shape-start-end: var(--md-outlined-button-container-shape-start-end, var(--md-outlined-button-container-shape, var(--md-sys-shape-corner-full, 9999px)));--_container-shape-end-end: var(--md-outlined-button-container-shape-end-end, var(--md-outlined-button-container-shape, var(--md-sys-shape-corner-full, 9999px)));--_container-shape-end-start: var(--md-outlined-button-container-shape-end-start, var(--md-outlined-button-container-shape, var(--md-sys-shape-corner-full, 9999px)));--_leading-space: var(--md-outlined-button-leading-space, 24px);--_trailing-space: var(--md-outlined-button-trailing-space, 24px);--_with-leading-icon-leading-space: var(--md-outlined-button-with-leading-icon-leading-space, 16px);--_with-leading-icon-trailing-space: var(--md-outlined-button-with-leading-icon-trailing-space, 24px);--_with-trailing-icon-leading-space: var(--md-outlined-button-with-trailing-icon-leading-space, 24px);--_with-trailing-icon-trailing-space: var(--md-outlined-button-with-trailing-icon-trailing-space, 16px);--_container-color: none;--_disabled-container-color: none;--_disabled-container-opacity: 0}.outline{inset:0;border-style:solid;position:absolute;box-sizing:border-box;border-color:var(--_outline-color);border-start-start-radius:var(--_container-shape-start-start);border-start-end-radius:var(--_container-shape-start-end);border-end-start-radius:var(--_container-shape-end-start);border-end-end-radius:var(--_container-shape-end-end)}:host(:active) .outline{border-color:var(--_pressed-outline-color)}:host(:is([disabled],[soft-disabled])) .outline{border-color:var(--_disabled-outline-color);opacity:var(--_disabled-outline-opacity)}@media(forced-colors: active){:host(:is([disabled],[soft-disabled])) .background{border-color:GrayText}:host(:is([disabled],[soft-disabled])) .outline{opacity:1}}.outline,md-ripple{border-width:var(--_outline-width)}md-ripple{inline-size:calc(100% - 2*var(--_outline-width));block-size:calc(100% - 2*var(--_outline-width));border-style:solid;border-color:rgba(0,0,0,0)}
`;

/**
 * @license
 * Copyright 2024 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Generated stylesheet for ./button/internal/shared-styles.css.
const styles$m = i$7`:host{border-start-start-radius:var(--_container-shape-start-start);border-start-end-radius:var(--_container-shape-start-end);border-end-start-radius:var(--_container-shape-end-start);border-end-end-radius:var(--_container-shape-end-end);box-sizing:border-box;cursor:pointer;display:inline-flex;gap:8px;min-height:var(--_container-height);outline:none;padding-block:calc((var(--_container-height) - max(var(--_label-text-line-height),var(--_icon-size)))/2);padding-inline-start:var(--_leading-space);padding-inline-end:var(--_trailing-space);place-content:center;place-items:center;position:relative;font-family:var(--_label-text-font);font-size:var(--_label-text-size);line-height:var(--_label-text-line-height);font-weight:var(--_label-text-weight);text-overflow:ellipsis;text-wrap:nowrap;user-select:none;-webkit-tap-highlight-color:rgba(0,0,0,0);vertical-align:top;--md-ripple-hover-color: var(--_hover-state-layer-color);--md-ripple-pressed-color: var(--_pressed-state-layer-color);--md-ripple-hover-opacity: var(--_hover-state-layer-opacity);--md-ripple-pressed-opacity: var(--_pressed-state-layer-opacity)}md-focus-ring{--md-focus-ring-shape-start-start: var(--_container-shape-start-start);--md-focus-ring-shape-start-end: var(--_container-shape-start-end);--md-focus-ring-shape-end-end: var(--_container-shape-end-end);--md-focus-ring-shape-end-start: var(--_container-shape-end-start)}:host(:is([disabled],[soft-disabled])){cursor:default;pointer-events:none}.button{border-radius:inherit;cursor:inherit;display:inline-flex;align-items:center;justify-content:center;border:none;outline:none;-webkit-appearance:none;vertical-align:middle;background:rgba(0,0,0,0);text-decoration:none;min-width:calc(64px - var(--_leading-space) - var(--_trailing-space));width:100%;z-index:0;height:100%;font:inherit;color:var(--_label-text-color);padding:0;gap:inherit;text-transform:inherit}.button::-moz-focus-inner{padding:0;border:0}:host(:hover) .button{color:var(--_hover-label-text-color)}:host(:focus-within) .button{color:var(--_focus-label-text-color)}:host(:active) .button{color:var(--_pressed-label-text-color)}.background{background:var(--_container-color);border-radius:inherit;inset:0;position:absolute}.label{overflow:hidden}:is(.button,.label,.label slot),.label ::slotted(*){text-overflow:inherit}:host(:is([disabled],[soft-disabled])) .label{color:var(--_disabled-label-text-color);opacity:var(--_disabled-label-text-opacity)}:host(:is([disabled],[soft-disabled])) .background{background:var(--_disabled-container-color);opacity:var(--_disabled-container-opacity)}@media(forced-colors: active){.background{border:1px solid CanvasText}:host(:is([disabled],[soft-disabled])){--_disabled-icon-color: GrayText;--_disabled-icon-opacity: 1;--_disabled-container-opacity: 1;--_disabled-label-text-color: GrayText;--_disabled-label-text-opacity: 1}}:host([has-icon]:not([trailing-icon])){padding-inline-start:var(--_with-leading-icon-leading-space);padding-inline-end:var(--_with-leading-icon-trailing-space)}:host([has-icon][trailing-icon]){padding-inline-start:var(--_with-trailing-icon-leading-space);padding-inline-end:var(--_with-trailing-icon-trailing-space)}::slotted([slot=icon]){display:inline-flex;position:relative;writing-mode:horizontal-tb;fill:currentColor;flex-shrink:0;color:var(--_icon-color);font-size:var(--_icon-size);inline-size:var(--_icon-size);block-size:var(--_icon-size)}:host(:hover) ::slotted([slot=icon]){color:var(--_hover-icon-color)}:host(:focus-within) ::slotted([slot=icon]){color:var(--_focus-icon-color)}:host(:active) ::slotted([slot=icon]){color:var(--_pressed-icon-color)}:host(:is([disabled],[soft-disabled])) ::slotted([slot=icon]){color:var(--_disabled-icon-color);opacity:var(--_disabled-icon-opacity)}.touch{position:absolute;top:50%;height:48px;left:0;right:0;transform:translateY(-50%)}:host([touch-target=wrapper]){margin:max(0px,(48px - var(--_container-height))/2) 0}:host([touch-target=none]) .touch{display:none}
`;

/**
 * @license
 * Copyright 2021 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @summary Buttons help people take action, such as sending an email, sharing a
 * document, or liking a comment.
 *
 * @description
 * __Emphasis:__ Medium emphasis – For important actions that don’t distract
 * from other onscreen elements.
 *
 * __Rationale:__ Use an outlined button for actions that need attention but
 * aren’t the primary action, such as “See all” or “Add to cart.” This is also
 * the button to use for giving someone the opportunity to change their mind or
 * escape a flow.
 *
 * __Example usages:__
 * - Reply
 * - View all
 * - Add to cart
 * - Take out of trash
 *
 * @final
 * @suppress {visibility}
 */
let MdOutlinedButton = class MdOutlinedButton extends OutlinedButton {};
MdOutlinedButton.styles = [styles$m, styles$n];
MdOutlinedButton = __decorate([t$1('md-outlined-button')], MdOutlinedButton);

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * A divider component.
 */
class Divider extends i$4 {
  constructor() {
    super(...arguments);
    /**
     * Indents the divider with equal padding on both sides.
     */
    this.inset = false;
    /**
     * Indents the divider with padding on the leading side.
     */
    this.insetStart = false;
    /**
     * Indents the divider with padding on the trailing side.
     */
    this.insetEnd = false;
  }
}
__decorate([n$5({
  type: Boolean,
  reflect: true
})], Divider.prototype, "inset", void 0);
__decorate([n$5({
  type: Boolean,
  reflect: true,
  attribute: 'inset-start'
})], Divider.prototype, "insetStart", void 0);
__decorate([n$5({
  type: Boolean,
  reflect: true,
  attribute: 'inset-end'
})], Divider.prototype, "insetEnd", void 0);

/**
 * @license
 * Copyright 2024 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Generated stylesheet for ./divider/internal/divider-styles.css.
const styles$l = i$7`:host{box-sizing:border-box;color:var(--md-divider-color, var(--md-sys-color-outline-variant, #cac4d0));display:flex;height:var(--md-divider-thickness, 1px);width:100%}:host([inset]),:host([inset-start]){padding-inline-start:16px}:host([inset]),:host([inset-end]){padding-inline-end:16px}:host::before{background:currentColor;content:"";height:100%;width:100%}@media(forced-colors: active){:host::before{background:CanvasText}}
`;

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @summary A divider is a thin line that groups content in lists and
 * containers.
 *
 * @description Dividers can reinforce tapability, such as when used to separate
 * list items or define tappable regions in an accordion.
 *
 * @final
 * @suppress {visibility}
 */
let MdDivider = class MdDivider extends Divider {};
MdDivider.styles = [styles$l];
MdDivider = __decorate([t$1('md-divider')], MdDivider);

/**
 * @license
 * Copyright 2020 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
const a = Symbol.for(""),
  o$4 = t => {
    if (t?.r === a) return t?._$litStatic$;
  },
  i$2 = (t, ...r) => ({
    _$litStatic$: r.reduce((r, e, a) => r + (t => {
      if (void 0 !== t._$litStatic$) return t._$litStatic$;
      throw Error(`Value passed to 'literal' function must be a 'literal' result: ${t}. Use 'unsafeStatic' to pass non-literal values, but\n            take care to ensure page security.`);
    })(e) + t[a + 1], t[0]),
    r: a
  }),
  l$1 = new Map(),
  n$3 = t => (r, ...e) => {
    const a = e.length;
    let s, i;
    const n = [],
      u = [];
    let c,
      $ = 0,
      f = false;
    for (; $ < a;) {
      for (c = r[$]; $ < a && void 0 !== (i = e[$], s = o$4(i));) c += s + r[++$], f = true;
      $ !== a && u.push(i), n.push(c), $++;
    }
    if ($ === a && n.push(r[a]), f) {
      const t = n.join("$$lit$$");
      void 0 === (r = l$1.get(t)) && (n.raw = n, l$1.set(t, r = n)), e = u;
    }
    return t(r, ...e);
  },
  u = n$3(b);

/**
 * @license
 * Copyright 2022 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * Returns `true` if the given element is in a right-to-left direction.
 *
 * @param el Element to determine direction from
 * @param shouldCheck Optional. If `false`, return `false` without checking
 *     direction. Determining the direction of `el` is somewhat expensive, so
 *     this parameter can be used as a conditional guard. Defaults to `true`.
 */
function isRtl(el, shouldCheck = true) {
  return shouldCheck && getComputedStyle(el).getPropertyValue('direction').trim() === 'rtl';
}

/**
 * @license
 * Copyright 2018 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Separate variable needed for closure.
const iconButtonBaseClass = mixinDelegatesAria(mixinElementInternals(i$4));
/**
 * A button for rendering icons.
 *
 * @fires input {InputEvent} Dispatched when a toggle button toggles --bubbles
 * --composed
 * @fires change {Event} Dispatched when a toggle button toggles --bubbles
 */
class IconButton extends iconButtonBaseClass {
  get name() {
    return this.getAttribute('name') ?? '';
  }
  set name(name) {
    this.setAttribute('name', name);
  }
  /**
   * The associated form element with which this element's value will submit.
   */
  get form() {
    return this[internals].form;
  }
  /**
   * The labels this element is associated with.
   */
  get labels() {
    return this[internals].labels;
  }
  constructor() {
    super();
    /**
     * Disables the icon button and makes it non-interactive.
     */
    this.disabled = false;
    /**
     * "Soft-disables" the icon button (disabled but still focusable).
     *
     * Use this when an icon button needs increased visibility when disabled. See
     * https://www.w3.org/WAI/ARIA/apg/practices/keyboard-interface/#kbd_disabled_controls
     * for more guidance on when this is needed.
     */
    this.softDisabled = false;
    /**
     * Flips the icon if it is in an RTL context at startup.
     */
    this.flipIconInRtl = false;
    /**
     * Sets the underlying `HTMLAnchorElement`'s `href` resource attribute.
     */
    this.href = '';
    /**
     * The filename to use when downloading the linked resource.
     * If not specified, the browser will determine a filename.
     * This is only applicable when the icon button is used as a link (`href` is set).
     */
    this.download = '';
    /**
     * Sets the underlying `HTMLAnchorElement`'s `target` attribute.
     */
    this.target = '';
    /**
     * The `aria-label` of the button when the button is toggleable and selected.
     */
    this.ariaLabelSelected = '';
    /**
     * When true, the button will toggle between selected and unselected
     * states
     */
    this.toggle = false;
    /**
     * Sets the selected state. When false, displays the default icon. When true,
     * displays the selected icon, or the default icon If no `slot="selected"`
     * icon is provided.
     */
    this.selected = false;
    /**
     * The default behavior of the button. May be "button", "reset", or "submit"
     * (default).
     */
    this.type = 'submit';
    /**
     * The value added to a form with the button's name when the button submits a
     * form.
     */
    this.value = '';
    this.flipIcon = isRtl(this, this.flipIconInRtl);
    {
      this.addEventListener('click', this.handleClick.bind(this));
    }
  }
  willUpdate() {
    // Link buttons cannot be disabled or soft-disabled.
    if (this.href) {
      this.disabled = false;
      this.softDisabled = false;
    }
  }
  render() {
    const tag = this.href ? i$2`div` : i$2`button`;
    // Needed for closure conformance
    const {
      ariaLabel,
      ariaHasPopup,
      ariaExpanded
    } = this;
    const hasToggledAriaLabel = ariaLabel && this.ariaLabelSelected;
    const ariaPressedValue = !this.toggle ? A : this.selected;
    let ariaLabelValue = A;
    if (!this.href) {
      ariaLabelValue = hasToggledAriaLabel && this.selected ? this.ariaLabelSelected : ariaLabel;
    }
    return u`<${tag}
        class="icon-button ${e$3(this.getRenderClasses())}"
        id="button"
        aria-label="${ariaLabelValue || A}"
        aria-haspopup="${!this.href && ariaHasPopup || A}"
        aria-expanded="${!this.href && ariaExpanded || A}"
        aria-pressed="${ariaPressedValue}"
        aria-disabled=${!this.href && this.softDisabled || A}
        ?disabled="${!this.href && this.disabled}"
        @click="${this.handleClickOnChild}">
        ${this.renderFocusRing()}
        ${this.renderRipple()}
        ${!this.selected ? this.renderIcon() : A}
        ${this.selected ? this.renderSelectedIcon() : A}
        ${this.href ? this.renderLink() : this.renderTouchTarget()}
  </${tag}>`;
  }
  renderLink() {
    // Needed for closure conformance
    const {
      ariaLabel
    } = this;
    return b`
      <a
        class="link"
        id="link"
        href="${this.href}"
        download="${this.download || A}"
        target="${this.target || A}"
        aria-label="${ariaLabel || A}">
        ${this.renderTouchTarget()}
      </a>
    `;
  }
  getRenderClasses() {
    return {
      'flip-icon': this.flipIcon,
      'selected': this.toggle && this.selected
    };
  }
  renderIcon() {
    return b`<span class="icon"><slot></slot></span>`;
  }
  renderSelectedIcon() {
    // Use default slot as fallback to not require specifying multiple icons
    return b`<span class="icon icon--selected"
      ><slot name="selected"><slot></slot></slot
    ></span>`;
  }
  renderTouchTarget() {
    return b`<span class="touch"></span>`;
  }
  renderFocusRing() {
    // TODO(b/310046938): use the same id for both elements
    return b`<md-focus-ring
      part="focus-ring"
      for=${this.href ? 'link' : 'button'}></md-focus-ring>`;
  }
  renderRipple() {
    const isRippleDisabled = !this.href && (this.disabled || this.softDisabled);
    // TODO(b/310046938): use the same id for both elements
    return b`<md-ripple
      for=${this.href ? 'link' : A}
      ?disabled="${isRippleDisabled}"></md-ripple>`;
  }
  connectedCallback() {
    this.flipIcon = isRtl(this, this.flipIconInRtl);
    super.connectedCallback();
  }
  /** Handles a click on this element. */
  handleClick(event) {
    // If the icon button is soft-disabled, we need to explicitly prevent the
    // click from propagating to other event listeners as well as prevent the
    // default action.
    if (!this.href && this.softDisabled) {
      event.stopImmediatePropagation();
      event.preventDefault();
      return;
    }
  }
  /**
   * Handles a click on the child <div> or <button> element within this
   * element's shadow DOM.
   */
  async handleClickOnChild(event) {
    // Allow the event to propagate
    await 0;
    if (!this.toggle || this.disabled || this.softDisabled || event.defaultPrevented) {
      return;
    }
    this.selected = !this.selected;
    this.dispatchEvent(new InputEvent('input', {
      bubbles: true,
      composed: true
    }));
    // Bubbles but does not compose to mimic native browser <input> & <select>
    // Additionally, native change event is not an InputEvent.
    this.dispatchEvent(new Event('change', {
      bubbles: true
    }));
  }
}
(() => {
  setupFormSubmitter(IconButton);
})();
/** @nocollapse */
IconButton.formAssociated = true;
/** @nocollapse */
IconButton.shadowRootOptions = {
  mode: 'open',
  delegatesFocus: true
};
__decorate([n$5({
  type: Boolean,
  reflect: true
})], IconButton.prototype, "disabled", void 0);
__decorate([n$5({
  type: Boolean,
  attribute: 'soft-disabled',
  reflect: true
})], IconButton.prototype, "softDisabled", void 0);
__decorate([n$5({
  type: Boolean,
  attribute: 'flip-icon-in-rtl'
})], IconButton.prototype, "flipIconInRtl", void 0);
__decorate([n$5()], IconButton.prototype, "href", void 0);
__decorate([n$5()], IconButton.prototype, "download", void 0);
__decorate([n$5()], IconButton.prototype, "target", void 0);
__decorate([n$5({
  attribute: 'aria-label-selected'
})], IconButton.prototype, "ariaLabelSelected", void 0);
__decorate([n$5({
  type: Boolean
})], IconButton.prototype, "toggle", void 0);
__decorate([n$5({
  type: Boolean,
  reflect: true
})], IconButton.prototype, "selected", void 0);
__decorate([n$5()], IconButton.prototype, "type", void 0);
__decorate([n$5({
  reflect: true
})], IconButton.prototype, "value", void 0);
__decorate([r$3()], IconButton.prototype, "flipIcon", void 0);

/**
 * @license
 * Copyright 2024 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Generated stylesheet for ./iconbutton/internal/shared-styles.css.
const styles$k = i$7`:host{display:inline-flex;outline:none;-webkit-tap-highlight-color:rgba(0,0,0,0);height:var(--_container-height);width:var(--_container-width);justify-content:center}:host([touch-target=wrapper]){margin:max(0px,(48px - var(--_container-height))/2) max(0px,(48px - var(--_container-width))/2)}md-focus-ring{--md-focus-ring-shape-start-start: var(--_container-shape-start-start);--md-focus-ring-shape-start-end: var(--_container-shape-start-end);--md-focus-ring-shape-end-end: var(--_container-shape-end-end);--md-focus-ring-shape-end-start: var(--_container-shape-end-start)}:host(:is([disabled],[soft-disabled])){pointer-events:none}.icon-button{place-items:center;background:none;border:none;box-sizing:border-box;cursor:pointer;display:flex;place-content:center;outline:none;padding:0;position:relative;text-decoration:none;user-select:none;z-index:0;flex:1;border-start-start-radius:var(--_container-shape-start-start);border-start-end-radius:var(--_container-shape-start-end);border-end-start-radius:var(--_container-shape-end-start);border-end-end-radius:var(--_container-shape-end-end)}.icon ::slotted(*){font-size:var(--_icon-size);height:var(--_icon-size);width:var(--_icon-size);font-weight:inherit}md-ripple{z-index:-1;border-start-start-radius:var(--_container-shape-start-start);border-start-end-radius:var(--_container-shape-start-end);border-end-start-radius:var(--_container-shape-end-start);border-end-end-radius:var(--_container-shape-end-end)}.flip-icon .icon{transform:scaleX(-1)}.icon{display:inline-flex}.link{display:grid;height:100%;outline:none;place-items:center;position:absolute;width:100%}.touch{position:absolute;height:max(48px,100%);width:max(48px,100%)}:host([touch-target=none]) .touch{display:none}@media(forced-colors: active){:host(:is([disabled],[soft-disabled])){--_disabled-icon-color: GrayText;--_disabled-icon-opacity: 1}}
`;

/**
 * @license
 * Copyright 2024 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Generated stylesheet for ./iconbutton/internal/standard-styles.css.
const styles$j = i$7`:host{--_disabled-icon-color: var(--md-icon-button-disabled-icon-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-icon-opacity: var(--md-icon-button-disabled-icon-opacity, 0.38);--_icon-size: var(--md-icon-button-icon-size, 24px);--_selected-focus-icon-color: var(--md-icon-button-selected-focus-icon-color, var(--md-sys-color-primary, #6750a4));--_selected-hover-icon-color: var(--md-icon-button-selected-hover-icon-color, var(--md-sys-color-primary, #6750a4));--_selected-hover-state-layer-color: var(--md-icon-button-selected-hover-state-layer-color, var(--md-sys-color-primary, #6750a4));--_selected-hover-state-layer-opacity: var(--md-icon-button-selected-hover-state-layer-opacity, 0.08);--_selected-icon-color: var(--md-icon-button-selected-icon-color, var(--md-sys-color-primary, #6750a4));--_selected-pressed-icon-color: var(--md-icon-button-selected-pressed-icon-color, var(--md-sys-color-primary, #6750a4));--_selected-pressed-state-layer-color: var(--md-icon-button-selected-pressed-state-layer-color, var(--md-sys-color-primary, #6750a4));--_selected-pressed-state-layer-opacity: var(--md-icon-button-selected-pressed-state-layer-opacity, 0.12);--_state-layer-height: var(--md-icon-button-state-layer-height, 40px);--_state-layer-shape: var(--md-icon-button-state-layer-shape, var(--md-sys-shape-corner-full, 9999px));--_state-layer-width: var(--md-icon-button-state-layer-width, 40px);--_focus-icon-color: var(--md-icon-button-focus-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_hover-icon-color: var(--md-icon-button-hover-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_hover-state-layer-color: var(--md-icon-button-hover-state-layer-color, var(--md-sys-color-on-surface-variant, #49454f));--_hover-state-layer-opacity: var(--md-icon-button-hover-state-layer-opacity, 0.08);--_icon-color: var(--md-icon-button-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_pressed-icon-color: var(--md-icon-button-pressed-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_pressed-state-layer-color: var(--md-icon-button-pressed-state-layer-color, var(--md-sys-color-on-surface-variant, #49454f));--_pressed-state-layer-opacity: var(--md-icon-button-pressed-state-layer-opacity, 0.12);--_container-shape-start-start: 0;--_container-shape-start-end: 0;--_container-shape-end-end: 0;--_container-shape-end-start: 0;--_container-height: 0;--_container-width: 0;height:var(--_state-layer-height);width:var(--_state-layer-width)}:host([touch-target=wrapper]){margin:max(0px,(48px - var(--_state-layer-height))/2) max(0px,(48px - var(--_state-layer-width))/2)}md-focus-ring{--md-focus-ring-shape-start-start: var(--_state-layer-shape);--md-focus-ring-shape-start-end: var(--_state-layer-shape);--md-focus-ring-shape-end-end: var(--_state-layer-shape);--md-focus-ring-shape-end-start: var(--_state-layer-shape)}.standard{background-color:rgba(0,0,0,0);color:var(--_icon-color);--md-ripple-hover-color: var(--_hover-state-layer-color);--md-ripple-hover-opacity: var(--_hover-state-layer-opacity);--md-ripple-pressed-color: var(--_pressed-state-layer-color);--md-ripple-pressed-opacity: var(--_pressed-state-layer-opacity)}.standard:hover{color:var(--_hover-icon-color)}.standard:focus{color:var(--_focus-icon-color)}.standard:active{color:var(--_pressed-icon-color)}.standard:is(:disabled,[aria-disabled=true]){color:var(--_disabled-icon-color)}md-ripple{border-radius:var(--_state-layer-shape)}.standard:is(:disabled,[aria-disabled=true]){opacity:var(--_disabled-icon-opacity)}.selected:not(:disabled,[aria-disabled=true]){color:var(--_selected-icon-color)}.selected:not(:disabled,[aria-disabled=true]):hover{color:var(--_selected-hover-icon-color)}.selected:not(:disabled,[aria-disabled=true]):focus{color:var(--_selected-focus-icon-color)}.selected:not(:disabled,[aria-disabled=true]):active{color:var(--_selected-pressed-icon-color)}.selected{--md-ripple-hover-color: var(--_selected-hover-state-layer-color);--md-ripple-hover-opacity: var(--_selected-hover-state-layer-opacity);--md-ripple-pressed-color: var(--_selected-pressed-state-layer-color);--md-ripple-pressed-opacity: var(--_selected-pressed-state-layer-opacity)}
`;

/**
 * @license
 * Copyright 2021 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @summary Icon buttons help people take supplementary actions with a single
 * tap.
 *
 * @description
 * __Emphasis:__ Low emphasis – For optional or supplementary actions with the
 * least amount of prominence.
 *
 * __Rationale:__ The most compact and unobtrusive type of button, icon buttons
 * are used for optional supplementary actions such as "Bookmark" or "Star."
 *
 * __Example usages:__
 * - Add to Favorites
 * - Print
 *
 * @final
 * @suppress {visibility}
 */
let MdIconButton = class MdIconButton extends IconButton {
  getRenderClasses() {
    return {
      ...super.getRenderClasses(),
      'standard': true
    };
  }
};
MdIconButton.styles = [styles$k, styles$j];
MdIconButton = __decorate([t$1('md-icon-button')], MdIconButton);

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * Activates the first non-disabled item of a given array of items.
 *
 * @param items {Array<ListItem>} The items from which to activate the
 *     first item.
 * @param isActivatable Function to determine if an item can be  activated.
 *     Defaults to non-disabled items.
 */
function activateFirstItem(items, isActivatable = isItemNotDisabled) {
  // NOTE: These selector functions are static and not on the instance such
  // that multiple operations can be chained and we do not have to re-query
  // the DOM
  const firstItem = getFirstActivatableItem(items, isActivatable);
  if (firstItem) {
    firstItem.tabIndex = 0;
    firstItem.focus();
  }
  return firstItem;
}
/**
 * Activates the last non-disabled item of a given array of items.
 *
 * @param items {Array<ListItem>} The items from which to activate the
 *     last item.
 * @param isActivatable Function to determine if an item can be  activated.
 *     Defaults to non-disabled items.
 * @nocollapse
 */
function activateLastItem(items, isActivatable = isItemNotDisabled) {
  const lastItem = getLastActivatableItem(items, isActivatable);
  if (lastItem) {
    lastItem.tabIndex = 0;
    lastItem.focus();
  }
  return lastItem;
}
/**
 * Retrieves the first activated item of a given array of items.
 *
 * @param items {Array<ListItem>} The items to search.
 * @param isActivatable Function to determine if an item can be  activated.
 *     Defaults to non-disabled items.
 * @return A record of the first activated item including the item and the
 *     index of the item or `null` if none are activated.
 * @nocollapse
 */
function getActiveItem(items, isActivatable = isItemNotDisabled) {
  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    if (item.tabIndex === 0 && isActivatable(item)) {
      return {
        item,
        index: i
      };
    }
  }
  return null;
}
/**
 * Retrieves the first non-disabled item of a given array of items. This
 * the first item that is not disabled.
 *
 * @param items {Array<ListItem>} The items to search.
 * @param isActivatable Function to determine if an item can be  activated.
 *     Defaults to non-disabled items.
 * @return The first activatable item or `null` if none are activatable.
 * @nocollapse
 */
function getFirstActivatableItem(items, isActivatable = isItemNotDisabled) {
  for (const item of items) {
    if (isActivatable(item)) {
      return item;
    }
  }
  return null;
}
/**
 * Retrieves the last non-disabled item of a given array of items.
 *
 * @param items {Array<ListItem>} The items to search.
 * @param isActivatable Function to determine if an item can be  activated.
 *     Defaults to non-disabled items.
 * @return The last activatable item or `null` if none are activatable.
 * @nocollapse
 */
function getLastActivatableItem(items, isActivatable = isItemNotDisabled) {
  for (let i = items.length - 1; i >= 0; i--) {
    const item = items[i];
    if (isActivatable(item)) {
      return item;
    }
  }
  return null;
}
/**
 * Retrieves the next non-disabled item of a given array of items.
 *
 * @param items {Array<ListItem>} The items to search.
 * @param index {{index: number}} The index to search from.
 * @param isActivatable Function to determine if an item can be  activated.
 *     Defaults to non-disabled items.
 * @param wrap If true, then the next item at the end of the list is the first
 *     item. Defaults to true.
 * @return The next activatable item or `null` if none are activatable.
 */
function getNextItem(items, index, isActivatable = isItemNotDisabled, wrap = true) {
  for (let i = 1; i < items.length; i++) {
    const nextIndex = (i + index) % items.length;
    if (nextIndex < index && !wrap) {
      // Return if the index loops back to the beginning and not wrapping.
      return null;
    }
    const item = items[nextIndex];
    if (isActivatable(item)) {
      return item;
    }
  }
  return items[index] ? items[index] : null;
}
/**
 * Retrieves the previous non-disabled item of a given array of items.
 *
 * @param items {Array<ListItem>} The items to search.
 * @param index {{index: number}} The index to search from.
 * @param isActivatable Function to determine if an item can be  activated.
 *     Defaults to non-disabled items.
 * @param wrap If true, then the previous item at the beginning of the list is
 *     the last item. Defaults to true.
 * @return The previous activatable item or `null` if none are activatable.
 */
function getPrevItem(items, index, isActivatable = isItemNotDisabled, wrap = true) {
  for (let i = 1; i < items.length; i++) {
    const prevIndex = (index - i + items.length) % items.length;
    if (prevIndex > index && !wrap) {
      // Return if the index loops back to the end and not wrapping.
      return null;
    }
    const item = items[prevIndex];
    if (isActivatable(item)) {
      return item;
    }
  }
  return items[index] ? items[index] : null;
}
/**
 * Activates the next item and focuses it. If nothing is currently activated,
 * activates the first item.
 */
function activateNextItem(items, activeItemRecord, isActivatable = isItemNotDisabled, wrap = true) {
  if (activeItemRecord) {
    const next = getNextItem(items, activeItemRecord.index, isActivatable, wrap);
    if (next) {
      next.tabIndex = 0;
      next.focus();
    }
    return next;
  } else {
    return activateFirstItem(items, isActivatable);
  }
}
/**
 * Activates the previous item and focuses it. If nothing is currently
 * activated, activates the last item.
 */
function activatePreviousItem(items, activeItemRecord, isActivatable = isItemNotDisabled, wrap = true) {
  if (activeItemRecord) {
    const prev = getPrevItem(items, activeItemRecord.index, isActivatable, wrap);
    if (prev) {
      prev.tabIndex = 0;
      prev.focus();
    }
    return prev;
  } else {
    return activateLastItem(items, isActivatable);
  }
}
/**
 * Creates an event that requests the menu to set `tabindex=0` on the item and
 * focus it. We use this pattern because List keeps track of what element is
 * active in the List by maintaining tabindex. We do not want list items
 * to set tabindex on themselves or focus themselves so that we can organize all
 * that logic in the parent List and Menus, and list item stays as dumb as
 * possible.
 */
function createRequestActivationEvent() {
  return new Event('request-activation', {
    bubbles: true,
    composed: true
  });
}
/**
 * The default `isActivatable` function, which checks if an item is not
 * disabled.
 *
 * @param item The item to check.
 * @return true if `item.disabled` is `false.
 */
function isItemNotDisabled(item) {
  return !item.disabled;
}

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// TODO: move this file to List and make List use this
/**
 * Default keys that trigger navigation.
 */
// tslint:disable:enforce-name-casing Following Enum style
const NavigableKeys = {
  ArrowDown: 'ArrowDown',
  ArrowLeft: 'ArrowLeft',
  ArrowUp: 'ArrowUp',
  ArrowRight: 'ArrowRight',
  Home: 'Home',
  End: 'End'
};
/**
 * A controller that handles list keyboard navigation and item management.
 */
class ListController {
  constructor(config) {
    /**
     * Handles keyboard navigation. Should be bound to the node that will act as
     * the List.
     */
    this.handleKeydown = event => {
      const key = event.key;
      if (event.defaultPrevented || !this.isNavigableKey(key)) {
        return;
      }
      // do not use this.items directly in upcoming calculations so we don't
      // re-query the DOM unnecessarily
      const items = this.items;
      if (!items.length) {
        return;
      }
      const activeItemRecord = getActiveItem(items, this.isActivatable);
      event.preventDefault();
      const isRtl = this.isRtl();
      const inlinePrevious = isRtl ? NavigableKeys.ArrowRight : NavigableKeys.ArrowLeft;
      const inlineNext = isRtl ? NavigableKeys.ArrowLeft : NavigableKeys.ArrowRight;
      let nextActiveItem = null;
      switch (key) {
        // Activate the next item
        case NavigableKeys.ArrowDown:
        case inlineNext:
          nextActiveItem = activateNextItem(items, activeItemRecord, this.isActivatable, this.wrapNavigation());
          break;
        // Activate the previous item
        case NavigableKeys.ArrowUp:
        case inlinePrevious:
          nextActiveItem = activatePreviousItem(items, activeItemRecord, this.isActivatable, this.wrapNavigation());
          break;
        // Activate the first item
        case NavigableKeys.Home:
          nextActiveItem = activateFirstItem(items, this.isActivatable);
          break;
        // Activate the last item
        case NavigableKeys.End:
          nextActiveItem = activateLastItem(items, this.isActivatable);
          break;
      }
      if (nextActiveItem && activeItemRecord && activeItemRecord.item !== nextActiveItem) {
        // If a new item was activated, remove the tabindex of the previous
        // activated item.
        activeItemRecord.item.tabIndex = -1;
      }
    };
    /**
     * Listener to be bound to the `deactivate-items` item event.
     */
    this.onDeactivateItems = () => {
      const items = this.items;
      for (const item of items) {
        this.deactivateItem(item);
      }
    };
    /**
     * Listener to be bound to the `request-activation` item event..
     */
    this.onRequestActivation = event => {
      this.onDeactivateItems();
      const target = event.target;
      this.activateItem(target);
      target.focus();
    };
    /**
     * Listener to be bound to the `slotchange` event for the slot that renders
     * the items.
     */
    this.onSlotchange = () => {
      const items = this.items;
      // Whether we have encountered an item that has been activated
      let encounteredActivated = false;
      for (const item of items) {
        const isActivated = !item.disabled && item.tabIndex > -1;
        if (isActivated && !encounteredActivated) {
          encounteredActivated = true;
          item.tabIndex = 0;
          continue;
        }
        // Deactivate the rest including disabled
        item.tabIndex = -1;
      }
      if (encounteredActivated) {
        return;
      }
      const firstActivatableItem = getFirstActivatableItem(items, this.isActivatable);
      if (!firstActivatableItem) {
        return;
      }
      firstActivatableItem.tabIndex = 0;
    };
    const {
      isItem,
      getPossibleItems,
      isRtl,
      deactivateItem,
      activateItem,
      isNavigableKey,
      isActivatable,
      wrapNavigation
    } = config;
    this.isItem = isItem;
    this.getPossibleItems = getPossibleItems;
    this.isRtl = isRtl;
    this.deactivateItem = deactivateItem;
    this.activateItem = activateItem;
    this.isNavigableKey = isNavigableKey;
    this.isActivatable = isActivatable;
    this.wrapNavigation = wrapNavigation ?? (() => true);
  }
  /**
   * The items being managed by the list. Additionally, attempts to see if the
   * object has a sub-item in the `.item` property.
   */
  get items() {
    const maybeItems = this.getPossibleItems();
    const items = [];
    for (const itemOrParent of maybeItems) {
      const isItem = this.isItem(itemOrParent);
      // if the item is a list item, add it to the list of items
      if (isItem) {
        items.push(itemOrParent);
        continue;
      }
      // If the item exposes an `item` property check if it is a list item.
      const subItem = itemOrParent.item;
      if (subItem && this.isItem(subItem)) {
        items.push(subItem);
      }
    }
    return items;
  }
  /**
   * Activates the next item in the list. If at the end of the list, the first
   * item will be activated.
   *
   * @return The activated list item or `null` if there are no items.
   */
  activateNextItem() {
    const items = this.items;
    const activeItemRecord = getActiveItem(items, this.isActivatable);
    if (activeItemRecord) {
      activeItemRecord.item.tabIndex = -1;
    }
    return activateNextItem(items, activeItemRecord, this.isActivatable, this.wrapNavigation());
  }
  /**
   * Activates the previous item in the list. If at the start of the list, the
   * last item will be activated.
   *
   * @return The activated list item or `null` if there are no items.
   */
  activatePreviousItem() {
    const items = this.items;
    const activeItemRecord = getActiveItem(items, this.isActivatable);
    if (activeItemRecord) {
      activeItemRecord.item.tabIndex = -1;
    }
    return activatePreviousItem(items, activeItemRecord, this.isActivatable, this.wrapNavigation());
  }
}

/**
 * @license
 * Copyright 2021 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
const NAVIGABLE_KEY_SET = new Set(Object.values(NavigableKeys));
// tslint:disable-next-line:enforce-comments-on-exported-symbols
class List extends i$4 {
  /** @export */
  get items() {
    return this.listController.items;
  }
  constructor() {
    super();
    this.listController = new ListController({
      isItem: item => item.hasAttribute('md-list-item'),
      getPossibleItems: () => this.slotItems,
      isRtl: () => getComputedStyle(this).direction === 'rtl',
      deactivateItem: item => {
        item.tabIndex = -1;
      },
      activateItem: item => {
        item.tabIndex = 0;
      },
      isNavigableKey: key => NAVIGABLE_KEY_SET.has(key),
      isActivatable: item => !item.disabled && item.type !== 'text'
    });
    this.internals =
    // Cast needed for closure
    this.attachInternals();
    {
      this.internals.role = 'list';
      this.addEventListener('keydown', this.listController.handleKeydown);
    }
  }
  render() {
    return b`
      <slot
        @deactivate-items=${this.listController.onDeactivateItems}
        @request-activation=${this.listController.onRequestActivation}
        @slotchange=${this.listController.onSlotchange}>
      </slot>
    `;
  }
  /**
   * Activates the next item in the list. If at the end of the list, the first
   * item will be activated.
   *
   * @return The activated list item or `null` if there are no items.
   */
  activateNextItem() {
    return this.listController.activateNextItem();
  }
  /**
   * Activates the previous item in the list. If at the start of the list, the
   * last item will be activated.
   *
   * @return The activated list item or `null` if there are no items.
   */
  activatePreviousItem() {
    return this.listController.activatePreviousItem();
  }
}
__decorate([o$5({
  flatten: true
})], List.prototype, "slotItems", void 0);

/**
 * @license
 * Copyright 2024 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Generated stylesheet for ./list/internal/list-styles.css.
const styles$i = i$7`:host{background:var(--md-list-container-color, var(--md-sys-color-surface, #fef7ff));color:unset;display:flex;flex-direction:column;outline:none;padding:8px 0;position:relative}
`;

/**
 * @license
 * Copyright 2021 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @summary Lists are continuous, vertical indexes of text or images.
 *
 * @description
 * Lists consist of one or more list items, and can contain actions represented
 * by icons and text. List items come in three sizes: one-line, two-line, and
 * three-line.
 *
 * __Takeaways:__
 *
 * - Lists should be sorted in logical ways that make content easy to scan, such
 *   as alphabetical, numerical, chronological, or by user preference.
 * - Lists present content in a way that makes it easy to identify a specific
 *   item in a collection and act on it.
 * - Lists should present icons, text, and actions in a consistent format.
 *
 * @final
 * @suppress {visibility}
 */
let MdList = class MdList extends List {};
MdList.styles = [styles$i];
MdList = __decorate([t$1('md-list')], MdList);

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * An item layout component.
 */
class Item extends i$4 {
  constructor() {
    super(...arguments);
    /**
     * Only needed for SSR.
     *
     * Add this attribute when an item has two lines to avoid a Flash Of Unstyled
     * Content. This attribute is not needed for single line items or items with
     * three or more lines.
     */
    this.multiline = false;
  }
  render() {
    return b`
      <slot name="container"></slot>
      <slot class="non-text" name="start"></slot>
      <div class="text">
        <slot name="overline" @slotchange=${this.handleTextSlotChange}></slot>
        <slot
          class="default-slot"
          @slotchange=${this.handleTextSlotChange}></slot>
        <slot name="headline" @slotchange=${this.handleTextSlotChange}></slot>
        <slot
          name="supporting-text"
          @slotchange=${this.handleTextSlotChange}></slot>
      </div>
      <slot class="non-text" name="trailing-supporting-text"></slot>
      <slot class="non-text" name="end"></slot>
    `;
  }
  handleTextSlotChange() {
    // Check if there's more than one text slot with content. If so, the item is
    // multiline, which has a different min-height than single line items.
    let isMultiline = false;
    let slotsWithContent = 0;
    for (const slot of this.textSlots) {
      if (slotHasContent(slot)) {
        slotsWithContent += 1;
      }
      if (slotsWithContent > 1) {
        isMultiline = true;
        break;
      }
    }
    this.multiline = isMultiline;
  }
}
__decorate([n$5({
  type: Boolean,
  reflect: true
})], Item.prototype, "multiline", void 0);
__decorate([r$2('.text slot')], Item.prototype, "textSlots", void 0);
function slotHasContent(slot) {
  for (const node of slot.assignedNodes({
    flatten: true
  })) {
    // Assume there's content if there's an element slotted in
    const isElement = node.nodeType === Node.ELEMENT_NODE;
    // If there's only text nodes for the default slot, check if there's
    // non-whitespace.
    const isTextWithContent = node.nodeType === Node.TEXT_NODE && node.textContent?.match(/\S/);
    if (isElement || isTextWithContent) {
      return true;
    }
  }
  return false;
}

/**
 * @license
 * Copyright 2024 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Generated stylesheet for ./labs/item/internal/item-styles.css.
const styles$h = i$7`:host{color:var(--md-sys-color-on-surface, #1d1b20);font-family:var(--md-sys-typescale-body-large-font, var(--md-ref-typeface-plain, Roboto));font-size:var(--md-sys-typescale-body-large-size, 1rem);font-weight:var(--md-sys-typescale-body-large-weight, var(--md-ref-typeface-weight-regular, 400));line-height:var(--md-sys-typescale-body-large-line-height, 1.5rem);align-items:center;box-sizing:border-box;display:flex;gap:16px;min-height:56px;overflow:hidden;padding:12px 16px;position:relative;text-overflow:ellipsis}:host([multiline]){min-height:72px}[name=overline]{color:var(--md-sys-color-on-surface-variant, #49454f);font-family:var(--md-sys-typescale-label-small-font, var(--md-ref-typeface-plain, Roboto));font-size:var(--md-sys-typescale-label-small-size, 0.6875rem);font-weight:var(--md-sys-typescale-label-small-weight, var(--md-ref-typeface-weight-medium, 500));line-height:var(--md-sys-typescale-label-small-line-height, 1rem)}[name=supporting-text]{color:var(--md-sys-color-on-surface-variant, #49454f);font-family:var(--md-sys-typescale-body-medium-font, var(--md-ref-typeface-plain, Roboto));font-size:var(--md-sys-typescale-body-medium-size, 0.875rem);font-weight:var(--md-sys-typescale-body-medium-weight, var(--md-ref-typeface-weight-regular, 400));line-height:var(--md-sys-typescale-body-medium-line-height, 1.25rem)}[name=trailing-supporting-text]{color:var(--md-sys-color-on-surface-variant, #49454f);font-family:var(--md-sys-typescale-label-small-font, var(--md-ref-typeface-plain, Roboto));font-size:var(--md-sys-typescale-label-small-size, 0.6875rem);font-weight:var(--md-sys-typescale-label-small-weight, var(--md-ref-typeface-weight-medium, 500));line-height:var(--md-sys-typescale-label-small-line-height, 1rem)}[name=container]::slotted(*){inset:0;position:absolute}.default-slot{display:inline}.default-slot,.text ::slotted(*){overflow:hidden;text-overflow:ellipsis}.text{display:flex;flex:1;flex-direction:column;overflow:hidden}
`;

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * An item layout component that can be used inside list items to give them
 * their customizable structure.
 *
 * `<md-item>` does not have any functionality, which must be added by the
 * component using it.
 *
 * All text will wrap unless `white-space: nowrap` is set on the item or any of
 * its children.
 *
 * Slots available:
 * - `<default>`: The headline, or custom content.
 * - `headline`: The first line.
 * - `supporting-text`: Supporting text lines underneath the headline.
 * - `trailing-supporting-text`: A small text snippet at the end of the item.
 * - `start`: Any leading content, such as icons, avatars, or checkboxes.
 * - `end`: Any trailing content, such as icons and buttons.
 * - `container`: Background container content, intended for adding additional
 *     styles, such as ripples or focus rings.
 *
 * @example
 * ```html
 * <md-item>Single line</md-item>
 *
 * <md-item>
 *   <div class="custom-content">...</div>
 * </md-item>
 *
 * <!-- Classic 1 to 3+ line list items -->
 * <md-item>
 *   <md-icon slot="start">image</md-icon>
 *   <div slot="overline">Overline</div>
 *   <div slot="headline">Headline</div>
 *   <div="supporting-text">Supporting text</div>
 *   <div="trailing-supporting-text">Trailing</div>
 *   <md-icon slot="end">image</md-icon>
 * </md-item>
 * ```
 *
 * When wrapping `<md-item>`, forward the available slots to use the same slot
 * structure for the wrapping component (this is what `<md-list-item>` does).
 *
 * @example
 * ```html
 * <md-item>
 *   <slot></slot>
 *   <slot name="overline" slot="overline"></slot>
 *   <slot name="headline" slot="headline"></slot>
 *   <slot name="supporting-text" slot="supporting-text"></slot>
 *   <slot name="trailing-supporting-text"
 *       slot="trailing-supporting-text"></slot>
 *   <slot name="start" slot="start"></slot>
 *   <slot name="end" slot="end"></slot>
 * </md-item>
 * ```
 *
 * @final
 * @suppress {visibility}
 */
let MdItem = class MdItem extends Item {};
MdItem.styles = [styles$h];
MdItem = __decorate([t$1('md-item')], MdItem);

/**
 * @license
 * Copyright 2022 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Separate variable needed for closure.
const listItemBaseClass = mixinDelegatesAria(i$4);
/**
 * @fires request-activation {Event} Requests the list to set `tabindex=0` on
 * the item and focus it. --bubbles --composed
 */
class ListItemEl extends listItemBaseClass {
  constructor() {
    super(...arguments);
    /**
     * Disables the item and makes it non-selectable and non-interactive.
     */
    this.disabled = false;
    /**
     * Sets the behavior of the list item, defaults to "text". Change to "link" or
     * "button" for interactive items.
     */
    this.type = 'text';
    /**
     * READONLY. Sets the `md-list-item` attribute on the element.
     */
    this.isListItem = true;
    /**
     * Sets the underlying `HTMLAnchorElement`'s `href` resource attribute.
     */
    this.href = '';
    /**
     * Sets the underlying `HTMLAnchorElement`'s `target` attribute when `href` is
     * set.
     */
    this.target = '';
  }
  get isDisabled() {
    return this.disabled && this.type !== 'link';
  }
  willUpdate(changed) {
    if (this.href) {
      this.type = 'link';
    }
    super.willUpdate(changed);
  }
  render() {
    return this.renderListItem(b`
      <md-item>
        <div slot="container">
          ${this.renderRipple()} ${this.renderFocusRing()}
        </div>
        <slot name="start" slot="start"></slot>
        <slot name="end" slot="end"></slot>
        ${this.renderBody()}
      </md-item>
    `);
  }
  /**
   * Renders the root list item.
   *
   * @param content the child content of the list item.
   */
  renderListItem(content) {
    const isAnchor = this.type === 'link';
    let tag;
    switch (this.type) {
      case 'link':
        tag = i$2`a`;
        break;
      case 'button':
        tag = i$2`button`;
        break;
      default:
      case 'text':
        tag = i$2`li`;
        break;
    }
    const isInteractive = this.type !== 'text';
    // TODO(b/265339866): announce "button"/"link" inside of a list item. Until
    // then all are "listitem" roles for correct announcement.
    const target = isAnchor && !!this.target ? this.target : A;
    return u`
      <${tag}
        id="item"
        tabindex="${this.isDisabled || !isInteractive ? -1 : 0}"
        ?disabled=${this.isDisabled}
        role="listitem"
        aria-selected=${this.ariaSelected || A}
        aria-checked=${this.ariaChecked || A}
        aria-expanded=${this.ariaExpanded || A}
        aria-haspopup=${this.ariaHasPopup || A}
        class="list-item ${e$3(this.getRenderClasses())}"
        href=${this.href || A}
        target=${target}
        @focus=${this.onFocus}
      >${content}</${tag}>
    `;
  }
  /**
   * Handles rendering of the ripple element.
   */
  renderRipple() {
    if (this.type === 'text') {
      return A;
    }
    return b` <md-ripple
      part="ripple"
      for="item"
      ?disabled=${this.isDisabled}></md-ripple>`;
  }
  /**
   * Handles rendering of the focus ring.
   */
  renderFocusRing() {
    if (this.type === 'text') {
      return A;
    }
    return b` <md-focus-ring
      @visibility-changed=${this.onFocusRingVisibilityChanged}
      part="focus-ring"
      for="item"
      inward></md-focus-ring>`;
  }
  onFocusRingVisibilityChanged(e) {}
  /**
   * Classes applied to the list item root.
   */
  getRenderClasses() {
    return {
      'disabled': this.isDisabled
    };
  }
  /**
   * Handles rendering the headline and supporting text.
   */
  renderBody() {
    return b`
      <slot></slot>
      <slot name="overline" slot="overline"></slot>
      <slot name="headline" slot="headline"></slot>
      <slot name="supporting-text" slot="supporting-text"></slot>
      <slot
        name="trailing-supporting-text"
        slot="trailing-supporting-text"></slot>
    `;
  }
  onFocus() {
    if (this.tabIndex !== -1) {
      return;
    }
    // Handles the case where the user clicks on the element and then tabs.
    this.dispatchEvent(createRequestActivationEvent());
  }
  focus() {
    // TODO(b/300334509): needed for some cases where delegatesFocus doesn't
    // work programmatically like in FF and select-option
    this.listItemRoot?.focus();
  }
  click() {
    if (!this.listItemRoot) {
      // If the element has not finished rendering, call super to ensure click
      // events are dispatched.
      super.click();
      return;
    }
    // Forward click to the element to ensure link <a>.click() works correctly.
    this.listItemRoot.click();
  }
}
/** @nocollapse */
ListItemEl.shadowRootOptions = {
  ...i$4.shadowRootOptions,
  delegatesFocus: true
};
__decorate([n$5({
  type: Boolean,
  reflect: true
})], ListItemEl.prototype, "disabled", void 0);
__decorate([n$5({
  reflect: true
})], ListItemEl.prototype, "type", void 0);
__decorate([n$5({
  type: Boolean,
  attribute: 'md-list-item',
  reflect: true
})], ListItemEl.prototype, "isListItem", void 0);
__decorate([n$5()], ListItemEl.prototype, "href", void 0);
__decorate([n$5()], ListItemEl.prototype, "target", void 0);
__decorate([e$6('.list-item')], ListItemEl.prototype, "listItemRoot", void 0);

/**
 * @license
 * Copyright 2024 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Generated stylesheet for ./list/internal/listitem/list-item-styles.css.
const styles$g = i$7`:host{display:flex;-webkit-tap-highlight-color:rgba(0,0,0,0);--md-ripple-hover-color: var(--md-list-item-hover-state-layer-color, var(--md-sys-color-on-surface, #1d1b20));--md-ripple-hover-opacity: var(--md-list-item-hover-state-layer-opacity, 0.08);--md-ripple-pressed-color: var(--md-list-item-pressed-state-layer-color, var(--md-sys-color-on-surface, #1d1b20));--md-ripple-pressed-opacity: var(--md-list-item-pressed-state-layer-opacity, 0.12)}:host(:is([type=button]:not([disabled]),[type=link])){cursor:pointer}md-focus-ring{z-index:1;--md-focus-ring-shape: 8px}a,button,li{background:none;border:none;cursor:inherit;padding:0;margin:0;text-align:unset;text-decoration:none}.list-item{border-radius:inherit;display:flex;flex:1;max-width:inherit;min-width:inherit;outline:none;-webkit-tap-highlight-color:rgba(0,0,0,0);width:100%}.list-item.interactive{cursor:pointer}.list-item.disabled{opacity:var(--md-list-item-disabled-opacity, 0.3);pointer-events:none}[slot=container]{pointer-events:none}md-ripple{border-radius:inherit}md-item{border-radius:inherit;flex:1;height:100%;color:var(--md-list-item-label-text-color, var(--md-sys-color-on-surface, #1d1b20));font-family:var(--md-list-item-label-text-font, var(--md-sys-typescale-body-large-font, var(--md-ref-typeface-plain, Roboto)));font-size:var(--md-list-item-label-text-size, var(--md-sys-typescale-body-large-size, 1rem));line-height:var(--md-list-item-label-text-line-height, var(--md-sys-typescale-body-large-line-height, 1.5rem));font-weight:var(--md-list-item-label-text-weight, var(--md-sys-typescale-body-large-weight, var(--md-ref-typeface-weight-regular, 400)));min-height:var(--md-list-item-one-line-container-height, 56px);padding-top:var(--md-list-item-top-space, 12px);padding-bottom:var(--md-list-item-bottom-space, 12px);padding-inline-start:var(--md-list-item-leading-space, 16px);padding-inline-end:var(--md-list-item-trailing-space, 16px)}md-item[multiline]{min-height:var(--md-list-item-two-line-container-height, 72px)}[slot=supporting-text]{color:var(--md-list-item-supporting-text-color, var(--md-sys-color-on-surface-variant, #49454f));font-family:var(--md-list-item-supporting-text-font, var(--md-sys-typescale-body-medium-font, var(--md-ref-typeface-plain, Roboto)));font-size:var(--md-list-item-supporting-text-size, var(--md-sys-typescale-body-medium-size, 0.875rem));line-height:var(--md-list-item-supporting-text-line-height, var(--md-sys-typescale-body-medium-line-height, 1.25rem));font-weight:var(--md-list-item-supporting-text-weight, var(--md-sys-typescale-body-medium-weight, var(--md-ref-typeface-weight-regular, 400)))}[slot=trailing-supporting-text]{color:var(--md-list-item-trailing-supporting-text-color, var(--md-sys-color-on-surface-variant, #49454f));font-family:var(--md-list-item-trailing-supporting-text-font, var(--md-sys-typescale-label-small-font, var(--md-ref-typeface-plain, Roboto)));font-size:var(--md-list-item-trailing-supporting-text-size, var(--md-sys-typescale-label-small-size, 0.6875rem));line-height:var(--md-list-item-trailing-supporting-text-line-height, var(--md-sys-typescale-label-small-line-height, 1rem));font-weight:var(--md-list-item-trailing-supporting-text-weight, var(--md-sys-typescale-label-small-weight, var(--md-ref-typeface-weight-medium, 500)))}:is([slot=start],[slot=end])::slotted(*){fill:currentColor}[slot=start]{color:var(--md-list-item-leading-icon-color, var(--md-sys-color-on-surface-variant, #49454f))}[slot=end]{color:var(--md-list-item-trailing-icon-color, var(--md-sys-color-on-surface-variant, #49454f))}@media(forced-colors: active){.disabled slot{color:GrayText}.list-item.disabled{color:GrayText;opacity:1}}
`;

/**
 * @license
 * Copyright 2022 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @summary
 * Lists are continuous, vertical indexes of text or images. Items are placed
 * inside the list.
 *
 * @description
 * Lists consist of one or more list items, and can contain actions represented
 * by icons and text. List items come in three sizes: one-line, two-line, and
 * three-line.
 *
 * __Takeaways:__
 *
 * - Lists should be sorted in logical ways that make content easy to scan, such
 *   as alphabetical, numerical, chronological, or by user preference.
 * - Lists present content in a way that makes it easy to identify a specific
 *   item in a collection and act on it.
 * - Lists should present icons, text, and actions in a consistent format.
 *
 * Acceptable slot child variants are:
 *
 * - `img[slot=end]`
 * - `img[slot=start]`
 *
 *  @example
 * ```html
 * <md-list-item
 *     headline="User Name"
 *     supportingText="user@name.com">
 *   <md-icon slot="start">account_circle</md-icon>
 *   <md-icon slot="end">check</md-icon>
 * </md-list-item>
 * ```
 *
 * @example
 *
 * @final
 * @suppress {visibility}
 */
let MdListItem = class MdListItem extends ListItemEl {};
MdListItem.styles = [styles$g];
MdListItem = __decorate([t$1('md-list-item')], MdListItem);

/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
const showSettingsDialog = async section => {
  await import('./settings-dialog-DH4tozUK.js');
  const dialog = document.createElement("settings-dialog");
  if (section) dialog.scrollToSection = section;
  document.querySelector("matter-dashboard-app")?.renderRoot.appendChild(dialog);
};

var showSettingsDialog$1 = /*#__PURE__*/Object.freeze({
  __proto__: null,
  showSettingsDialog: showSettingsDialog
});

/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
const URL_PARAM = "dev";
class DevModeServiceImpl {
  constructor() {
    this._listeners = /* @__PURE__ */new Set();
  }
  get active() {
    const value = new URLSearchParams(window.location.search).get(URL_PARAM);
    return value !== null && value !== "";
  }
  setActive(on) {
    const url = new URL(window.location.href);
    if (on) {
      url.searchParams.set(URL_PARAM, "on");
    } else {
      url.searchParams.delete(URL_PARAM);
    }
    history.replaceState(null, "", url.toString());
    const active = this.active;
    this._listeners.forEach(cb => cb(active));
  }
  subscribe(callback) {
    this._listeners.add(callback);
    return () => {
      this._listeners.delete(callback);
    };
  }
}
const DevModeService = new DevModeServiceImpl();

/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
const cssVarCache = /* @__PURE__ */new Map();
ThemeService.subscribe(() => cssVarCache.clear());
function getCssVar(name, fallback = "") {
  let value = cssVarCache.get(name);
  if (value === void 0) {
    value = getComputedStyle(document.body).getPropertyValue(name).trim();
    cssVarCache.set(name, value);
  }
  return value || fallback;
}
const reducedMotionStyles = i$7`
    @media (prefers-reduced-motion: reduce) {
        *,
        *::before,
        *::after {
            animation-duration: 0.01ms !important;
            animation-iteration-count: 1 !important;
            transition-duration: 0.01ms !important;
        }
    }
`;
const notFoundStyles = i$7`
    .not-found {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 48px 16px;
        gap: 16px;
        color: var(--md-sys-color-on-surface-variant);
    }

    .not-found ha-svg-icon {
        --icon-primary-color: var(--md-sys-color-error);
        width: 48px;
        height: 48px;
    }

    .not-found p {
        margin: 0;
        font-size: 1.1rem;
    }
`;

var __defProp$n = Object.defineProperty;
var __getOwnPropDesc$o = Object.getOwnPropertyDescriptor;
var __decorateClass$q = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$o(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp$n(target, key, result);
  return result;
};
let DashboardHeader = class extends i$4 {
  constructor() {
    super(...arguments);
    this._tick = 0;
    this._themePreference = ThemeService.preference;
    this._effectiveTheme = ThemeService.effectiveTheme;
    this._devMode = DevModeService.active;
  }
  connectedCallback() {
    super.connectedCallback();
    this._unsubscribeTheme = ThemeService.subscribe(theme => {
      this._effectiveTheme = theme;
      this._themePreference = ThemeService.preference;
    });
    this._unsubscribeDevMode = DevModeService.subscribe(active => {
      this._devMode = active;
    });
  }
  disconnectedCallback() {
    super.disconnectedCallback();
    this._unsubscribeTheme?.();
    this._unsubscribeDevMode?.();
  }
  _goBack() {
    if (this.backButton) {
      location.hash = this.backButton;
    }
  }
  _goHome() {
    location.hash = "#";
  }
  _cycleTheme() {
    ThemeService.cycleTheme();
  }
  _openSettings() {
    showSettingsDialog();
  }
  _getThemeIcon() {
    switch (this._themePreference) {
      case "light":
        return mdiWeatherSunny;
      case "dark":
        return mdiWeatherNight;
      case "system":
        return mdiBrightnessAuto;
    }
  }
  _getThemeTooltip() {
    switch (this._themePreference) {
      case "light":
        return "Theme: Light";
      case "dark":
        return "Theme: Dark";
      case "system":
        return `Theme: System (${this._effectiveTheme})`;
    }
  }
  _renderNavTabs() {
    if (this.activeView === void 0) {
      return A;
    }
    const showThreadTab = this.hasThreadDevices === true;
    const showWifiTab = this.hasWifiDevices === true;
    if (!showThreadTab && !showWifiTab) {
      return A;
    }
    return b`
            <nav class="nav-tabs" aria-label="View navigation">
                <a
                    href="#nodes"
                    class="nav-tab ${this.activeView === "nodes" ? "active" : ""}"
                    aria-current=${this.activeView === "nodes" ? "page" : A}
                    >Nodes</a
                >
                ${showThreadTab ? b`<a
                          href="#thread"
                          class="nav-tab ${this.activeView === "thread" ? "active" : ""}"
                          aria-current=${this.activeView === "thread" ? "page" : A}
                          >Thread</a
                      >` : A}
                ${showWifiTab ? b`<a
                          href="#wifi"
                          class="nav-tab ${this.activeView === "wifi" ? "active" : ""}"
                          aria-current=${this.activeView === "wifi" ? "page" : A}
                          >WiFi</a
                      >` : A}
            </nav>
        `;
  }
  render() {
    return b`
            <div class="header">
                <!-- optional back button -->
                ${this.backButton ? b` <md-icon-button title="Back" aria-label="Back" @click=${this._goBack}>
                              <ha-svg-icon .path=${mdiArrowLeft}></ha-svg-icon>
                          </md-icon-button>
                          <md-icon-button title="Home" aria-label="Home" @click=${this._goHome}>
                              <ha-svg-icon .path=${mdiHome}></ha-svg-icon>
                          </md-icon-button>` : ""}

                <div class="title">${this.title ?? ""}</div>
                ${this._renderNavTabs()}
                <div class="actions">
                    ${this.actions?.map(action => {
      return b`
                            <md-icon-button @click=${action.action} .title=${action.label}>
                                <ha-svg-icon .path=${action.icon}></ha-svg-icon>
                            </md-icon-button>
                        `;
    })}
                    <!-- dev-mode badge (only when dev mode is active and a client exists) -->
                    ${this._devMode && this.client ? b`
                              <button
                                  class="dev-badge"
                                  @click=${this._openSettings}
                                  title="Developer mode active — click to open settings"
                                  aria-label="Developer mode active — click to open settings"
                              >
                                  DEV
                              </button>
                          ` : A}
                    <!-- settings button (only when connected) -->
                    ${this.client ? b`
                              <md-icon-button @click=${this._openSettings} title="Settings">
                                  <ha-svg-icon .path=${mdiCog}></ha-svg-icon>
                              </md-icon-button>
                          ` : A}
                    <!-- theme toggle button -->
                    <md-icon-button @click=${this._cycleTheme} .title=${this._getThemeTooltip()}>
                        <ha-svg-icon .path=${this._getThemeIcon()}></ha-svg-icon>
                    </md-icon-button>
                    <!-- optional logout button (only when client exists and not in production) -->
                    ${this.client && !this.client.isProduction ? b`
                              <md-icon-button @click=${this.client.disconnect}>
                                  <ha-svg-icon .path=${mdiLogout}></ha-svg-icon>
                              </md-icon-button>
                          ` : A}
                </div>
            </div>
        `;
  }
};
DashboardHeader.styles = [reducedMotionStyles, i$7`
            .header {
                background-color: var(--md-sys-color-primary);
                color: var(--md-sys-color-on-primary);
                --icon-primary-color: var(--md-sys-color-on-primary);
                font-weight: 400;
                display: flex;
                align-items: center;
                padding-left: 18px;
                padding-right: 8px;
                min-height: 48px;
            }

            md-icon-button {
                margin-right: 8px;
            }

            .title {
                flex: 1;
                min-width: 0;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }

            .actions {
                display: flex;
                max-width: 100%;
                align-items: center;
            }

            .nav-tabs {
                display: flex;
                margin-left: 24px;
                gap: 4px;
            }

            .nav-tab {
                padding: 8px 16px;
                color: var(--md-sys-color-on-primary);
                text-decoration: none;
                font-size: 0.875rem;
                font-weight: 500;
                border-radius: 4px 4px 0 0;
                opacity: 0.7;
                transition: opacity 0.2s;
            }

            .nav-tab:hover {
                opacity: 0.9;
            }

            .nav-tab.active {
                opacity: 1;
                background-color: rgba(255, 255, 255, 0.15);
                border-bottom: 2px solid var(--md-sys-color-on-primary);
            }

            .dev-badge {
                font-family: var(--monospace-font);
                font-size: 0.7rem;
                font-weight: 600;
                letter-spacing: 0.08em;
                padding: 4px 8px;
                margin-right: 8px;
                border-radius: 4px;
                background: var(--dev-color);
                color: var(--dev-on-color);
                border: none;
                cursor: pointer;
                line-height: 1;
            }

            .dev-badge:hover {
                background: color-mix(in srgb, var(--dev-color) 88%, white);
            }

            .dev-badge:focus-visible {
                outline: 2px solid var(--dev-on-color);
                outline-offset: 2px;
            }
        `];
__decorateClass$q([n$5()], DashboardHeader.prototype, "backButton", 2);
__decorateClass$q([n$5()], DashboardHeader.prototype, "actions", 2);
__decorateClass$q([n$5()], DashboardHeader.prototype, "activeView", 2);
__decorateClass$q([n$5({
  type: Boolean
})], DashboardHeader.prototype, "hasThreadDevices", 2);
__decorateClass$q([n$5({
  type: Boolean
})], DashboardHeader.prototype, "hasWifiDevices", 2);
__decorateClass$q([c$5({
  context: clientContext
})], DashboardHeader.prototype, "client", 2);
__decorateClass$q([c$5({
  context: tickContext,
  subscribe: true
})], DashboardHeader.prototype, "_tick", 2);
__decorateClass$q([r$3()], DashboardHeader.prototype, "_themePreference", 2);
__decorateClass$q([r$3()], DashboardHeader.prototype, "_effectiveTheme", 2);
__decorateClass$q([r$3()], DashboardHeader.prototype, "_devMode", 2);
DashboardHeader = __decorateClass$q([t$1("dashboard-header")], DashboardHeader);

/**
 * @license
 * Copyright 2024 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Generated stylesheet for ./iconbutton/internal/outlined-styles.css.
const styles$f = i$7`:host{--_container-height: var(--md-outlined-icon-button-container-height, 40px);--_container-width: var(--md-outlined-icon-button-container-width, 40px);--_disabled-icon-color: var(--md-outlined-icon-button-disabled-icon-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-icon-opacity: var(--md-outlined-icon-button-disabled-icon-opacity, 0.38);--_disabled-selected-container-color: var(--md-outlined-icon-button-disabled-selected-container-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-selected-container-opacity: var(--md-outlined-icon-button-disabled-selected-container-opacity, 0.12);--_hover-state-layer-opacity: var(--md-outlined-icon-button-hover-state-layer-opacity, 0.08);--_icon-size: var(--md-outlined-icon-button-icon-size, 24px);--_pressed-state-layer-opacity: var(--md-outlined-icon-button-pressed-state-layer-opacity, 0.12);--_selected-container-color: var(--md-outlined-icon-button-selected-container-color, var(--md-sys-color-inverse-surface, #322f35));--_selected-focus-icon-color: var(--md-outlined-icon-button-selected-focus-icon-color, var(--md-sys-color-inverse-on-surface, #f5eff7));--_selected-hover-icon-color: var(--md-outlined-icon-button-selected-hover-icon-color, var(--md-sys-color-inverse-on-surface, #f5eff7));--_selected-hover-state-layer-color: var(--md-outlined-icon-button-selected-hover-state-layer-color, var(--md-sys-color-inverse-on-surface, #f5eff7));--_selected-icon-color: var(--md-outlined-icon-button-selected-icon-color, var(--md-sys-color-inverse-on-surface, #f5eff7));--_selected-pressed-icon-color: var(--md-outlined-icon-button-selected-pressed-icon-color, var(--md-sys-color-inverse-on-surface, #f5eff7));--_selected-pressed-state-layer-color: var(--md-outlined-icon-button-selected-pressed-state-layer-color, var(--md-sys-color-inverse-on-surface, #f5eff7));--_disabled-outline-color: var(--md-outlined-icon-button-disabled-outline-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-outline-opacity: var(--md-outlined-icon-button-disabled-outline-opacity, 0.12);--_focus-icon-color: var(--md-outlined-icon-button-focus-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_hover-icon-color: var(--md-outlined-icon-button-hover-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_hover-state-layer-color: var(--md-outlined-icon-button-hover-state-layer-color, var(--md-sys-color-on-surface-variant, #49454f));--_icon-color: var(--md-outlined-icon-button-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_outline-color: var(--md-outlined-icon-button-outline-color, var(--md-sys-color-outline, #79747e));--_outline-width: var(--md-outlined-icon-button-outline-width, 1px);--_pressed-icon-color: var(--md-outlined-icon-button-pressed-icon-color, var(--md-sys-color-on-surface, #1d1b20));--_pressed-state-layer-color: var(--md-outlined-icon-button-pressed-state-layer-color, var(--md-sys-color-on-surface, #1d1b20));--_container-shape-start-start: var(--md-outlined-icon-button-container-shape-start-start, var(--md-outlined-icon-button-container-shape, var(--md-sys-shape-corner-full, 9999px)));--_container-shape-start-end: var(--md-outlined-icon-button-container-shape-start-end, var(--md-outlined-icon-button-container-shape, var(--md-sys-shape-corner-full, 9999px)));--_container-shape-end-end: var(--md-outlined-icon-button-container-shape-end-end, var(--md-outlined-icon-button-container-shape, var(--md-sys-shape-corner-full, 9999px)));--_container-shape-end-start: var(--md-outlined-icon-button-container-shape-end-start, var(--md-outlined-icon-button-container-shape, var(--md-sys-shape-corner-full, 9999px)))}.outlined{background-color:rgba(0,0,0,0);color:var(--_icon-color);--md-ripple-hover-color: var(--_hover-state-layer-color);--md-ripple-hover-opacity: var(--_hover-state-layer-opacity);--md-ripple-pressed-color: var(--_pressed-state-layer-color);--md-ripple-pressed-opacity: var(--_pressed-state-layer-opacity)}.outlined::before{border-color:var(--_outline-color);border-width:var(--_outline-width)}.outlined:hover{color:var(--_hover-icon-color)}.outlined:focus{color:var(--_focus-icon-color)}.outlined:active{color:var(--_pressed-icon-color)}.outlined:is(:disabled,[aria-disabled=true]){color:var(--_disabled-icon-color)}.outlined:is(:disabled,[aria-disabled=true])::before{border-color:var(--_disabled-outline-color);opacity:var(--_disabled-outline-opacity)}.outlined:is(:disabled,[aria-disabled=true]) .icon{opacity:var(--_disabled-icon-opacity)}.outlined::before{block-size:100%;border-style:solid;border-radius:inherit;box-sizing:border-box;content:"";inline-size:100%;inset:0;pointer-events:none;position:absolute;z-index:-1}.outlined.selected::before{border-width:0}.selected:not(:disabled,[aria-disabled=true]){color:var(--_selected-icon-color)}.selected:not(:disabled,[aria-disabled=true]):hover{color:var(--_selected-hover-icon-color)}.selected:not(:disabled,[aria-disabled=true]):focus{color:var(--_selected-focus-icon-color)}.selected:not(:disabled,[aria-disabled=true]):active{color:var(--_selected-pressed-icon-color)}.selected{--md-ripple-hover-color: var(--_selected-hover-state-layer-color);--md-ripple-hover-opacity: var(--_hover-state-layer-opacity);--md-ripple-pressed-color: var(--_selected-pressed-state-layer-color);--md-ripple-pressed-opacity: var(--_pressed-state-layer-opacity)}.selected:not(:disabled,[aria-disabled=true])::before{background-color:var(--_selected-container-color)}.selected:is(:disabled,[aria-disabled=true])::before{background-color:var(--_disabled-selected-container-color);opacity:var(--_disabled-selected-container-opacity)}@media(forced-colors: active){:host(:is([disabled],[soft-disabled])){--_disabled-outline-opacity: 1}.selected::before{border-color:CanvasText;border-width:var(--_outline-width)}.selected:is(:disabled,[aria-disabled=true])::before{border-color:GrayText;opacity:1}}
`;

/**
 * @license
 * Copyright 2022 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @summary Icon buttons help people take supplementary actions with a single
 * tap.
 *
 * @description
 * __Emphasis:__ Low emphasis – For optional or supplementary actions with the
 * least amount of prominence.
 *
 * __Rationale:__ The most compact and unobtrusive type of button, icon buttons
 * are used for optional supplementary actions such as "Bookmark" or "Star."
 *
 * __Example usages:__
 * - Add to Favorites
 * - Print
 *
 * @final
 * @suppress {visibility}
 */
let MdOutlinedIconButton = class MdOutlinedIconButton extends IconButton {
  getRenderClasses() {
    return {
      ...super.getRenderClasses(),
      'outlined': true
    };
  }
};
MdOutlinedIconButton.styles = [styles$k, styles$f];
MdOutlinedIconButton = __decorate([t$1('md-outlined-icon-button')], MdOutlinedIconButton);

/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
let e$2 = class e extends i$3 {
  constructor(i) {
    if (super(i), this.it = A, i.type !== t.CHILD) throw Error(this.constructor.directiveName + "() can only be used in child bindings");
  }
  render(r) {
    if (r === A || null == r) return this._t = void 0, this.it = r;
    if (r === E) return r;
    if ("string" != typeof r) throw Error(this.constructor.directiveName + "() called with a non-string value");
    if (r === this.it) return this._t;
    this.it = r;
    const s = [r];
    return s.raw = s, this._t = {
      _$litType$: this.constructor.resultType,
      strings: s,
      values: []
    };
  }
};
e$2.directiveName = "unsafeHTML", e$2.resultType = 1;
const o$3 = e$4(e$2);

const device_types = {
  "10": {
    "id": 10,
    "label": "Door Lock"
  },
  "11": {
    "id": 11,
    "label": "Door Lock Controller"
  },
  "14": {
    "id": 14,
    "label": "Aggregator"
  },
  "15": {
    "id": 15,
    "label": "Generic Switch"
  },
  "17": {
    "id": 17,
    "label": "Power Source"
  },
  "18": {
    "id": 18,
    "label": "Ota Requestor"
  },
  "19": {
    "id": 19,
    "label": "Bridged Node"
  },
  "20": {
    "id": 20,
    "label": "Ota Provider"
  },
  "21": {
    "id": 21,
    "label": "Contact Sensor"
  },
  "22": {
    "id": 22,
    "label": "Root Node"
  },
  "23": {
    "id": 23,
    "label": "Solar Power"
  },
  "24": {
    "id": 24,
    "label": "Battery Storage"
  },
  "25": {
    "id": 25,
    "label": "Secondary Network Interface"
  },
  "34": {
    "id": 34,
    "label": "Speaker"
  },
  "35": {
    "id": 35,
    "label": "Casting Video Player"
  },
  "36": {
    "id": 36,
    "label": "Content App"
  },
  "39": {
    "id": 39,
    "label": "Mode Select"
  },
  "40": {
    "id": 40,
    "label": "Basic Video Player"
  },
  "41": {
    "id": 41,
    "label": "Casting Video Client"
  },
  "42": {
    "id": 42,
    "label": "Video Remote Control"
  },
  "43": {
    "id": 43,
    "label": "Fan"
  },
  "44": {
    "id": 44,
    "label": "Air Quality Sensor"
  },
  "45": {
    "id": 45,
    "label": "Air Purifier"
  },
  "64": {
    "id": 64,
    "label": "Irrigation System"
  },
  "65": {
    "id": 65,
    "label": "Water Freeze Detector"
  },
  "66": {
    "id": 66,
    "label": "Water Valve"
  },
  "67": {
    "id": 67,
    "label": "Water Leak Detector"
  },
  "68": {
    "id": 68,
    "label": "Rain Sensor"
  },
  "69": {
    "id": 69,
    "label": "Soil Sensor"
  },
  "112": {
    "id": 112,
    "label": "Refrigerator"
  },
  "113": {
    "id": 113,
    "label": "Temperature Controlled Cabinet"
  },
  "114": {
    "id": 114,
    "label": "Room Air Conditioner"
  },
  "115": {
    "id": 115,
    "label": "Laundry Washer"
  },
  "116": {
    "id": 116,
    "label": "Robotic Vacuum Cleaner"
  },
  "117": {
    "id": 117,
    "label": "Dishwasher"
  },
  "118": {
    "id": 118,
    "label": "Smoke Co Alarm"
  },
  "119": {
    "id": 119,
    "label": "Cook Surface"
  },
  "120": {
    "id": 120,
    "label": "Cooktop"
  },
  "121": {
    "id": 121,
    "label": "Microwave Oven"
  },
  "122": {
    "id": 122,
    "label": "Extractor Hood"
  },
  "123": {
    "id": 123,
    "label": "Oven"
  },
  "124": {
    "id": 124,
    "label": "Laundry Dryer"
  },
  "144": {
    "id": 144,
    "label": "Network Infrastructure Manager"
  },
  "145": {
    "id": 145,
    "label": "Thread Border Router"
  },
  "256": {
    "id": 256,
    "label": "On Off Light"
  },
  "257": {
    "id": 257,
    "label": "Dimmable Light"
  },
  "259": {
    "id": 259,
    "label": "On Off Light Switch"
  },
  "260": {
    "id": 260,
    "label": "Dimmer Switch"
  },
  "261": {
    "id": 261,
    "label": "Color Dimmer Switch"
  },
  "262": {
    "id": 262,
    "label": "Light Sensor"
  },
  "263": {
    "id": 263,
    "label": "Occupancy Sensor"
  },
  "266": {
    "id": 266,
    "label": "On Off Plug In Unit"
  },
  "267": {
    "id": 267,
    "label": "Dimmable Plug In Unit"
  },
  "268": {
    "id": 268,
    "label": "Color Temperature Light"
  },
  "269": {
    "id": 269,
    "label": "Extended Color Light"
  },
  "271": {
    "id": 271,
    "label": "Mounted On Off Control"
  },
  "272": {
    "id": 272,
    "label": "Mounted Dimmable Load Control"
  },
  "304": {
    "id": 304,
    "label": "Joint Fabric Administrator"
  },
  "320": {
    "id": 320,
    "label": "Intercom"
  },
  "321": {
    "id": 321,
    "label": "Audio Doorbell"
  },
  "322": {
    "id": 322,
    "label": "Camera"
  },
  "323": {
    "id": 323,
    "label": "Video Doorbell"
  },
  "324": {
    "id": 324,
    "label": "Floodlight Camera"
  },
  "325": {
    "id": 325,
    "label": "Snapshot Camera"
  },
  "326": {
    "id": 326,
    "label": "Chime"
  },
  "327": {
    "id": 327,
    "label": "Camera Controller"
  },
  "328": {
    "id": 328,
    "label": "Doorbell"
  },
  "514": {
    "id": 514,
    "label": "Window Covering"
  },
  "515": {
    "id": 515,
    "label": "Window Covering Controller"
  },
  "560": {
    "id": 560,
    "label": "Closure"
  },
  "561": {
    "id": 561,
    "label": "Closure Panel"
  },
  "574": {
    "id": 574,
    "label": "Closure Controller"
  },
  "769": {
    "id": 769,
    "label": "Thermostat"
  },
  "770": {
    "id": 770,
    "label": "Temperature Sensor"
  },
  "771": {
    "id": 771,
    "label": "Pump"
  },
  "772": {
    "id": 772,
    "label": "Pump Controller"
  },
  "773": {
    "id": 773,
    "label": "Pressure Sensor"
  },
  "774": {
    "id": 774,
    "label": "Flow Sensor"
  },
  "775": {
    "id": 775,
    "label": "Humidity Sensor"
  },
  "777": {
    "id": 777,
    "label": "Heat Pump"
  },
  "778": {
    "id": 778,
    "label": "Thermostat Controller"
  },
  "1292": {
    "id": 1292,
    "label": "Energy Evse"
  },
  "1293": {
    "id": 1293,
    "label": "Device Energy Management"
  },
  "1295": {
    "id": 1295,
    "label": "Water Heater"
  },
  "1296": {
    "id": 1296,
    "label": "Electrical Sensor"
  },
  "1297": {
    "id": 1297,
    "label": "Electrical Utility Meter"
  },
  "1298": {
    "id": 1298,
    "label": "Meter Reference Point"
  },
  "1299": {
    "id": 1299,
    "label": "Electrical Energy Tariff"
  },
  "1300": {
    "id": 1300,
    "label": "Electrical Meter"
  },
  "2112": {
    "id": 2112,
    "label": "Control Bridge"
  },
  "2128": {
    "id": 2128,
    "label": "On Off Sensor"
  }
};
const clusters = {
  "3": {
    "id": 3,
    "label": "Identify",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 3,
        "label": "IdentifyTime",
        "type": "uint16",
        "writable": true
      },
      "1": {
        "id": 1,
        "cluster_id": 3,
        "label": "IdentifyType",
        "type": "IdentifyTypeEnum",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 3,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 3,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 3,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 3,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 3,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 3,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 3,
        "name": "Identify",
        "label": "Identify"
      },
      "64": {
        "id": 64,
        "cluster_id": 3,
        "name": "TriggerEffect",
        "label": "Trigger Effect"
      }
    }
  },
  "4": {
    "id": 4,
    "label": "Groups",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 4,
        "label": "NameSupport",
        "type": "NameSupportBitmap",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 4,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 4,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 4,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 4,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 4,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 4,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 4,
        "name": "AddGroup",
        "label": "Add Group"
      },
      "1": {
        "id": 1,
        "cluster_id": 4,
        "name": "ViewGroup",
        "label": "View Group"
      },
      "2": {
        "id": 2,
        "cluster_id": 4,
        "name": "GetGroupMembership",
        "label": "Get Group Membership"
      },
      "3": {
        "id": 3,
        "cluster_id": 4,
        "name": "RemoveGroup",
        "label": "Remove Group"
      },
      "4": {
        "id": 4,
        "cluster_id": 4,
        "name": "RemoveAllGroups",
        "label": "Remove All Groups"
      },
      "5": {
        "id": 5,
        "cluster_id": 4,
        "name": "AddGroupIfIdentifying",
        "label": "Add Group If Identifying"
      }
    }
  },
  "6": {
    "id": 6,
    "label": "OnOff",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 6,
        "label": "OnOff",
        "type": "bool",
        "writable": false
      },
      "16384": {
        "id": 16384,
        "cluster_id": 6,
        "label": "GlobalSceneControl",
        "type": "Optional[bool]",
        "writable": false
      },
      "16385": {
        "id": 16385,
        "cluster_id": 6,
        "label": "OnTime",
        "type": "Optional[uint16]",
        "writable": true
      },
      "16386": {
        "id": 16386,
        "cluster_id": 6,
        "label": "OffWaitTime",
        "type": "Optional[uint16]",
        "writable": true
      },
      "16387": {
        "id": 16387,
        "cluster_id": 6,
        "label": "StartUpOnOff",
        "type": "Optional[Nullable[StartUpOnOffEnum]]",
        "writable": true
      },
      "65528": {
        "id": 65528,
        "cluster_id": 6,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 6,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 6,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 6,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 6,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 6,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 6,
        "name": "Off",
        "label": "Off"
      },
      "1": {
        "id": 1,
        "cluster_id": 6,
        "name": "On",
        "label": "On"
      },
      "2": {
        "id": 2,
        "cluster_id": 6,
        "name": "Toggle",
        "label": "Toggle"
      },
      "64": {
        "id": 64,
        "cluster_id": 6,
        "name": "OffWithEffect",
        "label": "Off With Effect"
      },
      "65": {
        "id": 65,
        "cluster_id": 6,
        "name": "OnWithRecallGlobalScene",
        "label": "On With Recall Global Scene"
      },
      "66": {
        "id": 66,
        "cluster_id": 6,
        "name": "OnWithTimedOff",
        "label": "On With Timed Off"
      }
    }
  },
  "8": {
    "id": 8,
    "label": "LevelControl",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 8,
        "label": "CurrentLevel",
        "type": "Nullable[uint8]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 8,
        "label": "RemainingTime",
        "type": "Optional[uint16]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 8,
        "label": "MinLevel",
        "type": "Optional[uint8]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 8,
        "label": "MaxLevel",
        "type": "Optional[uint8]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 8,
        "label": "CurrentFrequency",
        "type": "Optional[uint16]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 8,
        "label": "MinFrequency",
        "type": "Optional[uint16]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 8,
        "label": "MaxFrequency",
        "type": "Optional[uint16]",
        "writable": false
      },
      "15": {
        "id": 15,
        "cluster_id": 8,
        "label": "Options",
        "type": "OptionsBitmap",
        "writable": true
      },
      "16": {
        "id": 16,
        "cluster_id": 8,
        "label": "OnOffTransitionTime",
        "type": "Optional[uint16]",
        "writable": true
      },
      "17": {
        "id": 17,
        "cluster_id": 8,
        "label": "OnLevel",
        "type": "Nullable[uint8]",
        "writable": true
      },
      "18": {
        "id": 18,
        "cluster_id": 8,
        "label": "OnTransitionTime",
        "type": "Optional[Nullable[uint16]]",
        "writable": true
      },
      "19": {
        "id": 19,
        "cluster_id": 8,
        "label": "OffTransitionTime",
        "type": "Optional[Nullable[uint16]]",
        "writable": true
      },
      "20": {
        "id": 20,
        "cluster_id": 8,
        "label": "DefaultMoveRate",
        "type": "Optional[Nullable[uint8]]",
        "writable": true
      },
      "16384": {
        "id": 16384,
        "cluster_id": 8,
        "label": "StartUpCurrentLevel",
        "type": "Optional[Nullable[uint8]]",
        "writable": true
      },
      "65528": {
        "id": 65528,
        "cluster_id": 8,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 8,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 8,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 8,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 8,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 8,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 8,
        "name": "MoveToLevel",
        "label": "Move To Level"
      },
      "1": {
        "id": 1,
        "cluster_id": 8,
        "name": "Move",
        "label": "Move"
      },
      "2": {
        "id": 2,
        "cluster_id": 8,
        "name": "Step",
        "label": "Step"
      },
      "3": {
        "id": 3,
        "cluster_id": 8,
        "name": "Stop",
        "label": "Stop"
      },
      "4": {
        "id": 4,
        "cluster_id": 8,
        "name": "MoveToLevelWithOnOff",
        "label": "Move To Level With On Off"
      },
      "5": {
        "id": 5,
        "cluster_id": 8,
        "name": "MoveWithOnOff",
        "label": "Move With On Off"
      },
      "6": {
        "id": 6,
        "cluster_id": 8,
        "name": "StepWithOnOff",
        "label": "Step With On Off"
      },
      "7": {
        "id": 7,
        "cluster_id": 8,
        "name": "StopWithOnOff",
        "label": "Stop With On Off"
      },
      "8": {
        "id": 8,
        "cluster_id": 8,
        "name": "MoveToClosestFrequency",
        "label": "Move To Closest Frequency"
      }
    }
  },
  "29": {
    "id": 29,
    "label": "Descriptor",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 29,
        "label": "DeviceTypeList",
        "type": "List[DeviceTypeStruct]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 29,
        "label": "ServerList",
        "type": "List[cluster-id]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 29,
        "label": "ClientList",
        "type": "List[cluster-id]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 29,
        "label": "PartsList",
        "type": "List[endpoint-no]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 29,
        "label": "TagList",
        "type": "List[semtag]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 29,
        "label": "EndpointUniqueId",
        "type": "Optional[string]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 29,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 29,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 29,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 29,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 29,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 29,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "30": {
    "id": 30,
    "label": "Binding",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 30,
        "label": "Binding",
        "type": "List[TargetStruct]",
        "writable": true
      },
      "65528": {
        "id": 65528,
        "cluster_id": 30,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 30,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 30,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 30,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 30,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 30,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "31": {
    "id": 31,
    "label": "AccessControl",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 31,
        "label": "Acl",
        "type": "List[AccessControlEntryStruct]",
        "writable": true
      },
      "1": {
        "id": 1,
        "cluster_id": 31,
        "label": "Extension",
        "type": "List[AccessControlExtensionStruct]",
        "writable": true
      },
      "2": {
        "id": 2,
        "cluster_id": 31,
        "label": "SubjectsPerAccessControlEntry",
        "type": "uint16",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 31,
        "label": "TargetsPerAccessControlEntry",
        "type": "uint16",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 31,
        "label": "AccessControlEntriesPerFabric",
        "type": "uint16",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 31,
        "label": "CommissioningArl",
        "type": "List[CommissioningAccessRestrictionEntryStruct]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 31,
        "label": "Arl",
        "type": "List[AccessRestrictionEntryStruct]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 31,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 31,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 31,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 31,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 31,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 31,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 31,
        "name": "ReviewFabricRestrictions",
        "label": "Review Fabric Restrictions"
      }
    }
  },
  "37": {
    "id": 37,
    "label": "Actions",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 37,
        "label": "ActionList",
        "type": "List[ActionStruct]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 37,
        "label": "EndpointLists",
        "type": "List[EndpointListStruct]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 37,
        "label": "SetupUrl",
        "type": "Optional[string]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 37,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 37,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 37,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 37,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 37,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 37,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 37,
        "name": "InstantAction",
        "label": "Instant Action"
      },
      "1": {
        "id": 1,
        "cluster_id": 37,
        "name": "InstantActionWithTransition",
        "label": "Instant Action With Transition"
      },
      "2": {
        "id": 2,
        "cluster_id": 37,
        "name": "StartAction",
        "label": "Start Action"
      },
      "3": {
        "id": 3,
        "cluster_id": 37,
        "name": "StartActionWithDuration",
        "label": "Start Action With Duration"
      },
      "4": {
        "id": 4,
        "cluster_id": 37,
        "name": "StopAction",
        "label": "Stop Action"
      },
      "5": {
        "id": 5,
        "cluster_id": 37,
        "name": "PauseAction",
        "label": "Pause Action"
      },
      "6": {
        "id": 6,
        "cluster_id": 37,
        "name": "PauseActionWithDuration",
        "label": "Pause Action With Duration"
      },
      "7": {
        "id": 7,
        "cluster_id": 37,
        "name": "ResumeAction",
        "label": "Resume Action"
      },
      "8": {
        "id": 8,
        "cluster_id": 37,
        "name": "EnableAction",
        "label": "Enable Action"
      },
      "9": {
        "id": 9,
        "cluster_id": 37,
        "name": "EnableActionWithDuration",
        "label": "Enable Action With Duration"
      },
      "10": {
        "id": 10,
        "cluster_id": 37,
        "name": "DisableAction",
        "label": "Disable Action"
      },
      "11": {
        "id": 11,
        "cluster_id": 37,
        "name": "DisableActionWithDuration",
        "label": "Disable Action With Duration"
      }
    }
  },
  "40": {
    "id": 40,
    "label": "BasicInformation",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 40,
        "label": "DataModelRevision",
        "type": "uint16",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 40,
        "label": "VendorName",
        "type": "string",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 40,
        "label": "VendorId",
        "type": "vendor-id",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 40,
        "label": "ProductName",
        "type": "string",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 40,
        "label": "ProductId",
        "type": "uint16",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 40,
        "label": "NodeLabel",
        "type": "string",
        "writable": true
      },
      "6": {
        "id": 6,
        "cluster_id": 40,
        "label": "Location",
        "type": "string",
        "writable": true
      },
      "7": {
        "id": 7,
        "cluster_id": 40,
        "label": "HardwareVersion",
        "type": "uint16",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 40,
        "label": "HardwareVersionString",
        "type": "string",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 40,
        "label": "SoftwareVersion",
        "type": "uint32",
        "writable": false
      },
      "10": {
        "id": 10,
        "cluster_id": 40,
        "label": "SoftwareVersionString",
        "type": "string",
        "writable": false
      },
      "11": {
        "id": 11,
        "cluster_id": 40,
        "label": "ManufacturingDate",
        "type": "Optional[string]",
        "writable": false
      },
      "12": {
        "id": 12,
        "cluster_id": 40,
        "label": "PartNumber",
        "type": "Optional[string]",
        "writable": false
      },
      "13": {
        "id": 13,
        "cluster_id": 40,
        "label": "ProductUrl",
        "type": "Optional[string]",
        "writable": false
      },
      "14": {
        "id": 14,
        "cluster_id": 40,
        "label": "ProductLabel",
        "type": "Optional[string]",
        "writable": false
      },
      "15": {
        "id": 15,
        "cluster_id": 40,
        "label": "SerialNumber",
        "type": "Optional[string]",
        "writable": false
      },
      "16": {
        "id": 16,
        "cluster_id": 40,
        "label": "LocalConfigDisabled",
        "type": "Optional[bool]",
        "writable": true
      },
      "17": {
        "id": 17,
        "cluster_id": 40,
        "label": "Reachable",
        "type": "Optional[bool]",
        "writable": false
      },
      "18": {
        "id": 18,
        "cluster_id": 40,
        "label": "UniqueId",
        "type": "Optional[string]",
        "writable": false
      },
      "19": {
        "id": 19,
        "cluster_id": 40,
        "label": "CapabilityMinima",
        "type": "CapabilityMinimaStruct",
        "writable": false
      },
      "20": {
        "id": 20,
        "cluster_id": 40,
        "label": "ProductAppearance",
        "type": "Optional[ProductAppearanceStruct]",
        "writable": false
      },
      "21": {
        "id": 21,
        "cluster_id": 40,
        "label": "SpecificationVersion",
        "type": "Optional[uint32]",
        "writable": false
      },
      "22": {
        "id": 22,
        "cluster_id": 40,
        "label": "MaxPathsPerInvoke",
        "type": "Optional[uint16]",
        "writable": false
      },
      "24": {
        "id": 24,
        "cluster_id": 40,
        "label": "ConfigurationVersion",
        "type": "Optional[uint32]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 40,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 40,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 40,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 40,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 40,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 40,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "41": {
    "id": 41,
    "label": "OtaSoftwareUpdateProvider",
    "attributes": {
      "65528": {
        "id": 65528,
        "cluster_id": 41,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 41,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 41,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 41,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 41,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 41,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 41,
        "name": "QueryImage",
        "label": "Query Image"
      },
      "2": {
        "id": 2,
        "cluster_id": 41,
        "name": "ApplyUpdateRequest",
        "label": "Apply Update Request"
      },
      "4": {
        "id": 4,
        "cluster_id": 41,
        "name": "NotifyUpdateApplied",
        "label": "Notify Update Applied"
      }
    }
  },
  "42": {
    "id": 42,
    "label": "OtaSoftwareUpdateRequestor",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 42,
        "label": "DefaultOtaProviders",
        "type": "List[ProviderLocation]",
        "writable": true
      },
      "1": {
        "id": 1,
        "cluster_id": 42,
        "label": "UpdatePossible",
        "type": "bool",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 42,
        "label": "UpdateState",
        "type": "UpdateStateEnum",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 42,
        "label": "UpdateStateProgress",
        "type": "Nullable[uint8]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 42,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 42,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 42,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 42,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 42,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 42,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 42,
        "name": "AnnounceOtaProvider",
        "label": "Announce Ota Provider"
      }
    }
  },
  "43": {
    "id": 43,
    "label": "LocalizationConfiguration",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 43,
        "label": "ActiveLocale",
        "type": "string",
        "writable": true
      },
      "1": {
        "id": 1,
        "cluster_id": 43,
        "label": "SupportedLocales",
        "type": "List[string]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 43,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 43,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 43,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 43,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 43,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 43,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "44": {
    "id": 44,
    "label": "TimeFormatLocalization",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 44,
        "label": "HourFormat",
        "type": "HourFormatEnum",
        "writable": true
      },
      "1": {
        "id": 1,
        "cluster_id": 44,
        "label": "ActiveCalendarType",
        "type": "Optional[CalendarTypeEnum]",
        "writable": true
      },
      "2": {
        "id": 2,
        "cluster_id": 44,
        "label": "SupportedCalendarTypes",
        "type": "List[CalendarTypeEnum]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 44,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 44,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 44,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 44,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 44,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 44,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "45": {
    "id": 45,
    "label": "UnitLocalization",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 45,
        "label": "TemperatureUnit",
        "type": "Optional[TempUnitEnum]",
        "writable": true
      },
      "1": {
        "id": 1,
        "cluster_id": 45,
        "label": "SupportedTemperatureUnits",
        "type": "List[TempUnitEnum]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 45,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 45,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 45,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 45,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 45,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 45,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "46": {
    "id": 46,
    "label": "PowerSourceConfiguration",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 46,
        "label": "Sources",
        "type": "List[endpoint-no]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 46,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 46,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 46,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 46,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 46,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 46,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "47": {
    "id": 47,
    "label": "PowerSource",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 47,
        "label": "Status",
        "type": "PowerSourceStatusEnum",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 47,
        "label": "Order",
        "type": "uint8",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 47,
        "label": "Description",
        "type": "string",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 47,
        "label": "WiredAssessedInputVoltage",
        "type": "Optional[Nullable[uint32]]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 47,
        "label": "WiredAssessedInputFrequency",
        "type": "Optional[Nullable[uint16]]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 47,
        "label": "WiredCurrentType",
        "type": "Optional[WiredCurrentTypeEnum]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 47,
        "label": "WiredAssessedCurrent",
        "type": "Optional[Nullable[uint32]]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 47,
        "label": "WiredNominalVoltage",
        "type": "Optional[uint32]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 47,
        "label": "WiredMaximumCurrent",
        "type": "Optional[uint32]",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 47,
        "label": "WiredPresent",
        "type": "Optional[bool]",
        "writable": false
      },
      "10": {
        "id": 10,
        "cluster_id": 47,
        "label": "ActiveWiredFaults",
        "type": "List[WiredFaultEnum]",
        "writable": false
      },
      "11": {
        "id": 11,
        "cluster_id": 47,
        "label": "BatVoltage",
        "type": "Optional[Nullable[uint32]]",
        "writable": false
      },
      "12": {
        "id": 12,
        "cluster_id": 47,
        "label": "BatPercentRemaining",
        "type": "Optional[Nullable[uint8]]",
        "writable": false
      },
      "13": {
        "id": 13,
        "cluster_id": 47,
        "label": "BatTimeRemaining",
        "type": "Optional[Nullable[uint32]]",
        "writable": false
      },
      "14": {
        "id": 14,
        "cluster_id": 47,
        "label": "BatChargeLevel",
        "type": "Optional[BatChargeLevelEnum]",
        "writable": false
      },
      "15": {
        "id": 15,
        "cluster_id": 47,
        "label": "BatReplacementNeeded",
        "type": "Optional[bool]",
        "writable": false
      },
      "16": {
        "id": 16,
        "cluster_id": 47,
        "label": "BatReplaceability",
        "type": "Optional[BatReplaceabilityEnum]",
        "writable": false
      },
      "17": {
        "id": 17,
        "cluster_id": 47,
        "label": "BatPresent",
        "type": "Optional[bool]",
        "writable": false
      },
      "18": {
        "id": 18,
        "cluster_id": 47,
        "label": "ActiveBatFaults",
        "type": "List[BatFaultEnum]",
        "writable": false
      },
      "19": {
        "id": 19,
        "cluster_id": 47,
        "label": "BatReplacementDescription",
        "type": "Optional[string]",
        "writable": false
      },
      "20": {
        "id": 20,
        "cluster_id": 47,
        "label": "BatCommonDesignation",
        "type": "Optional[BatCommonDesignationEnum]",
        "writable": false
      },
      "21": {
        "id": 21,
        "cluster_id": 47,
        "label": "BatAnsiDesignation",
        "type": "Optional[string]",
        "writable": false
      },
      "22": {
        "id": 22,
        "cluster_id": 47,
        "label": "BatIecDesignation",
        "type": "Optional[string]",
        "writable": false
      },
      "23": {
        "id": 23,
        "cluster_id": 47,
        "label": "BatApprovedChemistry",
        "type": "Optional[BatApprovedChemistryEnum]",
        "writable": false
      },
      "24": {
        "id": 24,
        "cluster_id": 47,
        "label": "BatCapacity",
        "type": "Optional[uint32]",
        "writable": false
      },
      "25": {
        "id": 25,
        "cluster_id": 47,
        "label": "BatQuantity",
        "type": "Optional[uint8]",
        "writable": false
      },
      "26": {
        "id": 26,
        "cluster_id": 47,
        "label": "BatChargeState",
        "type": "Optional[BatChargeStateEnum]",
        "writable": false
      },
      "27": {
        "id": 27,
        "cluster_id": 47,
        "label": "BatTimeToFullCharge",
        "type": "Optional[Nullable[uint32]]",
        "writable": false
      },
      "28": {
        "id": 28,
        "cluster_id": 47,
        "label": "BatFunctionalWhileCharging",
        "type": "Optional[bool]",
        "writable": false
      },
      "29": {
        "id": 29,
        "cluster_id": 47,
        "label": "BatChargingCurrent",
        "type": "Optional[Nullable[uint32]]",
        "writable": false
      },
      "30": {
        "id": 30,
        "cluster_id": 47,
        "label": "ActiveBatChargeFaults",
        "type": "List[BatChargeFaultEnum]",
        "writable": false
      },
      "31": {
        "id": 31,
        "cluster_id": 47,
        "label": "EndpointList",
        "type": "List[endpoint-no]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 47,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 47,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 47,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 47,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 47,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 47,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "48": {
    "id": 48,
    "label": "GeneralCommissioning",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 48,
        "label": "Breadcrumb",
        "type": "uint64",
        "writable": true
      },
      "1": {
        "id": 1,
        "cluster_id": 48,
        "label": "BasicCommissioningInfo",
        "type": "BasicCommissioningInfo",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 48,
        "label": "RegulatoryConfig",
        "type": "RegulatoryLocationTypeEnum",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 48,
        "label": "LocationCapability",
        "type": "RegulatoryLocationTypeEnum",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 48,
        "label": "SupportsConcurrentConnection",
        "type": "bool",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 48,
        "label": "TcAcceptedVersion",
        "type": "Optional[uint16]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 48,
        "label": "TcMinRequiredVersion",
        "type": "Optional[uint16]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 48,
        "label": "TcAcknowledgements",
        "type": "Optional[map16]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 48,
        "label": "TcAcknowledgementsRequired",
        "type": "Optional[bool]",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 48,
        "label": "TcUpdateDeadline",
        "type": "Optional[Nullable[uint32]]",
        "writable": false
      },
      "10": {
        "id": 10,
        "cluster_id": 48,
        "label": "RecoveryIdentifier",
        "type": "Optional[bytes]",
        "writable": false
      },
      "11": {
        "id": 11,
        "cluster_id": 48,
        "label": "NetworkRecoveryReason",
        "type": "Optional[Nullable[NetworkRecoveryReasonEnum]]",
        "writable": false
      },
      "12": {
        "id": 12,
        "cluster_id": 48,
        "label": "IsCommissioningWithoutPower",
        "type": "Optional[bool]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 48,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 48,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 48,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 48,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 48,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 48,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 48,
        "name": "ArmFailSafe",
        "label": "Arm Fail Safe"
      },
      "2": {
        "id": 2,
        "cluster_id": 48,
        "name": "SetRegulatoryConfig",
        "label": "Set Regulatory Config"
      },
      "4": {
        "id": 4,
        "cluster_id": 48,
        "name": "CommissioningComplete",
        "label": "Commissioning Complete"
      },
      "6": {
        "id": 6,
        "cluster_id": 48,
        "name": "SetTcAcknowledgements",
        "label": "Set Tc Acknowledgements"
      }
    }
  },
  "49": {
    "id": 49,
    "label": "NetworkCommissioning",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 49,
        "label": "MaxNetworks",
        "type": "uint8",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 49,
        "label": "Networks",
        "type": "List[NetworkInfoStruct]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 49,
        "label": "ScanMaxTimeSeconds",
        "type": "Optional[uint8]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 49,
        "label": "ConnectMaxTimeSeconds",
        "type": "Optional[uint8]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 49,
        "label": "InterfaceEnabled",
        "type": "bool",
        "writable": true
      },
      "5": {
        "id": 5,
        "cluster_id": 49,
        "label": "LastNetworkingStatus",
        "type": "Nullable[NetworkCommissioningStatusEnum]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 49,
        "label": "LastNetworkId",
        "type": "Nullable[bytes]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 49,
        "label": "LastConnectErrorValue",
        "type": "Nullable[int32]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 49,
        "label": "SupportedWiFiBands",
        "type": "List[WiFiBandEnum]",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 49,
        "label": "SupportedThreadFeatures",
        "type": "Optional[ThreadCapabilitiesBitmap]",
        "writable": false
      },
      "10": {
        "id": 10,
        "cluster_id": 49,
        "label": "ThreadVersion",
        "type": "Optional[uint16]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 49,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 49,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 49,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 49,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 49,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 49,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 49,
        "name": "ScanNetworks",
        "label": "Scan Networks"
      },
      "2": {
        "id": 2,
        "cluster_id": 49,
        "name": "AddOrUpdateWiFiNetwork",
        "label": "Add Or Update Wi Fi Network"
      },
      "3": {
        "id": 3,
        "cluster_id": 49,
        "name": "AddOrUpdateThreadNetwork",
        "label": "Add Or Update Thread Network"
      },
      "4": {
        "id": 4,
        "cluster_id": 49,
        "name": "RemoveNetwork",
        "label": "Remove Network"
      },
      "6": {
        "id": 6,
        "cluster_id": 49,
        "name": "ConnectNetwork",
        "label": "Connect Network"
      },
      "8": {
        "id": 8,
        "cluster_id": 49,
        "name": "ReorderNetwork",
        "label": "Reorder Network"
      }
    }
  },
  "50": {
    "id": 50,
    "label": "DiagnosticLogs",
    "attributes": {
      "65528": {
        "id": 65528,
        "cluster_id": 50,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 50,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 50,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 50,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 50,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 50,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 50,
        "name": "RetrieveLogsRequest",
        "label": "Retrieve Logs Request"
      }
    }
  },
  "51": {
    "id": 51,
    "label": "GeneralDiagnostics",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 51,
        "label": "NetworkInterfaces",
        "type": "List[NetworkInterface]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 51,
        "label": "RebootCount",
        "type": "uint16",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 51,
        "label": "UpTime",
        "type": "uint64",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 51,
        "label": "TotalOperationalHours",
        "type": "Optional[uint32]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 51,
        "label": "BootReason",
        "type": "Optional[BootReasonEnum]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 51,
        "label": "ActiveHardwareFaults",
        "type": "List[HardwareFaultEnum]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 51,
        "label": "ActiveRadioFaults",
        "type": "List[RadioFaultEnum]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 51,
        "label": "ActiveNetworkFaults",
        "type": "List[NetworkFaultEnum]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 51,
        "label": "TestEventTriggersEnabled",
        "type": "bool",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 51,
        "label": "DoNotUse",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65528": {
        "id": 65528,
        "cluster_id": 51,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 51,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 51,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 51,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 51,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 51,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 51,
        "name": "TestEventTrigger",
        "label": "Test Event Trigger"
      },
      "1": {
        "id": 1,
        "cluster_id": 51,
        "name": "TimeSnapshot",
        "label": "Time Snapshot"
      },
      "3": {
        "id": 3,
        "cluster_id": 51,
        "name": "PayloadTestRequest",
        "label": "Payload Test Request"
      }
    }
  },
  "52": {
    "id": 52,
    "label": "SoftwareDiagnostics",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 52,
        "label": "ThreadMetrics",
        "type": "List[ThreadMetricsStruct]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 52,
        "label": "CurrentHeapFree",
        "type": "Optional[uint64]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 52,
        "label": "CurrentHeapUsed",
        "type": "Optional[uint64]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 52,
        "label": "CurrentHeapHighWatermark",
        "type": "Optional[uint64]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 52,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 52,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 52,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 52,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 52,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 52,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 52,
        "name": "ResetWatermarks",
        "label": "Reset Watermarks"
      }
    }
  },
  "53": {
    "id": 53,
    "label": "ThreadNetworkDiagnostics",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 53,
        "label": "Channel",
        "type": "Nullable[uint16]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 53,
        "label": "RoutingRole",
        "type": "Nullable[RoutingRoleEnum]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 53,
        "label": "NetworkName",
        "type": "Nullable[string]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 53,
        "label": "PanId",
        "type": "Nullable[uint16]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 53,
        "label": "ExtendedPanId",
        "type": "Nullable[uint64]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 53,
        "label": "MeshLocalPrefix",
        "type": "Nullable[bytes]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 53,
        "label": "OverrunCount",
        "type": "Optional[uint64]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 53,
        "label": "NeighborTable",
        "type": "List[NeighborTableStruct]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 53,
        "label": "RouteTable",
        "type": "List[RouteTableStruct]",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 53,
        "label": "PartitionId",
        "type": "Nullable[uint32]",
        "writable": false
      },
      "10": {
        "id": 10,
        "cluster_id": 53,
        "label": "Weighting",
        "type": "Nullable[uint16]",
        "writable": false
      },
      "11": {
        "id": 11,
        "cluster_id": 53,
        "label": "DataVersion",
        "type": "Nullable[uint16]",
        "writable": false
      },
      "12": {
        "id": 12,
        "cluster_id": 53,
        "label": "StableDataVersion",
        "type": "Nullable[uint16]",
        "writable": false
      },
      "13": {
        "id": 13,
        "cluster_id": 53,
        "label": "LeaderRouterId",
        "type": "Nullable[uint8]",
        "writable": false
      },
      "14": {
        "id": 14,
        "cluster_id": 53,
        "label": "DetachedRoleCount",
        "type": "Optional[uint16]",
        "writable": false
      },
      "15": {
        "id": 15,
        "cluster_id": 53,
        "label": "ChildRoleCount",
        "type": "Optional[uint16]",
        "writable": false
      },
      "16": {
        "id": 16,
        "cluster_id": 53,
        "label": "RouterRoleCount",
        "type": "Optional[uint16]",
        "writable": false
      },
      "17": {
        "id": 17,
        "cluster_id": 53,
        "label": "LeaderRoleCount",
        "type": "Optional[uint16]",
        "writable": false
      },
      "18": {
        "id": 18,
        "cluster_id": 53,
        "label": "AttachAttemptCount",
        "type": "Optional[uint16]",
        "writable": false
      },
      "19": {
        "id": 19,
        "cluster_id": 53,
        "label": "PartitionIdChangeCount",
        "type": "Optional[uint16]",
        "writable": false
      },
      "20": {
        "id": 20,
        "cluster_id": 53,
        "label": "BetterPartitionAttachAttemptCount",
        "type": "Optional[uint16]",
        "writable": false
      },
      "21": {
        "id": 21,
        "cluster_id": 53,
        "label": "ParentChangeCount",
        "type": "Optional[uint16]",
        "writable": false
      },
      "22": {
        "id": 22,
        "cluster_id": 53,
        "label": "TxTotalCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "23": {
        "id": 23,
        "cluster_id": 53,
        "label": "TxUnicastCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "24": {
        "id": 24,
        "cluster_id": 53,
        "label": "TxBroadcastCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "25": {
        "id": 25,
        "cluster_id": 53,
        "label": "TxAckRequestedCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "26": {
        "id": 26,
        "cluster_id": 53,
        "label": "TxAckedCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "27": {
        "id": 27,
        "cluster_id": 53,
        "label": "TxNoAckRequestedCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "28": {
        "id": 28,
        "cluster_id": 53,
        "label": "TxDataCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "29": {
        "id": 29,
        "cluster_id": 53,
        "label": "TxDataPollCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "30": {
        "id": 30,
        "cluster_id": 53,
        "label": "TxBeaconCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "31": {
        "id": 31,
        "cluster_id": 53,
        "label": "TxBeaconRequestCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "32": {
        "id": 32,
        "cluster_id": 53,
        "label": "TxOtherCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "33": {
        "id": 33,
        "cluster_id": 53,
        "label": "TxRetryCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "34": {
        "id": 34,
        "cluster_id": 53,
        "label": "TxDirectMaxRetryExpiryCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "35": {
        "id": 35,
        "cluster_id": 53,
        "label": "TxIndirectMaxRetryExpiryCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "36": {
        "id": 36,
        "cluster_id": 53,
        "label": "TxErrCcaCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "37": {
        "id": 37,
        "cluster_id": 53,
        "label": "TxErrAbortCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "38": {
        "id": 38,
        "cluster_id": 53,
        "label": "TxErrBusyChannelCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "39": {
        "id": 39,
        "cluster_id": 53,
        "label": "RxTotalCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "40": {
        "id": 40,
        "cluster_id": 53,
        "label": "RxUnicastCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "41": {
        "id": 41,
        "cluster_id": 53,
        "label": "RxBroadcastCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "42": {
        "id": 42,
        "cluster_id": 53,
        "label": "RxDataCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "43": {
        "id": 43,
        "cluster_id": 53,
        "label": "RxDataPollCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "44": {
        "id": 44,
        "cluster_id": 53,
        "label": "RxBeaconCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "45": {
        "id": 45,
        "cluster_id": 53,
        "label": "RxBeaconRequestCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "46": {
        "id": 46,
        "cluster_id": 53,
        "label": "RxOtherCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "47": {
        "id": 47,
        "cluster_id": 53,
        "label": "RxAddressFilteredCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "48": {
        "id": 48,
        "cluster_id": 53,
        "label": "RxDestAddrFilteredCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "49": {
        "id": 49,
        "cluster_id": 53,
        "label": "RxDuplicatedCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "50": {
        "id": 50,
        "cluster_id": 53,
        "label": "RxErrNoFrameCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "51": {
        "id": 51,
        "cluster_id": 53,
        "label": "RxErrUnknownNeighborCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "52": {
        "id": 52,
        "cluster_id": 53,
        "label": "RxErrInvalidSrcAddrCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "53": {
        "id": 53,
        "cluster_id": 53,
        "label": "RxErrSecCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "54": {
        "id": 54,
        "cluster_id": 53,
        "label": "RxErrFcsCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "55": {
        "id": 55,
        "cluster_id": 53,
        "label": "RxErrOtherCount",
        "type": "Optional[uint32]",
        "writable": false
      },
      "56": {
        "id": 56,
        "cluster_id": 53,
        "label": "ActiveTimestamp",
        "type": "Optional[Nullable[uint64]]",
        "writable": false
      },
      "57": {
        "id": 57,
        "cluster_id": 53,
        "label": "PendingTimestamp",
        "type": "Optional[Nullable[uint64]]",
        "writable": false
      },
      "58": {
        "id": 58,
        "cluster_id": 53,
        "label": "Delay",
        "type": "Optional[Nullable[uint32]]",
        "writable": false
      },
      "59": {
        "id": 59,
        "cluster_id": 53,
        "label": "SecurityPolicy",
        "type": "Nullable[SecurityPolicy]",
        "writable": false
      },
      "60": {
        "id": 60,
        "cluster_id": 53,
        "label": "ChannelPage0Mask",
        "type": "Nullable[bytes]",
        "writable": false
      },
      "61": {
        "id": 61,
        "cluster_id": 53,
        "label": "OperationalDatasetComponents",
        "type": "Nullable[OperationalDatasetComponents]",
        "writable": false
      },
      "62": {
        "id": 62,
        "cluster_id": 53,
        "label": "ActiveNetworkFaultsList",
        "type": "List[NetworkFaultEnum]",
        "writable": false
      },
      "63": {
        "id": 63,
        "cluster_id": 53,
        "label": "ExtAddress",
        "type": "Optional[Nullable[uint64]]",
        "writable": false
      },
      "64": {
        "id": 64,
        "cluster_id": 53,
        "label": "Rloc16",
        "type": "Optional[Nullable[uint16]]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 53,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 53,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 53,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 53,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 53,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 53,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 53,
        "name": "ResetCounts",
        "label": "Reset Counts"
      }
    }
  },
  "54": {
    "id": 54,
    "label": "WiFiNetworkDiagnostics",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 54,
        "label": "Bssid",
        "type": "Nullable[bytes]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 54,
        "label": "SecurityType",
        "type": "Nullable[SecurityTypeEnum]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 54,
        "label": "WiFiVersion",
        "type": "Nullable[WiFiVersionEnum]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 54,
        "label": "ChannelNumber",
        "type": "Nullable[uint16]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 54,
        "label": "Rssi",
        "type": "Nullable[int8]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 54,
        "label": "BeaconLostCount",
        "type": "Optional[Nullable[uint32]]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 54,
        "label": "BeaconRxCount",
        "type": "Optional[Nullable[uint32]]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 54,
        "label": "PacketMulticastRxCount",
        "type": "Optional[Nullable[uint32]]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 54,
        "label": "PacketMulticastTxCount",
        "type": "Optional[Nullable[uint32]]",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 54,
        "label": "PacketUnicastRxCount",
        "type": "Optional[Nullable[uint32]]",
        "writable": false
      },
      "10": {
        "id": 10,
        "cluster_id": 54,
        "label": "PacketUnicastTxCount",
        "type": "Optional[Nullable[uint32]]",
        "writable": false
      },
      "11": {
        "id": 11,
        "cluster_id": 54,
        "label": "CurrentMaxRate",
        "type": "Optional[Nullable[uint64]]",
        "writable": false
      },
      "12": {
        "id": 12,
        "cluster_id": 54,
        "label": "OverrunCount",
        "type": "Optional[Nullable[uint64]]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 54,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 54,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 54,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 54,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 54,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 54,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 54,
        "name": "ResetCounts",
        "label": "Reset Counts"
      }
    }
  },
  "55": {
    "id": 55,
    "label": "EthernetNetworkDiagnostics",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 55,
        "label": "PhyRate",
        "type": "Optional[Nullable[PHYRateEnum]]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 55,
        "label": "FullDuplex",
        "type": "Optional[Nullable[bool]]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 55,
        "label": "PacketRxCount",
        "type": "Optional[uint64]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 55,
        "label": "PacketTxCount",
        "type": "Optional[uint64]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 55,
        "label": "TxErrCount",
        "type": "Optional[uint64]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 55,
        "label": "CollisionCount",
        "type": "Optional[uint64]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 55,
        "label": "OverrunCount",
        "type": "Optional[uint64]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 55,
        "label": "CarrierDetect",
        "type": "Optional[Nullable[bool]]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 55,
        "label": "TimeSinceReset",
        "type": "Optional[uint64]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 55,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 55,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 55,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 55,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 55,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 55,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 55,
        "name": "ResetCounts",
        "label": "Reset Counts"
      }
    }
  },
  "56": {
    "id": 56,
    "label": "TimeSynchronization",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 56,
        "label": "UtcTime",
        "type": "Nullable[epoch-us]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 56,
        "label": "Granularity",
        "type": "GranularityEnum",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 56,
        "label": "TimeSource",
        "type": "Optional[TimeSourceEnum]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 56,
        "label": "TrustedTimeSource",
        "type": "Optional[Nullable[TrustedTimeSourceStruct]]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 56,
        "label": "DefaultNtp",
        "type": "Optional[Nullable[string]]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 56,
        "label": "TimeZone",
        "type": "List[TimeZoneStruct]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 56,
        "label": "DstOffset",
        "type": "List[DSTOffsetStruct]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 56,
        "label": "LocalTime",
        "type": "Optional[Nullable[epoch-us]]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 56,
        "label": "TimeZoneDatabase",
        "type": "Optional[TimeZoneDatabaseEnum]",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 56,
        "label": "NtpServerAvailable",
        "type": "Optional[bool]",
        "writable": false
      },
      "10": {
        "id": 10,
        "cluster_id": 56,
        "label": "TimeZoneListMaxSize",
        "type": "Optional[uint8]",
        "writable": false
      },
      "11": {
        "id": 11,
        "cluster_id": 56,
        "label": "DstOffsetListMaxSize",
        "type": "Optional[uint8]",
        "writable": false
      },
      "12": {
        "id": 12,
        "cluster_id": 56,
        "label": "SupportsDnsResolve",
        "type": "Optional[bool]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 56,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 56,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 56,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 56,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 56,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 56,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 56,
        "name": "SetUtcTime",
        "label": "Set Utc Time"
      },
      "1": {
        "id": 1,
        "cluster_id": 56,
        "name": "SetTrustedTimeSource",
        "label": "Set Trusted Time Source"
      },
      "2": {
        "id": 2,
        "cluster_id": 56,
        "name": "SetTimeZone",
        "label": "Set Time Zone"
      },
      "4": {
        "id": 4,
        "cluster_id": 56,
        "name": "SetDstOffset",
        "label": "Set Dst Offset"
      },
      "5": {
        "id": 5,
        "cluster_id": 56,
        "name": "SetDefaultNtp",
        "label": "Set Default Ntp"
      }
    }
  },
  "57": {
    "id": 57,
    "label": "BridgedDeviceBasicInformation",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 57,
        "label": "DataModelRevision",
        "type": "Optional[unknown]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 57,
        "label": "VendorName",
        "type": "Optional[string]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 57,
        "label": "VendorId",
        "type": "Optional[unknown]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 57,
        "label": "ProductName",
        "type": "Optional[string]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 57,
        "label": "ProductId",
        "type": "Optional[unknown]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 57,
        "label": "NodeLabel",
        "type": "Optional[string]",
        "writable": true
      },
      "6": {
        "id": 6,
        "cluster_id": 57,
        "label": "Location",
        "type": "Optional[string]",
        "writable": true
      },
      "7": {
        "id": 7,
        "cluster_id": 57,
        "label": "HardwareVersion",
        "type": "Optional[unknown]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 57,
        "label": "HardwareVersionString",
        "type": "Optional[string]",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 57,
        "label": "SoftwareVersion",
        "type": "Optional[unknown]",
        "writable": false
      },
      "10": {
        "id": 10,
        "cluster_id": 57,
        "label": "SoftwareVersionString",
        "type": "Optional[string]",
        "writable": false
      },
      "11": {
        "id": 11,
        "cluster_id": 57,
        "label": "ManufacturingDate",
        "type": "Optional[string]",
        "writable": false
      },
      "12": {
        "id": 12,
        "cluster_id": 57,
        "label": "PartNumber",
        "type": "Optional[string]",
        "writable": false
      },
      "13": {
        "id": 13,
        "cluster_id": 57,
        "label": "ProductUrl",
        "type": "Optional[string]",
        "writable": false
      },
      "14": {
        "id": 14,
        "cluster_id": 57,
        "label": "ProductLabel",
        "type": "Optional[string]",
        "writable": false
      },
      "15": {
        "id": 15,
        "cluster_id": 57,
        "label": "SerialNumber",
        "type": "Optional[string]",
        "writable": false
      },
      "16": {
        "id": 16,
        "cluster_id": 57,
        "label": "LocalConfigDisabled",
        "type": "Optional[bool]",
        "writable": true
      },
      "17": {
        "id": 17,
        "cluster_id": 57,
        "label": "Reachable",
        "type": "bool",
        "writable": false
      },
      "18": {
        "id": 18,
        "cluster_id": 57,
        "label": "UniqueId",
        "type": "Optional[string]",
        "writable": false
      },
      "19": {
        "id": 19,
        "cluster_id": 57,
        "label": "CapabilityMinima",
        "type": "Optional[unknown]",
        "writable": false
      },
      "20": {
        "id": 20,
        "cluster_id": 57,
        "label": "ProductAppearance",
        "type": "Optional[unknown]",
        "writable": false
      },
      "21": {
        "id": 21,
        "cluster_id": 57,
        "label": "SpecificationVersion",
        "type": "Optional[unknown]",
        "writable": false
      },
      "22": {
        "id": 22,
        "cluster_id": 57,
        "label": "MaxPathsPerInvoke",
        "type": "Optional[unknown]",
        "writable": false
      },
      "24": {
        "id": 24,
        "cluster_id": 57,
        "label": "ConfigurationVersion",
        "type": "Optional[unknown]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 57,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 57,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 57,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 57,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 57,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 57,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "128": {
        "id": 128,
        "cluster_id": 57,
        "name": "KeepActive",
        "label": "Keep Active"
      }
    }
  },
  "59": {
    "id": 59,
    "label": "Switch",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 59,
        "label": "NumberOfPositions",
        "type": "uint8",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 59,
        "label": "CurrentPosition",
        "type": "uint8",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 59,
        "label": "MultiPressMax",
        "type": "Optional[uint8]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 59,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 59,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 59,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 59,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 59,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 59,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "60": {
    "id": 60,
    "label": "AdministratorCommissioning",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 60,
        "label": "WindowStatus",
        "type": "CommissioningWindowStatusEnum",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 60,
        "label": "AdminFabricIndex",
        "type": "Nullable[fabric-idx]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 60,
        "label": "AdminVendorId",
        "type": "Nullable[vendor-id]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 60,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 60,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 60,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 60,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 60,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 60,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 60,
        "name": "OpenCommissioningWindow",
        "label": "Open Commissioning Window"
      },
      "1": {
        "id": 1,
        "cluster_id": 60,
        "name": "OpenBasicCommissioningWindow",
        "label": "Open Basic Commissioning Window"
      },
      "2": {
        "id": 2,
        "cluster_id": 60,
        "name": "RevokeCommissioning",
        "label": "Revoke Commissioning"
      }
    }
  },
  "62": {
    "id": 62,
    "label": "OperationalCredentials",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 62,
        "label": "Nocs",
        "type": "List[NOCStruct]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 62,
        "label": "Fabrics",
        "type": "List[FabricDescriptorStruct]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 62,
        "label": "SupportedFabrics",
        "type": "uint8",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 62,
        "label": "CommissionedFabrics",
        "type": "uint8",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 62,
        "label": "TrustedRootCertificates",
        "type": "List[octstr]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 62,
        "label": "CurrentFabricIndex",
        "type": "fabric-idx",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 62,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 62,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 62,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 62,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 62,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 62,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 62,
        "name": "AttestationRequest",
        "label": "Attestation Request"
      },
      "2": {
        "id": 2,
        "cluster_id": 62,
        "name": "CertificateChainRequest",
        "label": "Certificate Chain Request"
      },
      "4": {
        "id": 4,
        "cluster_id": 62,
        "name": "CsrRequest",
        "label": "Csr Request"
      },
      "6": {
        "id": 6,
        "cluster_id": 62,
        "name": "AddNoc",
        "label": "Add Noc"
      },
      "7": {
        "id": 7,
        "cluster_id": 62,
        "name": "UpdateNoc",
        "label": "Update Noc"
      },
      "9": {
        "id": 9,
        "cluster_id": 62,
        "name": "UpdateFabricLabel",
        "label": "Update Fabric Label"
      },
      "10": {
        "id": 10,
        "cluster_id": 62,
        "name": "RemoveFabric",
        "label": "Remove Fabric"
      },
      "11": {
        "id": 11,
        "cluster_id": 62,
        "name": "AddTrustedRootCertificate",
        "label": "Add Trusted Root Certificate"
      },
      "12": {
        "id": 12,
        "cluster_id": 62,
        "name": "SetVidVerificationStatement",
        "label": "Set Vid Verification Statement"
      },
      "13": {
        "id": 13,
        "cluster_id": 62,
        "name": "SignVidVerificationRequest",
        "label": "Sign Vid Verification Request"
      }
    }
  },
  "63": {
    "id": 63,
    "label": "GroupKeyManagement",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 63,
        "label": "GroupKeyMap",
        "type": "List[GroupKeyMapStruct]",
        "writable": true
      },
      "1": {
        "id": 1,
        "cluster_id": 63,
        "label": "GroupTable",
        "type": "List[GroupInfoMapStruct]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 63,
        "label": "MaxGroupsPerFabric",
        "type": "uint16",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 63,
        "label": "MaxGroupKeysPerFabric",
        "type": "uint16",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 63,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 63,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 63,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 63,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 63,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 63,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 63,
        "name": "KeySetWrite",
        "label": "Key Set Write"
      },
      "1": {
        "id": 1,
        "cluster_id": 63,
        "name": "KeySetRead",
        "label": "Key Set Read"
      },
      "3": {
        "id": 3,
        "cluster_id": 63,
        "name": "KeySetRemove",
        "label": "Key Set Remove"
      },
      "4": {
        "id": 4,
        "cluster_id": 63,
        "name": "KeySetReadAllIndices",
        "label": "Key Set Read All Indices"
      }
    }
  },
  "64": {
    "id": 64,
    "label": "FixedLabel",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 64,
        "label": "LabelList",
        "type": "List[LabelStruct]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 64,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 64,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 64,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 64,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 64,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 64,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "65": {
    "id": 65,
    "label": "UserLabel",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 65,
        "label": "LabelList",
        "type": "List[LabelStruct]",
        "writable": true
      },
      "65528": {
        "id": 65528,
        "cluster_id": 65,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 65,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 65,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 65,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 65,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 65,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "69": {
    "id": 69,
    "label": "BooleanState",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 69,
        "label": "StateValue",
        "type": "bool",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 69,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 69,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 69,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 69,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 69,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 69,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "70": {
    "id": 70,
    "label": "IcdManagement",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 70,
        "label": "IdleModeDuration",
        "type": "uint32",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 70,
        "label": "ActiveModeDuration",
        "type": "uint32",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 70,
        "label": "ActiveModeThreshold",
        "type": "uint16",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 70,
        "label": "RegisteredClients",
        "type": "List[MonitoringRegistrationStruct]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 70,
        "label": "IcdCounter",
        "type": "Optional[uint32]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 70,
        "label": "ClientsSupportedPerFabric",
        "type": "Optional[uint16]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 70,
        "label": "UserActiveModeTriggerHint",
        "type": "Optional[UserActiveModeTriggerBitmap]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 70,
        "label": "UserActiveModeTriggerInstruction",
        "type": "Optional[string]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 70,
        "label": "OperatingMode",
        "type": "Optional[OperatingModeEnum]",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 70,
        "label": "MaximumCheckInBackoff",
        "type": "Optional[uint32]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 70,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 70,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 70,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 70,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 70,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 70,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 70,
        "name": "RegisterClient",
        "label": "Register Client"
      },
      "2": {
        "id": 2,
        "cluster_id": 70,
        "name": "UnregisterClient",
        "label": "Unregister Client"
      },
      "3": {
        "id": 3,
        "cluster_id": 70,
        "name": "StayActiveRequest",
        "label": "Stay Active Request"
      }
    }
  },
  "72": {
    "id": 72,
    "label": "OvenCavityOperationalState",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 72,
        "label": "PhaseList",
        "type": "List[string]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 72,
        "label": "CurrentPhase",
        "type": "Nullable[uint8]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 72,
        "label": "CountdownTime",
        "type": "Optional[Nullable[elapsed-s]]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 72,
        "label": "OperationalStateList",
        "type": "List[OperationalStateStruct]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 72,
        "label": "OperationalState",
        "type": "OperationalStateEnum",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 72,
        "label": "OperationalError",
        "type": "ErrorStateStruct",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 72,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 72,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 72,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 72,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 72,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 72,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 72,
        "name": "Pause",
        "label": "Pause"
      },
      "1": {
        "id": 1,
        "cluster_id": 72,
        "name": "Stop",
        "label": "Stop"
      },
      "2": {
        "id": 2,
        "cluster_id": 72,
        "name": "Start",
        "label": "Start"
      },
      "3": {
        "id": 3,
        "cluster_id": 72,
        "name": "Resume",
        "label": "Resume"
      }
    }
  },
  "73": {
    "id": 73,
    "label": "OvenMode",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 73,
        "label": "SupportedModes",
        "type": "unknown",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 73,
        "label": "CurrentMode",
        "type": "unknown",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 73,
        "label": "StartUpMode",
        "type": "Optional[Nullable[unknown]]",
        "writable": true
      },
      "3": {
        "id": 3,
        "cluster_id": 73,
        "label": "OnMode",
        "type": "Optional[Nullable[unknown]]",
        "writable": true
      },
      "65528": {
        "id": 65528,
        "cluster_id": 73,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 73,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 73,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 73,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 73,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 73,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 73,
        "name": "ChangeToMode",
        "label": "Change To Mode"
      }
    }
  },
  "74": {
    "id": 74,
    "label": "LaundryDryerControls",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 74,
        "label": "SupportedDrynessLevels",
        "type": "List[DrynessLevelEnum]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 74,
        "label": "SelectedDrynessLevel",
        "type": "Nullable[DrynessLevelEnum]",
        "writable": true
      },
      "65528": {
        "id": 65528,
        "cluster_id": 74,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 74,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 74,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 74,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 74,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 74,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "80": {
    "id": 80,
    "label": "ModeSelect",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 80,
        "label": "Description",
        "type": "string",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 80,
        "label": "StandardNamespace",
        "type": "Nullable[namespace]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 80,
        "label": "SupportedModes",
        "type": "List[ModeOptionStruct]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 80,
        "label": "CurrentMode",
        "type": "uint8",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 80,
        "label": "StartUpMode",
        "type": "Optional[Nullable[uint8]]",
        "writable": true
      },
      "5": {
        "id": 5,
        "cluster_id": 80,
        "label": "OnMode",
        "type": "Optional[Nullable[uint8]]",
        "writable": true
      },
      "65528": {
        "id": 65528,
        "cluster_id": 80,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 80,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 80,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 80,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 80,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 80,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 80,
        "name": "ChangeToMode",
        "label": "Change To Mode"
      }
    }
  },
  "81": {
    "id": 81,
    "label": "LaundryWasherMode",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 81,
        "label": "SupportedModes",
        "type": "unknown",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 81,
        "label": "CurrentMode",
        "type": "unknown",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 81,
        "label": "StartUpMode",
        "type": "Optional[Nullable[unknown]]",
        "writable": true
      },
      "3": {
        "id": 3,
        "cluster_id": 81,
        "label": "OnMode",
        "type": "Optional[Nullable[unknown]]",
        "writable": true
      },
      "65528": {
        "id": 65528,
        "cluster_id": 81,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 81,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 81,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 81,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 81,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 81,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 81,
        "name": "ChangeToMode",
        "label": "Change To Mode"
      }
    }
  },
  "82": {
    "id": 82,
    "label": "RefrigeratorAndTemperatureControlledCabinetMode",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 82,
        "label": "SupportedModes",
        "type": "unknown",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 82,
        "label": "CurrentMode",
        "type": "unknown",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 82,
        "label": "StartUpMode",
        "type": "Optional[Nullable[unknown]]",
        "writable": true
      },
      "3": {
        "id": 3,
        "cluster_id": 82,
        "label": "OnMode",
        "type": "Optional[Nullable[unknown]]",
        "writable": true
      },
      "65528": {
        "id": 65528,
        "cluster_id": 82,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 82,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 82,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 82,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 82,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 82,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 82,
        "name": "ChangeToMode",
        "label": "Change To Mode"
      }
    }
  },
  "83": {
    "id": 83,
    "label": "LaundryWasherControls",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 83,
        "label": "SpinSpeeds",
        "type": "List[string]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 83,
        "label": "SpinSpeedCurrent",
        "type": "Optional[Nullable[uint8]]",
        "writable": true
      },
      "2": {
        "id": 2,
        "cluster_id": 83,
        "label": "NumberOfRinses",
        "type": "Optional[NumberOfRinsesEnum]",
        "writable": true
      },
      "3": {
        "id": 3,
        "cluster_id": 83,
        "label": "SupportedRinses",
        "type": "List[NumberOfRinsesEnum]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 83,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 83,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 83,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 83,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 83,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 83,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "84": {
    "id": 84,
    "label": "RvcRunMode",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 84,
        "label": "SupportedModes",
        "type": "unknown",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 84,
        "label": "CurrentMode",
        "type": "unknown",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 84,
        "label": "StartUpMode",
        "type": "Optional[Nullable[unknown]]",
        "writable": true
      },
      "3": {
        "id": 3,
        "cluster_id": 84,
        "label": "OnMode",
        "type": "Optional[Nullable[unknown]]",
        "writable": true
      },
      "65528": {
        "id": 65528,
        "cluster_id": 84,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 84,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 84,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 84,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 84,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 84,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 84,
        "name": "ChangeToMode",
        "label": "Change To Mode"
      }
    }
  },
  "85": {
    "id": 85,
    "label": "RvcCleanMode",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 85,
        "label": "SupportedModes",
        "type": "unknown",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 85,
        "label": "CurrentMode",
        "type": "unknown",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 85,
        "label": "StartUpMode",
        "type": "Optional[Nullable[unknown]]",
        "writable": true
      },
      "3": {
        "id": 3,
        "cluster_id": 85,
        "label": "OnMode",
        "type": "Optional[Nullable[unknown]]",
        "writable": true
      },
      "65528": {
        "id": 65528,
        "cluster_id": 85,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 85,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 85,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 85,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 85,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 85,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 85,
        "name": "ChangeToMode",
        "label": "Change To Mode"
      }
    }
  },
  "86": {
    "id": 86,
    "label": "TemperatureControl",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 86,
        "label": "TemperatureSetpoint",
        "type": "Optional[temperature]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 86,
        "label": "MinTemperature",
        "type": "Optional[temperature]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 86,
        "label": "MaxTemperature",
        "type": "Optional[temperature]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 86,
        "label": "Step",
        "type": "Optional[temperature]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 86,
        "label": "SelectedTemperatureLevel",
        "type": "Optional[uint8]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 86,
        "label": "SupportedTemperatureLevels",
        "type": "List[string]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 86,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 86,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 86,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 86,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 86,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 86,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 86,
        "name": "SetTemperature",
        "label": "Set Temperature"
      }
    }
  },
  "87": {
    "id": 87,
    "label": "RefrigeratorAlarm",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 87,
        "label": "Mask",
        "type": "AlarmBitmap",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 87,
        "label": "Latch",
        "type": "Optional[AlarmBitmap]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 87,
        "label": "State",
        "type": "AlarmBitmap",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 87,
        "label": "Supported",
        "type": "AlarmBitmap",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 87,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 87,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 87,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 87,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 87,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 87,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 87,
        "name": "Reset",
        "label": "Reset"
      },
      "1": {
        "id": 1,
        "cluster_id": 87,
        "name": "ModifyEnabledAlarms",
        "label": "Modify Enabled Alarms"
      }
    }
  },
  "89": {
    "id": 89,
    "label": "DishwasherMode",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 89,
        "label": "SupportedModes",
        "type": "unknown",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 89,
        "label": "CurrentMode",
        "type": "unknown",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 89,
        "label": "StartUpMode",
        "type": "Optional[Nullable[unknown]]",
        "writable": true
      },
      "3": {
        "id": 3,
        "cluster_id": 89,
        "label": "OnMode",
        "type": "Optional[Nullable[unknown]]",
        "writable": true
      },
      "65528": {
        "id": 65528,
        "cluster_id": 89,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 89,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 89,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 89,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 89,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 89,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 89,
        "name": "ChangeToMode",
        "label": "Change To Mode"
      }
    }
  },
  "91": {
    "id": 91,
    "label": "AirQuality",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 91,
        "label": "AirQuality",
        "type": "AirQualityEnum",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 91,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 91,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 91,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 91,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 91,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 91,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "92": {
    "id": 92,
    "label": "SmokeCoAlarm",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 92,
        "label": "ExpressedState",
        "type": "ExpressedStateEnum",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 92,
        "label": "SmokeState",
        "type": "Optional[AlarmStateEnum]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 92,
        "label": "CoState",
        "type": "Optional[AlarmStateEnum]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 92,
        "label": "BatteryAlert",
        "type": "AlarmStateEnum",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 92,
        "label": "DeviceMuted",
        "type": "Optional[MuteStateEnum]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 92,
        "label": "TestInProgress",
        "type": "bool",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 92,
        "label": "HardwareFaultAlert",
        "type": "bool",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 92,
        "label": "EndOfServiceAlert",
        "type": "EndOfServiceEnum",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 92,
        "label": "InterconnectSmokeAlarm",
        "type": "Optional[AlarmStateEnum]",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 92,
        "label": "InterconnectCoAlarm",
        "type": "Optional[AlarmStateEnum]",
        "writable": false
      },
      "10": {
        "id": 10,
        "cluster_id": 92,
        "label": "ContaminationState",
        "type": "Optional[ContaminationStateEnum]",
        "writable": false
      },
      "11": {
        "id": 11,
        "cluster_id": 92,
        "label": "SmokeSensitivityLevel",
        "type": "Optional[SensitivityEnum]",
        "writable": true
      },
      "12": {
        "id": 12,
        "cluster_id": 92,
        "label": "ExpiryDate",
        "type": "Optional[epoch-s]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 92,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 92,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 92,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 92,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 92,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 92,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 92,
        "name": "SelfTestRequest",
        "label": "Self Test Request"
      }
    }
  },
  "93": {
    "id": 93,
    "label": "DishwasherAlarm",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 93,
        "label": "Mask",
        "type": "AlarmBitmap",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 93,
        "label": "Latch",
        "type": "Optional[AlarmBitmap]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 93,
        "label": "State",
        "type": "AlarmBitmap",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 93,
        "label": "Supported",
        "type": "AlarmBitmap",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 93,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 93,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 93,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 93,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 93,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 93,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 93,
        "name": "Reset",
        "label": "Reset"
      },
      "1": {
        "id": 1,
        "cluster_id": 93,
        "name": "ModifyEnabledAlarms",
        "label": "Modify Enabled Alarms"
      }
    }
  },
  "94": {
    "id": 94,
    "label": "MicrowaveOvenMode",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 94,
        "label": "SupportedModes",
        "type": "unknown",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 94,
        "label": "CurrentMode",
        "type": "unknown",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 94,
        "label": "StartUpMode",
        "type": "Optional[Nullable[unknown]]",
        "writable": true
      },
      "3": {
        "id": 3,
        "cluster_id": 94,
        "label": "OnMode",
        "type": "Optional[Nullable[unknown]]",
        "writable": true
      },
      "65528": {
        "id": 65528,
        "cluster_id": 94,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 94,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 94,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 94,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 94,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 94,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 94,
        "name": "ChangeToMode",
        "label": "Change To Mode"
      }
    }
  },
  "95": {
    "id": 95,
    "label": "MicrowaveOvenControl",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 95,
        "label": "CookTime",
        "type": "elapsed-s",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 95,
        "label": "MaxCookTime",
        "type": "elapsed-s",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 95,
        "label": "PowerSetting",
        "type": "Optional[uint8]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 95,
        "label": "MinPower",
        "type": "Optional[uint8]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 95,
        "label": "MaxPower",
        "type": "Optional[uint8]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 95,
        "label": "PowerStep",
        "type": "Optional[uint8]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 95,
        "label": "SupportedWatts",
        "type": "List[uint16]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 95,
        "label": "SelectedWattIndex",
        "type": "Optional[uint8]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 95,
        "label": "WattRating",
        "type": "Optional[uint16]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 95,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 95,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 95,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 95,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 95,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 95,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 95,
        "name": "SetCookingParameters",
        "label": "Set Cooking Parameters"
      },
      "1": {
        "id": 1,
        "cluster_id": 95,
        "name": "AddMoreTime",
        "label": "Add More Time"
      }
    }
  },
  "96": {
    "id": 96,
    "label": "OperationalState",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 96,
        "label": "PhaseList",
        "type": "List[string]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 96,
        "label": "CurrentPhase",
        "type": "Nullable[uint8]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 96,
        "label": "CountdownTime",
        "type": "Optional[Nullable[elapsed-s]]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 96,
        "label": "OperationalStateList",
        "type": "List[OperationalStateStruct]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 96,
        "label": "OperationalState",
        "type": "OperationalStateEnum",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 96,
        "label": "OperationalError",
        "type": "ErrorStateStruct",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 96,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 96,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 96,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 96,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 96,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 96,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 96,
        "name": "Pause",
        "label": "Pause"
      },
      "1": {
        "id": 1,
        "cluster_id": 96,
        "name": "Stop",
        "label": "Stop"
      },
      "2": {
        "id": 2,
        "cluster_id": 96,
        "name": "Start",
        "label": "Start"
      },
      "3": {
        "id": 3,
        "cluster_id": 96,
        "name": "Resume",
        "label": "Resume"
      }
    }
  },
  "97": {
    "id": 97,
    "label": "RvcOperationalState",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 97,
        "label": "PhaseList",
        "type": "List[string]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 97,
        "label": "CurrentPhase",
        "type": "Nullable[uint8]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 97,
        "label": "CountdownTime",
        "type": "Optional[Nullable[elapsed-s]]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 97,
        "label": "OperationalStateList",
        "type": "List[OperationalStateStruct]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 97,
        "label": "OperationalState",
        "type": "OperationalStateEnum",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 97,
        "label": "OperationalError",
        "type": "ErrorStateStruct",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 97,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 97,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 97,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 97,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 97,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 97,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 97,
        "name": "Pause",
        "label": "Pause"
      },
      "1": {
        "id": 1,
        "cluster_id": 97,
        "name": "Stop",
        "label": "Stop"
      },
      "2": {
        "id": 2,
        "cluster_id": 97,
        "name": "Start",
        "label": "Start"
      },
      "3": {
        "id": 3,
        "cluster_id": 97,
        "name": "Resume",
        "label": "Resume"
      },
      "128": {
        "id": 128,
        "cluster_id": 97,
        "name": "GoHome",
        "label": "Go Home"
      }
    }
  },
  "98": {
    "id": 98,
    "label": "ScenesManagement",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 98,
        "label": "DoNotUse",
        "type": "Optional[unknown]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 98,
        "label": "SceneTableSize",
        "type": "uint16",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 98,
        "label": "FabricSceneInfo",
        "type": "List[SceneInfoStruct]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 98,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 98,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 98,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 98,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 98,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 98,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 98,
        "name": "AddScene",
        "label": "Add Scene"
      },
      "1": {
        "id": 1,
        "cluster_id": 98,
        "name": "ViewScene",
        "label": "View Scene"
      },
      "2": {
        "id": 2,
        "cluster_id": 98,
        "name": "RemoveScene",
        "label": "Remove Scene"
      },
      "3": {
        "id": 3,
        "cluster_id": 98,
        "name": "RemoveAllScenes",
        "label": "Remove All Scenes"
      },
      "4": {
        "id": 4,
        "cluster_id": 98,
        "name": "StoreScene",
        "label": "Store Scene"
      },
      "5": {
        "id": 5,
        "cluster_id": 98,
        "name": "RecallScene",
        "label": "Recall Scene"
      },
      "6": {
        "id": 6,
        "cluster_id": 98,
        "name": "GetSceneMembership",
        "label": "Get Scene Membership"
      },
      "64": {
        "id": 64,
        "cluster_id": 98,
        "name": "CopyScene",
        "label": "Copy Scene"
      }
    }
  },
  "113": {
    "id": 113,
    "label": "HepaFilterMonitoring",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 113,
        "label": "Condition",
        "type": "Optional[percent]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 113,
        "label": "DegradationDirection",
        "type": "Optional[DegradationDirectionEnum]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 113,
        "label": "ChangeIndication",
        "type": "ChangeIndicationEnum",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 113,
        "label": "InPlaceIndicator",
        "type": "Optional[bool]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 113,
        "label": "LastChangedTime",
        "type": "Optional[Nullable[epoch-s]]",
        "writable": true
      },
      "5": {
        "id": 5,
        "cluster_id": 113,
        "label": "ReplacementProductList",
        "type": "List[ReplacementProductStruct]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 113,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 113,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 113,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 113,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 113,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 113,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 113,
        "name": "ResetCondition",
        "label": "Reset Condition"
      }
    }
  },
  "114": {
    "id": 114,
    "label": "ActivatedCarbonFilterMonitoring",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 114,
        "label": "Condition",
        "type": "Optional[percent]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 114,
        "label": "DegradationDirection",
        "type": "Optional[DegradationDirectionEnum]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 114,
        "label": "ChangeIndication",
        "type": "ChangeIndicationEnum",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 114,
        "label": "InPlaceIndicator",
        "type": "Optional[bool]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 114,
        "label": "LastChangedTime",
        "type": "Optional[Nullable[epoch-s]]",
        "writable": true
      },
      "5": {
        "id": 5,
        "cluster_id": 114,
        "label": "ReplacementProductList",
        "type": "List[ReplacementProductStruct]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 114,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 114,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 114,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 114,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 114,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 114,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 114,
        "name": "ResetCondition",
        "label": "Reset Condition"
      }
    }
  },
  "121": {
    "id": 121,
    "label": "WaterTankLevelMonitoring",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 121,
        "label": "Condition",
        "type": "Optional[percent]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 121,
        "label": "DegradationDirection",
        "type": "Optional[DegradationDirectionEnum]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 121,
        "label": "ChangeIndication",
        "type": "ChangeIndicationEnum",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 121,
        "label": "InPlaceIndicator",
        "type": "Optional[bool]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 121,
        "label": "LastChangedTime",
        "type": "Optional[Nullable[epoch-s]]",
        "writable": true
      },
      "5": {
        "id": 5,
        "cluster_id": 121,
        "label": "ReplacementProductList",
        "type": "List[ReplacementProductStruct]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 121,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 121,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 121,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 121,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 121,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 121,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 121,
        "name": "ResetCondition",
        "label": "Reset Condition"
      }
    }
  },
  "128": {
    "id": 128,
    "label": "BooleanStateConfiguration",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 128,
        "label": "CurrentSensitivityLevel",
        "type": "Optional[uint8]",
        "writable": true
      },
      "1": {
        "id": 1,
        "cluster_id": 128,
        "label": "SupportedSensitivityLevels",
        "type": "Optional[uint8]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 128,
        "label": "DefaultSensitivityLevel",
        "type": "Optional[uint8]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 128,
        "label": "AlarmsActive",
        "type": "Optional[AlarmModeBitmap]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 128,
        "label": "AlarmsSuppressed",
        "type": "Optional[AlarmModeBitmap]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 128,
        "label": "AlarmsEnabled",
        "type": "Optional[AlarmModeBitmap]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 128,
        "label": "AlarmsSupported",
        "type": "Optional[AlarmModeBitmap]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 128,
        "label": "SensorFault",
        "type": "Optional[SensorFaultBitmap]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 128,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 128,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 128,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 128,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 128,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 128,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 128,
        "name": "SuppressAlarm",
        "label": "Suppress Alarm"
      },
      "1": {
        "id": 1,
        "cluster_id": 128,
        "name": "EnableDisableAlarm",
        "label": "Enable Disable Alarm"
      }
    }
  },
  "129": {
    "id": 129,
    "label": "ValveConfigurationAndControl",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 129,
        "label": "OpenDuration",
        "type": "Nullable[elapsed-s]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 129,
        "label": "DefaultOpenDuration",
        "type": "Nullable[elapsed-s]",
        "writable": true
      },
      "2": {
        "id": 2,
        "cluster_id": 129,
        "label": "AutoCloseTime",
        "type": "Optional[Nullable[epoch-us]]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 129,
        "label": "RemainingDuration",
        "type": "Nullable[elapsed-s]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 129,
        "label": "CurrentState",
        "type": "Nullable[ValveStateEnum]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 129,
        "label": "TargetState",
        "type": "Nullable[ValveStateEnum]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 129,
        "label": "CurrentLevel",
        "type": "Optional[Nullable[percent]]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 129,
        "label": "TargetLevel",
        "type": "Optional[Nullable[percent]]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 129,
        "label": "DefaultOpenLevel",
        "type": "Optional[percent]",
        "writable": true
      },
      "9": {
        "id": 9,
        "cluster_id": 129,
        "label": "ValveFault",
        "type": "Optional[ValveFaultBitmap]",
        "writable": false
      },
      "10": {
        "id": 10,
        "cluster_id": 129,
        "label": "LevelStep",
        "type": "Optional[uint8]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 129,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 129,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 129,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 129,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 129,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 129,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 129,
        "name": "Open",
        "label": "Open"
      },
      "1": {
        "id": 1,
        "cluster_id": 129,
        "name": "Close",
        "label": "Close"
      }
    }
  },
  "144": {
    "id": 144,
    "label": "ElectricalPowerMeasurement",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 144,
        "label": "PowerMode",
        "type": "PowerModeEnum",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 144,
        "label": "NumberOfMeasurementTypes",
        "type": "uint8",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 144,
        "label": "Accuracy",
        "type": "List[MeasurementAccuracyStruct]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 144,
        "label": "Ranges",
        "type": "List[MeasurementRangeStruct]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 144,
        "label": "Voltage",
        "type": "Optional[Nullable[voltage-mV]]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 144,
        "label": "ActiveCurrent",
        "type": "Optional[Nullable[amperage-mA]]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 144,
        "label": "ReactiveCurrent",
        "type": "Optional[Nullable[amperage-mA]]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 144,
        "label": "ApparentCurrent",
        "type": "Optional[Nullable[amperage-mA]]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 144,
        "label": "ActivePower",
        "type": "Nullable[power-mW]",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 144,
        "label": "ReactivePower",
        "type": "Optional[Nullable[power-mVAR]]",
        "writable": false
      },
      "10": {
        "id": 10,
        "cluster_id": 144,
        "label": "ApparentPower",
        "type": "Optional[Nullable[power-mVA]]",
        "writable": false
      },
      "11": {
        "id": 11,
        "cluster_id": 144,
        "label": "RmsVoltage",
        "type": "Optional[Nullable[voltage-mV]]",
        "writable": false
      },
      "12": {
        "id": 12,
        "cluster_id": 144,
        "label": "RmsCurrent",
        "type": "Optional[Nullable[amperage-mA]]",
        "writable": false
      },
      "13": {
        "id": 13,
        "cluster_id": 144,
        "label": "RmsPower",
        "type": "Optional[Nullable[power-mW]]",
        "writable": false
      },
      "14": {
        "id": 14,
        "cluster_id": 144,
        "label": "Frequency",
        "type": "Optional[Nullable[int64]]",
        "writable": false
      },
      "15": {
        "id": 15,
        "cluster_id": 144,
        "label": "HarmonicCurrents",
        "type": "List[HarmonicMeasurementStruct]",
        "writable": false
      },
      "16": {
        "id": 16,
        "cluster_id": 144,
        "label": "HarmonicPhases",
        "type": "List[HarmonicMeasurementStruct]",
        "writable": false
      },
      "17": {
        "id": 17,
        "cluster_id": 144,
        "label": "PowerFactor",
        "type": "Optional[Nullable[int64]]",
        "writable": false
      },
      "18": {
        "id": 18,
        "cluster_id": 144,
        "label": "NeutralCurrent",
        "type": "Optional[Nullable[amperage-mA]]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 144,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 144,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 144,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 144,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 144,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 144,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "145": {
    "id": 145,
    "label": "ElectricalEnergyMeasurement",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 145,
        "label": "Accuracy",
        "type": "MeasurementAccuracyStruct",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 145,
        "label": "CumulativeEnergyImported",
        "type": "Optional[Nullable[EnergyMeasurementStruct]]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 145,
        "label": "CumulativeEnergyExported",
        "type": "Optional[Nullable[EnergyMeasurementStruct]]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 145,
        "label": "PeriodicEnergyImported",
        "type": "Optional[Nullable[EnergyMeasurementStruct]]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 145,
        "label": "PeriodicEnergyExported",
        "type": "Optional[Nullable[EnergyMeasurementStruct]]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 145,
        "label": "CumulativeEnergyReset",
        "type": "Optional[Nullable[CumulativeEnergyResetStruct]]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 145,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 145,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 145,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 145,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 145,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 145,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "148": {
    "id": 148,
    "label": "WaterHeaterManagement",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 148,
        "label": "HeaterTypes",
        "type": "WaterHeaterHeatSourceBitmap",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 148,
        "label": "HeatDemand",
        "type": "WaterHeaterHeatSourceBitmap",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 148,
        "label": "TankVolume",
        "type": "Optional[uint16]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 148,
        "label": "EstimatedHeatRequired",
        "type": "Optional[energy-mWh]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 148,
        "label": "TankPercentage",
        "type": "Optional[percent]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 148,
        "label": "BoostState",
        "type": "BoostStateEnum",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 148,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 148,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 148,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 148,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 148,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 148,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 148,
        "name": "Boost",
        "label": "Boost"
      },
      "1": {
        "id": 1,
        "cluster_id": 148,
        "name": "CancelBoost",
        "label": "Cancel Boost"
      }
    }
  },
  "149": {
    "id": 149,
    "label": "CommodityPrice",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 149,
        "label": "TariffUnit",
        "type": "TariffUnitEnum",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 149,
        "label": "Currency",
        "type": "Nullable[currency]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 149,
        "label": "CurrentPrice",
        "type": "Nullable[CommodityPriceStruct]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 149,
        "label": "PriceForecast",
        "type": "List[CommodityPriceStruct]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 149,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 149,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 149,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 149,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 149,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 149,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 149,
        "name": "GetDetailedPriceRequest",
        "label": "Get Detailed Price Request"
      },
      "2": {
        "id": 2,
        "cluster_id": 149,
        "name": "GetDetailedForecastRequest",
        "label": "Get Detailed Forecast Request"
      }
    }
  },
  "151": {
    "id": 151,
    "label": "Messages",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 151,
        "label": "Messages",
        "type": "List[MessageStruct]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 151,
        "label": "ActiveMessageIDs",
        "type": "List[MessageID]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 151,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 151,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 151,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 151,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 151,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 151,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 151,
        "name": "PresentMessagesRequest",
        "label": "Present Messages Request"
      },
      "1": {
        "id": 1,
        "cluster_id": 151,
        "name": "CancelMessagesRequest",
        "label": "Cancel Messages Request"
      }
    }
  },
  "152": {
    "id": 152,
    "label": "DeviceEnergyManagement",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 152,
        "label": "EsaType",
        "type": "ESATypeEnum",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 152,
        "label": "EsaCanGenerate",
        "type": "bool",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 152,
        "label": "EsaState",
        "type": "ESAStateEnum",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 152,
        "label": "AbsMinPower",
        "type": "power-mW",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 152,
        "label": "AbsMaxPower",
        "type": "power-mW",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 152,
        "label": "PowerAdjustmentCapability",
        "type": "Optional[Nullable[PowerAdjustCapabilityStruct]]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 152,
        "label": "Forecast",
        "type": "Optional[Nullable[ForecastStruct]]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 152,
        "label": "OptOutState",
        "type": "Optional[OptOutStateEnum]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 152,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 152,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 152,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 152,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 152,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 152,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 152,
        "name": "PowerAdjustRequest",
        "label": "Power Adjust Request"
      },
      "1": {
        "id": 1,
        "cluster_id": 152,
        "name": "CancelPowerAdjustRequest",
        "label": "Cancel Power Adjust Request"
      },
      "2": {
        "id": 2,
        "cluster_id": 152,
        "name": "StartTimeAdjustRequest",
        "label": "Start Time Adjust Request"
      },
      "3": {
        "id": 3,
        "cluster_id": 152,
        "name": "PauseRequest",
        "label": "Pause Request"
      },
      "4": {
        "id": 4,
        "cluster_id": 152,
        "name": "ResumeRequest",
        "label": "Resume Request"
      },
      "5": {
        "id": 5,
        "cluster_id": 152,
        "name": "ModifyForecastRequest",
        "label": "Modify Forecast Request"
      },
      "6": {
        "id": 6,
        "cluster_id": 152,
        "name": "RequestConstraintBasedForecast",
        "label": "Request Constraint Based Forecast"
      },
      "7": {
        "id": 7,
        "cluster_id": 152,
        "name": "CancelRequest",
        "label": "Cancel Request"
      }
    }
  },
  "153": {
    "id": 153,
    "label": "EnergyEvse",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 153,
        "label": "State",
        "type": "Nullable[StateEnum]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 153,
        "label": "SupplyState",
        "type": "SupplyStateEnum",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 153,
        "label": "FaultState",
        "type": "FaultStateEnum",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 153,
        "label": "ChargingEnabledUntil",
        "type": "Nullable[epoch-s]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 153,
        "label": "DischargingEnabledUntil",
        "type": "Optional[Nullable[epoch-s]]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 153,
        "label": "CircuitCapacity",
        "type": "amperage-mA",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 153,
        "label": "MinimumChargeCurrent",
        "type": "amperage-mA",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 153,
        "label": "MaximumChargeCurrent",
        "type": "amperage-mA",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 153,
        "label": "MaximumDischargeCurrent",
        "type": "Optional[amperage-mA]",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 153,
        "label": "UserMaximumChargeCurrent",
        "type": "Optional[amperage-mA]",
        "writable": true
      },
      "10": {
        "id": 10,
        "cluster_id": 153,
        "label": "RandomizationDelayWindow",
        "type": "Optional[elapsed-s]",
        "writable": true
      },
      "35": {
        "id": 35,
        "cluster_id": 153,
        "label": "NextChargeStartTime",
        "type": "Optional[Nullable[epoch-s]]",
        "writable": false
      },
      "36": {
        "id": 36,
        "cluster_id": 153,
        "label": "NextChargeTargetTime",
        "type": "Optional[Nullable[epoch-s]]",
        "writable": false
      },
      "37": {
        "id": 37,
        "cluster_id": 153,
        "label": "NextChargeRequiredEnergy",
        "type": "Optional[Nullable[energy-mWh]]",
        "writable": false
      },
      "38": {
        "id": 38,
        "cluster_id": 153,
        "label": "NextChargeTargetSoC",
        "type": "Optional[Nullable[percent]]",
        "writable": false
      },
      "39": {
        "id": 39,
        "cluster_id": 153,
        "label": "ApproximateEvEfficiency",
        "type": "Optional[Nullable[uint16]]",
        "writable": true
      },
      "48": {
        "id": 48,
        "cluster_id": 153,
        "label": "StateOfCharge",
        "type": "Optional[Nullable[percent]]",
        "writable": false
      },
      "49": {
        "id": 49,
        "cluster_id": 153,
        "label": "BatteryCapacity",
        "type": "Optional[Nullable[energy-mWh]]",
        "writable": false
      },
      "50": {
        "id": 50,
        "cluster_id": 153,
        "label": "VehicleId",
        "type": "Optional[Nullable[string]]",
        "writable": false
      },
      "64": {
        "id": 64,
        "cluster_id": 153,
        "label": "SessionId",
        "type": "Nullable[uint32]",
        "writable": false
      },
      "65": {
        "id": 65,
        "cluster_id": 153,
        "label": "SessionDuration",
        "type": "Nullable[elapsed-s]",
        "writable": false
      },
      "66": {
        "id": 66,
        "cluster_id": 153,
        "label": "SessionEnergyCharged",
        "type": "Nullable[energy-mWh]",
        "writable": false
      },
      "67": {
        "id": 67,
        "cluster_id": 153,
        "label": "SessionEnergyDischarged",
        "type": "Optional[Nullable[energy-mWh]]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 153,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 153,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 153,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 153,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 153,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 153,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "1": {
        "id": 1,
        "cluster_id": 153,
        "name": "Disable",
        "label": "Disable"
      },
      "2": {
        "id": 2,
        "cluster_id": 153,
        "name": "EnableCharging",
        "label": "Enable Charging"
      },
      "3": {
        "id": 3,
        "cluster_id": 153,
        "name": "EnableDischarging",
        "label": "Enable Discharging"
      },
      "4": {
        "id": 4,
        "cluster_id": 153,
        "name": "StartDiagnostics",
        "label": "Start Diagnostics"
      },
      "5": {
        "id": 5,
        "cluster_id": 153,
        "name": "SetTargets",
        "label": "Set Targets"
      },
      "6": {
        "id": 6,
        "cluster_id": 153,
        "name": "GetTargets",
        "label": "Get Targets"
      },
      "7": {
        "id": 7,
        "cluster_id": 153,
        "name": "ClearTargets",
        "label": "Clear Targets"
      }
    }
  },
  "155": {
    "id": 155,
    "label": "EnergyPreference",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 155,
        "label": "EnergyBalances",
        "type": "List[BalanceStruct]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 155,
        "label": "CurrentEnergyBalance",
        "type": "Optional[uint8]",
        "writable": true
      },
      "2": {
        "id": 2,
        "cluster_id": 155,
        "label": "EnergyPriorities",
        "type": "List[EnergyPriorityEnum]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 155,
        "label": "LowPowerModeSensitivities",
        "type": "List[BalanceStruct]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 155,
        "label": "CurrentLowPowerModeSensitivity",
        "type": "Optional[uint8]",
        "writable": true
      },
      "65528": {
        "id": 65528,
        "cluster_id": 155,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 155,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 155,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 155,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 155,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 155,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "156": {
    "id": 156,
    "label": "PowerTopology",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 156,
        "label": "AvailableEndpoints",
        "type": "List[endpoint-no]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 156,
        "label": "ActiveEndpoints",
        "type": "List[endpoint-no]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 156,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 156,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 156,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 156,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 156,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 156,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "157": {
    "id": 157,
    "label": "EnergyEvseMode",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 157,
        "label": "SupportedModes",
        "type": "unknown",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 157,
        "label": "CurrentMode",
        "type": "unknown",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 157,
        "label": "StartUpMode",
        "type": "Optional[Nullable[unknown]]",
        "writable": true
      },
      "3": {
        "id": 3,
        "cluster_id": 157,
        "label": "OnMode",
        "type": "Optional[Nullable[unknown]]",
        "writable": true
      },
      "65528": {
        "id": 65528,
        "cluster_id": 157,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 157,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 157,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 157,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 157,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 157,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 157,
        "name": "ChangeToMode",
        "label": "Change To Mode"
      }
    }
  },
  "158": {
    "id": 158,
    "label": "WaterHeaterMode",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 158,
        "label": "SupportedModes",
        "type": "unknown",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 158,
        "label": "CurrentMode",
        "type": "unknown",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 158,
        "label": "StartUpMode",
        "type": "Optional[Nullable[unknown]]",
        "writable": true
      },
      "3": {
        "id": 3,
        "cluster_id": 158,
        "label": "OnMode",
        "type": "Optional[Nullable[unknown]]",
        "writable": true
      },
      "65528": {
        "id": 65528,
        "cluster_id": 158,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 158,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 158,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 158,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 158,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 158,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 158,
        "name": "ChangeToMode",
        "label": "Change To Mode"
      }
    }
  },
  "159": {
    "id": 159,
    "label": "DeviceEnergyManagementMode",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 159,
        "label": "SupportedModes",
        "type": "unknown",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 159,
        "label": "CurrentMode",
        "type": "unknown",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 159,
        "label": "StartUpMode",
        "type": "Optional[Nullable[unknown]]",
        "writable": true
      },
      "3": {
        "id": 3,
        "cluster_id": 159,
        "label": "OnMode",
        "type": "Optional[Nullable[unknown]]",
        "writable": true
      },
      "65528": {
        "id": 65528,
        "cluster_id": 159,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 159,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 159,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 159,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 159,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 159,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 159,
        "name": "ChangeToMode",
        "label": "Change To Mode"
      }
    }
  },
  "160": {
    "id": 160,
    "label": "ElectricalGridConditions",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 160,
        "label": "LocalGenerationAvailable",
        "type": "Nullable[bool]",
        "writable": true
      },
      "1": {
        "id": 1,
        "cluster_id": 160,
        "label": "CurrentConditions",
        "type": "Nullable[ElectricalGridConditionsStruct]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 160,
        "label": "ForecastConditions",
        "type": "List[ElectricalGridConditionsStruct]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 160,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 160,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 160,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 160,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 160,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 160,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "257": {
    "id": 257,
    "label": "DoorLock",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 257,
        "label": "LockState",
        "type": "Nullable[LockStateEnum]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 257,
        "label": "LockType",
        "type": "LockTypeEnum",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 257,
        "label": "ActuatorEnabled",
        "type": "bool",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 257,
        "label": "DoorState",
        "type": "Optional[Nullable[DoorStateEnum]]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 257,
        "label": "DoorOpenEvents",
        "type": "Optional[uint32]",
        "writable": true
      },
      "5": {
        "id": 5,
        "cluster_id": 257,
        "label": "DoorClosedEvents",
        "type": "Optional[uint32]",
        "writable": true
      },
      "6": {
        "id": 6,
        "cluster_id": 257,
        "label": "OpenPeriod",
        "type": "Optional[uint16]",
        "writable": true
      },
      "17": {
        "id": 17,
        "cluster_id": 257,
        "label": "NumberOfTotalUsersSupported",
        "type": "Optional[uint16]",
        "writable": false
      },
      "18": {
        "id": 18,
        "cluster_id": 257,
        "label": "NumberOfPinUsersSupported",
        "type": "Optional[uint16]",
        "writable": false
      },
      "19": {
        "id": 19,
        "cluster_id": 257,
        "label": "NumberOfRfidUsersSupported",
        "type": "Optional[uint16]",
        "writable": false
      },
      "20": {
        "id": 20,
        "cluster_id": 257,
        "label": "NumberOfWeekDaySchedulesSupportedPerUser",
        "type": "Optional[uint8]",
        "writable": false
      },
      "21": {
        "id": 21,
        "cluster_id": 257,
        "label": "NumberOfYearDaySchedulesSupportedPerUser",
        "type": "Optional[uint8]",
        "writable": false
      },
      "22": {
        "id": 22,
        "cluster_id": 257,
        "label": "NumberOfHolidaySchedulesSupported",
        "type": "Optional[uint8]",
        "writable": false
      },
      "23": {
        "id": 23,
        "cluster_id": 257,
        "label": "MaxPinCodeLength",
        "type": "Optional[uint8]",
        "writable": false
      },
      "24": {
        "id": 24,
        "cluster_id": 257,
        "label": "MinPinCodeLength",
        "type": "Optional[uint8]",
        "writable": false
      },
      "25": {
        "id": 25,
        "cluster_id": 257,
        "label": "MaxRfidCodeLength",
        "type": "Optional[uint8]",
        "writable": false
      },
      "26": {
        "id": 26,
        "cluster_id": 257,
        "label": "MinRfidCodeLength",
        "type": "Optional[uint8]",
        "writable": false
      },
      "27": {
        "id": 27,
        "cluster_id": 257,
        "label": "CredentialRulesSupport",
        "type": "Optional[CredentialRulesBitmap]",
        "writable": false
      },
      "28": {
        "id": 28,
        "cluster_id": 257,
        "label": "NumberOfCredentialsSupportedPerUser",
        "type": "Optional[uint8]",
        "writable": false
      },
      "33": {
        "id": 33,
        "cluster_id": 257,
        "label": "Language",
        "type": "Optional[string]",
        "writable": true
      },
      "34": {
        "id": 34,
        "cluster_id": 257,
        "label": "LedSettings",
        "type": "Optional[LEDSettingEnum]",
        "writable": true
      },
      "35": {
        "id": 35,
        "cluster_id": 257,
        "label": "AutoRelockTime",
        "type": "Optional[uint32]",
        "writable": true
      },
      "36": {
        "id": 36,
        "cluster_id": 257,
        "label": "SoundVolume",
        "type": "Optional[SoundVolumeEnum]",
        "writable": true
      },
      "37": {
        "id": 37,
        "cluster_id": 257,
        "label": "OperatingMode",
        "type": "OperatingModeEnum",
        "writable": true
      },
      "38": {
        "id": 38,
        "cluster_id": 257,
        "label": "SupportedOperatingModes",
        "type": "OperatingModesBitmap",
        "writable": false
      },
      "39": {
        "id": 39,
        "cluster_id": 257,
        "label": "DefaultConfigurationRegister",
        "type": "Optional[ConfigurationRegisterBitmap]",
        "writable": false
      },
      "40": {
        "id": 40,
        "cluster_id": 257,
        "label": "EnableLocalProgramming",
        "type": "Optional[bool]",
        "writable": true
      },
      "41": {
        "id": 41,
        "cluster_id": 257,
        "label": "EnableOneTouchLocking",
        "type": "Optional[bool]",
        "writable": true
      },
      "42": {
        "id": 42,
        "cluster_id": 257,
        "label": "EnableInsideStatusLed",
        "type": "Optional[bool]",
        "writable": true
      },
      "43": {
        "id": 43,
        "cluster_id": 257,
        "label": "EnablePrivacyModeButton",
        "type": "Optional[bool]",
        "writable": true
      },
      "44": {
        "id": 44,
        "cluster_id": 257,
        "label": "LocalProgrammingFeatures",
        "type": "Optional[LocalProgrammingFeaturesBitmap]",
        "writable": true
      },
      "48": {
        "id": 48,
        "cluster_id": 257,
        "label": "WrongCodeEntryLimit",
        "type": "Optional[uint8]",
        "writable": true
      },
      "49": {
        "id": 49,
        "cluster_id": 257,
        "label": "UserCodeTemporaryDisableTime",
        "type": "Optional[uint8]",
        "writable": true
      },
      "50": {
        "id": 50,
        "cluster_id": 257,
        "label": "SendPinOverTheAir",
        "type": "Optional[bool]",
        "writable": true
      },
      "51": {
        "id": 51,
        "cluster_id": 257,
        "label": "RequirePinForRemoteOperation",
        "type": "Optional[bool]",
        "writable": true
      },
      "52": {
        "id": 52,
        "cluster_id": 257,
        "label": "SecurityLevel",
        "type": "Optional[unknown]",
        "writable": false
      },
      "53": {
        "id": 53,
        "cluster_id": 257,
        "label": "ExpiringUserTimeout",
        "type": "Optional[uint16]",
        "writable": true
      },
      "128": {
        "id": 128,
        "cluster_id": 257,
        "label": "AliroReaderVerificationKey",
        "type": "Optional[Nullable[bytes]]",
        "writable": false
      },
      "129": {
        "id": 129,
        "cluster_id": 257,
        "label": "AliroReaderGroupIdentifier",
        "type": "Optional[Nullable[bytes]]",
        "writable": false
      },
      "130": {
        "id": 130,
        "cluster_id": 257,
        "label": "AliroReaderGroupSubIdentifier",
        "type": "Optional[bytes]",
        "writable": false
      },
      "131": {
        "id": 131,
        "cluster_id": 257,
        "label": "AliroExpeditedTransactionSupportedProtocolVersions",
        "type": "List[octstr]",
        "writable": false
      },
      "132": {
        "id": 132,
        "cluster_id": 257,
        "label": "AliroGroupResolvingKey",
        "type": "Optional[Nullable[bytes]]",
        "writable": false
      },
      "133": {
        "id": 133,
        "cluster_id": 257,
        "label": "AliroSupportedBleuwbProtocolVersions",
        "type": "List[octstr]",
        "writable": false
      },
      "134": {
        "id": 134,
        "cluster_id": 257,
        "label": "AliroBleAdvertisingVersion",
        "type": "Optional[uint8]",
        "writable": false
      },
      "135": {
        "id": 135,
        "cluster_id": 257,
        "label": "NumberOfAliroCredentialIssuerKeysSupported",
        "type": "Optional[uint16]",
        "writable": false
      },
      "136": {
        "id": 136,
        "cluster_id": 257,
        "label": "NumberOfAliroEndpointKeysSupported",
        "type": "Optional[uint16]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 257,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 257,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 257,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 257,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 257,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 257,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 257,
        "name": "LockDoor",
        "label": "Lock Door"
      },
      "1": {
        "id": 1,
        "cluster_id": 257,
        "name": "UnlockDoor",
        "label": "Unlock Door"
      },
      "2": {
        "id": 2,
        "cluster_id": 257,
        "name": "Toggle",
        "label": "Toggle"
      },
      "3": {
        "id": 3,
        "cluster_id": 257,
        "name": "UnlockWithTimeout",
        "label": "Unlock With Timeout"
      },
      "11": {
        "id": 11,
        "cluster_id": 257,
        "name": "SetWeekDaySchedule",
        "label": "Set Week Day Schedule"
      },
      "12": {
        "id": 12,
        "cluster_id": 257,
        "name": "GetWeekDaySchedule",
        "label": "Get Week Day Schedule"
      },
      "13": {
        "id": 13,
        "cluster_id": 257,
        "name": "ClearWeekDaySchedule",
        "label": "Clear Week Day Schedule"
      },
      "14": {
        "id": 14,
        "cluster_id": 257,
        "name": "SetYearDaySchedule",
        "label": "Set Year Day Schedule"
      },
      "15": {
        "id": 15,
        "cluster_id": 257,
        "name": "GetYearDaySchedule",
        "label": "Get Year Day Schedule"
      },
      "16": {
        "id": 16,
        "cluster_id": 257,
        "name": "ClearYearDaySchedule",
        "label": "Clear Year Day Schedule"
      },
      "17": {
        "id": 17,
        "cluster_id": 257,
        "name": "SetHolidaySchedule",
        "label": "Set Holiday Schedule"
      },
      "18": {
        "id": 18,
        "cluster_id": 257,
        "name": "GetHolidaySchedule",
        "label": "Get Holiday Schedule"
      },
      "19": {
        "id": 19,
        "cluster_id": 257,
        "name": "ClearHolidaySchedule",
        "label": "Clear Holiday Schedule"
      },
      "26": {
        "id": 26,
        "cluster_id": 257,
        "name": "SetUser",
        "label": "Set User"
      },
      "27": {
        "id": 27,
        "cluster_id": 257,
        "name": "GetUser",
        "label": "Get User"
      },
      "29": {
        "id": 29,
        "cluster_id": 257,
        "name": "ClearUser",
        "label": "Clear User"
      },
      "34": {
        "id": 34,
        "cluster_id": 257,
        "name": "SetCredential",
        "label": "Set Credential"
      },
      "36": {
        "id": 36,
        "cluster_id": 257,
        "name": "GetCredentialStatus",
        "label": "Get Credential Status"
      },
      "38": {
        "id": 38,
        "cluster_id": 257,
        "name": "ClearCredential",
        "label": "Clear Credential"
      },
      "39": {
        "id": 39,
        "cluster_id": 257,
        "name": "UnboltDoor",
        "label": "Unbolt Door"
      },
      "40": {
        "id": 40,
        "cluster_id": 257,
        "name": "SetAliroReaderConfig",
        "label": "Set Aliro Reader Config"
      },
      "41": {
        "id": 41,
        "cluster_id": 257,
        "name": "ClearAliroReaderConfig",
        "label": "Clear Aliro Reader Config"
      }
    }
  },
  "258": {
    "id": 258,
    "label": "WindowCovering",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 258,
        "label": "Type",
        "type": "TypeEnum",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 258,
        "label": "NumberOfActuationsLift",
        "type": "Optional[uint16]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 258,
        "label": "NumberOfActuationsTilt",
        "type": "Optional[uint16]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 258,
        "label": "ConfigStatus",
        "type": "ConfigStatusBitmap",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 258,
        "label": "CurrentPositionLiftPercentage",
        "type": "Optional[Nullable[percent]]",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 258,
        "label": "CurrentPositionTiltPercentage",
        "type": "Optional[Nullable[percent]]",
        "writable": false
      },
      "10": {
        "id": 10,
        "cluster_id": 258,
        "label": "OperationalStatus",
        "type": "OperationalStatusBitmap",
        "writable": false
      },
      "11": {
        "id": 11,
        "cluster_id": 258,
        "label": "TargetPositionLiftPercent100ths",
        "type": "Optional[Nullable[percent100ths]]",
        "writable": false
      },
      "12": {
        "id": 12,
        "cluster_id": 258,
        "label": "TargetPositionTiltPercent100ths",
        "type": "Optional[Nullable[percent100ths]]",
        "writable": false
      },
      "13": {
        "id": 13,
        "cluster_id": 258,
        "label": "EndProductType",
        "type": "EndProductTypeEnum",
        "writable": false
      },
      "14": {
        "id": 14,
        "cluster_id": 258,
        "label": "CurrentPositionLiftPercent100ths",
        "type": "Optional[Nullable[percent100ths]]",
        "writable": false
      },
      "15": {
        "id": 15,
        "cluster_id": 258,
        "label": "CurrentPositionTiltPercent100ths",
        "type": "Optional[Nullable[percent100ths]]",
        "writable": false
      },
      "23": {
        "id": 23,
        "cluster_id": 258,
        "label": "Mode",
        "type": "ModeBitmap",
        "writable": true
      },
      "26": {
        "id": 26,
        "cluster_id": 258,
        "label": "SafetyStatus",
        "type": "Optional[SafetyStatusBitmap]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 258,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 258,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 258,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 258,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 258,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 258,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 258,
        "name": "UpOrOpen",
        "label": "Up Or Open"
      },
      "1": {
        "id": 1,
        "cluster_id": 258,
        "name": "DownOrClose",
        "label": "Down Or Close"
      },
      "2": {
        "id": 2,
        "cluster_id": 258,
        "name": "StopMotion",
        "label": "Stop Motion"
      },
      "5": {
        "id": 5,
        "cluster_id": 258,
        "name": "GoToLiftPercentage",
        "label": "Go To Lift Percentage"
      },
      "8": {
        "id": 8,
        "cluster_id": 258,
        "name": "GoToTiltPercentage",
        "label": "Go To Tilt Percentage"
      }
    }
  },
  "260": {
    "id": 260,
    "label": "ClosureControl",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 260,
        "label": "CountdownTime",
        "type": "Optional[Nullable[elapsed-s]]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 260,
        "label": "MainState",
        "type": "MainStateEnum",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 260,
        "label": "CurrentErrorList",
        "type": "List[ClosureErrorEnum]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 260,
        "label": "OverallCurrentState",
        "type": "Nullable[OverallCurrentStateStruct]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 260,
        "label": "OverallTargetState",
        "type": "Nullable[OverallTargetStateStruct]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 260,
        "label": "LatchControlModes",
        "type": "Optional[LatchControlModesBitmap]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 260,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 260,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 260,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 260,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 260,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 260,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 260,
        "name": "Stop",
        "label": "Stop"
      },
      "1": {
        "id": 1,
        "cluster_id": 260,
        "name": "MoveTo",
        "label": "Move To"
      },
      "2": {
        "id": 2,
        "cluster_id": 260,
        "name": "Calibrate",
        "label": "Calibrate"
      }
    }
  },
  "261": {
    "id": 261,
    "label": "ClosureDimension",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 261,
        "label": "CurrentState",
        "type": "Nullable[DimensionStateStruct]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 261,
        "label": "TargetState",
        "type": "Nullable[DimensionStateStruct]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 261,
        "label": "Resolution",
        "type": "Optional[percent100ths]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 261,
        "label": "StepValue",
        "type": "Optional[percent100ths]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 261,
        "label": "Unit",
        "type": "Optional[ClosureUnitEnum]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 261,
        "label": "UnitRange",
        "type": "Optional[Nullable[UnitRangeStruct]]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 261,
        "label": "LimitRange",
        "type": "Optional[RangePercent100thsStruct]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 261,
        "label": "TranslationDirection",
        "type": "Optional[TranslationDirectionEnum]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 261,
        "label": "RotationAxis",
        "type": "Optional[RotationAxisEnum]",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 261,
        "label": "Overflow",
        "type": "Optional[OverflowEnum]",
        "writable": false
      },
      "10": {
        "id": 10,
        "cluster_id": 261,
        "label": "ModulationType",
        "type": "Optional[ModulationTypeEnum]",
        "writable": false
      },
      "11": {
        "id": 11,
        "cluster_id": 261,
        "label": "LatchControlModes",
        "type": "Optional[LatchControlModesBitmap]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 261,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 261,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 261,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 261,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 261,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 261,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 261,
        "name": "SetTarget",
        "label": "Set Target"
      },
      "1": {
        "id": 1,
        "cluster_id": 261,
        "name": "Step",
        "label": "Step"
      }
    }
  },
  "336": {
    "id": 336,
    "label": "ServiceArea",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 336,
        "label": "SupportedAreas",
        "type": "List[AreaStruct]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 336,
        "label": "SupportedMaps",
        "type": "List[MapStruct]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 336,
        "label": "SelectedAreas",
        "type": "List[uint32]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 336,
        "label": "CurrentArea",
        "type": "Optional[Nullable[uint32]]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 336,
        "label": "EstimatedEndTime",
        "type": "Optional[Nullable[epoch-s]]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 336,
        "label": "Progress",
        "type": "List[ProgressStruct]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 336,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 336,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 336,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 336,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 336,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 336,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 336,
        "name": "SelectAreas",
        "label": "Select Areas"
      },
      "2": {
        "id": 2,
        "cluster_id": 336,
        "name": "SkipArea",
        "label": "Skip Area"
      }
    }
  },
  "512": {
    "id": 512,
    "label": "PumpConfigurationAndControl",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 512,
        "label": "MaxPressure",
        "type": "Nullable[int16]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 512,
        "label": "MaxSpeed",
        "type": "Nullable[uint16]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 512,
        "label": "MaxFlow",
        "type": "Nullable[uint16]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 512,
        "label": "MinConstPressure",
        "type": "Optional[Nullable[int16]]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 512,
        "label": "MaxConstPressure",
        "type": "Optional[Nullable[int16]]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 512,
        "label": "MinCompPressure",
        "type": "Optional[Nullable[int16]]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 512,
        "label": "MaxCompPressure",
        "type": "Optional[Nullable[int16]]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 512,
        "label": "MinConstSpeed",
        "type": "Optional[Nullable[uint16]]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 512,
        "label": "MaxConstSpeed",
        "type": "Optional[Nullable[uint16]]",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 512,
        "label": "MinConstFlow",
        "type": "Optional[Nullable[uint16]]",
        "writable": false
      },
      "10": {
        "id": 10,
        "cluster_id": 512,
        "label": "MaxConstFlow",
        "type": "Optional[Nullable[uint16]]",
        "writable": false
      },
      "11": {
        "id": 11,
        "cluster_id": 512,
        "label": "MinConstTemp",
        "type": "Optional[Nullable[int16]]",
        "writable": false
      },
      "12": {
        "id": 12,
        "cluster_id": 512,
        "label": "MaxConstTemp",
        "type": "Optional[Nullable[int16]]",
        "writable": false
      },
      "16": {
        "id": 16,
        "cluster_id": 512,
        "label": "PumpStatus",
        "type": "Optional[PumpStatusBitmap]",
        "writable": false
      },
      "17": {
        "id": 17,
        "cluster_id": 512,
        "label": "EffectiveOperationMode",
        "type": "OperationModeEnum",
        "writable": false
      },
      "18": {
        "id": 18,
        "cluster_id": 512,
        "label": "EffectiveControlMode",
        "type": "ControlModeEnum",
        "writable": false
      },
      "19": {
        "id": 19,
        "cluster_id": 512,
        "label": "Capacity",
        "type": "Nullable[int16]",
        "writable": false
      },
      "20": {
        "id": 20,
        "cluster_id": 512,
        "label": "Speed",
        "type": "Optional[Nullable[uint16]]",
        "writable": false
      },
      "21": {
        "id": 21,
        "cluster_id": 512,
        "label": "LifetimeRunningHours",
        "type": "Optional[Nullable[uint24]]",
        "writable": true
      },
      "22": {
        "id": 22,
        "cluster_id": 512,
        "label": "Power",
        "type": "Optional[Nullable[uint24]]",
        "writable": false
      },
      "23": {
        "id": 23,
        "cluster_id": 512,
        "label": "LifetimeEnergyConsumed",
        "type": "Optional[Nullable[uint32]]",
        "writable": true
      },
      "32": {
        "id": 32,
        "cluster_id": 512,
        "label": "OperationMode",
        "type": "OperationModeEnum",
        "writable": true
      },
      "33": {
        "id": 33,
        "cluster_id": 512,
        "label": "ControlMode",
        "type": "Optional[ControlModeEnum]",
        "writable": true
      },
      "34": {
        "id": 34,
        "cluster_id": 512,
        "label": "AlarmMask",
        "type": "Optional[uint16]",
        "writable": true
      },
      "65528": {
        "id": 65528,
        "cluster_id": 512,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 512,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 512,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 512,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 512,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 512,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "513": {
    "id": 513,
    "label": "Thermostat",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 513,
        "label": "LocalTemperature",
        "type": "Nullable[temperature]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 513,
        "label": "OutdoorTemperature",
        "type": "Optional[Nullable[temperature]]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 513,
        "label": "Occupancy",
        "type": "Optional[OccupancyBitmap]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 513,
        "label": "AbsMinHeatSetpointLimit",
        "type": "Optional[temperature]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 513,
        "label": "AbsMaxHeatSetpointLimit",
        "type": "Optional[temperature]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 513,
        "label": "AbsMinCoolSetpointLimit",
        "type": "Optional[temperature]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 513,
        "label": "AbsMaxCoolSetpointLimit",
        "type": "Optional[temperature]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 513,
        "label": "PiCoolingDemand",
        "type": "Optional[unknown]",
        "writable": true
      },
      "8": {
        "id": 8,
        "cluster_id": 513,
        "label": "PiHeatingDemand",
        "type": "Optional[unknown]",
        "writable": true
      },
      "9": {
        "id": 9,
        "cluster_id": 513,
        "label": "HvacSystemTypeConfiguration",
        "type": "Optional[unknown]",
        "writable": true
      },
      "16": {
        "id": 16,
        "cluster_id": 513,
        "label": "LocalTemperatureCalibration",
        "type": "Optional[SignedTemperature]",
        "writable": true
      },
      "17": {
        "id": 17,
        "cluster_id": 513,
        "label": "OccupiedCoolingSetpoint",
        "type": "Optional[temperature]",
        "writable": true
      },
      "18": {
        "id": 18,
        "cluster_id": 513,
        "label": "OccupiedHeatingSetpoint",
        "type": "Optional[temperature]",
        "writable": true
      },
      "19": {
        "id": 19,
        "cluster_id": 513,
        "label": "UnoccupiedCoolingSetpoint",
        "type": "Optional[temperature]",
        "writable": true
      },
      "20": {
        "id": 20,
        "cluster_id": 513,
        "label": "UnoccupiedHeatingSetpoint",
        "type": "Optional[temperature]",
        "writable": true
      },
      "21": {
        "id": 21,
        "cluster_id": 513,
        "label": "MinHeatSetpointLimit",
        "type": "Optional[temperature]",
        "writable": true
      },
      "22": {
        "id": 22,
        "cluster_id": 513,
        "label": "MaxHeatSetpointLimit",
        "type": "Optional[temperature]",
        "writable": true
      },
      "23": {
        "id": 23,
        "cluster_id": 513,
        "label": "MinCoolSetpointLimit",
        "type": "Optional[temperature]",
        "writable": true
      },
      "24": {
        "id": 24,
        "cluster_id": 513,
        "label": "MaxCoolSetpointLimit",
        "type": "Optional[temperature]",
        "writable": true
      },
      "25": {
        "id": 25,
        "cluster_id": 513,
        "label": "MinSetpointDeadBand",
        "type": "Optional[SignedTemperature]",
        "writable": true
      },
      "26": {
        "id": 26,
        "cluster_id": 513,
        "label": "RemoteSensing",
        "type": "Optional[RemoteSensingBitmap]",
        "writable": true
      },
      "27": {
        "id": 27,
        "cluster_id": 513,
        "label": "ControlSequenceOfOperation",
        "type": "ControlSequenceOfOperationEnum",
        "writable": true
      },
      "28": {
        "id": 28,
        "cluster_id": 513,
        "label": "SystemMode",
        "type": "SystemModeEnum",
        "writable": true
      },
      "30": {
        "id": 30,
        "cluster_id": 513,
        "label": "ThermostatRunningMode",
        "type": "Optional[ThermostatRunningModeEnum]",
        "writable": false
      },
      "35": {
        "id": 35,
        "cluster_id": 513,
        "label": "TemperatureSetpointHold",
        "type": "Optional[TemperatureSetpointHoldEnum]",
        "writable": true
      },
      "36": {
        "id": 36,
        "cluster_id": 513,
        "label": "TemperatureSetpointHoldDuration",
        "type": "Optional[Nullable[uint16]]",
        "writable": true
      },
      "37": {
        "id": 37,
        "cluster_id": 513,
        "label": "ThermostatProgrammingOperationMode",
        "type": "Optional[unknown]",
        "writable": true
      },
      "41": {
        "id": 41,
        "cluster_id": 513,
        "label": "ThermostatRunningState",
        "type": "Optional[RelayStateBitmap]",
        "writable": false
      },
      "48": {
        "id": 48,
        "cluster_id": 513,
        "label": "SetpointChangeSource",
        "type": "Optional[SetpointChangeSourceEnum]",
        "writable": false
      },
      "49": {
        "id": 49,
        "cluster_id": 513,
        "label": "SetpointChangeAmount",
        "type": "Optional[Nullable[TemperatureDifference]]",
        "writable": false
      },
      "50": {
        "id": 50,
        "cluster_id": 513,
        "label": "SetpointChangeSourceTimestamp",
        "type": "Optional[epoch-s]",
        "writable": false
      },
      "52": {
        "id": 52,
        "cluster_id": 513,
        "label": "OccupiedSetback",
        "type": "Optional[unknown]",
        "writable": true
      },
      "53": {
        "id": 53,
        "cluster_id": 513,
        "label": "OccupiedSetbackMin",
        "type": "Optional[unknown]",
        "writable": true
      },
      "54": {
        "id": 54,
        "cluster_id": 513,
        "label": "OccupiedSetbackMax",
        "type": "Optional[unknown]",
        "writable": true
      },
      "55": {
        "id": 55,
        "cluster_id": 513,
        "label": "UnoccupiedSetback",
        "type": "Optional[unknown]",
        "writable": true
      },
      "56": {
        "id": 56,
        "cluster_id": 513,
        "label": "UnoccupiedSetbackMin",
        "type": "Optional[unknown]",
        "writable": true
      },
      "57": {
        "id": 57,
        "cluster_id": 513,
        "label": "UnoccupiedSetbackMax",
        "type": "Optional[unknown]",
        "writable": true
      },
      "58": {
        "id": 58,
        "cluster_id": 513,
        "label": "EmergencyHeatDelta",
        "type": "Optional[UnsignedTemperature]",
        "writable": true
      },
      "64": {
        "id": 64,
        "cluster_id": 513,
        "label": "AcType",
        "type": "Optional[ACTypeEnum]",
        "writable": true
      },
      "65": {
        "id": 65,
        "cluster_id": 513,
        "label": "AcCapacity",
        "type": "Optional[uint16]",
        "writable": true
      },
      "66": {
        "id": 66,
        "cluster_id": 513,
        "label": "AcRefrigerantType",
        "type": "Optional[ACRefrigerantTypeEnum]",
        "writable": true
      },
      "67": {
        "id": 67,
        "cluster_id": 513,
        "label": "AcCompressorType",
        "type": "Optional[ACCompressorTypeEnum]",
        "writable": true
      },
      "68": {
        "id": 68,
        "cluster_id": 513,
        "label": "AcErrorCode",
        "type": "Optional[ACErrorCodeBitmap]",
        "writable": true
      },
      "69": {
        "id": 69,
        "cluster_id": 513,
        "label": "AcLouverPosition",
        "type": "Optional[ACLouverPositionEnum]",
        "writable": true
      },
      "70": {
        "id": 70,
        "cluster_id": 513,
        "label": "AcCoilTemperature",
        "type": "Optional[Nullable[temperature]]",
        "writable": false
      },
      "71": {
        "id": 71,
        "cluster_id": 513,
        "label": "AcCapacityFormat",
        "type": "Optional[ACCapacityFormatEnum]",
        "writable": true
      },
      "72": {
        "id": 72,
        "cluster_id": 513,
        "label": "PresetTypes",
        "type": "List[PresetTypeStruct]",
        "writable": false
      },
      "73": {
        "id": 73,
        "cluster_id": 513,
        "label": "ScheduleTypes",
        "type": "List[ScheduleTypeStruct]",
        "writable": false
      },
      "74": {
        "id": 74,
        "cluster_id": 513,
        "label": "NumberOfPresets",
        "type": "Optional[uint8]",
        "writable": false
      },
      "75": {
        "id": 75,
        "cluster_id": 513,
        "label": "NumberOfSchedules",
        "type": "Optional[uint8]",
        "writable": false
      },
      "76": {
        "id": 76,
        "cluster_id": 513,
        "label": "NumberOfScheduleTransitions",
        "type": "Optional[uint8]",
        "writable": false
      },
      "77": {
        "id": 77,
        "cluster_id": 513,
        "label": "NumberOfScheduleTransitionPerDay",
        "type": "Optional[Nullable[uint8]]",
        "writable": false
      },
      "78": {
        "id": 78,
        "cluster_id": 513,
        "label": "ActivePresetHandle",
        "type": "Optional[Nullable[bytes]]",
        "writable": false
      },
      "79": {
        "id": 79,
        "cluster_id": 513,
        "label": "ActiveScheduleHandle",
        "type": "Optional[Nullable[bytes]]",
        "writable": false
      },
      "80": {
        "id": 80,
        "cluster_id": 513,
        "label": "Presets",
        "type": "List[PresetStruct]",
        "writable": true
      },
      "81": {
        "id": 81,
        "cluster_id": 513,
        "label": "Schedules",
        "type": "List[ScheduleStruct]",
        "writable": true
      },
      "82": {
        "id": 82,
        "cluster_id": 513,
        "label": "SetpointHoldExpiryTimestamp",
        "type": "Optional[Nullable[epoch-s]]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 513,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 513,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 513,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 513,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 513,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 513,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 513,
        "name": "SetpointRaiseLower",
        "label": "Setpoint Raise Lower"
      },
      "5": {
        "id": 5,
        "cluster_id": 513,
        "name": "SetActiveScheduleRequest",
        "label": "Set Active Schedule Request"
      },
      "6": {
        "id": 6,
        "cluster_id": 513,
        "name": "SetActivePresetRequest",
        "label": "Set Active Preset Request"
      },
      "254": {
        "id": 254,
        "cluster_id": 513,
        "name": "AtomicRequest",
        "label": "Atomic Request"
      }
    }
  },
  "514": {
    "id": 514,
    "label": "FanControl",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 514,
        "label": "FanMode",
        "type": "FanModeEnum",
        "writable": true
      },
      "1": {
        "id": 1,
        "cluster_id": 514,
        "label": "FanModeSequence",
        "type": "FanModeSequenceEnum",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 514,
        "label": "PercentSetting",
        "type": "Nullable[percent]",
        "writable": true
      },
      "3": {
        "id": 3,
        "cluster_id": 514,
        "label": "PercentCurrent",
        "type": "percent",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 514,
        "label": "SpeedMax",
        "type": "Optional[uint8]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 514,
        "label": "SpeedSetting",
        "type": "Optional[Nullable[uint8]]",
        "writable": true
      },
      "6": {
        "id": 6,
        "cluster_id": 514,
        "label": "SpeedCurrent",
        "type": "Optional[uint8]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 514,
        "label": "RockSupport",
        "type": "Optional[RockBitmap]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 514,
        "label": "RockSetting",
        "type": "Optional[RockBitmap]",
        "writable": true
      },
      "9": {
        "id": 9,
        "cluster_id": 514,
        "label": "WindSupport",
        "type": "Optional[WindBitmap]",
        "writable": false
      },
      "10": {
        "id": 10,
        "cluster_id": 514,
        "label": "WindSetting",
        "type": "Optional[WindBitmap]",
        "writable": true
      },
      "11": {
        "id": 11,
        "cluster_id": 514,
        "label": "AirflowDirection",
        "type": "Optional[AirflowDirectionEnum]",
        "writable": true
      },
      "65528": {
        "id": 65528,
        "cluster_id": 514,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 514,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 514,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 514,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 514,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 514,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 514,
        "name": "Step",
        "label": "Step"
      }
    }
  },
  "516": {
    "id": 516,
    "label": "ThermostatUserInterfaceConfiguration",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 516,
        "label": "TemperatureDisplayMode",
        "type": "TemperatureDisplayModeEnum",
        "writable": true
      },
      "1": {
        "id": 1,
        "cluster_id": 516,
        "label": "KeypadLockout",
        "type": "KeypadLockoutEnum",
        "writable": true
      },
      "2": {
        "id": 2,
        "cluster_id": 516,
        "label": "ScheduleProgrammingVisibility",
        "type": "Optional[ScheduleProgrammingVisibilityEnum]",
        "writable": true
      },
      "65528": {
        "id": 65528,
        "cluster_id": 516,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 516,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 516,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 516,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 516,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 516,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "768": {
    "id": 768,
    "label": "ColorControl",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 768,
        "label": "CurrentHue",
        "type": "Optional[uint8]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 768,
        "label": "CurrentSaturation",
        "type": "Optional[uint8]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 768,
        "label": "RemainingTime",
        "type": "Optional[uint16]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 768,
        "label": "CurrentX",
        "type": "Optional[uint16]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 768,
        "label": "CurrentY",
        "type": "Optional[uint16]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 768,
        "label": "DriftCompensation",
        "type": "Optional[DriftCompensationEnum]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 768,
        "label": "CompensationText",
        "type": "Optional[string]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 768,
        "label": "ColorTemperatureMireds",
        "type": "Optional[uint16]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 768,
        "label": "ColorMode",
        "type": "ColorModeEnum",
        "writable": false
      },
      "15": {
        "id": 15,
        "cluster_id": 768,
        "label": "Options",
        "type": "OptionsBitmap",
        "writable": true
      },
      "16": {
        "id": 16,
        "cluster_id": 768,
        "label": "NumberOfPrimaries",
        "type": "Nullable[uint8]",
        "writable": false
      },
      "17": {
        "id": 17,
        "cluster_id": 768,
        "label": "Primary1X",
        "type": "Optional[uint16]",
        "writable": false
      },
      "18": {
        "id": 18,
        "cluster_id": 768,
        "label": "Primary1Y",
        "type": "Optional[uint16]",
        "writable": false
      },
      "19": {
        "id": 19,
        "cluster_id": 768,
        "label": "Primary1Intensity",
        "type": "Optional[Nullable[uint8]]",
        "writable": false
      },
      "21": {
        "id": 21,
        "cluster_id": 768,
        "label": "Primary2X",
        "type": "Optional[uint16]",
        "writable": false
      },
      "22": {
        "id": 22,
        "cluster_id": 768,
        "label": "Primary2Y",
        "type": "Optional[uint16]",
        "writable": false
      },
      "23": {
        "id": 23,
        "cluster_id": 768,
        "label": "Primary2Intensity",
        "type": "Optional[Nullable[uint8]]",
        "writable": false
      },
      "25": {
        "id": 25,
        "cluster_id": 768,
        "label": "Primary3X",
        "type": "Optional[uint16]",
        "writable": false
      },
      "26": {
        "id": 26,
        "cluster_id": 768,
        "label": "Primary3Y",
        "type": "Optional[uint16]",
        "writable": false
      },
      "27": {
        "id": 27,
        "cluster_id": 768,
        "label": "Primary3Intensity",
        "type": "Optional[Nullable[uint8]]",
        "writable": false
      },
      "32": {
        "id": 32,
        "cluster_id": 768,
        "label": "Primary4X",
        "type": "Optional[uint16]",
        "writable": false
      },
      "33": {
        "id": 33,
        "cluster_id": 768,
        "label": "Primary4Y",
        "type": "Optional[uint16]",
        "writable": false
      },
      "34": {
        "id": 34,
        "cluster_id": 768,
        "label": "Primary4Intensity",
        "type": "Optional[Nullable[uint8]]",
        "writable": false
      },
      "36": {
        "id": 36,
        "cluster_id": 768,
        "label": "Primary5X",
        "type": "Optional[uint16]",
        "writable": false
      },
      "37": {
        "id": 37,
        "cluster_id": 768,
        "label": "Primary5Y",
        "type": "Optional[uint16]",
        "writable": false
      },
      "38": {
        "id": 38,
        "cluster_id": 768,
        "label": "Primary5Intensity",
        "type": "Optional[Nullable[uint8]]",
        "writable": false
      },
      "40": {
        "id": 40,
        "cluster_id": 768,
        "label": "Primary6X",
        "type": "Optional[uint16]",
        "writable": false
      },
      "41": {
        "id": 41,
        "cluster_id": 768,
        "label": "Primary6Y",
        "type": "Optional[uint16]",
        "writable": false
      },
      "42": {
        "id": 42,
        "cluster_id": 768,
        "label": "Primary6Intensity",
        "type": "Optional[Nullable[uint8]]",
        "writable": false
      },
      "48": {
        "id": 48,
        "cluster_id": 768,
        "label": "WhitePointX",
        "type": "Optional[uint16]",
        "writable": false
      },
      "49": {
        "id": 49,
        "cluster_id": 768,
        "label": "WhitePointY",
        "type": "Optional[uint16]",
        "writable": false
      },
      "50": {
        "id": 50,
        "cluster_id": 768,
        "label": "ColorPointRx",
        "type": "Optional[uint16]",
        "writable": false
      },
      "51": {
        "id": 51,
        "cluster_id": 768,
        "label": "ColorPointRy",
        "type": "Optional[uint16]",
        "writable": false
      },
      "52": {
        "id": 52,
        "cluster_id": 768,
        "label": "ColorPointRIntensity",
        "type": "Optional[Nullable[uint8]]",
        "writable": false
      },
      "54": {
        "id": 54,
        "cluster_id": 768,
        "label": "ColorPointGx",
        "type": "Optional[uint16]",
        "writable": false
      },
      "55": {
        "id": 55,
        "cluster_id": 768,
        "label": "ColorPointGy",
        "type": "Optional[uint16]",
        "writable": false
      },
      "56": {
        "id": 56,
        "cluster_id": 768,
        "label": "ColorPointGIntensity",
        "type": "Optional[Nullable[uint8]]",
        "writable": false
      },
      "58": {
        "id": 58,
        "cluster_id": 768,
        "label": "ColorPointBx",
        "type": "Optional[uint16]",
        "writable": false
      },
      "59": {
        "id": 59,
        "cluster_id": 768,
        "label": "ColorPointBy",
        "type": "Optional[uint16]",
        "writable": false
      },
      "60": {
        "id": 60,
        "cluster_id": 768,
        "label": "ColorPointBIntensity",
        "type": "Optional[Nullable[uint8]]",
        "writable": false
      },
      "16384": {
        "id": 16384,
        "cluster_id": 768,
        "label": "EnhancedCurrentHue",
        "type": "Optional[uint16]",
        "writable": false
      },
      "16385": {
        "id": 16385,
        "cluster_id": 768,
        "label": "EnhancedColorMode",
        "type": "EnhancedColorModeEnum",
        "writable": false
      },
      "16386": {
        "id": 16386,
        "cluster_id": 768,
        "label": "ColorLoopActive",
        "type": "Optional[enum8]",
        "writable": false
      },
      "16387": {
        "id": 16387,
        "cluster_id": 768,
        "label": "ColorLoopDirection",
        "type": "Optional[ColorLoopDirectionEnum]",
        "writable": false
      },
      "16388": {
        "id": 16388,
        "cluster_id": 768,
        "label": "ColorLoopTime",
        "type": "Optional[uint16]",
        "writable": false
      },
      "16389": {
        "id": 16389,
        "cluster_id": 768,
        "label": "ColorLoopStartEnhancedHue",
        "type": "Optional[uint16]",
        "writable": false
      },
      "16390": {
        "id": 16390,
        "cluster_id": 768,
        "label": "ColorLoopStoredEnhancedHue",
        "type": "Optional[uint16]",
        "writable": false
      },
      "16394": {
        "id": 16394,
        "cluster_id": 768,
        "label": "ColorCapabilities",
        "type": "ColorCapabilitiesBitmap",
        "writable": false
      },
      "16395": {
        "id": 16395,
        "cluster_id": 768,
        "label": "ColorTempPhysicalMinMireds",
        "type": "Optional[uint16]",
        "writable": false
      },
      "16396": {
        "id": 16396,
        "cluster_id": 768,
        "label": "ColorTempPhysicalMaxMireds",
        "type": "Optional[uint16]",
        "writable": false
      },
      "16397": {
        "id": 16397,
        "cluster_id": 768,
        "label": "CoupleColorTempToLevelMinMireds",
        "type": "Optional[uint16]",
        "writable": false
      },
      "16400": {
        "id": 16400,
        "cluster_id": 768,
        "label": "StartUpColorTemperatureMireds",
        "type": "Optional[Nullable[uint16]]",
        "writable": true
      },
      "65528": {
        "id": 65528,
        "cluster_id": 768,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 768,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 768,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 768,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 768,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 768,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 768,
        "name": "MoveToHue",
        "label": "Move To Hue"
      },
      "1": {
        "id": 1,
        "cluster_id": 768,
        "name": "MoveHue",
        "label": "Move Hue"
      },
      "2": {
        "id": 2,
        "cluster_id": 768,
        "name": "StepHue",
        "label": "Step Hue"
      },
      "3": {
        "id": 3,
        "cluster_id": 768,
        "name": "MoveToSaturation",
        "label": "Move To Saturation"
      },
      "4": {
        "id": 4,
        "cluster_id": 768,
        "name": "MoveSaturation",
        "label": "Move Saturation"
      },
      "5": {
        "id": 5,
        "cluster_id": 768,
        "name": "StepSaturation",
        "label": "Step Saturation"
      },
      "6": {
        "id": 6,
        "cluster_id": 768,
        "name": "MoveToHueAndSaturation",
        "label": "Move To Hue And Saturation"
      },
      "7": {
        "id": 7,
        "cluster_id": 768,
        "name": "MoveToColor",
        "label": "Move To Color"
      },
      "8": {
        "id": 8,
        "cluster_id": 768,
        "name": "MoveColor",
        "label": "Move Color"
      },
      "9": {
        "id": 9,
        "cluster_id": 768,
        "name": "StepColor",
        "label": "Step Color"
      },
      "10": {
        "id": 10,
        "cluster_id": 768,
        "name": "MoveToColorTemperature",
        "label": "Move To Color Temperature"
      },
      "64": {
        "id": 64,
        "cluster_id": 768,
        "name": "EnhancedMoveToHue",
        "label": "Enhanced Move To Hue"
      },
      "65": {
        "id": 65,
        "cluster_id": 768,
        "name": "EnhancedMoveHue",
        "label": "Enhanced Move Hue"
      },
      "66": {
        "id": 66,
        "cluster_id": 768,
        "name": "EnhancedStepHue",
        "label": "Enhanced Step Hue"
      },
      "67": {
        "id": 67,
        "cluster_id": 768,
        "name": "EnhancedMoveToHueAndSaturation",
        "label": "Enhanced Move To Hue And Saturation"
      },
      "68": {
        "id": 68,
        "cluster_id": 768,
        "name": "ColorLoopSet",
        "label": "Color Loop Set"
      },
      "71": {
        "id": 71,
        "cluster_id": 768,
        "name": "StopMoveStep",
        "label": "Stop Move Step"
      },
      "75": {
        "id": 75,
        "cluster_id": 768,
        "name": "MoveColorTemperature",
        "label": "Move Color Temperature"
      },
      "76": {
        "id": 76,
        "cluster_id": 768,
        "name": "StepColorTemperature",
        "label": "Step Color Temperature"
      }
    }
  },
  "1024": {
    "id": 1024,
    "label": "IlluminanceMeasurement",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1024,
        "label": "MeasuredValue",
        "type": "Nullable[uint16]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1024,
        "label": "MinMeasuredValue",
        "type": "Nullable[uint16]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 1024,
        "label": "MaxMeasuredValue",
        "type": "Nullable[uint16]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 1024,
        "label": "Tolerance",
        "type": "Optional[uint16]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 1024,
        "label": "LightSensorType",
        "type": "Optional[Nullable[uint8]]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1024,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1024,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1024,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1024,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1024,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1024,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "1026": {
    "id": 1026,
    "label": "TemperatureMeasurement",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1026,
        "label": "MeasuredValue",
        "type": "Nullable[temperature]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1026,
        "label": "MinMeasuredValue",
        "type": "Nullable[temperature]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 1026,
        "label": "MaxMeasuredValue",
        "type": "Nullable[temperature]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 1026,
        "label": "Tolerance",
        "type": "Optional[uint16]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1026,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1026,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1026,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1026,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1026,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1026,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "1027": {
    "id": 1027,
    "label": "PressureMeasurement",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1027,
        "label": "MeasuredValue",
        "type": "Nullable[int16]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1027,
        "label": "MinMeasuredValue",
        "type": "Nullable[int16]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 1027,
        "label": "MaxMeasuredValue",
        "type": "Nullable[int16]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 1027,
        "label": "Tolerance",
        "type": "Optional[uint16]",
        "writable": false
      },
      "16": {
        "id": 16,
        "cluster_id": 1027,
        "label": "ScaledValue",
        "type": "Optional[Nullable[int16]]",
        "writable": false
      },
      "17": {
        "id": 17,
        "cluster_id": 1027,
        "label": "MinScaledValue",
        "type": "Optional[Nullable[int16]]",
        "writable": false
      },
      "18": {
        "id": 18,
        "cluster_id": 1027,
        "label": "MaxScaledValue",
        "type": "Optional[Nullable[int16]]",
        "writable": false
      },
      "19": {
        "id": 19,
        "cluster_id": 1027,
        "label": "ScaledTolerance",
        "type": "Optional[uint16]",
        "writable": false
      },
      "20": {
        "id": 20,
        "cluster_id": 1027,
        "label": "Scale",
        "type": "Optional[int8]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1027,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1027,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1027,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1027,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1027,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1027,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "1028": {
    "id": 1028,
    "label": "FlowMeasurement",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1028,
        "label": "MeasuredValue",
        "type": "Nullable[uint16]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1028,
        "label": "MinMeasuredValue",
        "type": "Nullable[uint16]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 1028,
        "label": "MaxMeasuredValue",
        "type": "Nullable[uint16]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 1028,
        "label": "Tolerance",
        "type": "Optional[uint16]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1028,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1028,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1028,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1028,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1028,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1028,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "1029": {
    "id": 1029,
    "label": "RelativeHumidityMeasurement",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1029,
        "label": "MeasuredValue",
        "type": "Nullable[uint16]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1029,
        "label": "MinMeasuredValue",
        "type": "Nullable[uint16]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 1029,
        "label": "MaxMeasuredValue",
        "type": "Nullable[uint16]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 1029,
        "label": "Tolerance",
        "type": "Optional[uint16]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1029,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1029,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1029,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1029,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1029,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1029,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "1030": {
    "id": 1030,
    "label": "OccupancySensing",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1030,
        "label": "Occupancy",
        "type": "OccupancyBitmap",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1030,
        "label": "OccupancySensorType",
        "type": "OccupancySensorTypeEnum",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 1030,
        "label": "OccupancySensorTypeBitmap",
        "type": "OccupancySensorTypeBitmap",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 1030,
        "label": "HoldTime",
        "type": "Optional[uint16]",
        "writable": true
      },
      "4": {
        "id": 4,
        "cluster_id": 1030,
        "label": "HoldTimeLimits",
        "type": "Optional[HoldTimeLimitsStruct]",
        "writable": false
      },
      "16": {
        "id": 16,
        "cluster_id": 1030,
        "label": "PirOccupiedToUnoccupiedDelay",
        "type": "Optional[uint16]",
        "writable": true
      },
      "17": {
        "id": 17,
        "cluster_id": 1030,
        "label": "PirUnoccupiedToOccupiedDelay",
        "type": "Optional[uint16]",
        "writable": true
      },
      "18": {
        "id": 18,
        "cluster_id": 1030,
        "label": "PirUnoccupiedToOccupiedThreshold",
        "type": "Optional[uint8]",
        "writable": true
      },
      "32": {
        "id": 32,
        "cluster_id": 1030,
        "label": "UltrasonicOccupiedToUnoccupiedDelay",
        "type": "Optional[uint16]",
        "writable": true
      },
      "33": {
        "id": 33,
        "cluster_id": 1030,
        "label": "UltrasonicUnoccupiedToOccupiedDelay",
        "type": "Optional[uint16]",
        "writable": true
      },
      "34": {
        "id": 34,
        "cluster_id": 1030,
        "label": "UltrasonicUnoccupiedToOccupiedThreshold",
        "type": "Optional[uint8]",
        "writable": true
      },
      "48": {
        "id": 48,
        "cluster_id": 1030,
        "label": "PhysicalContactOccupiedToUnoccupiedDelay",
        "type": "Optional[uint16]",
        "writable": true
      },
      "49": {
        "id": 49,
        "cluster_id": 1030,
        "label": "PhysicalContactUnoccupiedToOccupiedDelay",
        "type": "Optional[uint16]",
        "writable": true
      },
      "50": {
        "id": 50,
        "cluster_id": 1030,
        "label": "PhysicalContactUnoccupiedToOccupiedThreshold",
        "type": "Optional[uint8]",
        "writable": true
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1030,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1030,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1030,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1030,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1030,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1030,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "1036": {
    "id": 1036,
    "label": "CarbonMonoxideConcentrationMeasurement",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1036,
        "label": "MeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1036,
        "label": "MinMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 1036,
        "label": "MaxMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 1036,
        "label": "PeakMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 1036,
        "label": "PeakMeasuredValueWindow",
        "type": "Optional[elapsed-s]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 1036,
        "label": "AverageMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 1036,
        "label": "AverageMeasuredValueWindow",
        "type": "Optional[elapsed-s]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 1036,
        "label": "Uncertainty",
        "type": "Optional[single]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 1036,
        "label": "MeasurementUnit",
        "type": "Optional[MeasurementUnitEnum]",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 1036,
        "label": "MeasurementMedium",
        "type": "MeasurementMediumEnum",
        "writable": false
      },
      "10": {
        "id": 10,
        "cluster_id": 1036,
        "label": "LevelValue",
        "type": "Optional[LevelValueEnum]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1036,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1036,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1036,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1036,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1036,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1036,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "1037": {
    "id": 1037,
    "label": "CarbonDioxideConcentrationMeasurement",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1037,
        "label": "MeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1037,
        "label": "MinMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 1037,
        "label": "MaxMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 1037,
        "label": "PeakMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 1037,
        "label": "PeakMeasuredValueWindow",
        "type": "Optional[elapsed-s]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 1037,
        "label": "AverageMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 1037,
        "label": "AverageMeasuredValueWindow",
        "type": "Optional[elapsed-s]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 1037,
        "label": "Uncertainty",
        "type": "Optional[single]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 1037,
        "label": "MeasurementUnit",
        "type": "Optional[MeasurementUnitEnum]",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 1037,
        "label": "MeasurementMedium",
        "type": "MeasurementMediumEnum",
        "writable": false
      },
      "10": {
        "id": 10,
        "cluster_id": 1037,
        "label": "LevelValue",
        "type": "Optional[LevelValueEnum]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1037,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1037,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1037,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1037,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1037,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1037,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "1043": {
    "id": 1043,
    "label": "NitrogenDioxideConcentrationMeasurement",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1043,
        "label": "MeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1043,
        "label": "MinMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 1043,
        "label": "MaxMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 1043,
        "label": "PeakMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 1043,
        "label": "PeakMeasuredValueWindow",
        "type": "Optional[elapsed-s]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 1043,
        "label": "AverageMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 1043,
        "label": "AverageMeasuredValueWindow",
        "type": "Optional[elapsed-s]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 1043,
        "label": "Uncertainty",
        "type": "Optional[single]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 1043,
        "label": "MeasurementUnit",
        "type": "Optional[MeasurementUnitEnum]",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 1043,
        "label": "MeasurementMedium",
        "type": "MeasurementMediumEnum",
        "writable": false
      },
      "10": {
        "id": 10,
        "cluster_id": 1043,
        "label": "LevelValue",
        "type": "Optional[LevelValueEnum]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1043,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1043,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1043,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1043,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1043,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1043,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "1045": {
    "id": 1045,
    "label": "OzoneConcentrationMeasurement",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1045,
        "label": "MeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1045,
        "label": "MinMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 1045,
        "label": "MaxMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 1045,
        "label": "PeakMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 1045,
        "label": "PeakMeasuredValueWindow",
        "type": "Optional[elapsed-s]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 1045,
        "label": "AverageMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 1045,
        "label": "AverageMeasuredValueWindow",
        "type": "Optional[elapsed-s]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 1045,
        "label": "Uncertainty",
        "type": "Optional[single]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 1045,
        "label": "MeasurementUnit",
        "type": "Optional[MeasurementUnitEnum]",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 1045,
        "label": "MeasurementMedium",
        "type": "MeasurementMediumEnum",
        "writable": false
      },
      "10": {
        "id": 10,
        "cluster_id": 1045,
        "label": "LevelValue",
        "type": "Optional[LevelValueEnum]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1045,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1045,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1045,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1045,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1045,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1045,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "1066": {
    "id": 1066,
    "label": "Pm25ConcentrationMeasurement",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1066,
        "label": "MeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1066,
        "label": "MinMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 1066,
        "label": "MaxMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 1066,
        "label": "PeakMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 1066,
        "label": "PeakMeasuredValueWindow",
        "type": "Optional[elapsed-s]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 1066,
        "label": "AverageMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 1066,
        "label": "AverageMeasuredValueWindow",
        "type": "Optional[elapsed-s]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 1066,
        "label": "Uncertainty",
        "type": "Optional[single]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 1066,
        "label": "MeasurementUnit",
        "type": "Optional[MeasurementUnitEnum]",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 1066,
        "label": "MeasurementMedium",
        "type": "MeasurementMediumEnum",
        "writable": false
      },
      "10": {
        "id": 10,
        "cluster_id": 1066,
        "label": "LevelValue",
        "type": "Optional[LevelValueEnum]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1066,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1066,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1066,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1066,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1066,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1066,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "1067": {
    "id": 1067,
    "label": "FormaldehydeConcentrationMeasurement",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1067,
        "label": "MeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1067,
        "label": "MinMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 1067,
        "label": "MaxMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 1067,
        "label": "PeakMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 1067,
        "label": "PeakMeasuredValueWindow",
        "type": "Optional[elapsed-s]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 1067,
        "label": "AverageMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 1067,
        "label": "AverageMeasuredValueWindow",
        "type": "Optional[elapsed-s]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 1067,
        "label": "Uncertainty",
        "type": "Optional[single]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 1067,
        "label": "MeasurementUnit",
        "type": "Optional[MeasurementUnitEnum]",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 1067,
        "label": "MeasurementMedium",
        "type": "MeasurementMediumEnum",
        "writable": false
      },
      "10": {
        "id": 10,
        "cluster_id": 1067,
        "label": "LevelValue",
        "type": "Optional[LevelValueEnum]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1067,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1067,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1067,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1067,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1067,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1067,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "1068": {
    "id": 1068,
    "label": "Pm1ConcentrationMeasurement",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1068,
        "label": "MeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1068,
        "label": "MinMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 1068,
        "label": "MaxMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 1068,
        "label": "PeakMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 1068,
        "label": "PeakMeasuredValueWindow",
        "type": "Optional[elapsed-s]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 1068,
        "label": "AverageMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 1068,
        "label": "AverageMeasuredValueWindow",
        "type": "Optional[elapsed-s]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 1068,
        "label": "Uncertainty",
        "type": "Optional[single]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 1068,
        "label": "MeasurementUnit",
        "type": "Optional[MeasurementUnitEnum]",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 1068,
        "label": "MeasurementMedium",
        "type": "MeasurementMediumEnum",
        "writable": false
      },
      "10": {
        "id": 10,
        "cluster_id": 1068,
        "label": "LevelValue",
        "type": "Optional[LevelValueEnum]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1068,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1068,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1068,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1068,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1068,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1068,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "1069": {
    "id": 1069,
    "label": "Pm10ConcentrationMeasurement",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1069,
        "label": "MeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1069,
        "label": "MinMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 1069,
        "label": "MaxMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 1069,
        "label": "PeakMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 1069,
        "label": "PeakMeasuredValueWindow",
        "type": "Optional[elapsed-s]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 1069,
        "label": "AverageMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 1069,
        "label": "AverageMeasuredValueWindow",
        "type": "Optional[elapsed-s]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 1069,
        "label": "Uncertainty",
        "type": "Optional[single]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 1069,
        "label": "MeasurementUnit",
        "type": "Optional[MeasurementUnitEnum]",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 1069,
        "label": "MeasurementMedium",
        "type": "MeasurementMediumEnum",
        "writable": false
      },
      "10": {
        "id": 10,
        "cluster_id": 1069,
        "label": "LevelValue",
        "type": "Optional[LevelValueEnum]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1069,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1069,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1069,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1069,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1069,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1069,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "1070": {
    "id": 1070,
    "label": "TotalVolatileOrganicCompoundsConcentrationMeasurement",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1070,
        "label": "MeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1070,
        "label": "MinMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 1070,
        "label": "MaxMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 1070,
        "label": "PeakMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 1070,
        "label": "PeakMeasuredValueWindow",
        "type": "Optional[elapsed-s]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 1070,
        "label": "AverageMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 1070,
        "label": "AverageMeasuredValueWindow",
        "type": "Optional[elapsed-s]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 1070,
        "label": "Uncertainty",
        "type": "Optional[single]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 1070,
        "label": "MeasurementUnit",
        "type": "Optional[MeasurementUnitEnum]",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 1070,
        "label": "MeasurementMedium",
        "type": "MeasurementMediumEnum",
        "writable": false
      },
      "10": {
        "id": 10,
        "cluster_id": 1070,
        "label": "LevelValue",
        "type": "Optional[LevelValueEnum]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1070,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1070,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1070,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1070,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1070,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1070,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "1071": {
    "id": 1071,
    "label": "RadonConcentrationMeasurement",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1071,
        "label": "MeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1071,
        "label": "MinMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 1071,
        "label": "MaxMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 1071,
        "label": "PeakMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 1071,
        "label": "PeakMeasuredValueWindow",
        "type": "Optional[elapsed-s]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 1071,
        "label": "AverageMeasuredValue",
        "type": "Optional[Nullable[single]]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 1071,
        "label": "AverageMeasuredValueWindow",
        "type": "Optional[elapsed-s]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 1071,
        "label": "Uncertainty",
        "type": "Optional[single]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 1071,
        "label": "MeasurementUnit",
        "type": "Optional[MeasurementUnitEnum]",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 1071,
        "label": "MeasurementMedium",
        "type": "MeasurementMediumEnum",
        "writable": false
      },
      "10": {
        "id": 10,
        "cluster_id": 1071,
        "label": "LevelValue",
        "type": "Optional[LevelValueEnum]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1071,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1071,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1071,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1071,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1071,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1071,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "1072": {
    "id": 1072,
    "label": "SoilMeasurement",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1072,
        "label": "SoilMoistureMeasurementLimits",
        "type": "MeasurementAccuracyStruct",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1072,
        "label": "SoilMoistureMeasuredValue",
        "type": "Nullable[percent]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1072,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1072,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1072,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1072,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1072,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1072,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "1105": {
    "id": 1105,
    "label": "WiFiNetworkManagement",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1105,
        "label": "Ssid",
        "type": "Nullable[bytes]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1105,
        "label": "PassphraseSurrogate",
        "type": "Nullable[uint64]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1105,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1105,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1105,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1105,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1105,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1105,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 1105,
        "name": "NetworkPassphraseRequest",
        "label": "Network Passphrase Request"
      }
    }
  },
  "1106": {
    "id": 1106,
    "label": "ThreadBorderRouterManagement",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1106,
        "label": "BorderRouterName",
        "type": "string",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1106,
        "label": "BorderAgentId",
        "type": "bytes",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 1106,
        "label": "ThreadVersion",
        "type": "uint16",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 1106,
        "label": "InterfaceEnabled",
        "type": "bool",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 1106,
        "label": "ActiveDatasetTimestamp",
        "type": "Nullable[uint64]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 1106,
        "label": "PendingDatasetTimestamp",
        "type": "Nullable[uint64]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1106,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1106,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1106,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1106,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1106,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1106,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 1106,
        "name": "GetActiveDatasetRequest",
        "label": "Get Active Dataset Request"
      },
      "1": {
        "id": 1,
        "cluster_id": 1106,
        "name": "GetPendingDatasetRequest",
        "label": "Get Pending Dataset Request"
      },
      "3": {
        "id": 3,
        "cluster_id": 1106,
        "name": "SetActiveDatasetRequest",
        "label": "Set Active Dataset Request"
      },
      "4": {
        "id": 4,
        "cluster_id": 1106,
        "name": "SetPendingDatasetRequest",
        "label": "Set Pending Dataset Request"
      }
    }
  },
  "1107": {
    "id": 1107,
    "label": "ThreadNetworkDirectory",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1107,
        "label": "PreferredExtendedPanId",
        "type": "Nullable[bytes]",
        "writable": true
      },
      "1": {
        "id": 1,
        "cluster_id": 1107,
        "label": "ThreadNetworks",
        "type": "List[ThreadNetworkStruct]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 1107,
        "label": "ThreadNetworkTableSize",
        "type": "uint8",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1107,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1107,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1107,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1107,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1107,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1107,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 1107,
        "name": "AddNetwork",
        "label": "Add Network"
      },
      "1": {
        "id": 1,
        "cluster_id": 1107,
        "name": "RemoveNetwork",
        "label": "Remove Network"
      },
      "2": {
        "id": 2,
        "cluster_id": 1107,
        "name": "GetOperationalDataset",
        "label": "Get Operational Dataset"
      }
    }
  },
  "1283": {
    "id": 1283,
    "label": "WakeOnLan",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1283,
        "label": "MacAddress",
        "type": "Optional[string]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1283,
        "label": "LinkLocalAddress",
        "type": "Optional[bytes]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1283,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1283,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1283,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1283,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1283,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1283,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "1284": {
    "id": 1284,
    "label": "Channel",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1284,
        "label": "ChannelList",
        "type": "List[ChannelInfoStruct]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1284,
        "label": "Lineup",
        "type": "Optional[Nullable[LineupInfoStruct]]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 1284,
        "label": "CurrentChannel",
        "type": "Optional[Nullable[ChannelInfoStruct]]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1284,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1284,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1284,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1284,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1284,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1284,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 1284,
        "name": "ChangeChannel",
        "label": "Change Channel"
      },
      "2": {
        "id": 2,
        "cluster_id": 1284,
        "name": "ChangeChannelByNumber",
        "label": "Change Channel By Number"
      },
      "3": {
        "id": 3,
        "cluster_id": 1284,
        "name": "SkipChannel",
        "label": "Skip Channel"
      },
      "4": {
        "id": 4,
        "cluster_id": 1284,
        "name": "GetProgramGuide",
        "label": "Get Program Guide"
      },
      "6": {
        "id": 6,
        "cluster_id": 1284,
        "name": "RecordProgram",
        "label": "Record Program"
      },
      "7": {
        "id": 7,
        "cluster_id": 1284,
        "name": "CancelRecordProgram",
        "label": "Cancel Record Program"
      }
    }
  },
  "1285": {
    "id": 1285,
    "label": "TargetNavigator",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1285,
        "label": "TargetList",
        "type": "List[TargetInfoStruct]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1285,
        "label": "CurrentTarget",
        "type": "Optional[uint8]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1285,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1285,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1285,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1285,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1285,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1285,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 1285,
        "name": "NavigateTarget",
        "label": "Navigate Target"
      }
    }
  },
  "1286": {
    "id": 1286,
    "label": "MediaPlayback",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1286,
        "label": "CurrentState",
        "type": "PlaybackStateEnum",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1286,
        "label": "StartTime",
        "type": "Optional[Nullable[epoch-us]]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 1286,
        "label": "Duration",
        "type": "Optional[Nullable[uint64]]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 1286,
        "label": "SampledPosition",
        "type": "Optional[Nullable[PlaybackPositionStruct]]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 1286,
        "label": "PlaybackSpeed",
        "type": "Optional[single]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 1286,
        "label": "SeekRangeEnd",
        "type": "Optional[Nullable[uint64]]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 1286,
        "label": "SeekRangeStart",
        "type": "Optional[Nullable[uint64]]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 1286,
        "label": "ActiveAudioTrack",
        "type": "Optional[Nullable[TrackStruct]]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 1286,
        "label": "AvailableAudioTracks",
        "type": "List[TrackStruct]",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 1286,
        "label": "ActiveTextTrack",
        "type": "Optional[Nullable[TrackStruct]]",
        "writable": false
      },
      "10": {
        "id": 10,
        "cluster_id": 1286,
        "label": "AvailableTextTracks",
        "type": "List[TrackStruct]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1286,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1286,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1286,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1286,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1286,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1286,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 1286,
        "name": "Play",
        "label": "Play"
      },
      "1": {
        "id": 1,
        "cluster_id": 1286,
        "name": "Pause",
        "label": "Pause"
      },
      "2": {
        "id": 2,
        "cluster_id": 1286,
        "name": "Stop",
        "label": "Stop"
      },
      "3": {
        "id": 3,
        "cluster_id": 1286,
        "name": "StartOver",
        "label": "Start Over"
      },
      "4": {
        "id": 4,
        "cluster_id": 1286,
        "name": "Previous",
        "label": "Previous"
      },
      "5": {
        "id": 5,
        "cluster_id": 1286,
        "name": "Next",
        "label": "Next"
      },
      "6": {
        "id": 6,
        "cluster_id": 1286,
        "name": "Rewind",
        "label": "Rewind"
      },
      "7": {
        "id": 7,
        "cluster_id": 1286,
        "name": "FastForward",
        "label": "Fast Forward"
      },
      "8": {
        "id": 8,
        "cluster_id": 1286,
        "name": "SkipForward",
        "label": "Skip Forward"
      },
      "9": {
        "id": 9,
        "cluster_id": 1286,
        "name": "SkipBackward",
        "label": "Skip Backward"
      },
      "11": {
        "id": 11,
        "cluster_id": 1286,
        "name": "Seek",
        "label": "Seek"
      },
      "12": {
        "id": 12,
        "cluster_id": 1286,
        "name": "ActivateAudioTrack",
        "label": "Activate Audio Track"
      },
      "13": {
        "id": 13,
        "cluster_id": 1286,
        "name": "ActivateTextTrack",
        "label": "Activate Text Track"
      },
      "14": {
        "id": 14,
        "cluster_id": 1286,
        "name": "DeactivateTextTrack",
        "label": "Deactivate Text Track"
      }
    }
  },
  "1287": {
    "id": 1287,
    "label": "MediaInput",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1287,
        "label": "InputList",
        "type": "List[InputInfoStruct]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1287,
        "label": "CurrentInput",
        "type": "uint8",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1287,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1287,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1287,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1287,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1287,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1287,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 1287,
        "name": "SelectInput",
        "label": "Select Input"
      },
      "1": {
        "id": 1,
        "cluster_id": 1287,
        "name": "ShowInputStatus",
        "label": "Show Input Status"
      },
      "2": {
        "id": 2,
        "cluster_id": 1287,
        "name": "HideInputStatus",
        "label": "Hide Input Status"
      },
      "3": {
        "id": 3,
        "cluster_id": 1287,
        "name": "RenameInput",
        "label": "Rename Input"
      }
    }
  },
  "1288": {
    "id": 1288,
    "label": "LowPower",
    "attributes": {
      "65528": {
        "id": 65528,
        "cluster_id": 1288,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1288,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1288,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1288,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1288,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1288,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 1288,
        "name": "Sleep",
        "label": "Sleep"
      }
    }
  },
  "1289": {
    "id": 1289,
    "label": "KeypadInput",
    "attributes": {
      "65528": {
        "id": 65528,
        "cluster_id": 1289,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1289,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1289,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1289,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1289,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1289,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 1289,
        "name": "SendKey",
        "label": "Send Key"
      }
    }
  },
  "1290": {
    "id": 1290,
    "label": "ContentLauncher",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1290,
        "label": "AcceptHeader",
        "type": "List[string]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1290,
        "label": "SupportedStreamingProtocols",
        "type": "Optional[SupportedProtocolsBitmap]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1290,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1290,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1290,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1290,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1290,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1290,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 1290,
        "name": "LaunchContent",
        "label": "Launch Content"
      },
      "1": {
        "id": 1,
        "cluster_id": 1290,
        "name": "LaunchUrl",
        "label": "Launch Url"
      }
    }
  },
  "1291": {
    "id": 1291,
    "label": "AudioOutput",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1291,
        "label": "OutputList",
        "type": "List[OutputInfoStruct]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1291,
        "label": "CurrentOutput",
        "type": "uint8",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1291,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1291,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1291,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1291,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1291,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1291,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 1291,
        "name": "SelectOutput",
        "label": "Select Output"
      },
      "1": {
        "id": 1,
        "cluster_id": 1291,
        "name": "RenameOutput",
        "label": "Rename Output"
      }
    }
  },
  "1292": {
    "id": 1292,
    "label": "ApplicationLauncher",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1292,
        "label": "CatalogList",
        "type": "List[uint16]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1292,
        "label": "CurrentApp",
        "type": "Optional[Nullable[ApplicationEPStruct]]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1292,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1292,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1292,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1292,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1292,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1292,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 1292,
        "name": "LaunchApp",
        "label": "Launch App"
      },
      "1": {
        "id": 1,
        "cluster_id": 1292,
        "name": "StopApp",
        "label": "Stop App"
      },
      "2": {
        "id": 2,
        "cluster_id": 1292,
        "name": "HideApp",
        "label": "Hide App"
      }
    }
  },
  "1293": {
    "id": 1293,
    "label": "ApplicationBasic",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1293,
        "label": "VendorName",
        "type": "Optional[string]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1293,
        "label": "VendorId",
        "type": "Optional[vendor-id]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 1293,
        "label": "ApplicationName",
        "type": "string",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 1293,
        "label": "ProductId",
        "type": "Optional[uint16]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 1293,
        "label": "Application",
        "type": "ApplicationStruct",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 1293,
        "label": "Status",
        "type": "ApplicationStatusEnum",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 1293,
        "label": "ApplicationVersion",
        "type": "string",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 1293,
        "label": "AllowedVendorList",
        "type": "List[vendor-id]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1293,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1293,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1293,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1293,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1293,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1293,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "1294": {
    "id": 1294,
    "label": "AccountLogin",
    "attributes": {
      "65528": {
        "id": 65528,
        "cluster_id": 1294,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1294,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1294,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1294,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1294,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1294,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 1294,
        "name": "GetSetupPin",
        "label": "Get Setup Pin"
      },
      "2": {
        "id": 2,
        "cluster_id": 1294,
        "name": "Login",
        "label": "Login"
      },
      "3": {
        "id": 3,
        "cluster_id": 1294,
        "name": "Logout",
        "label": "Logout"
      }
    }
  },
  "1295": {
    "id": 1295,
    "label": "ContentControl",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1295,
        "label": "Enabled",
        "type": "bool",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1295,
        "label": "OnDemandRatings",
        "type": "List[RatingNameStruct]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 1295,
        "label": "OnDemandRatingThreshold",
        "type": "Optional[string]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 1295,
        "label": "ScheduledContentRatings",
        "type": "List[RatingNameStruct]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 1295,
        "label": "ScheduledContentRatingThreshold",
        "type": "Optional[string]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 1295,
        "label": "ScreenDailyTime",
        "type": "Optional[elapsed-s]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 1295,
        "label": "RemainingScreenTime",
        "type": "Optional[elapsed-s]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 1295,
        "label": "BlockUnrated",
        "type": "Optional[bool]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 1295,
        "label": "BlockChannelList",
        "type": "List[BlockChannelStruct]",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 1295,
        "label": "BlockApplicationList",
        "type": "List[AppInfoStruct]",
        "writable": false
      },
      "10": {
        "id": 10,
        "cluster_id": 1295,
        "label": "BlockContentTimeWindow",
        "type": "List[TimeWindowStruct]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1295,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1295,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1295,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1295,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1295,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1295,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 1295,
        "name": "UpdatePin",
        "label": "Update Pin"
      },
      "1": {
        "id": 1,
        "cluster_id": 1295,
        "name": "ResetPin",
        "label": "Reset Pin"
      },
      "3": {
        "id": 3,
        "cluster_id": 1295,
        "name": "Enable",
        "label": "Enable"
      },
      "4": {
        "id": 4,
        "cluster_id": 1295,
        "name": "Disable",
        "label": "Disable"
      },
      "5": {
        "id": 5,
        "cluster_id": 1295,
        "name": "AddBonusTime",
        "label": "Add Bonus Time"
      },
      "6": {
        "id": 6,
        "cluster_id": 1295,
        "name": "SetScreenDailyTime",
        "label": "Set Screen Daily Time"
      },
      "7": {
        "id": 7,
        "cluster_id": 1295,
        "name": "BlockUnratedContent",
        "label": "Block Unrated Content"
      },
      "8": {
        "id": 8,
        "cluster_id": 1295,
        "name": "UnblockUnratedContent",
        "label": "Unblock Unrated Content"
      },
      "9": {
        "id": 9,
        "cluster_id": 1295,
        "name": "SetOnDemandRatingThreshold",
        "label": "Set On Demand Rating Threshold"
      },
      "10": {
        "id": 10,
        "cluster_id": 1295,
        "name": "SetScheduledContentRatingThreshold",
        "label": "Set Scheduled Content Rating Threshold"
      },
      "11": {
        "id": 11,
        "cluster_id": 1295,
        "name": "AddBlockChannels",
        "label": "Add Block Channels"
      },
      "12": {
        "id": 12,
        "cluster_id": 1295,
        "name": "RemoveBlockChannels",
        "label": "Remove Block Channels"
      },
      "13": {
        "id": 13,
        "cluster_id": 1295,
        "name": "AddBlockApplications",
        "label": "Add Block Applications"
      },
      "14": {
        "id": 14,
        "cluster_id": 1295,
        "name": "RemoveBlockApplications",
        "label": "Remove Block Applications"
      },
      "15": {
        "id": 15,
        "cluster_id": 1295,
        "name": "SetBlockContentTimeWindow",
        "label": "Set Block Content Time Window"
      },
      "16": {
        "id": 16,
        "cluster_id": 1295,
        "name": "RemoveBlockContentTimeWindow",
        "label": "Remove Block Content Time Window"
      }
    }
  },
  "1296": {
    "id": 1296,
    "label": "ContentAppObserver",
    "attributes": {
      "65528": {
        "id": 65528,
        "cluster_id": 1296,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1296,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1296,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1296,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1296,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1296,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 1296,
        "name": "ContentAppMessage",
        "label": "Content App Message"
      }
    }
  },
  "1360": {
    "id": 1360,
    "label": "ZoneManagement",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1360,
        "label": "MaxUserDefinedZones",
        "type": "Optional[uint8]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1360,
        "label": "MaxZones",
        "type": "uint8",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 1360,
        "label": "Zones",
        "type": "List[ZoneInformationStruct]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 1360,
        "label": "Triggers",
        "type": "List[ZoneTriggerControlStruct]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 1360,
        "label": "SensitivityMax",
        "type": "uint8",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 1360,
        "label": "Sensitivity",
        "type": "Optional[uint8]",
        "writable": true
      },
      "6": {
        "id": 6,
        "cluster_id": 1360,
        "label": "TwoDCartesianMax",
        "type": "Optional[TwoDCartesianVertexStruct]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1360,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1360,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1360,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1360,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1360,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1360,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 1360,
        "name": "CreateTwoDCartesianZone",
        "label": "Create Two Dcartesian Zone"
      },
      "2": {
        "id": 2,
        "cluster_id": 1360,
        "name": "UpdateTwoDCartesianZone",
        "label": "Update Two Dcartesian Zone"
      },
      "3": {
        "id": 3,
        "cluster_id": 1360,
        "name": "RemoveZone",
        "label": "Remove Zone"
      },
      "4": {
        "id": 4,
        "cluster_id": 1360,
        "name": "CreateOrUpdateTrigger",
        "label": "Create Or Update Trigger"
      },
      "5": {
        "id": 5,
        "cluster_id": 1360,
        "name": "RemoveTrigger",
        "label": "Remove Trigger"
      }
    }
  },
  "1361": {
    "id": 1361,
    "label": "CameraAvStreamManagement",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1361,
        "label": "MaxConcurrentEncoders",
        "type": "Optional[uint8]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1361,
        "label": "MaxEncodedPixelRate",
        "type": "Optional[uint32]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 1361,
        "label": "VideoSensorParams",
        "type": "Optional[VideoSensorParamsStruct]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 1361,
        "label": "NightVisionUsesInfrared",
        "type": "Optional[bool]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 1361,
        "label": "MinViewportResolution",
        "type": "Optional[VideoResolutionStruct]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 1361,
        "label": "RateDistortionTradeOffPoints",
        "type": "List[RateDistortionTradeOffPointsStruct]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 1361,
        "label": "MaxContentBufferSize",
        "type": "uint32",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 1361,
        "label": "MicrophoneCapabilities",
        "type": "Optional[AudioCapabilitiesStruct]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 1361,
        "label": "SpeakerCapabilities",
        "type": "Optional[AudioCapabilitiesStruct]",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 1361,
        "label": "TwoWayTalkSupport",
        "type": "Optional[TwoWayTalkSupportTypeEnum]",
        "writable": false
      },
      "10": {
        "id": 10,
        "cluster_id": 1361,
        "label": "SnapshotCapabilities",
        "type": "List[SnapshotCapabilitiesStruct]",
        "writable": false
      },
      "11": {
        "id": 11,
        "cluster_id": 1361,
        "label": "MaxNetworkBandwidth",
        "type": "uint32",
        "writable": false
      },
      "12": {
        "id": 12,
        "cluster_id": 1361,
        "label": "CurrentFrameRate",
        "type": "Optional[uint16]",
        "writable": false
      },
      "13": {
        "id": 13,
        "cluster_id": 1361,
        "label": "HdrModeEnabled",
        "type": "Optional[bool]",
        "writable": true
      },
      "14": {
        "id": 14,
        "cluster_id": 1361,
        "label": "SupportedStreamUsages",
        "type": "List[StreamUsageEnum]",
        "writable": false
      },
      "15": {
        "id": 15,
        "cluster_id": 1361,
        "label": "AllocatedVideoStreams",
        "type": "List[VideoStreamStruct]",
        "writable": false
      },
      "16": {
        "id": 16,
        "cluster_id": 1361,
        "label": "AllocatedAudioStreams",
        "type": "List[AudioStreamStruct]",
        "writable": false
      },
      "17": {
        "id": 17,
        "cluster_id": 1361,
        "label": "AllocatedSnapshotStreams",
        "type": "List[SnapshotStreamStruct]",
        "writable": false
      },
      "18": {
        "id": 18,
        "cluster_id": 1361,
        "label": "StreamUsagePriorities",
        "type": "List[StreamUsageEnum]",
        "writable": false
      },
      "19": {
        "id": 19,
        "cluster_id": 1361,
        "label": "SoftRecordingPrivacyModeEnabled",
        "type": "Optional[bool]",
        "writable": true
      },
      "20": {
        "id": 20,
        "cluster_id": 1361,
        "label": "SoftLivestreamPrivacyModeEnabled",
        "type": "Optional[bool]",
        "writable": true
      },
      "21": {
        "id": 21,
        "cluster_id": 1361,
        "label": "HardPrivacyModeOn",
        "type": "Optional[bool]",
        "writable": false
      },
      "22": {
        "id": 22,
        "cluster_id": 1361,
        "label": "NightVision",
        "type": "Optional[TriStateAutoEnum]",
        "writable": true
      },
      "23": {
        "id": 23,
        "cluster_id": 1361,
        "label": "NightVisionIllum",
        "type": "Optional[TriStateAutoEnum]",
        "writable": true
      },
      "24": {
        "id": 24,
        "cluster_id": 1361,
        "label": "Viewport",
        "type": "Optional[ViewportStruct]",
        "writable": true
      },
      "25": {
        "id": 25,
        "cluster_id": 1361,
        "label": "SpeakerMuted",
        "type": "Optional[bool]",
        "writable": true
      },
      "26": {
        "id": 26,
        "cluster_id": 1361,
        "label": "SpeakerVolumeLevel",
        "type": "Optional[uint8]",
        "writable": true
      },
      "27": {
        "id": 27,
        "cluster_id": 1361,
        "label": "SpeakerMaxLevel",
        "type": "Optional[uint8]",
        "writable": false
      },
      "28": {
        "id": 28,
        "cluster_id": 1361,
        "label": "SpeakerMinLevel",
        "type": "Optional[uint8]",
        "writable": false
      },
      "29": {
        "id": 29,
        "cluster_id": 1361,
        "label": "MicrophoneMuted",
        "type": "Optional[bool]",
        "writable": true
      },
      "30": {
        "id": 30,
        "cluster_id": 1361,
        "label": "MicrophoneVolumeLevel",
        "type": "Optional[uint8]",
        "writable": true
      },
      "31": {
        "id": 31,
        "cluster_id": 1361,
        "label": "MicrophoneMaxLevel",
        "type": "Optional[uint8]",
        "writable": false
      },
      "32": {
        "id": 32,
        "cluster_id": 1361,
        "label": "MicrophoneMinLevel",
        "type": "Optional[uint8]",
        "writable": false
      },
      "33": {
        "id": 33,
        "cluster_id": 1361,
        "label": "MicrophoneAgcEnabled",
        "type": "Optional[bool]",
        "writable": true
      },
      "34": {
        "id": 34,
        "cluster_id": 1361,
        "label": "ImageRotation",
        "type": "Optional[uint16]",
        "writable": true
      },
      "35": {
        "id": 35,
        "cluster_id": 1361,
        "label": "ImageFlipHorizontal",
        "type": "Optional[bool]",
        "writable": true
      },
      "36": {
        "id": 36,
        "cluster_id": 1361,
        "label": "ImageFlipVertical",
        "type": "Optional[bool]",
        "writable": true
      },
      "37": {
        "id": 37,
        "cluster_id": 1361,
        "label": "LocalVideoRecordingEnabled",
        "type": "Optional[bool]",
        "writable": true
      },
      "38": {
        "id": 38,
        "cluster_id": 1361,
        "label": "LocalSnapshotRecordingEnabled",
        "type": "Optional[bool]",
        "writable": true
      },
      "39": {
        "id": 39,
        "cluster_id": 1361,
        "label": "StatusLightEnabled",
        "type": "Optional[bool]",
        "writable": true
      },
      "40": {
        "id": 40,
        "cluster_id": 1361,
        "label": "StatusLightBrightness",
        "type": "Optional[ThreeLevelAutoEnum]",
        "writable": true
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1361,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1361,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1361,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1361,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1361,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1361,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 1361,
        "name": "AudioStreamAllocate",
        "label": "Audio Stream Allocate"
      },
      "2": {
        "id": 2,
        "cluster_id": 1361,
        "name": "AudioStreamDeallocate",
        "label": "Audio Stream Deallocate"
      },
      "3": {
        "id": 3,
        "cluster_id": 1361,
        "name": "VideoStreamAllocate",
        "label": "Video Stream Allocate"
      },
      "5": {
        "id": 5,
        "cluster_id": 1361,
        "name": "VideoStreamModify",
        "label": "Video Stream Modify"
      },
      "6": {
        "id": 6,
        "cluster_id": 1361,
        "name": "VideoStreamDeallocate",
        "label": "Video Stream Deallocate"
      },
      "7": {
        "id": 7,
        "cluster_id": 1361,
        "name": "SnapshotStreamAllocate",
        "label": "Snapshot Stream Allocate"
      },
      "9": {
        "id": 9,
        "cluster_id": 1361,
        "name": "SnapshotStreamModify",
        "label": "Snapshot Stream Modify"
      },
      "10": {
        "id": 10,
        "cluster_id": 1361,
        "name": "SnapshotStreamDeallocate",
        "label": "Snapshot Stream Deallocate"
      },
      "11": {
        "id": 11,
        "cluster_id": 1361,
        "name": "SetStreamPriorities",
        "label": "Set Stream Priorities"
      },
      "12": {
        "id": 12,
        "cluster_id": 1361,
        "name": "CaptureSnapshot",
        "label": "Capture Snapshot"
      }
    }
  },
  "1362": {
    "id": 1362,
    "label": "CameraAvSettingsUserLevelManagement",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1362,
        "label": "MptzPosition",
        "type": "Optional[MPTZStruct]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1362,
        "label": "MaxPresets",
        "type": "Optional[uint8]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 1362,
        "label": "MptzPresets",
        "type": "List[MPTZPresetStruct]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 1362,
        "label": "DptzStreams",
        "type": "List[DPTZStruct]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 1362,
        "label": "ZoomMax",
        "type": "Optional[uint8]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 1362,
        "label": "TiltMin",
        "type": "Optional[int16]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 1362,
        "label": "TiltMax",
        "type": "Optional[int16]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 1362,
        "label": "PanMin",
        "type": "Optional[int16]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 1362,
        "label": "PanMax",
        "type": "Optional[int16]",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 1362,
        "label": "MovementState",
        "type": "Optional[PhysicalMovementEnum]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1362,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1362,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1362,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1362,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1362,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1362,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 1362,
        "name": "MptzSetPosition",
        "label": "Mptz Set Position"
      },
      "1": {
        "id": 1,
        "cluster_id": 1362,
        "name": "MptzRelativeMove",
        "label": "Mptz Relative Move"
      },
      "2": {
        "id": 2,
        "cluster_id": 1362,
        "name": "MptzMoveToPreset",
        "label": "Mptz Move To Preset"
      },
      "3": {
        "id": 3,
        "cluster_id": 1362,
        "name": "MptzSavePreset",
        "label": "Mptz Save Preset"
      },
      "4": {
        "id": 4,
        "cluster_id": 1362,
        "name": "MptzRemovePreset",
        "label": "Mptz Remove Preset"
      },
      "5": {
        "id": 5,
        "cluster_id": 1362,
        "name": "DptzSetViewport",
        "label": "Dptz Set Viewport"
      },
      "6": {
        "id": 6,
        "cluster_id": 1362,
        "name": "DptzRelativeMove",
        "label": "Dptz Relative Move"
      }
    }
  },
  "1363": {
    "id": 1363,
    "label": "WebRtcTransportProvider",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1363,
        "label": "CurrentSessions",
        "type": "List[WebRtcTransportDefinitions.WebRTCSessionStruct]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1363,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1363,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1363,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1363,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1363,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1363,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 1363,
        "name": "SolicitOffer",
        "label": "Solicit Offer"
      },
      "2": {
        "id": 2,
        "cluster_id": 1363,
        "name": "ProvideOffer",
        "label": "Provide Offer"
      },
      "4": {
        "id": 4,
        "cluster_id": 1363,
        "name": "ProvideAnswer",
        "label": "Provide Answer"
      },
      "5": {
        "id": 5,
        "cluster_id": 1363,
        "name": "ProvideIceCandidates",
        "label": "Provide Ice Candidates"
      },
      "6": {
        "id": 6,
        "cluster_id": 1363,
        "name": "EndSession",
        "label": "End Session"
      }
    }
  },
  "1364": {
    "id": 1364,
    "label": "WebRtcTransportRequestor",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1364,
        "label": "CurrentSessions",
        "type": "List[WebRtcTransportDefinitions.WebRTCSessionStruct]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1364,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1364,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1364,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1364,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1364,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1364,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 1364,
        "name": "Offer",
        "label": "Offer"
      },
      "1": {
        "id": 1,
        "cluster_id": 1364,
        "name": "Answer",
        "label": "Answer"
      },
      "2": {
        "id": 2,
        "cluster_id": 1364,
        "name": "IceCandidates",
        "label": "Ice Candidates"
      },
      "3": {
        "id": 3,
        "cluster_id": 1364,
        "name": "End",
        "label": "End"
      }
    }
  },
  "1365": {
    "id": 1365,
    "label": "PushAvStreamTransport",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1365,
        "label": "SupportedFormats",
        "type": "List[SupportedFormatStruct]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1365,
        "label": "CurrentConnections",
        "type": "List[TransportConfigurationStruct]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1365,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1365,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1365,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1365,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1365,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1365,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 1365,
        "name": "AllocatePushTransport",
        "label": "Allocate Push Transport"
      },
      "2": {
        "id": 2,
        "cluster_id": 1365,
        "name": "DeallocatePushTransport",
        "label": "Deallocate Push Transport"
      },
      "3": {
        "id": 3,
        "cluster_id": 1365,
        "name": "ModifyPushTransport",
        "label": "Modify Push Transport"
      },
      "4": {
        "id": 4,
        "cluster_id": 1365,
        "name": "SetTransportStatus",
        "label": "Set Transport Status"
      },
      "5": {
        "id": 5,
        "cluster_id": 1365,
        "name": "ManuallyTriggerTransport",
        "label": "Manually Trigger Transport"
      },
      "6": {
        "id": 6,
        "cluster_id": 1365,
        "name": "FindTransport",
        "label": "Find Transport"
      }
    }
  },
  "1366": {
    "id": 1366,
    "label": "Chime",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1366,
        "label": "InstalledChimeSounds",
        "type": "List[ChimeSoundStruct]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1366,
        "label": "SelectedChime",
        "type": "uint8",
        "writable": true
      },
      "2": {
        "id": 2,
        "cluster_id": 1366,
        "label": "Enabled",
        "type": "bool",
        "writable": true
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1366,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1366,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1366,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1366,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1366,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1366,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 1366,
        "name": "PlayChimeSound",
        "label": "Play Chime Sound"
      }
    }
  },
  "1792": {
    "id": 1792,
    "label": "CommodityTariff",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1792,
        "label": "TariffInfo",
        "type": "Nullable[TariffInformationStruct]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1792,
        "label": "TariffUnit",
        "type": "Nullable[TariffUnitEnum]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 1792,
        "label": "StartDate",
        "type": "Nullable[epoch-s]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 1792,
        "label": "DayEntries",
        "type": "List[DayEntryStruct]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 1792,
        "label": "DayPatterns",
        "type": "List[DayPatternStruct]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 1792,
        "label": "CalendarPeriods",
        "type": "List[CalendarPeriodStruct]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 1792,
        "label": "IndividualDays",
        "type": "List[DayStruct]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 1792,
        "label": "CurrentDay",
        "type": "Nullable[DayStruct]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 1792,
        "label": "NextDay",
        "type": "Nullable[DayStruct]",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 1792,
        "label": "CurrentDayEntry",
        "type": "Nullable[DayEntryStruct]",
        "writable": false
      },
      "10": {
        "id": 10,
        "cluster_id": 1792,
        "label": "CurrentDayEntryDate",
        "type": "Nullable[epoch-s]",
        "writable": false
      },
      "11": {
        "id": 11,
        "cluster_id": 1792,
        "label": "NextDayEntry",
        "type": "Nullable[DayEntryStruct]",
        "writable": false
      },
      "12": {
        "id": 12,
        "cluster_id": 1792,
        "label": "NextDayEntryDate",
        "type": "Nullable[epoch-s]",
        "writable": false
      },
      "13": {
        "id": 13,
        "cluster_id": 1792,
        "label": "TariffComponents",
        "type": "List[TariffComponentStruct]",
        "writable": false
      },
      "14": {
        "id": 14,
        "cluster_id": 1792,
        "label": "TariffPeriods",
        "type": "List[TariffPeriodStruct]",
        "writable": false
      },
      "15": {
        "id": 15,
        "cluster_id": 1792,
        "label": "CurrentTariffComponents",
        "type": "List[TariffComponentStruct]",
        "writable": false
      },
      "16": {
        "id": 16,
        "cluster_id": 1792,
        "label": "NextTariffComponents",
        "type": "List[TariffComponentStruct]",
        "writable": false
      },
      "17": {
        "id": 17,
        "cluster_id": 1792,
        "label": "DefaultRandomizationOffset",
        "type": "Optional[Nullable[int16]]",
        "writable": false
      },
      "18": {
        "id": 18,
        "cluster_id": 1792,
        "label": "DefaultRandomizationType",
        "type": "Optional[Nullable[DayEntryRandomizationTypeEnum]]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1792,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1792,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1792,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1792,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1792,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1792,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 1792,
        "name": "GetTariffComponent",
        "label": "Get Tariff Component"
      },
      "1": {
        "id": 1,
        "cluster_id": 1792,
        "name": "GetDayEntry",
        "label": "Get Day Entry"
      }
    }
  },
  "1872": {
    "id": 1872,
    "label": "EcosystemInformation",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1872,
        "label": "DeviceDirectory",
        "type": "List[EcosystemDeviceStruct]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1872,
        "label": "LocationDirectory",
        "type": "List[EcosystemLocationStruct]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1872,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1872,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1872,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1872,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1872,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1872,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "1873": {
    "id": 1873,
    "label": "CommissionerControl",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1873,
        "label": "SupportedDeviceCategories",
        "type": "SupportedDeviceCategoryBitmap",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1873,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1873,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1873,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1873,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1873,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1873,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 1873,
        "name": "RequestCommissioningApproval",
        "label": "Request Commissioning Approval"
      },
      "1": {
        "id": 1,
        "cluster_id": 1873,
        "name": "CommissionNode",
        "label": "Commission Node"
      }
    }
  },
  "1874": {
    "id": 1874,
    "label": "JointFabricDatastore",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1874,
        "label": "AnchorRootCa",
        "type": "Optional[bytes]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 1874,
        "label": "AnchorNodeId",
        "type": "Optional[node-id]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 1874,
        "label": "AnchorVendorId",
        "type": "Optional[vendor-id]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 1874,
        "label": "FriendlyName",
        "type": "Optional[string]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 1874,
        "label": "GroupKeySetList",
        "type": "List[DatastoreGroupKeySetStruct]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 1874,
        "label": "GroupList",
        "type": "List[DatastoreGroupInformationEntryStruct]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 1874,
        "label": "NodeList",
        "type": "List[DatastoreNodeInformationEntryStruct]",
        "writable": false
      },
      "7": {
        "id": 7,
        "cluster_id": 1874,
        "label": "AdminList",
        "type": "List[DatastoreAdministratorInformationEntryStruct]",
        "writable": false
      },
      "8": {
        "id": 8,
        "cluster_id": 1874,
        "label": "Status",
        "type": "Optional[DatastoreStatusEntryStruct]",
        "writable": false
      },
      "9": {
        "id": 9,
        "cluster_id": 1874,
        "label": "EndpointGroupIdList",
        "type": "List[DatastoreEndpointGroupIDEntryStruct]",
        "writable": false
      },
      "10": {
        "id": 10,
        "cluster_id": 1874,
        "label": "EndpointBindingList",
        "type": "List[DatastoreEndpointBindingEntryStruct]",
        "writable": false
      },
      "11": {
        "id": 11,
        "cluster_id": 1874,
        "label": "NodeKeySetList",
        "type": "List[DatastoreNodeKeySetEntryStruct]",
        "writable": false
      },
      "12": {
        "id": 12,
        "cluster_id": 1874,
        "label": "NodeAclList",
        "type": "List[DatastoreACLEntryStruct]",
        "writable": false
      },
      "13": {
        "id": 13,
        "cluster_id": 1874,
        "label": "NodeEndpointList",
        "type": "List[DatastoreEndpointEntryStruct]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1874,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1874,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1874,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1874,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1874,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1874,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 1874,
        "name": "AddKeySet",
        "label": "Add Key Set"
      },
      "1": {
        "id": 1,
        "cluster_id": 1874,
        "name": "UpdateKeySet",
        "label": "Update Key Set"
      },
      "2": {
        "id": 2,
        "cluster_id": 1874,
        "name": "RemoveKeySet",
        "label": "Remove Key Set"
      },
      "3": {
        "id": 3,
        "cluster_id": 1874,
        "name": "AddGroup",
        "label": "Add Group"
      },
      "4": {
        "id": 4,
        "cluster_id": 1874,
        "name": "UpdateGroup",
        "label": "Update Group"
      },
      "5": {
        "id": 5,
        "cluster_id": 1874,
        "name": "RemoveGroup",
        "label": "Remove Group"
      },
      "6": {
        "id": 6,
        "cluster_id": 1874,
        "name": "AddAdmin",
        "label": "Add Admin"
      },
      "7": {
        "id": 7,
        "cluster_id": 1874,
        "name": "UpdateAdmin",
        "label": "Update Admin"
      },
      "8": {
        "id": 8,
        "cluster_id": 1874,
        "name": "RemoveAdmin",
        "label": "Remove Admin"
      },
      "9": {
        "id": 9,
        "cluster_id": 1874,
        "name": "AddPendingNode",
        "label": "Add Pending Node"
      },
      "10": {
        "id": 10,
        "cluster_id": 1874,
        "name": "RefreshNode",
        "label": "Refresh Node"
      },
      "11": {
        "id": 11,
        "cluster_id": 1874,
        "name": "UpdateNode",
        "label": "Update Node"
      },
      "12": {
        "id": 12,
        "cluster_id": 1874,
        "name": "RemoveNode",
        "label": "Remove Node"
      },
      "13": {
        "id": 13,
        "cluster_id": 1874,
        "name": "UpdateEndpointForNode",
        "label": "Update Endpoint For Node"
      },
      "14": {
        "id": 14,
        "cluster_id": 1874,
        "name": "AddGroupIdToEndpointForNode",
        "label": "Add Group Id To Endpoint For Node"
      },
      "15": {
        "id": 15,
        "cluster_id": 1874,
        "name": "RemoveGroupIdFromEndpointForNode",
        "label": "Remove Group Id From Endpoint For Node"
      },
      "16": {
        "id": 16,
        "cluster_id": 1874,
        "name": "AddBindingToEndpointForNode",
        "label": "Add Binding To Endpoint For Node"
      },
      "17": {
        "id": 17,
        "cluster_id": 1874,
        "name": "RemoveBindingFromEndpointForNode",
        "label": "Remove Binding From Endpoint For Node"
      },
      "18": {
        "id": 18,
        "cluster_id": 1874,
        "name": "AddAclToNode",
        "label": "Add Acl To Node"
      },
      "19": {
        "id": 19,
        "cluster_id": 1874,
        "name": "RemoveAclFromNode",
        "label": "Remove Acl From Node"
      }
    }
  },
  "1875": {
    "id": 1875,
    "label": "JointFabricAdministrator",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 1875,
        "label": "AdministratorFabricIndex",
        "type": "Optional[Nullable[fabric-idx]]",
        "writable": true
      },
      "65528": {
        "id": 65528,
        "cluster_id": 1875,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 1875,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 1875,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 1875,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 1875,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 1875,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 1875,
        "name": "IcaccsrRequest",
        "label": "Icaccsr Request"
      },
      "2": {
        "id": 2,
        "cluster_id": 1875,
        "name": "AddIcac",
        "label": "Add Icac"
      },
      "4": {
        "id": 4,
        "cluster_id": 1875,
        "name": "OpenJointCommissioningWindow",
        "label": "Open Joint Commissioning Window"
      },
      "5": {
        "id": 5,
        "cluster_id": 1875,
        "name": "TransferAnchorRequest",
        "label": "Transfer Anchor Request"
      },
      "7": {
        "id": 7,
        "cluster_id": 1875,
        "name": "TransferAnchorComplete",
        "label": "Transfer Anchor Complete"
      },
      "8": {
        "id": 8,
        "cluster_id": 1875,
        "name": "AnnounceJointFabricAdministrator",
        "label": "Announce Joint Fabric Administrator"
      }
    }
  },
  "2049": {
    "id": 2049,
    "label": "TlsCertificateManagement",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 2049,
        "label": "MaxRootCertificates",
        "type": "uint8",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 2049,
        "label": "ProvisionedRootCertificates",
        "type": "List[TLSCertStruct]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 2049,
        "label": "MaxClientCertificates",
        "type": "uint8",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 2049,
        "label": "ProvisionedClientCertificates",
        "type": "List[TLSClientCertificateDetailStruct]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 2049,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 2049,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 2049,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 2049,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 2049,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 2049,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 2049,
        "name": "ProvisionRootCertificate",
        "label": "Provision Root Certificate"
      },
      "2": {
        "id": 2,
        "cluster_id": 2049,
        "name": "FindRootCertificate",
        "label": "Find Root Certificate"
      },
      "4": {
        "id": 4,
        "cluster_id": 2049,
        "name": "LookupRootCertificate",
        "label": "Lookup Root Certificate"
      },
      "6": {
        "id": 6,
        "cluster_id": 2049,
        "name": "RemoveRootCertificate",
        "label": "Remove Root Certificate"
      },
      "7": {
        "id": 7,
        "cluster_id": 2049,
        "name": "ClientCsr",
        "label": "Client Csr"
      },
      "9": {
        "id": 9,
        "cluster_id": 2049,
        "name": "ProvisionClientCertificate",
        "label": "Provision Client Certificate"
      },
      "10": {
        "id": 10,
        "cluster_id": 2049,
        "name": "FindClientCertificate",
        "label": "Find Client Certificate"
      },
      "12": {
        "id": 12,
        "cluster_id": 2049,
        "name": "LookupClientCertificate",
        "label": "Lookup Client Certificate"
      },
      "14": {
        "id": 14,
        "cluster_id": 2049,
        "name": "RemoveClientCertificate",
        "label": "Remove Client Certificate"
      }
    }
  },
  "2050": {
    "id": 2050,
    "label": "TlsClientManagement",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 2050,
        "label": "MaxProvisioned",
        "type": "uint8",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 2050,
        "label": "ProvisionedEndpoints",
        "type": "List[TLSEndpointStruct]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 2050,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 2050,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 2050,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 2050,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 2050,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 2050,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 2050,
        "name": "ProvisionEndpoint",
        "label": "Provision Endpoint"
      },
      "2": {
        "id": 2,
        "cluster_id": 2050,
        "name": "FindEndpoint",
        "label": "Find Endpoint"
      },
      "4": {
        "id": 4,
        "cluster_id": 2050,
        "name": "RemoveEndpoint",
        "label": "Remove Endpoint"
      }
    }
  },
  "2820": {
    "id": 2820,
    "label": "DraftElectricalMeasurementCluster",
    "attributes": {
      "1285": {
        "id": 1285,
        "cluster_id": 2820,
        "label": "RmsVoltage",
        "type": "Optional[unknown]",
        "writable": false
      },
      "1288": {
        "id": 1288,
        "cluster_id": 2820,
        "label": "RmsCurrent",
        "type": "Optional[unknown]",
        "writable": false
      },
      "1291": {
        "id": 1291,
        "cluster_id": 2820,
        "label": "ActivePower",
        "type": "Optional[unknown]",
        "writable": false
      },
      "1536": {
        "id": 1536,
        "cluster_id": 2820,
        "label": "AcVoltageMultiplier",
        "type": "Optional[unknown]",
        "writable": false
      },
      "1537": {
        "id": 1537,
        "cluster_id": 2820,
        "label": "AcVoltageDivisor",
        "type": "Optional[unknown]",
        "writable": false
      },
      "1538": {
        "id": 1538,
        "cluster_id": 2820,
        "label": "AcCurrentMultiplier",
        "type": "Optional[unknown]",
        "writable": false
      },
      "1539": {
        "id": 1539,
        "cluster_id": 2820,
        "label": "AcCurrentDivisor",
        "type": "Optional[unknown]",
        "writable": false
      },
      "1540": {
        "id": 1540,
        "cluster_id": 2820,
        "label": "AcPowerMultiplier",
        "type": "Optional[unknown]",
        "writable": false
      },
      "1541": {
        "id": 1541,
        "cluster_id": 2820,
        "label": "AcPowerDivisor",
        "type": "Optional[unknown]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 2820,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 2820,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 2820,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 2820,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 2820,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 2820,
        "label": "ClusterRevision",
        "type": "uint16",
        "writable": false
      }
    },
    "commands": {}
  },
  "2822": {
    "id": 2822,
    "label": "MeterIdentification",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 2822,
        "label": "MeterType",
        "type": "Nullable[MeterTypeEnum]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 2822,
        "label": "PointOfDelivery",
        "type": "Nullable[string]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 2822,
        "label": "MeterSerialNumber",
        "type": "Nullable[string]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 2822,
        "label": "ProtocolVersion",
        "type": "Optional[Nullable[string]]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 2822,
        "label": "PowerThreshold",
        "type": "Optional[Nullable[PowerThresholdStruct]]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 2822,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 2822,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 2822,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 2822,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 2822,
        "label": "FeatureMap",
        "type": "FeatureMap",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 2822,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "2823": {
    "id": 2823,
    "label": "CommodityMetering",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 2823,
        "label": "MeteredQuantity",
        "type": "List[MeteredQuantityStruct]",
        "writable": false
      },
      "1": {
        "id": 1,
        "cluster_id": 2823,
        "label": "MeteredQuantityTimestamp",
        "type": "Nullable[epoch-s]",
        "writable": false
      },
      "2": {
        "id": 2,
        "cluster_id": 2823,
        "label": "TariffUnit",
        "type": "Nullable[TariffUnitEnum]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 2823,
        "label": "MaximumMeteredQuantities",
        "type": "Nullable[uint16]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 2823,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 2823,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 2823,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 2823,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 2823,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 2823,
        "label": "ClusterRevision",
        "type": "ClusterRevision",
        "writable": false
      }
    },
    "commands": {}
  },
  "302775297": {
    "id": 302775297,
    "label": "HeimanCluster",
    "attributes": {
      "16": {
        "id": 16,
        "cluster_id": 302775297,
        "label": "TamperAlarm",
        "type": "Optional[unknown]",
        "writable": false
      },
      "17": {
        "id": 17,
        "cluster_id": 302775297,
        "label": "PreheatingState",
        "type": "Optional[unknown]",
        "writable": false
      },
      "18": {
        "id": 18,
        "cluster_id": 302775297,
        "label": "NoDisturbingState",
        "type": "Optional[unknown]",
        "writable": false
      },
      "19": {
        "id": 19,
        "cluster_id": 302775297,
        "label": "SensorType",
        "type": "Optional[unknown]",
        "writable": false
      },
      "20": {
        "id": 20,
        "cluster_id": 302775297,
        "label": "SirenActive",
        "type": "Optional[unknown]",
        "writable": true
      },
      "21": {
        "id": 21,
        "cluster_id": 302775297,
        "label": "AlarmMute",
        "type": "Optional[unknown]",
        "writable": true
      },
      "22": {
        "id": 22,
        "cluster_id": 302775297,
        "label": "LowPowerMode",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65528": {
        "id": 65528,
        "cluster_id": 302775297,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 302775297,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 302775297,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 302775297,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 302775297,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 302775297,
        "label": "ClusterRevision",
        "type": "uint16",
        "writable": false
      }
    },
    "commands": {
      "0": {
        "id": 0,
        "cluster_id": 302775297,
        "name": "mutingSensor",
        "label": "Muting Sensor"
      }
    }
  },
  "305134641": {
    "id": 305134641,
    "label": "InovelliCluster",
    "attributes": {
      "65528": {
        "id": 65528,
        "cluster_id": 305134641,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 305134641,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 305134641,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 305134641,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 305134641,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 305134641,
        "label": "ClusterRevision",
        "type": "uint16",
        "writable": false
      },
      "305070177": {
        "id": 305070177,
        "cluster_id": 305134641,
        "label": "LedIndicatorIntensityOn",
        "type": "Optional[unknown]",
        "writable": true
      },
      "305070178": {
        "id": 305070178,
        "cluster_id": 305134641,
        "label": "LedIndicatorIntensityOff",
        "type": "Optional[unknown]",
        "writable": true
      },
      "305070342": {
        "id": 305070342,
        "cluster_id": 305134641,
        "label": "ClearNotificationWithConfigDoubleTap",
        "type": "Optional[bool]",
        "writable": true
      }
    },
    "commands": {}
  },
  "308149265": {
    "id": 308149265,
    "label": "NeoCluster",
    "attributes": {
      "65528": {
        "id": 65528,
        "cluster_id": 308149265,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 308149265,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 308149265,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 308149265,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 308149265,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 308149265,
        "label": "ClusterRevision",
        "type": "uint16",
        "writable": false
      },
      "308084769": {
        "id": 308084769,
        "cluster_id": 308149265,
        "label": "WattAccumulated",
        "type": "Optional[unknown]",
        "writable": false
      },
      "308084770": {
        "id": 308084770,
        "cluster_id": 308149265,
        "label": "Current",
        "type": "Optional[unknown]",
        "writable": false
      },
      "308084771": {
        "id": 308084771,
        "cluster_id": 308149265,
        "label": "Watt",
        "type": "Optional[unknown]",
        "writable": false
      },
      "308084772": {
        "id": 308084772,
        "cluster_id": 308149265,
        "label": "Voltage",
        "type": "Optional[unknown]",
        "writable": false
      }
    },
    "commands": {}
  },
  "319486977": {
    "id": 319486977,
    "label": "EveCluster",
    "attributes": {
      "65528": {
        "id": 65528,
        "cluster_id": 319486977,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 319486977,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 319486977,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 319486977,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 319486977,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 319486977,
        "label": "ClusterRevision",
        "type": "uint16",
        "writable": false
      },
      "319422464": {
        "id": 319422464,
        "cluster_id": 319486977,
        "label": "GetConfig",
        "type": "Optional[bytes]",
        "writable": false
      },
      "319422465": {
        "id": 319422465,
        "cluster_id": 319486977,
        "label": "SetConfig",
        "type": "Optional[bytes]",
        "writable": true
      },
      "319422466": {
        "id": 319422466,
        "cluster_id": 319486977,
        "label": "LoggingMetadata",
        "type": "Optional[bytes]",
        "writable": false
      },
      "319422467": {
        "id": 319422467,
        "cluster_id": 319486977,
        "label": "LoggingData",
        "type": "Optional[bytes]",
        "writable": false
      },
      "319422470": {
        "id": 319422470,
        "cluster_id": 319486977,
        "label": "TimesOpened",
        "type": "Optional[unknown]",
        "writable": false
      },
      "319422471": {
        "id": 319422471,
        "cluster_id": 319486977,
        "label": "LastEventTime",
        "type": "Optional[unknown]",
        "writable": false
      },
      "319422472": {
        "id": 319422472,
        "cluster_id": 319486977,
        "label": "Voltage",
        "type": "Optional[unknown]",
        "writable": false
      },
      "319422473": {
        "id": 319422473,
        "cluster_id": 319486977,
        "label": "Current",
        "type": "Optional[unknown]",
        "writable": false
      },
      "319422474": {
        "id": 319422474,
        "cluster_id": 319486977,
        "label": "Watt",
        "type": "Optional[unknown]",
        "writable": false
      },
      "319422475": {
        "id": 319422475,
        "cluster_id": 319486977,
        "label": "WattAccumulated",
        "type": "Optional[unknown]",
        "writable": false
      },
      "319422476": {
        "id": 319422476,
        "cluster_id": 319486977,
        "label": "StatusFault",
        "type": "Optional[unknown]",
        "writable": false
      },
      "319422477": {
        "id": 319422477,
        "cluster_id": 319486977,
        "label": "MotionSensitivity",
        "type": "Optional[unknown]",
        "writable": false
      },
      "319422478": {
        "id": 319422478,
        "cluster_id": 319486977,
        "label": "WattAccumulatedControlPoint",
        "type": "Optional[unknown]",
        "writable": false
      },
      "319422480": {
        "id": 319422480,
        "cluster_id": 319486977,
        "label": "ObstructionDetected",
        "type": "Optional[bool]",
        "writable": false
      },
      "319422481": {
        "id": 319422481,
        "cluster_id": 319486977,
        "label": "ChildLock",
        "type": "Optional[bool]",
        "writable": true
      },
      "319422482": {
        "id": 319422482,
        "cluster_id": 319486977,
        "label": "Rloc16",
        "type": "Optional[unknown]",
        "writable": false
      },
      "319422483": {
        "id": 319422483,
        "cluster_id": 319486977,
        "label": "Altitude",
        "type": "Optional[unknown]",
        "writable": false
      },
      "319422484": {
        "id": 319422484,
        "cluster_id": 319486977,
        "label": "Pressure",
        "type": "Optional[unknown]",
        "writable": false
      },
      "319422485": {
        "id": 319422485,
        "cluster_id": 319486977,
        "label": "WeatherTrend",
        "type": "Optional[unknown]",
        "writable": false
      },
      "319422487": {
        "id": 319422487,
        "cluster_id": 319486977,
        "label": "WindowOpenMode",
        "type": "Optional[bool]",
        "writable": false
      },
      "319422488": {
        "id": 319422488,
        "cluster_id": 319486977,
        "label": "ValvePosition",
        "type": "Optional[unknown]",
        "writable": false
      }
    },
    "commands": {}
  },
  "319683586": {
    "id": 319683586,
    "label": "ThirdRealityMeteringCluster",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 319683586,
        "label": "CurrentSummationDelivered",
        "type": "Optional[unknown]",
        "writable": false
      },
      "769": {
        "id": 769,
        "cluster_id": 319683586,
        "label": "Multiplier",
        "type": "Optional[unknown]",
        "writable": false
      },
      "770": {
        "id": 770,
        "cluster_id": 319683586,
        "label": "Divisor",
        "type": "Optional[unknown]",
        "writable": false
      },
      "1024": {
        "id": 1024,
        "cluster_id": 319683586,
        "label": "InstantaneousDemand",
        "type": "Optional[unknown]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 319683586,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 319683586,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 319683586,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 319683586,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 319683586,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 319683586,
        "label": "ClusterRevision",
        "type": "uint16",
        "writable": false
      }
    },
    "commands": {}
  },
  "322239491": {
    "id": 322239491,
    "label": "TclDehumidifierCluster",
    "attributes": {
      "0": {
        "id": 0,
        "cluster_id": 322239491,
        "label": "Mode",
        "type": "Optional[unknown]",
        "writable": true
      },
      "1": {
        "id": 1,
        "cluster_id": 322239491,
        "label": "TargetHumidity",
        "type": "Optional[unknown]",
        "writable": true
      },
      "2": {
        "id": 2,
        "cluster_id": 322239491,
        "label": "CurrentHumidity",
        "type": "Optional[unknown]",
        "writable": false
      },
      "3": {
        "id": 3,
        "cluster_id": 322239491,
        "label": "WaterBucketFull",
        "type": "Optional[bool]",
        "writable": false
      },
      "4": {
        "id": 4,
        "cluster_id": 322239491,
        "label": "FilterAlert",
        "type": "Optional[bool]",
        "writable": false
      },
      "5": {
        "id": 5,
        "cluster_id": 322239491,
        "label": "ErrorCodes",
        "type": "Optional[string]",
        "writable": false
      },
      "6": {
        "id": 6,
        "cluster_id": 322239491,
        "label": "FeatureSet",
        "type": "Optional[string]",
        "writable": false
      },
      "65528": {
        "id": 65528,
        "cluster_id": 322239491,
        "label": "GeneratedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65529": {
        "id": 65529,
        "cluster_id": 322239491,
        "label": "AcceptedCommandList",
        "type": "List[command-id]",
        "writable": false
      },
      "65530": {
        "id": 65530,
        "cluster_id": 322239491,
        "label": "EventList",
        "type": "Optional[unknown]",
        "writable": true
      },
      "65531": {
        "id": 65531,
        "cluster_id": 322239491,
        "label": "AttributeList",
        "type": "List[attrib-id]",
        "writable": false
      },
      "65532": {
        "id": 65532,
        "cluster_id": 322239491,
        "label": "FeatureMap",
        "type": "map32",
        "writable": false
      },
      "65533": {
        "id": 65533,
        "cluster_id": 322239491,
        "label": "ClusterRevision",
        "type": "uint16",
        "writable": false
      }
    },
    "commands": {}
  }
};

/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
const showDialogBox = async (type, dialogParams) => {
  await import('./dialog-box-GO3dAXJL.js');
  return new Promise(resolve => {
    const dialog = document.createElement("dialog-box");
    dialog.params = dialogParams;
    dialog.dialogResult = resolve;
    dialog.type = type;
    document.body.appendChild(dialog);
  });
};
const showAlertDialog = dialogParams => showDialogBox("alert", dialogParams);
const showPromptDialog = dialogParams => showDialogBox("prompt", dialogParams);

/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
const showAttributeWriteDialog = async options => {
  await import('./attribute-write-dialog-BtlX13v4.js');
  const dialog = document.createElement("attribute-write-dialog");
  dialog.client = options.client;
  dialog.nodeId = options.nodeId;
  dialog.endpointId = options.endpointId;
  dialog.clusterId = options.clusterId;
  dialog.attributeId = options.attributeId;
  dialog.label = options.label;
  dialog.currentValue = options.currentValue;
  document.querySelector("matter-dashboard-app")?.renderRoot.appendChild(dialog);
};

/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
const showCommandInvokeDialog = async options => {
  await import('./command-invoke-dialog-BtP8qgM-.js');
  const dialog = document.createElement("command-invoke-dialog");
  dialog.client = options.client;
  dialog.nodeId = options.nodeId;
  dialog.endpointId = options.endpointId;
  dialog.clusterId = options.clusterId;
  dialog.commandId = options.commandId;
  dialog.commandName = options.commandName;
  document.querySelector("matter-dashboard-app")?.renderRoot.appendChild(dialog);
};

/**
 * @license
 * Copyright 2022 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * A component for elevation.
 */
class Elevation extends i$4 {
  connectedCallback() {
    super.connectedCallback();
    // Needed for VoiceOver, which will create a "group" if the element is a
    // sibling to other content.
    this.setAttribute('aria-hidden', 'true');
  }
  render() {
    return b`<span class="shadow"></span>`;
  }
}

/**
 * @license
 * Copyright 2024 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Generated stylesheet for ./elevation/internal/elevation-styles.css.
const styles$e = i$7`:host,.shadow,.shadow::before,.shadow::after{border-radius:inherit;inset:0;position:absolute;transition-duration:inherit;transition-property:inherit;transition-timing-function:inherit}:host{display:flex;pointer-events:none;transition-property:box-shadow,opacity}.shadow::before,.shadow::after{content:"";transition-property:box-shadow,opacity;--_level: var(--md-elevation-level, 0);--_shadow-color: var(--md-elevation-shadow-color, var(--md-sys-color-shadow, #000))}.shadow::before{box-shadow:0px calc(1px*(clamp(0,var(--_level),1) + clamp(0,var(--_level) - 3,1) + 2*clamp(0,var(--_level) - 4,1))) calc(1px*(2*clamp(0,var(--_level),1) + clamp(0,var(--_level) - 2,1) + clamp(0,var(--_level) - 4,1))) 0px var(--_shadow-color);opacity:.3}.shadow::after{box-shadow:0px calc(1px*(clamp(0,var(--_level),1) + clamp(0,var(--_level) - 1,1) + 2*clamp(0,var(--_level) - 2,3))) calc(1px*(3*clamp(0,var(--_level),2) + 2*clamp(0,var(--_level) - 2,3))) calc(1px*(clamp(0,var(--_level),4) + 2*clamp(0,var(--_level) - 4,1))) var(--_shadow-color);opacity:.15}
`;

/**
 * @license
 * Copyright 2022 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * The `<md-elevation>` custom element with default styles.
 *
 * Elevation is the relative distance between two surfaces along the z-axis.
 *
 * @final
 * @suppress {visibility}
 */
let MdElevation = class MdElevation extends Elevation {};
MdElevation.styles = [styles$e];
MdElevation = __decorate([t$1('md-elevation')], MdElevation);

/**
 * @license
 * Copyright 2021 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * A filled button component.
 */
class FilledButton extends Button {
  renderElevationOrOutline() {
    return b`<md-elevation part="elevation"></md-elevation>`;
  }
}

/**
 * @license
 * Copyright 2024 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Generated stylesheet for ./button/internal/filled-styles.css.
const styles$d = i$7`:host{--_container-color: var(--md-filled-button-container-color, var(--md-sys-color-primary, #6750a4));--_container-elevation: var(--md-filled-button-container-elevation, 0);--_container-height: var(--md-filled-button-container-height, 40px);--_container-shadow-color: var(--md-filled-button-container-shadow-color, var(--md-sys-color-shadow, #000));--_disabled-container-color: var(--md-filled-button-disabled-container-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-container-elevation: var(--md-filled-button-disabled-container-elevation, 0);--_disabled-container-opacity: var(--md-filled-button-disabled-container-opacity, 0.12);--_disabled-label-text-color: var(--md-filled-button-disabled-label-text-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-label-text-opacity: var(--md-filled-button-disabled-label-text-opacity, 0.38);--_focus-container-elevation: var(--md-filled-button-focus-container-elevation, 0);--_focus-label-text-color: var(--md-filled-button-focus-label-text-color, var(--md-sys-color-on-primary, #fff));--_hover-container-elevation: var(--md-filled-button-hover-container-elevation, 1);--_hover-label-text-color: var(--md-filled-button-hover-label-text-color, var(--md-sys-color-on-primary, #fff));--_hover-state-layer-color: var(--md-filled-button-hover-state-layer-color, var(--md-sys-color-on-primary, #fff));--_hover-state-layer-opacity: var(--md-filled-button-hover-state-layer-opacity, 0.08);--_label-text-color: var(--md-filled-button-label-text-color, var(--md-sys-color-on-primary, #fff));--_label-text-font: var(--md-filled-button-label-text-font, var(--md-sys-typescale-label-large-font, var(--md-ref-typeface-plain, Roboto)));--_label-text-line-height: var(--md-filled-button-label-text-line-height, var(--md-sys-typescale-label-large-line-height, 1.25rem));--_label-text-size: var(--md-filled-button-label-text-size, var(--md-sys-typescale-label-large-size, 0.875rem));--_label-text-weight: var(--md-filled-button-label-text-weight, var(--md-sys-typescale-label-large-weight, var(--md-ref-typeface-weight-medium, 500)));--_pressed-container-elevation: var(--md-filled-button-pressed-container-elevation, 0);--_pressed-label-text-color: var(--md-filled-button-pressed-label-text-color, var(--md-sys-color-on-primary, #fff));--_pressed-state-layer-color: var(--md-filled-button-pressed-state-layer-color, var(--md-sys-color-on-primary, #fff));--_pressed-state-layer-opacity: var(--md-filled-button-pressed-state-layer-opacity, 0.12);--_disabled-icon-color: var(--md-filled-button-disabled-icon-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-icon-opacity: var(--md-filled-button-disabled-icon-opacity, 0.38);--_focus-icon-color: var(--md-filled-button-focus-icon-color, var(--md-sys-color-on-primary, #fff));--_hover-icon-color: var(--md-filled-button-hover-icon-color, var(--md-sys-color-on-primary, #fff));--_icon-color: var(--md-filled-button-icon-color, var(--md-sys-color-on-primary, #fff));--_icon-size: var(--md-filled-button-icon-size, 18px);--_pressed-icon-color: var(--md-filled-button-pressed-icon-color, var(--md-sys-color-on-primary, #fff));--_container-shape-start-start: var(--md-filled-button-container-shape-start-start, var(--md-filled-button-container-shape, var(--md-sys-shape-corner-full, 9999px)));--_container-shape-start-end: var(--md-filled-button-container-shape-start-end, var(--md-filled-button-container-shape, var(--md-sys-shape-corner-full, 9999px)));--_container-shape-end-end: var(--md-filled-button-container-shape-end-end, var(--md-filled-button-container-shape, var(--md-sys-shape-corner-full, 9999px)));--_container-shape-end-start: var(--md-filled-button-container-shape-end-start, var(--md-filled-button-container-shape, var(--md-sys-shape-corner-full, 9999px)));--_leading-space: var(--md-filled-button-leading-space, 24px);--_trailing-space: var(--md-filled-button-trailing-space, 24px);--_with-leading-icon-leading-space: var(--md-filled-button-with-leading-icon-leading-space, 16px);--_with-leading-icon-trailing-space: var(--md-filled-button-with-leading-icon-trailing-space, 24px);--_with-trailing-icon-leading-space: var(--md-filled-button-with-trailing-icon-leading-space, 24px);--_with-trailing-icon-trailing-space: var(--md-filled-button-with-trailing-icon-trailing-space, 16px)}
`;

/**
 * @license
 * Copyright 2024 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Generated stylesheet for ./button/internal/shared-elevation-styles.css.
const styles$c = i$7`md-elevation{transition-duration:280ms}:host(:is([disabled],[soft-disabled])) md-elevation{transition:none}md-elevation{--md-elevation-level: var(--_container-elevation);--md-elevation-shadow-color: var(--_container-shadow-color)}:host(:focus-within) md-elevation{--md-elevation-level: var(--_focus-container-elevation)}:host(:hover) md-elevation{--md-elevation-level: var(--_hover-container-elevation)}:host(:active) md-elevation{--md-elevation-level: var(--_pressed-container-elevation)}:host(:is([disabled],[soft-disabled])) md-elevation{--md-elevation-level: var(--_disabled-container-elevation)}
`;

/**
 * @license
 * Copyright 2021 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @summary Buttons help people take action, such as sending an email, sharing a
 * document, or liking a comment.
 *
 * @description
 * __Emphasis:__ High emphasis – For the primary, most important, or most common
 * action on a screen
 *
 * __Rationale:__ The filled button’s contrasting surface color makes it the
 * most prominent button after the FAB. It’s used for final or unblocking
 * actions in a flow.
 *
 * __Example usages:__
 * - Save
 * - Confirm
 * - Done
 *
 * @final
 * @suppress {visibility}
 */
let MdFilledButton = class MdFilledButton extends FilledButton {};
MdFilledButton.styles = [styles$m, styles$c, styles$d];
MdFilledButton = __decorate([t$1('md-filled-button')], MdFilledButton);

/**
 * @license
 * Copyright 2021 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * A text button component.
 */
class TextButton extends Button {}

/**
 * @license
 * Copyright 2024 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Generated stylesheet for ./button/internal/text-styles.css.
const styles$b = i$7`:host{--_container-height: var(--md-text-button-container-height, 40px);--_disabled-label-text-color: var(--md-text-button-disabled-label-text-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-label-text-opacity: var(--md-text-button-disabled-label-text-opacity, 0.38);--_focus-label-text-color: var(--md-text-button-focus-label-text-color, var(--md-sys-color-primary, #6750a4));--_hover-label-text-color: var(--md-text-button-hover-label-text-color, var(--md-sys-color-primary, #6750a4));--_hover-state-layer-color: var(--md-text-button-hover-state-layer-color, var(--md-sys-color-primary, #6750a4));--_hover-state-layer-opacity: var(--md-text-button-hover-state-layer-opacity, 0.08);--_label-text-color: var(--md-text-button-label-text-color, var(--md-sys-color-primary, #6750a4));--_label-text-font: var(--md-text-button-label-text-font, var(--md-sys-typescale-label-large-font, var(--md-ref-typeface-plain, Roboto)));--_label-text-line-height: var(--md-text-button-label-text-line-height, var(--md-sys-typescale-label-large-line-height, 1.25rem));--_label-text-size: var(--md-text-button-label-text-size, var(--md-sys-typescale-label-large-size, 0.875rem));--_label-text-weight: var(--md-text-button-label-text-weight, var(--md-sys-typescale-label-large-weight, var(--md-ref-typeface-weight-medium, 500)));--_pressed-label-text-color: var(--md-text-button-pressed-label-text-color, var(--md-sys-color-primary, #6750a4));--_pressed-state-layer-color: var(--md-text-button-pressed-state-layer-color, var(--md-sys-color-primary, #6750a4));--_pressed-state-layer-opacity: var(--md-text-button-pressed-state-layer-opacity, 0.12);--_disabled-icon-color: var(--md-text-button-disabled-icon-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-icon-opacity: var(--md-text-button-disabled-icon-opacity, 0.38);--_focus-icon-color: var(--md-text-button-focus-icon-color, var(--md-sys-color-primary, #6750a4));--_hover-icon-color: var(--md-text-button-hover-icon-color, var(--md-sys-color-primary, #6750a4));--_icon-color: var(--md-text-button-icon-color, var(--md-sys-color-primary, #6750a4));--_icon-size: var(--md-text-button-icon-size, 18px);--_pressed-icon-color: var(--md-text-button-pressed-icon-color, var(--md-sys-color-primary, #6750a4));--_container-shape-start-start: var(--md-text-button-container-shape-start-start, var(--md-text-button-container-shape, var(--md-sys-shape-corner-full, 9999px)));--_container-shape-start-end: var(--md-text-button-container-shape-start-end, var(--md-text-button-container-shape, var(--md-sys-shape-corner-full, 9999px)));--_container-shape-end-end: var(--md-text-button-container-shape-end-end, var(--md-text-button-container-shape, var(--md-sys-shape-corner-full, 9999px)));--_container-shape-end-start: var(--md-text-button-container-shape-end-start, var(--md-text-button-container-shape, var(--md-sys-shape-corner-full, 9999px)));--_leading-space: var(--md-text-button-leading-space, 12px);--_trailing-space: var(--md-text-button-trailing-space, 12px);--_with-leading-icon-leading-space: var(--md-text-button-with-leading-icon-leading-space, 12px);--_with-leading-icon-trailing-space: var(--md-text-button-with-leading-icon-trailing-space, 16px);--_with-trailing-icon-leading-space: var(--md-text-button-with-trailing-icon-leading-space, 16px);--_with-trailing-icon-trailing-space: var(--md-text-button-with-trailing-icon-trailing-space, 12px);--_container-color: none;--_disabled-container-color: none;--_disabled-container-opacity: 0}
`;

/**
 * @license
 * Copyright 2021 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @summary Buttons help people take action, such as sending an email, sharing a
 * document, or liking a comment.
 *
 * @description
 * __Emphasis:__ Low emphasis – For optional or supplementary actions with the
 * least amount of prominence
 *
 * __Rationale:__ Text buttons have less visual prominence, so should be used
 * for low emphasis actions, such as an alternative option.
 *
 * __Example usages:__
 * - Learn more
 * - View all
 * - Change account
 * - Turn on
 *
 * @final
 * @suppress {visibility}
 */
let MdTextButton = class MdTextButton extends TextButton {};
MdTextButton.styles = [styles$m, styles$b];
MdTextButton = __decorate([t$1('md-text-button')], MdTextButton);

/**
 * @license
 * Copyright 2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
const showNodeLabelDialog = async (client, node) => {
  await import('./node-label-dialog-BSb88oAs.js');
  const dialog = document.createElement("node-label-dialog");
  dialog.client = client;
  dialog.node = node;
  document.querySelector("matter-dashboard-app")?.renderRoot.appendChild(dialog);
};

/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
function handleAsync(fn, onError) {
  return () => {
    fn().catch(error => {
      console.error("Async operation failed:", error);
    });
  };
}
function handleAsyncEvent(fn, onError) {
  return event => {
    fn(event).catch(error => {
      console.error("Async operation failed:", error);
    });
  };
}
function fireAndForget(promise, onError) {
  promise.catch(error => {
    console.error("Async operation failed:", error);
  });
}

/**
 * @license
 * Copyright 2021 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * A field component.
 */
class Field extends i$4 {
  constructor() {
    super(...arguments);
    this.disabled = false;
    this.error = false;
    this.focused = false;
    this.label = '';
    this.noAsterisk = false;
    this.populated = false;
    this.required = false;
    this.resizable = false;
    this.supportingText = '';
    this.errorText = '';
    this.count = -1;
    this.max = -1;
    /**
     * Whether or not the field has leading content.
     */
    this.hasStart = false;
    /**
     * Whether or not the field has trailing content.
     */
    this.hasEnd = false;
    this.isAnimating = false;
    /**
     * When set to true, the error text's `role="alert"` will be removed, then
     * re-added after an animation frame. This will re-announce an error message
     * to screen readers.
     */
    this.refreshErrorAlert = false;
    this.disableTransitions = false;
  }
  get counterText() {
    // Count and max are typed as number, but can be set to null when Lit removes
    // their attributes. These getters coerce back to a number for calculations.
    const countAsNumber = this.count ?? -1;
    const maxAsNumber = this.max ?? -1;
    // Counter does not show if count is negative, or max is negative or 0.
    if (countAsNumber < 0 || maxAsNumber <= 0) {
      return '';
    }
    return `${countAsNumber} / ${maxAsNumber}`;
  }
  get supportingOrErrorText() {
    return this.error && this.errorText ? this.errorText : this.supportingText;
  }
  /**
   * Re-announces the field's error supporting text to screen readers.
   *
   * Error text announces to screen readers anytime it is visible and changes.
   * Use the method to re-announce the message when the text has not changed,
   * but announcement is still needed (such as for `reportValidity()`).
   */
  reannounceError() {
    this.refreshErrorAlert = true;
  }
  update(props) {
    // Client-side property updates
    const isDisabledChanging = props.has('disabled') && props.get('disabled') !== undefined;
    if (isDisabledChanging) {
      this.disableTransitions = true;
    }
    // When disabling, remove focus styles if focused.
    if (this.disabled && this.focused) {
      props.set('focused', true);
      this.focused = false;
    }
    // Animate if focused or populated change.
    this.animateLabelIfNeeded({
      wasFocused: props.get('focused'),
      wasPopulated: props.get('populated')
    });
    super.update(props);
  }
  render() {
    const floatingLabel = this.renderLabel(/*isFloating*/true);
    const restingLabel = this.renderLabel(/*isFloating*/false);
    const outline = this.renderOutline?.(floatingLabel);
    const classes = {
      'disabled': this.disabled,
      'disable-transitions': this.disableTransitions,
      'error': this.error && !this.disabled,
      'focused': this.focused,
      'with-start': this.hasStart,
      'with-end': this.hasEnd,
      'populated': this.populated,
      'resizable': this.resizable,
      'required': this.required,
      'no-label': !this.label
    };
    return b`
      <div class="field ${e$3(classes)}">
        <div class="container-overflow">
          ${this.renderBackground?.()}
          <slot name="container"></slot>
          ${this.renderStateLayer?.()} ${this.renderIndicator?.()} ${outline}
          <div class="container">
            <div class="start">
              <slot name="start"></slot>
            </div>
            <div class="middle">
              <div class="label-wrapper">
                ${restingLabel} ${outline ? A : floatingLabel}
              </div>
              <div class="content">
                <slot></slot>
              </div>
            </div>
            <div class="end">
              <slot name="end"></slot>
            </div>
          </div>
        </div>
        ${this.renderSupportingText()}
      </div>
    `;
  }
  updated(changed) {
    if (changed.has('supportingText') || changed.has('errorText') || changed.has('count') || changed.has('max')) {
      this.updateSlottedAriaDescribedBy();
    }
    if (this.refreshErrorAlert) {
      // The past render cycle removed the role="alert" from the error message.
      // Re-add it after an animation frame to re-announce the error.
      requestAnimationFrame(() => {
        this.refreshErrorAlert = false;
      });
    }
    if (this.disableTransitions) {
      requestAnimationFrame(() => {
        this.disableTransitions = false;
      });
    }
  }
  renderSupportingText() {
    const {
      supportingOrErrorText,
      counterText
    } = this;
    if (!supportingOrErrorText && !counterText) {
      return A;
    }
    // Always render the supporting text span so that our `space-around`
    // container puts the counter at the end.
    const start = b`<span>${supportingOrErrorText}</span>`;
    // Conditionally render counter so we don't render the extra `gap`.
    // TODO(b/244473435): add aria-label and announcements
    const end = counterText ? b`<span class="counter">${counterText}</span>` : A;
    // Announce if there is an error and error text visible.
    // If refreshErrorAlert is true, do not announce. This will remove the
    // role="alert" attribute. Another render cycle will happen after an
    // animation frame to re-add the role.
    const shouldErrorAnnounce = this.error && this.errorText && !this.refreshErrorAlert;
    const role = shouldErrorAnnounce ? 'alert' : A;
    return b`
      <div class="supporting-text" role=${role}>${start}${end}</div>
      <slot
        name="aria-describedby"
        @slotchange=${this.updateSlottedAriaDescribedBy}></slot>
    `;
  }
  updateSlottedAriaDescribedBy() {
    for (const element of this.slottedAriaDescribedBy) {
      D(b`${this.supportingOrErrorText} ${this.counterText}`, element);
      element.setAttribute('hidden', '');
    }
  }
  renderLabel(isFloating) {
    if (!this.label) {
      return A;
    }
    let visible;
    if (isFloating) {
      // Floating label is visible when focused/populated or when animating.
      visible = this.focused || this.populated || this.isAnimating;
    } else {
      // Resting label is visible when unfocused. It is never visible while
      // animating.
      visible = !this.focused && !this.populated && !this.isAnimating;
    }
    const classes = {
      'hidden': !visible,
      'floating': isFloating,
      'resting': !isFloating
    };
    // Add '*' if a label is present and the field is required
    const labelText = `${this.label}${this.required && !this.noAsterisk ? '*' : ''}`;
    return b`
      <span class="label ${e$3(classes)}" aria-hidden=${!visible}
        >${labelText}</span
      >
    `;
  }
  animateLabelIfNeeded({
    wasFocused,
    wasPopulated
  }) {
    if (!this.label) {
      return;
    }
    wasFocused ?? (wasFocused = this.focused);
    wasPopulated ?? (wasPopulated = this.populated);
    const wasFloating = wasFocused || wasPopulated;
    const shouldBeFloating = this.focused || this.populated;
    if (wasFloating === shouldBeFloating) {
      return;
    }
    this.isAnimating = true;
    this.labelAnimation?.cancel();
    // Only one label is visible at a time for clearer text rendering.
    // The floating label is visible and used during animation. At the end of
    // the animation, it will either remain visible (if floating) or hide and
    // the resting label will be shown.
    //
    // We don't use forward filling because if the dimensions of the text field
    // change (leading icon removed, density changes, etc), then the animation
    // will be inaccurate.
    //
    // Re-calculating the animation each time will prevent any visual glitches
    // from appearing.
    // TODO(b/241113345): use animation tokens
    this.labelAnimation = this.floatingLabelEl?.animate(this.getLabelKeyframes(), {
      duration: 150,
      easing: EASING.STANDARD
    });
    this.labelAnimation?.addEventListener('finish', () => {
      // At the end of the animation, update the visible label.
      this.isAnimating = false;
    });
  }
  getLabelKeyframes() {
    const {
      floatingLabelEl,
      restingLabelEl
    } = this;
    if (!floatingLabelEl || !restingLabelEl) {
      return [];
    }
    const {
      x: floatingX,
      y: floatingY,
      height: floatingHeight
    } = floatingLabelEl.getBoundingClientRect();
    const {
      x: restingX,
      y: restingY,
      height: restingHeight
    } = restingLabelEl.getBoundingClientRect();
    const floatingScrollWidth = floatingLabelEl.scrollWidth;
    const restingScrollWidth = restingLabelEl.scrollWidth;
    // Scale by width ratio instead of font size since letter-spacing will scale
    // incorrectly. Using the width we can better approximate the adjusted
    // scale and compensate for tracking and overflow.
    // (use scrollWidth instead of width to account for clipped labels)
    const scale = restingScrollWidth / floatingScrollWidth;
    const xDelta = restingX - floatingX;
    // The line-height of the resting and floating label are different. When
    // we move the floating label down to the resting label's position, it won't
    // exactly match because of this. We need to adjust by half of what the
    // final scaled floating label's height will be.
    const yDelta = restingY - floatingY + Math.round((restingHeight - floatingHeight * scale) / 2);
    // Create the two transforms: floating to resting (using the calculations
    // above), and resting to floating (re-setting the transform to initial
    // values).
    const restTransform = `translateX(${xDelta}px) translateY(${yDelta}px) scale(${scale})`;
    const floatTransform = `translateX(0) translateY(0) scale(1)`;
    // Constrain the floating labels width to a scaled percentage of the
    // resting label's width. This will prevent long clipped labels from
    // overflowing the container.
    const restingClientWidth = restingLabelEl.clientWidth;
    const isRestingClipped = restingScrollWidth > restingClientWidth;
    const width = isRestingClipped ? `${restingClientWidth / scale}px` : '';
    if (this.focused || this.populated) {
      return [{
        transform: restTransform,
        width
      }, {
        transform: floatTransform,
        width
      }];
    }
    return [{
      transform: floatTransform,
      width
    }, {
      transform: restTransform,
      width
    }];
  }
  getSurfacePositionClientRect() {
    return this.containerEl.getBoundingClientRect();
  }
}
__decorate([n$5({
  type: Boolean
})], Field.prototype, "disabled", void 0);
__decorate([n$5({
  type: Boolean
})], Field.prototype, "error", void 0);
__decorate([n$5({
  type: Boolean
})], Field.prototype, "focused", void 0);
__decorate([n$5()], Field.prototype, "label", void 0);
__decorate([n$5({
  type: Boolean,
  attribute: 'no-asterisk'
})], Field.prototype, "noAsterisk", void 0);
__decorate([n$5({
  type: Boolean
})], Field.prototype, "populated", void 0);
__decorate([n$5({
  type: Boolean
})], Field.prototype, "required", void 0);
__decorate([n$5({
  type: Boolean
})], Field.prototype, "resizable", void 0);
__decorate([n$5({
  attribute: 'supporting-text'
})], Field.prototype, "supportingText", void 0);
__decorate([n$5({
  attribute: 'error-text'
})], Field.prototype, "errorText", void 0);
__decorate([n$5({
  type: Number
})], Field.prototype, "count", void 0);
__decorate([n$5({
  type: Number
})], Field.prototype, "max", void 0);
__decorate([n$5({
  type: Boolean,
  attribute: 'has-start'
})], Field.prototype, "hasStart", void 0);
__decorate([n$5({
  type: Boolean,
  attribute: 'has-end'
})], Field.prototype, "hasEnd", void 0);
__decorate([o$5({
  slot: 'aria-describedby'
})], Field.prototype, "slottedAriaDescribedBy", void 0);
__decorate([r$3()], Field.prototype, "isAnimating", void 0);
__decorate([r$3()], Field.prototype, "refreshErrorAlert", void 0);
__decorate([r$3()], Field.prototype, "disableTransitions", void 0);
__decorate([e$6('.label.floating')], Field.prototype, "floatingLabelEl", void 0);
__decorate([e$6('.label.resting')], Field.prototype, "restingLabelEl", void 0);
__decorate([e$6('.container')], Field.prototype, "containerEl", void 0);

/**
 * @license
 * Copyright 2021 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * An outlined field component.
 */
class OutlinedField extends Field {
  renderOutline(floatingLabel) {
    return b`
      <div class="outline">
        <div class="outline-start"></div>
        <div class="outline-notch">
          <div class="outline-panel-inactive"></div>
          <div class="outline-panel-active"></div>
          <div class="outline-label">${floatingLabel}</div>
        </div>
        <div class="outline-end"></div>
      </div>
    `;
  }
}

/**
 * @license
 * Copyright 2024 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Generated stylesheet for ./field/internal/outlined-styles.css.
const styles$a = i$7`@layer styles{:host{--_bottom-space: var(--md-outlined-field-bottom-space, 16px);--_content-color: var(--md-outlined-field-content-color, var(--md-sys-color-on-surface, #1d1b20));--_content-font: var(--md-outlined-field-content-font, var(--md-sys-typescale-body-large-font, var(--md-ref-typeface-plain, Roboto)));--_content-line-height: var(--md-outlined-field-content-line-height, var(--md-sys-typescale-body-large-line-height, 1.5rem));--_content-size: var(--md-outlined-field-content-size, var(--md-sys-typescale-body-large-size, 1rem));--_content-space: var(--md-outlined-field-content-space, 16px);--_content-weight: var(--md-outlined-field-content-weight, var(--md-sys-typescale-body-large-weight, var(--md-ref-typeface-weight-regular, 400)));--_disabled-content-color: var(--md-outlined-field-disabled-content-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-content-opacity: var(--md-outlined-field-disabled-content-opacity, 0.38);--_disabled-label-text-color: var(--md-outlined-field-disabled-label-text-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-label-text-opacity: var(--md-outlined-field-disabled-label-text-opacity, 0.38);--_disabled-leading-content-color: var(--md-outlined-field-disabled-leading-content-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-leading-content-opacity: var(--md-outlined-field-disabled-leading-content-opacity, 0.38);--_disabled-outline-color: var(--md-outlined-field-disabled-outline-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-outline-opacity: var(--md-outlined-field-disabled-outline-opacity, 0.12);--_disabled-outline-width: var(--md-outlined-field-disabled-outline-width, 1px);--_disabled-supporting-text-color: var(--md-outlined-field-disabled-supporting-text-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-supporting-text-opacity: var(--md-outlined-field-disabled-supporting-text-opacity, 0.38);--_disabled-trailing-content-color: var(--md-outlined-field-disabled-trailing-content-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-trailing-content-opacity: var(--md-outlined-field-disabled-trailing-content-opacity, 0.38);--_error-content-color: var(--md-outlined-field-error-content-color, var(--md-sys-color-on-surface, #1d1b20));--_error-focus-content-color: var(--md-outlined-field-error-focus-content-color, var(--md-sys-color-on-surface, #1d1b20));--_error-focus-label-text-color: var(--md-outlined-field-error-focus-label-text-color, var(--md-sys-color-error, #b3261e));--_error-focus-leading-content-color: var(--md-outlined-field-error-focus-leading-content-color, var(--md-sys-color-on-surface-variant, #49454f));--_error-focus-outline-color: var(--md-outlined-field-error-focus-outline-color, var(--md-sys-color-error, #b3261e));--_error-focus-supporting-text-color: var(--md-outlined-field-error-focus-supporting-text-color, var(--md-sys-color-error, #b3261e));--_error-focus-trailing-content-color: var(--md-outlined-field-error-focus-trailing-content-color, var(--md-sys-color-error, #b3261e));--_error-hover-content-color: var(--md-outlined-field-error-hover-content-color, var(--md-sys-color-on-surface, #1d1b20));--_error-hover-label-text-color: var(--md-outlined-field-error-hover-label-text-color, var(--md-sys-color-on-error-container, #410e0b));--_error-hover-leading-content-color: var(--md-outlined-field-error-hover-leading-content-color, var(--md-sys-color-on-surface-variant, #49454f));--_error-hover-outline-color: var(--md-outlined-field-error-hover-outline-color, var(--md-sys-color-on-error-container, #410e0b));--_error-hover-supporting-text-color: var(--md-outlined-field-error-hover-supporting-text-color, var(--md-sys-color-error, #b3261e));--_error-hover-trailing-content-color: var(--md-outlined-field-error-hover-trailing-content-color, var(--md-sys-color-on-error-container, #410e0b));--_error-label-text-color: var(--md-outlined-field-error-label-text-color, var(--md-sys-color-error, #b3261e));--_error-leading-content-color: var(--md-outlined-field-error-leading-content-color, var(--md-sys-color-on-surface-variant, #49454f));--_error-outline-color: var(--md-outlined-field-error-outline-color, var(--md-sys-color-error, #b3261e));--_error-supporting-text-color: var(--md-outlined-field-error-supporting-text-color, var(--md-sys-color-error, #b3261e));--_error-trailing-content-color: var(--md-outlined-field-error-trailing-content-color, var(--md-sys-color-error, #b3261e));--_focus-content-color: var(--md-outlined-field-focus-content-color, var(--md-sys-color-on-surface, #1d1b20));--_focus-label-text-color: var(--md-outlined-field-focus-label-text-color, var(--md-sys-color-primary, #6750a4));--_focus-leading-content-color: var(--md-outlined-field-focus-leading-content-color, var(--md-sys-color-on-surface-variant, #49454f));--_focus-outline-color: var(--md-outlined-field-focus-outline-color, var(--md-sys-color-primary, #6750a4));--_focus-outline-width: var(--md-outlined-field-focus-outline-width, 3px);--_focus-supporting-text-color: var(--md-outlined-field-focus-supporting-text-color, var(--md-sys-color-on-surface-variant, #49454f));--_focus-trailing-content-color: var(--md-outlined-field-focus-trailing-content-color, var(--md-sys-color-on-surface-variant, #49454f));--_hover-content-color: var(--md-outlined-field-hover-content-color, var(--md-sys-color-on-surface, #1d1b20));--_hover-label-text-color: var(--md-outlined-field-hover-label-text-color, var(--md-sys-color-on-surface, #1d1b20));--_hover-leading-content-color: var(--md-outlined-field-hover-leading-content-color, var(--md-sys-color-on-surface-variant, #49454f));--_hover-outline-color: var(--md-outlined-field-hover-outline-color, var(--md-sys-color-on-surface, #1d1b20));--_hover-outline-width: var(--md-outlined-field-hover-outline-width, 1px);--_hover-supporting-text-color: var(--md-outlined-field-hover-supporting-text-color, var(--md-sys-color-on-surface-variant, #49454f));--_hover-trailing-content-color: var(--md-outlined-field-hover-trailing-content-color, var(--md-sys-color-on-surface-variant, #49454f));--_label-text-color: var(--md-outlined-field-label-text-color, var(--md-sys-color-on-surface-variant, #49454f));--_label-text-font: var(--md-outlined-field-label-text-font, var(--md-sys-typescale-body-large-font, var(--md-ref-typeface-plain, Roboto)));--_label-text-line-height: var(--md-outlined-field-label-text-line-height, var(--md-sys-typescale-body-large-line-height, 1.5rem));--_label-text-padding-bottom: var(--md-outlined-field-label-text-padding-bottom, 8px);--_label-text-populated-line-height: var(--md-outlined-field-label-text-populated-line-height, var(--md-sys-typescale-body-small-line-height, 1rem));--_label-text-populated-size: var(--md-outlined-field-label-text-populated-size, var(--md-sys-typescale-body-small-size, 0.75rem));--_label-text-size: var(--md-outlined-field-label-text-size, var(--md-sys-typescale-body-large-size, 1rem));--_label-text-weight: var(--md-outlined-field-label-text-weight, var(--md-sys-typescale-body-large-weight, var(--md-ref-typeface-weight-regular, 400)));--_leading-content-color: var(--md-outlined-field-leading-content-color, var(--md-sys-color-on-surface-variant, #49454f));--_leading-space: var(--md-outlined-field-leading-space, 16px);--_outline-color: var(--md-outlined-field-outline-color, var(--md-sys-color-outline, #79747e));--_outline-label-padding: var(--md-outlined-field-outline-label-padding, 4px);--_outline-width: var(--md-outlined-field-outline-width, 1px);--_supporting-text-color: var(--md-outlined-field-supporting-text-color, var(--md-sys-color-on-surface-variant, #49454f));--_supporting-text-font: var(--md-outlined-field-supporting-text-font, var(--md-sys-typescale-body-small-font, var(--md-ref-typeface-plain, Roboto)));--_supporting-text-leading-space: var(--md-outlined-field-supporting-text-leading-space, 16px);--_supporting-text-line-height: var(--md-outlined-field-supporting-text-line-height, var(--md-sys-typescale-body-small-line-height, 1rem));--_supporting-text-size: var(--md-outlined-field-supporting-text-size, var(--md-sys-typescale-body-small-size, 0.75rem));--_supporting-text-top-space: var(--md-outlined-field-supporting-text-top-space, 4px);--_supporting-text-trailing-space: var(--md-outlined-field-supporting-text-trailing-space, 16px);--_supporting-text-weight: var(--md-outlined-field-supporting-text-weight, var(--md-sys-typescale-body-small-weight, var(--md-ref-typeface-weight-regular, 400)));--_top-space: var(--md-outlined-field-top-space, 16px);--_trailing-content-color: var(--md-outlined-field-trailing-content-color, var(--md-sys-color-on-surface-variant, #49454f));--_trailing-space: var(--md-outlined-field-trailing-space, 16px);--_with-leading-content-leading-space: var(--md-outlined-field-with-leading-content-leading-space, 12px);--_with-trailing-content-trailing-space: var(--md-outlined-field-with-trailing-content-trailing-space, 12px);--_container-shape-start-start: var(--md-outlined-field-container-shape-start-start, var(--md-outlined-field-container-shape, var(--md-sys-shape-corner-extra-small, 4px)));--_container-shape-start-end: var(--md-outlined-field-container-shape-start-end, var(--md-outlined-field-container-shape, var(--md-sys-shape-corner-extra-small, 4px)));--_container-shape-end-end: var(--md-outlined-field-container-shape-end-end, var(--md-outlined-field-container-shape, var(--md-sys-shape-corner-extra-small, 4px)));--_container-shape-end-start: var(--md-outlined-field-container-shape-end-start, var(--md-outlined-field-container-shape, var(--md-sys-shape-corner-extra-small, 4px)))}.outline{border-color:var(--_outline-color);border-radius:inherit;display:flex;pointer-events:none;height:100%;position:absolute;width:100%;z-index:1}.outline-start::before,.outline-start::after,.outline-panel-inactive::before,.outline-panel-inactive::after,.outline-panel-active::before,.outline-panel-active::after,.outline-end::before,.outline-end::after{border:inherit;content:"";inset:0;position:absolute}.outline-start,.outline-end{border:inherit;border-radius:inherit;box-sizing:border-box;position:relative}.outline-start::before,.outline-start::after,.outline-end::before,.outline-end::after{border-bottom-style:solid;border-top-style:solid}.outline-start::after,.outline-end::after{opacity:0;transition:opacity 150ms cubic-bezier(0.2, 0, 0, 1)}.focused .outline-start::after,.focused .outline-end::after{opacity:1}.outline-start::before,.outline-start::after{border-inline-start-style:solid;border-inline-end-style:none;border-start-start-radius:inherit;border-start-end-radius:0;border-end-start-radius:inherit;border-end-end-radius:0;margin-inline-end:var(--_outline-label-padding)}.outline-end{flex-grow:1;margin-inline-start:calc(-1*var(--_outline-label-padding))}.outline-end::before,.outline-end::after{border-inline-start-style:none;border-inline-end-style:solid;border-start-start-radius:0;border-start-end-radius:inherit;border-end-start-radius:0;border-end-end-radius:inherit}.outline-notch{align-items:flex-start;border:inherit;display:flex;margin-inline-start:calc(-1*var(--_outline-label-padding));margin-inline-end:var(--_outline-label-padding);max-width:calc(100% - var(--_leading-space) - var(--_trailing-space));padding:0 var(--_outline-label-padding);position:relative}.no-label .outline-notch{display:none}.outline-panel-inactive,.outline-panel-active{border:inherit;border-bottom-style:solid;inset:0;position:absolute}.outline-panel-inactive::before,.outline-panel-inactive::after,.outline-panel-active::before,.outline-panel-active::after{border-top-style:solid;border-bottom:none;bottom:auto;transform:scaleX(1);transition:transform 150ms cubic-bezier(0.2, 0, 0, 1)}.outline-panel-inactive::before,.outline-panel-active::before{right:50%;transform-origin:top left}.outline-panel-inactive::after,.outline-panel-active::after{left:50%;transform-origin:top right}.populated .outline-panel-inactive::before,.populated .outline-panel-inactive::after,.populated .outline-panel-active::before,.populated .outline-panel-active::after,.focused .outline-panel-inactive::before,.focused .outline-panel-inactive::after,.focused .outline-panel-active::before,.focused .outline-panel-active::after{transform:scaleX(0)}.outline-panel-active{opacity:0;transition:opacity 150ms cubic-bezier(0.2, 0, 0, 1)}.focused .outline-panel-active{opacity:1}.outline-label{display:flex;max-width:100%;transform:translateY(calc(-100% + var(--_label-text-padding-bottom)))}.outline-start,.field:not(.with-start) .content ::slotted(*){padding-inline-start:max(var(--_leading-space),max(var(--_container-shape-start-start),var(--_container-shape-end-start)) + var(--_outline-label-padding))}.field:not(.with-start) .label-wrapper{margin-inline-start:max(var(--_leading-space),max(var(--_container-shape-start-start),var(--_container-shape-end-start)) + var(--_outline-label-padding))}.field:not(.with-end) .content ::slotted(*){padding-inline-end:max(var(--_trailing-space),max(var(--_container-shape-start-end),var(--_container-shape-end-end)))}.field:not(.with-end) .label-wrapper{margin-inline-end:max(var(--_trailing-space),max(var(--_container-shape-start-end),var(--_container-shape-end-end)))}.outline-start::before,.outline-end::before,.outline-panel-inactive,.outline-panel-inactive::before,.outline-panel-inactive::after{border-width:var(--_outline-width)}:hover .outline{border-color:var(--_hover-outline-color);color:var(--_hover-outline-color)}:hover .outline-start::before,:hover .outline-end::before,:hover .outline-panel-inactive,:hover .outline-panel-inactive::before,:hover .outline-panel-inactive::after{border-width:var(--_hover-outline-width)}.focused .outline{border-color:var(--_focus-outline-color);color:var(--_focus-outline-color)}.outline-start::after,.outline-end::after,.outline-panel-active,.outline-panel-active::before,.outline-panel-active::after{border-width:var(--_focus-outline-width)}.disabled .outline{border-color:var(--_disabled-outline-color);color:var(--_disabled-outline-color)}.disabled .outline-start,.disabled .outline-end,.disabled .outline-panel-inactive{opacity:var(--_disabled-outline-opacity)}.disabled .outline-start::before,.disabled .outline-end::before,.disabled .outline-panel-inactive,.disabled .outline-panel-inactive::before,.disabled .outline-panel-inactive::after{border-width:var(--_disabled-outline-width)}.error .outline{border-color:var(--_error-outline-color);color:var(--_error-outline-color)}.error:hover .outline{border-color:var(--_error-hover-outline-color);color:var(--_error-hover-outline-color)}.error.focused .outline{border-color:var(--_error-focus-outline-color);color:var(--_error-focus-outline-color)}.resizable .container{bottom:var(--_focus-outline-width);inset-inline-end:var(--_focus-outline-width);clip-path:inset(var(--_focus-outline-width) 0 0 var(--_focus-outline-width))}.resizable .container>*{top:var(--_focus-outline-width);inset-inline-start:var(--_focus-outline-width)}.resizable .container:dir(rtl){clip-path:inset(var(--_focus-outline-width) var(--_focus-outline-width) 0 0)}}@layer hcm{@media(forced-colors: active){.disabled .outline{border-color:GrayText;color:GrayText}.disabled :is(.outline-start,.outline-end,.outline-panel-inactive){opacity:1}}}
`;

/**
 * @license
 * Copyright 2024 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Generated stylesheet for ./field/internal/shared-styles.css.
const styles$9 = i$7`:host{display:inline-flex;resize:both}.field{display:flex;flex:1;flex-direction:column;writing-mode:horizontal-tb;max-width:100%}.container-overflow{border-start-start-radius:var(--_container-shape-start-start);border-start-end-radius:var(--_container-shape-start-end);border-end-end-radius:var(--_container-shape-end-end);border-end-start-radius:var(--_container-shape-end-start);display:flex;height:100%;position:relative}.container{align-items:center;border-radius:inherit;display:flex;flex:1;max-height:100%;min-height:100%;min-width:min-content;position:relative}.field,.container-overflow{resize:inherit}.resizable:not(.disabled) .container{resize:inherit;overflow:hidden}.disabled{pointer-events:none}slot[name=container]{border-radius:inherit}slot[name=container]::slotted(*){border-radius:inherit;inset:0;pointer-events:none;position:absolute}@layer styles{.start,.middle,.end{display:flex;box-sizing:border-box;height:100%;position:relative}.start{color:var(--_leading-content-color)}.end{color:var(--_trailing-content-color)}.start,.end{align-items:center;justify-content:center}.with-start .start{margin-inline:var(--_with-leading-content-leading-space) var(--_content-space)}.with-end .end{margin-inline:var(--_content-space) var(--_with-trailing-content-trailing-space)}.middle{align-items:stretch;align-self:baseline;flex:1}.content{color:var(--_content-color);display:flex;flex:1;opacity:0;transition:opacity 83ms cubic-bezier(0.2, 0, 0, 1)}.no-label .content,.focused .content,.populated .content{opacity:1;transition-delay:67ms}:is(.disabled,.disable-transitions) .content{transition:none}.content ::slotted(*){all:unset;color:currentColor;font-family:var(--_content-font);font-size:var(--_content-size);line-height:var(--_content-line-height);font-weight:var(--_content-weight);width:100%;overflow-wrap:revert;white-space:revert}.content ::slotted(:not(textarea)){padding-top:var(--_top-space);padding-bottom:var(--_bottom-space)}.content ::slotted(textarea){margin-top:var(--_top-space);margin-bottom:var(--_bottom-space)}:hover .content{color:var(--_hover-content-color)}:hover .start{color:var(--_hover-leading-content-color)}:hover .end{color:var(--_hover-trailing-content-color)}.focused .content{color:var(--_focus-content-color)}.focused .start{color:var(--_focus-leading-content-color)}.focused .end{color:var(--_focus-trailing-content-color)}.disabled .content{color:var(--_disabled-content-color)}.disabled.no-label .content,.disabled.focused .content,.disabled.populated .content{opacity:var(--_disabled-content-opacity)}.disabled .start{color:var(--_disabled-leading-content-color);opacity:var(--_disabled-leading-content-opacity)}.disabled .end{color:var(--_disabled-trailing-content-color);opacity:var(--_disabled-trailing-content-opacity)}.error .content{color:var(--_error-content-color)}.error .start{color:var(--_error-leading-content-color)}.error .end{color:var(--_error-trailing-content-color)}.error:hover .content{color:var(--_error-hover-content-color)}.error:hover .start{color:var(--_error-hover-leading-content-color)}.error:hover .end{color:var(--_error-hover-trailing-content-color)}.error.focused .content{color:var(--_error-focus-content-color)}.error.focused .start{color:var(--_error-focus-leading-content-color)}.error.focused .end{color:var(--_error-focus-trailing-content-color)}}@layer hcm{@media(forced-colors: active){.disabled :is(.start,.content,.end){color:GrayText;opacity:1}}}@layer styles{.label{box-sizing:border-box;color:var(--_label-text-color);overflow:hidden;max-width:100%;text-overflow:ellipsis;white-space:nowrap;z-index:1;font-family:var(--_label-text-font);font-size:var(--_label-text-size);line-height:var(--_label-text-line-height);font-weight:var(--_label-text-weight);width:min-content}.label-wrapper{inset:0;pointer-events:none;position:absolute}.label.resting{position:absolute;top:var(--_top-space)}.label.floating{font-size:var(--_label-text-populated-size);line-height:var(--_label-text-populated-line-height);transform-origin:top left}.label.hidden{opacity:0}.no-label .label{display:none}.label-wrapper{inset:0;position:absolute;text-align:initial}:hover .label{color:var(--_hover-label-text-color)}.focused .label{color:var(--_focus-label-text-color)}.disabled .label{color:var(--_disabled-label-text-color)}.disabled .label:not(.hidden){opacity:var(--_disabled-label-text-opacity)}.error .label{color:var(--_error-label-text-color)}.error:hover .label{color:var(--_error-hover-label-text-color)}.error.focused .label{color:var(--_error-focus-label-text-color)}}@layer hcm{@media(forced-colors: active){.disabled .label:not(.hidden){color:GrayText;opacity:1}}}@layer styles{.supporting-text{color:var(--_supporting-text-color);display:flex;font-family:var(--_supporting-text-font);font-size:var(--_supporting-text-size);line-height:var(--_supporting-text-line-height);font-weight:var(--_supporting-text-weight);gap:16px;justify-content:space-between;padding-inline-start:var(--_supporting-text-leading-space);padding-inline-end:var(--_supporting-text-trailing-space);padding-top:var(--_supporting-text-top-space)}.supporting-text :nth-child(2){flex-shrink:0}:hover .supporting-text{color:var(--_hover-supporting-text-color)}.focus .supporting-text{color:var(--_focus-supporting-text-color)}.disabled .supporting-text{color:var(--_disabled-supporting-text-color);opacity:var(--_disabled-supporting-text-opacity)}.error .supporting-text{color:var(--_error-supporting-text-color)}.error:hover .supporting-text{color:var(--_error-hover-supporting-text-color)}.error.focus .supporting-text{color:var(--_error-focus-supporting-text-color)}}@layer hcm{@media(forced-colors: active){.disabled .supporting-text{color:GrayText;opacity:1}}}
`;

/**
 * @license
 * Copyright 2021 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * TODO(b/228525797): add docs
 * @final
 * @suppress {visibility}
 */
let MdOutlinedField = class MdOutlinedField extends OutlinedField {};
MdOutlinedField.styles = [styles$9, styles$a];
MdOutlinedField = __decorate([t$1('md-outlined-field')], MdOutlinedField);

/**
 * @license
 * Copyright 2018 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
const n$2 = "important",
  i$1 = " !" + n$2,
  o$2 = e$4(class extends i$3 {
    constructor(t$1) {
      if (super(t$1), t$1.type !== t.ATTRIBUTE || "style" !== t$1.name || t$1.strings?.length > 2) throw Error("The `styleMap` directive must be used in the `style` attribute and must be the only part in the attribute.");
    }
    render(t) {
      return Object.keys(t).reduce((e, r) => {
        const s = t[r];
        return null == s ? e : e + `${r = r.includes("-") ? r : r.replace(/(?:^(webkit|moz|ms|o)|)(?=[A-Z])/g, "-$&").toLowerCase()}:${s};`;
      }, "");
    }
    update(e, [r]) {
      const {
        style: s
      } = e.element;
      if (void 0 === this.ft) return this.ft = new Set(Object.keys(r)), this.render(r);
      for (const t of this.ft) null == r[t] && (this.ft.delete(t), t.includes("-") ? s.removeProperty(t) : s[t] = null);
      for (const t in r) {
        const e = r[t];
        if (null != e) {
          this.ft.add(t);
          const r = "string" == typeof e && e.endsWith(i$1);
          t.includes("-") || r ? s.setProperty(t, r ? e.slice(0, -11) : e, r ? n$2 : "") : s[t] = e;
        }
      }
      return E;
    }
  });

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * Creates an event that closes any parent menus.
 */
function createCloseMenuEvent(initiator, reason) {
  return new CustomEvent('close-menu', {
    bubbles: true,
    composed: true,
    detail: {
      initiator,
      reason,
      itemPath: [initiator]
    }
  });
}
/**
 * Creates a default close menu event used by md-menu.
 */
const createDefaultCloseMenuEvent = createCloseMenuEvent;
/**
 * Keys that are used for selection in menus.
 */
// tslint:disable-next-line:enforce-name-casing We are mimicking enum style
const SelectionKey = {
  SPACE: 'Space',
  ENTER: 'Enter'
};
/**
 * Default close `Reason` kind values.
 */
// tslint:disable-next-line:enforce-name-casing We are mimicking enum style
const CloseReason = {
  CLICK_SELECTION: 'click-selection',
  KEYDOWN: 'keydown'
};
/**
 * Keys that can close menus.
 */
// tslint:disable-next-line:enforce-name-casing We are mimicking enum style
const KeydownCloseKey = {
  ESCAPE: 'Escape',
  SPACE: SelectionKey.SPACE,
  ENTER: SelectionKey.ENTER
};
/**
 * Determines whether the given key code is a key code that should close the
 * menu.
 *
 * @param code The KeyboardEvent code to check.
 * @return Whether or not the key code is in the predetermined list to close the
 * menu.
 */
function isClosableKey(code) {
  return Object.values(KeydownCloseKey).some(value => value === code);
}
/**
 * Determines whether the given key code is a key code that should select a menu
 * item.
 *
 * @param code They KeyboardEvent code to check.
 * @return Whether or not the key code is in the predetermined list to select a
 * menu item.
 */
function isSelectableKey(code) {
  return Object.values(SelectionKey).some(value => value === code);
}
/**
 * Determines whether a target element is contained inside another element's
 * composed tree.
 *
 * @param target The potential contained element.
 * @param container The potential containing element of the target.
 * @returns Whether the target element is contained inside the container's
 * composed subtree
 */
function isElementInSubtree(target, container) {
  // Dispatch a composed, bubbling event to check its path to see if the
  // newly-focused element is contained in container's subtree
  const focusEv = new Event('md-contains', {
    bubbles: true,
    composed: true
  });
  let composedPath = [];
  const listener = ev => {
    composedPath = ev.composedPath();
  };
  container.addEventListener('md-contains', listener);
  target.dispatchEvent(focusEv);
  container.removeEventListener('md-contains', listener);
  const isContained = composedPath.length > 0;
  return isContained;
}
/**
 * Element to focus on when menu is first opened.
 */
// tslint:disable-next-line:enforce-name-casing We are mimicking enum style
const FocusState = {
  NONE: 'none',
  LIST_ROOT: 'list-root',
  FIRST_ITEM: 'first-item',
  LAST_ITEM: 'last-item'
};

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * An enum of supported Menu corners
 */
// tslint:disable-next-line:enforce-name-casing We are mimicking enum style
const Corner = {
  END_START: 'end-start',
  START_START: 'start-start'};
/**
 * Given a surface, an anchor, corners, and some options, this surface will
 * calculate the position of a surface to align the two given corners and keep
 * the surface inside the window viewport. It also provides a StyleInfo map that
 * can be applied to the surface to handle visiblility and position.
 */
class SurfacePositionController {
  /**
   * @param host The host to connect the controller to.
   * @param getProperties A function that returns the properties for the
   * controller.
   */
  constructor(host, getProperties) {
    this.host = host;
    this.getProperties = getProperties;
    // The current styles to apply to the surface.
    this.surfaceStylesInternal = {
      'display': 'none'
    };
    // Previous values stored for change detection. Open change detection is
    // calculated separately so initialize it here.
    this.lastValues = {
      isOpen: false
    };
    this.host.addController(this);
  }
  /**
   * The StyleInfo map to apply to the surface via Lit's stylemap
   */
  get surfaceStyles() {
    return this.surfaceStylesInternal;
  }
  /**
   * Calculates the surface's new position required so that the surface's
   * `surfaceCorner` aligns to the anchor's `anchorCorner` while keeping the
   * surface inside the window viewport. This positioning also respects RTL by
   * checking `getComputedStyle()` on the surface element.
   */
  async position() {
    const {
      surfaceEl,
      anchorEl,
      anchorCorner: anchorCornerRaw,
      surfaceCorner: surfaceCornerRaw,
      positioning,
      xOffset,
      yOffset,
      disableBlockFlip,
      disableInlineFlip,
      repositionStrategy
    } = this.getProperties();
    const anchorCorner = anchorCornerRaw.toLowerCase().trim();
    const surfaceCorner = surfaceCornerRaw.toLowerCase().trim();
    if (!surfaceEl || !anchorEl) {
      return;
    }
    // Store these before we potentially resize the window with the next set of
    // lines
    const windowInnerWidth = window.innerWidth;
    const windowInnerHeight = window.innerHeight;
    const div = document.createElement('div');
    div.style.opacity = '0';
    div.style.position = 'fixed';
    div.style.display = 'block';
    div.style.inset = '0';
    document.body.appendChild(div);
    const scrollbarTestRect = div.getBoundingClientRect();
    div.remove();
    // Calculate the widths of the scrollbars in the inline and block directions
    // to account for window-relative calculations.
    const blockScrollbarHeight = window.innerHeight - scrollbarTestRect.bottom;
    const inlineScrollbarWidth = window.innerWidth - scrollbarTestRect.right;
    // Paint the surface transparently so that we can get the position and the
    // rect info of the surface.
    this.surfaceStylesInternal = {
      'display': 'block',
      'opacity': '0'
    };
    // Wait for it to be visible.
    this.host.requestUpdate();
    await this.host.updateComplete;
    // Safari has a bug that makes popovers render incorrectly if the node is
    // made visible + Animation Frame before calling showPopover().
    // https://bugs.webkit.org/show_bug.cgi?id=264069
    // also the cast is required due to differing TS types in Google and OSS.
    if (surfaceEl.popover && surfaceEl.isConnected) {
      surfaceEl.showPopover();
    }
    const surfaceRect = surfaceEl.getSurfacePositionClientRect ? surfaceEl.getSurfacePositionClientRect() : surfaceEl.getBoundingClientRect();
    const anchorRect = anchorEl.getSurfacePositionClientRect ? anchorEl.getSurfacePositionClientRect() : anchorEl.getBoundingClientRect();
    const [surfaceBlock, surfaceInline] = surfaceCorner.split('-');
    const [anchorBlock, anchorInline] = anchorCorner.split('-');
    // LTR depends on the direction of the SURFACE not the anchor.
    const isLTR = getComputedStyle(surfaceEl).direction === 'ltr';
    /*
     * For more on inline and block dimensions, see MDN article:
     * https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_logical_properties_and_values
     *
     * ┌───── inline/blockDocumentOffset  inlineScrollbarWidth
     * │       │                                    │
     * │     ┌─▼─────┐                              │Document
     * │    ┌┼───────┴──────────────────────────────┼────────┐
     * │    ││                                      │        │
     * └──► ││ ┌───── inline/blockWindowOffset      │        │
     *      ││ │       │                            ▼        │
     *      ││ │     ┌─▼───┐                 Window┌┐        │
     *      └┤ │    ┌┼─────┴───────────────────────┼│        │
     *       │ │    ││                             ││        │
     *       │ └──► ││  ┌──inline/blockAnchorOffset││        │
     *       │      ││  │     │                    ││        │
     *       │      └┤  │  ┌──▼───┐                ││        │
     *       │       │  │ ┌┼──────┤                ││        │
     *       │       │  └─►│Anchor│                ││        │
     *       │       │    └┴──────┘                ││        │
     *       │       │                             ││        │
     *       │       │     ┌───────────────────────┼┼────┐   │
     *       │       │     │ Surface               ││    │   │
     *       │       │     │                       ││    │   │
     *       │       │     │                       ││    │   │
     *       │       │     │                       ││    │   │
     *       │       │     │                       ││    │   │
     *       │      ┌┼─────┼───────────────────────┼│    │   │
     *       │   ┌─►┴──────┼────────────────────────┘    ├┐  │
     *       │   │         │ inline/blockOOBCorrection   ││  │
     *       │   │         │                         │   ││  │
     *       │   │         │                         ├──►├│  │
     *       │   │         │                         │   ││  │
     *       │   │         └────────────────────────┐▼───┼┘  │
     *       │  blockScrollbarHeight                └────┘   │
     *       │                                               │
     *       └───────────────────────────────────────────────┘
     */
    // Calculate the block positioning properties
    let {
      blockInset,
      blockOutOfBoundsCorrection,
      surfaceBlockProperty
    } = this.calculateBlock({
      surfaceRect,
      anchorRect,
      anchorBlock,
      surfaceBlock,
      yOffset,
      positioning,
      windowInnerHeight,
      blockScrollbarHeight
    });
    // If the surface should be out of bounds in the block direction, flip the
    // surface and anchor corner block values and recalculate
    if (blockOutOfBoundsCorrection && !disableBlockFlip) {
      const flippedSurfaceBlock = surfaceBlock === 'start' ? 'end' : 'start';
      const flippedAnchorBlock = anchorBlock === 'start' ? 'end' : 'start';
      const flippedBlock = this.calculateBlock({
        surfaceRect,
        anchorRect,
        anchorBlock: flippedAnchorBlock,
        surfaceBlock: flippedSurfaceBlock,
        yOffset,
        positioning,
        windowInnerHeight,
        blockScrollbarHeight
      });
      // In the case that the flipped verion would require less out of bounds
      // correcting, use the flipped corner block values
      if (blockOutOfBoundsCorrection > flippedBlock.blockOutOfBoundsCorrection) {
        blockInset = flippedBlock.blockInset;
        blockOutOfBoundsCorrection = flippedBlock.blockOutOfBoundsCorrection;
        surfaceBlockProperty = flippedBlock.surfaceBlockProperty;
      }
    }
    // Calculate the inline positioning properties
    let {
      inlineInset,
      inlineOutOfBoundsCorrection,
      surfaceInlineProperty
    } = this.calculateInline({
      surfaceRect,
      anchorRect,
      anchorInline,
      surfaceInline,
      xOffset,
      positioning,
      isLTR,
      windowInnerWidth,
      inlineScrollbarWidth
    });
    // If the surface should be out of bounds in the inline direction, flip the
    // surface and anchor corner inline values and recalculate
    if (inlineOutOfBoundsCorrection && !disableInlineFlip) {
      const flippedSurfaceInline = surfaceInline === 'start' ? 'end' : 'start';
      const flippedAnchorInline = anchorInline === 'start' ? 'end' : 'start';
      const flippedInline = this.calculateInline({
        surfaceRect,
        anchorRect,
        anchorInline: flippedAnchorInline,
        surfaceInline: flippedSurfaceInline,
        xOffset,
        positioning,
        isLTR,
        windowInnerWidth,
        inlineScrollbarWidth
      });
      // In the case that the flipped verion would require less out of bounds
      // correcting, use the flipped corner inline values
      if (Math.abs(inlineOutOfBoundsCorrection) > Math.abs(flippedInline.inlineOutOfBoundsCorrection)) {
        inlineInset = flippedInline.inlineInset;
        inlineOutOfBoundsCorrection = flippedInline.inlineOutOfBoundsCorrection;
        surfaceInlineProperty = flippedInline.surfaceInlineProperty;
      }
    }
    // If we are simply repositioning the surface back inside the viewport,
    // subtract the out of bounds correction values from the positioning.
    if (repositionStrategy === 'move') {
      blockInset = blockInset - blockOutOfBoundsCorrection;
      inlineInset = inlineInset - inlineOutOfBoundsCorrection;
    }
    this.surfaceStylesInternal = {
      'display': 'block',
      'opacity': '1',
      [surfaceBlockProperty]: `${blockInset}px`,
      [surfaceInlineProperty]: `${inlineInset}px`
    };
    // In the case that we are resizing the surface to stay inside the viewport
    // we need to set height and width on the surface.
    if (repositionStrategy === 'resize') {
      // Add a height property to the styles if there is block height correction
      if (blockOutOfBoundsCorrection) {
        this.surfaceStylesInternal['height'] = `${surfaceRect.height - blockOutOfBoundsCorrection}px`;
      }
      // Add a width property to the styles if there is block height correction
      if (inlineOutOfBoundsCorrection) {
        this.surfaceStylesInternal['width'] = `${surfaceRect.width - inlineOutOfBoundsCorrection}px`;
      }
    }
    this.host.requestUpdate();
  }
  /**
   * Calculates the css property, the inset, and the out of bounds correction
   * for the surface in the block direction.
   */
  calculateBlock(config) {
    const {
      surfaceRect,
      anchorRect,
      anchorBlock,
      surfaceBlock,
      yOffset,
      positioning,
      windowInnerHeight,
      blockScrollbarHeight
    } = config;
    // We use number booleans to multiply values rather than `if` / ternary
    // statements because it _heavily_ cuts down on nesting and readability
    const relativeToWindow = positioning === 'fixed' || positioning === 'document' ? 1 : 0;
    const relativeToDocument = positioning === 'document' ? 1 : 0;
    const isSurfaceBlockStart = surfaceBlock === 'start' ? 1 : 0;
    const isSurfaceBlockEnd = surfaceBlock === 'end' ? 1 : 0;
    const isOneBlockEnd = anchorBlock !== surfaceBlock ? 1 : 0;
    // Whether or not to apply the height of the anchor
    const blockAnchorOffset = isOneBlockEnd * anchorRect.height + yOffset;
    // The absolute block position of the anchor relative to window
    const blockTopLayerOffset = isSurfaceBlockStart * anchorRect.top + isSurfaceBlockEnd * (windowInnerHeight - anchorRect.bottom - blockScrollbarHeight);
    const blockDocumentOffset = isSurfaceBlockStart * window.scrollY - isSurfaceBlockEnd * window.scrollY;
    // If the surface's block would be out of bounds of the window, move it back
    // in
    const blockOutOfBoundsCorrection = Math.abs(Math.min(0, windowInnerHeight - blockTopLayerOffset - blockAnchorOffset - surfaceRect.height));
    // The block logical value of the surface
    const blockInset = relativeToWindow * blockTopLayerOffset + relativeToDocument * blockDocumentOffset + blockAnchorOffset;
    const surfaceBlockProperty = surfaceBlock === 'start' ? 'inset-block-start' : 'inset-block-end';
    return {
      blockInset,
      blockOutOfBoundsCorrection,
      surfaceBlockProperty
    };
  }
  /**
   * Calculates the css property, the inset, and the out of bounds correction
   * for the surface in the inline direction.
   */
  calculateInline(config) {
    const {
      isLTR: isLTRBool,
      surfaceInline,
      anchorInline,
      anchorRect,
      surfaceRect,
      xOffset,
      positioning,
      windowInnerWidth,
      inlineScrollbarWidth
    } = config;
    // We use number booleans to multiply values rather than `if` / ternary
    // statements because it _heavily_ cuts down on nesting and readability
    const relativeToWindow = positioning === 'fixed' || positioning === 'document' ? 1 : 0;
    const relativeToDocument = positioning === 'document' ? 1 : 0;
    const isLTR = isLTRBool ? 1 : 0;
    const isRTL = isLTRBool ? 0 : 1;
    const isSurfaceInlineStart = surfaceInline === 'start' ? 1 : 0;
    const isSurfaceInlineEnd = surfaceInline === 'end' ? 1 : 0;
    const isOneInlineEnd = anchorInline !== surfaceInline ? 1 : 0;
    // Whether or not to apply the width of the anchor
    const inlineAnchorOffset = isOneInlineEnd * anchorRect.width + xOffset;
    // The inline position of the anchor relative to window in LTR
    const inlineTopLayerOffsetLTR = isSurfaceInlineStart * anchorRect.left + isSurfaceInlineEnd * (windowInnerWidth - anchorRect.right - inlineScrollbarWidth);
    // The inline position of the anchor relative to window in RTL
    const inlineTopLayerOffsetRTL = isSurfaceInlineStart * (windowInnerWidth - anchorRect.right - inlineScrollbarWidth) + isSurfaceInlineEnd * anchorRect.left;
    // The inline position of the anchor relative to window
    const inlineTopLayerOffset = isLTR * inlineTopLayerOffsetLTR + isRTL * inlineTopLayerOffsetRTL;
    // The inline position of the anchor relative to window in LTR
    const inlineDocumentOffsetLTR = isSurfaceInlineStart * window.scrollX - isSurfaceInlineEnd * window.scrollX;
    // The inline position of the anchor relative to window in RTL
    const inlineDocumentOffsetRTL = isSurfaceInlineEnd * window.scrollX - isSurfaceInlineStart * window.scrollX;
    // The inline position of the anchor relative to window
    const inlineDocumentOffset = isLTR * inlineDocumentOffsetLTR + isRTL * inlineDocumentOffsetRTL;
    // If the surface's inline would be out of bounds of the window, move it
    // back in
    const inlineOutOfBoundsCorrection = Math.abs(Math.min(0, windowInnerWidth - inlineTopLayerOffset - inlineAnchorOffset - surfaceRect.width));
    // The inline logical value of the surface
    const inlineInset = relativeToWindow * inlineTopLayerOffset + inlineAnchorOffset + relativeToDocument * inlineDocumentOffset;
    let surfaceInlineProperty = surfaceInline === 'start' ? 'inset-inline-start' : 'inset-inline-end';
    // There are cases where the element is RTL but the root of the page is not.
    // In these cases we want to not use logical properties.
    if (positioning === 'document' || positioning === 'fixed') {
      if (surfaceInline === 'start' && isLTRBool || surfaceInline === 'end' && !isLTRBool) {
        surfaceInlineProperty = 'left';
      } else {
        surfaceInlineProperty = 'right';
      }
    }
    return {
      inlineInset,
      inlineOutOfBoundsCorrection,
      surfaceInlineProperty
    };
  }
  hostUpdate() {
    this.onUpdate();
  }
  hostUpdated() {
    this.onUpdate();
  }
  /**
   * Checks whether the properties passed into the controller have changed since
   * the last positioning. If so, it will reposition if the surface is open or
   * close it if the surface should close.
   */
  async onUpdate() {
    const props = this.getProperties();
    let hasChanged = false;
    for (const [key, value] of Object.entries(props)) {
      // tslint:disable-next-line
      hasChanged = hasChanged || value !== this.lastValues[key];
      if (hasChanged) break;
    }
    const openChanged = this.lastValues.isOpen !== props.isOpen;
    const hasAnchor = !!props.anchorEl;
    const hasSurface = !!props.surfaceEl;
    if (hasChanged && hasAnchor && hasSurface) {
      // Only update isOpen, because if it's closed, we do not want to waste
      // time on a useless reposition calculation. So save the other "dirty"
      // values until next time it opens.
      this.lastValues.isOpen = props.isOpen;
      if (props.isOpen) {
        // We are going to do a reposition, so save the prop values for future
        // dirty checking.
        this.lastValues = props;
        await this.position();
        props.onOpen();
      } else if (openChanged) {
        await props.beforeClose();
        this.close();
        props.onClose();
      }
    }
  }
  /**
   * Hides the surface.
   */
  close() {
    this.surfaceStylesInternal = {
      'display': 'none'
    };
    this.host.requestUpdate();
    const surfaceEl = this.getProperties().surfaceEl;
    // The following type casts are required due to differing TS types in Google
    // and open source.
    if (surfaceEl?.popover && surfaceEl?.isConnected) {
      surfaceEl.hidePopover();
    }
  }
}

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * Indicies to access the TypeaheadRecord tuple type.
 */
const TYPEAHEAD_RECORD = {
  INDEX: 0,
  ITEM: 1,
  TEXT: 2
};
/**
 * This controller listens to `keydown` events and searches the header text of
 * an array of `MenuItem`s with the corresponding entered keys within the buffer
 * time and activates the item.
 *
 * @example
 * ```ts
 * const typeaheadController = new TypeaheadController(() => ({
 *   typeaheadBufferTime: 50,
 *   getItems: () => Array.from(document.querySelectorAll('md-menu-item'))
 * }));
 * html`
 *   <div
 *       @keydown=${typeaheadController.onKeydown}
 *       tabindex="0"
 *       class="activeItemText">
 *     <!-- focusable element that will receive keydown events -->
 *     Apple
 *   </div>
 *   <div>
 *     <md-menu-item active header="Apple"></md-menu-item>
 *     <md-menu-item header="Apricot"></md-menu-item>
 *     <md-menu-item header="Banana"></md-menu-item>
 *     <md-menu-item header="Olive"></md-menu-item>
 *     <md-menu-item header="Orange"></md-menu-item>
 *   </div>
 * `;
 * ```
 */
class TypeaheadController {
  /**
   * @param getProperties A function that returns the options of the typeahead
   * controller:
   *
   * {
   *   getItems: A function that returns an array of menu items to be searched.
   *   typeaheadBufferTime: The maximum time between each keystroke to keep the
   *       current type buffer alive.
   * }
   */
  constructor(getProperties) {
    this.getProperties = getProperties;
    /**
     * Array of tuples that helps with indexing.
     */
    this.typeaheadRecords = [];
    /**
     * Currently-typed text since last buffer timeout
     */
    this.typaheadBuffer = '';
    /**
     * The timeout id from the current buffer's setTimeout
     */
    this.cancelTypeaheadTimeout = 0;
    /**
     * If we are currently "typing"
     */
    this.isTypingAhead = false;
    /**
     * The record of the last active item.
     */
    this.lastActiveRecord = null;
    /**
     * Apply this listener to the element that will receive `keydown` events that
     * should trigger this controller.
     *
     * @param event The native browser `KeyboardEvent` from the `keydown` event.
     */
    this.onKeydown = event => {
      if (this.isTypingAhead) {
        this.typeahead(event);
      } else {
        this.beginTypeahead(event);
      }
    };
    /**
     * Ends the current typeahead and clears the buffer.
     */
    this.endTypeahead = () => {
      this.isTypingAhead = false;
      this.typaheadBuffer = '';
      this.typeaheadRecords = [];
    };
  }
  get items() {
    return this.getProperties().getItems();
  }
  get active() {
    return this.getProperties().active;
  }
  /**
   * Sets up typingahead
   */
  beginTypeahead(event) {
    if (!this.active) {
      return;
    }
    // We don't want to typeahead if the _beginning_ of the typeahead is a menu
    // navigation, or a selection. We will handle "Space" only if it's in the
    // middle of a typeahead
    if (event.code === 'Space' || event.code === 'Enter' || event.code.startsWith('Arrow') || event.code === 'Escape') {
      return;
    }
    this.isTypingAhead = true;
    // Generates the record array data structure which is the index, the element
    // and a normalized header.
    this.typeaheadRecords = this.items.map((el, index) => [index, el, el.typeaheadText.trim().toLowerCase()]);
    this.lastActiveRecord = this.typeaheadRecords.find(record => record[TYPEAHEAD_RECORD.ITEM].tabIndex === 0) ?? null;
    if (this.lastActiveRecord) {
      this.lastActiveRecord[TYPEAHEAD_RECORD.ITEM].tabIndex = -1;
    }
    this.typeahead(event);
  }
  /**
   * Performs the typeahead. Based on the normalized items and the current text
   * buffer, finds the _next_ item with matching text and activates it.
   *
   * @example
   *
   * items: Apple, Banana, Olive, Orange, Cucumber
   * buffer: ''
   * user types: o
   *
   * activates Olive
   *
   * @example
   *
   * items: Apple, Banana, Olive (active), Orange, Cucumber
   * buffer: 'o'
   * user types: l
   *
   * activates Olive
   *
   * @example
   *
   * items: Apple, Banana, Olive (active), Orange, Cucumber
   * buffer: ''
   * user types: o
   *
   * activates Orange
   *
   * @example
   *
   * items: Apple, Banana, Olive, Orange (active), Cucumber
   * buffer: ''
   * user types: o
   *
   * activates Olive
   */
  typeahead(event) {
    if (event.defaultPrevented) return;
    clearTimeout(this.cancelTypeaheadTimeout);
    // Stop typingahead if one of the navigation or selection keys (except for
    // Space) are pressed
    if (event.code === 'Enter' || event.code.startsWith('Arrow') || event.code === 'Escape') {
      this.endTypeahead();
      if (this.lastActiveRecord) {
        this.lastActiveRecord[TYPEAHEAD_RECORD.ITEM].tabIndex = -1;
      }
      return;
    }
    // If Space is pressed, prevent it from selecting and closing the menu
    if (event.code === 'Space') {
      event.preventDefault();
    }
    // Start up a new keystroke buffer timeout
    this.cancelTypeaheadTimeout = setTimeout(this.endTypeahead, this.getProperties().typeaheadBufferTime);
    this.typaheadBuffer += event.key.toLowerCase();
    const lastActiveIndex = this.lastActiveRecord ? this.lastActiveRecord[TYPEAHEAD_RECORD.INDEX] : -1;
    const numRecords = this.typeaheadRecords.length;
    /**
     * Sorting function that will resort the items starting with the given index
     *
     * @example
     *
     * this.typeaheadRecords =
     * 0: [0, <reference>, 'apple']
     * 1: [1, <reference>, 'apricot']
     * 2: [2, <reference>, 'banana']
     * 3: [3, <reference>, 'olive'] <-- lastActiveIndex
     * 4: [4, <reference>, 'orange']
     * 5: [5, <reference>, 'strawberry']
     *
     * this.typeaheadRecords.sort((a,b) => rebaseIndexOnActive(a)
     *                                       - rebaseIndexOnActive(b)) ===
     * 0: [3, <reference>, 'olive'] <-- lastActiveIndex
     * 1: [4, <reference>, 'orange']
     * 2: [5, <reference>, 'strawberry']
     * 3: [0, <reference>, 'apple']
     * 4: [1, <reference>, 'apricot']
     * 5: [2, <reference>, 'banana']
     */
    const rebaseIndexOnActive = record => {
      return (record[TYPEAHEAD_RECORD.INDEX] + numRecords - lastActiveIndex) % numRecords;
    };
    // records filtered and sorted / rebased around the last active index
    const matchingRecords = this.typeaheadRecords.filter(record => !record[TYPEAHEAD_RECORD.ITEM].disabled && record[TYPEAHEAD_RECORD.TEXT].startsWith(this.typaheadBuffer)).sort((a, b) => rebaseIndexOnActive(a) - rebaseIndexOnActive(b));
    // Just leave if there's nothing that matches. Native select will just
    // choose the first thing that starts with the next letter in the alphabet
    // but that's out of scope and hard to localize
    if (matchingRecords.length === 0) {
      clearTimeout(this.cancelTypeaheadTimeout);
      if (this.lastActiveRecord) {
        this.lastActiveRecord[TYPEAHEAD_RECORD.ITEM].tabIndex = -1;
      }
      this.endTypeahead();
      return;
    }
    const isNewQuery = this.typaheadBuffer.length === 1;
    let nextRecord;
    // This is likely the case that someone is trying to "tab" through different
    // entries that start with the same letter
    if (this.lastActiveRecord === matchingRecords[0] && isNewQuery) {
      nextRecord = matchingRecords[1] ?? matchingRecords[0];
    } else {
      nextRecord = matchingRecords[0];
    }
    if (this.lastActiveRecord) {
      this.lastActiveRecord[TYPEAHEAD_RECORD.ITEM].tabIndex = -1;
    }
    this.lastActiveRecord = nextRecord;
    nextRecord[TYPEAHEAD_RECORD.ITEM].tabIndex = 0;
    nextRecord[TYPEAHEAD_RECORD.ITEM].focus();
    return;
  }
}

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * The default value for the typeahead buffer time in Milliseconds.
 */
const DEFAULT_TYPEAHEAD_BUFFER_TIME = 200;
const submenuNavKeys = new Set([NavigableKeys.ArrowDown, NavigableKeys.ArrowUp, NavigableKeys.Home, NavigableKeys.End]);
const menuNavKeys = new Set([NavigableKeys.ArrowLeft, NavigableKeys.ArrowRight, ...submenuNavKeys]);
/**
 * Gets the currently focused element on the page.
 *
 * @param activeDoc The document or shadowroot from which to start the search.
 *    Defaults to `window.document`
 * @return Returns the currently deeply focused element or `null` if none.
 */
function getFocusedElement(activeDoc = document) {
  let activeEl = activeDoc.activeElement;
  // Check for activeElement in the case that an element with a shadow root host
  // is currently focused.
  while (activeEl && activeEl?.shadowRoot?.activeElement) {
    activeEl = activeEl.shadowRoot.activeElement;
  }
  return activeEl;
}
/**
 * @fires opening {Event} Fired before the opening animation begins
 * @fires opened {Event} Fired once the menu is open, after any animations
 * @fires closing {Event} Fired before the closing animation begins
 * @fires closed {Event} Fired once the menu is closed, after any animations
 */
class Menu extends i$4 {
  /**
   * Whether the menu is animating upwards or downwards when opening. This is
   * helpful for calculating some animation calculations.
   */
  get openDirection() {
    const menuCornerBlock = this.menuCorner.split('-')[0];
    return menuCornerBlock === 'start' ? 'DOWN' : 'UP';
  }
  /**
   * The element which the menu should align to. If `anchor` is set to a
   * non-empty idref string, then `anchorEl` will resolve to the element with
   * the given id in the same root node. Otherwise, `null`.
   */
  get anchorElement() {
    if (this.anchor) {
      return this.getRootNode().querySelector(`#${this.anchor}`);
    }
    return this.currentAnchorElement;
  }
  set anchorElement(element) {
    this.currentAnchorElement = element;
    this.requestUpdate('anchorElement');
  }
  constructor() {
    super();
    /**
     * The ID of the element in the same root node in which the menu should align
     * to. Overrides setting `anchorElement = elementReference`.
     *
     * __NOTE__: anchor or anchorElement must either be an HTMLElement or resolve
     * to an HTMLElement in order for menu to open.
     */
    this.anchor = '';
    /**
     * Whether the positioning algorithm should calculate relative to the parent
     * of the anchor element (`absolute`), relative to the window (`fixed`), or
     * relative to the document (`document`). `popover` will use the popover API
     * to render the menu in the top-layer. If your browser does not support the
     * popover API, it will fall back to `fixed`.
     *
     * __Examples for `position = 'fixed'`:__
     *
     * - If there is no `position:relative` in the given parent tree and the
     *   surface is `position:absolute`
     * - If the surface is `position:fixed`
     * - If the surface is in the "top layer"
     * - The anchor and the surface do not share a common `position:relative`
     *   ancestor
     *
     * When using `positioning=fixed`, in most cases, the menu should position
     * itself above most other `position:absolute` or `position:fixed` elements
     * when placed inside of them. e.g. using a menu inside of an `md-dialog`.
     *
     * __NOTE__: Fixed menus will not scroll with the page and will be fixed to
     * the window instead.
     *
     * __Examples for `position = 'document'`:__
     *
     * - There is no parent that creates a relative positioning context e.g.
     *   `position: relative`, `position: absolute`, `transform: translate(x, y)`,
     *   etc.
     * - You put the effort into hoisting the menu to the top of the DOM like the
     *   end of the `<body>` to render over everything or in a top-layer.
     * - You are reusing a single `md-menu` element that dynamically renders
     *   content.
     *
     * __Examples for `position = 'popover'`:__
     *
     * - Your browser supports `popover`.
     * - Most cases. Once popover is in browsers, this will become the default.
     */
    this.positioning = 'absolute';
    /**
     * Skips the opening and closing animations.
     */
    this.quick = false;
    /**
     * Displays overflow content like a submenu. Not required in most cases when
     * using `positioning="popover"`.
     *
     * __NOTE__: This may cause adverse effects if you set
     * `md-menu {max-height:...}`
     * and have items overflowing items in the "y" direction.
     */
    this.hasOverflow = false;
    /**
     * Opens the menu and makes it visible. Alternative to the `.show()` and
     * `.close()` methods
     */
    this.open = false;
    /**
     * Offsets the menu's inline alignment from the anchor by the given number in
     * pixels. This value is direction aware and will follow the LTR / RTL
     * direction.
     *
     * e.g. LTR: positive -> right, negative -> left
     *      RTL: positive -> left, negative -> right
     */
    this.xOffset = 0;
    /**
     * Offsets the menu's block alignment from the anchor by the given number in
     * pixels.
     *
     * e.g. positive -> down, negative -> up
     */
    this.yOffset = 0;
    /**
     * Disable the `flip` behavior that usually happens on the horizontal axis
     * when the surface would render outside the viewport.
     */
    this.noHorizontalFlip = false;
    /**
     * Disable the `flip` behavior that usually happens on the vertical axis when
     * the surface would render outside the viewport.
     */
    this.noVerticalFlip = false;
    /**
     * The max time between the keystrokes of the typeahead menu behavior before
     * it clears the typeahead buffer.
     */
    this.typeaheadDelay = DEFAULT_TYPEAHEAD_BUFFER_TIME;
    /**
     * The corner of the anchor which to align the menu in the standard logical
     * property style of <block>-<inline> e.g. `'end-start'`.
     *
     * NOTE: This value may not be respected by the menu positioning algorithm
     * if the menu would render outisde the viewport.
     * Use `no-horizontal-flip` or `no-vertical-flip` to force the usage of the value
     */
    this.anchorCorner = Corner.END_START;
    /**
     * The corner of the menu which to align the anchor in the standard logical
     * property style of <block>-<inline> e.g. `'start-start'`.
     *
     * NOTE: This value may not be respected by the menu positioning algorithm
     * if the menu would render outisde the viewport.
     * Use `no-horizontal-flip` or `no-vertical-flip` to force the usage of the value
     */
    this.menuCorner = Corner.START_START;
    /**
     * Keeps the user clicks outside the menu.
     *
     * NOTE: clicking outside may still cause focusout to close the menu so see
     * `stayOpenOnFocusout`.
     */
    this.stayOpenOnOutsideClick = false;
    /**
     * Keeps the menu open when focus leaves the menu's composed subtree.
     *
     * NOTE: Focusout behavior will stop propagation of the focusout event. Set
     * this property to true to opt-out of menu's focusout handling altogether.
     */
    this.stayOpenOnFocusout = false;
    /**
     * After closing, does not restore focus to the last focused element before
     * the menu was opened.
     */
    this.skipRestoreFocus = false;
    /**
     * The element that should be focused by default once opened.
     *
     * NOTE: When setting default focus to 'LIST_ROOT', remember to change
     * `tabindex` to `0` and change md-menu's display to something other than
     * `display: contents` when necessary.
     */
    this.defaultFocus = FocusState.FIRST_ITEM;
    /**
     * Turns off navigation wrapping. By default, navigating past the end of the
     * menu items will wrap focus back to the beginning and vice versa. Use this
     * for ARIA patterns that do not wrap focus, like combobox.
     */
    this.noNavigationWrap = false;
    this.typeaheadActive = true;
    /**
     * Whether or not the current menu is a submenu and should not handle specific
     * navigation keys.
     *
     * @export
     */
    this.isSubmenu = false;
    /**
     * The event path of the last window pointerdown event.
     */
    this.pointerPath = [];
    /**
     * Whether or not the menu is repositoining due to window / document resize
     */
    this.isRepositioning = false;
    this.openCloseAnimationSignal = createAnimationSignal();
    this.listController = new ListController({
      isItem: maybeItem => {
        return maybeItem.hasAttribute('md-menu-item');
      },
      getPossibleItems: () => this.slotItems,
      isRtl: () => getComputedStyle(this).direction === 'rtl',
      deactivateItem: item => {
        item.selected = false;
        item.tabIndex = -1;
      },
      activateItem: item => {
        item.selected = true;
        item.tabIndex = 0;
      },
      isNavigableKey: key => {
        if (!this.isSubmenu) {
          return menuNavKeys.has(key);
        }
        const isRtl = getComputedStyle(this).direction === 'rtl';
        // we want md-submenu to handle the submenu's left/right arrow exit
        // key so it can close the menu instead of navigate the list.
        // Therefore we need to include all keys but left/right arrow close
        // key
        const arrowOpen = isRtl ? NavigableKeys.ArrowLeft : NavigableKeys.ArrowRight;
        if (key === arrowOpen) {
          return true;
        }
        return submenuNavKeys.has(key);
      },
      wrapNavigation: () => !this.noNavigationWrap
    });
    /**
     * The element that was focused before the menu opened.
     */
    this.lastFocusedElement = null;
    /**
     * Handles typeahead navigation through the menu.
     */
    this.typeaheadController = new TypeaheadController(() => {
      return {
        getItems: () => this.items,
        typeaheadBufferTime: this.typeaheadDelay,
        active: this.typeaheadActive
      };
    });
    this.currentAnchorElement = null;
    this.internals =
    // Cast needed for closure
    this.attachInternals();
    /**
     * Handles positioning the surface and aligning it to the anchor as well as
     * keeping it in the viewport.
     */
    this.menuPositionController = new SurfacePositionController(this, () => {
      return {
        anchorCorner: this.anchorCorner,
        surfaceCorner: this.menuCorner,
        surfaceEl: this.surfaceEl,
        anchorEl: this.anchorElement,
        positioning: this.positioning === 'popover' ? 'document' : this.positioning,
        isOpen: this.open,
        xOffset: this.xOffset,
        yOffset: this.yOffset,
        disableBlockFlip: this.noVerticalFlip,
        disableInlineFlip: this.noHorizontalFlip,
        onOpen: this.onOpened,
        beforeClose: this.beforeClose,
        onClose: this.onClosed,
        // We can't resize components that have overflow like menus with
        // submenus because the overflow-y will show menu items / content
        // outside the bounds of the menu. Popover API fixes this because each
        // submenu is hoisted to the top-layer and are not considered overflow
        // content.
        repositionStrategy: this.hasOverflow && this.positioning !== 'popover' ? 'move' : 'resize'
      };
    });
    this.onWindowResize = () => {
      if (this.isRepositioning || this.positioning !== 'document' && this.positioning !== 'fixed' && this.positioning !== 'popover') {
        return;
      }
      this.isRepositioning = true;
      this.reposition();
      this.isRepositioning = false;
    };
    this.handleFocusout = async event => {
      const anchorEl = this.anchorElement;
      // Do not close if we focused out by clicking on the anchor element. We
      // can't assume anchor buttons can be the related target because of iOS does
      // not focus buttons.
      if (this.stayOpenOnFocusout || !this.open || this.pointerPath.includes(anchorEl)) {
        return;
      }
      if (event.relatedTarget) {
        // Don't close the menu if we are switching focus between menu,
        // md-menu-item, and md-list or if the anchor was click focused, but check
        // if length of pointerPath is 0 because that means something was at least
        // clicked (shift+tab case).
        if (isElementInSubtree(event.relatedTarget, this) || this.pointerPath.length !== 0 && isElementInSubtree(event.relatedTarget, anchorEl)) {
          return;
        }
      } else if (this.pointerPath.includes(this)) {
        // If menu tabindex == -1 and the user clicks on the menu or a divider, we
        // want to keep the menu open.
        return;
      }
      const oldRestoreFocus = this.skipRestoreFocus;
      // allow focus to continue to the next focused object rather than returning
      this.skipRestoreFocus = true;
      this.close();
      // await for close
      await this.updateComplete;
      // return to previous behavior
      this.skipRestoreFocus = oldRestoreFocus;
    };
    /**
     * Saves the last focused element focuses the new element based on
     * `defaultFocus`, and animates open.
     */
    this.onOpened = async () => {
      this.lastFocusedElement = getFocusedElement();
      const items = this.items;
      const activeItemRecord = getActiveItem(items);
      if (activeItemRecord && this.defaultFocus !== FocusState.NONE) {
        activeItemRecord.item.tabIndex = -1;
      }
      let animationAborted = !this.quick;
      if (this.quick) {
        this.dispatchEvent(new Event('opening'));
      } else {
        animationAborted = !!(await this.animateOpen());
      }
      // This must come after the opening animation or else it may focus one of
      // the items before the animation has begun and causes the list to slide
      // (block-padding-of-the-menu)px at the end of the animation
      switch (this.defaultFocus) {
        case FocusState.FIRST_ITEM:
          const first = getFirstActivatableItem(items);
          if (first) {
            first.tabIndex = 0;
            first.focus();
            await first.updateComplete;
          }
          break;
        case FocusState.LAST_ITEM:
          const last = getLastActivatableItem(items);
          if (last) {
            last.tabIndex = 0;
            last.focus();
            await last.updateComplete;
          }
          break;
        case FocusState.LIST_ROOT:
          this.focus();
          break;
        default:
        case FocusState.NONE:
          // Do nothing.
          break;
      }
      if (!animationAborted) {
        this.dispatchEvent(new Event('opened'));
      }
    };
    /**
     * Animates closed.
     */
    this.beforeClose = async () => {
      this.open = false;
      if (!this.skipRestoreFocus) {
        this.lastFocusedElement?.focus?.();
      }
      if (!this.quick) {
        await this.animateClose();
      }
    };
    /**
     * Focuses the last focused element.
     */
    this.onClosed = () => {
      if (this.quick) {
        this.dispatchEvent(new Event('closing'));
        this.dispatchEvent(new Event('closed'));
      }
    };
    this.onWindowPointerdown = event => {
      this.pointerPath = event.composedPath();
    };
    /**
     * We cannot listen to window click because Safari on iOS will not bubble a
     * click event on window if the item clicked is not a "clickable" item such as
     * <body>
     */
    this.onDocumentClick = event => {
      if (!this.open) {
        return;
      }
      const path = event.composedPath();
      if (!this.stayOpenOnOutsideClick && !path.includes(this) && !path.includes(this.anchorElement)) {
        this.open = false;
      }
    };
    {
      this.internals.role = 'menu';
      this.addEventListener('keydown', this.handleKeydown);
      // Capture so that we can grab the event before it reaches the menu item
      // istelf. Specifically useful for the case where typeahead encounters a
      // space and we don't want the menu item to close the menu.
      this.addEventListener('keydown', this.captureKeydown, {
        capture: true
      });
      this.addEventListener('focusout', this.handleFocusout);
    }
  }
  /**
   * The menu items associated with this menu. The items must be `MenuItem`s and
   * have both the `md-menu-item` and `md-list-item` attributes.
   */
  get items() {
    return this.listController.items;
  }
  willUpdate(changed) {
    if (!changed.has('open')) {
      return;
    }
    if (this.open) {
      this.removeAttribute('aria-hidden');
      return;
    }
    this.setAttribute('aria-hidden', 'true');
  }
  update(changed) {
    if (changed.has('open')) {
      if (this.open) {
        this.setUpGlobalEventListeners();
      } else {
        this.cleanUpGlobalEventListeners();
      }
    }
    // Firefox does not support popover. Fall-back to using fixed.
    if (changed.has('positioning') && this.positioning === 'popover' &&
    // type required for Google JS conformance
    !this.showPopover) {
      this.positioning = 'fixed';
    }
    super.update(changed);
  }
  connectedCallback() {
    super.connectedCallback();
    if (this.open) {
      this.setUpGlobalEventListeners();
    }
  }
  disconnectedCallback() {
    super.disconnectedCallback();
    this.cleanUpGlobalEventListeners();
  }
  getBoundingClientRect() {
    if (!this.surfaceEl) {
      return super.getBoundingClientRect();
    }
    return this.surfaceEl.getBoundingClientRect();
  }
  getClientRects() {
    if (!this.surfaceEl) {
      return super.getClientRects();
    }
    return this.surfaceEl.getClientRects();
  }
  render() {
    return this.renderSurface();
  }
  /**
   * Renders the positionable surface element and its contents.
   */
  renderSurface() {
    return b`
      <div
        class="menu ${e$3(this.getSurfaceClasses())}"
        style=${o$2(this.menuPositionController.surfaceStyles)}
        popover=${this.positioning === 'popover' ? 'manual' : A}>
        ${this.renderElevation()}
        <div class="items">
          <div class="item-padding"> ${this.renderMenuItems()} </div>
        </div>
      </div>
    `;
  }
  /**
   * Renders the menu items' slot
   */
  renderMenuItems() {
    return b`<slot
      @close-menu=${this.onCloseMenu}
      @deactivate-items=${this.onDeactivateItems}
      @request-activation=${this.onRequestActivation}
      @deactivate-typeahead=${this.handleDeactivateTypeahead}
      @activate-typeahead=${this.handleActivateTypeahead}
      @stay-open-on-focusout=${this.handleStayOpenOnFocusout}
      @close-on-focusout=${this.handleCloseOnFocusout}
      @slotchange=${this.listController.onSlotchange}></slot>`;
  }
  /**
   * Renders the elevation component.
   */
  renderElevation() {
    return b`<md-elevation part="elevation"></md-elevation>`;
  }
  getSurfaceClasses() {
    return {
      open: this.open,
      fixed: this.positioning === 'fixed',
      'has-overflow': this.hasOverflow
    };
  }
  captureKeydown(event) {
    if (event.target === this && !event.defaultPrevented && isClosableKey(event.code)) {
      event.preventDefault();
      this.close();
    }
    this.typeaheadController.onKeydown(event);
  }
  /**
   * Performs the opening animation:
   *
   * https://direct.googleplex.com/#/spec/295000003+271060003
   *
   * @return A promise that resolve to `true` if the animation was aborted,
   *     `false` if it was not aborted.
   */
  async animateOpen() {
    const surfaceEl = this.surfaceEl;
    const slotEl = this.slotEl;
    if (!surfaceEl || !slotEl) return true;
    const openDirection = this.openDirection;
    this.dispatchEvent(new Event('opening'));
    // needs to be imperative because we don't want to mix animation and Lit
    // render timing
    surfaceEl.classList.toggle('animating', true);
    const signal = this.openCloseAnimationSignal.start();
    const height = surfaceEl.offsetHeight;
    const openingUpwards = openDirection === 'UP';
    const children = this.items;
    const FULL_DURATION = 500;
    const SURFACE_OPACITY_DURATION = 50;
    const ITEM_OPACITY_DURATION = 250;
    // We want to fit every child fade-in animation within the full duration of
    // the animation.
    const DELAY_BETWEEN_ITEMS = (FULL_DURATION - ITEM_OPACITY_DURATION) / children.length;
    const surfaceHeightAnimation = surfaceEl.animate([{
      height: '0px'
    }, {
      height: `${height}px`
    }], {
      duration: FULL_DURATION,
      easing: EASING.EMPHASIZED
    });
    // When we are opening upwards, we want to make sure the last item is always
    // in view, so we need to translate it upwards the opposite direction of the
    // height animation
    const upPositionCorrectionAnimation = slotEl.animate([{
      transform: openingUpwards ? `translateY(-${height}px)` : ''
    }, {
      transform: ''
    }], {
      duration: FULL_DURATION,
      easing: EASING.EMPHASIZED
    });
    const surfaceOpacityAnimation = surfaceEl.animate([{
      opacity: 0
    }, {
      opacity: 1
    }], SURFACE_OPACITY_DURATION);
    const childrenAnimations = [];
    for (let i = 0; i < children.length; i++) {
      // If we are animating upwards, then reverse the children list.
      const directionalIndex = openingUpwards ? children.length - 1 - i : i;
      const child = children[directionalIndex];
      const animation = child.animate([{
        opacity: 0
      }, {
        opacity: 1
      }], {
        duration: ITEM_OPACITY_DURATION,
        delay: DELAY_BETWEEN_ITEMS * i
      });
      // Make them all initially hidden and then clean up at the end of each
      // animation.
      child.classList.toggle('md-menu-hidden', true);
      animation.addEventListener('finish', () => {
        child.classList.toggle('md-menu-hidden', false);
      });
      childrenAnimations.push([child, animation]);
    }
    let resolveAnimation = value => {};
    const animationFinished = new Promise(resolve => {
      resolveAnimation = resolve;
    });
    signal.addEventListener('abort', () => {
      surfaceHeightAnimation.cancel();
      upPositionCorrectionAnimation.cancel();
      surfaceOpacityAnimation.cancel();
      childrenAnimations.forEach(([child, animation]) => {
        child.classList.toggle('md-menu-hidden', false);
        animation.cancel();
      });
      resolveAnimation(true);
    });
    surfaceHeightAnimation.addEventListener('finish', () => {
      surfaceEl.classList.toggle('animating', false);
      this.openCloseAnimationSignal.finish();
      resolveAnimation(false);
    });
    return await animationFinished;
  }
  /**
   * Performs the closing animation:
   *
   * https://direct.googleplex.com/#/spec/295000003+271060003
   */
  animateClose() {
    let resolve;
    // This promise blocks the surface position controller from setting
    // display: none on the surface which will interfere with this animation.
    const animationEnded = new Promise(res => {
      resolve = res;
    });
    const surfaceEl = this.surfaceEl;
    const slotEl = this.slotEl;
    if (!surfaceEl || !slotEl) {
      resolve(false);
      return animationEnded;
    }
    const openDirection = this.openDirection;
    const closingDownwards = openDirection === 'UP';
    this.dispatchEvent(new Event('closing'));
    // needs to be imperative because we don't want to mix animation and Lit
    // render timing
    surfaceEl.classList.toggle('animating', true);
    const signal = this.openCloseAnimationSignal.start();
    const height = surfaceEl.offsetHeight;
    const children = this.items;
    const FULL_DURATION = 150;
    const SURFACE_OPACITY_DURATION = 50;
    // The surface fades away at the very end
    const SURFACE_OPACITY_DELAY = FULL_DURATION - SURFACE_OPACITY_DURATION;
    const ITEM_OPACITY_DURATION = 50;
    const ITEM_OPACITY_INITIAL_DELAY = 50;
    const END_HEIGHT_PERCENTAGE = 0.35;
    // We want to fit every child fade-out animation within the full duration of
    // the animation.
    const DELAY_BETWEEN_ITEMS = (FULL_DURATION - ITEM_OPACITY_INITIAL_DELAY - ITEM_OPACITY_DURATION) / children.length;
    // The mock has the animation shrink to 35%
    const surfaceHeightAnimation = surfaceEl.animate([{
      height: `${height}px`
    }, {
      height: `${height * END_HEIGHT_PERCENTAGE}px`
    }], {
      duration: FULL_DURATION,
      easing: EASING.EMPHASIZED_ACCELERATE
    });
    // When we are closing downwards, we want to make sure the last item is
    // always in view, so we need to translate it upwards the opposite direction
    // of the height animation
    const downPositionCorrectionAnimation = slotEl.animate([{
      transform: ''
    }, {
      transform: closingDownwards ? `translateY(-${height * (1 - END_HEIGHT_PERCENTAGE)}px)` : ''
    }], {
      duration: FULL_DURATION,
      easing: EASING.EMPHASIZED_ACCELERATE
    });
    const surfaceOpacityAnimation = surfaceEl.animate([{
      opacity: 1
    }, {
      opacity: 0
    }], {
      duration: SURFACE_OPACITY_DURATION,
      delay: SURFACE_OPACITY_DELAY
    });
    const childrenAnimations = [];
    for (let i = 0; i < children.length; i++) {
      // If the animation is closing upwards, then reverse the list of
      // children so that we animate in the opposite direction.
      const directionalIndex = closingDownwards ? i : children.length - 1 - i;
      const child = children[directionalIndex];
      const animation = child.animate([{
        opacity: 1
      }, {
        opacity: 0
      }], {
        duration: ITEM_OPACITY_DURATION,
        delay: ITEM_OPACITY_INITIAL_DELAY + DELAY_BETWEEN_ITEMS * i
      });
      // Make sure the items stay hidden at the end of each child animation.
      // We clean this up at the end of the overall animation.
      animation.addEventListener('finish', () => {
        child.classList.toggle('md-menu-hidden', true);
      });
      childrenAnimations.push([child, animation]);
    }
    signal.addEventListener('abort', () => {
      surfaceHeightAnimation.cancel();
      downPositionCorrectionAnimation.cancel();
      surfaceOpacityAnimation.cancel();
      childrenAnimations.forEach(([child, animation]) => {
        animation.cancel();
        child.classList.toggle('md-menu-hidden', false);
      });
      resolve(false);
    });
    surfaceHeightAnimation.addEventListener('finish', () => {
      surfaceEl.classList.toggle('animating', false);
      childrenAnimations.forEach(([child]) => {
        child.classList.toggle('md-menu-hidden', false);
      });
      this.openCloseAnimationSignal.finish();
      this.dispatchEvent(new Event('closed'));
      resolve(true);
    });
    return animationEnded;
  }
  handleKeydown(event) {
    // At any key event, the pointer interaction is done so we need to clear our
    // cached pointerpath. This handles the case where the user clicks on the
    // anchor, and then hits shift+tab
    this.pointerPath = [];
    this.listController.handleKeydown(event);
  }
  setUpGlobalEventListeners() {
    document.addEventListener('click', this.onDocumentClick, {
      capture: true
    });
    window.addEventListener('pointerdown', this.onWindowPointerdown);
    document.addEventListener('resize', this.onWindowResize, {
      passive: true
    });
    window.addEventListener('resize', this.onWindowResize, {
      passive: true
    });
  }
  cleanUpGlobalEventListeners() {
    document.removeEventListener('click', this.onDocumentClick, {
      capture: true
    });
    window.removeEventListener('pointerdown', this.onWindowPointerdown);
    document.removeEventListener('resize', this.onWindowResize);
    window.removeEventListener('resize', this.onWindowResize);
  }
  onCloseMenu() {
    this.close();
  }
  onDeactivateItems(event) {
    event.stopPropagation();
    this.listController.onDeactivateItems();
  }
  onRequestActivation(event) {
    event.stopPropagation();
    this.listController.onRequestActivation(event);
  }
  handleDeactivateTypeahead(event) {
    // stopPropagation so that this does not deactivate any typeaheads in menus
    // nested above it e.g. md-sub-menu
    event.stopPropagation();
    this.typeaheadActive = false;
  }
  handleActivateTypeahead(event) {
    // stopPropagation so that this does not activate any typeaheads in menus
    // nested above it e.g. md-sub-menu
    event.stopPropagation();
    this.typeaheadActive = true;
  }
  handleStayOpenOnFocusout(event) {
    event.stopPropagation();
    this.stayOpenOnFocusout = true;
  }
  handleCloseOnFocusout(event) {
    event.stopPropagation();
    this.stayOpenOnFocusout = false;
  }
  close() {
    this.open = false;
    const maybeSubmenu = this.slotItems;
    maybeSubmenu.forEach(item => {
      item.close?.();
    });
  }
  show() {
    this.open = true;
  }
  /**
   * Activates the next item in the menu. If at the end of the menu, the first
   * item will be activated.
   *
   * @return The activated menu item or `null` if there are no items.
   */
  activateNextItem() {
    return this.listController.activateNextItem() ?? null;
  }
  /**
   * Activates the previous item in the menu. If at the start of the menu, the
   * last item will be activated.
   *
   * @return The activated menu item or `null` if there are no items.
   */
  activatePreviousItem() {
    return this.listController.activatePreviousItem() ?? null;
  }
  /**
   * Repositions the menu if it is open.
   *
   * Useful for the case where document or window-positioned menus have their
   * anchors moved while open.
   */
  reposition() {
    if (this.open) {
      this.menuPositionController.position();
    }
  }
}
__decorate([e$6('.menu')], Menu.prototype, "surfaceEl", void 0);
__decorate([e$6('slot')], Menu.prototype, "slotEl", void 0);
__decorate([n$5()], Menu.prototype, "anchor", void 0);
__decorate([n$5()], Menu.prototype, "positioning", void 0);
__decorate([n$5({
  type: Boolean
})], Menu.prototype, "quick", void 0);
__decorate([n$5({
  type: Boolean,
  attribute: 'has-overflow'
})], Menu.prototype, "hasOverflow", void 0);
__decorate([n$5({
  type: Boolean,
  reflect: true
})], Menu.prototype, "open", void 0);
__decorate([n$5({
  type: Number,
  attribute: 'x-offset'
})], Menu.prototype, "xOffset", void 0);
__decorate([n$5({
  type: Number,
  attribute: 'y-offset'
})], Menu.prototype, "yOffset", void 0);
__decorate([n$5({
  type: Boolean,
  attribute: 'no-horizontal-flip'
})], Menu.prototype, "noHorizontalFlip", void 0);
__decorate([n$5({
  type: Boolean,
  attribute: 'no-vertical-flip'
})], Menu.prototype, "noVerticalFlip", void 0);
__decorate([n$5({
  type: Number,
  attribute: 'typeahead-delay'
})], Menu.prototype, "typeaheadDelay", void 0);
__decorate([n$5({
  attribute: 'anchor-corner'
})], Menu.prototype, "anchorCorner", void 0);
__decorate([n$5({
  attribute: 'menu-corner'
})], Menu.prototype, "menuCorner", void 0);
__decorate([n$5({
  type: Boolean,
  attribute: 'stay-open-on-outside-click'
})], Menu.prototype, "stayOpenOnOutsideClick", void 0);
__decorate([n$5({
  type: Boolean,
  attribute: 'stay-open-on-focusout'
})], Menu.prototype, "stayOpenOnFocusout", void 0);
__decorate([n$5({
  type: Boolean,
  attribute: 'skip-restore-focus'
})], Menu.prototype, "skipRestoreFocus", void 0);
__decorate([n$5({
  attribute: 'default-focus'
})], Menu.prototype, "defaultFocus", void 0);
__decorate([n$5({
  type: Boolean,
  attribute: 'no-navigation-wrap'
})], Menu.prototype, "noNavigationWrap", void 0);
__decorate([o$5({
  flatten: true
})], Menu.prototype, "slotItems", void 0);
__decorate([r$3()], Menu.prototype, "typeaheadActive", void 0);

/**
 * @license
 * Copyright 2024 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Generated stylesheet for ./menu/internal/menu-styles.css.
const styles$8 = i$7`:host{--md-elevation-level: var(--md-menu-container-elevation, 2);--md-elevation-shadow-color: var(--md-menu-container-shadow-color, var(--md-sys-color-shadow, #000));min-width:112px;color:unset;display:contents}md-focus-ring{--md-focus-ring-shape: var(--md-menu-container-shape, var(--md-sys-shape-corner-extra-small, 4px))}.menu{border-radius:var(--md-menu-container-shape, var(--md-sys-shape-corner-extra-small, 4px));display:none;inset:auto;border:none;padding:0px;overflow:visible;background-color:rgba(0,0,0,0);color:inherit;opacity:0;z-index:20;position:absolute;user-select:none;max-height:inherit;height:inherit;min-width:inherit;max-width:inherit;scrollbar-width:inherit}.menu::backdrop{display:none}.fixed{position:fixed}.items{display:block;list-style-type:none;margin:0;outline:none;box-sizing:border-box;background-color:var(--md-menu-container-color, var(--md-sys-color-surface-container, #f3edf7));height:inherit;max-height:inherit;overflow:auto;min-width:inherit;max-width:inherit;border-radius:inherit;scrollbar-width:inherit}.item-padding{padding-block:var(--md-menu-top-space, 8px) var(--md-menu-bottom-space, 8px)}.has-overflow:not([popover]) .items{overflow:visible}.has-overflow.animating .items,.animating .items{overflow:hidden}.has-overflow.animating .items{pointer-events:none}.animating ::slotted(.md-menu-hidden){opacity:0}slot{display:block;height:inherit;max-height:inherit}::slotted(:is(md-divider,[role=separator])){margin:8px 0}@media(forced-colors: active){.menu{border-style:solid;border-color:CanvasText;border-width:1px}}
`;

/**
 * @license
 * Copyright 2022 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @summary Menus display a list of choices on a temporary surface.
 *
 * @description
 * Menus appear when users interact with a button, action, or other control.
 *
 * They can be opened from a variety of elements, most commonly icon buttons,
 * buttons, and text fields.
 *
 * md-menu listens for the `close-menu` and `deselect-items` events.
 *
 * - `close-menu` closes the menu when dispatched from a child element.
 * - `deselect-items` deselects all of its immediate menu-item children.
 *
 * @example
 * ```html
 * <div style="position:relative;">
 *   <button
 *       id="anchor"
 *       @click=${() => this.menuRef.value.show()}>
 *     Click to open menu
 *   </button>
 *   <!--
 *     `has-overflow` is required when using a submenu which overflows the
 *     menu's contents.
 *
 *     Additionally, `anchor` ingests an idref which do not pass through shadow
 *     roots. You can also set `.anchorElement` to an element reference if
 *     necessary.
 *   -->
 *   <md-menu anchor="anchor" has-overflow ${ref(menuRef)}>
 *     <md-menu-item headline="This is a headline"></md-menu-item>
 *     <md-sub-menu>
 *       <md-menu-item
 *           slot="item"
 *           headline="this is a submenu item">
 *       </md-menu-item>
 *       <md-menu slot="menu">
 *         <md-menu-item headline="This is an item inside a submenu">
 *         </md-menu-item>
 *       </md-menu>
 *     </md-sub-menu>
 *   </md-menu>
 * </div>
 * ```
 *
 * @final
 * @suppress {visibility}
 */
let MdMenu = class MdMenu extends Menu {};
MdMenu.styles = [styles$8];
MdMenu = __decorate([t$1('md-menu')], MdMenu);

/**
 * @license
 * Copyright 2021 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * Re-dispatches an event from the provided element.
 *
 * This function is useful for forwarding non-composed events, such as `change`
 * events.
 *
 * @example
 * class MyInput extends LitElement {
 *   render() {
 *     return html`<input @change=${this.redispatchEvent}>`;
 *   }
 *
 *   protected redispatchEvent(event: Event) {
 *     redispatchEvent(this, event);
 *   }
 * }
 *
 * @param element The element to dispatch the event from.
 * @param event The event to re-dispatch.
 * @return Whether or not the event was dispatched (if cancelable).
 */
function redispatchEvent(element, event) {
  // For bubbling events in SSR light DOM (or composed), stop their propagation
  // and dispatch the copy.
  if (event.bubbles && (!element.shadowRoot || event.composed)) {
    event.stopPropagation();
  }
  const copy = Reflect.construct(event.constructor, [event.type, event]);
  const dispatched = element.dispatchEvent(copy);
  if (!dispatched) {
    event.preventDefault();
  }
  return dispatched;
}

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * A symbol property used to create a constraint validation `Validator`.
 * Required for all `mixinConstraintValidation()` elements.
 */
const createValidator = Symbol('createValidator');
/**
 * A symbol property used to return an anchor for constraint validation popups.
 * Required for all `mixinConstraintValidation()` elements.
 */
const getValidityAnchor = Symbol('getValidityAnchor');
// Private symbol members, used to avoid name clashing.
const privateValidator = Symbol('privateValidator');
const privateSyncValidity = Symbol('privateSyncValidity');
const privateCustomValidationMessage = Symbol('privateCustomValidationMessage');
/**
 * Mixes in constraint validation APIs for an element.
 *
 * See https://developer.mozilla.org/en-US/docs/Web/HTML/Constraint_validation
 * for more details.
 *
 * Implementations must provide a validator to cache and compute its validity,
 * along with a shadow root element to anchor validation popups to.
 *
 * @example
 * ```ts
 * const baseClass = mixinConstraintValidation(
 *   mixinFormAssociated(mixinElementInternals(LitElement))
 * );
 *
 * class MyCheckbox extends baseClass {
 *   \@property({type: Boolean}) checked = false;
 *   \@property({type: Boolean}) required = false;
 *
 *   [createValidator]() {
 *     return new CheckboxValidator(() => this);
 *   }
 *
 *   [getValidityAnchor]() {
 *     return this.renderRoot.querySelector('.root');
 *   }
 * }
 * ```
 *
 * @param base The class to mix functionality into.
 * @return The provided class with `ConstraintValidation` mixed in.
 */
function mixinConstraintValidation(base) {
  var _a;
  class ConstraintValidationElement extends base {
    constructor() {
      super(...arguments);
      /**
       * Needed for Safari, see https://bugs.webkit.org/show_bug.cgi?id=261432
       * Replace with this[internals].validity.customError when resolved.
       */
      this[_a] = '';
    }
    get validity() {
      this[privateSyncValidity]();
      return this[internals].validity;
    }
    get validationMessage() {
      this[privateSyncValidity]();
      return this[internals].validationMessage;
    }
    get willValidate() {
      this[privateSyncValidity]();
      return this[internals].willValidate;
    }
    checkValidity() {
      this[privateSyncValidity]();
      return this[internals].checkValidity();
    }
    reportValidity() {
      this[privateSyncValidity]();
      return this[internals].reportValidity();
    }
    setCustomValidity(error) {
      this[privateCustomValidationMessage] = error;
      this[privateSyncValidity]();
    }
    requestUpdate(name, oldValue, options) {
      super.requestUpdate(name, oldValue, options);
      this[privateSyncValidity]();
    }
    firstUpdated(changed) {
      super.firstUpdated(changed);
      // Sync the validity again when the element first renders, since the
      // validity anchor is now available.
      //
      // Elements that `delegatesFocus: true` to an `<input>` will throw an
      // error in Chrome and Safari when a form tries to submit or call
      // `form.reportValidity()`:
      // "An invalid form control with name='' is not focusable"
      //
      // The validity anchor MUST be provided in `internals.setValidity()` and
      // MUST be the `<input>` element rendered.
      //
      // See https://lit.dev/playground/#gist=6c26e418e0010f7a5aac15005cde8bde
      // for a reproduction.
      this[privateSyncValidity]();
    }
    [(_a = privateCustomValidationMessage, privateSyncValidity)]() {
      if (!this[privateValidator]) {
        this[privateValidator] = this[createValidator]();
      }
      const {
        validity,
        validationMessage: nonCustomValidationMessage
      } = this[privateValidator].getValidity();
      const customError = !!this[privateCustomValidationMessage];
      const validationMessage = this[privateCustomValidationMessage] || nonCustomValidationMessage;
      this[internals].setValidity({
        ...validity,
        customError
      }, validationMessage, this[getValidityAnchor]() ?? undefined);
    }
    [createValidator]() {
      throw new Error('Implement [createValidator]');
    }
    [getValidityAnchor]() {
      throw new Error('Implement [getValidityAnchor]');
    }
  }
  return ConstraintValidationElement;
}

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * A symbol property to retrieve the form value for an element.
 */
const getFormValue = Symbol('getFormValue');
/**
 * A symbol property to retrieve the form state for an element.
 */
const getFormState = Symbol('getFormState');
/**
 * Mixes in form-associated behavior for a class. This allows an element to add
 * values to `<form>` elements.
 *
 * Implementing classes should provide a `[formValue]` to return the current
 * value of the element, as well as reset and restore callbacks.
 *
 * @example
 * ```ts
 * const base = mixinFormAssociated(mixinElementInternals(LitElement));
 *
 * class MyControl extends base {
 *   \@property()
 *   value = '';
 *
 *   override [getFormValue]() {
 *     return this.value;
 *   }
 *
 *   override formResetCallback() {
 *     const defaultValue = this.getAttribute('value');
 *     this.value = defaultValue;
 *   }
 *
 *   override formStateRestoreCallback(state: string) {
 *     this.value = state;
 *   }
 * }
 * ```
 *
 * Elements may optionally provide a `[formState]` if their values do not
 * represent the state of the component.
 *
 * @example
 * ```ts
 * const base = mixinFormAssociated(mixinElementInternals(LitElement));
 *
 * class MyCheckbox extends base {
 *   \@property()
 *   value = 'on';
 *
 *   \@property({type: Boolean})
 *   checked = false;
 *
 *   override [getFormValue]() {
 *     return this.checked ? this.value : null;
 *   }
 *
 *   override [getFormState]() {
 *     return String(this.checked);
 *   }
 *
 *   override formResetCallback() {
 *     const defaultValue = this.hasAttribute('checked');
 *     this.checked = defaultValue;
 *   }
 *
 *   override formStateRestoreCallback(state: string) {
 *     this.checked = Boolean(state);
 *   }
 * }
 * ```
 *
 * IMPORTANT: Requires declares for lit-analyzer
 * @example
 * ```ts
 * const base = mixinFormAssociated(mixinElementInternals(LitElement));
 * class MyControl extends base {
 *   // Writable mixin properties for lit-html binding, needed for lit-analyzer
 *   declare disabled: boolean;
 *   declare name: string;
 * }
 * ```
 *
 * @param base The class to mix functionality into. The base class must use
 *     `mixinElementInternals()`.
 * @return The provided class with `FormAssociated` mixed in.
 */
function mixinFormAssociated(base) {
  class FormAssociatedElement extends base {
    get form() {
      return this[internals].form;
    }
    get labels() {
      return this[internals].labels;
    }
    // Use @property for the `name` and `disabled` properties to add them to the
    // `observedAttributes` array and trigger `attributeChangedCallback()`.
    //
    // We don't use Lit's default getter/setter (`noAccessor: true`) because
    // the attributes need to be updated synchronously to work with synchronous
    // form APIs, and Lit updates attributes async by default.
    get name() {
      return this.getAttribute('name') ?? '';
    }
    set name(name) {
      // Note: setting name to null or empty does not remove the attribute.
      this.setAttribute('name', name);
      // We don't need to call `requestUpdate()` since it's called synchronously
      // in `attributeChangedCallback()`.
    }
    get disabled() {
      return this.hasAttribute('disabled');
    }
    set disabled(disabled) {
      this.toggleAttribute('disabled', disabled);
      // We don't need to call `requestUpdate()` since it's called synchronously
      // in `attributeChangedCallback()`.
    }
    attributeChangedCallback(name, old, value) {
      // Manually `requestUpdate()` for `name` and `disabled` when their
      // attribute or property changes.
      // The properties update their attributes, so this callback is invoked
      // immediately when the properties are set. We call `requestUpdate()` here
      // instead of letting Lit set the properties from the attribute change.
      // That would cause the properties to re-set the attribute and invoke this
      // callback again in a loop. This leads to stale state when Lit tries to
      // determine if a property changed or not.
      if (name === 'name' || name === 'disabled') {
        // Disabled's value is only false if the attribute is missing and null.
        const oldValue = name === 'disabled' ? old !== null : old;
        // Trigger a lit update when the attribute changes.
        this.requestUpdate(name, oldValue);
        return;
      }
      super.attributeChangedCallback(name, old, value);
    }
    requestUpdate(name, oldValue, options) {
      super.requestUpdate(name, oldValue, options);
      // If any properties change, update the form value, which may have changed
      // as well.
      // Update the form value synchronously in `requestUpdate()` rather than
      // `update()` or `updated()`, which are async. This is necessary to ensure
      // that form data is updated in time for synchronous event listeners.
      this[internals].setFormValue(this[getFormValue](), this[getFormState]());
    }
    [getFormValue]() {
      // Closure does not allow abstract symbol members, so a default
      // implementation is needed.
      throw new Error('Implement [getFormValue]');
    }
    [getFormState]() {
      return this[getFormValue]();
    }
    formDisabledCallback(disabled) {
      this.disabled = disabled;
    }
  }
  /** @nocollapse */
  FormAssociatedElement.formAssociated = true;
  __decorate([n$5({
    noAccessor: true
  })], FormAssociatedElement.prototype, "name", null);
  __decorate([n$5({
    type: Boolean,
    noAccessor: true
  })], FormAssociatedElement.prototype, "disabled", null);
  return FormAssociatedElement;
}

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * A symbol property used for a callback when validity has been reported.
 */
const onReportValidity = Symbol('onReportValidity');
// Private symbol members, used to avoid name clashing.
const privateCleanupFormListeners = Symbol('privateCleanupFormListeners');
const privateDoNotReportInvalid = Symbol('privateDoNotReportInvalid');
const privateIsSelfReportingValidity = Symbol('privateIsSelfReportingValidity');
const privateCallOnReportValidity = Symbol('privateCallOnReportValidity');
/**
 * Mixes in a callback for constraint validation when validity should be
 * styled and reported to the user.
 *
 * This is commonly used in text-field-like controls that display error styles
 * and error messages.
 *
 * @example
 * ```ts
 * const baseClass = mixinOnReportValidity(
 *   mixinConstraintValidation(
 *     mixinFormAssociated(mixinElementInternals(LitElement)),
 *   ),
 * );
 *
 * class MyField extends baseClass {
 *   \@property({type: Boolean}) error = false;
 *   \@property() errorMessage = '';
 *
 *   [onReportValidity](invalidEvent: Event | null) {
 *     this.error = !!invalidEvent;
 *     this.errorMessage = this.validationMessage;
 *
 *     // Optionally prevent platform popup from displaying
 *     invalidEvent?.preventDefault();
 *   }
 * }
 * ```
 *
 * @param base The class to mix functionality into.
 * @return The provided class with `OnReportValidity` mixed in.
 */
function mixinOnReportValidity(base) {
  var _a, _b, _c;
  class OnReportValidityElement extends base {
    // Mixins must have a constructor with `...args: any[]`
    // tslint:disable-next-line:no-any
    constructor(...args) {
      super(...args);
      /**
       * Used to clean up event listeners when a new form is associated.
       */
      this[_a] = new AbortController();
      /**
       * Used to determine if an invalid event should report validity. Invalid
       * events from `checkValidity()` do not trigger reporting.
       */
      this[_b] = false;
      /**
       * Used to determine if the control is reporting validity from itself, or
       * if a `<form>` is causing the validity report. Forms have different
       * control focusing behavior.
       */
      this[_c] = false;
      this.addEventListener('invalid', invalidEvent => {
        // Listen for invalid events dispatched by a `<form>` when it tries to
        // submit and the element is invalid. We ignore events dispatched when
        // calling `checkValidity()` as well as untrusted events, since the
        // `reportValidity()` and `<form>`-dispatched events are always
        // trusted.
        if (this[privateDoNotReportInvalid] || !invalidEvent.isTrusted) {
          return;
        }
        this.addEventListener('invalid', () => {
          // A normal bubbling phase event listener. By adding it here, we
          // ensure it's the last event listener that is called during the
          // bubbling phase.
          this[privateCallOnReportValidity](invalidEvent);
        }, {
          once: true
        });
      }, {
        // Listen during the capture phase, which will happen before the
        // bubbling phase. That way, we can add a final event listener that
        // will run after other event listeners, and we can check if it was
        // default prevented. This works because invalid does not bubble.
        capture: true
      });
    }
    checkValidity() {
      this[privateDoNotReportInvalid] = true;
      const valid = super.checkValidity();
      this[privateDoNotReportInvalid] = false;
      return valid;
    }
    reportValidity() {
      this[privateIsSelfReportingValidity] = true;
      const valid = super.reportValidity();
      // Constructor's invalid listener will handle reporting invalid events.
      if (valid) {
        this[privateCallOnReportValidity](null);
      }
      this[privateIsSelfReportingValidity] = false;
      return valid;
    }
    [(_a = privateCleanupFormListeners, _b = privateDoNotReportInvalid, _c = privateIsSelfReportingValidity, privateCallOnReportValidity)](invalidEvent) {
      // Since invalid events do not bubble to parent listeners, and because
      // our invalid listeners are added lazily after other listeners, we can
      // reliably read `defaultPrevented` synchronously without worrying
      // about waiting for another listener that could cancel it.
      const wasCanceled = invalidEvent?.defaultPrevented;
      if (wasCanceled) {
        return;
      }
      this[onReportValidity](invalidEvent);
      // If an implementation calls invalidEvent.preventDefault() to stop the
      // platform popup from displaying, focusing is also prevented, so we need
      // to manually focus.
      const implementationCanceledFocus = !wasCanceled && invalidEvent?.defaultPrevented;
      if (!implementationCanceledFocus) {
        return;
      }
      // The control should be focused when:
      // - `control.reportValidity()` is called (self-reporting).
      // - a form is reporting validity for its controls and this is the first
      //   invalid control.
      if (this[privateIsSelfReportingValidity] || isFirstInvalidControlInForm(this[internals].form, this)) {
        this.focus();
      }
    }
    [onReportValidity](invalidEvent) {
      throw new Error('Implement [onReportValidity]');
    }
    formAssociatedCallback(form) {
      // can't use super.formAssociatedCallback?.() due to closure
      if (super.formAssociatedCallback) {
        super.formAssociatedCallback(form);
      }
      // Clean up previous form listeners.
      this[privateCleanupFormListeners].abort();
      if (!form) {
        return;
      }
      this[privateCleanupFormListeners] = new AbortController();
      // Add a listener that fires when the form runs constraint validation and
      // the control is valid, so that it may remove its error styles.
      //
      // This happens on `form.reportValidity()` and `form.requestSubmit()`
      // (both when the submit fails and passes).
      addFormReportValidListener(this, form, () => {
        this[privateCallOnReportValidity](null);
      }, this[privateCleanupFormListeners].signal);
    }
  }
  return OnReportValidityElement;
}
/**
 * Add a listener that fires when a form runs constraint validation on a control
 * and it is valid. This is needed to clear previously invalid styles.
 *
 * @param control The control of the form to listen for valid events.
 * @param form The control's form that can run constraint validation.
 * @param onControlValid A listener that is called when the form runs constraint
 *     validation and the control is valid.
 * @param cleanup A cleanup signal to remove the listener.
 */
function addFormReportValidListener(control, form, onControlValid, cleanup) {
  const validateHooks = getFormValidateHooks(form);
  // When a form validates its controls, check if an invalid event is dispatched
  // on the control. If it is not, then inform the control to report its valid
  // state.
  let controlFiredInvalid = false;
  let cleanupInvalidListener;
  let isNextSubmitFromHook = false;
  validateHooks.addEventListener('before', () => {
    isNextSubmitFromHook = true;
    cleanupInvalidListener = new AbortController();
    controlFiredInvalid = false;
    control.addEventListener('invalid', () => {
      controlFiredInvalid = true;
    }, {
      signal: cleanupInvalidListener.signal
    });
  }, {
    signal: cleanup
  });
  validateHooks.addEventListener('after', () => {
    isNextSubmitFromHook = false;
    cleanupInvalidListener?.abort();
    if (controlFiredInvalid) {
      return;
    }
    onControlValid();
  }, {
    signal: cleanup
  });
  // The above hooks handle imperatively submitting the form, but not
  // declaratively submitting the form. This happens when:
  // 1. A non-custom element `<button type="submit">` is clicked.
  // 2. Enter is pressed on a non-custom element text editable `<input>`.
  form.addEventListener('submit', () => {
    // This submit was from `form.requestSubmit()`, which already calls the
    // listener.
    if (isNextSubmitFromHook) {
      return;
    }
    onControlValid();
  }, {
    signal: cleanup
  });
  // Note: it is a known limitation that we cannot detect if a form tries to
  // submit declaratively, but fails to do so because an unrelated sibling
  // control failed its constraint validation.
  //
  // Since we cannot detect when that happens, a previously invalid control may
  // not clear its error styling when it becomes valid again.
  //
  // To work around this, call `form.reportValidity()` when submitting a form
  // declaratively. This can be down on the `<button type="submit">`'s click or
  // the text editable `<input>`'s 'Enter' keydown.
}
const FORM_VALIDATE_HOOKS = new WeakMap();
/**
 * Get a hooks `EventTarget` that dispatches 'before' and 'after' events that
 * fire before a form runs constraint validation and immediately after it
 * finishes running constraint validation on its controls.
 *
 * This happens during `form.reportValidity()` and `form.requestSubmit()`.
 *
 * @param form The form to get or set up hooks for.
 * @return A hooks `EventTarget` to add listeners to.
 */
function getFormValidateHooks(form) {
  if (!FORM_VALIDATE_HOOKS.has(form)) {
    // Patch form methods to add event listener hooks. These are needed to react
    // to form behaviors that do not dispatch events, such as a form asking its
    // controls to report their validity.
    //
    // We should only patch the methods once, since multiple controls and other
    // forces may want to patch this method. We cannot reliably clean it up if
    // there are multiple patched and re-patched methods referring holding
    // references to each other.
    //
    // Instead, we never clean up the patch but add and clean up event listeners
    // added to the hooks after the patch.
    const hooks = new EventTarget();
    FORM_VALIDATE_HOOKS.set(form, hooks);
    // Add hooks to support notifying before and after a form has run constraint
    // validation on its controls.
    // Note: `form.submit()` does not run constraint validation per spec.
    for (const methodName of ['reportValidity', 'requestSubmit']) {
      const superMethod = form[methodName];
      form[methodName] = function () {
        hooks.dispatchEvent(new Event('before'));
        const result = Reflect.apply(superMethod, this, arguments);
        hooks.dispatchEvent(new Event('after'));
        return result;
      };
    }
  }
  return FORM_VALIDATE_HOOKS.get(form);
}
/**
 * Checks if a control is the first invalid control in a form.
 *
 * @param form The control's form. When `null`, the control doesn't have a form
 *     and the method returns true.
 * @param control The control to check.
 * @return True if there is no form or if the control is the form's first
 *     invalid control.
 */
function isFirstInvalidControlInForm(form, control) {
  if (!form) {
    return true;
  }
  let firstInvalidControl;
  for (const element of form.elements) {
    if (element.matches(':invalid')) {
      firstInvalidControl = element;
      break;
    }
  }
  return firstInvalidControl === control;
}

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * A class that computes and caches `ValidityStateFlags` for a component with
 * a given `State` interface.
 *
 * Cached performance before computing validity is important since constraint
 * validation must be checked frequently and synchronously when properties
 * change.
 *
 * @template State The expected interface of properties relevant to constraint
 *     validation.
 */
let Validator$2 = class Validator {
  /**
   * Creates a new validator.
   *
   * @param getCurrentState A callback that returns the current state of
   *     constraint validation-related properties.
   */
  constructor(getCurrentState) {
    this.getCurrentState = getCurrentState;
    /**
     * The current validity state and message. This is cached and returns if
     * constraint validation state does not change.
     */
    this.currentValidity = {
      validity: {},
      validationMessage: ''
    };
  }
  /**
   * Returns the current `ValidityStateFlags` and validation message for the
   * validator.
   *
   * If the constraint validation state has not changed, this will return a
   * cached result. This is important since `getValidity()` can be called
   * frequently in response to synchronous property changes.
   *
   * @return The current validity and validation message.
   */
  getValidity() {
    const state = this.getCurrentState();
    const hasStateChanged = !this.prevState || !this.equals(this.prevState, state);
    if (!hasStateChanged) {
      return this.currentValidity;
    }
    const {
      validity,
      validationMessage
    } = this.computeValidity(state);
    this.prevState = this.copy(state);
    this.currentValidity = {
      validationMessage,
      validity: {
        // Change any `ValidityState` instances into `ValidityStateFlags` since
        // `ValidityState` cannot be easily `{...spread}`.
        badInput: validity.badInput,
        customError: validity.customError,
        patternMismatch: validity.patternMismatch,
        rangeOverflow: validity.rangeOverflow,
        rangeUnderflow: validity.rangeUnderflow,
        stepMismatch: validity.stepMismatch,
        tooLong: validity.tooLong,
        tooShort: validity.tooShort,
        typeMismatch: validity.typeMismatch,
        valueMissing: validity.valueMissing
      }
    };
    return this.currentValidity;
  }
};

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * A validator that provides constraint validation that emulates `<select>`
 * validation.
 */
class SelectValidator extends Validator$2 {
  computeValidity(state) {
    if (!this.selectControl) {
      // Lazily create the platform select
      this.selectControl = document.createElement('select');
    }
    D(b`<option value=${state.value}></option>`, this.selectControl);
    this.selectControl.value = state.value;
    this.selectControl.required = state.required;
    return {
      validity: this.selectControl.validity,
      validationMessage: this.selectControl.validationMessage
    };
  }
  equals(prev, next) {
    return prev.value === next.value && prev.required === next.required;
  }
  copy({
    value,
    required
  }) {
    return {
      value,
      required
    };
  }
}

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * Given a list of select options, this function will return an array of
 * SelectOptionRecords that are selected.
 *
 * @return An array of SelectOptionRecords describing the options that are
 * selected.
 */
function getSelectedItems(items) {
  const selectedItemRecords = [];
  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    if (item.selected) {
      selectedItemRecords.push([item, i]);
    }
  }
  return selectedItemRecords;
}

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
var _a;
const VALUE = Symbol('value');
// Separate variable needed for closure.
const selectBaseClass = mixinDelegatesAria(mixinOnReportValidity(mixinConstraintValidation(mixinFormAssociated(mixinElementInternals(i$4)))));
/**
 * @fires change {Event} The native `change` event on
 * [`<input>`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event)
 * --bubbles
 * @fires input {InputEvent} The native `input` event on
 * [`<input>`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event)
 * --bubbles --composed
 * @fires opening {Event} Fired when the select's menu is about to open.
 * @fires opened {Event} Fired when the select's menu has finished animations
 * and opened.
 * @fires closing {Event} Fired when the select's menu is about to close.
 * @fires closed {Event} Fired when the select's menu has finished animations
 * and closed.
 */
class Select extends selectBaseClass {
  /**
   * The value of the currently selected option.
   *
   * Note: For SSR, set `[selected]` on the requested option and `displayText`
   * rather than setting `value` setting `value` will incur a DOM query.
   */
  get value() {
    return this[VALUE];
  }
  set value(value) {
    this.lastUserSetValue = value;
    this.select(value);
  }
  get options() {
    // NOTE: this does a DOM query.
    return this.menu?.items ?? [];
  }
  /**
   * The index of the currently selected option.
   *
   * Note: For SSR, set `[selected]` on the requested option and `displayText`
   * rather than setting `selectedIndex` setting `selectedIndex` will incur a
   * DOM query.
   */
  get selectedIndex() {
    // tslint:disable-next-line:enforce-name-casing
    const [_option, index] = (this.getSelectedOptions() ?? [])[0] ?? [];
    return index ?? -1;
  }
  set selectedIndex(index) {
    this.lastUserSetSelectedIndex = index;
    this.selectIndex(index);
  }
  /**
   * Returns an array of selected options.
   *
   * NOTE: md-select only supports single selection.
   */
  get selectedOptions() {
    return (this.getSelectedOptions() ?? []).map(([option]) => option);
  }
  get hasError() {
    return this.error || this.nativeError;
  }
  constructor() {
    super();
    /**
     * Opens the menu synchronously with no animation.
     */
    this.quick = false;
    /**
     * Whether or not the select is required.
     */
    this.required = false;
    /**
     * The error message that replaces supporting text when `error` is true. If
     * `errorText` is an empty string, then the supporting text will continue to
     * show.
     *
     * This error message overrides the error message displayed by
     * `reportValidity()`.
     */
    this.errorText = '';
    /**
     * The floating label for the field.
     */
    this.label = '';
    /**
     * Disables the asterisk on the floating label, when the select is
     * required.
     */
    this.noAsterisk = false;
    /**
     * Conveys additional information below the select, such as how it should
     * be used.
     */
    this.supportingText = '';
    /**
     * Gets or sets whether or not the select is in a visually invalid state.
     *
     * This error state overrides the error state controlled by
     * `reportValidity()`.
     */
    this.error = false;
    /**
     * Whether or not the underlying md-menu should be position: fixed to display
     * in a top-level manner, or position: absolute.
     *
     * position:fixed is useful for cases where select is inside of another
     * element with stacking context and hidden overflows such as `md-dialog`.
     */
    this.menuPositioning = 'popover';
    /**
     * Clamps the menu-width to the width of the select.
     */
    this.clampMenuWidth = false;
    /**
     * The max time between the keystrokes of the typeahead select / menu behavior
     * before it clears the typeahead buffer.
     */
    this.typeaheadDelay = DEFAULT_TYPEAHEAD_BUFFER_TIME;
    /**
     * Whether or not the text field has a leading icon. Used for SSR.
     */
    this.hasLeadingIcon = false;
    /**
     * Text to display in the field. Only set for SSR.
     */
    this.displayText = '';
    /**
     * Whether the menu should be aligned to the start or the end of the select's
     * textbox.
     */
    this.menuAlign = 'start';
    this[_a] = '';
    /**
     * Used for initializing select when the user sets the `value` directly.
     */
    this.lastUserSetValue = null;
    /**
     * Used for initializing select when the user sets the `selectedIndex`
     * directly.
     */
    this.lastUserSetSelectedIndex = null;
    /**
     * Used for `input` and `change` event change detection.
     */
    this.lastSelectedOption = null;
    // tslint:disable-next-line:enforce-name-casing
    this.lastSelectedOptionRecords = [];
    /**
     * Whether or not a native error has been reported via `reportValidity()`.
     */
    this.nativeError = false;
    /**
     * The validation message displayed from a native error via
     * `reportValidity()`.
     */
    this.nativeErrorText = '';
    this.focused = false;
    this.open = false;
    this.defaultFocus = FocusState.NONE;
    // Have to keep track of previous open because it's state and private and thus
    // cannot be tracked in PropertyValues<this> map.
    this.prevOpen = this.open;
    this.selectWidth = 0;
    this.addEventListener('focus', this.handleFocus.bind(this));
    this.addEventListener('blur', this.handleBlur.bind(this));
  }
  /**
   * Selects an option given the value of the option, and updates MdSelect's
   * value.
   */
  select(value) {
    const optionToSelect = this.options.find(option => option.value === value);
    if (optionToSelect) {
      this.selectItem(optionToSelect);
    }
  }
  /**
   * Selects an option given the index of the option, and updates MdSelect's
   * value.
   */
  selectIndex(index) {
    const optionToSelect = this.options[index];
    if (optionToSelect) {
      this.selectItem(optionToSelect);
    }
  }
  /**
   * Reset the select to its default value.
   */
  reset() {
    for (const option of this.options) {
      option.selected = option.hasAttribute('selected');
    }
    this.updateValueAndDisplayText();
    this.nativeError = false;
    this.nativeErrorText = '';
  }
  /** Shows the picker. If it's already open, this is a no-op. */
  showPicker() {
    this.open = true;
  }
  [(_a = VALUE, onReportValidity)](invalidEvent) {
    // Prevent default pop-up behavior.
    invalidEvent?.preventDefault();
    const prevMessage = this.getErrorText();
    this.nativeError = !!invalidEvent;
    this.nativeErrorText = this.validationMessage;
    if (prevMessage === this.getErrorText()) {
      this.field?.reannounceError();
    }
  }
  update(changed) {
    // In SSR the options will be ready to query, so try to figure out what
    // the value and display text should be.
    if (!this.hasUpdated) {
      this.initUserSelection();
    }
    // We have just opened the menu.
    // We are only able to check for the select's rect in `update()` instead of
    // having to wait for `updated()` because the menu can never be open on
    // first render since it is not settable and Lit SSR does not support click
    // events which would open the menu.
    if (this.prevOpen !== this.open && this.open) {
      const selectRect = this.getBoundingClientRect();
      this.selectWidth = selectRect.width;
    }
    this.prevOpen = this.open;
    super.update(changed);
  }
  render() {
    return b`
      <span
        class="select ${e$3(this.getRenderClasses())}"
        @focusout=${this.handleFocusout}>
        ${this.renderField()} ${this.renderMenu()}
      </span>
    `;
  }
  async firstUpdated(changed) {
    await this.menu?.updateComplete;
    // If this has been handled on update already due to SSR, try again.
    if (!this.lastSelectedOptionRecords.length) {
      this.initUserSelection();
    }
    // Case for when the DOM is streaming, there are no children, and a child
    // has [selected] set on it, we need to wait for DOM to render something.
    if (!this.lastSelectedOptionRecords.length && true && !this.options.length) {
      setTimeout(() => {
        this.updateValueAndDisplayText();
      });
    }
    super.firstUpdated(changed);
  }
  getRenderClasses() {
    return {
      'disabled': this.disabled,
      'error': this.error,
      'open': this.open
    };
  }
  renderField() {
    const ariaLabel = this.ariaLabel || this.label;
    return u`
      <${this.fieldTag}
          aria-haspopup="listbox"
          role="combobox"
          part="field"
          id="field"
          tabindex=${this.disabled ? '-1' : '0'}
          aria-label=${ariaLabel || A}
          aria-describedby="description"
          aria-expanded=${this.open ? 'true' : 'false'}
          aria-controls="listbox"
          class="field"
          label=${this.label}
          ?no-asterisk=${this.noAsterisk}
          .focused=${this.focused || this.open}
          .populated=${!!this.displayText}
          .disabled=${this.disabled}
          .required=${this.required}
          .error=${this.hasError}
          ?has-start=${this.hasLeadingIcon}
          has-end
          supporting-text=${this.supportingText}
          error-text=${this.getErrorText()}
          @keydown=${this.handleKeydown}
          @click=${this.handleClick}>
         ${this.renderFieldContent()}
         <div id="description" slot="aria-describedby"></div>
      </${this.fieldTag}>`;
  }
  renderFieldContent() {
    return [this.renderLeadingIcon(), this.renderLabel(), this.renderTrailingIcon()];
  }
  renderLeadingIcon() {
    return b`
      <span class="icon leading" slot="start">
        <slot name="leading-icon" @slotchange=${this.handleIconChange}></slot>
      </span>
    `;
  }
  renderTrailingIcon() {
    return b`
      <span class="icon trailing" slot="end">
        <slot name="trailing-icon" @slotchange=${this.handleIconChange}>
          <svg height="5" viewBox="7 10 10 5" focusable="false">
            <polygon
              class="down"
              stroke="none"
              fill-rule="evenodd"
              points="7 10 12 15 17 10"></polygon>
            <polygon
              class="up"
              stroke="none"
              fill-rule="evenodd"
              points="7 15 12 10 17 15"></polygon>
          </svg>
        </slot>
      </span>
    `;
  }
  renderLabel() {
    // need to render &nbsp; so that line-height can apply and give it a
    // non-zero height
    return b`<div id="label">${this.displayText || b`&nbsp;`}</div>`;
  }
  renderMenu() {
    const ariaLabel = this.label || this.ariaLabel;
    return b`<div class="menu-wrapper">
      <md-menu
        id="listbox"
        .defaultFocus=${this.defaultFocus}
        role="listbox"
        tabindex="-1"
        aria-label=${ariaLabel || A}
        stay-open-on-focusout
        part="menu"
        exportparts="focus-ring: menu-focus-ring"
        anchor="field"
        style=${o$2({
      '--__menu-min-width': `${this.selectWidth}px`,
      '--__menu-max-width': this.clampMenuWidth ? `${this.selectWidth}px` : undefined
    })}
        no-navigation-wrap
        .open=${this.open}
        .quick=${this.quick}
        .positioning=${this.menuPositioning}
        .typeaheadDelay=${this.typeaheadDelay}
        .anchorCorner=${this.menuAlign === 'start' ? 'end-start' : 'end-end'}
        .menuCorner=${this.menuAlign === 'start' ? 'start-start' : 'start-end'}
        @opening=${this.handleOpening}
        @opened=${this.redispatchEvent}
        @closing=${this.redispatchEvent}
        @closed=${this.handleClosed}
        @close-menu=${this.handleCloseMenu}
        @request-selection=${this.handleRequestSelection}
        @request-deselection=${this.handleRequestDeselection}>
        ${this.renderMenuContent()}
      </md-menu>
    </div>`;
  }
  renderMenuContent() {
    return b`<slot></slot>`;
  }
  /**
   * Handles opening the select on keydown and typahead selection when the menu
   * is closed.
   */
  handleKeydown(event) {
    if (this.open || this.disabled || !this.menu) {
      return;
    }
    const typeaheadController = this.menu.typeaheadController;
    const isOpenKey = event.code === 'Space' || event.code === 'ArrowDown' || event.code === 'ArrowUp' || event.code === 'End' || event.code === 'Home' || event.code === 'Enter';
    // Do not open if currently typing ahead because the user may be typing the
    // spacebar to match a word with a space
    if (!typeaheadController.isTypingAhead && isOpenKey) {
      event.preventDefault();
      this.open = true;
      // https://www.w3.org/WAI/ARIA/apg/patterns/combobox/examples/combobox-select-only/#kbd_label
      switch (event.code) {
        case 'Space':
        case 'ArrowDown':
        case 'Enter':
          // We will handle focusing last selected item in this.handleOpening()
          this.defaultFocus = FocusState.NONE;
          break;
        case 'End':
          this.defaultFocus = FocusState.LAST_ITEM;
          break;
        case 'ArrowUp':
        case 'Home':
          this.defaultFocus = FocusState.FIRST_ITEM;
          break;
      }
      return;
    }
    const isPrintableKey = event.key.length === 1;
    // Handles typing ahead when the menu is closed by delegating the event to
    // the underlying menu's typeaheadController
    if (isPrintableKey) {
      typeaheadController.onKeydown(event);
      event.preventDefault();
      const {
        lastActiveRecord
      } = typeaheadController;
      if (!lastActiveRecord) {
        return;
      }
      this.labelEl?.setAttribute?.('aria-live', 'polite');
      const hasChanged = this.selectItem(lastActiveRecord[TYPEAHEAD_RECORD.ITEM]);
      if (hasChanged) {
        this.dispatchInteractionEvents();
      }
    }
  }
  handleClick() {
    this.open = !this.open;
  }
  handleFocus() {
    this.focused = true;
  }
  handleBlur() {
    this.focused = false;
  }
  /**
   * Handles closing the menu when the focus leaves the select's subtree.
   */
  handleFocusout(event) {
    // Don't close the menu if we are switching focus between menu,
    // select-option, and field
    if (event.relatedTarget && isElementInSubtree(event.relatedTarget, this)) {
      return;
    }
    this.open = false;
  }
  /**
   * Gets a list of all selected select options as a list item record array.
   *
   * @return An array of selected list option records.
   */
  getSelectedOptions() {
    if (!this.menu) {
      this.lastSelectedOptionRecords = [];
      return null;
    }
    const items = this.menu.items;
    this.lastSelectedOptionRecords = getSelectedItems(items);
    return this.lastSelectedOptionRecords;
  }
  async getUpdateComplete() {
    await this.menu?.updateComplete;
    return super.getUpdateComplete();
  }
  /**
   * Gets the selected options from the DOM, and updates the value and display
   * text to the first selected option's value and headline respectively.
   *
   * @return Whether or not the selected option has changed since last update.
   */
  updateValueAndDisplayText() {
    const selectedOptions = this.getSelectedOptions() ?? [];
    // Used to determine whether or not we need to fire an input / change event
    // which fire whenever the option element changes (value or selectedIndex)
    // on user interaction.
    let hasSelectedOptionChanged = false;
    if (selectedOptions.length) {
      const [firstSelectedOption] = selectedOptions[0];
      hasSelectedOptionChanged = this.lastSelectedOption !== firstSelectedOption;
      this.lastSelectedOption = firstSelectedOption;
      this[VALUE] = firstSelectedOption.value;
      this.displayText = firstSelectedOption.displayText;
    } else {
      hasSelectedOptionChanged = this.lastSelectedOption !== null;
      this.lastSelectedOption = null;
      this[VALUE] = '';
      this.displayText = '';
    }
    return hasSelectedOptionChanged;
  }
  /**
   * Focuses and activates the last selected item upon opening, and resets other
   * active items.
   */
  async handleOpening(e) {
    this.labelEl?.removeAttribute?.('aria-live');
    this.redispatchEvent(e);
    // FocusState.NONE means we want to handle focus ourselves and focus the
    // last selected item.
    if (this.defaultFocus !== FocusState.NONE) {
      return;
    }
    const items = this.menu.items;
    const activeItem = getActiveItem(items)?.item;
    let [selectedItem] = this.lastSelectedOptionRecords[0] ?? [null];
    // This is true if the user keys through the list but clicks out of the menu
    // thus no close-menu event is fired by an item and we can't clean up in
    // handleCloseMenu.
    if (activeItem && activeItem !== selectedItem) {
      activeItem.tabIndex = -1;
    }
    // in the case that nothing is selected, focus the first item
    selectedItem = selectedItem ?? items[0];
    if (selectedItem) {
      selectedItem.tabIndex = 0;
      selectedItem.focus();
    }
  }
  redispatchEvent(e) {
    redispatchEvent(this, e);
  }
  handleClosed(e) {
    this.open = false;
    this.redispatchEvent(e);
  }
  /**
   * Determines the reason for closing, and updates the UI accordingly.
   */
  handleCloseMenu(event) {
    const reason = event.detail.reason;
    const item = event.detail.itemPath[0];
    this.open = false;
    let hasChanged = false;
    if (reason.kind === 'click-selection') {
      hasChanged = this.selectItem(item);
    } else if (reason.kind === 'keydown' && isSelectableKey(reason.key)) {
      hasChanged = this.selectItem(item);
    } else {
      // This can happen on ESC being pressed
      item.tabIndex = -1;
      item.blur();
    }
    // Dispatch interaction events since selection has been made via keyboard
    // or mouse.
    if (hasChanged) {
      this.dispatchInteractionEvents();
    }
  }
  /**
   * Selects a given option, deselects other options, and updates the UI.
   *
   * @return Whether the last selected option has changed.
   */
  selectItem(item) {
    const selectedOptions = this.getSelectedOptions() ?? [];
    selectedOptions.forEach(([option]) => {
      if (item !== option) {
        option.selected = false;
      }
    });
    item.selected = true;
    return this.updateValueAndDisplayText();
  }
  /**
   * Handles updating selection when an option element requests selection via
   * property / attribute change.
   */
  handleRequestSelection(event) {
    const requestingOptionEl = event.target;
    // No-op if this item is already selected.
    if (this.lastSelectedOptionRecords.some(([option]) => option === requestingOptionEl)) {
      return;
    }
    this.selectItem(requestingOptionEl);
  }
  /**
   * Handles updating selection when an option element requests deselection via
   * property / attribute change.
   */
  handleRequestDeselection(event) {
    const requestingOptionEl = event.target;
    // No-op if this item is not even in the list of tracked selected items.
    if (!this.lastSelectedOptionRecords.some(([option]) => option === requestingOptionEl)) {
      return;
    }
    this.updateValueAndDisplayText();
  }
  /**
   * Attempts to initialize the selected option from user-settable values like
   * SSR, setting `value`, or `selectedIndex` at startup.
   */
  initUserSelection() {
    // User has set `.value` directly, but internals have not yet booted up.
    if (this.lastUserSetValue && !this.lastSelectedOptionRecords.length) {
      this.select(this.lastUserSetValue);
      // User has set `.selectedIndex` directly, but internals have not yet
      // booted up.
    } else if (this.lastUserSetSelectedIndex !== null && !this.lastSelectedOptionRecords.length) {
      this.selectIndex(this.lastUserSetSelectedIndex);
      // Regular boot up!
    } else {
      this.updateValueAndDisplayText();
    }
  }
  handleIconChange() {
    this.hasLeadingIcon = this.leadingIcons.length > 0;
  }
  /**
   * Dispatches the `input` and `change` events.
   */
  dispatchInteractionEvents() {
    this.dispatchEvent(new Event('input', {
      bubbles: true,
      composed: true
    }));
    this.dispatchEvent(new Event('change', {
      bubbles: true
    }));
  }
  getErrorText() {
    return this.error ? this.errorText : this.nativeErrorText;
  }
  [getFormValue]() {
    return this.value;
  }
  formResetCallback() {
    this.reset();
  }
  formStateRestoreCallback(state) {
    this.value = state;
  }
  click() {
    this.field?.click();
  }
  [createValidator]() {
    return new SelectValidator(() => this);
  }
  [getValidityAnchor]() {
    return this.field;
  }
}
/** @nocollapse */
Select.shadowRootOptions = {
  ...i$4.shadowRootOptions,
  delegatesFocus: true
};
__decorate([n$5({
  type: Boolean
})], Select.prototype, "quick", void 0);
__decorate([n$5({
  type: Boolean
})], Select.prototype, "required", void 0);
__decorate([n$5({
  type: String,
  attribute: 'error-text'
})], Select.prototype, "errorText", void 0);
__decorate([n$5()], Select.prototype, "label", void 0);
__decorate([n$5({
  type: Boolean,
  attribute: 'no-asterisk'
})], Select.prototype, "noAsterisk", void 0);
__decorate([n$5({
  type: String,
  attribute: 'supporting-text'
})], Select.prototype, "supportingText", void 0);
__decorate([n$5({
  type: Boolean,
  reflect: true
})], Select.prototype, "error", void 0);
__decorate([n$5({
  attribute: 'menu-positioning'
})], Select.prototype, "menuPositioning", void 0);
__decorate([n$5({
  type: Boolean,
  attribute: 'clamp-menu-width'
})], Select.prototype, "clampMenuWidth", void 0);
__decorate([n$5({
  type: Number,
  attribute: 'typeahead-delay'
})], Select.prototype, "typeaheadDelay", void 0);
__decorate([n$5({
  type: Boolean,
  attribute: 'has-leading-icon'
})], Select.prototype, "hasLeadingIcon", void 0);
__decorate([n$5({
  attribute: 'display-text'
})], Select.prototype, "displayText", void 0);
__decorate([n$5({
  attribute: 'menu-align'
})], Select.prototype, "menuAlign", void 0);
__decorate([n$5()], Select.prototype, "value", null);
__decorate([n$5({
  type: Number,
  attribute: 'selected-index'
})], Select.prototype, "selectedIndex", null);
__decorate([r$3()], Select.prototype, "nativeError", void 0);
__decorate([r$3()], Select.prototype, "nativeErrorText", void 0);
__decorate([r$3()], Select.prototype, "focused", void 0);
__decorate([r$3()], Select.prototype, "open", void 0);
__decorate([r$3()], Select.prototype, "defaultFocus", void 0);
__decorate([e$6('.field')], Select.prototype, "field", void 0);
__decorate([e$6('md-menu')], Select.prototype, "menu", void 0);
__decorate([e$6('#label')], Select.prototype, "labelEl", void 0);
__decorate([o$5({
  slot: 'leading-icon',
  flatten: true
})], Select.prototype, "leadingIcons", void 0);

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// tslint:disable-next-line:enforce-comments-on-exported-symbols
class OutlinedSelect extends Select {
  constructor() {
    super(...arguments);
    this.fieldTag = i$2`md-outlined-field`;
  }
}

/**
 * @license
 * Copyright 2024 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Generated stylesheet for ./select/internal/outlined-select-styles.css.
const styles$7 = i$7`:host{--_text-field-disabled-input-text-color: var(--md-outlined-select-text-field-disabled-input-text-color, var(--md-sys-color-on-surface, #1d1b20));--_text-field-disabled-input-text-opacity: var(--md-outlined-select-text-field-disabled-input-text-opacity, 0.38);--_text-field-disabled-label-text-color: var(--md-outlined-select-text-field-disabled-label-text-color, var(--md-sys-color-on-surface, #1d1b20));--_text-field-disabled-label-text-opacity: var(--md-outlined-select-text-field-disabled-label-text-opacity, 0.38);--_text-field-disabled-leading-icon-color: var(--md-outlined-select-text-field-disabled-leading-icon-color, var(--md-sys-color-on-surface, #1d1b20));--_text-field-disabled-leading-icon-opacity: var(--md-outlined-select-text-field-disabled-leading-icon-opacity, 0.38);--_text-field-disabled-outline-color: var(--md-outlined-select-text-field-disabled-outline-color, var(--md-sys-color-on-surface, #1d1b20));--_text-field-disabled-outline-opacity: var(--md-outlined-select-text-field-disabled-outline-opacity, 0.12);--_text-field-disabled-outline-width: var(--md-outlined-select-text-field-disabled-outline-width, 1px);--_text-field-disabled-supporting-text-color: var(--md-outlined-select-text-field-disabled-supporting-text-color, var(--md-sys-color-on-surface, #1d1b20));--_text-field-disabled-supporting-text-opacity: var(--md-outlined-select-text-field-disabled-supporting-text-opacity, 0.38);--_text-field-disabled-trailing-icon-color: var(--md-outlined-select-text-field-disabled-trailing-icon-color, var(--md-sys-color-on-surface, #1d1b20));--_text-field-disabled-trailing-icon-opacity: var(--md-outlined-select-text-field-disabled-trailing-icon-opacity, 0.38);--_text-field-error-focus-input-text-color: var(--md-outlined-select-text-field-error-focus-input-text-color, var(--md-sys-color-on-surface, #1d1b20));--_text-field-error-focus-label-text-color: var(--md-outlined-select-text-field-error-focus-label-text-color, var(--md-sys-color-error, #b3261e));--_text-field-error-focus-leading-icon-color: var(--md-outlined-select-text-field-error-focus-leading-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_text-field-error-focus-outline-color: var(--md-outlined-select-text-field-error-focus-outline-color, var(--md-sys-color-error, #b3261e));--_text-field-error-focus-supporting-text-color: var(--md-outlined-select-text-field-error-focus-supporting-text-color, var(--md-sys-color-error, #b3261e));--_text-field-error-focus-trailing-icon-color: var(--md-outlined-select-text-field-error-focus-trailing-icon-color, var(--md-sys-color-error, #b3261e));--_text-field-error-hover-input-text-color: var(--md-outlined-select-text-field-error-hover-input-text-color, var(--md-sys-color-on-surface, #1d1b20));--_text-field-error-hover-label-text-color: var(--md-outlined-select-text-field-error-hover-label-text-color, var(--md-sys-color-on-error-container, #410e0b));--_text-field-error-hover-leading-icon-color: var(--md-outlined-select-text-field-error-hover-leading-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_text-field-error-hover-outline-color: var(--md-outlined-select-text-field-error-hover-outline-color, var(--md-sys-color-on-error-container, #410e0b));--_text-field-error-hover-supporting-text-color: var(--md-outlined-select-text-field-error-hover-supporting-text-color, var(--md-sys-color-error, #b3261e));--_text-field-error-hover-trailing-icon-color: var(--md-outlined-select-text-field-error-hover-trailing-icon-color, var(--md-sys-color-on-error-container, #410e0b));--_text-field-error-input-text-color: var(--md-outlined-select-text-field-error-input-text-color, var(--md-sys-color-on-surface, #1d1b20));--_text-field-error-label-text-color: var(--md-outlined-select-text-field-error-label-text-color, var(--md-sys-color-error, #b3261e));--_text-field-error-leading-icon-color: var(--md-outlined-select-text-field-error-leading-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_text-field-error-outline-color: var(--md-outlined-select-text-field-error-outline-color, var(--md-sys-color-error, #b3261e));--_text-field-error-supporting-text-color: var(--md-outlined-select-text-field-error-supporting-text-color, var(--md-sys-color-error, #b3261e));--_text-field-error-trailing-icon-color: var(--md-outlined-select-text-field-error-trailing-icon-color, var(--md-sys-color-error, #b3261e));--_text-field-focus-input-text-color: var(--md-outlined-select-text-field-focus-input-text-color, var(--md-sys-color-on-surface, #1d1b20));--_text-field-focus-label-text-color: var(--md-outlined-select-text-field-focus-label-text-color, var(--md-sys-color-primary, #6750a4));--_text-field-focus-leading-icon-color: var(--md-outlined-select-text-field-focus-leading-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_text-field-focus-outline-color: var(--md-outlined-select-text-field-focus-outline-color, var(--md-sys-color-primary, #6750a4));--_text-field-focus-outline-width: var(--md-outlined-select-text-field-focus-outline-width, 3px);--_text-field-focus-supporting-text-color: var(--md-outlined-select-text-field-focus-supporting-text-color, var(--md-sys-color-on-surface-variant, #49454f));--_text-field-focus-trailing-icon-color: var(--md-outlined-select-text-field-focus-trailing-icon-color, var(--md-sys-color-primary, #6750a4));--_text-field-hover-input-text-color: var(--md-outlined-select-text-field-hover-input-text-color, var(--md-sys-color-on-surface, #1d1b20));--_text-field-hover-label-text-color: var(--md-outlined-select-text-field-hover-label-text-color, var(--md-sys-color-on-surface, #1d1b20));--_text-field-hover-leading-icon-color: var(--md-outlined-select-text-field-hover-leading-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_text-field-hover-outline-color: var(--md-outlined-select-text-field-hover-outline-color, var(--md-sys-color-on-surface, #1d1b20));--_text-field-hover-outline-width: var(--md-outlined-select-text-field-hover-outline-width, 1px);--_text-field-hover-supporting-text-color: var(--md-outlined-select-text-field-hover-supporting-text-color, var(--md-sys-color-on-surface-variant, #49454f));--_text-field-hover-trailing-icon-color: var(--md-outlined-select-text-field-hover-trailing-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_text-field-input-text-color: var(--md-outlined-select-text-field-input-text-color, var(--md-sys-color-on-surface, #1d1b20));--_text-field-input-text-font: var(--md-outlined-select-text-field-input-text-font, var(--md-sys-typescale-body-large-font, var(--md-ref-typeface-plain, Roboto)));--_text-field-input-text-line-height: var(--md-outlined-select-text-field-input-text-line-height, var(--md-sys-typescale-body-large-line-height, 1.5rem));--_text-field-input-text-size: var(--md-outlined-select-text-field-input-text-size, var(--md-sys-typescale-body-large-size, 1rem));--_text-field-input-text-weight: var(--md-outlined-select-text-field-input-text-weight, var(--md-sys-typescale-body-large-weight, var(--md-ref-typeface-weight-regular, 400)));--_text-field-label-text-color: var(--md-outlined-select-text-field-label-text-color, var(--md-sys-color-on-surface-variant, #49454f));--_text-field-label-text-font: var(--md-outlined-select-text-field-label-text-font, var(--md-sys-typescale-body-large-font, var(--md-ref-typeface-plain, Roboto)));--_text-field-label-text-line-height: var(--md-outlined-select-text-field-label-text-line-height, var(--md-sys-typescale-body-large-line-height, 1.5rem));--_text-field-label-text-populated-line-height: var(--md-outlined-select-text-field-label-text-populated-line-height, var(--md-sys-typescale-body-small-line-height, 1rem));--_text-field-label-text-populated-size: var(--md-outlined-select-text-field-label-text-populated-size, var(--md-sys-typescale-body-small-size, 0.75rem));--_text-field-label-text-size: var(--md-outlined-select-text-field-label-text-size, var(--md-sys-typescale-body-large-size, 1rem));--_text-field-label-text-weight: var(--md-outlined-select-text-field-label-text-weight, var(--md-sys-typescale-body-large-weight, var(--md-ref-typeface-weight-regular, 400)));--_text-field-leading-icon-color: var(--md-outlined-select-text-field-leading-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_text-field-leading-icon-size: var(--md-outlined-select-text-field-leading-icon-size, 24px);--_text-field-outline-color: var(--md-outlined-select-text-field-outline-color, var(--md-sys-color-outline, #79747e));--_text-field-outline-width: var(--md-outlined-select-text-field-outline-width, 1px);--_text-field-supporting-text-color: var(--md-outlined-select-text-field-supporting-text-color, var(--md-sys-color-on-surface-variant, #49454f));--_text-field-supporting-text-font: var(--md-outlined-select-text-field-supporting-text-font, var(--md-sys-typescale-body-small-font, var(--md-ref-typeface-plain, Roboto)));--_text-field-supporting-text-line-height: var(--md-outlined-select-text-field-supporting-text-line-height, var(--md-sys-typescale-body-small-line-height, 1rem));--_text-field-supporting-text-size: var(--md-outlined-select-text-field-supporting-text-size, var(--md-sys-typescale-body-small-size, 0.75rem));--_text-field-supporting-text-weight: var(--md-outlined-select-text-field-supporting-text-weight, var(--md-sys-typescale-body-small-weight, var(--md-ref-typeface-weight-regular, 400)));--_text-field-trailing-icon-color: var(--md-outlined-select-text-field-trailing-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_text-field-trailing-icon-size: var(--md-outlined-select-text-field-trailing-icon-size, 24px);--_text-field-container-shape-start-start: var(--md-outlined-select-text-field-container-shape-start-start, var(--md-outlined-select-text-field-container-shape, var(--md-sys-shape-corner-extra-small, 4px)));--_text-field-container-shape-start-end: var(--md-outlined-select-text-field-container-shape-start-end, var(--md-outlined-select-text-field-container-shape, var(--md-sys-shape-corner-extra-small, 4px)));--_text-field-container-shape-end-end: var(--md-outlined-select-text-field-container-shape-end-end, var(--md-outlined-select-text-field-container-shape, var(--md-sys-shape-corner-extra-small, 4px)));--_text-field-container-shape-end-start: var(--md-outlined-select-text-field-container-shape-end-start, var(--md-outlined-select-text-field-container-shape, var(--md-sys-shape-corner-extra-small, 4px)));--md-outlined-field-container-shape-end-end: var(--_text-field-container-shape-end-end);--md-outlined-field-container-shape-end-start: var(--_text-field-container-shape-end-start);--md-outlined-field-container-shape-start-end: var(--_text-field-container-shape-start-end);--md-outlined-field-container-shape-start-start: var(--_text-field-container-shape-start-start);--md-outlined-field-content-color: var(--_text-field-input-text-color);--md-outlined-field-content-font: var(--_text-field-input-text-font);--md-outlined-field-content-line-height: var(--_text-field-input-text-line-height);--md-outlined-field-content-size: var(--_text-field-input-text-size);--md-outlined-field-content-weight: var(--_text-field-input-text-weight);--md-outlined-field-disabled-content-color: var(--_text-field-disabled-input-text-color);--md-outlined-field-disabled-content-opacity: var(--_text-field-disabled-input-text-opacity);--md-outlined-field-disabled-label-text-color: var(--_text-field-disabled-label-text-color);--md-outlined-field-disabled-label-text-opacity: var(--_text-field-disabled-label-text-opacity);--md-outlined-field-disabled-leading-content-color: var(--_text-field-disabled-leading-icon-color);--md-outlined-field-disabled-leading-content-opacity: var(--_text-field-disabled-leading-icon-opacity);--md-outlined-field-disabled-outline-color: var(--_text-field-disabled-outline-color);--md-outlined-field-disabled-outline-opacity: var(--_text-field-disabled-outline-opacity);--md-outlined-field-disabled-outline-width: var(--_text-field-disabled-outline-width);--md-outlined-field-disabled-supporting-text-color: var(--_text-field-disabled-supporting-text-color);--md-outlined-field-disabled-supporting-text-opacity: var(--_text-field-disabled-supporting-text-opacity);--md-outlined-field-disabled-trailing-content-color: var(--_text-field-disabled-trailing-icon-color);--md-outlined-field-disabled-trailing-content-opacity: var(--_text-field-disabled-trailing-icon-opacity);--md-outlined-field-error-content-color: var(--_text-field-error-input-text-color);--md-outlined-field-error-focus-content-color: var(--_text-field-error-focus-input-text-color);--md-outlined-field-error-focus-label-text-color: var(--_text-field-error-focus-label-text-color);--md-outlined-field-error-focus-leading-content-color: var(--_text-field-error-focus-leading-icon-color);--md-outlined-field-error-focus-outline-color: var(--_text-field-error-focus-outline-color);--md-outlined-field-error-focus-supporting-text-color: var(--_text-field-error-focus-supporting-text-color);--md-outlined-field-error-focus-trailing-content-color: var(--_text-field-error-focus-trailing-icon-color);--md-outlined-field-error-hover-content-color: var(--_text-field-error-hover-input-text-color);--md-outlined-field-error-hover-label-text-color: var(--_text-field-error-hover-label-text-color);--md-outlined-field-error-hover-leading-content-color: var(--_text-field-error-hover-leading-icon-color);--md-outlined-field-error-hover-outline-color: var(--_text-field-error-hover-outline-color);--md-outlined-field-error-hover-supporting-text-color: var(--_text-field-error-hover-supporting-text-color);--md-outlined-field-error-hover-trailing-content-color: var(--_text-field-error-hover-trailing-icon-color);--md-outlined-field-error-label-text-color: var(--_text-field-error-label-text-color);--md-outlined-field-error-leading-content-color: var(--_text-field-error-leading-icon-color);--md-outlined-field-error-outline-color: var(--_text-field-error-outline-color);--md-outlined-field-error-supporting-text-color: var(--_text-field-error-supporting-text-color);--md-outlined-field-error-trailing-content-color: var(--_text-field-error-trailing-icon-color);--md-outlined-field-focus-content-color: var(--_text-field-focus-input-text-color);--md-outlined-field-focus-label-text-color: var(--_text-field-focus-label-text-color);--md-outlined-field-focus-leading-content-color: var(--_text-field-focus-leading-icon-color);--md-outlined-field-focus-outline-color: var(--_text-field-focus-outline-color);--md-outlined-field-focus-outline-width: var(--_text-field-focus-outline-width);--md-outlined-field-focus-supporting-text-color: var(--_text-field-focus-supporting-text-color);--md-outlined-field-focus-trailing-content-color: var(--_text-field-focus-trailing-icon-color);--md-outlined-field-hover-content-color: var(--_text-field-hover-input-text-color);--md-outlined-field-hover-label-text-color: var(--_text-field-hover-label-text-color);--md-outlined-field-hover-leading-content-color: var(--_text-field-hover-leading-icon-color);--md-outlined-field-hover-outline-color: var(--_text-field-hover-outline-color);--md-outlined-field-hover-outline-width: var(--_text-field-hover-outline-width);--md-outlined-field-hover-supporting-text-color: var(--_text-field-hover-supporting-text-color);--md-outlined-field-hover-trailing-content-color: var(--_text-field-hover-trailing-icon-color);--md-outlined-field-label-text-color: var(--_text-field-label-text-color);--md-outlined-field-label-text-font: var(--_text-field-label-text-font);--md-outlined-field-label-text-line-height: var(--_text-field-label-text-line-height);--md-outlined-field-label-text-populated-line-height: var(--_text-field-label-text-populated-line-height);--md-outlined-field-label-text-populated-size: var(--_text-field-label-text-populated-size);--md-outlined-field-label-text-size: var(--_text-field-label-text-size);--md-outlined-field-label-text-weight: var(--_text-field-label-text-weight);--md-outlined-field-leading-content-color: var(--_text-field-leading-icon-color);--md-outlined-field-outline-color: var(--_text-field-outline-color);--md-outlined-field-outline-width: var(--_text-field-outline-width);--md-outlined-field-supporting-text-color: var(--_text-field-supporting-text-color);--md-outlined-field-supporting-text-font: var(--_text-field-supporting-text-font);--md-outlined-field-supporting-text-line-height: var(--_text-field-supporting-text-line-height);--md-outlined-field-supporting-text-size: var(--_text-field-supporting-text-size);--md-outlined-field-supporting-text-weight: var(--_text-field-supporting-text-weight);--md-outlined-field-trailing-content-color: var(--_text-field-trailing-icon-color)}[has-start] .icon.leading{font-size:var(--_text-field-leading-icon-size);height:var(--_text-field-leading-icon-size);width:var(--_text-field-leading-icon-size)}.icon.trailing{font-size:var(--_text-field-trailing-icon-size);height:var(--_text-field-trailing-icon-size);width:var(--_text-field-trailing-icon-size)}
`;

/**
 * @license
 * Copyright 2024 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Generated stylesheet for ./select/internal/shared-styles.css.
const styles$6 = i$7`:host{color:unset;min-width:210px;display:flex}.field{cursor:default;outline:none}.select{position:relative;flex-direction:column}.icon.trailing svg,.icon ::slotted(*){fill:currentColor}.icon ::slotted(*){width:inherit;height:inherit;font-size:inherit}.icon slot{display:flex;height:100%;width:100%;align-items:center;justify-content:center}.icon.trailing :is(.up,.down){opacity:0;transition:opacity 75ms linear 75ms}.select:not(.open) .down,.select.open .up{opacity:1}.field,.select,md-menu{min-width:inherit;width:inherit;max-width:inherit;display:flex}md-menu{min-width:var(--__menu-min-width);max-width:var(--__menu-max-width, inherit)}.menu-wrapper{width:0px;height:0px;max-width:inherit}md-menu ::slotted(:not[disabled]){cursor:pointer}.field,.select{width:100%}:host{display:inline-flex}:host([disabled]){pointer-events:none}
`;

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @summary
 * Select menus display a list of choices on temporary surfaces and display the
 * currently selected menu item above the menu.
 *
 * @description
 * The select component allows users to choose a value from a fixed list of
 * available options. Composed of an interactive anchor button and a menu, it is
 * analogous to the native HTML `<select>` element. This is the "outlined"
 * variant.
 *
 * @example
 * ```html
 * <md-outlined-select label="fruits">
 *   <!-- An empty selected option will give select an "un-filled" state -->
 *   <md-select-option selected></md-select-option>
 *   <md-select-option value="apple" headline="Apple"></md-select-option>
 *   <md-select-option value="banana" headline="Banana"></md-select-option>
 *   <md-select-option value="kiwi" headline="Kiwi"></md-select-option>
 *   <md-select-option value="orange" headline="Orange"></md-select-option>
 *   <md-select-option value="tomato" headline="Tomato"></md-select-option>
 * </md-outlined-select>
 * ```
 *
 * @final
 * @suppress {visibility}
 */
let MdOutlinedSelect = class MdOutlinedSelect extends OutlinedSelect {};
MdOutlinedSelect.styles = [styles$6, styles$7];
MdOutlinedSelect = __decorate([t$1('md-outlined-select')], MdOutlinedSelect);

/**
 * @license
 * Copyright 2024 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Generated stylesheet for ./menu/internal/menuitem/menu-item-styles.css.
const styles$5 = i$7`:host{display:flex;--md-ripple-hover-color: var(--md-menu-item-hover-state-layer-color, var(--md-sys-color-on-surface, #1d1b20));--md-ripple-hover-opacity: var(--md-menu-item-hover-state-layer-opacity, 0.08);--md-ripple-pressed-color: var(--md-menu-item-pressed-state-layer-color, var(--md-sys-color-on-surface, #1d1b20));--md-ripple-pressed-opacity: var(--md-menu-item-pressed-state-layer-opacity, 0.12)}:host([disabled]){opacity:var(--md-menu-item-disabled-opacity, 0.3);pointer-events:none}md-focus-ring{z-index:1;--md-focus-ring-shape: 8px}a,button,li{background:none;border:none;padding:0;margin:0;text-align:unset;text-decoration:none}.list-item{border-radius:inherit;display:flex;flex:1;max-width:inherit;min-width:inherit;outline:none;-webkit-tap-highlight-color:rgba(0,0,0,0)}.list-item:not(.disabled){cursor:pointer}[slot=container]{pointer-events:none}md-ripple{border-radius:inherit}md-item{border-radius:inherit;flex:1;color:var(--md-menu-item-label-text-color, var(--md-sys-color-on-surface, #1d1b20));font-family:var(--md-menu-item-label-text-font, var(--md-sys-typescale-body-large-font, var(--md-ref-typeface-plain, Roboto)));font-size:var(--md-menu-item-label-text-size, var(--md-sys-typescale-body-large-size, 1rem));line-height:var(--md-menu-item-label-text-line-height, var(--md-sys-typescale-body-large-line-height, 1.5rem));font-weight:var(--md-menu-item-label-text-weight, var(--md-sys-typescale-body-large-weight, var(--md-ref-typeface-weight-regular, 400)));min-height:var(--md-menu-item-one-line-container-height, 56px);padding-top:var(--md-menu-item-top-space, 12px);padding-bottom:var(--md-menu-item-bottom-space, 12px);padding-inline-start:var(--md-menu-item-leading-space, 16px);padding-inline-end:var(--md-menu-item-trailing-space, 16px)}md-item[multiline]{min-height:var(--md-menu-item-two-line-container-height, 72px)}[slot=supporting-text]{color:var(--md-menu-item-supporting-text-color, var(--md-sys-color-on-surface-variant, #49454f));font-family:var(--md-menu-item-supporting-text-font, var(--md-sys-typescale-body-medium-font, var(--md-ref-typeface-plain, Roboto)));font-size:var(--md-menu-item-supporting-text-size, var(--md-sys-typescale-body-medium-size, 0.875rem));line-height:var(--md-menu-item-supporting-text-line-height, var(--md-sys-typescale-body-medium-line-height, 1.25rem));font-weight:var(--md-menu-item-supporting-text-weight, var(--md-sys-typescale-body-medium-weight, var(--md-ref-typeface-weight-regular, 400)))}[slot=trailing-supporting-text]{color:var(--md-menu-item-trailing-supporting-text-color, var(--md-sys-color-on-surface-variant, #49454f));font-family:var(--md-menu-item-trailing-supporting-text-font, var(--md-sys-typescale-label-small-font, var(--md-ref-typeface-plain, Roboto)));font-size:var(--md-menu-item-trailing-supporting-text-size, var(--md-sys-typescale-label-small-size, 0.6875rem));line-height:var(--md-menu-item-trailing-supporting-text-line-height, var(--md-sys-typescale-label-small-line-height, 1rem));font-weight:var(--md-menu-item-trailing-supporting-text-weight, var(--md-sys-typescale-label-small-weight, var(--md-ref-typeface-weight-medium, 500)))}:is([slot=start],[slot=end])::slotted(*){fill:currentColor}[slot=start]{color:var(--md-menu-item-leading-icon-color, var(--md-sys-color-on-surface-variant, #49454f))}[slot=end]{color:var(--md-menu-item-trailing-icon-color, var(--md-sys-color-on-surface-variant, #49454f))}.list-item{background-color:var(--md-menu-item-container-color, transparent)}.list-item.selected{background-color:var(--md-menu-item-selected-container-color, var(--md-sys-color-secondary-container, #e8def8))}.selected:not(.disabled) ::slotted(*){color:var(--md-menu-item-selected-label-text-color, var(--md-sys-color-on-secondary-container, #1d192b))}@media(forced-colors: active){:host([disabled]),:host([disabled]) slot{color:GrayText;opacity:1}.list-item{position:relative}.list-item.selected::before{content:"";position:absolute;inset:0;box-sizing:border-box;border-radius:inherit;pointer-events:none;border:3px double CanvasText}}
`;

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * A controller that provides most functionality of an element that implements
 * the MenuItem interface.
 */
class MenuItemController {
  /**
   * @param host The MenuItem in which to attach this controller to.
   * @param config The object that configures this controller's behavior.
   */
  constructor(host, config) {
    this.host = host;
    this.internalTypeaheadText = null;
    /**
     * Bind this click listener to the interactive element. Handles closing the
     * menu.
     */
    this.onClick = () => {
      if (this.host.keepOpen) return;
      this.host.dispatchEvent(createDefaultCloseMenuEvent(this.host, {
        kind: CloseReason.CLICK_SELECTION
      }));
    };
    /**
     * Bind this click listener to the interactive element. Handles closing the
     * menu.
     */
    this.onKeydown = event => {
      // Check if the interactive element is an anchor tag. If so, click it.
      if (this.host.href && event.code === 'Enter') {
        const interactiveElement = this.getInteractiveElement();
        if (interactiveElement instanceof HTMLAnchorElement) {
          interactiveElement.click();
        }
      }
      if (event.defaultPrevented) return;
      // If the host has keepOpen = true we should ignore clicks & Space/Enter,
      // however we always maintain the ability to close a menu with a explicit
      // `escape` keypress.
      const keyCode = event.code;
      if (this.host.keepOpen && keyCode !== 'Escape') return;
      if (isClosableKey(keyCode)) {
        event.preventDefault();
        this.host.dispatchEvent(createDefaultCloseMenuEvent(this.host, {
          kind: CloseReason.KEYDOWN,
          key: keyCode
        }));
      }
    };
    this.getHeadlineElements = config.getHeadlineElements;
    this.getSupportingTextElements = config.getSupportingTextElements;
    this.getDefaultElements = config.getDefaultElements;
    this.getInteractiveElement = config.getInteractiveElement;
    this.host.addController(this);
  }
  /**
   * The text that is selectable via typeahead. If not set, defaults to the
   * innerText of the item slotted into the `"headline"` slot, and if there are
   * no slotted elements into headline, then it checks the _default_ slot, and
   * then the `"supporting-text"` slot if nothing is in _default_.
   */
  get typeaheadText() {
    if (this.internalTypeaheadText !== null) {
      return this.internalTypeaheadText;
    }
    const headlineElements = this.getHeadlineElements();
    const textParts = [];
    headlineElements.forEach(headlineElement => {
      if (headlineElement.textContent && headlineElement.textContent.trim()) {
        textParts.push(headlineElement.textContent.trim());
      }
    });
    // If there are no headline elements, check the default slot's text content
    if (textParts.length === 0) {
      this.getDefaultElements().forEach(defaultElement => {
        if (defaultElement.textContent && defaultElement.textContent.trim()) {
          textParts.push(defaultElement.textContent.trim());
        }
      });
    }
    // If there are no headline nor default slot elements, check the
    //supporting-text slot's text content
    if (textParts.length === 0) {
      this.getSupportingTextElements().forEach(supportingTextElement => {
        if (supportingTextElement.textContent && supportingTextElement.textContent.trim()) {
          textParts.push(supportingTextElement.textContent.trim());
        }
      });
    }
    return textParts.join(' ');
  }
  /**
   * The recommended tag name to render as the list item.
   */
  get tagName() {
    const type = this.host.type;
    switch (type) {
      case 'link':
        return 'a';
      case 'button':
        return 'button';
      default:
      case 'menuitem':
      case 'option':
        return 'li';
    }
  }
  /**
   * The recommended role of the menu item.
   */
  get role() {
    return this.host.type === 'option' ? 'option' : 'menuitem';
  }
  hostConnected() {
    this.host.toggleAttribute('md-menu-item', true);
  }
  hostUpdate() {
    if (this.host.href) {
      this.host.type = 'link';
    }
  }
  /**
   * Use to set the typeaheadText when it changes.
   */
  setTypeaheadText(text) {
    this.internalTypeaheadText = text;
  }
}

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * Creates an event fired by a SelectOption to request selection from md-select.
 * Typically fired after `selected` changes from `false` to `true`.
 */
function createRequestSelectionEvent() {
  return new Event('request-selection', {
    bubbles: true,
    composed: true
  });
}
/**
 * Creates an event fired by a SelectOption to request deselection from
 * md-select. Typically fired after `selected` changes from `true` to `false`.
 */
function createRequestDeselectionEvent() {
  return new Event('request-deselection', {
    bubbles: true,
    composed: true
  });
}
/**
 * A controller that provides most functionality and md-select compatibility for
 * an element that implements the SelectOption interface.
 */
class SelectOptionController {
  /**
   * The recommended role of the select option.
   */
  get role() {
    return this.menuItemController.role;
  }
  /**
   * The text that is selectable via typeahead. If not set, defaults to the
   * innerText of the item slotted into the `"headline"` slot, and if there are
   * no slotted elements into headline, then it checks the _default_ slot, and
   * then the `"supporting-text"` slot if nothing is in _default_.
   */
  get typeaheadText() {
    return this.menuItemController.typeaheadText;
  }
  setTypeaheadText(text) {
    this.menuItemController.setTypeaheadText(text);
  }
  /**
   * The text that is displayed in the select field when selected. If not set,
   * defaults to the textContent of the item slotted into the `"headline"` slot,
   * and if there are no slotted elements into headline, then it checks the
   * _default_ slot, and then the `"supporting-text"` slot if nothing is in
   * _default_.
   */
  get displayText() {
    if (this.internalDisplayText !== null) {
      return this.internalDisplayText;
    }
    return this.menuItemController.typeaheadText;
  }
  setDisplayText(text) {
    this.internalDisplayText = text;
  }
  /**
   * @param host The SelectOption in which to attach this controller to.
   * @param config The object that configures this controller's behavior.
   */
  constructor(host, config) {
    this.host = host;
    this.internalDisplayText = null;
    this.firstUpdate = true;
    /**
     * Bind this click listener to the interactive element. Handles closing the
     * menu.
     */
    this.onClick = () => {
      this.menuItemController.onClick();
    };
    /**
     * Bind this click listener to the interactive element. Handles closing the
     * menu.
     */
    this.onKeydown = e => {
      this.menuItemController.onKeydown(e);
    };
    this.lastSelected = this.host.selected;
    this.menuItemController = new MenuItemController(host, config);
    host.addController(this);
  }
  hostUpdate() {
    if (this.lastSelected !== this.host.selected) {
      this.host.ariaSelected = this.host.selected ? 'true' : 'false';
    }
  }
  hostUpdated() {
    // Do not dispatch event on first update / boot-up.
    if (this.lastSelected !== this.host.selected && !this.firstUpdate) {
      // This section is really useful for when the user sets selected on the
      // option programmatically. Most other cases (click and keyboard) are
      // handled by md-select because it needs to coordinate the
      // single-selection behavior.
      if (this.host.selected) {
        this.host.dispatchEvent(createRequestSelectionEvent());
      } else {
        this.host.dispatchEvent(createRequestDeselectionEvent());
      }
    }
    this.lastSelected = this.host.selected;
    this.firstUpdate = false;
  }
}

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Separate variable needed for closure.
const selectOptionBaseClass = mixinDelegatesAria(i$4);
/**
 * @fires close-menu {CustomEvent<{initiator: SelectOption, reason: Reason, itemPath: SelectOption[]}>}
 * Closes the encapsulating menu on closable interaction. --bubbles --composed
 * @fires request-selection {Event} Requests the parent md-select to select this
 * element (and deselect others if single-selection) when `selected` changed to
 * `true`. --bubbles --composed
 * @fires request-deselection {Event} Requests the parent md-select to deselect
 * this element when `selected` changed to `false`. --bubbles --composed
 */
class SelectOptionEl extends selectOptionBaseClass {
  constructor() {
    super(...arguments);
    /**
     * Disables the item and makes it non-selectable and non-interactive.
     */
    this.disabled = false;
    /**
     * READONLY: self-identifies as a menu item and sets its identifying attribute
     */
    this.isMenuItem = true;
    /**
     * Sets the item in the selected visual state when a submenu is opened.
     */
    this.selected = false;
    /**
     * Form value of the option.
     */
    this.value = '';
    this.type = 'option';
    this.selectOptionController = new SelectOptionController(this, {
      getHeadlineElements: () => {
        return this.headlineElements;
      },
      getSupportingTextElements: () => {
        return this.supportingTextElements;
      },
      getDefaultElements: () => {
        return this.defaultElements;
      },
      getInteractiveElement: () => this.listItemRoot
    });
  }
  /**
   * The text that is selectable via typeahead. If not set, defaults to the
   * innerText of the item slotted into the `"headline"` slot.
   */
  get typeaheadText() {
    return this.selectOptionController.typeaheadText;
  }
  set typeaheadText(text) {
    this.selectOptionController.setTypeaheadText(text);
  }
  /**
   * The text that is displayed in the select field when selected. If not set,
   * defaults to the textContent of the item slotted into the `"headline"` slot.
   */
  get displayText() {
    return this.selectOptionController.displayText;
  }
  set displayText(text) {
    this.selectOptionController.setDisplayText(text);
  }
  render() {
    return this.renderListItem(b`
      <md-item>
        <div slot="container">
          ${this.renderRipple()} ${this.renderFocusRing()}
        </div>
        <slot name="start" slot="start"></slot>
        <slot name="end" slot="end"></slot>
        ${this.renderBody()}
      </md-item>
    `);
  }
  /**
   * Renders the root list item.
   *
   * @param content the child content of the list item.
   */
  renderListItem(content) {
    return b`
      <li
        id="item"
        tabindex=${this.disabled ? -1 : 0}
        role=${this.selectOptionController.role}
        aria-label=${this.ariaLabel || A}
        aria-selected=${this.ariaSelected || A}
        aria-checked=${this.ariaChecked || A}
        aria-expanded=${this.ariaExpanded || A}
        aria-haspopup=${this.ariaHasPopup || A}
        class="list-item ${e$3(this.getRenderClasses())}"
        @click=${this.selectOptionController.onClick}
        @keydown=${this.selectOptionController.onKeydown}
        >${content}</li
      >
    `;
  }
  /**
   * Handles rendering of the ripple element.
   */
  renderRipple() {
    return b` <md-ripple
      part="ripple"
      for="item"
      ?disabled=${this.disabled}></md-ripple>`;
  }
  /**
   * Handles rendering of the focus ring.
   */
  renderFocusRing() {
    return b` <md-focus-ring
      part="focus-ring"
      for="item"
      inward></md-focus-ring>`;
  }
  /**
   * Classes applied to the list item root.
   */
  getRenderClasses() {
    return {
      'disabled': this.disabled,
      'selected': this.selected
    };
  }
  /**
   * Handles rendering the headline and supporting text.
   */
  renderBody() {
    return b`
      <slot></slot>
      <slot name="overline" slot="overline"></slot>
      <slot name="headline" slot="headline"></slot>
      <slot name="supporting-text" slot="supporting-text"></slot>
      <slot
        name="trailing-supporting-text"
        slot="trailing-supporting-text"></slot>
    `;
  }
  focus() {
    // TODO(b/300334509): needed for some cases where delegatesFocus doesn't
    // work programmatically like in FF and select-option
    this.listItemRoot?.focus();
  }
}
/** @nocollapse */
SelectOptionEl.shadowRootOptions = {
  ...i$4.shadowRootOptions,
  delegatesFocus: true
};
__decorate([n$5({
  type: Boolean,
  reflect: true
})], SelectOptionEl.prototype, "disabled", void 0);
__decorate([n$5({
  type: Boolean,
  attribute: 'md-menu-item',
  reflect: true
})], SelectOptionEl.prototype, "isMenuItem", void 0);
__decorate([n$5({
  type: Boolean
})], SelectOptionEl.prototype, "selected", void 0);
__decorate([n$5()], SelectOptionEl.prototype, "value", void 0);
__decorate([e$6('.list-item')], SelectOptionEl.prototype, "listItemRoot", void 0);
__decorate([o$5({
  slot: 'headline'
})], SelectOptionEl.prototype, "headlineElements", void 0);
__decorate([o$5({
  slot: 'supporting-text'
})], SelectOptionEl.prototype, "supportingTextElements", void 0);
__decorate([n$4({
  slot: ''
})], SelectOptionEl.prototype, "defaultElements", void 0);
__decorate([n$5({
  attribute: 'typeahead-text'
})], SelectOptionEl.prototype, "typeaheadText", null);
__decorate([n$5({
  attribute: 'display-text'
})], SelectOptionEl.prototype, "displayText", null);

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @summary
 * Select menus display a list of choices on temporary surfaces and display the
 * currently selected menu item above the menu.
 *
 * @description
 * The select component allows users to choose a value from a fixed list of
 * available options. Composed of an interactive anchor button and a menu, it is
 * analogous to the native HTML `<select>` element. This is the option that
 * can be placed inside of an md-select.
 *
 * This component is a subclass of `md-menu-item` and can accept the same slots,
 * properties, and events as `md-menu-item`.
 *
 * @example
 * ```html
 * <md-outlined-select label="fruits">
 *   <!-- An empty selected option will give select an "un-filled" state -->
 *   <md-select-option selected></md-select-option>
 *   <md-select-option value="apple" headline="Apple"></md-select-option>
 *   <md-select-option value="banana" headline="Banana"></md-select-option>
 *   <md-select-option value="kiwi" headline="Kiwi"></md-select-option>
 *   <md-select-option value="orange" headline="Orange"></md-select-option>
 *   <md-select-option value="tomato" headline="Tomato"></md-select-option>
 * </md-outlined-select>
 * ```
 *
 * @final
 * @suppress {visibility}
 */
let MdSelectOption = class MdSelectOption extends SelectOptionEl {};
MdSelectOption.styles = [styles$5];
MdSelectOption = __decorate([t$1('md-select-option')], MdSelectOption);

/**
 * @license
 * Copyright 2020 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
const r$1 = o => void 0 === o.strings,
  m = {},
  p = (o, t = m) => o._$AH = t;

/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
const s = (i, t) => {
    const e = i._$AN;
    if (void 0 === e) return false;
    for (const i of e) i._$AO?.(t, false), s(i, t);
    return true;
  },
  o$1 = i => {
    let t, e;
    do {
      if (void 0 === (t = i._$AM)) break;
      e = t._$AN, e.delete(i), i = t;
    } while (0 === e?.size);
  },
  r = i => {
    for (let t; t = i._$AM; i = t) {
      let e = t._$AN;
      if (void 0 === e) t._$AN = e = new Set();else if (e.has(i)) break;
      e.add(i), c$1(t);
    }
  };
function h$1(i) {
  void 0 !== this._$AN ? (o$1(this), this._$AM = i, r(this)) : this._$AM = i;
}
function n$1(i, t = false, e = 0) {
  const r = this._$AH,
    h = this._$AN;
  if (void 0 !== h && 0 !== h.size) if (t) {
    if (Array.isArray(r)) for (let i = e; i < r.length; i++) s(r[i], false), o$1(r[i]);else null != r && (s(r, false), o$1(r));
  } else s(this, i);
}
const c$1 = i => {
  i.type == t.CHILD && (i._$AP ?? (i._$AP = n$1), i._$AQ ?? (i._$AQ = h$1));
};
class f extends i$3 {
  constructor() {
    super(...arguments), this._$AN = void 0;
  }
  _$AT(i, t, e) {
    super._$AT(i, t, e), r(this), this.isConnected = i._$AU;
  }
  _$AO(i, t = true) {
    i !== this.isConnected && (this.isConnected = i, i ? this.reconnected?.() : this.disconnected?.()), t && (s(this, i), o$1(this));
  }
  setValue(t) {
    if (r$1(this._$Ct)) this._$Ct._$AI(t, this);else {
      const i = [...this._$Ct._$AH];
      i[this._$Ci] = t, this._$Ct._$AI(i, this, 0);
    }
  }
  disconnected() {}
  reconnected() {}
}

/**
 * @license
 * Copyright 2020 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
const e$1 = () => new h();
class h {}
const o = new WeakMap(),
  n = e$4(class extends f {
    render(i) {
      return A;
    }
    update(i, [s]) {
      const e = s !== this.G;
      return e && this.rt(void 0), (e || this.lt !== this.ct) && (this.G = s, this.ht = i.options?.host, this.rt(this.ct = i.element)), A;
    }
    rt(t) {
      if (void 0 !== this.G) if (this.isConnected || (t = void 0), "function" == typeof this.G) {
        const i = this.ht ?? globalThis;
        let s = o.get(i);
        void 0 === s && (s = new WeakMap(), o.set(i, s)), void 0 !== s.get(this.G) && this.G.call(this.ht, void 0), s.set(this.G, t), void 0 !== t && this.G.call(this.ht, t);
      } else this.G.value = t;
    }
    get lt() {
      return "function" == typeof this.G ? o.get(this.ht ?? globalThis)?.get(this.G) : this.G?.value;
    }
    disconnected() {
      this.lt === this.ct && this.rt(void 0);
    }
    reconnected() {
      this.rt(this.ct);
    }
  });

/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
function asObject(value) {
  return typeof value === "object" && value !== null ? value : null;
}
function pickNumber(obj, ...keys) {
  for (const k of keys) {
    const v = obj[k];
    if (typeof v === "number" && Number.isFinite(v)) return v;
  }
  return null;
}
function pickString(obj, key) {
  const v = obj[key];
  return typeof v === "string" ? v : null;
}

var __defProp$m = Object.defineProperty;
var __getOwnPropDesc$n = Object.getOwnPropertyDescriptor;
var __decorateClass$p = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$n(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp$m(target, key, result);
  return result;
};
const STREAM_USAGE_LIVE_VIEW = 3;
const END_REASON_USER_HANGUP = 2;
const CAMERA_AV_STREAM_MANAGEMENT_CLUSTER_ID = 1361;
const WEBRTC_TRANSPORT_PROVIDER_CLUSTER_ID = 1363;
const AVSM_FEAT_WMARK = 1 << 6;
const AVSM_FEAT_OSD = 1 << 7;
const AVSM_FEATURE_MAP_ATTR_ID = 65532;
const DEFAULT_MAX_RESOLUTION = {
  width: 1920,
  height: 1080
};
const DEFAULT_MIN_RESOLUTION = {
  width: 640,
  height: 480
};
function parseStreamAllocate(value, idKey) {
  const obj = asObject(value);
  if (!obj) return null;
  return pickNumber(obj, idKey);
}
function parseSnapshotAllocateResponse(value) {
  const obj = asObject(value);
  if (!obj) return null;
  return pickNumber(obj, "snapshotStreamId");
}
const SNAPSHOT_DEFAULTS = {
  resolution: {
    width: 1920,
    height: 1080
  },
  maxFrameRate: 30,
  imageCodec: 0
};
function parseSnapshotCapabilitiesFromList(list) {
  const candidates = list.map(asObject).filter(c => c !== void 0);
  if (candidates.length === 0) return SNAPSHOT_DEFAULTS;
  const parsed = candidates.map(cap => {
    const res = asObject(cap["resolution"] ?? cap["0"]);
    const width = res ? pickNumber(res, "width", "0") : null;
    const height = res ? pickNumber(res, "height", "1") : null;
    const maxFrameRate = pickNumber(cap, "maxFrameRate", "1");
    const imageCodec = pickNumber(cap, "imageCodec", "2");
    return {
      resolution: {
        width: width ?? SNAPSHOT_DEFAULTS.resolution.width,
        height: height ?? SNAPSHOT_DEFAULTS.resolution.height
      },
      maxFrameRate: maxFrameRate ?? SNAPSHOT_DEFAULTS.maxFrameRate,
      imageCodec: imageCodec ?? SNAPSHOT_DEFAULTS.imageCodec
    };
  });
  return parsed.reduce((best, cur) => cur.resolution.width * cur.resolution.height > best.resolution.width * best.resolution.height ? cur : best);
}
function bytesToBase64(bytes) {
  const CHUNK = 8192;
  let binary = "";
  for (let i = 0; i < bytes.length; i += CHUNK) {
    binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));
  }
  return btoa(binary);
}
function parseDataToBase64(data) {
  if (typeof data === "string") return data;
  if (data instanceof Uint8Array) return bytesToBase64(data);
  if (data instanceof ArrayBuffer) return bytesToBase64(new Uint8Array(data));
  if (Array.isArray(data)) return bytesToBase64(new Uint8Array(data));
  throw new Error(`Unexpected snapshot data shape: ${typeof data}`);
}
function parseCaptureSnapshotResponse(value) {
  const obj = asObject(value);
  if (!obj) throw new Error("CaptureSnapshot returned no response");
  const data = obj["data"];
  if (data == null) throw new Error("CaptureSnapshot response missing data field");
  const imageCodec = pickNumber(obj, "imageCodec") ?? 0;
  const res = asObject(obj["resolution"]);
  const width = res ? pickNumber(res, "width") ?? 0 : 0;
  const height = res ? pickNumber(res, "height") ?? 0 : 0;
  return {
    dataBase64: parseDataToBase64(data),
    imageCodec,
    resolution: {
      width,
      height
    }
  };
}
function parseProvideOfferResponse(value) {
  const obj = asObject(value);
  if (!obj) return null;
  const sessionId = pickNumber(obj, "webRtcSessionId");
  if (sessionId === null) return null;
  return {
    webRtcSessionId: sessionId,
    videoStreamId: parseStreamAllocate(value, "videoStreamId"),
    audioStreamId: parseStreamAllocate(value, "audioStreamId")
  };
}
let WebRtcStreamView = class extends i$4 {
  constructor() {
    super(...arguments);
    this.resolution = null;
    this.watermarkEnabled = false;
    this.osdEnabled = false;
    this._state = "idle";
    this._errorMessage = null;
    this.snapshotResolution = null;
    this._snapshotStreamId = null;
    this._snapshotResolution = null;
    /** True when we allocated this stream ourselves and must Deallocate it on stop. False when reusing an existing allocation. */
    this._videoStreamOwned = false;
    this._audioStreamOwned = false;
    this._snapshotStreamOwned = false;
    this._pc = null;
    this._localIceQueue = [];
    this._answerReceived = false;
    this._webRtcSessionId = null;
    this._videoStreamId = null;
    this._audioStreamId = null;
    this._unsubscribe = null;
    this._stopping = false;
    this._endReceivedFromPeer = false;
    this._preSessionQueue = [];
  }
  get state() {
    return this._state;
  }
  get videoStreamId() {
    return this._videoStreamId;
  }
  get muted() {
    return this._video?.muted ?? true;
  }
  setMuted(muted) {
    if (this._video) this._video.muted = muted;
  }
  disconnectedCallback() {
    super.disconnectedCallback();
    void this.deallocateSnapshot();
    void this.stop();
  }
  render() {
    return b`
            <video
                autoplay
                playsinline
                muted
                disablepictureinpicture
                disableremoteplayback
                ?hidden=${this._state !== "streaming"}
            ></video>
            ${this._state === "idle" ? b`<div class="placeholder">
                      <ha-svg-icon class="placeholder-icon" .path=${mdiVideoOutline}></ha-svg-icon>
                      <div class="placeholder-text">Click <b>Start</b> to begin streaming</div>
                  </div>` : null}
            ${this._state === "connecting" ? b`<div class="placeholder">
                      <div class="spinner"></div>
                      <div class="placeholder-text">Connecting…</div>
                  </div>` : null}
            ${this._state === "error" ? b`<div class="placeholder error">
                      <ha-svg-icon class="placeholder-icon" .path=${mdiAlertCircleOutline}></ha-svg-icon>
                      <div class="placeholder-text">${this._errorMessage ?? "Stream error"}</div>
                  </div>` : null}
        `;
  }
  async start() {
    if (!this.client) throw new Error("Matter client not available");
    if (this._state === "connecting" || this._state === "streaming") return;
    this._fireStateChange("connecting", null);
    this._answerReceived = false;
    this._localIceQueue = [];
    this._stopping = false;
    this._endReceivedFromPeer = false;
    this._preSessionQueue = [];
    try {
      const pc = new RTCPeerConnection({
        iceServers: []
      });
      this._pc = pc;
      pc.addTransceiver("video", {
        direction: "recvonly"
      });
      pc.addTransceiver("audio", {
        direction: "recvonly"
      });
      pc.onicecandidate = ev => {
        if (ev.candidate === null) {
          console.log("[webrtc-stream-view] local ICE gathering complete");
          return;
        }
        console.log("[webrtc-stream-view] local ICE candidate", ev.candidate.candidate, {
          queued: !this._answerReceived,
          queueDepth: this._localIceQueue.length
        });
        if (!this._answerReceived) {
          this._localIceQueue.push(ev.candidate);
          return;
        }
        void this._sendLocalIceCandidates([ev.candidate]);
      };
      pc.oniceconnectionstatechange = () => {
        console.log("[webrtc-stream-view] iceConnectionState ->", pc.iceConnectionState);
      };
      pc.onconnectionstatechange = () => {
        console.log("[webrtc-stream-view] connectionState ->", pc.connectionState);
      };
      pc.onsignalingstatechange = () => {
        console.log("[webrtc-stream-view] signalingState ->", pc.signalingState);
      };
      pc.ontrack = ev => {
        console.log("[webrtc-stream-view] ontrack", {
          kind: ev.track.kind,
          readyState: ev.track.readyState,
          streams: ev.streams.length
        });
        const video = this._video;
        if (!video) {
          console.warn("[webrtc-stream-view] ontrack fired but <video> query is null");
          return;
        }
        const stream = ev.streams[0];
        if (!stream) return;
        if (video.srcObject !== stream) {
          video.srcObject = stream;
        }
      };
      const minResolution = this.resolution ?? DEFAULT_MIN_RESOLUTION;
      const maxResolution = this.resolution ?? DEFAULT_MAX_RESOLUTION;
      const avsmFeatures = this._readAvsmFeatures();
      const videoAllocPayload = {
        streamUsage: STREAM_USAGE_LIVE_VIEW,
        videoCodec: 0,
        minFrameRate: 30,
        maxFrameRate: 120,
        minResolution,
        maxResolution,
        minBitRate: 1e4,
        maxBitRate: 1e4,
        keyFrameInterval: 4e3
      };
      if (avsmFeatures.wmark) videoAllocPayload.watermarkEnabled = this.watermarkEnabled;
      if (avsmFeatures.osd) videoAllocPayload.osdEnabled = this.osdEnabled;
      const reusedVideoId = this._findMatchingVideoStream({
        streamUsage: STREAM_USAGE_LIVE_VIEW,
        videoCodec: 0,
        minRes: minResolution,
        maxRes: maxResolution,
        watermarkEnabled: avsmFeatures.wmark ? this.watermarkEnabled : void 0,
        osdEnabled: avsmFeatures.osd ? this.osdEnabled : void 0
      });
      let videoAlloc = null;
      if (reusedVideoId !== null) {
        console.info("[webrtc-stream-view] reusing existing video stream", reusedVideoId);
        this._videoStreamId = reusedVideoId;
        this._videoStreamOwned = false;
      } else {
        try {
          videoAlloc = await this.client.deviceCommand(this.nodeId, this.endpointId, CAMERA_AV_STREAM_MANAGEMENT_CLUSTER_ID, "VideoStreamAllocate", videoAllocPayload);
        } catch (err) {
          const message = err instanceof Error ? err.message : String(err);
          const isResourceExhausted = message.includes("Resource exhausted") || message.includes("(code 137)");
          if (!isResourceExhausted || this._snapshotStreamId === null) throw err;
          console.info("[webrtc-stream-view] VideoStreamAllocate ResourceExhausted; freeing snapshot stream and retrying");
          await this.deallocateSnapshot();
          videoAlloc = await this.client.deviceCommand(this.nodeId, this.endpointId, CAMERA_AV_STREAM_MANAGEMENT_CLUSTER_ID, "VideoStreamAllocate", videoAllocPayload);
        }
        const videoStreamId = parseStreamAllocate(videoAlloc, "videoStreamId");
        if (videoStreamId === null) {
          throw new Error("VideoStreamAllocate did not return a videoStreamId");
        }
        this._videoStreamId = videoStreamId;
        this._videoStreamOwned = true;
      }
      const audioWant = {
        streamUsage: STREAM_USAGE_LIVE_VIEW,
        audioCodec: 0,
        channelCount: 1,
        sampleRate: 48e3
      };
      const reusedAudioId = this._findMatchingAudioStream(audioWant);
      if (reusedAudioId !== null) {
        console.info("[webrtc-stream-view] reusing existing audio stream", reusedAudioId);
        this._audioStreamId = reusedAudioId;
        this._audioStreamOwned = false;
      } else {
        try {
          const audioAlloc = await this.client.deviceCommand(this.nodeId, this.endpointId, CAMERA_AV_STREAM_MANAGEMENT_CLUSTER_ID, "AudioStreamAllocate", {
            ...audioWant,
            bitRate: 2e4,
            bitDepth: 24
          });
          this._audioStreamId = parseStreamAllocate(audioAlloc, "audioStreamId");
          this._audioStreamOwned = this._audioStreamId !== null;
        } catch (err) {
          console.info("AudioStreamAllocate failed; continuing video-only", err);
          this._audioStreamId = null;
        }
      }
      const offer = await pc.createOffer();
      await pc.setLocalDescription(offer);
      this._unsubscribe = this.client.addWebRtcCallbackListener(data => void this._onWebRtcCallback(data));
      const sdp = pc.localDescription?.sdp;
      if (!sdp) {
        throw new Error("Failed to create local SDP offer");
      }
      console.log("[webrtc-stream-view] sending ProvideOffer", {
        nodeId: this.nodeId,
        endpointId: this.endpointId,
        videoStreamId: this._videoStreamId,
        audioStreamId: this._audioStreamId,
        streamUsage: STREAM_USAGE_LIVE_VIEW,
        sdpLength: sdp.length
      });
      const offerResponse = await this.client.sendWebRtcProviderCommand(this.nodeId, this.endpointId, "ProvideOffer", {
        webRtcSessionId: null,
        sdp,
        streamUsage: STREAM_USAGE_LIVE_VIEW,
        videoStreamId: this._videoStreamId,
        audioStreamId: this._audioStreamId
      });
      console.log("[webrtc-stream-view] ProvideOffer response", offerResponse);
      const parsed = parseProvideOfferResponse(offerResponse);
      if (parsed === null) {
        throw new Error("ProvideOffer response missing webRtcSessionId");
      }
      this._webRtcSessionId = parsed.webRtcSessionId;
      console.log("[webrtc-stream-view] webRtcSessionId established", this._webRtcSessionId);
      const buffered = this._preSessionQueue;
      this._preSessionQueue = [];
      for (const ev of buffered) {
        if (ev.webrtc_session_id === parsed.webRtcSessionId) {
          await this._onWebRtcCallback(ev);
        }
      }
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err);
      this._fireStateChange("error", message);
      await this.stop();
    }
  }
  async stop() {
    if (this._stopping) return;
    this._stopping = true;
    if (this._unsubscribe) {
      this._unsubscribe();
      this._unsubscribe = null;
    }
    const sessionId = this._webRtcSessionId;
    const initiatedEnd = sessionId !== null && !this._endReceivedFromPeer;
    if (initiatedEnd) {
      try {
        await this.client?.deviceCommand(this.nodeId, this.endpointId, WEBRTC_TRANSPORT_PROVIDER_CLUSTER_ID, "EndSession", {
          webRtcSessionId: sessionId,
          reason: END_REASON_USER_HANGUP
        });
      } catch (err) {
        console.warn("EndSession failed during stop", err);
      }
    }
    if (this._videoStreamId !== null && this._videoStreamOwned) {
      try {
        await this.client?.deviceCommand(this.nodeId, this.endpointId, CAMERA_AV_STREAM_MANAGEMENT_CLUSTER_ID, "VideoStreamDeallocate", {
          videoStreamId: this._videoStreamId
        });
      } catch (err) {
        console.warn("VideoStreamDeallocate failed during stop", err);
      }
    }
    if (this._audioStreamId !== null && this._audioStreamOwned) {
      try {
        await this.client?.deviceCommand(this.nodeId, this.endpointId, CAMERA_AV_STREAM_MANAGEMENT_CLUSTER_ID, "AudioStreamDeallocate", {
          audioStreamId: this._audioStreamId
        });
      } catch (err) {
        console.warn("AudioStreamDeallocate failed during stop", err);
      }
    }
    this._videoStreamOwned = false;
    this._audioStreamOwned = false;
    await this.deallocateSnapshot();
    const video = this._video;
    if (video && video.srcObject) {
      video.srcObject = null;
    }
    if (this._pc) {
      try {
        this._pc.close();
      } catch {}
      this._pc = null;
    }
    this._localIceQueue = [];
    this._answerReceived = false;
    this._webRtcSessionId = null;
    this._videoStreamId = null;
    this._audioStreamId = null;
    this._endReceivedFromPeer = false;
    this._preSessionQueue = [];
    if (this._state !== "idle" && this._state !== "error") {
      this._fireStateChange("idle", null);
    }
    this._stopping = false;
  }
  async takeSnapshot() {
    if (!this.client) throw new Error("Matter client not available");
    const streamId = await this._ensureSnapshotStream();
    const requestedResolution = this._snapshotResolution ?? SNAPSHOT_DEFAULTS.resolution;
    const response = await this.client.deviceCommand(this.nodeId, this.endpointId, CAMERA_AV_STREAM_MANAGEMENT_CLUSTER_ID, "CaptureSnapshot", {
      snapshotStreamId: streamId,
      requestedResolution
    });
    const parsed = parseCaptureSnapshotResponse(response);
    const mimeType = parsed.imageCodec === 0 ? "jpeg" : "png";
    return {
      dataUri: `data:image/${mimeType};base64,${parsed.dataBase64}`,
      resolution: parsed.resolution
    };
  }
  _readAvsmFeatures() {
    const node = this.client?.nodes[String(this.nodeId)];
    const raw = node?.attributes[`${this.endpointId}/${CAMERA_AV_STREAM_MANAGEMENT_CLUSTER_ID}/${AVSM_FEATURE_MAP_ATTR_ID}`];
    const bits = typeof raw === "number" ? raw : 0;
    return {
      wmark: (bits & AVSM_FEAT_WMARK) !== 0,
      osd: (bits & AVSM_FEAT_OSD) !== 0
    };
  }
  async deallocateSnapshot() {
    if (this._snapshotStreamId === null) return;
    const id = this._snapshotStreamId;
    const wasOwned = this._snapshotStreamOwned;
    this._snapshotStreamId = null;
    this._snapshotResolution = null;
    this._snapshotStreamOwned = false;
    if (!wasOwned) return;
    try {
      await this.client?.deviceCommand(this.nodeId, this.endpointId, CAMERA_AV_STREAM_MANAGEMENT_CLUSTER_ID, "SnapshotStreamDeallocate", {
        snapshotStreamId: id
      });
    } catch (e) {
      console.warn("SnapshotStreamDeallocate failed (continuing):", e);
    }
  }
  /**
   * Search AllocatedVideoStreams (attr 0x000F) for an entry whose advertised
   * capability ranges cover our requested params. Spec §11.2.1.2.1 says the
   * camera SHALL reuse a matching stream — reading first avoids creating
   * duplicates when a server's reuse logic is buggy or matching is too strict.
   */
  _findMatchingVideoStream(want) {
    const node = this.client?.nodes[String(this.nodeId)];
    const list = node?.attributes[`${this.endpointId}/${CAMERA_AV_STREAM_MANAGEMENT_CLUSTER_ID}/15`];
    if (!Array.isArray(list)) return null;
    for (const item of list) {
      const obj = asObject(item);
      if (!obj) continue;
      const streamUsage = pickNumber(obj, "streamUsage", "1");
      const videoCodec = pickNumber(obj, "videoCodec", "2");
      if (streamUsage !== want.streamUsage || videoCodec !== want.videoCodec) continue;
      const minRes = asObject(obj["minResolution"] ?? obj["5"]);
      const maxRes = asObject(obj["maxResolution"] ?? obj["6"]);
      if (!minRes || !maxRes) continue;
      const eMinW = pickNumber(minRes, "width", "0") ?? 0;
      const eMinH = pickNumber(minRes, "height", "1") ?? 0;
      const eMaxW = pickNumber(maxRes, "width", "0") ?? 0;
      const eMaxH = pickNumber(maxRes, "height", "1") ?? 0;
      if (eMinW > want.minRes.width || eMaxW < want.maxRes.width) continue;
      if (eMinH > want.minRes.height || eMaxH < want.maxRes.height) continue;
      if (want.watermarkEnabled !== void 0) {
        const v = obj["watermarkEnabled"] ?? obj["10"];
        if (v !== want.watermarkEnabled) continue;
      }
      if (want.osdEnabled !== void 0) {
        const v = obj["osdEnabled"] ?? obj["11"];
        if (v !== want.osdEnabled) continue;
      }
      const id = pickNumber(obj, "videoStreamId", "0");
      if (id !== null) return id;
    }
    return null;
  }
  _findMatchingAudioStream(want) {
    const node = this.client?.nodes[String(this.nodeId)];
    const list = node?.attributes[`${this.endpointId}/${CAMERA_AV_STREAM_MANAGEMENT_CLUSTER_ID}/16`];
    if (!Array.isArray(list)) return null;
    for (const item of list) {
      const obj = asObject(item);
      if (!obj) continue;
      const streamUsage = pickNumber(obj, "streamUsage", "1");
      const audioCodec = pickNumber(obj, "audioCodec", "2");
      const channelCount = pickNumber(obj, "channelCount", "3");
      const sampleRate = pickNumber(obj, "sampleRate", "4");
      if (streamUsage !== want.streamUsage || audioCodec !== want.audioCodec || channelCount !== want.channelCount || sampleRate !== want.sampleRate) continue;
      const id = pickNumber(obj, "audioStreamId", "0");
      if (id !== null) return id;
    }
    return null;
  }
  _findMatchingSnapshotStream(want) {
    const node = this.client?.nodes[String(this.nodeId)];
    const list = node?.attributes[`${this.endpointId}/${CAMERA_AV_STREAM_MANAGEMENT_CLUSTER_ID}/17`];
    if (!Array.isArray(list)) return null;
    for (const item of list) {
      const obj = asObject(item);
      if (!obj) continue;
      const imageCodec = pickNumber(obj, "imageCodec", "1");
      if (imageCodec !== want.imageCodec) continue;
      const minRes = asObject(obj["minResolution"] ?? obj["3"]);
      const maxRes = asObject(obj["maxResolution"] ?? obj["4"]);
      if (!minRes || !maxRes) continue;
      const eMinW = pickNumber(minRes, "width", "0") ?? 0;
      const eMinH = pickNumber(minRes, "height", "1") ?? 0;
      const eMaxW = pickNumber(maxRes, "width", "0") ?? 0;
      const eMaxH = pickNumber(maxRes, "height", "1") ?? 0;
      if (eMinW > want.resolution.width || eMaxW < want.resolution.width) continue;
      if (eMinH > want.resolution.height || eMaxH < want.resolution.height) continue;
      if (want.watermarkEnabled !== void 0) {
        const v = obj["watermarkEnabled"] ?? obj["9"];
        if (v !== want.watermarkEnabled) continue;
      }
      if (want.osdEnabled !== void 0) {
        const v = obj["osdEnabled"] ?? obj["10"];
        if (v !== want.osdEnabled) continue;
      }
      const id = pickNumber(obj, "snapshotStreamId", "0");
      const resolution = {
        width: eMaxW,
        height: eMaxH
      };
      if (id !== null) return {
        id,
        resolution
      };
    }
    return null;
  }
  async _ensureSnapshotStream() {
    if (this._snapshotStreamId !== null) return this._snapshotStreamId;
    if (!this.client) throw new Error("Matter client not available");
    const node = this.client.nodes[String(this.nodeId)];
    const capsRaw = node?.attributes[`${this.endpointId}/${CAMERA_AV_STREAM_MANAGEMENT_CLUSTER_ID}/10`];
    const cap = Array.isArray(capsRaw) && capsRaw.length > 0 ? parseSnapshotCapabilitiesFromList(capsRaw) : SNAPSHOT_DEFAULTS;
    const targetResolution = this.snapshotResolution ?? cap.resolution;
    const avsmFeatures = this._readAvsmFeatures();
    const reused = this._findMatchingSnapshotStream({
      imageCodec: cap.imageCodec,
      resolution: targetResolution,
      watermarkEnabled: avsmFeatures.wmark ? this.watermarkEnabled : void 0,
      osdEnabled: avsmFeatures.osd ? this.osdEnabled : void 0
    });
    if (reused !== null) {
      console.info("[webrtc-stream-view] reusing existing snapshot stream", reused.id);
      this._snapshotStreamId = reused.id;
      this._snapshotResolution = reused.resolution;
      this._snapshotStreamOwned = false;
      return reused.id;
    }
    const snapshotAllocPayload = {
      imageCodec: cap.imageCodec,
      maxFrameRate: cap.maxFrameRate,
      minResolution: targetResolution,
      maxResolution: targetResolution,
      quality: 90
    };
    if (avsmFeatures.wmark) snapshotAllocPayload.watermarkEnabled = this.watermarkEnabled;
    if (avsmFeatures.osd) snapshotAllocPayload.osdEnabled = this.osdEnabled;
    const response = await this.client.deviceCommand(this.nodeId, this.endpointId, CAMERA_AV_STREAM_MANAGEMENT_CLUSTER_ID, "SnapshotStreamAllocate", snapshotAllocPayload);
    const snapshotStreamId = parseSnapshotAllocateResponse(response);
    if (snapshotStreamId === null) {
      throw new Error("SnapshotStreamAllocate did not return a snapshot stream id");
    }
    this._snapshotStreamId = snapshotStreamId;
    this._snapshotResolution = targetResolution;
    this._snapshotStreamOwned = true;
    return this._snapshotStreamId;
  }
  async _onWebRtcCallback(data) {
    console.log("[webrtc-stream-view] webrtc_callback received", {
      event_type: data.event_type,
      webrtc_session_id: data.webrtc_session_id,
      node_id: data.node_id,
      endpoint_id: data.endpoint_id,
      fabric_index: data.fabric_index,
      myNodeId: this.nodeId,
      myEndpointId: this.endpointId,
      mySessionId: this._webRtcSessionId
    });
    if (this._webRtcSessionId === null) {
      if (String(data.node_id) === String(this.nodeId) && data.endpoint_id === this.endpointId) {
        this._preSessionQueue.push(data);
        console.log("[webrtc-stream-view] queued pre-session callback");
      } else {
        console.log("[webrtc-stream-view] dropped pre-session callback (different node/endpoint)");
      }
      return;
    }
    if (data.webrtc_session_id !== this._webRtcSessionId) {
      console.log("[webrtc-stream-view] dropped: session id mismatch");
      return;
    }
    if (String(data.node_id) !== String(this.nodeId)) {
      console.log("[webrtc-stream-view] dropped: node id mismatch");
      return;
    }
    if (data.endpoint_id !== this.endpointId) {
      console.log("[webrtc-stream-view] dropped: endpoint id mismatch");
      return;
    }
    switch (data.event_type) {
      case "answer":
        void this._handleAnswer(data.data);
        return;
      case "ice_candidates":
        void this._handleRemoteIceCandidates(data.data);
        return;
      case "end":
        this._handleEnd(data.data);
        return;
      case "offer":
        console.info("WebRTC re-offer received; renegotiation unsupported", data);
        return;
    }
  }
  async _handleAnswer(data) {
    if (!this._pc || !data) return;
    try {
      const sdp = this._sanitizeAnswerSdp(data.sdp);
      await this._pc.setRemoteDescription({
        type: "answer",
        sdp
      });
      this._answerReceived = true;
      const queue = this._localIceQueue;
      this._localIceQueue = [];
      if (queue.length > 0) {
        await this._sendLocalIceCandidates(queue);
      }
      this._fireStateChange("streaming", null);
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err);
      this._fireStateChange("error", `Failed to apply answer: ${message}`);
      await this.stop();
    }
  }
  /**
   * Some Matter cameras (notably the matter.js camera-controller example app) answer
   * `a=sendrecv` on audio m-lines even when our offer is `a=recvonly`. Per RFC 3264 the
   * only valid mirror of recvonly is sendonly; sendrecv triggers
   * "Answer tried to set recv when offer did not set send" in setRemoteDescription.
   * We add both video and audio transceivers as recvonly, so any sendrecv answer must
   * be coerced to sendonly to apply cleanly.
   */
  _sanitizeAnswerSdp(sdp) {
    const lines = sdp.split(/\r\n|\n/);
    let inMediaSection = false;
    let mutated = false;
    for (let i = 0; i < lines.length; i++) {
      const line = lines[i];
      if (line.startsWith("m=")) {
        inMediaSection = true;
        continue;
      }
      if (inMediaSection && line === "a=sendrecv") {
        lines[i] = "a=sendonly";
        mutated = true;
      }
    }
    if (mutated) {
      console.warn("[webrtc-stream-view] coerced a=sendrecv -> a=sendonly in answer (offer was recvonly on all m-lines)");
    }
    return lines.join("\r\n");
  }
  async _handleRemoteIceCandidates(data) {
    if (!this._pc || !data) return;
    for (const c of data.ice_candidates) {
      try {
        await this._pc.addIceCandidate({
          candidate: c.candidate,
          sdpMid: c.sdpMid ?? void 0,
          sdpMLineIndex: c.sdpMLineIndex ?? void 0
        });
      } catch (err) {
        console.warn("Failed to add remote ICE candidate", err, c);
      }
    }
  }
  _handleEnd(_data) {
    this._endReceivedFromPeer = true;
    void this.stop();
  }
  async _sendLocalIceCandidates(candidates) {
    if (!this.client || this._webRtcSessionId === null || candidates.length === 0) return;
    try {
      await this.client.deviceCommand(this.nodeId, this.endpointId, WEBRTC_TRANSPORT_PROVIDER_CLUSTER_ID, "ProvideICECandidates", {
        webRtcSessionId: this._webRtcSessionId,
        ICECandidates: candidates.map(c => ({
          candidate: c.candidate,
          SDPMid: c.sdpMid,
          SDPMLineIndex: c.sdpMLineIndex
        }))
      });
    } catch (err) {
      console.warn("ProvideICECandidates failed", err);
    }
  }
  _fireStateChange(state2, errorMessage) {
    this._state = state2;
    this._errorMessage = errorMessage;
    this.dispatchEvent(new CustomEvent("streamstate", {
      detail: {
        state: state2,
        errorMessage
      },
      bubbles: false,
      composed: false
    }));
  }
};
WebRtcStreamView.styles = i$7`
        :host {
            display: flex;
            flex-direction: column;
            width: 100%;
            height: 100%;
            background: black;
            position: relative;
        }
        video {
            display: block;
            flex: 1 1 0;
            min-height: 0;
            width: 100%;
            object-fit: contain;
            background: black;
        }
        video[hidden] {
            display: none;
        }
        .placeholder {
            flex: 1 1 0;
            min-height: 0;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            gap: 16px;
            color: rgba(255, 255, 255, 0.6);
            text-align: center;
            padding: 24px;
        }
        .placeholder-icon {
            --icon-primary-color: rgba(255, 255, 255, 0.3);
            width: 64px;
            height: 64px;
        }
        .placeholder-text {
            font-size: 0.95rem;
        }
        .placeholder-text b {
            color: rgba(255, 255, 255, 0.85);
            font-weight: 500;
        }
        .placeholder.error {
            color: var(--danger-color, #ff6b6b);
        }
        .placeholder.error .placeholder-icon {
            --icon-primary-color: var(--danger-color, #ff6b6b);
        }
        .spinner {
            width: 32px;
            height: 32px;
            border: 3px solid rgba(255, 255, 255, 0.15);
            border-top-color: rgba(255, 255, 255, 0.7);
            border-radius: 50%;
            animation: spin 0.9s linear infinite;
        }
        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }
        @media (prefers-reduced-motion: reduce) {
            .spinner {
                animation: none;
            }
        }
    `;
__decorateClass$p([c$5({
  context: clientContext,
  subscribe: true
}), n$5({
  attribute: false
})], WebRtcStreamView.prototype, "client", 2);
__decorateClass$p([n$5({
  attribute: false
})], WebRtcStreamView.prototype, "nodeId", 2);
__decorateClass$p([n$5({
  type: Number
})], WebRtcStreamView.prototype, "endpointId", 2);
__decorateClass$p([n$5({
  type: Object
})], WebRtcStreamView.prototype, "resolution", 2);
__decorateClass$p([n$5({
  type: Boolean
})], WebRtcStreamView.prototype, "watermarkEnabled", 2);
__decorateClass$p([n$5({
  type: Boolean
})], WebRtcStreamView.prototype, "osdEnabled", 2);
__decorateClass$p([r$3()], WebRtcStreamView.prototype, "_state", 2);
__decorateClass$p([r$3()], WebRtcStreamView.prototype, "_errorMessage", 2);
__decorateClass$p([n$5({
  attribute: false
})], WebRtcStreamView.prototype, "snapshotResolution", 2);
__decorateClass$p([e$6("video")], WebRtcStreamView.prototype, "_video", 2);
WebRtcStreamView = __decorateClass$p([t$1("webrtc-stream-view")], WebRtcStreamView);

/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
const AVSUM_CLUSTER_ID = 1362;
const ATTR_MPTZ_POSITION = 0;
const ATTR_MAX_PRESETS = 1;
const ATTR_MPTZ_PRESETS = 2;
const ATTR_DPTZ_STREAMS = 3;
const ATTR_ZOOM_MAX = 4;
const ATTR_TILT_MIN = 5;
const ATTR_TILT_MAX = 6;
const ATTR_PAN_MIN = 7;
const ATTR_PAN_MAX = 8;
const ATTR_MOVEMENT_STATE = 9;
const ATTR_FEATURE_MAP = 65532;
const AVSUM_FEAT_DPTZ = 1 << 0;
const AVSUM_FEAT_MPAN = 1 << 1;
const AVSUM_FEAT_MTILT = 1 << 2;
const AVSUM_FEAT_MZOOM = 1 << 3;
const AVSUM_FEAT_MPRESETS = 1 << 4;
function readAttr$1(node, endpoint, attrId) {
  return node.attributes[`${endpoint}/${AVSUM_CLUSTER_ID}/${attrId}`];
}
function readFeatures(node, endpoint) {
  const fm = readAttr$1(node, endpoint, ATTR_FEATURE_MAP);
  const bits = typeof fm === "number" ? fm : 0;
  return {
    dptz: (bits & AVSUM_FEAT_DPTZ) !== 0,
    mPan: (bits & AVSUM_FEAT_MPAN) !== 0,
    mTilt: (bits & AVSUM_FEAT_MTILT) !== 0,
    mZoom: (bits & AVSUM_FEAT_MZOOM) !== 0,
    mPresets: (bits & AVSUM_FEAT_MPRESETS) !== 0
  };
}
function pickFieldNumber(obj, named, tagId) {
  return pickNumber(obj, named) ?? pickNumber(obj, tagId);
}
function readPosition(node, endpoint) {
  const obj = asObject(readAttr$1(node, endpoint, ATTR_MPTZ_POSITION));
  if (!obj) return {
    pan: null,
    tilt: null,
    zoom: null
  };
  return {
    pan: pickFieldNumber(obj, "pan", "0"),
    tilt: pickFieldNumber(obj, "tilt", "1"),
    zoom: pickFieldNumber(obj, "zoom", "2")
  };
}
function readRanges(node, endpoint) {
  const v = id => {
    const x = readAttr$1(node, endpoint, id);
    return typeof x === "number" ? x : null;
  };
  return {
    panMin: v(ATTR_PAN_MIN),
    panMax: v(ATTR_PAN_MAX),
    tiltMin: v(ATTR_TILT_MIN),
    tiltMax: v(ATTR_TILT_MAX),
    zoomMax: v(ATTR_ZOOM_MAX)
  };
}
function readMovementState(node, endpoint) {
  const v = readAttr$1(node, endpoint, ATTR_MOVEMENT_STATE);
  if (v === 0) return "idle";
  if (v === 1) return "moving";
  return "unknown";
}
function readPresets(node, endpoint) {
  const max = readAttr$1(node, endpoint, ATTR_MAX_PRESETS);
  const raw = readAttr$1(node, endpoint, ATTR_MPTZ_PRESETS);
  const items = new Array();
  if (Array.isArray(raw)) {
    for (const item of raw) {
      const obj = asObject(item);
      if (!obj) continue;
      const presetId = pickFieldNumber(obj, "presetId", "0");
      const name = pickString(obj, "name") ?? pickString(obj, "1");
      const settings = asObject(obj["settings"] ?? obj["2"]);
      if (presetId === null || name === null) continue;
      items.push({
        presetId,
        name,
        settings: {
          pan: settings ? pickFieldNumber(settings, "pan", "0") : null,
          tilt: settings ? pickFieldNumber(settings, "tilt", "1") : null,
          zoom: settings ? pickFieldNumber(settings, "zoom", "2") : null
        }
      });
    }
  }
  return {
    items,
    max: typeof max === "number" ? max : 0
  };
}
function readDptzStreams(node, endpoint) {
  const raw = readAttr$1(node, endpoint, ATTR_DPTZ_STREAMS);
  if (!Array.isArray(raw)) return [];
  const out = new Array();
  for (const item of raw) {
    const obj = asObject(item);
    if (!obj) continue;
    const id = pickFieldNumber(obj, "videoStreamId", "0");
    if (id !== null) out.push({
      videoStreamId: id
    });
  }
  return out;
}
async function relativeMove(client, nodeId, endpoint, delta) {
  await client.deviceCommand(nodeId, endpoint, AVSUM_CLUSTER_ID, "MPTZRelativeMove", delta);
}
async function moveToPreset(client, nodeId, endpoint, presetId) {
  await client.deviceCommand(nodeId, endpoint, AVSUM_CLUSTER_ID, "MPTZMoveToPreset", {
    presetID: presetId
  });
}
async function savePreset(client, nodeId, endpoint, name, presetId) {
  const payload = {
    name
  };
  if (presetId !== void 0) payload.presetID = presetId;
  await client.deviceCommand(nodeId, endpoint, AVSUM_CLUSTER_ID, "MPTZSavePreset", payload);
}
async function removePreset(client, nodeId, endpoint, presetId) {
  await client.deviceCommand(nodeId, endpoint, AVSUM_CLUSTER_ID, "MPTZRemovePreset", {
    presetID: presetId
  });
}
async function dptzRelativeMove(client, nodeId, endpoint, streamId, delta) {
  await client.deviceCommand(nodeId, endpoint, AVSUM_CLUSTER_ID, "DPTZRelativeMove", {
    videoStreamID: streamId,
    ...delta
  });
}
function hasAvsumOnEndpoint(node, endpoint) {
  const prefix = `${endpoint}/${AVSUM_CLUSTER_ID}/`;
  return Object.keys(node.attributes).some(k => k.startsWith(prefix));
}

var __defProp$l = Object.defineProperty;
var __getOwnPropDesc$m = Object.getOwnPropertyDescriptor;
var __decorateClass$o = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$m(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp$l(target, key, result);
  return result;
};
let AvsumPtzStrip = class extends i$4 {
  constructor() {
    super(...arguments);
    this.activeVideoStreamId = null;
    this.sensorSize = null;
    this._mode = "mech";
    this._toast = null;
  }
  get _node() {
    if (!this.client) return null;
    return this.client.nodes[String(this.nodeId)] ?? null;
  }
  connectedCallback() {
    super.connectedCallback();
    if (this.client) {
      this._unsubscribeNodes = this.client.addEventListener("nodes_changed", () => this.requestUpdate());
    }
  }
  disconnectedCallback() {
    super.disconnectedCallback();
    this._unsubscribeNodes?.();
    if (this._toastTimer) {
      clearTimeout(this._toastTimer);
      this._toastTimer = void 0;
    }
  }
  render() {
    const node = this._node;
    if (!node || !hasAvsumOnEndpoint(node, this.endpointId)) return A;
    const features = readFeatures(node, this.endpointId);
    if (!features.mPan && !features.mTilt && !features.mZoom && !features.dptz && !features.mPresets) return A;
    const hasMech = features.mPan || features.mTilt || features.mZoom;
    const effective = hasMech && features.dptz ? this._mode : hasMech ? "mech" : "digital";
    const pos = readPosition(node, this.endpointId);
    const movement = readMovementState(node, this.endpointId);
    const presets = features.mPresets ? readPresets(node, this.endpointId).items : [];
    return b`
            <div class="strip">
                ${hasMech || features.dptz ? b`<div class="group movement">
                          <div class="dpad">
                              <span></span>
                              <md-icon-button
                                  ?disabled=${this._isDisabled(effective, "tilt", features, movement)}
                                  title="Tilt up"
                                  @click=${handleAsyncEvent(e => this._move(effective, "tilt", this._step(e, 10)))}
                              >
                                  <ha-svg-icon .path=${mdiArrowUp}></ha-svg-icon>
                              </md-icon-button>
                              <span></span>
                              <md-icon-button
                                  ?disabled=${this._isDisabled(effective, "pan", features, movement)}
                                  title="Pan left"
                                  @click=${handleAsyncEvent(e => this._move(effective, "pan", this._step(e, -10)))}
                              >
                                  <ha-svg-icon .path=${mdiArrowLeft}></ha-svg-icon>
                              </md-icon-button>
                              <span></span>
                              <md-icon-button
                                  ?disabled=${this._isDisabled(effective, "pan", features, movement)}
                                  title="Pan right"
                                  @click=${handleAsyncEvent(e => this._move(effective, "pan", this._step(e, 10)))}
                              >
                                  <ha-svg-icon .path=${mdiArrowRight}></ha-svg-icon>
                              </md-icon-button>
                              <span></span>
                              <md-icon-button
                                  ?disabled=${this._isDisabled(effective, "tilt", features, movement)}
                                  title="Tilt down"
                                  @click=${handleAsyncEvent(e => this._move(effective, "tilt", this._step(e, -10)))}
                              >
                                  <ha-svg-icon .path=${mdiArrowDown}></ha-svg-icon>
                              </md-icon-button>
                              <span></span>
                          </div>
                          <div class="zoom">
                              <md-icon-button
                                  ?disabled=${this._isDisabled(effective, "zoom", features, movement)}
                                  title="Zoom in"
                                  @click=${handleAsyncEvent(e => this._move(effective, "zoom", this._step(e, 10)))}
                              >
                                  <ha-svg-icon .path=${mdiPlus}></ha-svg-icon>
                              </md-icon-button>
                              <md-icon-button
                                  ?disabled=${this._isDisabled(effective, "zoom", features, movement)}
                                  title="Zoom out"
                                  @click=${handleAsyncEvent(e => this._move(effective, "zoom", this._step(e, -10)))}
                              >
                                  <ha-svg-icon .path=${mdiMinus}></ha-svg-icon>
                              </md-icon-button>
                          </div>
                          ${hasMech && features.dptz ? b`<div class="mode-toggle">
                                    <button
                                        class=${this._mode === "mech" ? "active" : ""}
                                        @click=${() => this._mode = "mech"}
                                    >
                                        Mech
                                    </button>
                                    <button
                                        class=${this._mode === "digital" ? "active" : ""}
                                        @click=${() => this._mode = "digital"}
                                    >
                                        Digital
                                    </button>
                                </div>` : A}
                          ${effective === "digital" && this.activeVideoStreamId === null ? b`<span class="mode-hint">Start stream to enable DPTZ</span>` : A}
                      </div>` : A}
                ${features.mPresets && presets.length > 0 ? b`<div class="group presets">
                          ${presets.map(p => b`<button
                                  class="chip"
                                  title="p=${p.settings.pan ?? 0}° · t=${p.settings.tilt ?? 0}° · z=${p.settings.zoom ?? 1}×"
                                  @click=${handleAsync(() => this._handleGoPreset(p.presetId))}
                              >
                                  ${p.name}
                              </button>`)}
                      </div>` : A}
                <div class="group readout">
                    ${features.mPan && pos.pan !== null ? b`<span>Pan ${this._fmt(pos.pan)}°</span>` : A}
                    ${features.mTilt && pos.tilt !== null ? b`<span>Tilt ${this._fmt(pos.tilt)}°</span>` : A}
                    ${features.mZoom && pos.zoom !== null ? b`<span>Zoom ${pos.zoom}×</span>` : A}
                </div>
                ${this._toast ? b`<div class="toast">${this._toast}</div>` : A}
            </div>
        `;
  }
  _fmt(v) {
    return v >= 0 ? `+${v}` : `${v}`;
  }
  _step(e, base) {
    return e.shiftKey ? Math.sign(base) : base;
  }
  _isDisabled(mode, axis, f, movement) {
    if (mode === "mech") {
      if (movement === "moving") return true;
      if (axis === "pan") return !f.mPan;
      if (axis === "tilt") return !f.mTilt;
      return !f.mZoom;
    }
    if (!f.dptz) return true;
    if (this.activeVideoStreamId === null) return true;
    return false;
  }
  async _move(mode, axis, step) {
    if (!this.client) return;
    try {
      if (mode === "mech") {
        const delta = {};
        if (axis === "pan") delta.panDelta = step;else if (axis === "tilt") delta.tiltDelta = step;else delta.zoomDelta = step;
        await relativeMove(this.client, this.nodeId, this.endpointId, delta);
      } else {
        if (this.activeVideoStreamId === null) return;
        const scale = step / 10;
        const dx = this.sensorSize ? Math.round(this.sensorSize.width * 0.1 * scale) : Math.round(100 * scale);
        const dy = this.sensorSize ? Math.round(this.sensorSize.height * 0.1 * scale) : Math.round(100 * scale);
        const delta = {};
        if (axis === "pan") delta.deltaX = dx;else if (axis === "tilt") delta.deltaY = dy;else delta.zoomDelta = step;
        await dptzRelativeMove(this.client, this.nodeId, this.endpointId, this.activeVideoStreamId, delta);
      }
    } catch (err) {
      const msg = err instanceof Error ? err.message.toLowerCase() : String(err).toLowerCase();
      if (msg.includes("busy")) {
        this._toast = "Camera busy";
      } else {
        console.warn("PTZ move failed:", err);
        this._toast = "Move failed";
      }
      this._scheduleToastClear();
    }
  }
  async _handleGoPreset(presetId) {
    if (!this.client) return;
    try {
      await moveToPreset(this.client, this.nodeId, this.endpointId, presetId);
    } catch (err) {
      const msg = err instanceof Error ? err.message.toLowerCase() : String(err).toLowerCase();
      if (msg.includes("busy")) {
        this._toast = "Camera busy";
      } else if (msg.includes("not_found")) {
        this._toast = "Preset removed";
      } else {
        console.warn("Preset move failed:", err);
        this._toast = "Move failed";
      }
      this._scheduleToastClear();
    }
  }
  _scheduleToastClear() {
    if (this._toastTimer) clearTimeout(this._toastTimer);
    this._toastTimer = setTimeout(() => {
      this._toast = null;
    }, 2e3);
  }
};
AvsumPtzStrip.styles = i$7`
        :host {
            display: block;
            color: white;
        }
        .strip {
            background: rgba(0, 0, 0, 0.6);
            padding: 8px 12px;
            display: flex;
            gap: 16px;
            align-items: center;
            flex-wrap: wrap;
        }
        .group {
            display: flex;
            align-items: center;
            gap: 8px;
            padding-right: 16px;
            border-right: 1px solid rgba(255, 255, 255, 0.15);
        }
        .group:last-child {
            border-right: none;
        }
        .movement {
            gap: 12px;
        }
        .dpad {
            display: grid;
            grid-template-columns: 32px 32px 32px;
            grid-template-rows: 32px 32px 32px;
            gap: 2px;
        }
        .zoom {
            display: flex;
            flex-direction: column;
            gap: 2px;
        }
        md-icon-button {
            --md-icon-button-icon-color: white;
            --md-icon-button-state-layer-color: white;
            width: 32px;
            height: 32px;
        }
        md-icon-button[disabled] {
            opacity: 0.55;
        }
        .mode-toggle {
            display: flex;
            border: 1px solid rgba(255, 255, 255, 0.3);
            border-radius: 4px;
            overflow: hidden;
        }
        .mode-toggle button {
            background: transparent;
            border: none;
            padding: 4px 10px;
            cursor: pointer;
            color: rgba(255, 255, 255, 0.7);
            font-size: 0.75rem;
            font-family: inherit;
        }
        .mode-toggle button.active {
            background: rgba(255, 255, 255, 0.2);
            color: white;
        }
        .mode-hint {
            color: rgba(255, 255, 255, 0.6);
            font-size: 0.7rem;
            font-style: italic;
        }
        .presets {
            flex-wrap: wrap;
        }
        .chip {
            padding: 4px 12px;
            border-radius: 12px;
            background: rgba(255, 255, 255, 0.15);
            color: white;
            border: none;
            cursor: pointer;
            font-size: 0.8rem;
            font-family: inherit;
        }
        .chip:hover {
            background: rgba(255, 255, 255, 0.3);
        }
        .readout {
            color: rgba(255, 255, 255, 0.85);
            font-family: var(--monospace-font, monospace);
            font-size: 0.8rem;
            gap: 12px;
        }
        .toast {
            background: rgba(0, 0, 0, 0.85);
            color: white;
            padding: 4px 10px;
            border-radius: 4px;
            font-size: 0.8rem;
            margin-left: auto;
        }
        @media (max-width: 900px) {
            .readout {
                display: none;
            }
        }
    `;
__decorateClass$o([c$5({
  context: clientContext,
  subscribe: true
}), n$5({
  attribute: false
})], AvsumPtzStrip.prototype, "client", 2);
__decorateClass$o([n$5({
  attribute: false
})], AvsumPtzStrip.prototype, "nodeId", 2);
__decorateClass$o([n$5({
  type: Number
})], AvsumPtzStrip.prototype, "endpointId", 2);
__decorateClass$o([n$5({
  type: Number,
  attribute: false
})], AvsumPtzStrip.prototype, "activeVideoStreamId", 2);
__decorateClass$o([n$5({
  type: Object,
  attribute: false
})], AvsumPtzStrip.prototype, "sensorSize", 2);
__decorateClass$o([r$3()], AvsumPtzStrip.prototype, "_mode", 2);
__decorateClass$o([r$3()], AvsumPtzStrip.prototype, "_toast", 2);
AvsumPtzStrip = __decorateClass$o([t$1("avsum-ptz-strip")], AvsumPtzStrip);

var __defProp$k = Object.defineProperty;
var __getOwnPropDesc$l = Object.getOwnPropertyDescriptor;
var __decorateClass$n = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$l(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp$k(target, key, result);
  return result;
};
const HA_DEFAULT_RESOLUTIONS = [{
  width: 1920,
  height: 1080
}, {
  width: 1280,
  height: 720
}, {
  width: 640,
  height: 480
}];
let CameraOverlay = class extends i$4 {
  constructor() {
    super(...arguments);
    this._state = "idle";
    this._errorMessage = null;
    this._snapshotDataUri = null;
    this._snapshotResolution = null;
    this._snapshotBusy = false;
    this._snapshotError = null;
    this._resolutions = [];
    this._selectedResolution = null;
    this._resolutionsLoading = true;
    this._closing = false;
    this._activeVideoStreamId = null;
    this._muted = true;
    this._watermarkEnabled = false;
    this._osdEnabled = false;
    this._snapshotResolutions = [];
    this._selectedSnapshotResolution = null;
    this._streamViewRef = e$1();
  }
  get _snapshotSupported() {
    const node = this.client?.nodes[String(this.nodeId)];
    const accepted = node?.attributes[`${this.endpointId}/1361/65529`];
    if (!Array.isArray(accepted) || !accepted.includes(12)) return false;
    const featureMap = node?.attributes[`${this.endpointId}/1361/65532`];
    if (typeof featureMap === "number" && (featureMap & 4) !== 0) return true;
    const caps = node?.attributes[`${this.endpointId}/1361/10`];
    return Array.isArray(caps) && caps.length > 0;
  }
  firstUpdated() {
    this._initResolutions();
  }
  _initResolutions() {
    this._resolutions = this._loadResolutions();
    this._selectedResolution = this._resolutions[0] ?? null;
    this._snapshotResolutions = this._loadSnapshotResolutions();
    this._selectedSnapshotResolution = this._snapshotResolutions[0] ?? null;
    this._resolutionsLoading = false;
  }
  _loadSnapshotResolutions() {
    const raw = this._readCachedAvsmAttribute(10);
    if (!Array.isArray(raw)) return [];
    const seen = /* @__PURE__ */new Map();
    for (const item of raw) {
      const obj = asObject(item);
      if (!obj) continue;
      const res = asObject(obj["resolution"] ?? obj["0"]);
      if (!res) continue;
      const w = pickNumber(res, "width", "0");
      const h = pickNumber(res, "height", "1");
      if (w !== null && h !== null) {
        const key = `${w}x${h}`;
        if (!seen.has(key)) seen.set(key, {
          width: w,
          height: h
        });
      }
    }
    return [...seen.values()].sort((a, b) => b.width * b.height - a.width * a.height);
  }
  _onSnapshotResolutionChange(ev) {
    const value = ev.target.value;
    const [w, h] = value.split("x").map(Number);
    if (!Number.isFinite(w) || !Number.isFinite(h)) return;
    this._selectedSnapshotResolution = {
      width: w,
      height: h
    };
  }
  _readCachedAvsmAttribute(attributeId) {
    const node = this.client?.nodes[String(this.nodeId)];
    if (!node) return void 0;
    return node.attributes[`${this.endpointId}/${CAMERA_AV_STREAM_MANAGEMENT_CLUSTER_ID}/${attributeId}`];
  }
  _loadResolutions() {
    const rdtRaw = this._readCachedAvsmAttribute(5);
    if (Array.isArray(rdtRaw) && rdtRaw.length > 0) {
      const seen = /* @__PURE__ */new Map();
      for (const item of rdtRaw) {
        const resObj = asObject(item)?.["resolution"];
        const res = asObject(resObj);
        if (!res) continue;
        const w = pickNumber(res, "width");
        const h = pickNumber(res, "height");
        if (w !== null && h !== null) {
          const key = `${w}x${h}`;
          if (!seen.has(key)) seen.set(key, {
            width: w,
            height: h
          });
        }
      }
      const results = [...seen.values()].sort((a, b) => b.width * b.height - a.width * a.height);
      if (results.length > 0) return results;
    }
    const minVpRaw = this._readCachedAvsmAttribute(4);
    const minVp = asObject(minVpRaw);
    if (minVp) {
      const w = pickNumber(minVp, "width");
      const h = pickNumber(minVp, "height");
      if (w !== null && h !== null && w > 0 && h > 0) return [{
        width: w,
        height: h
      }];
    }
    return HA_DEFAULT_RESOLUTIONS;
  }
  _getSensorSize() {
    const node = this.client?.nodes[String(this.nodeId)];
    if (!node) return null;
    const raw = node.attributes[`${this.endpointId}/1361/7`];
    const obj = asObject(raw);
    if (!obj) return null;
    const w = pickNumber(obj, "sensorWidth", "0");
    const h = pickNumber(obj, "sensorHeight", "1");
    if (w === null || h === null) return null;
    return {
      width: w,
      height: h
    };
  }
  _avsmFeatures() {
    const node = this.client?.nodes[String(this.nodeId)];
    const raw = node?.attributes[`${this.endpointId}/${CAMERA_AV_STREAM_MANAGEMENT_CLUSTER_ID}/${AVSM_FEATURE_MAP_ATTR_ID}`];
    const bits = typeof raw === "number" ? raw : 0;
    return {
      wmark: (bits & AVSM_FEAT_WMARK) !== 0,
      osd: (bits & AVSM_FEAT_OSD) !== 0
    };
  }
  _avsumPresent() {
    const node = this.client?.nodes[String(this.nodeId)];
    if (!node) return false;
    return hasAvsumOnEndpoint(node, this.endpointId);
  }
  async _close() {
    const view = this._streamViewRef.value;
    if (view) {
      this._closing = true;
      try {
        await view.stop();
        await view.deallocateSnapshot();
      } finally {
        this._closing = false;
      }
    }
    this.remove();
  }
  _onStreamState(ev) {
    this._state = ev.detail.state;
    this._errorMessage = ev.detail.errorMessage;
    this._activeVideoStreamId = ev.detail.state === "streaming" ? this._streamViewRef.value?.videoStreamId ?? null : null;
  }
  _start() {
    const view = this._streamViewRef.value;
    if (view) {
      void view.start();
    }
  }
  _stop() {
    const view = this._streamViewRef.value;
    if (view) {
      void view.stop();
    }
  }
  _toggleMute() {
    const view = this._streamViewRef.value;
    if (!view) return;
    const next = !this._muted;
    view.setMuted(next);
    this._muted = next;
  }
  async _onSnapshot() {
    const view = this._streamViewRef.value;
    if (!view) return;
    this._snapshotBusy = true;
    this._snapshotError = null;
    try {
      const {
        dataUri,
        resolution
      } = await view.takeSnapshot();
      this._snapshotDataUri = dataUri;
      this._snapshotResolution = resolution;
    } catch (e) {
      this._snapshotError = e instanceof Error ? e.message : String(e);
    } finally {
      this._snapshotBusy = false;
    }
  }
  _downloadSnapshot() {
    if (!this._snapshotDataUri) return;
    const a = document.createElement("a");
    a.href = this._snapshotDataUri;
    a.download = `snapshot-node${this.nodeId}-ep${this.endpointId}-${Date.now()}.jpg`;
    a.click();
  }
  _onResolutionChange(ev) {
    const value = ev.target.value;
    const [w, h] = value.split("x").map(Number);
    if (!Number.isFinite(w) || !Number.isFinite(h)) return;
    this._selectedResolution = {
      width: w,
      height: h
    };
  }
  render() {
    const canStart = this._state === "idle" || this._state === "error";
    return b`
            <div class="backdrop" @click=${this._closing ? void 0 : this._close}></div>
            <div class="frame" @click=${e => e.stopPropagation()}>
                <header>
                    <md-icon-button @click=${this._close} ?disabled=${this._closing} aria-label="Close">
                        <ha-svg-icon .path=${mdiClose}></ha-svg-icon>
                    </md-icon-button>
                    <span>Node ${this.nodeId} • Endpoint ${this.endpointId}</span>
                </header>
                ${this._avsumPresent() ? b`<avsum-ptz-strip
                          .nodeId=${this.nodeId}
                          .endpointId=${this.endpointId}
                          .activeVideoStreamId=${this._activeVideoStreamId}
                          .sensorSize=${this._getSensorSize()}
                      ></avsum-ptz-strip>` : A}
                <main>
                    ${this.client ? b`<webrtc-stream-view
                              ${n(this._streamViewRef)}
                              .nodeId=${this.nodeId}
                              .endpointId=${this.endpointId}
                              .resolution=${this._selectedResolution}
                              .watermarkEnabled=${this._watermarkEnabled}
                              .osdEnabled=${this._osdEnabled}
                              .snapshotResolution=${this._selectedSnapshotResolution}
                              @streamstate=${this._onStreamState}
                          ></webrtc-stream-view>` : b`<div class="status error">No Matter client available.</div>`}
                    ${this._snapshotDataUri ? b`
                              <div class="snapshot-preview">
                                  <img
                                      src=${this._snapshotDataUri}
                                      @click=${this._downloadSnapshot}
                                      title="Click to download${this._snapshotResolution ? ` (${this._snapshotResolution.width}\xD7${this._snapshotResolution.height})` : ""}"
                                      alt="Snapshot"
                                  />
                                  <md-icon-button
                                      @click=${() => {
      this._snapshotDataUri = null;
    }}
                                      aria-label="Close snapshot"
                                  >
                                      <ha-svg-icon .path=${mdiClose}></ha-svg-icon>
                                  </md-icon-button>
                              </div>
                          ` : A}
                    ${this._snapshotError ? b`<div class="snapshot-error">${this._snapshotError}</div>` : A}
                </main>
                <footer>
                    ${this._closing ? b`<span class="footer-status">Closing…</span>` : A}
                    ${!this._closing && this._state === "connecting" ? b`<span class="footer-status">Waiting for camera response…</span>` : A}
                    ${!this._closing && this._state === "error" && this._errorMessage ? b`<span class="footer-status error">${this._errorMessage}</span>` : A}
                    ${canStart && this._resolutions.length > 0 ? b`
                              <md-outlined-select
                                  label="Resolution"
                                  .value=${this._selectedResolution ? `${this._selectedResolution.width}x${this._selectedResolution.height}` : ""}
                                  @change=${this._onResolutionChange}
                              >
                                  ${this._resolutions.map(r => b`
                                          <md-select-option value=${`${r.width}x${r.height}`}>
                                              <div slot="headline">${r.width}×${r.height}</div>
                                          </md-select-option>
                                      `)}
                              </md-outlined-select>
                          ` : A}
                    ${canStart && this._snapshotSupported && this._snapshotResolutions.length > 0 ? b`
                              <md-outlined-select
                                  label="Snapshot"
                                  .value=${this._selectedSnapshotResolution ? `${this._selectedSnapshotResolution.width}x${this._selectedSnapshotResolution.height}` : ""}
                                  @change=${this._onSnapshotResolutionChange}
                              >
                                  ${this._snapshotResolutions.map(r => b`
                                          <md-select-option value=${`${r.width}x${r.height}`}>
                                              <div slot="headline">${r.width}×${r.height}</div>
                                          </md-select-option>
                                      `)}
                              </md-outlined-select>
                          ` : A}
                    ${canStart && this._avsmFeatures().wmark ? b`<label class="overlay-toggle">
                              <input
                                  type="checkbox"
                                  ?checked=${this._watermarkEnabled}
                                  @change=${e => this._watermarkEnabled = e.target.checked}
                              />
                              Watermark
                          </label>` : A}
                    ${canStart && this._avsmFeatures().osd ? b`<label class="overlay-toggle">
                              <input
                                  type="checkbox"
                                  ?checked=${this._osdEnabled}
                                  @change=${e => this._osdEnabled = e.target.checked}
                              />
                              OSD
                          </label>` : A}
                    ${canStart ? b`<md-filled-button
                              @click=${this._start}
                              ?disabled=${!this.client || this._resolutionsLoading}
                          >
                              ${this._state === "error" ? "Retry" : "Start"}
                          </md-filled-button>` : A}
                    ${this._state === "streaming" ? b`<md-filled-button @click=${this._stop}>End</md-filled-button>
                              <md-text-button @click=${this._toggleMute} aria-label=${this._muted ? "Unmute" : "Mute"}>
                                  <ha-svg-icon
                                      slot="icon"
                                      .path=${this._muted ? mdiVolumeOff : mdiVolumeHigh}
                                  ></ha-svg-icon>
                                  ${this._muted ? "Unmute" : "Mute"}
                              </md-text-button>` : A}
                    ${this._snapshotSupported ? b`<md-text-button
                              @click=${this._onSnapshot}
                              ?disabled=${this._snapshotBusy || !this.client}
                              aria-label="Take snapshot"
                          >
                              <ha-svg-icon .path=${mdiCamera} slot="icon"></ha-svg-icon>
                              ${this._snapshotBusy ? "Capturing\u2026" : "Snapshot"}
                          </md-text-button>` : A}
                    <md-text-button @click=${this._close} ?disabled=${this._closing}>Close</md-text-button>
                </footer>
            </div>
        `;
  }
};
CameraOverlay.styles = i$7`
        :host {
            position: fixed;
            inset: 0;
            display: grid;
            place-items: center;
            z-index: 9999;
        }
        .backdrop {
            position: fixed;
            inset: 0;
            background: rgba(0, 0, 0, 0.8);
        }
        .frame {
            position: relative;
            width: min(80vw, 1200px);
            height: min(80vh, 800px);
            background: var(--md-sys-color-surface);
            color: var(--md-sys-color-on-surface);
            display: grid;
            grid-template-rows: auto auto 1fr auto;
            grid-template-areas: "header" "strip" "main" "footer";
            border-radius: 8px;
            overflow: hidden;
        }
        header {
            grid-area: header;
        }
        avsum-ptz-strip {
            grid-area: strip;
        }
        main {
            grid-area: main;
        }
        footer {
            grid-area: footer;
        }
        header {
            display: flex;
            align-items: center;
            padding: 8px 16px;
            gap: 12px;
            border-bottom: 1px solid var(--md-sys-color-outline-variant);
        }
        main {
            display: flex;
            flex-direction: column;
            background: black;
            position: relative;
            overflow: hidden;
            min-height: 0;
        }
        webrtc-stream-view {
            flex: 1 1 0;
            min-height: 0;
            width: 100%;
        }
        .status.error {
            color: var(--danger-color);
            text-align: center;
            padding: 16px;
        }
        .overlay-toggle {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            font-size: 0.85rem;
            color: var(--md-sys-color-on-surface-variant);
            user-select: none;
            cursor: pointer;
        }
        .overlay-toggle input[type="checkbox"] {
            accent-color: var(--md-sys-color-primary);
            margin: 0;
        }
        .snapshot-preview {
            position: absolute;
            top: 8px;
            right: 8px;
            max-width: 200px;
            background: var(--md-sys-color-surface-container);
            border: 1px solid var(--md-sys-color-outline-variant);
            border-radius: 4px;
            padding: 4px;
            display: grid;
            grid-template-columns: 1fr auto;
            align-items: start;
            gap: 4px;
            z-index: 10;
        }
        .snapshot-preview img {
            max-width: 100%;
            cursor: pointer;
            display: block;
            border-radius: 2px;
        }
        .snapshot-error {
            position: absolute;
            bottom: 8px;
            left: 50%;
            transform: translateX(-50%);
            color: var(--danger-color);
            background: var(--md-sys-color-surface-container);
            border-radius: 4px;
            padding: 6px 12px;
            font-size: 0.875rem;
            z-index: 10;
            white-space: nowrap;
        }
        footer {
            padding: 8px 16px;
            display: flex;
            align-items: center;
            justify-content: flex-end;
            gap: 12px;
            border-top: 1px solid var(--md-sys-color-outline-variant);
        }
        .footer-status {
            margin-right: auto;
            color: var(--md-sys-color-on-surface-variant);
            font-style: italic;
        }
        .footer-status.error {
            color: var(--danger-color);
            font-style: normal;
        }
    `;
__decorateClass$n([c$5({
  context: clientContext,
  subscribe: true
}), n$5({
  attribute: false
})], CameraOverlay.prototype, "client", 2);
__decorateClass$n([n$5({
  attribute: false
})], CameraOverlay.prototype, "nodeId", 2);
__decorateClass$n([n$5({
  type: Number
})], CameraOverlay.prototype, "endpointId", 2);
__decorateClass$n([r$3()], CameraOverlay.prototype, "_state", 2);
__decorateClass$n([r$3()], CameraOverlay.prototype, "_errorMessage", 2);
__decorateClass$n([r$3()], CameraOverlay.prototype, "_snapshotDataUri", 2);
__decorateClass$n([r$3()], CameraOverlay.prototype, "_snapshotResolution", 2);
__decorateClass$n([r$3()], CameraOverlay.prototype, "_snapshotBusy", 2);
__decorateClass$n([r$3()], CameraOverlay.prototype, "_snapshotError", 2);
__decorateClass$n([r$3()], CameraOverlay.prototype, "_resolutions", 2);
__decorateClass$n([r$3()], CameraOverlay.prototype, "_selectedResolution", 2);
__decorateClass$n([r$3()], CameraOverlay.prototype, "_resolutionsLoading", 2);
__decorateClass$n([r$3()], CameraOverlay.prototype, "_closing", 2);
__decorateClass$n([r$3()], CameraOverlay.prototype, "_activeVideoStreamId", 2);
__decorateClass$n([r$3()], CameraOverlay.prototype, "_muted", 2);
__decorateClass$n([r$3()], CameraOverlay.prototype, "_watermarkEnabled", 2);
__decorateClass$n([r$3()], CameraOverlay.prototype, "_osdEnabled", 2);
__decorateClass$n([r$3()], CameraOverlay.prototype, "_snapshotResolutions", 2);
__decorateClass$n([r$3()], CameraOverlay.prototype, "_selectedSnapshotResolution", 2);
CameraOverlay = __decorateClass$n([t$1("camera-overlay")], CameraOverlay);

/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
function getDefaultIconColor() {
  return getCssVar("--node-color-default", "#666666");
}
const DeviceTypes = {
  // Utility (per Matter spec - deprioritized for icon selection)
  ROOT_NODE: 22,
  POWER_SOURCE: 17,
  OTA_REQUESTOR: 18,
  OTA_PROVIDER: 20,
  BRIDGED_NODE: 19,
  ELECTRICAL_SENSOR: 1296,
  DEVICE_ENERGY_MANAGEMENT: 1293,
  SECONDARY_NETWORK_INTERFACE: 25,
  JOINT_FABRIC_ADMINISTRATOR: 304,
  // Lighting
  ON_OFF_LIGHT: 256,
  DIMMABLE_LIGHT: 257,
  COLOR_TEMPERATURE_LIGHT: 268,
  EXTENDED_COLOR_LIGHT: 269,
  // Smart Plugs/Outlets and Other Actuators
  ON_OFF_PLUG: 266,
  DIMMABLE_PLUG: 267,
  MOUNTED_ON_OFF_CONTROL: 271,
  MOUNTED_DIMMABLE_LOAD_CONTROL: 272,
  PUMP: 771,
  WATER_VALVE: 66,
  IRRIGATION_SYSTEM: 64,
  // Switches and Controls
  ON_OFF_SWITCH: 259,
  DIMMER_SWITCH: 260,
  COLOR_DIMMER_SWITCH: 261,
  CONTROL_BRIDGE: 2112,
  PUMP_CONTROLLER: 772,
  GENERIC_SWITCH: 15,
  // Sensors
  CONTACT_SENSOR: 21,
  LIGHT_SENSOR: 262,
  OCCUPANCY_SENSOR: 263,
  TEMPERATURE_SENSOR: 770,
  PRESSURE_SENSOR: 773,
  FLOW_SENSOR: 774,
  HUMIDITY_SENSOR: 775,
  ON_OFF_SENSOR: 2128,
  SMOKE_CO_ALARM: 118,
  AIR_QUALITY_SENSOR: 44,
  WATER_FREEZE_DETECTOR: 65,
  WATER_LEAK_DETECTOR: 67,
  RAIN_SENSOR: 68,
  SOIL_SENSOR: 69,
  // Closures
  DOOR_LOCK: 10,
  DOOR_LOCK_CONTROLLER: 11,
  WINDOW_COVERING: 514,
  WINDOW_COVERING_CONTROLLER: 515,
  CLOSURE: 560,
  CLOSURE_PANEL: 561,
  CLOSURE_CONTROLLER: 574,
  // HVAC
  THERMOSTAT: 769,
  FAN: 43,
  AIR_PURIFIER: 45,
  THERMOSTAT_CONTROLLER: 778,
  HEAT_PUMP: 777,
  ROOM_AIR_CONDITIONER: 114,
  // Media
  SPEAKER: 34,
  CASTING_VIDEO_PLAYER: 35,
  CONTENT_APP: 36,
  BASIC_VIDEO_PLAYER: 40,
  CASTING_VIDEO_CLIENT: 41,
  VIDEO_REMOTE_CONTROL: 42,
  // Generic
  AGGREGATOR: 14,
  // Appliances
  REFRIGERATOR: 112,
  TEMPERATURE_CONTROLLED_CABINET: 113,
  LAUNDRY_WASHER: 115,
  ROBOTIC_VACUUM_CLEANER: 116,
  DISHWASHER: 117,
  COOK_SURFACE: 119,
  COOKTOP: 120,
  MICROWAVE_OVEN: 121,
  EXTRACTOR_HOOD: 122,
  OVEN: 123,
  LAUNDRY_DRYER: 124,
  // Energy
  EVSE: 1292,
  WATER_HEATER: 1295,
  SOLAR_POWER: 23,
  BATTERY_STORAGE: 24,
  // Network Infrastructure
  NETWORK_INFRASTRUCTURE_MANAGER: 144,
  THREAD_BORDER_ROUTER: 145,
  // Cameras
  CAMERA: 322,
  SNAPSHOT_CAMERA: 325,
  VIDEO_DOORBELL: 323,
  AUDIO_DOORBELL: 321,
  FLOODLIGHT_CAMERA: 324,
  DOORBELL: 328,
  CHIME: 326,
  CAMERA_CONTROLLER: 327,
  INTERCOM: 320
};
const deviceTypeToIcon = {
  // Utility
  [DeviceTypes.ROOT_NODE]: mdiHome,
  [DeviceTypes.ELECTRICAL_SENSOR]: mdiMeterElectric,
  [DeviceTypes.DEVICE_ENERGY_MANAGEMENT]: mdiMeterElectric,
  // Lighting
  [DeviceTypes.ON_OFF_LIGHT]: mdiLightbulb,
  [DeviceTypes.DIMMABLE_LIGHT]: mdiLightbulb,
  [DeviceTypes.COLOR_TEMPERATURE_LIGHT]: mdiLightbulb,
  [DeviceTypes.EXTENDED_COLOR_LIGHT]: mdiLightbulb,
  // Smart Plugs/Outlets and Other Actuators
  [DeviceTypes.ON_OFF_PLUG]: mdiPowerPlug,
  [DeviceTypes.DIMMABLE_PLUG]: mdiPowerPlug,
  [DeviceTypes.MOUNTED_ON_OFF_CONTROL]: mdiPowerPlug,
  [DeviceTypes.MOUNTED_DIMMABLE_LOAD_CONTROL]: mdiPowerPlug,
  [DeviceTypes.PUMP]: mdiPump,
  [DeviceTypes.WATER_VALVE]: mdiWater,
  [DeviceTypes.IRRIGATION_SYSTEM]: mdiSprinkler,
  // Switches and Controls
  [DeviceTypes.ON_OFF_SWITCH]: mdiToggleSwitch,
  [DeviceTypes.DIMMER_SWITCH]: mdiToggleSwitch,
  [DeviceTypes.COLOR_DIMMER_SWITCH]: mdiToggleSwitch,
  [DeviceTypes.CONTROL_BRIDGE]: mdiRouter,
  [DeviceTypes.PUMP_CONTROLLER]: mdiPump,
  [DeviceTypes.GENERIC_SWITCH]: mdiToggleSwitch,
  // Sensors
  [DeviceTypes.CONTACT_SENSOR]: mdiDoorOpen,
  [DeviceTypes.LIGHT_SENSOR]: mdiBrightnessPercent,
  [DeviceTypes.OCCUPANCY_SENSOR]: mdiMotionSensor,
  [DeviceTypes.TEMPERATURE_SENSOR]: mdiThermometer,
  [DeviceTypes.PRESSURE_SENSOR]: mdiGauge,
  [DeviceTypes.FLOW_SENSOR]: mdiWater,
  [DeviceTypes.HUMIDITY_SENSOR]: mdiWaterPercent,
  [DeviceTypes.ON_OFF_SENSOR]: mdiMotionSensor,
  [DeviceTypes.SMOKE_CO_ALARM]: mdiSmokeDetector,
  [DeviceTypes.AIR_QUALITY_SENSOR]: mdiAirFilter,
  [DeviceTypes.WATER_FREEZE_DETECTOR]: mdiSnowflakeAlert,
  [DeviceTypes.WATER_LEAK_DETECTOR]: mdiWater,
  [DeviceTypes.RAIN_SENSOR]: mdiWeatherRainy,
  [DeviceTypes.SOIL_SENSOR]: mdiLeaf,
  // Closures
  [DeviceTypes.DOOR_LOCK]: mdiLock,
  [DeviceTypes.DOOR_LOCK_CONTROLLER]: mdiLock,
  [DeviceTypes.WINDOW_COVERING]: mdiBlindsHorizontal,
  [DeviceTypes.WINDOW_COVERING_CONTROLLER]: mdiBlindsHorizontal,
  [DeviceTypes.CLOSURE]: mdiDoorOpen,
  [DeviceTypes.CLOSURE_PANEL]: mdiDoorOpen,
  [DeviceTypes.CLOSURE_CONTROLLER]: mdiDoorOpen,
  // HVAC
  [DeviceTypes.THERMOSTAT]: mdiThermometer,
  [DeviceTypes.FAN]: mdiFan,
  [DeviceTypes.AIR_PURIFIER]: mdiAirPurifier,
  [DeviceTypes.THERMOSTAT_CONTROLLER]: mdiThermometer,
  [DeviceTypes.HEAT_PUMP]: mdiHeatPump,
  [DeviceTypes.ROOM_AIR_CONDITIONER]: mdiAirConditioner,
  // Media
  [DeviceTypes.SPEAKER]: mdiSpeaker,
  [DeviceTypes.CASTING_VIDEO_PLAYER]: mdiTelevision,
  [DeviceTypes.CONTENT_APP]: mdiTelevision,
  [DeviceTypes.BASIC_VIDEO_PLAYER]: mdiTelevision,
  [DeviceTypes.CASTING_VIDEO_CLIENT]: mdiCast,
  [DeviceTypes.VIDEO_REMOTE_CONTROL]: mdiRemote,
  // Generic
  [DeviceTypes.AGGREGATOR]: mdiRouter,
  // Appliances
  [DeviceTypes.REFRIGERATOR]: mdiFridge,
  [DeviceTypes.TEMPERATURE_CONTROLLED_CABINET]: mdiFridge,
  [DeviceTypes.LAUNDRY_WASHER]: mdiWashingMachine,
  [DeviceTypes.ROBOTIC_VACUUM_CLEANER]: mdiRobotVacuum,
  [DeviceTypes.DISHWASHER]: mdiDishwasher,
  [DeviceTypes.COOK_SURFACE]: mdiStove,
  [DeviceTypes.COOKTOP]: mdiStove,
  [DeviceTypes.MICROWAVE_OVEN]: mdiMicrowave,
  [DeviceTypes.EXTRACTOR_HOOD]: mdiFan,
  [DeviceTypes.OVEN]: mdiStove,
  [DeviceTypes.LAUNDRY_DRYER]: mdiTumbleDryer,
  // Energy
  [DeviceTypes.EVSE]: mdiEvStation,
  [DeviceTypes.WATER_HEATER]: mdiWaterBoiler,
  [DeviceTypes.SOLAR_POWER]: mdiSolarPower,
  [DeviceTypes.BATTERY_STORAGE]: mdiMeterElectric,
  // Network Infrastructure
  [DeviceTypes.NETWORK_INFRASTRUCTURE_MANAGER]: mdiRouter,
  [DeviceTypes.THREAD_BORDER_ROUTER]: mdiAccessPoint,
  // Cameras
  [DeviceTypes.CAMERA]: mdiCamera,
  [DeviceTypes.SNAPSHOT_CAMERA]: mdiCamera,
  [DeviceTypes.VIDEO_DOORBELL]: mdiDoorbellVideo,
  [DeviceTypes.AUDIO_DOORBELL]: mdiDoorbell,
  [DeviceTypes.FLOODLIGHT_CAMERA]: mdiCctv,
  [DeviceTypes.DOORBELL]: mdiDoorbell,
  [DeviceTypes.CHIME]: mdiBell,
  [DeviceTypes.CAMERA_CONTROLLER]: mdiCamera,
  [DeviceTypes.INTERCOM]: mdiDoorbell
};
const threadRoleToIcon = {
  5: mdiRouter,
  // Router
  6: mdiAccessPoint
  // Leader
};
const THREAD_ROLE_BADGES = {
  2: {
    iconPath: mdiSleep,
    colorVar: "--node-color-thread-enddevice",
    colorFallback: "#90a4ae"
  },
  // Sleepy End Device
  3: {
    iconPath: mdiCircleMedium,
    colorVar: "--node-color-thread-enddevice",
    colorFallback: "#90a4ae"
  },
  // End Device
  4: {
    iconPath: mdiCircleMedium,
    colorVar: "--node-color-thread-enddevice",
    colorFallback: "#90a4ae"
  },
  // REED
  5: {
    iconPath: mdiSwapHorizontal,
    colorVar: "--node-color-thread-router",
    colorFallback: "#1e88e5"
  },
  // Router
  6: {
    iconPath: mdiCrown,
    colorVar: "--node-color-thread-leader",
    colorFallback: "#f9a825"
  }
  // Leader
};
const UTILITY_TYPES = /* @__PURE__ */new Set([DeviceTypes.ROOT_NODE, DeviceTypes.POWER_SOURCE, DeviceTypes.OTA_REQUESTOR, DeviceTypes.OTA_PROVIDER, DeviceTypes.BRIDGED_NODE, DeviceTypes.ELECTRICAL_SENSOR, DeviceTypes.DEVICE_ENERGY_MANAGEMENT, DeviceTypes.SECONDARY_NETWORK_INTERFACE, DeviceTypes.JOINT_FABRIC_ADMINISTRATOR]);
function extractDeviceType(entry) {
  return entry?.["0"] ?? entry?.deviceType;
}
function selectBestDeviceType(deviceTypeList) {
  if (!deviceTypeList?.length) return void 0;
  let firstFound;
  for (const entry of deviceTypeList) {
    const deviceType = extractDeviceType(entry);
    if (deviceType === void 0) continue;
    firstFound ?? (firstFound = deviceType);
    if (deviceTypeToIcon[deviceType] && !UTILITY_TYPES.has(deviceType)) {
      return deviceType;
    }
  }
  return firstFound;
}
function getPrimaryDeviceType(node) {
  const endpoints = [];
  for (const key of Object.keys(node.attributes)) {
    const match = key.match(/^(\d+)\/29\/0$/);
    if (match) {
      endpoints.push(Number(match[1]));
    }
  }
  endpoints.sort((a, b) => a === 0 ? 1 : b === 0 ? -1 : a - b);
  let firstFound;
  for (const ep of endpoints) {
    const deviceTypeList = node.attributes[`${ep}/29/0`];
    const deviceType = selectBestDeviceType(deviceTypeList);
    if (deviceType === void 0) continue;
    firstFound ?? (firstFound = deviceType);
    if (deviceTypeToIcon[deviceType] && !UTILITY_TYPES.has(deviceType)) {
      return deviceType;
    }
  }
  return firstFound;
}
function getEndpointIcon(node, endpoint) {
  const deviceTypeList = node.attributes[`${endpoint}/29/0`];
  const deviceType = selectBestDeviceType(deviceTypeList);
  if (deviceType !== void 0 && deviceTypeToIcon[deviceType]) {
    return deviceTypeToIcon[deviceType];
  }
  return mdiChip;
}
function getDeviceIcon(node, threadRole) {
  if (threadRole !== void 0 && threadRoleToIcon[threadRole]) {
    const deviceType2 = getPrimaryDeviceType(node);
    if (deviceType2 === DeviceTypes.ROOT_NODE || deviceType2 === DeviceTypes.AGGREGATOR || node.is_bridge) {
      return threadRoleToIcon[threadRole];
    }
  }
  if (node.is_bridge) {
    return mdiRouter;
  }
  const deviceType = getPrimaryDeviceType(node);
  if (deviceType !== void 0 && deviceTypeToIcon[deviceType]) {
    return deviceTypeToIcon[deviceType];
  }
  return mdiChip;
}
function createIconDataUrl(iconPath, color, size = 48, badge) {
  const badgeMarkup = badge !== void 0 ? `<circle cx="18" cy="6" r="4" fill="${badge.color}"/>
            <path d="${badge.iconPath}" fill="white" transform="translate(14.64,2.64) scale(0.28)"/>` : "";
  const svg = `
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="${size}" height="${size}">
            <circle cx="12" cy="12" r="11" fill="white" stroke="${color}" stroke-width="1"/>
            <path d="${iconPath}" fill="${color}" transform="scale(0.6) translate(8,8)"/>
            ${badgeMarkup}
        </svg>
    `.trim();
  return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
}
function createNodeIconDataUrl(node, threadRole, isSelected = false, isOffline = false) {
  const iconPath = getDeviceIcon(node, threadRole);
  let color;
  if (isSelected) {
    color = isOffline ? getCssVar("--node-color-selected-offline", "#b71c1c") : getCssVar("--node-color-selected", "#1976d2");
  } else if (isOffline) {
    color = getCssVar("--node-color-offline", "#d32f2f");
  } else {
    color = getDefaultIconColor();
  }
  const roleBadge = threadRole !== void 0 ? THREAD_ROLE_BADGES[threadRole] : void 0;
  const badge = roleBadge !== void 0 ? {
    iconPath: roleBadge.iconPath,
    color: getCssVar(roleBadge.colorVar, roleBadge.colorFallback)
  } : void 0;
  return createIconDataUrl(iconPath, color, 48, badge);
}
function createUnknownDeviceIconDataUrl(isRouter = false, isSelected = false) {
  const iconPath = isRouter ? mdiAccessPoint : mdiHelp;
  const color = isSelected ? getCssVar("--node-color-selected", "#1976d2") : getCssVar("--node-color-unknown", "#ff9800");
  return createIconDataUrl(iconPath, color);
}
function createBorderRouterIconDataUrl(isSelected = false, isLeader = false, isPrimaryBbr = false) {
  const glyph = isLeader ? mdiCrown : mdiRouterWireless;
  const color = isSelected ? getCssVar("--node-color-selected", "#1976d2") : isLeader ? getCssVar("--node-color-thread-leader", "#f9a825") : getCssVar("--md-sys-color-primary", "#03a9f4");
  const badge = isPrimaryBbr ? {
    iconPath: mdiStar,
    color: getCssVar("--node-color-primary-bbr", "#00897b")
  } : void 0;
  return createIconDataUrl(glyph, color, 48, badge);
}
function createWiFiRouterIconDataUrl(isSelected = false) {
  const color = isSelected ? getCssVar("--node-color-selected", "#1976d2") : getCssVar("--node-color-unknown", "#ff9800");
  return createIconDataUrl(mdiWifi, color);
}

/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
function getEndpointDeviceTypes(node, endpoint) {
  const rawValues = node.attributes[`${endpoint}/29/0`];
  if (!rawValues) return new Array();
  return rawValues.map(rawValue => {
    const id = rawValue["0"] ?? rawValue["deviceType"];
    return device_types[id] ?? {
      id: id ?? -1,
      label: `Unknown Device Type (${id})`,
      clusters: []
    };
  });
}

/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
const bindingContext = n$9("binding");

var __defProp$j = Object.defineProperty;
var __getOwnPropDesc$k = Object.getOwnPropertyDescriptor;
var __decorateClass$m = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$k(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp$j(target, key, result);
  return result;
};
const UPDATE_STATE_LABELS = {
  1: "Idle",
  2: "Querying",
  3: "Waiting (Querying)",
  4: "Downloading",
  5: "Applying",
  6: "Waiting (Applying)",
  7: "Rolling back",
  8: "Waiting for consent"
};
function getUpdateStateLabel(state2, progress) {
  const label = UPDATE_STATE_LABELS[state2] ?? `Unknown (${state2})`;
  if (state2 === 4 && progress !== void 0) {
    return `${label} (${progress}%)`;
  }
  return label;
}
function getNodeDeviceTypes(node) {
  const uniqueEndpoints = new Set(Object.keys(node.attributes).map(key => Number(key.split("/")[0])));
  const allDeviceTypes = /* @__PURE__ */new Set();
  uniqueEndpoints.forEach(endpointId => {
    getEndpointDeviceTypes(node, endpointId).forEach(deviceType => {
      allDeviceTypes.add(deviceType);
    });
  });
  return Array.from(allDeviceTypes);
}
let NodeDetails = class extends i$4 {
  constructor() {
    super(...arguments);
    this._tick = 0;
    this._updateInitiated = false;
  }
  render() {
    if (!this.node) return b``;
    const deviceTypeIds = getEndpointDeviceTypes(this.node, this.endpoint).map(d => d.id);
    const isCamera = deviceTypeIds.includes(322) || deviceTypeIds.includes(323);
    return b`
            <md-list>
                <md-list-item>
                    <ha-svg-icon slot="start" class="device-icon" .path=${getDeviceIcon(this.node)}></ha-svg-icon>
                    <div slot="headline" class="node-label-row">
                        <b>${this.node.nodeLabel || "Node Info"}</b>
                        ${this.node.available ? b`
                                  <md-icon-button
                                      @click=${() => this._editNodeLabel()}
                                      aria-label="Edit node label"
                                      title="Edit node label"
                                  >
                                      <ha-svg-icon .path=${mdiPencil}></ha-svg-icon>
                                  </md-icon-button>
                              ` : A}
                        ${this.node.available ? A : b` <span class="status">OFFLINE</span> `}
                    </div>
                </md-list-item>
                <md-list-item>
                    <div slot="supporting-text"><span class="left">VendorName: </span>${this.node.vendorName}</div>
                    <div slot="supporting-text"><span class="left">ProductName: </span>${this.node.productName}</div>
                    <div slot="supporting-text">
                        <span class="left">Commissioned: </span>${this.node.date_commissioned}
                    </div>
                    <div slot="supporting-text">
                        <span class="left">Last interviewed: </span>${this.node.last_interview}
                    </div>
                    <div slot="supporting-text"><span class="left">Is bridge: </span>${this.node.is_bridge}</div>
                    <div slot="supporting-text"><span class="left">Serialnumber: </span>${this.node.serialNumber}</div>
                    ${this.node.matter_version ? b`<div slot="supporting-text">
                              <span class="left">Matter version: </span>${this.node.matter_version}
                          </div>` : A}
                    ${this.node.is_bridge ? "" : b` <div slot="supporting-text">
                              <span class="left">All device types: </span>${getNodeDeviceTypes(this.node).map(deviceType => {
      return deviceType.label;
    }).join(" / ")}
                          </div>`}
                </md-list-item>
                <md-list-item>
                    <div class="btn-row">
                        <md-outlined-button @click=${handleAsync(() => this._reinterview())}
                            >Interview<ha-svg-icon slot="icon" .path=${mdiChatProcessing}></ha-svg-icon
                        ></md-outlined-button>
                        ${this._updateInitiated ? b` <md-outlined-button disabled
                                  >Checking for updates<ha-svg-icon slot="icon" .path=${mdiUpdate}></ha-svg-icon
                              ></md-outlined-button>` : (this.node.updateState ?? 0) > 1 ? b` <md-outlined-button disabled
                                    >${getUpdateStateLabel(this.node.updateState, this.node.updateStateProgress)}<ha-svg-icon slot="icon" .path=${mdiUpdate}></ha-svg-icon
                                ></md-outlined-button>` : b`<md-outlined-button @click=${handleAsync(() => this._searchUpdate())}
                                    >Update<ha-svg-icon slot="icon" .path=${mdiUpdate}></ha-svg-icon
                                ></md-outlined-button>`}
                        ${isCamera ? b`
                                  <md-outlined-button
                                      @click=${() => this._openCameraOverlay()}
                                      ?disabled=${!this.node.available}
                                  >
                                      Live View
                                      <ha-svg-icon slot="icon" .path=${mdiVideo}></ha-svg-icon>
                                  </md-outlined-button>
                              ` : A}
                        <md-outlined-button @click=${handleAsync(() => this._openCommissioningWindow())}
                            >Share<ha-svg-icon slot="icon" .path=${mdiShareVariant}></ha-svg-icon
                        ></md-outlined-button>
                        <md-outlined-button @click=${handleAsync(() => this._remove())}
                            >Remove<ha-svg-icon slot="icon" .path=${mdiTrashCan}></ha-svg-icon
                        ></md-outlined-button>
                    </div>
                </md-list-item>
            </md-list>
        `;
  }
  _editNodeLabel() {
    showNodeLabelDialog(this.client, this.node);
  }
  async _reinterview() {
    if (!(await showPromptDialog({
      title: "Reinterview",
      text: "Are you sure you want to reinterview this node?",
      confirmText: "Reinterview"
    }))) {
      return;
    }
    try {
      await this.client.interviewNode(this.node.node_id);
      showAlertDialog({
        title: "Reinterview node",
        text: "Success!"
      });
      location.hash = "#";
    } catch (err) {
      showAlertDialog({
        title: "Failed to reinterview node",
        text: err.message
      });
    }
  }
  async _remove() {
    if (!(await showPromptDialog({
      title: "Remove",
      text: "Are you sure you want to remove this node?",
      confirmText: "Remove"
    }))) {
      return;
    }
    try {
      await this.client.removeNode(this.node.node_id);
      location.replace("#");
    } catch (err) {
      showAlertDialog({
        title: "Failed to remove node",
        text: err.message
      });
    }
  }
  _openCameraOverlay() {
    const overlay = document.createElement("camera-overlay");
    overlay.nodeId = this.node.node_id;
    overlay.endpointId = this.endpoint;
    const root = document.querySelector("matter-dashboard-app");
    if (root) {
      root.renderRoot.appendChild(overlay);
    } else {
      document.body.appendChild(overlay);
    }
  }
  async _searchUpdate() {
    const nodeUpdate = await this.client.checkNodeUpdate(this.node.node_id);
    if (!nodeUpdate) {
      showAlertDialog({
        title: "No update available",
        text: "No update available for this node"
      });
      return;
    }
    const isUnverifiedSource = nodeUpdate.update_source !== UpdateSource.MAIN_NET_DCL;
    if (!(await showPromptDialog({
      title: "Firmware update available",
      text: b`Found a firmware update for this node on <b>${nodeUpdate.update_source}</b>.
                    ${isUnverifiedSource ? b`
                              <p
                                  style="
                                          background: var(--md-sys-color-error, #b3261e);
                                          color: var(--md-sys-color-on-error, #fff);
                                          padding: 8px 12px;
                                          border-radius: 4px;
                                          font-weight: bold;
                                      "
                              >
                                  Warning: This update was found on an unverified source. Updates from test-net or local
                                  sources have not been certified and may contain untested firmware that could result in
                                  non-functional devices. Applying these updates is entirely at your own risk.
                              </p>
                          ` : A}
                    <p>
                        Do you want to update this node to version
                        <b>${nodeUpdate.software_version_string}</b>?
                    </p>
                    <p>
                        Note that updating firmware is at your own risk and may cause the device to malfunction or needs
                        additional handling such as power cycling it and/or recommissioning it. Use with care.
                    </p>
                    ${nodeUpdate.firmware_information ? b`<p>${nodeUpdate.firmware_information}</p>` : A}`,
      confirmText: "Start Update"
    }))) {
      return;
    }
    try {
      this._updateInitiated = true;
      await this.client.updateNode(this.node.node_id, nodeUpdate.software_version);
    } catch (err) {
      showAlertDialog({
        title: "Failed to update node",
        text: err.message
      });
    } finally {
      this._updateInitiated = false;
    }
  }
  async _openCommissioningWindow() {
    if (!(await showPromptDialog({
      title: "Share device",
      text: "Do you want to share this device with another Matter controller (open commissioning window)?",
      confirmText: "Share"
    }))) {
      return;
    }
    try {
      const shareCode = await this.client.openCommissioningWindow(this.node.node_id);
      showAlertDialog({
        title: "Share device",
        text: `Setup code: ${shareCode.setup_manual_code}`
      });
    } catch (err) {
      showAlertDialog({
        title: "Failed to open commissioning window on node",
        text: err.message
      });
    }
  }
};
NodeDetails.styles = i$7`
        .node-label-row {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .node-label-row md-icon-button {
            width: 24px;
            height: 24px;
            --md-icon-button-state-layer-width: 32px;
            --md-icon-button-state-layer-height: 32px;
        }

        .device-icon {
            --icon-primary-color: var(--md-sys-color-on-surface-variant, #666);
        }

        .btn-row {
            --md-outlined-button-container-shape: 0px;
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
        }

        .btn-row md-outlined-button {
            max-width: 100%;
        }

        .left {
            min-width: 120px;
            display: inline-block;
        }

        @media (min-width: 600px) {
            .left {
                min-width: 150px;
            }
        }

        .whitespace {
            height: 15px;
        }

        .status {
            color: var(--danger-color);
            font-weight: bold;
            font-size: 0.8em;
        }
    `;
__decorateClass$m([c$5({
  context: clientContext
})], NodeDetails.prototype, "client", 2);
__decorateClass$m([c$5({
  context: tickContext,
  subscribe: true
})], NodeDetails.prototype, "_tick", 2);
__decorateClass$m([n$5()], NodeDetails.prototype, "node", 2);
__decorateClass$m([r$3()], NodeDetails.prototype, "_updateInitiated", 2);
__decorateClass$m([c$5({
  context: bindingContext
})], NodeDetails.prototype, "endpoint", 2);
NodeDetails = __decorateClass$m([t$1("node-details")], NodeDetails);

/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
function formatHex(value) {
  let hex = value.toString(16).toUpperCase();
  if (hex.length < 4) {
    hex = hex.padStart(4, "0");
  } else if (hex.length % 2 !== 0) {
    hex = "0" + hex;
  }
  return `0x${hex}`;
}
function formatNodeAddress(fabricIndex, nodeId) {
  const fabricPart = fabricIndex !== void 0 ? fabricIndex : "?";
  return `@${fabricPart}:${nodeId.toString(16)}`;
}
function getEffectiveFabricIndex(serverFabricIndex, isTestNode) {
  return isTestNode || serverFabricIndex === void 0 ? void 0 : serverFabricIndex;
}
function formatNodeAddressFromAny(fabricIndex, nodeId) {
  let numericId;
  if (typeof nodeId === "bigint") {
    numericId = nodeId;
  } else if (typeof nodeId === "number") {
    numericId = BigInt(nodeId);
  } else {
    try {
      numericId = BigInt(nodeId);
    } catch {
      return "";
    }
  }
  return formatNodeAddress(fabricIndex, numericId);
}

/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
const clusterCommandRegistry = /* @__PURE__ */new Map();
function registerClusterCommands(clusterId, tagName) {
  clusterCommandRegistry.set(clusterId, tagName);
}
function getClusterCommandsTag(clusterId) {
  return clusterCommandRegistry.get(clusterId);
}

var _staticBlock$3;
var __defProp$i = Object.defineProperty;
var __decorateClass$l = (decorators, target, key, kind) => {
  var result = void 0 ;
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (decorator(target, key, result) ) || result;
  if (result) __defProp$i(target, key, result);
  return result;
};
class BaseClusterCommands extends i$4 {
  constructor() {
    super(...arguments);
    this._tick = 0;
  }
  /**
   * Send a command to the device.
   * @param command - The command name (PascalCase, e.g., "On", "Off", "MoveToLevel")
   * @param payload - Optional command payload
   */
  async sendCommand(command, payload) {
    try {
      await this.client.deviceCommand(this.node.node_id, this.endpoint, this.cluster, command, payload ?? {});
    } catch (error) {
      console.error(`Failed to send command ${command}:`, error);
    }
  }
  static #_ = _staticBlock$3 = () => this.styles = [reducedMotionStyles, i$7`
            :host {
                display: block;
                color: var(--md-sys-color-on-surface);
            }

            details.command-panel {
                background-color: var(--md-sys-color-surface-container);
                border-radius: 12px;
                overflow: hidden;
            }

            details.command-panel summary {
                padding: 16px;
                font-weight: 500;
                color: var(--md-sys-color-on-surface);
                cursor: pointer;
                user-select: none;
                display: flex;
                align-items: center;
                gap: 8px;
            }

            details.command-panel summary:hover {
                background-color: var(--md-sys-color-surface-container-high);
            }

            details.command-panel summary::before {
                content: "▶";
                font-size: 12px;
                transition: transform 0.2s ease;
            }

            details.command-panel[open] summary::before {
                transform: rotate(90deg);
            }

            details.command-panel summary::-webkit-details-marker {
                display: none;
            }

            .command-content {
                padding: 0 16px 16px 16px;
            }

            .command-row {
                display: flex;
                align-items: center;
                gap: 12px;
                flex-wrap: wrap;
            }

            .command-row label {
                font-size: 14px;
                color: var(--md-sys-color-on-surface-variant);
                display: flex;
                align-items: center;
                gap: 4px;
            }

            .command-row input[type="number"] {
                width: 70px;
                padding: 8px;
                border: 1px solid var(--md-sys-color-outline);
                border-radius: 4px;
                background: var(--md-sys-color-surface);
                color: var(--md-sys-color-on-surface);
            }

            .command-row input[type="checkbox"] {
                width: 16px;
                height: 16px;
                margin: 0;
            }

            md-filled-button,
            md-outlined-button {
                --md-filled-button-container-height: 36px;
                --md-outlined-button-container-height: 36px;
            }
        `];
}
_staticBlock$3();
__decorateClass$l([c$5({
  context: clientContext
})], BaseClusterCommands.prototype, "client");
__decorateClass$l([c$5({
  context: tickContext,
  subscribe: true
})], BaseClusterCommands.prototype, "_tick");
__decorateClass$l([n$5({
  attribute: false
})], BaseClusterCommands.prototype, "node");
__decorateClass$l([n$5({
  type: Number
})], BaseClusterCommands.prototype, "endpoint");
__decorateClass$l([n$5({
  type: Number
})], BaseClusterCommands.prototype, "cluster");

var _staticBlock$2, _staticBlock2;
/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
function isRecord$1(value) {
  return typeof value === "object" && value !== null;
}
class AccessControlTargetTransformer {
  static transform(input) {
    if (!isRecord$1(input)) {
      throw new Error("Invalid input: expected an object");
    }
    const result = {};
    const keyMapping = AccessControlTargetTransformer.KEY_MAPPING;
    for (const key in input) {
      if (key in keyMapping) {
        const mappedKey = keyMapping[key];
        if (mappedKey) {
          const value = input[key];
          if (value == null) continue;
          result[mappedKey] = Number(value);
        }
      }
    }
    return result;
  }
  static #_ = _staticBlock$2 = () => this.KEY_MAPPING = {
    "0": "cluster",
    "1": "endpoint",
    "2": "deviceType"
  };
}
_staticBlock$2();
class AccessControlEntryDataTransformer {
  static transform(input) {
    if (!isRecord$1(input)) {
      throw new Error("Invalid input: expected an object");
    }
    const result = {};
    const keyMapping = AccessControlEntryDataTransformer.KEY_MAPPING;
    for (const key in input) {
      if (key in keyMapping) {
        const mappedKey = keyMapping[key];
        if (mappedKey) {
          const value = input[key];
          if (value == null) continue;
          if (mappedKey === "subjects") {
            result.subjects = Array.isArray(value) ? value : void 0;
          } else if (mappedKey === "targets") {
            result.targets = Array.isArray(value) ? value.map(val => AccessControlTargetTransformer.transform(val)) : void 0;
          } else {
            result[mappedKey] = Number(value);
          }
        }
      }
    }
    return result;
  }
  static #_ = _staticBlock2 = () => this.KEY_MAPPING = {
    "1": "privilege",
    "2": "authMode",
    "3": "subjects",
    "4": "targets",
    "254": "fabricIndex"
  };
}
_staticBlock2();

/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
var Privilege = /* @__PURE__ */(Privilege2 => {
  Privilege2[Privilege2["View"] = 1] = "View";
  Privilege2[Privilege2["ProxyView"] = 2] = "ProxyView";
  Privilege2[Privilege2["Operate"] = 3] = "Operate";
  Privilege2[Privilege2["Manage"] = 4] = "Manage";
  Privilege2[Privilege2["Administer"] = 5] = "Administer";
  return Privilege2;
})(Privilege || {});
var AuthMode = /* @__PURE__ */(AuthMode2 => {
  AuthMode2[AuthMode2["Pase"] = 1] = "Pase";
  AuthMode2[AuthMode2["Case"] = 2] = "Case";
  AuthMode2[AuthMode2["Group"] = 3] = "Group";
  return AuthMode2;
})(AuthMode || {});
const PRIVILEGE_NAMES = {
  [1 /* View */]: "View",
  [2 /* ProxyView */]: "ProxyView",
  [3 /* Operate */]: "Operate",
  [4 /* Manage */]: "Manage",
  [5 /* Administer */]: "Administer"
};
const AUTH_MODE_NAMES = {
  [1 /* Pase */]: "PASE",
  [2 /* Case */]: "CASE",
  [3 /* Group */]: "Group"
};
function nodeIdKey(id) {
  return String(id);
}
function attributeArray(value) {
  if (Array.isArray(value)) return value;
  if (value && typeof value === "object") return Object.values(value);
  return new Array();
}
function readAclEntries(node) {
  return attributeArray(node.attributes["0/31/0"]).map(value => AccessControlEntryDataTransformer.transform(value));
}
function entriesForFabric(entries, fabricIndex) {
  if (fabricIndex === void 0) return entries;
  return entries.filter(e => e.fabricIndex === fabricIndex);
}
function nodeFabricIndex(node) {
  const v = node.attributes["0/62/5"];
  return typeof v === "number" ? v : void 0;
}
function isWholeNode(entry) {
  return !entry.targets || entry.targets.length === 0;
}
function entryMatchesTarget(entry, endpoint, cluster) {
  if (isWholeNode(entry)) return true;
  return entry.targets.some(t => {
    const endpointMatch = t.endpoint == null || t.endpoint === endpoint;
    const clusterMatch = cluster == null ? t.cluster == null : t.cluster == null || t.cluster === cluster;
    return endpointMatch && clusterMatch;
  });
}
function aclCapacity(node) {
  const num = (key, fallback) => {
    const v = node.attributes[key];
    return typeof v === "number" ? v : fallback;
  };
  return {
    max: num("0/31/4", 0),
    subjectsMax: num("0/31/2", 0),
    targetsMax: num("0/31/3", 0)
  };
}
function aclEntryKey(entry) {
  const subjects = (entry.subjects ?? []).map(nodeIdKey).sort();
  const targets = (entry.targets ?? []).map(t => `${t.endpoint ?? ""}:${t.cluster ?? ""}:${t.deviceType ?? ""}`).sort();
  return JSON.stringify([entry.fabricIndex, entry.privilege, entry.authMode, subjects, targets]);
}
function subjectsInclude(entry, nodeId) {
  const key = nodeIdKey(nodeId);
  return (entry.subjects ?? []).some(s => nodeIdKey(s) === key);
}
function isProtectedAdmin(entry, controllerNodeId) {
  if (controllerNodeId === void 0) return false;
  return entry.privilege === 5 /* Administer */ && entry.authMode === 2 /* Case */ && subjectsInclude(entry, controllerNodeId);
}

/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
function toApiAcl$1(e) {
  return {
    privilege: e.privilege,
    auth_mode: e.authMode,
    subjects: e.subjects ?? null,
    targets: e.targets?.map(t => ({
      cluster: t.cluster ?? null,
      endpoint: t.endpoint ?? null,
      device_type: t.deviceType ?? null
    })) ?? null
  };
}
async function freshOurAcl$1(client, nodeId) {
  const res = await client.readAttribute(nodeId, ["0/31/0", "0/62/5"]);
  const all = attributeArray(res["0/31/0"]).map(v => AccessControlEntryDataTransformer.transform(v));
  const fi = res["0/62/5"];
  if (typeof fi !== "number") {
    throw new Error(`Cannot determine the current fabric index (0/62/5) for node ${nodeId}`);
  }
  return entriesForFabric(all, fi);
}
async function addAclEntry(client, nodeId, entry) {
  const acl = await freshOurAcl$1(client, nodeId);
  acl.push(entry);
  await client.setACLEntry(nodeId, acl.map(toApiAcl$1));
}
async function deleteAclEntry(client, nodeId, key) {
  const acl = await freshOurAcl$1(client, nodeId);
  let removed = false;
  const kept = acl.filter(e => {
    if (!removed && aclEntryKey(e) === key) {
      removed = true;
      return false;
    }
    return true;
  });
  await client.setACLEntry(nodeId, kept.map(toApiAcl$1));
}
async function downgradeToOperate(client, nodeId, keys) {
  const acl = await freshOurAcl$1(client, nodeId);
  const updated = acl.map(e => keys.has(aclEntryKey(e)) ? {
    ...e,
    privilege: Privilege.Operate
  } : e);
  await client.setACLEntry(nodeId, updated.map(toApiAcl$1));
}

/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
const showNodeAclAddDialog = async node => {
  await import('./node-acl-add-dialog-DT3GqKYq.js');
  const dialog = document.createElement("node-acl-add-dialog");
  dialog.node = node;
  document.querySelector("matter-dashboard-app")?.renderRoot.appendChild(dialog);
};

var _staticBlock$1;
/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
function isRecord(value) {
  return typeof value === "object" && value !== null;
}
class BindingEntryDataTransformer {
  static transform(input) {
    if (!isRecord(input)) {
      throw new Error("Invalid input: expected an object");
    }
    const result = {};
    const keyMapping = BindingEntryDataTransformer.KEY_MAPPING;
    for (const key in input) {
      if (key in keyMapping) {
        const mappedKey = keyMapping[key];
        if (mappedKey) {
          const value = input[key];
          if (value == null) {
            continue;
          }
          if (mappedKey === "node") {
            if (typeof value === "number" || typeof value === "bigint") {
              result.node = value;
            }
          } else {
            result[mappedKey] = Number(value);
          }
        }
      }
    }
    return result;
  }
  static #_ = _staticBlock$1 = () => this.KEY_MAPPING = {
    "1": "node",
    "2": "group",
    "3": "endpoint",
    "4": "cluster",
    "254": "fabricIndex"
  };
}
_staticBlock$1();

/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
const BINDING_KEY_RE = /^(\d+)\/30\/0$/;
function readBindings(node, endpoint) {
  return attributeArray(node.attributes[`${endpoint}/30/0`]).map(value => BindingEntryDataTransformer.transform(value));
}
function readAllBindings(node) {
  const result = new Array();
  for (const key of Object.keys(node.attributes)) {
    const m = BINDING_KEY_RE.exec(key);
    if (!m) continue;
    const endpoint = Number(m[1]);
    for (const value of attributeArray(node.attributes[key])) {
      result.push({
        endpoint,
        binding: BindingEntryDataTransformer.transform(value)
      });
    }
  }
  return result;
}
function numberList(node, key) {
  const raw = node.attributes[key];
  if (!Array.isArray(raw)) return new Array();
  return raw.map(v => Number(v));
}
function targetServerClusters(node, endpoint) {
  return numberList(node, `${endpoint}/29/1`);
}
function sourceClientClusters(node, endpoint) {
  return numberList(node, `${endpoint}/29/2`);
}
function bindableClusters(source, sourceEndpoint, target, targetEndpoint) {
  const client = new Set(sourceClientClusters(source, sourceEndpoint));
  const server = targetServerClusters(target, targetEndpoint);
  const bindable = new Array();
  const otherTarget = new Array();
  for (const c of server) {
    if (client.has(c)) bindable.push(c);else otherTarget.push(c);
  }
  return {
    bindable,
    otherTarget
  };
}
function reverseAclState(sourceNodeId, binding, targetNode) {
  if (binding.node != null && nodeIdKey(binding.node) === nodeIdKey(sourceNodeId)) return {
    state: "self"
  };
  if (!targetNode || !targetNode.available) return {
    state: "cannotVerify"
  };
  const matching = entriesForFabric(readAclEntries(targetNode), nodeFabricIndex(targetNode)).filter(e => e.authMode === AuthMode.Case && subjectsInclude(e, sourceNodeId) && entryMatchesTarget(e, binding.endpoint ?? -1, binding.cluster));
  const granting = matching.filter(e => e.privilege >= Privilege.Operate);
  if (granting.length === 0) return {
    state: "missing"
  };
  if (granting.some(e => e.privilege === Privilege.Operate)) return {
    state: "present"
  };
  return {
    state: "overPrivileged"
  };
}
function detectBindingRelationship(entry, viewedNodeId, allNodes) {
  if (entry.authMode !== AuthMode.Case) return {
    kind: "none"
  };
  const viewedKey = nodeIdKey(viewedNodeId);
  for (const subject of entry.subjects ?? []) {
    const sourceKey = nodeIdKey(subject);
    const source = allNodes.find(n => nodeIdKey(n.node_id) === sourceKey);
    if (!source || !source.available) continue;
    for (const {
      endpoint,
      binding
    } of readAllBindings(source)) {
      if (binding.node == null) continue;
      if (nodeIdKey(binding.node) !== viewedKey) continue;
      if (!entryMatchesTarget(entry, binding.endpoint ?? -1, binding.cluster)) continue;
      const kind = entry.privilege > Privilege.Operate ? "overPrivileged" : "backs";
      return {
        kind,
        sourceNodeId: source.node_id,
        sourceEndpoint: endpoint
      };
    }
  }
  return {
    kind: "none"
  };
}
function targetAclCapacityForBinding(targetNode, sourceNodeId) {
  if (nodeIdKey(targetNode.node_id) === nodeIdKey(sourceNodeId)) return {
    canAdd: true
  };
  const fabricIndex = nodeFabricIndex(targetNode);
  if (fabricIndex === void 0) return {
    canAdd: true
  };
  const entries = entriesForFabric(readAclEntries(targetNode), fabricIndex);
  const targetsMaxRaw = targetNode.attributes["0/31/3"];
  const targetsMax = typeof targetsMaxRaw === "number" && targetsMaxRaw > 0 ? targetsMaxRaw : Number.MAX_SAFE_INTEGER;
  const reusable = entries.some(e => e.authMode === AuthMode.Case && e.privilege >= Privilege.Operate && subjectsInclude(e, sourceNodeId) && (isWholeNode(e) || (e.targets?.length ?? 0) < targetsMax));
  if (reusable) return {
    canAdd: true
  };
  const maxRaw = targetNode.attributes["0/31/4"];
  const max = typeof maxRaw === "number" ? maxRaw : 0;
  if (max > 0 && entries.length >= max) {
    return {
      canAdd: false,
      reason: "Target node's access control list is full."
    };
  }
  return {
    canAdd: true
  };
}

/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
function getDeviceName(node) {
  if (node.nodeLabel) return node.nodeLabel;
  const productName = node.productName || "Unknown Device";
  const serialNumber = node.serialNumber;
  return serialNumber ? `${productName} (${serialNumber})` : productName;
}

var __defProp$h = Object.defineProperty;
var __getOwnPropDesc$j = Object.getOwnPropertyDescriptor;
var __decorateClass$k = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$j(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp$h(target, key, result);
  return result;
};
const CLUSTER_ID$3 = 31;
let AccessControlClusterCommands = class extends BaseClusterCommands {
  constructor() {
    super(...arguments);
    this._loadedKey = "";
    this._busy = false;
  }
  updated(changed) {
    super.updated(changed);
    if (changed.has("client") && this.client && !this._unsubscribe) {
      this._unsubscribe = this.client.addEventListener("nodes_changed", () => this.requestUpdate());
    }
    void this._ensureLoaded();
  }
  disconnectedCallback() {
    super.disconnectedCallback();
    this._unsubscribe?.();
  }
  /** The acl attribute is fabric-scoped and may be absent from the cache until read. Load it on open. */
  async _ensureLoaded() {
    if (!this.client || !this.node || !this.node.available) return;
    const key = nodeIdKey(this.node.node_id);
    if (this._loadedKey === key) return;
    this._loadedKey = key;
    try {
      const res = await this.client.readAttribute(this.node.node_id, ["0/31/0", "0/62/5"]);
      for (const [k, v] of Object.entries(res)) this.node.attributes[k] = v;
      this.requestUpdate();
    } catch (err) {
      this._loadedKey = "";
      console.error("Failed to load ACL", err);
    }
  }
  get _controllerNodeId() {
    return this.client.serverInfo?.controller_node_id;
  }
  _entries() {
    return entriesForFabric(readAclEntries(this.node), nodeFabricIndex(this.node));
  }
  _clusterName(id) {
    if (id == null) return "all clusters";
    return `${clusters[id]?.label ?? "Cluster"} (0x${id.toString(16).padStart(2, "0").toUpperCase()})`;
  }
  _privilegeClass(p) {
    return `pv pv-${p}`;
  }
  async _delete(entry) {
    const isAdmin = entry.privilege === Privilege.Administer && entry.authMode === AuthMode.Case;
    const unverified = isAdmin && this._controllerNodeId === void 0;
    const confirmed = await showPromptDialog({
      title: "Delete ACL entry",
      text: unverified ? "This is an Administer entry and the controller cannot verify whether it is its own. Deleting the wrong admin entry can lock the controller out of this device. Continue?" : "Remove this access control entry? Devices relying on it will lose the granted access.",
      confirmText: "Delete"
    });
    if (!confirmed) return;
    this._busy = true;
    try {
      await deleteAclEntry(this.client, this.node.node_id, aclEntryKey(entry));
    } catch (err) {
      await showAlertDialog({
        title: "Delete failed",
        text: err instanceof Error ? err.message : String(err)
      });
    } finally {
      this._busy = false;
    }
  }
  async _fix(keys) {
    this._busy = true;
    try {
      await downgradeToOperate(this.client, this.node.node_id, keys);
    } catch (err) {
      await showAlertDialog({
        title: "Fix failed",
        text: err instanceof Error ? err.message : String(err)
      });
    } finally {
      this._busy = false;
    }
  }
  async _openAdd() {
    await showNodeAclAddDialog(this.node);
  }
  _renderSubjects(entry) {
    const subjects = entry.subjects ?? [];
    if (entry.authMode === AuthMode.Case && subjects.length === 0) {
      return b`<span class="mut">Any node on fabric</span>`;
    }
    if (entry.authMode === AuthMode.Group) {
      return b`${subjects.map(s => b`<div class="ident">Group ${s.toString()}</div>`)}`;
    }
    return b`${subjects.map(s => {
      const known = this.client.nodes[nodeIdKey(s)];
      const protectedMe = isProtectedAdmin(entry, this._controllerNodeId) && nodeIdKey(s) === nodeIdKey(this._controllerNodeId);
      return b`<div class="ident ${protectedMe ? "me" : ""}">
                ${protectedMe ? "This controller" : known ? getDeviceName(known) : "Unknown node"} ·
                <span class="nid">${s.toString()}</span><span class="hex">0x${s.toString(16).toUpperCase()}</span>
            </div>`;
    })}`;
  }
  _renderTargets(entry) {
    if (isWholeNode(entry)) return b`<span class="mut">Whole node</span>`;
    return b`${entry.targets.map(t => {
      if (t.cluster != null) return b`<span class="chip ep">EP ${t.endpoint ?? "*"} · ${this._clusterName(t.cluster)}</span>`;
      if (t.deviceType != null) return b`<span class="chip ep">EP ${t.endpoint ?? "*"} · device type ${t.deviceType}</span>`;
      return b`<span class="chip ep">EP ${t.endpoint ?? "*"}</span>`;
    })}`;
  }
  _renderRelationship(rel) {
    if (rel.kind === "none") return b`<span class="mut">—</span>`;
    const source = rel.sourceNodeId != null ? this.client.nodes[nodeIdKey(rel.sourceNodeId)] : void 0;
    const label = source ? getDeviceName(source) : "node";
    if (rel.kind === "overPrivileged") {
      return b`<span class="chip bug"
                ><ha-svg-icon .path=${mdiAlert}></ha-svg-icon> over-privileged binding ACL</span
            >`;
    }
    return b`<span class="chip link"
            ><ha-svg-icon .path=${mdiLink}></ha-svg-icon> backs binding · ${label} EP${rel.sourceEndpoint}</span
        >`;
  }
  render() {
    if (!this.node || this.cluster !== CLUSTER_ID$3) return A;
    const entries = this._entries();
    const allNodes = Object.values(this.client.nodes);
    const rels = entries.map(e => detectBindingRelationship(e, this.node.node_id, allNodes));
    const capacity = aclCapacity(this.node);
    const full = capacity.max > 0 && entries.length >= capacity.max;
    const overPrivilegedKeys = /* @__PURE__ */new Set();
    entries.forEach((e, i) => {
      if (rels[i].kind === "overPrivileged") overPrivilegedKeys.add(aclEntryKey(e));
    });
    return b`
            <details class="command-panel">
                <summary>Access Control — ACL Entries (${entries.length})</summary>
                <div class="command-content">
                    ${overPrivilegedKeys.size >= 2 ? b`<div class="banner">
                              <span
                                  >${overPrivilegedKeys.size} binding ACL entries grant Administer where Operate is
                                  sufficient.</span
                              >
                              <md-outlined-button
                                  ?disabled=${this._busy || !this.node.available}
                                  @click=${handleAsync(() => this._fix(overPrivilegedKeys))}
                                  >Fix all → Operate</md-outlined-button
                              >
                          </div>` : A}
                    <table class="acl">
                        <thead>
                            <tr>
                                <th>Privilege</th>
                                <th>Auth</th>
                                <th>Subjects</th>
                                <th>Targets</th>
                                <th>Relationship</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>
                            ${entries.map((e, i) => this._row(e, rels[i]))}
                        </tbody>
                    </table>
                    <md-outlined-button
                        ?disabled=${this._busy || full || !this.node.available}
                        title=${full ? "Access control list is full" : ""}
                        @click=${handleAsync(() => this._openAdd())}
                        >Add ACL entry</md-outlined-button
                    >
                    ${full ? b`<span class="mut full-note">List full (${capacity.max} entries)</span>` : A}
                </div>
            </details>
        `;
  }
  _row(entry, rel) {
    const protectedEntry = isProtectedAdmin(entry, this._controllerNodeId);
    const overPrivileged = rel.kind === "overPrivileged";
    return b`
            <tr class=${overPrivileged ? "row-warn" : ""}>
                <td>
                    <span class=${this._privilegeClass(entry.privilege)}
                        >${PRIVILEGE_NAMES[entry.privilege] ?? entry.privilege} · ${entry.privilege}</span
                    >
                    ${overPrivileged ? b`<div>
                              <md-outlined-button
                                  class="fix"
                                  ?disabled=${this._busy || !this.node.available}
                                  @click=${handleAsync(() => this._fix(/* @__PURE__ */new Set([aclEntryKey(entry)])))}
                                  >Fix → Operate</md-outlined-button
                              >
                          </div>` : A}
                </td>
                <td>${AUTH_MODE_NAMES[entry.authMode] ?? entry.authMode}</td>
                <td>${this._renderSubjects(entry)}</td>
                <td>${this._renderTargets(entry)}</td>
                <td>${this._renderRelationship(rel)}</td>
                <td>
                    ${protectedEntry ? b`<ha-svg-icon
                              class="lock"
                              .path=${mdiLock}
                              title="Your controller's administrator entry — deleting it would lock you out."
                          ></ha-svg-icon>` : b`<md-outlined-button
                              class="danger"
                              ?disabled=${this._busy || !this.node.available}
                              @click=${handleAsync(() => this._delete(entry))}
                          >
                              <ha-svg-icon .path=${mdiTrashCan} slot="icon"></ha-svg-icon>delete
                          </md-outlined-button>`}
                </td>
            </tr>
        `;
  }
};
AccessControlClusterCommands.styles = [BaseClusterCommands.styles, i$7`
            .acl {
                width: 100%;
                border-collapse: collapse;
                margin-bottom: 12px;
            }
            .acl th {
                text-align: left;
                font-size: 11px;
                text-transform: uppercase;
                opacity: 0.6;
                padding: 8px 10px;
                border-bottom: 1px solid var(--md-sys-color-outline-variant);
            }
            .acl td {
                padding: 10px;
                border-bottom: 1px solid var(--md-sys-color-outline-variant);
                vertical-align: middle;
            }
            .ident {
                line-height: 1.4;
            }
            .ident.me {
                color: var(--md-sys-color-primary);
                font-weight: 600;
            }
            .ident .nid {
                font-weight: 600;
            }
            .row-warn td {
                background: var(--md-sys-color-error-container);
                box-shadow: inset 3px 0 0 var(--md-sys-color-error);
            }
            .pv {
                display: inline-block;
                padding: 2px 8px;
                border-radius: 999px;
                font-size: 12px;
                font-weight: 700;
            }
            .pv-5 {
                background: var(--md-sys-color-error-container);
                color: var(--md-sys-color-on-error-container);
            }
            .pv-4 {
                background: var(--md-sys-color-tertiary-container);
                color: var(--md-sys-color-on-tertiary-container);
            }
            .pv-3 {
                background: var(--md-sys-color-primary-container);
                color: var(--md-sys-color-on-primary-container);
            }
            .pv-1,
            .pv-2 {
                background: var(--md-sys-color-surface-container-highest);
                color: var(--md-sys-color-on-surface-variant);
            }
            .chip {
                display: inline-flex;
                align-items: center;
                gap: 4px;
                padding: 3px 8px;
                border-radius: 6px;
                margin: 2px 4px 2px 0;
                font-size: inherit;
                background: var(--md-sys-color-surface-container-high);
                color: var(--md-sys-color-on-surface);
            }
            .chip ha-svg-icon {
                --mdc-icon-size: 14px;
                width: 14px;
                height: 14px;
            }
            .chip.ep {
                background: var(--md-sys-color-secondary-container);
                color: var(--md-sys-color-on-secondary-container);
            }
            .chip.me {
                background: var(--md-sys-color-tertiary-container);
                color: var(--md-sys-color-on-tertiary-container);
            }
            .chip.link {
                background: var(--md-sys-color-primary-container);
                color: var(--md-sys-color-on-primary-container);
            }
            .chip.bug {
                background: var(--md-sys-color-error-container);
                color: var(--md-sys-color-on-error-container);
            }
            .nid {
                font-weight: 600;
            }
            .hex {
                font-family: var(--monospace-font, monospace);
                font-size: 10px;
                opacity: 0.6;
                margin-left: 4px;
            }
            .mut {
                opacity: 0.6;
            }
            .full-note {
                margin-left: 8px;
                font-size: 12px;
            }
            .banner {
                display: flex;
                align-items: center;
                justify-content: space-between;
                gap: 12px;
                padding: 10px 12px;
                margin-bottom: 12px;
                border-radius: 8px;
                background: var(--md-sys-color-error-container);
                color: var(--md-sys-color-on-error-container);
            }
            md-outlined-button.danger {
                --md-outlined-button-label-text-color: var(--md-sys-color-error);
                --md-outlined-button-outline-color: var(--md-sys-color-error);
            }
            md-outlined-button.fix {
                margin-top: 4px;
                --md-outlined-button-container-height: 28px;
            }
        `];
__decorateClass$k([r$3()], AccessControlClusterCommands.prototype, "_busy", 2);
AccessControlClusterCommands = __decorateClass$k([t$1("access-control-cluster-commands")], AccessControlClusterCommands);
registerClusterCommands(CLUSTER_ID$3, "access-control-cluster-commands");

var __defProp$g = Object.defineProperty;
var __getOwnPropDesc$i = Object.getOwnPropertyDescriptor;
var __decorateClass$j = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$i(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp$g(target, key, result);
  return result;
};
let AvsumClusterCommands = class extends BaseClusterCommands {
  constructor() {
    super(...arguments);
    this._toast = null;
    this._newPresetName = "";
  }
  updated(changedProperties) {
    super.updated(changedProperties);
    if (changedProperties.has("client") && this.client && !this._unsubscribeNodes) {
      this._unsubscribeNodes = this.client.addEventListener("nodes_changed", () => this.requestUpdate());
    }
  }
  disconnectedCallback() {
    super.disconnectedCallback();
    this._unsubscribeNodes?.();
    if (this._toastTimer) {
      clearTimeout(this._toastTimer);
      this._toastTimer = void 0;
    }
  }
  render() {
    if (!this.node || this.cluster !== AVSUM_CLUSTER_ID) return A;
    const features = readFeatures(this.node, this.endpoint);
    const pos = readPosition(this.node, this.endpoint);
    const ranges = readRanges(this.node, this.endpoint);
    const movement = readMovementState(this.node, this.endpoint);
    return b`
            <details class="command-panel" open>
                <summary>Camera AV Settings — Pan / Tilt / Zoom</summary>
                <div class="command-content">
                    <div class="readout">
                        ${features.mPan && pos.pan !== null ? b`<span><b>Pan</b> ${this._fmtDeg(pos.pan)}</span>` : A}
                        ${features.mTilt && pos.tilt !== null ? b`<span><b>Tilt</b> ${this._fmtDeg(pos.tilt)}</span>` : A}
                        ${features.mZoom && pos.zoom !== null ? b`<span><b>Zoom</b> ${pos.zoom}×</span>` : A}
                        ${movement !== "unknown" ? b`<span class="badge ${movement === "moving" ? "moving" : ""}"
                                  >${movement === "moving" ? "Moving\u2026" : "Idle"}</span
                              >` : A}
                        ${features.mPan && ranges.panMin !== null && ranges.panMax !== null ? b`<span class="range">P [${ranges.panMin}°, ${ranges.panMax}°]</span>` : A}
                        ${features.mTilt && ranges.tiltMin !== null && ranges.tiltMax !== null ? b`<span class="range">T [${ranges.tiltMin}°, ${ranges.tiltMax}°]</span>` : A}
                        ${features.mZoom && ranges.zoomMax !== null ? b`<span class="range">Z [1×, ${ranges.zoomMax}×]</span>` : A}
                    </div>
                    ${features.mPan || features.mTilt || features.mZoom ? b`<div class="dpad-row">
                              <div class="dpad-grid">
                                  <span></span>
                                  <md-outlined-icon-button
                                      ?disabled=${!features.mTilt || movement === "moving"}
                                      title="Tilt up (Shift = fine)"
                                      aria-label="Tilt up"
                                      @click=${handleAsyncEvent(e => this._move({
      tiltDelta: this._stepFromEvent(e, 10)
    }))}
                                  >
                                      <ha-svg-icon .path=${mdiArrowUp}></ha-svg-icon>
                                  </md-outlined-icon-button>
                                  <span></span>
                                  <md-outlined-icon-button
                                      ?disabled=${!features.mPan || movement === "moving"}
                                      title="Pan left (Shift = fine)"
                                      aria-label="Pan left"
                                      @click=${handleAsyncEvent(e => this._move({
      panDelta: this._stepFromEvent(e, -10)
    }))}
                                  >
                                      <ha-svg-icon .path=${mdiArrowLeft}></ha-svg-icon>
                                  </md-outlined-icon-button>
                                  <span class="dpad-center" aria-hidden="true">
                                      <ha-svg-icon .path=${mdiCircleMedium}></ha-svg-icon>
                                  </span>
                                  <md-outlined-icon-button
                                      ?disabled=${!features.mPan || movement === "moving"}
                                      title="Pan right (Shift = fine)"
                                      aria-label="Pan right"
                                      @click=${handleAsyncEvent(e => this._move({
      panDelta: this._stepFromEvent(e, 10)
    }))}
                                  >
                                      <ha-svg-icon .path=${mdiArrowRight}></ha-svg-icon>
                                  </md-outlined-icon-button>
                                  <span></span>
                                  <md-outlined-icon-button
                                      ?disabled=${!features.mTilt || movement === "moving"}
                                      title="Tilt down (Shift = fine)"
                                      aria-label="Tilt down"
                                      @click=${handleAsyncEvent(e => this._move({
      tiltDelta: this._stepFromEvent(e, -10)
    }))}
                                  >
                                      <ha-svg-icon .path=${mdiArrowDown}></ha-svg-icon>
                                  </md-outlined-icon-button>
                                  <span></span>
                              </div>
                              ${features.mZoom ? b`<div class="zoom-col">
                                        <md-outlined-icon-button
                                            ?disabled=${movement === "moving"}
                                            title="Zoom in (Shift = fine)"
                                            aria-label="Zoom in"
                                            @click=${handleAsyncEvent(e => this._move({
      zoomDelta: this._stepFromEvent(e, 10)
    }))}
                                        >
                                            <ha-svg-icon .path=${mdiPlus}></ha-svg-icon>
                                        </md-outlined-icon-button>
                                        <span class="muted small">zoom</span>
                                        <md-outlined-icon-button
                                            ?disabled=${movement === "moving"}
                                            title="Zoom out (Shift = fine)"
                                            aria-label="Zoom out"
                                            @click=${handleAsyncEvent(e => this._move({
      zoomDelta: this._stepFromEvent(e, -10)
    }))}
                                        >
                                            <ha-svg-icon .path=${mdiMinus}></ha-svg-icon>
                                        </md-outlined-icon-button>
                                    </div>` : A}
                          </div>` : A}
                    ${this._toast ? b`<div class="toast">${this._toast}</div>` : A}
                    ${features.mPresets ? (() => {
      const {
        items,
        max
      } = readPresets(this.node, this.endpoint);
      return b`
                                  <div class="presets-frame">
                                      <div class="presets-header">
                                          <span>Presets</span>
                                          <span class="muted small">${items.length} / ${max}</span>
                                      </div>
                                      <div class="chip-row">
                                          ${items.map(p => b`<button
                                                  class="chip"
                                                  title="p=${this._fmtDeg(p.settings.pan ?? 0)} · t=${this._fmtDeg(p.settings.tilt ?? 0)} · z=${p.settings.zoom ?? 1}×"
                                                  @click=${handleAsync(() => this._goPreset(p.presetId))}
                                              >
                                                  ${p.name}
                                              </button>`)}
                                          ${items.length === 0 ? b`<span class="muted small">No presets saved.</span>` : A}
                                      </div>
                                      <details class="manager">
                                          <summary>Manage presets…</summary>
                                          ${items.map(p => b`<div class="preset-row">
                                                  <span class="pid">#${p.presetId}</span>
                                                  <span class="pname">${p.name}</span>
                                                  <span class="pcoord">
                                                      p=${this._fmtDeg(p.settings.pan ?? 0)} ·
                                                      t=${this._fmtDeg(p.settings.tilt ?? 0)} ·
                                                      z=${p.settings.zoom ?? 1}×
                                                  </span>
                                                  <span class="grow"></span>
                                                  <md-outlined-icon-button
                                                      title="Overwrite with current MPTZ"
                                                      @click=${handleAsync(() => this._savePresetUpdate(p.presetId))}
                                                  >
                                                      <ha-svg-icon .path=${mdiContentSaveOutline}></ha-svg-icon>
                                                  </md-outlined-icon-button>
                                                  <md-outlined-icon-button
                                                      title="Rename (also overwrites position with current MPTZ)"
                                                      aria-label="Rename preset"
                                                      @click=${handleAsync(() => this._renamePreset(p.presetId, p.name))}
                                                  >
                                                      <ha-svg-icon .path=${mdiPencil}></ha-svg-icon>
                                                  </md-outlined-icon-button>
                                                  <md-outlined-icon-button
                                                      title="Remove"
                                                      @click=${handleAsync(() => this._removePreset(p.presetId, p.name))}
                                                  >
                                                      <ha-svg-icon .path=${mdiTrashCan}></ha-svg-icon>
                                                  </md-outlined-icon-button>
                                              </div>`)}
                                          <div class="add-bar">
                                              <input
                                                  class="add-input"
                                                  placeholder="New preset name…"
                                                  .value=${this._newPresetName}
                                                  @input=${e => this._newPresetName = e.target.value}
                                              />
                                              <md-outlined-button
                                                  ?disabled=${!this._newPresetName.trim() || items.length >= max}
                                                  @click=${handleAsync(() => this._saveNewPreset())}
                                              >
                                                  Save current MPTZ
                                              </md-outlined-button>
                                          </div>
                                      </details>
                                  </div>
                              `;
    })() : A}
                    ${features.dptz ? (() => {
      const streams = readDptzStreams(this.node, this.endpoint);
      return b`<div class="dptz-note">
                                  Digital PTZ: <b>${streams.length}</b> active stream${streams.length === 1 ? "" : "s"}
                                  <span class="muted small">(controls available during live view)</span>
                              </div>`;
    })() : A}
                </div>
            </details>
        `;
  }
  _fmtDeg(v) {
    const sign = v >= 0 ? "+" : "";
    return `${sign}${v}\xB0`;
  }
  _showBusy() {
    this._toast = "Camera busy";
    this._scheduleToastClear();
  }
  _isBusy(err) {
    const msg = err instanceof Error ? err.message.toLowerCase() : String(err).toLowerCase();
    return msg.includes("busy");
  }
  _stepFromEvent(e, base) {
    return e.shiftKey ? Math.sign(base) : base;
  }
  async _move(delta) {
    try {
      await relativeMove(this.client, this.node.node_id, this.endpoint, delta);
    } catch (err) {
      if (this._isBusy(err)) {
        this._showBusy();
        return;
      }
      showAlertDialog({
        title: "Move failed",
        text: err instanceof Error ? err.message : String(err)
      });
    }
  }
  async _goPreset(presetId) {
    try {
      await moveToPreset(this.client, this.node.node_id, this.endpoint, presetId);
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      if (this._isBusy(err)) return this._showBusy();
      if (msg.toLowerCase().includes("not_found")) {
        this._toast = "Preset removed";
        this._scheduleToastClear();
        return;
      }
      showAlertDialog({
        title: "Move failed",
        text: msg
      });
    }
  }
  _scheduleToastClear() {
    if (this._toastTimer) clearTimeout(this._toastTimer);
    this._toastTimer = setTimeout(() => {
      this._toast = null;
    }, 2e3);
  }
  async _savePresetUpdate(presetId) {
    if (!this.node) return;
    const preset = readPresets(this.node, this.endpoint).items.find(p => p.presetId === presetId);
    if (!preset) return;
    try {
      await savePreset(this.client, this.node.node_id, this.endpoint, preset.name, presetId);
    } catch (err) {
      showAlertDialog({
        title: "Update failed",
        text: err instanceof Error ? err.message : String(err)
      });
    }
  }
  async _renamePreset(presetId, currentName) {
    const next = window.prompt("New name (max 32 chars)", currentName);
    if (typeof next !== "string" || !next.trim()) return;
    try {
      await savePreset(this.client, this.node.node_id, this.endpoint, next.trim().slice(0, 32), presetId);
    } catch (err) {
      showAlertDialog({
        title: "Rename failed",
        text: err instanceof Error ? err.message : String(err)
      });
    }
  }
  async _removePreset(presetId, name) {
    const ok = await showPromptDialog({
      title: "Remove preset",
      text: `Remove "${name}"?`,
      confirmText: "Remove"
    });
    if (!ok) return;
    try {
      await removePreset(this.client, this.node.node_id, this.endpoint, presetId);
    } catch (err) {
      showAlertDialog({
        title: "Remove failed",
        text: err instanceof Error ? err.message : String(err)
      });
    }
  }
  async _saveNewPreset() {
    if (!this.node) return;
    const name = this._newPresetName.trim().slice(0, 32);
    if (!name) return;
    try {
      await savePreset(this.client, this.node.node_id, this.endpoint, name);
      this._newPresetName = "";
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      if (msg.toLowerCase().includes("resource_exhausted")) {
        const max = readPresets(this.node, this.endpoint).max;
        this._toast = `Preset list full (${max})`;
        this._scheduleToastClear();
        return;
      }
      showAlertDialog({
        title: "Save failed",
        text: msg
      });
    }
  }
};
AvsumClusterCommands.styles = [...(Array.isArray(BaseClusterCommands.styles) ? BaseClusterCommands.styles : [BaseClusterCommands.styles]), i$7`
            .readout {
                display: flex;
                align-items: center;
                gap: 16px;
                flex-wrap: wrap;
                font-family: var(--monospace-font, monospace);
                font-size: 0.85rem;
                padding: 4px 0 12px;
            }
            .readout b {
                font-weight: 500;
                color: var(--md-sys-color-on-surface-variant);
                margin-right: 4px;
            }
            .badge {
                padding: 2px 8px;
                border-radius: 4px;
                background: var(--md-sys-color-secondary-container);
                color: var(--md-sys-color-on-secondary-container);
                font-size: 0.75rem;
            }
            .badge.moving {
                background: var(--md-sys-color-primary-container);
                color: var(--md-sys-color-on-primary-container);
            }
            .range {
                color: var(--md-sys-color-on-surface-variant);
                font-size: 0.75rem;
            }
            .dpad-row {
                display: flex;
                align-items: center;
                justify-content: center;
                gap: 24px;
                padding: 12px 0;
            }
            md-outlined-icon-button {
                --md-outlined-icon-button-icon-color: var(--md-sys-color-on-surface);
                --md-outlined-icon-button-outline-color: var(--md-sys-color-outline);
            }
            md-outlined-icon-button[disabled] {
                opacity: 0.6;
            }
            .dpad-grid {
                display: grid;
                grid-template-columns: 40px 40px 40px;
                grid-template-rows: 40px 40px 40px;
                gap: 4px;
            }
            .dpad-center {
                display: grid;
                place-items: center;
                color: var(--md-sys-color-on-surface-variant);
                opacity: 0.4;
            }
            .zoom-col {
                display: flex;
                flex-direction: column;
                align-items: center;
                gap: 4px;
            }
            .muted.small {
                font-size: 0.7rem;
                color: var(--md-sys-color-on-surface-variant);
            }
            .muted {
                color: var(--md-sys-color-on-surface-variant);
            }
            .toast {
                margin-top: 8px;
                padding: 6px 12px;
                background: var(--md-sys-color-inverse-surface);
                color: var(--md-sys-color-inverse-on-surface);
                border-radius: 4px;
                font-size: 0.85rem;
                text-align: center;
            }
            .presets-frame {
                margin-top: 12px;
                padding-top: 12px;
                border-top: 1px solid var(--md-sys-color-outline-variant);
            }
            .presets-header {
                display: flex;
                justify-content: space-between;
                font-weight: 500;
                margin-bottom: 8px;
            }
            .chip-row {
                display: flex;
                gap: 6px;
                flex-wrap: wrap;
                margin-bottom: 8px;
            }
            .chip {
                padding: 6px 14px;
                border-radius: 16px;
                background: var(--md-sys-color-primary-container);
                color: var(--md-sys-color-on-primary-container);
                border: none;
                cursor: pointer;
                font-size: 0.85rem;
                font-family: inherit;
            }
            .chip:hover {
                filter: brightness(1.05);
            }
            details.manager summary {
                cursor: pointer;
                font-size: 0.85rem;
                color: var(--md-sys-color-on-surface-variant);
                padding: 4px 0;
            }
            .preset-row {
                display: flex;
                align-items: center;
                gap: 12px;
                padding: 4px 8px;
                border-radius: 4px;
            }
            .preset-row:hover {
                background: var(--md-sys-color-surface-container-high);
            }
            .pid {
                font-family: var(--monospace-font, monospace);
                color: var(--md-sys-color-on-surface-variant);
                font-size: 0.85rem;
                min-width: 32px;
            }
            .pname {
                font-weight: 500;
            }
            .pcoord {
                font-family: var(--monospace-font, monospace);
                font-size: 0.75rem;
                color: var(--md-sys-color-on-surface-variant);
            }
            .grow {
                flex: 1;
            }
            .add-bar {
                display: flex;
                gap: 8px;
                align-items: center;
                padding-top: 8px;
                margin-top: 8px;
                border-top: 1px solid var(--md-sys-color-outline-variant);
            }
            .add-input {
                flex: 1;
                padding: 6px 8px;
                border: 1px solid var(--md-sys-color-outline);
                border-radius: 4px;
                background: var(--md-sys-color-surface);
                color: var(--md-sys-color-on-surface);
                font-family: inherit;
                font-size: 0.85rem;
            }
            .dptz-note {
                margin-top: 12px;
                padding: 8px 12px;
                background: var(--md-sys-color-surface-container);
                border-radius: 4px;
                font-size: 0.85rem;
            }
            .dptz-note b {
                font-weight: 500;
            }
        `];
__decorateClass$j([r$3()], AvsumClusterCommands.prototype, "_toast", 2);
__decorateClass$j([r$3()], AvsumClusterCommands.prototype, "_newPresetName", 2);
AvsumClusterCommands = __decorateClass$j([t$1("avsum-cluster-commands")], AvsumClusterCommands);
registerClusterCommands(AVSUM_CLUSTER_ID, "avsum-cluster-commands");

/**
 * @license
 * Copyright 2024 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Generated stylesheet for ./textfield/internal/outlined-styles.css.
const styles$4 = i$7`:host{--_caret-color: var(--md-outlined-text-field-caret-color, var(--md-sys-color-primary, #6750a4));--_disabled-input-text-color: var(--md-outlined-text-field-disabled-input-text-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-input-text-opacity: var(--md-outlined-text-field-disabled-input-text-opacity, 0.38);--_disabled-label-text-color: var(--md-outlined-text-field-disabled-label-text-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-label-text-opacity: var(--md-outlined-text-field-disabled-label-text-opacity, 0.38);--_disabled-leading-icon-color: var(--md-outlined-text-field-disabled-leading-icon-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-leading-icon-opacity: var(--md-outlined-text-field-disabled-leading-icon-opacity, 0.38);--_disabled-outline-color: var(--md-outlined-text-field-disabled-outline-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-outline-opacity: var(--md-outlined-text-field-disabled-outline-opacity, 0.12);--_disabled-outline-width: var(--md-outlined-text-field-disabled-outline-width, 1px);--_disabled-supporting-text-color: var(--md-outlined-text-field-disabled-supporting-text-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-supporting-text-opacity: var(--md-outlined-text-field-disabled-supporting-text-opacity, 0.38);--_disabled-trailing-icon-color: var(--md-outlined-text-field-disabled-trailing-icon-color, var(--md-sys-color-on-surface, #1d1b20));--_disabled-trailing-icon-opacity: var(--md-outlined-text-field-disabled-trailing-icon-opacity, 0.38);--_error-focus-caret-color: var(--md-outlined-text-field-error-focus-caret-color, var(--md-sys-color-error, #b3261e));--_error-focus-input-text-color: var(--md-outlined-text-field-error-focus-input-text-color, var(--md-sys-color-on-surface, #1d1b20));--_error-focus-label-text-color: var(--md-outlined-text-field-error-focus-label-text-color, var(--md-sys-color-error, #b3261e));--_error-focus-leading-icon-color: var(--md-outlined-text-field-error-focus-leading-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_error-focus-outline-color: var(--md-outlined-text-field-error-focus-outline-color, var(--md-sys-color-error, #b3261e));--_error-focus-supporting-text-color: var(--md-outlined-text-field-error-focus-supporting-text-color, var(--md-sys-color-error, #b3261e));--_error-focus-trailing-icon-color: var(--md-outlined-text-field-error-focus-trailing-icon-color, var(--md-sys-color-error, #b3261e));--_error-hover-input-text-color: var(--md-outlined-text-field-error-hover-input-text-color, var(--md-sys-color-on-surface, #1d1b20));--_error-hover-label-text-color: var(--md-outlined-text-field-error-hover-label-text-color, var(--md-sys-color-on-error-container, #410e0b));--_error-hover-leading-icon-color: var(--md-outlined-text-field-error-hover-leading-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_error-hover-outline-color: var(--md-outlined-text-field-error-hover-outline-color, var(--md-sys-color-on-error-container, #410e0b));--_error-hover-supporting-text-color: var(--md-outlined-text-field-error-hover-supporting-text-color, var(--md-sys-color-error, #b3261e));--_error-hover-trailing-icon-color: var(--md-outlined-text-field-error-hover-trailing-icon-color, var(--md-sys-color-on-error-container, #410e0b));--_error-input-text-color: var(--md-outlined-text-field-error-input-text-color, var(--md-sys-color-on-surface, #1d1b20));--_error-label-text-color: var(--md-outlined-text-field-error-label-text-color, var(--md-sys-color-error, #b3261e));--_error-leading-icon-color: var(--md-outlined-text-field-error-leading-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_error-outline-color: var(--md-outlined-text-field-error-outline-color, var(--md-sys-color-error, #b3261e));--_error-supporting-text-color: var(--md-outlined-text-field-error-supporting-text-color, var(--md-sys-color-error, #b3261e));--_error-trailing-icon-color: var(--md-outlined-text-field-error-trailing-icon-color, var(--md-sys-color-error, #b3261e));--_focus-input-text-color: var(--md-outlined-text-field-focus-input-text-color, var(--md-sys-color-on-surface, #1d1b20));--_focus-label-text-color: var(--md-outlined-text-field-focus-label-text-color, var(--md-sys-color-primary, #6750a4));--_focus-leading-icon-color: var(--md-outlined-text-field-focus-leading-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_focus-outline-color: var(--md-outlined-text-field-focus-outline-color, var(--md-sys-color-primary, #6750a4));--_focus-outline-width: var(--md-outlined-text-field-focus-outline-width, 3px);--_focus-supporting-text-color: var(--md-outlined-text-field-focus-supporting-text-color, var(--md-sys-color-on-surface-variant, #49454f));--_focus-trailing-icon-color: var(--md-outlined-text-field-focus-trailing-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_hover-input-text-color: var(--md-outlined-text-field-hover-input-text-color, var(--md-sys-color-on-surface, #1d1b20));--_hover-label-text-color: var(--md-outlined-text-field-hover-label-text-color, var(--md-sys-color-on-surface, #1d1b20));--_hover-leading-icon-color: var(--md-outlined-text-field-hover-leading-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_hover-outline-color: var(--md-outlined-text-field-hover-outline-color, var(--md-sys-color-on-surface, #1d1b20));--_hover-outline-width: var(--md-outlined-text-field-hover-outline-width, 1px);--_hover-supporting-text-color: var(--md-outlined-text-field-hover-supporting-text-color, var(--md-sys-color-on-surface-variant, #49454f));--_hover-trailing-icon-color: var(--md-outlined-text-field-hover-trailing-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_input-text-color: var(--md-outlined-text-field-input-text-color, var(--md-sys-color-on-surface, #1d1b20));--_input-text-font: var(--md-outlined-text-field-input-text-font, var(--md-sys-typescale-body-large-font, var(--md-ref-typeface-plain, Roboto)));--_input-text-line-height: var(--md-outlined-text-field-input-text-line-height, var(--md-sys-typescale-body-large-line-height, 1.5rem));--_input-text-placeholder-color: var(--md-outlined-text-field-input-text-placeholder-color, var(--md-sys-color-on-surface-variant, #49454f));--_input-text-prefix-color: var(--md-outlined-text-field-input-text-prefix-color, var(--md-sys-color-on-surface-variant, #49454f));--_input-text-size: var(--md-outlined-text-field-input-text-size, var(--md-sys-typescale-body-large-size, 1rem));--_input-text-suffix-color: var(--md-outlined-text-field-input-text-suffix-color, var(--md-sys-color-on-surface-variant, #49454f));--_input-text-weight: var(--md-outlined-text-field-input-text-weight, var(--md-sys-typescale-body-large-weight, var(--md-ref-typeface-weight-regular, 400)));--_label-text-color: var(--md-outlined-text-field-label-text-color, var(--md-sys-color-on-surface-variant, #49454f));--_label-text-font: var(--md-outlined-text-field-label-text-font, var(--md-sys-typescale-body-large-font, var(--md-ref-typeface-plain, Roboto)));--_label-text-line-height: var(--md-outlined-text-field-label-text-line-height, var(--md-sys-typescale-body-large-line-height, 1.5rem));--_label-text-populated-line-height: var(--md-outlined-text-field-label-text-populated-line-height, var(--md-sys-typescale-body-small-line-height, 1rem));--_label-text-populated-size: var(--md-outlined-text-field-label-text-populated-size, var(--md-sys-typescale-body-small-size, 0.75rem));--_label-text-size: var(--md-outlined-text-field-label-text-size, var(--md-sys-typescale-body-large-size, 1rem));--_label-text-weight: var(--md-outlined-text-field-label-text-weight, var(--md-sys-typescale-body-large-weight, var(--md-ref-typeface-weight-regular, 400)));--_leading-icon-color: var(--md-outlined-text-field-leading-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_leading-icon-size: var(--md-outlined-text-field-leading-icon-size, 24px);--_outline-color: var(--md-outlined-text-field-outline-color, var(--md-sys-color-outline, #79747e));--_outline-width: var(--md-outlined-text-field-outline-width, 1px);--_supporting-text-color: var(--md-outlined-text-field-supporting-text-color, var(--md-sys-color-on-surface-variant, #49454f));--_supporting-text-font: var(--md-outlined-text-field-supporting-text-font, var(--md-sys-typescale-body-small-font, var(--md-ref-typeface-plain, Roboto)));--_supporting-text-line-height: var(--md-outlined-text-field-supporting-text-line-height, var(--md-sys-typescale-body-small-line-height, 1rem));--_supporting-text-size: var(--md-outlined-text-field-supporting-text-size, var(--md-sys-typescale-body-small-size, 0.75rem));--_supporting-text-weight: var(--md-outlined-text-field-supporting-text-weight, var(--md-sys-typescale-body-small-weight, var(--md-ref-typeface-weight-regular, 400)));--_trailing-icon-color: var(--md-outlined-text-field-trailing-icon-color, var(--md-sys-color-on-surface-variant, #49454f));--_trailing-icon-size: var(--md-outlined-text-field-trailing-icon-size, 24px);--_container-shape-start-start: var(--md-outlined-text-field-container-shape-start-start, var(--md-outlined-text-field-container-shape, var(--md-sys-shape-corner-extra-small, 4px)));--_container-shape-start-end: var(--md-outlined-text-field-container-shape-start-end, var(--md-outlined-text-field-container-shape, var(--md-sys-shape-corner-extra-small, 4px)));--_container-shape-end-end: var(--md-outlined-text-field-container-shape-end-end, var(--md-outlined-text-field-container-shape, var(--md-sys-shape-corner-extra-small, 4px)));--_container-shape-end-start: var(--md-outlined-text-field-container-shape-end-start, var(--md-outlined-text-field-container-shape, var(--md-sys-shape-corner-extra-small, 4px)));--_icon-input-space: var(--md-outlined-text-field-icon-input-space, 16px);--_leading-space: var(--md-outlined-text-field-leading-space, 16px);--_trailing-space: var(--md-outlined-text-field-trailing-space, 16px);--_top-space: var(--md-outlined-text-field-top-space, 16px);--_bottom-space: var(--md-outlined-text-field-bottom-space, 16px);--_input-text-prefix-trailing-space: var(--md-outlined-text-field-input-text-prefix-trailing-space, 2px);--_input-text-suffix-leading-space: var(--md-outlined-text-field-input-text-suffix-leading-space, 2px);--_focus-caret-color: var(--md-outlined-text-field-focus-caret-color, var(--md-sys-color-primary, #6750a4));--_with-leading-icon-leading-space: var(--md-outlined-text-field-with-leading-icon-leading-space, 12px);--_with-trailing-icon-trailing-space: var(--md-outlined-text-field-with-trailing-icon-trailing-space, 12px);--md-outlined-field-bottom-space: var(--_bottom-space);--md-outlined-field-container-shape-end-end: var(--_container-shape-end-end);--md-outlined-field-container-shape-end-start: var(--_container-shape-end-start);--md-outlined-field-container-shape-start-end: var(--_container-shape-start-end);--md-outlined-field-container-shape-start-start: var(--_container-shape-start-start);--md-outlined-field-content-color: var(--_input-text-color);--md-outlined-field-content-font: var(--_input-text-font);--md-outlined-field-content-line-height: var(--_input-text-line-height);--md-outlined-field-content-size: var(--_input-text-size);--md-outlined-field-content-space: var(--_icon-input-space);--md-outlined-field-content-weight: var(--_input-text-weight);--md-outlined-field-disabled-content-color: var(--_disabled-input-text-color);--md-outlined-field-disabled-content-opacity: var(--_disabled-input-text-opacity);--md-outlined-field-disabled-label-text-color: var(--_disabled-label-text-color);--md-outlined-field-disabled-label-text-opacity: var(--_disabled-label-text-opacity);--md-outlined-field-disabled-leading-content-color: var(--_disabled-leading-icon-color);--md-outlined-field-disabled-leading-content-opacity: var(--_disabled-leading-icon-opacity);--md-outlined-field-disabled-outline-color: var(--_disabled-outline-color);--md-outlined-field-disabled-outline-opacity: var(--_disabled-outline-opacity);--md-outlined-field-disabled-outline-width: var(--_disabled-outline-width);--md-outlined-field-disabled-supporting-text-color: var(--_disabled-supporting-text-color);--md-outlined-field-disabled-supporting-text-opacity: var(--_disabled-supporting-text-opacity);--md-outlined-field-disabled-trailing-content-color: var(--_disabled-trailing-icon-color);--md-outlined-field-disabled-trailing-content-opacity: var(--_disabled-trailing-icon-opacity);--md-outlined-field-error-content-color: var(--_error-input-text-color);--md-outlined-field-error-focus-content-color: var(--_error-focus-input-text-color);--md-outlined-field-error-focus-label-text-color: var(--_error-focus-label-text-color);--md-outlined-field-error-focus-leading-content-color: var(--_error-focus-leading-icon-color);--md-outlined-field-error-focus-outline-color: var(--_error-focus-outline-color);--md-outlined-field-error-focus-supporting-text-color: var(--_error-focus-supporting-text-color);--md-outlined-field-error-focus-trailing-content-color: var(--_error-focus-trailing-icon-color);--md-outlined-field-error-hover-content-color: var(--_error-hover-input-text-color);--md-outlined-field-error-hover-label-text-color: var(--_error-hover-label-text-color);--md-outlined-field-error-hover-leading-content-color: var(--_error-hover-leading-icon-color);--md-outlined-field-error-hover-outline-color: var(--_error-hover-outline-color);--md-outlined-field-error-hover-supporting-text-color: var(--_error-hover-supporting-text-color);--md-outlined-field-error-hover-trailing-content-color: var(--_error-hover-trailing-icon-color);--md-outlined-field-error-label-text-color: var(--_error-label-text-color);--md-outlined-field-error-leading-content-color: var(--_error-leading-icon-color);--md-outlined-field-error-outline-color: var(--_error-outline-color);--md-outlined-field-error-supporting-text-color: var(--_error-supporting-text-color);--md-outlined-field-error-trailing-content-color: var(--_error-trailing-icon-color);--md-outlined-field-focus-content-color: var(--_focus-input-text-color);--md-outlined-field-focus-label-text-color: var(--_focus-label-text-color);--md-outlined-field-focus-leading-content-color: var(--_focus-leading-icon-color);--md-outlined-field-focus-outline-color: var(--_focus-outline-color);--md-outlined-field-focus-outline-width: var(--_focus-outline-width);--md-outlined-field-focus-supporting-text-color: var(--_focus-supporting-text-color);--md-outlined-field-focus-trailing-content-color: var(--_focus-trailing-icon-color);--md-outlined-field-hover-content-color: var(--_hover-input-text-color);--md-outlined-field-hover-label-text-color: var(--_hover-label-text-color);--md-outlined-field-hover-leading-content-color: var(--_hover-leading-icon-color);--md-outlined-field-hover-outline-color: var(--_hover-outline-color);--md-outlined-field-hover-outline-width: var(--_hover-outline-width);--md-outlined-field-hover-supporting-text-color: var(--_hover-supporting-text-color);--md-outlined-field-hover-trailing-content-color: var(--_hover-trailing-icon-color);--md-outlined-field-label-text-color: var(--_label-text-color);--md-outlined-field-label-text-font: var(--_label-text-font);--md-outlined-field-label-text-line-height: var(--_label-text-line-height);--md-outlined-field-label-text-populated-line-height: var(--_label-text-populated-line-height);--md-outlined-field-label-text-populated-size: var(--_label-text-populated-size);--md-outlined-field-label-text-size: var(--_label-text-size);--md-outlined-field-label-text-weight: var(--_label-text-weight);--md-outlined-field-leading-content-color: var(--_leading-icon-color);--md-outlined-field-leading-space: var(--_leading-space);--md-outlined-field-outline-color: var(--_outline-color);--md-outlined-field-outline-width: var(--_outline-width);--md-outlined-field-supporting-text-color: var(--_supporting-text-color);--md-outlined-field-supporting-text-font: var(--_supporting-text-font);--md-outlined-field-supporting-text-line-height: var(--_supporting-text-line-height);--md-outlined-field-supporting-text-size: var(--_supporting-text-size);--md-outlined-field-supporting-text-weight: var(--_supporting-text-weight);--md-outlined-field-top-space: var(--_top-space);--md-outlined-field-trailing-content-color: var(--_trailing-icon-color);--md-outlined-field-trailing-space: var(--_trailing-space);--md-outlined-field-with-leading-content-leading-space: var(--_with-leading-icon-leading-space);--md-outlined-field-with-trailing-content-trailing-space: var(--_with-trailing-icon-trailing-space)}
`;

/**
 * @license
 * Copyright 2020 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
const l = e$4(class extends i$3 {
  constructor(r) {
    if (super(r), r.type !== t.PROPERTY && r.type !== t.ATTRIBUTE && r.type !== t.BOOLEAN_ATTRIBUTE) throw Error("The `live` directive is not allowed on child or event bindings");
    if (!r$1(r)) throw Error("`live` bindings can only contain a single expression");
  }
  render(r) {
    return r;
  }
  update(i, [t$1]) {
    if (t$1 === E || t$1 === A) return t$1;
    const o = i.element,
      l = i.name;
    if (i.type === t.PROPERTY) {
      if (t$1 === o[l]) return E;
    } else if (i.type === t.BOOLEAN_ATTRIBUTE) {
      if (!!t$1 === o.hasAttribute(l)) return E;
    } else if (i.type === t.ATTRIBUTE && o.getAttribute(l) === t$1 + "") return E;
    return p(i), t$1;
  }
});

/**
 * @license
 * Copyright 2022 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
const stringConverter = {
  fromAttribute(value) {
    return value ?? '';
  },
  toAttribute(value) {
    return value || null;
  }
};

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * A validator that provides constraint validation that emulates `<input>` and
 * `<textarea>` validation.
 */
class TextFieldValidator extends Validator$2 {
  computeValidity({
    state,
    renderedControl
  }) {
    let inputOrTextArea = renderedControl;
    if (isInputState(state) && !inputOrTextArea) {
      // Get cached <input> or create it.
      inputOrTextArea = this.inputControl || document.createElement('input');
      // Cache the <input> to re-use it next time.
      this.inputControl = inputOrTextArea;
    } else if (!inputOrTextArea) {
      // Get cached <textarea> or create it.
      inputOrTextArea = this.textAreaControl || document.createElement('textarea');
      // Cache the <textarea> to re-use it next time.
      this.textAreaControl = inputOrTextArea;
    }
    // Set this variable so we can check it for input-specific properties.
    const input = isInputState(state) ? inputOrTextArea : null;
    // Set input's "type" first, since this can change the other properties
    if (input) {
      input.type = state.type;
    }
    if (inputOrTextArea.value !== state.value) {
      // Only programmatically set the value if there's a difference. When using
      // the rendered control, the value will always be up to date. Setting the
      // property (even if it's the same string) will reset the internal <input>
      // dirty flag, making minlength and maxlength validation reset.
      inputOrTextArea.value = state.value;
    }
    inputOrTextArea.required = state.required;
    // The following IDLAttribute properties will always hydrate an attribute,
    // even if set to a the default value ('' or -1). The presence of the
    // attribute triggers constraint validation, so we must remove the attribute
    // when empty.
    if (input) {
      const inputState = state;
      if (inputState.pattern) {
        input.pattern = inputState.pattern;
      } else {
        input.removeAttribute('pattern');
      }
      if (inputState.min) {
        input.min = inputState.min;
      } else {
        input.removeAttribute('min');
      }
      if (inputState.max) {
        input.max = inputState.max;
      } else {
        input.removeAttribute('max');
      }
      if (inputState.step) {
        input.step = inputState.step;
      } else {
        input.removeAttribute('step');
      }
    }
    // Use -1 to represent no minlength and maxlength, which is what the
    // platform input returns. However, it will throw an error if you try to
    // manually set it to -1.
    //
    // While the type is `number`, it may actually be `null` at runtime.
    // `null > -1` is true since `null` coerces to `0`, so we default null and
    // undefined to -1.
    //
    // We set attributes instead of properties since setting a property may
    // throw an out of bounds error in relation to the other property.
    // Attributes will not throw errors while the state is updating.
    if ((state.minLength ?? -1) > -1) {
      inputOrTextArea.setAttribute('minlength', String(state.minLength));
    } else {
      inputOrTextArea.removeAttribute('minlength');
    }
    if ((state.maxLength ?? -1) > -1) {
      inputOrTextArea.setAttribute('maxlength', String(state.maxLength));
    } else {
      inputOrTextArea.removeAttribute('maxlength');
    }
    return {
      validity: inputOrTextArea.validity,
      validationMessage: inputOrTextArea.validationMessage
    };
  }
  equals({
    state: prev
  }, {
    state: next
  }) {
    // Check shared input and textarea properties
    const inputOrTextAreaEqual = prev.type === next.type && prev.value === next.value && prev.required === next.required && prev.minLength === next.minLength && prev.maxLength === next.maxLength;
    if (!isInputState(prev) || !isInputState(next)) {
      // Both are textareas, all relevant properties are equal.
      return inputOrTextAreaEqual;
    }
    // Check additional input-specific properties.
    return inputOrTextAreaEqual && prev.pattern === next.pattern && prev.min === next.min && prev.max === next.max && prev.step === next.step;
  }
  copy({
    state
  }) {
    // Don't hold a reference to the rendered control when copying since we
    // don't use it when checking if the state changed.
    return {
      state: isInputState(state) ? this.copyInput(state) : this.copyTextArea(state),
      renderedControl: null
    };
  }
  copyInput(state) {
    const {
      type,
      pattern,
      min,
      max,
      step
    } = state;
    return {
      ...this.copySharedState(state),
      type,
      pattern,
      min,
      max,
      step
    };
  }
  copyTextArea(state) {
    return {
      ...this.copySharedState(state),
      type: state.type
    };
  }
  copySharedState({
    value,
    required,
    minLength,
    maxLength
  }) {
    return {
      value,
      required,
      minLength,
      maxLength
    };
  }
}
function isInputState(state) {
  return state.type !== 'textarea';
}

/**
 * @license
 * Copyright 2021 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Separate variable needed for closure.
const textFieldBaseClass = mixinDelegatesAria(mixinOnReportValidity(mixinConstraintValidation(mixinFormAssociated(mixinElementInternals(i$4)))));
/**
 * A text field component.
 *
 * @fires select {Event} The native `select` event on
 * [`<input>`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select_event)
 * --bubbles
 * @fires change {Event} The native `change` event on
 * [`<input>`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event)
 * --bubbles
 * @fires input {InputEvent} The native `input` event on
 * [`<input>`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event)
 * --bubbles --composed
 */
class TextField extends textFieldBaseClass {
  constructor() {
    super(...arguments);
    /**
     * Gets or sets whether or not the text field is in a visually invalid state.
     *
     * This error state overrides the error state controlled by
     * `reportValidity()`.
     */
    this.error = false;
    /**
     * The error message that replaces supporting text when `error` is true. If
     * `errorText` is an empty string, then the supporting text will continue to
     * show.
     *
     * This error message overrides the error message displayed by
     * `reportValidity()`.
     */
    this.errorText = '';
    /**
     * The floating Material label of the textfield component. It informs the user
     * about what information is requested for a text field. It is aligned with
     * the input text, is always visible, and it floats when focused or when text
     * is entered into the textfield. This label also sets accessibilty labels,
     * but the accessible label is overriden by `aria-label`.
     *
     * Learn more about floating labels from the Material Design guidelines:
     * https://m3.material.io/components/text-fields/guidelines
     */
    this.label = '';
    /**
     * Disables the asterisk on the floating label, when the text field is
     * required.
     */
    this.noAsterisk = false;
    /**
     * Indicates that the user must specify a value for the input before the
     * owning form can be submitted and will render an error state when
     * `reportValidity()` is invoked when value is empty. Additionally the
     * floating label will render an asterisk `"*"` when true.
     *
     * https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/required
     */
    this.required = false;
    /**
     * The current value of the text field. It is always a string.
     */
    this.value = '';
    /**
     * An optional prefix to display before the input value.
     */
    this.prefixText = '';
    /**
     * An optional suffix to display after the input value.
     */
    this.suffixText = '';
    /**
     * Whether or not the text field has a leading icon. Used for SSR.
     */
    this.hasLeadingIcon = false;
    /**
     * Whether or not the text field has a trailing icon. Used for SSR.
     */
    this.hasTrailingIcon = false;
    /**
     * Conveys additional information below the text field, such as how it should
     * be used.
     */
    this.supportingText = '';
    /**
     * Override the input text CSS `direction`. Useful for RTL languages that use
     * LTR notation for fractions.
     */
    this.textDirection = '';
    /**
     * The number of rows to display for a `type="textarea"` text field.
     * Defaults to 2.
     */
    this.rows = 2;
    /**
     * The number of cols to display for a `type="textarea"` text field.
     * Defaults to 20.
     */
    this.cols = 20;
    // <input> properties
    this.inputMode = '';
    /**
     * Defines the greatest value in the range of permitted values.
     *
     * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#max
     */
    this.max = '';
    /**
     * The maximum number of characters a user can enter into the text field. Set
     * to -1 for none.
     *
     * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#maxlength
     */
    this.maxLength = -1;
    /**
     * Defines the most negative value in the range of permitted values.
     *
     * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#min
     */
    this.min = '';
    /**
     * The minimum number of characters a user can enter into the text field. Set
     * to -1 for none.
     *
     * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#minlength
     */
    this.minLength = -1;
    /**
     * When true, hide the spinner for `type="number"` text fields.
     */
    this.noSpinner = false;
    /**
     * A regular expression that the text field's value must match to pass
     * constraint validation.
     *
     * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#pattern
     */
    this.pattern = '';
    /**
     * Defines the text displayed in the textfield when it has no value. Provides
     * a brief hint to the user as to the expected type of data that should be
     * entered into the control. Unlike `label`, the placeholder is not visible
     * and does not float when the textfield has a value.
     *
     * https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/placeholder
     */
    this.placeholder = '';
    /**
     * Indicates whether or not a user should be able to edit the text field's
     * value.
     *
     * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#readonly
     */
    this.readOnly = false;
    /**
     * Indicates that input accepts multiple email addresses.
     *
     * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email#multiple
     */
    this.multiple = false;
    /**
     * Returns or sets the element's step attribute, which works with min and max
     * to limit the increments at which a numeric or date-time value can be set.
     *
     * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#step
     */
    this.step = '';
    /**
     * The `<input>` type to use, defaults to "text". The type greatly changes how
     * the text field behaves.
     *
     * Text fields support a limited number of `<input>` types:
     *
     * - text
     * - textarea
     * - email
     * - number
     * - password
     * - search
     * - tel
     * - url
     *
     * See
     * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#input_types
     * for more details on each input type.
     */
    this.type = 'text';
    /**
     * Describes what, if any, type of autocomplete functionality the input
     * should provide.
     *
     * https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete
     */
    this.autocomplete = '';
    /**
     * Returns true when the text field has been interacted with. Native
     * validation errors only display in response to user interactions.
     */
    this.dirty = false;
    this.focused = false;
    /**
     * Whether or not a native error has been reported via `reportValidity()`.
     */
    this.nativeError = false;
    /**
     * The validation message displayed from a native error via
     * `reportValidity()`.
     */
    this.nativeErrorText = '';
  }
  /**
   * Gets or sets the direction in which selection occurred.
   */
  get selectionDirection() {
    return this.getInputOrTextarea().selectionDirection;
  }
  set selectionDirection(value) {
    this.getInputOrTextarea().selectionDirection = value;
  }
  /**
   * Gets or sets the end position or offset of a text selection.
   */
  get selectionEnd() {
    return this.getInputOrTextarea().selectionEnd;
  }
  set selectionEnd(value) {
    this.getInputOrTextarea().selectionEnd = value;
  }
  /**
   * Gets or sets the starting position or offset of a text selection.
   */
  get selectionStart() {
    return this.getInputOrTextarea().selectionStart;
  }
  set selectionStart(value) {
    this.getInputOrTextarea().selectionStart = value;
  }
  /**
   * The text field's value as a number.
   */
  get valueAsNumber() {
    const input = this.getInput();
    if (!input) {
      return NaN;
    }
    return input.valueAsNumber;
  }
  set valueAsNumber(value) {
    const input = this.getInput();
    if (!input) {
      return;
    }
    input.valueAsNumber = value;
    this.value = input.value;
  }
  /**
   * The text field's value as a Date.
   */
  get valueAsDate() {
    const input = this.getInput();
    if (!input) {
      return null;
    }
    return input.valueAsDate;
  }
  set valueAsDate(value) {
    const input = this.getInput();
    if (!input) {
      return;
    }
    input.valueAsDate = value;
    this.value = input.value;
  }
  get hasError() {
    return this.error || this.nativeError;
  }
  /**
   * Selects all the text in the text field.
   *
   * https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select
   */
  select() {
    this.getInputOrTextarea().select();
  }
  setRangeText(...args) {
    // Calling setRangeText with 1 vs 3-4 arguments has different behavior.
    // Use spread syntax and type casting to ensure correct usage.
    this.getInputOrTextarea().setRangeText(...args);
    this.value = this.getInputOrTextarea().value;
  }
  /**
   * Sets the start and end positions of a selection in the text field.
   *
   * https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange
   *
   * @param start The offset into the text field for the start of the selection.
   * @param end The offset into the text field for the end of the selection.
   * @param direction The direction in which the selection is performed.
   */
  setSelectionRange(start, end, direction) {
    this.getInputOrTextarea().setSelectionRange(start, end, direction);
  }
  /**
   * Shows the browser picker for an input element of type "date", "time", etc.
   *
   * For a full list of supported types, see:
   * https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/showPicker#browser_compatibility
   *
   * https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/showPicker
   */
  showPicker() {
    const input = this.getInput();
    if (!input) {
      return;
    }
    input.showPicker();
  }
  /**
   * Decrements the value of a numeric type text field by `step` or `n` `step`
   * number of times.
   *
   * https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/stepDown
   *
   * @param stepDecrement The number of steps to decrement, defaults to 1.
   */
  stepDown(stepDecrement) {
    const input = this.getInput();
    if (!input) {
      return;
    }
    input.stepDown(stepDecrement);
    this.value = input.value;
  }
  /**
   * Increments the value of a numeric type text field by `step` or `n` `step`
   * number of times.
   *
   * https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/stepUp
   *
   * @param stepIncrement The number of steps to increment, defaults to 1.
   */
  stepUp(stepIncrement) {
    const input = this.getInput();
    if (!input) {
      return;
    }
    input.stepUp(stepIncrement);
    this.value = input.value;
  }
  /**
   * Reset the text field to its default value.
   */
  reset() {
    this.dirty = false;
    this.value = this.getAttribute('value') ?? '';
    this.nativeError = false;
    this.nativeErrorText = '';
  }
  attributeChangedCallback(attribute, newValue, oldValue) {
    if (attribute === 'value' && this.dirty) {
      // After user input, changing the value attribute no longer updates the
      // text field's value (until reset). This matches native <input> behavior.
      return;
    }
    super.attributeChangedCallback(attribute, newValue, oldValue);
  }
  render() {
    const classes = {
      'disabled': this.disabled,
      'error': !this.disabled && this.hasError,
      'textarea': this.type === 'textarea',
      'no-spinner': this.noSpinner
    };
    return b`
      <span class="text-field ${e$3(classes)}">
        ${this.renderField()}
      </span>
    `;
  }
  updated(changedProperties) {
    // Keep changedProperties arg so that subclasses may call it
    // If a property such as `type` changes and causes the internal <input>
    // value to change without dispatching an event, re-sync it.
    const value = this.getInputOrTextarea().value;
    if (this.value !== value) {
      // Note this is typically inefficient in updated() since it schedules
      // another update. However, it is needed for the <input> to fully render
      // before checking its value.
      this.value = value;
    }
  }
  renderField() {
    return u`<${this.fieldTag}
      class="field"
      count=${this.value.length}
      ?disabled=${this.disabled}
      ?error=${this.hasError}
      error-text=${this.getErrorText()}
      ?focused=${this.focused}
      ?has-end=${this.hasTrailingIcon}
      ?has-start=${this.hasLeadingIcon}
      label=${this.label}
      ?no-asterisk=${this.noAsterisk}
      max=${this.maxLength}
      ?populated=${!!this.value}
      ?required=${this.required}
      ?resizable=${this.type === 'textarea'}
      supporting-text=${this.supportingText}
    >
      ${this.renderLeadingIcon()}
      ${this.renderInputOrTextarea()}
      ${this.renderTrailingIcon()}
      <div id="description" slot="aria-describedby"></div>
      <slot name="container" slot="container"></slot>
    </${this.fieldTag}>`;
  }
  renderLeadingIcon() {
    return b`
      <span class="icon leading" slot="start">
        <slot name="leading-icon" @slotchange=${this.handleIconChange}></slot>
      </span>
    `;
  }
  renderTrailingIcon() {
    return b`
      <span class="icon trailing" slot="end">
        <slot name="trailing-icon" @slotchange=${this.handleIconChange}></slot>
      </span>
    `;
  }
  renderInputOrTextarea() {
    const style = {
      'direction': this.textDirection
    };
    const ariaLabel = this.ariaLabel || this.label || A;
    // lit-anaylzer `autocomplete` types are too strict
    // tslint:disable-next-line:no-any
    const autocomplete = this.autocomplete;
    // These properties may be set to null if the attribute is removed, and
    // `null > -1` is incorrectly `true`.
    const hasMaxLength = (this.maxLength ?? -1) > -1;
    const hasMinLength = (this.minLength ?? -1) > -1;
    if (this.type === 'textarea') {
      return b`
        <textarea
          class="input"
          style=${o$2(style)}
          aria-describedby="description"
          aria-invalid=${this.hasError}
          aria-label=${ariaLabel}
          autocomplete=${autocomplete || A}
          name=${this.name || A}
          ?disabled=${this.disabled}
          maxlength=${hasMaxLength ? this.maxLength : A}
          minlength=${hasMinLength ? this.minLength : A}
          placeholder=${this.placeholder || A}
          ?readonly=${this.readOnly}
          ?required=${this.required}
          rows=${this.rows}
          cols=${this.cols}
          .value=${l(this.value)}
          @change=${this.redispatchEvent}
          @focus=${this.handleFocusChange}
          @blur=${this.handleFocusChange}
          @input=${this.handleInput}
          @select=${this.redispatchEvent}></textarea>
      `;
    }
    const prefix = this.renderPrefix();
    const suffix = this.renderSuffix();
    // TODO(b/243805848): remove `as unknown as number` and `as any` once lit
    // analyzer is fixed
    // tslint:disable-next-line:no-any
    const inputMode = this.inputMode;
    return b`
      <div class="input-wrapper">
        ${prefix}
        <input
          class="input"
          style=${o$2(style)}
          aria-describedby="description"
          aria-invalid=${this.hasError}
          aria-label=${ariaLabel}
          autocomplete=${autocomplete || A}
          name=${this.name || A}
          ?disabled=${this.disabled}
          inputmode=${inputMode || A}
          max=${this.max || A}
          maxlength=${hasMaxLength ? this.maxLength : A}
          min=${this.min || A}
          minlength=${hasMinLength ? this.minLength : A}
          pattern=${this.pattern || A}
          placeholder=${this.placeholder || A}
          ?readonly=${this.readOnly}
          ?required=${this.required}
          ?multiple=${this.multiple}
          step=${this.step || A}
          type=${this.type}
          .value=${l(this.value)}
          @change=${this.redispatchEvent}
          @focus=${this.handleFocusChange}
          @blur=${this.handleFocusChange}
          @input=${this.handleInput}
          @select=${this.redispatchEvent} />
        ${suffix}
      </div>
    `;
  }
  renderPrefix() {
    return this.renderAffix(this.prefixText, /* isSuffix */false);
  }
  renderSuffix() {
    return this.renderAffix(this.suffixText, /* isSuffix */true);
  }
  renderAffix(text, isSuffix) {
    if (!text) {
      return A;
    }
    const classes = {
      'suffix': isSuffix,
      'prefix': !isSuffix
    };
    return b`<span class="${e$3(classes)}">${text}</span>`;
  }
  getErrorText() {
    return this.error ? this.errorText : this.nativeErrorText;
  }
  handleFocusChange() {
    // When calling focus() or reportValidity() during change, it's possible
    // for blur to be called after the new focus event. Rather than set
    // `this.focused` to true/false on focus/blur, we always set it to whether
    // or not the input itself is focused.
    this.focused = this.inputOrTextarea?.matches(':focus') ?? false;
  }
  handleInput(event) {
    this.dirty = true;
    this.value = event.target.value;
  }
  redispatchEvent(event) {
    redispatchEvent(this, event);
  }
  getInputOrTextarea() {
    if (!this.inputOrTextarea) {
      // If the input is not yet defined, synchronously render.
      // e.g.
      // const textField = document.createElement('md-outlined-text-field');
      // document.body.appendChild(textField);
      // textField.focus(); // synchronously render
      this.connectedCallback();
      this.scheduleUpdate();
    }
    if (this.isUpdatePending) {
      // If there are pending updates, synchronously perform them. This ensures
      // that constraint validation properties (like `required`) are synced
      // before interacting with input APIs that depend on them.
      this.scheduleUpdate();
    }
    return this.inputOrTextarea;
  }
  getInput() {
    if (this.type === 'textarea') {
      return null;
    }
    return this.getInputOrTextarea();
  }
  handleIconChange() {
    this.hasLeadingIcon = this.leadingIcons.length > 0;
    this.hasTrailingIcon = this.trailingIcons.length > 0;
  }
  [getFormValue]() {
    return this.value;
  }
  formResetCallback() {
    this.reset();
  }
  formStateRestoreCallback(state) {
    this.value = state;
  }
  focus() {
    // Required for the case that the user slots a focusable element into the
    // leading icon slot such as an iconbutton due to how delegatesFocus works.
    this.getInputOrTextarea().focus();
  }
  [createValidator]() {
    return new TextFieldValidator(() => ({
      state: this,
      renderedControl: this.inputOrTextarea
    }));
  }
  [getValidityAnchor]() {
    return this.inputOrTextarea;
  }
  [onReportValidity](invalidEvent) {
    // Prevent default pop-up behavior.
    invalidEvent?.preventDefault();
    const prevMessage = this.getErrorText();
    this.nativeError = !!invalidEvent;
    this.nativeErrorText = this.validationMessage;
    if (prevMessage === this.getErrorText()) {
      this.field?.reannounceError();
    }
  }
}
/** @nocollapse */
TextField.shadowRootOptions = {
  ...i$4.shadowRootOptions,
  delegatesFocus: true
};
__decorate([n$5({
  type: Boolean,
  reflect: true
})], TextField.prototype, "error", void 0);
__decorate([n$5({
  attribute: 'error-text'
})], TextField.prototype, "errorText", void 0);
__decorate([n$5()], TextField.prototype, "label", void 0);
__decorate([n$5({
  type: Boolean,
  attribute: 'no-asterisk'
})], TextField.prototype, "noAsterisk", void 0);
__decorate([n$5({
  type: Boolean,
  reflect: true
})], TextField.prototype, "required", void 0);
__decorate([n$5()], TextField.prototype, "value", void 0);
__decorate([n$5({
  attribute: 'prefix-text'
})], TextField.prototype, "prefixText", void 0);
__decorate([n$5({
  attribute: 'suffix-text'
})], TextField.prototype, "suffixText", void 0);
__decorate([n$5({
  type: Boolean,
  attribute: 'has-leading-icon'
})], TextField.prototype, "hasLeadingIcon", void 0);
__decorate([n$5({
  type: Boolean,
  attribute: 'has-trailing-icon'
})], TextField.prototype, "hasTrailingIcon", void 0);
__decorate([n$5({
  attribute: 'supporting-text'
})], TextField.prototype, "supportingText", void 0);
__decorate([n$5({
  attribute: 'text-direction'
})], TextField.prototype, "textDirection", void 0);
__decorate([n$5({
  type: Number
})], TextField.prototype, "rows", void 0);
__decorate([n$5({
  type: Number
})], TextField.prototype, "cols", void 0);
__decorate([n$5({
  reflect: true
})], TextField.prototype, "inputMode", void 0);
__decorate([n$5()], TextField.prototype, "max", void 0);
__decorate([n$5({
  type: Number
})], TextField.prototype, "maxLength", void 0);
__decorate([n$5()], TextField.prototype, "min", void 0);
__decorate([n$5({
  type: Number
})], TextField.prototype, "minLength", void 0);
__decorate([n$5({
  type: Boolean,
  attribute: 'no-spinner'
})], TextField.prototype, "noSpinner", void 0);
__decorate([n$5()], TextField.prototype, "pattern", void 0);
__decorate([n$5({
  reflect: true,
  converter: stringConverter
})], TextField.prototype, "placeholder", void 0);
__decorate([n$5({
  type: Boolean,
  reflect: true
})], TextField.prototype, "readOnly", void 0);
__decorate([n$5({
  type: Boolean,
  reflect: true
})], TextField.prototype, "multiple", void 0);
__decorate([n$5()], TextField.prototype, "step", void 0);
__decorate([n$5({
  reflect: true
})], TextField.prototype, "type", void 0);
__decorate([n$5({
  reflect: true
})], TextField.prototype, "autocomplete", void 0);
__decorate([r$3()], TextField.prototype, "dirty", void 0);
__decorate([r$3()], TextField.prototype, "focused", void 0);
__decorate([r$3()], TextField.prototype, "nativeError", void 0);
__decorate([r$3()], TextField.prototype, "nativeErrorText", void 0);
__decorate([e$6('.input')], TextField.prototype, "inputOrTextarea", void 0);
__decorate([e$6('.field')], TextField.prototype, "field", void 0);
__decorate([o$5({
  slot: 'leading-icon'
})], TextField.prototype, "leadingIcons", void 0);
__decorate([o$5({
  slot: 'trailing-icon'
})], TextField.prototype, "trailingIcons", void 0);

/**
 * @license
 * Copyright 2021 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * An outlined text field component
 */
class OutlinedTextField extends TextField {
  constructor() {
    super(...arguments);
    this.fieldTag = i$2`md-outlined-field`;
  }
}

/**
 * @license
 * Copyright 2024 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Generated stylesheet for ./textfield/internal/shared-styles.css.
const styles$3 = i$7`:host{display:inline-flex;outline:none;resize:both;text-align:start;-webkit-tap-highlight-color:rgba(0,0,0,0)}.text-field,.field{width:100%}.text-field{display:inline-flex}.field{cursor:text}.disabled .field{cursor:default}.text-field,.textarea .field{resize:inherit}slot[name=container]{border-radius:inherit}.icon{color:currentColor;display:flex;align-items:center;justify-content:center;fill:currentColor;position:relative}.icon ::slotted(*){display:flex;position:absolute}[has-start] .icon.leading{font-size:var(--_leading-icon-size);height:var(--_leading-icon-size);width:var(--_leading-icon-size)}[has-end] .icon.trailing{font-size:var(--_trailing-icon-size);height:var(--_trailing-icon-size);width:var(--_trailing-icon-size)}.input-wrapper{display:flex}.input-wrapper>*{all:inherit;padding:0}.input{caret-color:var(--_caret-color);overflow-x:hidden;text-align:inherit}.input::placeholder{color:currentColor;opacity:1}.input::-webkit-calendar-picker-indicator{display:none}.input::-webkit-search-decoration,.input::-webkit-search-cancel-button{display:none}@media(forced-colors: active){.input{background:none}}.no-spinner .input::-webkit-inner-spin-button,.no-spinner .input::-webkit-outer-spin-button{display:none}.no-spinner .input[type=number]{-moz-appearance:textfield}:focus-within .input{caret-color:var(--_focus-caret-color)}.error:focus-within .input{caret-color:var(--_error-focus-caret-color)}.text-field:not(.disabled) .prefix{color:var(--_input-text-prefix-color)}.text-field:not(.disabled) .suffix{color:var(--_input-text-suffix-color)}.text-field:not(.disabled) .input::placeholder{color:var(--_input-text-placeholder-color)}.prefix,.suffix{text-wrap:nowrap;width:min-content}.prefix{padding-inline-end:var(--_input-text-prefix-trailing-space)}.suffix{padding-inline-start:var(--_input-text-suffix-leading-space)}
`;

/**
 * @license
 * Copyright 2021 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * TODO(b/228525797): Add docs
 * @final
 * @suppress {visibility}
 */
let MdOutlinedTextField = class MdOutlinedTextField extends OutlinedTextField {
  constructor() {
    super(...arguments);
    this.fieldTag = i$2`md-outlined-field`;
  }
};
MdOutlinedTextField.styles = [styles$3, styles$4];
MdOutlinedTextField = __decorate([t$1('md-outlined-text-field')], MdOutlinedTextField);

/**
 * @license
 * Copyright 2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
const NODE_LABEL_CLUSTER_ID = 40;
const NODE_LABEL_ATTRIBUTE_ID = 5;
const MAX_NODE_LABEL_LENGTH = 32;
const NODE_LABEL_ATTRIBUTE_PATH = `0/${NODE_LABEL_CLUSTER_ID}/${NODE_LABEL_ATTRIBUTE_ID}`;
function writeNodeLabel(client, node, label) {
  return client.writeAttribute(node.node_id, NODE_LABEL_ATTRIBUTE_PATH, label.trim());
}

var __defProp$f = Object.defineProperty;
var __getOwnPropDesc$h = Object.getOwnPropertyDescriptor;
var __decorateClass$i = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$h(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp$f(target, key, result);
  return result;
};
let BasicInformationClusterCommands = class extends BaseClusterCommands {
  constructor() {
    super(...arguments);
    this._nodeLabel = "";
    this._saving = false;
  }
  updated(changedProperties) {
    super.updated(changedProperties);
    if (changedProperties.has("node") && this.node) {
      this._loadCurrentNodeLabel();
    }
  }
  /**
   * Load the current NodeLabel from the node's cached attributes.
   */
  _loadCurrentNodeLabel() {
    if (!this.node) {
      return;
    }
    this._nodeLabel = this.node.nodeLabel;
  }
  /**
   * Check if the node is available (not offline).
   */
  get _isNodeAvailable() {
    return this.node.available;
  }
  render() {
    return b`
            <details class="command-panel">
                <summary>Node Label</summary>
                <div class="command-content">
                    ${!this._isNodeAvailable ? b` <div class="offline-warning">Node is offline - cannot edit label</div> ` : A}
                    <div class="command-row">
                        <md-outlined-text-field
                            label="Node Label"
                            .value=${this._nodeLabel}
                            @input=${this._handleInput}
                            maxlength=${MAX_NODE_LABEL_LENGTH}
                            ?disabled=${!this._isNodeAvailable || this._saving}
                            supporting-text="Max ${MAX_NODE_LABEL_LENGTH} characters"
                        ></md-outlined-text-field>
                        <md-filled-button
                            @click=${handleAsync(() => this._handleSave())}
                            ?disabled=${!this._isNodeAvailable || this._saving}
                        >
                            ${this._saving ? "Saving..." : "Save"}
                        </md-filled-button>
                    </div>
                </div>
            </details>
        `;
  }
  _handleInput(e) {
    const input = e.target;
    this._nodeLabel = input.value;
  }
  async _handleSave() {
    if (!this._isNodeAvailable) {
      showAlertDialog({
        title: "Cannot Save",
        text: "Node is offline. Please wait until the node is available."
      });
      return;
    }
    this._saving = true;
    try {
      const label = this._nodeLabel.trim();
      await writeNodeLabel(this.client, this.node, label);
      this._nodeLabel = label;
      showAlertDialog({
        title: "Success",
        text: `Node label set to "${label}"`
      });
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      showAlertDialog({
        title: "Failed to set node label",
        text: errorMessage
      });
    } finally {
      this._saving = false;
    }
  }
};
BasicInformationClusterCommands.styles = [BaseClusterCommands.styles, i$7`
            .command-row {
                align-items: flex-start;
            }

            md-outlined-text-field {
                width: 36ch; /* 32 chars + some padding for field chrome */
            }

            md-filled-button {
                margin-top: 8px; /* Align with text field input area, accounting for label */
            }

            .offline-warning {
                color: var(--danger-color, #d32f2f);
                font-size: 14px;
                margin-bottom: 12px;
                padding: 8px 12px;
                background-color: var(--md-sys-color-error-container, #fdecea);
                border-radius: 4px;
            }
        `];
__decorateClass$i([r$3()], BasicInformationClusterCommands.prototype, "_nodeLabel", 2);
__decorateClass$i([r$3()], BasicInformationClusterCommands.prototype, "_saving", 2);
BasicInformationClusterCommands = __decorateClass$i([t$1("basic-information-cluster-commands")], BasicInformationClusterCommands);
registerClusterCommands(NODE_LABEL_CLUSTER_ID, "basic-information-cluster-commands");

/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
function toBindingTarget(e) {
  return {
    node: e.node ?? null,
    group: e.group ?? null,
    endpoint: e.endpoint ?? null,
    cluster: e.cluster ?? null
  };
}
function toApiAcl(e) {
  return {
    privilege: e.privilege,
    auth_mode: e.authMode,
    subjects: e.subjects ?? null,
    targets: e.targets?.map(t => ({
      cluster: t.cluster ?? null,
      endpoint: t.endpoint ?? null,
      device_type: t.deviceType ?? null
    })) ?? null
  };
}
function requireFabricIndex(res, nodeId) {
  const fi = res["0/62/5"];
  if (typeof fi !== "number") {
    throw new Error(`Cannot determine the current fabric index (0/62/5) for node ${nodeId}`);
  }
  return fi;
}
async function freshOurAcl(client, nodeId) {
  const res = await client.readAttribute(nodeId, ["0/31/0", "0/62/5"]);
  const all = attributeArray(res["0/31/0"]).map(v => AccessControlEntryDataTransformer.transform(v));
  return entriesForFabric(all, requireFabricIndex(res, nodeId));
}
async function freshOurBindings(client, nodeId, endpoint) {
  const res = await client.readAttribute(nodeId, [`${endpoint}/30/0`, "0/62/5"]);
  const all = attributeArray(res[`${endpoint}/30/0`]).map(v => BindingEntryDataTransformer.transform(v));
  const fabricIndex = requireFabricIndex(res, nodeId);
  return all.filter(b => b.fabricIndex === fabricIndex);
}
function hasTarget(e, endpoint, cluster) {
  return (e.targets ?? []).some(t => t.endpoint === endpoint && t.cluster === cluster);
}
function aclTargetsMax(client, nodeId) {
  const raw = client.nodes[nodeIdKey(nodeId)]?.attributes["0/31/3"];
  return typeof raw === "number" && raw > 0 ? raw : Number.MAX_SAFE_INTEGER;
}
async function ensureBindingAcl(client, sourceNodeId, targetNodeId, targetEndpoint, cluster) {
  if (nodeIdKey(targetNodeId) === nodeIdKey(sourceNodeId)) return;
  const acl = await freshOurAcl(client, targetNodeId);
  const alreadyGranted = acl.some(e => e.authMode === AuthMode.Case && e.privilege >= Privilege.Operate && subjectsInclude(e, sourceNodeId) && entryMatchesTarget(e, targetEndpoint, cluster));
  if (alreadyGranted) return;
  const targetsMax = aclTargetsMax(client, targetNodeId);
  const reusable = acl.find(e => e.authMode === AuthMode.Case && e.privilege >= Privilege.Operate && subjectsInclude(e, sourceNodeId) && (isWholeNode(e) || hasTarget(e, targetEndpoint, cluster) || (e.targets?.length ?? 0) < targetsMax));
  if (reusable) {
    if (!isWholeNode(reusable) && !hasTarget(reusable, targetEndpoint, cluster)) {
      reusable.targets = reusable.targets ?? [];
      reusable.targets.push({
        endpoint: targetEndpoint,
        cluster,
        deviceType: void 0
      });
    }
  } else {
    acl.push({
      privilege: Privilege.Operate,
      authMode: AuthMode.Case,
      subjects: [sourceNodeId],
      targets: [{
        endpoint: targetEndpoint,
        cluster,
        deviceType: void 0
      }],
      fabricIndex: 0
    });
  }
  await client.setACLEntry(targetNodeId, acl.map(toApiAcl));
}
async function fixOverPrivilegedBindingAcl(client, sourceNodeId, targetNodeId, targetEndpoint, cluster) {
  const acl = await freshOurAcl(client, targetNodeId);
  const updated = acl.map(e => e.authMode === AuthMode.Case && subjectsInclude(e, sourceNodeId) && e.privilege > Privilege.Operate && entryMatchesTarget(e, targetEndpoint, cluster) ? {
    ...e,
    privilege: Privilege.Operate
  } : e);
  await client.setACLEntry(targetNodeId, updated.map(toApiAcl));
}
async function addBinding(client, sourceNode, sourceEndpoint, targetNodeId, targetEndpoint, cluster) {
  await ensureBindingAcl(client, sourceNode.node_id, targetNodeId, targetEndpoint, cluster);
  const bindings = await freshOurBindings(client, sourceNode.node_id, sourceEndpoint);
  const targetKey = nodeIdKey(targetNodeId);
  const exists = bindings.some(b => b.node != null && nodeIdKey(b.node) === targetKey && b.endpoint === targetEndpoint && b.cluster === cluster);
  if (exists) return;
  bindings.push({
    node: targetNodeId,
    group: void 0,
    endpoint: targetEndpoint,
    cluster,
    fabricIndex: void 0
  });
  await client.setNodeBinding(sourceNode.node_id, sourceEndpoint, bindings.map(toBindingTarget));
}
async function deleteBindingAtIndex(client, sourceNode, sourceEndpoint, index) {
  const bindings = await freshOurBindings(client, sourceNode.node_id, sourceEndpoint);
  const removed = bindings[index];
  if (!removed) return;
  const updated = [...bindings.slice(0, index), ...bindings.slice(index + 1)];
  await client.setNodeBinding(sourceNode.node_id, sourceEndpoint, updated.map(toBindingTarget));
  if (removed.node == null || removed.endpoint == null) return;
  if (nodeIdKey(removed.node) === nodeIdKey(sourceNode.node_id)) return;
  const targetEndpoint = removed.endpoint;
  const removedCluster = removed.cluster;
  try {
    const acl = await freshOurAcl(client, removed.node);
    const kept = acl.map(e => {
      if (!subjectsInclude(e, sourceNode.node_id) || isWholeNode(e)) return e;
      const targets = e.targets.filter(t => !(t.endpoint === targetEndpoint && t.cluster === removedCluster));
      if (targets.length === 0) return void 0;
      return {
        ...e,
        targets
      };
    }).filter(e => e !== void 0);
    await client.setACLEntry(removed.node, kept.map(toApiAcl));
  } catch (err) {
    const detail = err instanceof Error ? err.message : String(err);
    throw new Error(`Binding removed, but cleaning up the access control entry on the target node failed: ${detail}. The target may retain a stale access grant.`);
  }
}

/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
const showNodeBindingDialog = async (node, endpoint) => {
  await import('./node-binding-dialog-VnKnuV9C.js');
  const dialog = document.createElement("node-binding-dialog");
  dialog.node = node;
  dialog.endpoint = endpoint;
  document.querySelector("matter-dashboard-app")?.renderRoot.appendChild(dialog);
};

var __defProp$e = Object.defineProperty;
var __getOwnPropDesc$g = Object.getOwnPropertyDescriptor;
var __decorateClass$h = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$g(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp$e(target, key, result);
  return result;
};
const CLUSTER_ID$2 = 30;
let BindingClusterCommands = class extends BaseClusterCommands {
  constructor() {
    super(...arguments);
    this._loadedKey = "";
    this._busy = false;
  }
  updated(changed) {
    super.updated(changed);
    if (changed.has("client") && this.client && !this._unsubscribe) {
      this._unsubscribe = this.client.addEventListener("nodes_changed", () => this.requestUpdate());
    }
    void this._ensureLoaded();
  }
  disconnectedCallback() {
    super.disconnectedCallback();
    this._unsubscribe?.();
  }
  /** Read the (fabric-scoped) binding attribute and each target's ACL into the cache on open. */
  async _ensureLoaded() {
    if (!this.client || !this.node || !this.node.available || this.endpoint === void 0) return;
    const key = `${nodeIdKey(this.node.node_id)}/${this.endpoint}`;
    if (this._loadedKey === key) return;
    this._loadedKey = key;
    try {
      await this._readInto(this.node.node_id, [`${this.endpoint}/30/0`, "0/62/5"]);
      const targets = new Set(readBindings(this.node, this.endpoint).map(b => b.node != null ? nodeIdKey(b.node) : void 0).filter(k => k !== void 0));
      await Promise.all([...targets].map(k => {
        const target = this.client.nodes[k];
        return target?.available ? this._readInto(target.node_id, ["0/31/0", "0/62/5"]) : void 0;
      }));
      this.requestUpdate();
    } catch (err) {
      this._loadedKey = "";
      console.error("Failed to load binding/ACL data", err);
    }
  }
  async _readInto(nodeId, path) {
    const res = await this.client.readAttribute(nodeId, path);
    const node = this.client.nodes[nodeIdKey(nodeId)];
    if (node) for (const [k, v] of Object.entries(res)) node.attributes[k] = v;
  }
  _clusterName(id) {
    if (id == null) return "All clusters";
    return `${clusters[id]?.label ?? "Cluster"} (0x${id.toString(16).padStart(2, "0").toUpperCase()})`;
  }
  _targetNode(nodeId) {
    if (nodeId == null) return void 0;
    return this.client.nodes[nodeIdKey(nodeId)];
  }
  async _openAdd() {
    await showNodeBindingDialog(this.node, this.endpoint);
  }
  async _run(action, failTitle) {
    this._busy = true;
    try {
      await action();
    } catch (err) {
      await showAlertDialog({
        title: failTitle,
        text: err instanceof Error ? err.message : String(err)
      });
    } finally {
      this._busy = false;
    }
  }
  async _delete(index) {
    const confirmed = await showPromptDialog({
      title: "Remove binding",
      text: "Remove this binding and clean up the matching access control entry on the target node?",
      confirmText: "Remove"
    });
    if (!confirmed) return;
    await this._run(() => deleteBindingAtIndex(this.client, this.node, this.endpoint, index), "Delete failed");
  }
  async _fixAcl(b, mode) {
    if (b.node == null || b.endpoint == null) return;
    await this._run(() => mode === "missing" ? ensureBindingAcl(this.client, this.node.node_id, b.node, b.endpoint, b.cluster) : fixOverPrivilegedBindingAcl(this.client, this.node.node_id, b.node, b.endpoint, b.cluster), "Fix failed");
  }
  render() {
    if (!this.node || this.cluster !== CLUSTER_ID$2) return A;
    const bindings = readBindings(this.node, this.endpoint);
    return b`
            <details class="command-panel">
                <summary>Bindings (${bindings.length})</summary>
                <div class="command-content">
                    ${bindings.length === 0 ? b`<div class="empty">No bindings on this endpoint.</div>` : b`<table class="bt">
                              <thead>
                                  <tr>
                                      <th>Target node</th>
                                      <th>Endpoint</th>
                                      <th>Cluster</th>
                                      <th>ACL on target</th>
                                      <th></th>
                                  </tr>
                              </thead>
                              <tbody>
                                  ${bindings.map((b, i) => this._row(b, i))}
                              </tbody>
                          </table>`}
                    <md-outlined-button
                        ?disabled=${this._busy || !this.node.available}
                        @click=${handleAsync(() => this._openAdd())}
                        >Add binding</md-outlined-button
                    >
                </div>
            </details>
        `;
  }
  _row(b$1, index) {
    const target = this._targetNode(b$1.node);
    const aclState = b$1.node == null ? "cannotVerify" : reverseAclState(this.node.node_id, b$1, target).state;
    const name = b$1.group != null ? `Group ${b$1.group}` : target ? getDeviceName(target) : "Unknown node";
    const deviceType = b$1.endpoint != null && target ? getEndpointDeviceTypes(target, b$1.endpoint)[0] : void 0;
    const endpointText = b$1.endpoint == null ? "\u2014" : deviceType ? `EP ${b$1.endpoint} \xB7 ${deviceType.label}` : `EP ${b$1.endpoint}`;
    return b`
            <tr>
                <td>
                    <span class="ident"
                        ><b>${name}</b>${b$1.node != null ? b` · <span class="nid">${b$1.node.toString()}</span>` : A}</span
                    >
                </td>
                <td>${endpointText}</td>
                <td>${this._clusterName(b$1.cluster)}</td>
                <td>${this._aclCell(b$1, aclState)}</td>
                <td class="actions">
                    <md-outlined-button
                        class="danger"
                        ?disabled=${this._busy || !this.node.available}
                        @click=${handleAsync(() => this._delete(index))}
                    >
                        <ha-svg-icon .path=${mdiTrashCan} slot="icon"></ha-svg-icon>delete
                    </md-outlined-button>
                </td>
            </tr>
        `;
  }
  _aclCell(b$1, state2) {
    if (state2 === "self") return b`<span class="status mut">self — no ACL needed</span>`;
    if (state2 === "present") return b`<span class="status ok">ACL present</span>`;
    if (state2 === "cannotVerify") return b`<span class="status mut">can't verify</span>`;
    const label = state2 === "missing" ? "ACL missing" : "ACL > Operate";
    const fixLabel = state2 === "missing" ? "Fix ACL" : "Fix \u2192 Operate";
    return b`
            <span class="status warn">${label}</span>
            <md-outlined-button
                class="fix"
                ?disabled=${this._busy || !this.node.available}
                @click=${handleAsync(() => this._fixAcl(b$1, state2))}
                >${fixLabel}</md-outlined-button
            >
        `;
  }
};
BindingClusterCommands.styles = [BaseClusterCommands.styles, i$7`
            .bt {
                width: 100%;
                border-collapse: collapse;
                margin-bottom: 12px;
            }
            .bt th {
                text-align: left;
                font-size: 11px;
                text-transform: uppercase;
                opacity: 0.6;
                padding: 8px 10px;
                border-bottom: 1px solid var(--md-sys-color-outline-variant);
            }
            .bt td {
                padding: 10px;
                border-bottom: 1px solid var(--md-sys-color-outline-variant);
                vertical-align: middle;
            }
            .empty {
                opacity: 0.6;
                padding: 8px 0 12px;
            }
            .ident .nid {
                font-weight: 600;
            }
            .status {
                font-size: inherit;
            }
            .status.ok {
                color: var(--md-sys-color-primary);
            }
            .status.warn {
                color: var(--md-sys-color-error);
                margin-right: 8px;
            }
            .status.mut {
                opacity: 0.6;
            }
            .actions {
                text-align: right;
                white-space: nowrap;
            }
            md-outlined-button.fix {
                --md-outlined-button-container-height: 28px;
            }
            md-outlined-button.danger {
                --md-outlined-button-label-text-color: var(--md-sys-color-error);
                --md-outlined-button-outline-color: var(--md-sys-color-error);
            }
        `];
__decorateClass$h([r$3()], BindingClusterCommands.prototype, "_busy", 2);
BindingClusterCommands = __decorateClass$h([t$1("binding-cluster-commands")], BindingClusterCommands);
registerClusterCommands(CLUSTER_ID$2, "binding-cluster-commands");

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * A symbol used to access dispatch hooks on an event.
 */
const dispatchHooks = Symbol('dispatchHooks');
/**
 * Add a hook for an event that is called after the event is dispatched and
 * propagates to other event listeners.
 *
 * This is useful for behaviors that need to check if an event is canceled.
 *
 * The callback is invoked synchronously, which allows for better integration
 * with synchronous platform APIs (like `<form>` or `<label>` clicking).
 *
 * Note: `setupDispatchHooks()` must be called on the element before adding any
 * other event listeners. Call it in the constructor of an element or
 * controller.
 *
 * @example
 * ```ts
 * class MyControl extends LitElement {
 *   constructor() {
 *     super();
 *     setupDispatchHooks(this, 'click');
 *     this.addEventListener('click', event => {
 *       afterDispatch(event, () => {
 *         if (event.defaultPrevented) {
 *           return
 *         }
 *
 *         // ... perform logic
 *       });
 *     });
 *   }
 * }
 * ```
 *
 * @example
 * ```ts
 * class MyController implements ReactiveController {
 *   constructor(host: ReactiveElement) {
 *     // setupDispatchHooks() may be called multiple times for the same
 *     // element and events, making it safe for multiple controllers to use it.
 *     setupDispatchHooks(host, 'click');
 *     host.addEventListener('click', event => {
 *       afterDispatch(event, () => {
 *         if (event.defaultPrevented) {
 *           return;
 *         }
 *
 *         // ... perform logic
 *       });
 *     });
 *   }
 * }
 * ```
 *
 * @param event The event to add a hook to.
 * @param callback A hook that is called after the event finishes dispatching.
 */
function afterDispatch(event, callback) {
  const hooks = event[dispatchHooks];
  if (!hooks) {
    throw new Error(`'${event.type}' event needs setupDispatchHooks().`);
  }
  hooks.addEventListener('after', callback);
}
/**
 * A lookup map of elements and event types that have a dispatch hook listener
 * set up. Used to ensure we don't set up multiple hook listeners on the same
 * element for the same event.
 */
const ELEMENT_DISPATCH_HOOK_TYPES = new WeakMap();
/**
 * Sets up an element to add dispatch hooks to given event types. This must be
 * called before adding any event listeners that need to use dispatch hooks
 * like `afterDispatch()`.
 *
 * This function is safe to call multiple times with the same element or event
 * types. Call it in the constructor of elements, mixins, and controllers to
 * ensure it is set up before external listeners.
 *
 * @example
 * ```ts
 * class MyControl extends LitElement {
 *   constructor() {
 *     super();
 *     setupDispatchHooks(this, 'click');
 *     this.addEventListener('click', this.listenerUsingAfterDispatch);
 *   }
 * }
 * ```
 *
 * @param element The element to set up event dispatch hooks for.
 * @param eventTypes The event types to add dispatch hooks to.
 */
function setupDispatchHooks(element, ...eventTypes) {
  let typesAlreadySetUp = ELEMENT_DISPATCH_HOOK_TYPES.get(element);
  if (!typesAlreadySetUp) {
    typesAlreadySetUp = new Set();
    ELEMENT_DISPATCH_HOOK_TYPES.set(element, typesAlreadySetUp);
  }
  for (const eventType of eventTypes) {
    // Don't register multiple dispatch hook listeners. A second registration
    // would lead to the second listener re-dispatching a re-dispatched event,
    // which can cause an infinite loop inside the other one.
    if (typesAlreadySetUp.has(eventType)) {
      continue;
    }
    // When we re-dispatch the event, it's going to immediately trigger this
    // listener again. Use a flag to ignore it.
    let isRedispatching = false;
    element.addEventListener(eventType, event => {
      if (isRedispatching) {
        return;
      }
      // Do not let the event propagate to any other listener (not just
      // bubbling listeners with `stopPropagation()`).
      event.stopImmediatePropagation();
      // Make a copy.
      const eventCopy = Reflect.construct(event.constructor, [event.type, event]);
      // Add hooks onto the event.
      const hooks = new EventTarget();
      eventCopy[dispatchHooks] = hooks;
      // Re-dispatch the event. We can't reuse `redispatchEvent()` since we
      // need to add the hooks to the copy before it's dispatched.
      isRedispatching = true;
      const dispatched = element.dispatchEvent(eventCopy);
      isRedispatching = false;
      if (!dispatched) {
        event.preventDefault();
      }
      // Synchronously call afterDispatch() hooks.
      hooks.dispatchEvent(new Event('after'));
    }, {
      // Ensure this listener runs before other listeners.
      // `setupDispatchHooks()` should be called in constructors to also
      // ensure they run before any other externally-added capture listeners.
      capture: true
    });
    typesAlreadySetUp.add(eventType);
  }
}

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * A validator that provides constraint validation that emulates
 * `<input type="checkbox">` validation.
 */
class CheckboxValidator extends Validator$2 {
  computeValidity(state) {
    if (!this.checkboxControl) {
      // Lazily create the platform input
      this.checkboxControl = document.createElement('input');
      this.checkboxControl.type = 'checkbox';
    }
    this.checkboxControl.checked = state.checked;
    this.checkboxControl.required = state.required;
    return {
      validity: this.checkboxControl.validity,
      validationMessage: this.checkboxControl.validationMessage
    };
  }
  equals(prev, next) {
    return prev.checked === next.checked && prev.required === next.required;
  }
  copy({
    checked,
    required
  }) {
    return {
      checked,
      required
    };
  }
}

/**
 * @license
 * Copyright 2021 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Separate variable needed for closure.
const switchBaseClass = mixinDelegatesAria(mixinConstraintValidation(mixinFormAssociated(mixinElementInternals(i$4))));
/**
 * @fires input {InputEvent} Fired whenever `selected` changes due to user
 * interaction (bubbles and composed).
 * @fires change {Event} Fired whenever `selected` changes due to user
 * interaction (bubbles).
 */
class Switch extends switchBaseClass {
  constructor() {
    super();
    /**
     * Puts the switch in the selected state and sets the form submission value to
     * the `value` property.
     */
    this.selected = false;
    /**
     * Shows both the selected and deselected icons.
     */
    this.icons = false;
    /**
     * Shows only the selected icon, and not the deselected icon. If `true`,
     * overrides the behavior of the `icons` property.
     */
    this.showOnlySelectedIcon = false;
    /**
     * When true, require the switch to be selected when participating in
     * form submission.
     *
     * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox#validation
     */
    this.required = false;
    /**
     * The value associated with this switch on form submission. `null` is
     * submitted when `selected` is `false`.
     */
    this.value = 'on';
    // This click listener does not currently need dispatch hooks since it does
    // not check `event.defaultPrevented`.
    this.addEventListener('click', event => {
      if (!isActivationClick(event) || !this.input) {
        return;
      }
      this.focus();
      dispatchActivationClick(this.input);
    });
    // Add the aria keyboard interaction pattern for switch and the Enter key.
    // See https://www.w3.org/WAI/ARIA/apg/patterns/switch/.
    setupDispatchHooks(this, 'keydown');
    this.addEventListener('keydown', event => {
      afterDispatch(event, () => {
        const ignoreEvent = event.defaultPrevented || event.key !== 'Enter';
        if (ignoreEvent || this.disabled || !this.input) {
          return;
        }
        this.input.click();
      });
    });
  }
  render() {
    return b`
      <div class="switch ${e$3(this.getRenderClasses())}">
        <input
          id="switch"
          class="touch"
          type="checkbox"
          role="switch"
          aria-label=${this.ariaLabel || A}
          ?checked=${this.selected}
          ?disabled=${this.disabled}
          ?required=${this.required}
          @input=${this.handleInput}
          @change=${this.handleChange} />

        <md-focus-ring part="focus-ring" for="switch"></md-focus-ring>
        <span class="track"> ${this.renderHandle()} </span>
      </div>
    `;
  }
  getRenderClasses() {
    return {
      'selected': this.selected,
      'unselected': !this.selected,
      'disabled': this.disabled
    };
  }
  renderHandle() {
    const classes = {
      'with-icon': this.showOnlySelectedIcon ? this.selected : this.icons
    };
    return b`
      ${this.renderTouchTarget()}
      <span class="handle-container">
        <md-ripple for="switch" ?disabled="${this.disabled}"></md-ripple>
        <span class="handle ${e$3(classes)}">
          ${this.shouldShowIcons() ? this.renderIcons() : b``}
        </span>
      </span>
    `;
  }
  renderIcons() {
    return b`
      <div class="icons">
        ${this.renderOnIcon()}
        ${this.showOnlySelectedIcon ? b`` : this.renderOffIcon()}
      </div>
    `;
  }
  /**
   * https://fonts.google.com/icons?selected=Material%20Symbols%20Outlined%3Acheck%3AFILL%400%3Bwght%40500%3BGRAD%400%3Bopsz%4024
   */
  renderOnIcon() {
    return b`
      <slot class="icon icon--on" name="on-icon">
        <svg viewBox="0 0 24 24">
          <path
            d="M9.55 18.2 3.65 12.3 5.275 10.675 9.55 14.95 18.725 5.775 20.35 7.4Z" />
        </svg>
      </slot>
    `;
  }
  /**
   * https://fonts.google.com/icons?selected=Material%20Symbols%20Outlined%3Aclose%3AFILL%400%3Bwght%40500%3BGRAD%400%3Bopsz%4024
   */
  renderOffIcon() {
    return b`
      <slot class="icon icon--off" name="off-icon">
        <svg viewBox="0 0 24 24">
          <path
            d="M6.4 19.2 4.8 17.6 10.4 12 4.8 6.4 6.4 4.8 12 10.4 17.6 4.8 19.2 6.4 13.6 12 19.2 17.6 17.6 19.2 12 13.6Z" />
        </svg>
      </slot>
    `;
  }
  renderTouchTarget() {
    return b`<span class="touch"></span>`;
  }
  shouldShowIcons() {
    return this.icons || this.showOnlySelectedIcon;
  }
  handleInput(event) {
    const target = event.target;
    this.selected = target.checked;
    // <input> 'input' event bubbles and is composed, don't re-dispatch it.
  }
  handleChange(event) {
    // <input> 'change' event is not composed, re-dispatch it.
    redispatchEvent(this, event);
  }
  [getFormValue]() {
    return this.selected ? this.value : null;
  }
  [getFormState]() {
    return String(this.selected);
  }
  formResetCallback() {
    // The selected property does not reflect, so the original attribute set by
    // the user is used to determine the default value.
    this.selected = this.hasAttribute('selected');
  }
  formStateRestoreCallback(state) {
    this.selected = state === 'true';
  }
  [createValidator]() {
    return new CheckboxValidator(() => ({
      checked: this.selected,
      required: this.required
    }));
  }
  [getValidityAnchor]() {
    return this.input;
  }
}
/** @nocollapse */
Switch.shadowRootOptions = {
  mode: 'open',
  delegatesFocus: true
};
__decorate([n$5({
  type: Boolean
})], Switch.prototype, "selected", void 0);
__decorate([n$5({
  type: Boolean
})], Switch.prototype, "icons", void 0);
__decorate([n$5({
  type: Boolean,
  attribute: 'show-only-selected-icon'
})], Switch.prototype, "showOnlySelectedIcon", void 0);
__decorate([n$5({
  type: Boolean
})], Switch.prototype, "required", void 0);
__decorate([n$5()], Switch.prototype, "value", void 0);
__decorate([e$6('input')], Switch.prototype, "input", void 0);

/**
 * @license
 * Copyright 2024 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Generated stylesheet for ./switch/internal/switch-styles.css.
const styles$2 = i$7`@layer styles, hcm;@layer styles{:host{display:inline-flex;outline:none;vertical-align:top;-webkit-tap-highlight-color:rgba(0,0,0,0);cursor:pointer}:host([disabled]){cursor:default}:host([touch-target=wrapper]){margin:max(0px,(48px - var(--md-switch-track-height, 32px))/2) 0px}md-focus-ring{--md-focus-ring-shape-start-start: var(--md-switch-track-shape-start-start, var(--md-switch-track-shape, var(--md-sys-shape-corner-full, 9999px)));--md-focus-ring-shape-start-end: var(--md-switch-track-shape-start-end, var(--md-switch-track-shape, var(--md-sys-shape-corner-full, 9999px)));--md-focus-ring-shape-end-end: var(--md-switch-track-shape-end-end, var(--md-switch-track-shape, var(--md-sys-shape-corner-full, 9999px)));--md-focus-ring-shape-end-start: var(--md-switch-track-shape-end-start, var(--md-switch-track-shape, var(--md-sys-shape-corner-full, 9999px)))}.switch{align-items:center;display:inline-flex;flex-shrink:0;position:relative;width:var(--md-switch-track-width, 52px);height:var(--md-switch-track-height, 32px);border-start-start-radius:var(--md-switch-track-shape-start-start, var(--md-switch-track-shape, var(--md-sys-shape-corner-full, 9999px)));border-start-end-radius:var(--md-switch-track-shape-start-end, var(--md-switch-track-shape, var(--md-sys-shape-corner-full, 9999px)));border-end-end-radius:var(--md-switch-track-shape-end-end, var(--md-switch-track-shape, var(--md-sys-shape-corner-full, 9999px)));border-end-start-radius:var(--md-switch-track-shape-end-start, var(--md-switch-track-shape, var(--md-sys-shape-corner-full, 9999px)))}input{appearance:none;height:max(100%,var(--md-switch-touch-target-size, 48px));outline:none;margin:0;position:absolute;width:max(100%,var(--md-switch-touch-target-size, 48px));z-index:1;cursor:inherit;top:50%;left:50%;transform:translate(-50%, -50%)}:host([touch-target=none]) input{display:none}}@layer styles{.track{position:absolute;width:100%;height:100%;box-sizing:border-box;border-radius:inherit;display:flex;justify-content:center;align-items:center}.track::before{content:"";display:flex;position:absolute;height:100%;width:100%;border-radius:inherit;box-sizing:border-box;transition-property:opacity,background-color;transition-timing-function:linear;transition-duration:67ms}.disabled .track{background-color:rgba(0,0,0,0);border-color:rgba(0,0,0,0)}.disabled .track::before,.disabled .track::after{transition:none;opacity:var(--md-switch-disabled-track-opacity, 0.12)}.disabled .track::before{background-clip:content-box}.selected .track::before{background-color:var(--md-switch-selected-track-color, var(--md-sys-color-primary, #6750a4))}.selected:hover .track::before{background-color:var(--md-switch-selected-hover-track-color, var(--md-sys-color-primary, #6750a4))}.selected:focus-within .track::before{background-color:var(--md-switch-selected-focus-track-color, var(--md-sys-color-primary, #6750a4))}.selected:active .track::before{background-color:var(--md-switch-selected-pressed-track-color, var(--md-sys-color-primary, #6750a4))}.selected.disabled .track{background-clip:border-box}.selected.disabled .track::before{background-color:var(--md-switch-disabled-selected-track-color, var(--md-sys-color-on-surface, #1d1b20))}.unselected .track::before{background-color:var(--md-switch-track-color, var(--md-sys-color-surface-container-highest, #e6e0e9));border-color:var(--md-switch-track-outline-color, var(--md-sys-color-outline, #79747e));border-style:solid;border-width:var(--md-switch-track-outline-width, 2px)}.unselected:hover .track::before{background-color:var(--md-switch-hover-track-color, var(--md-sys-color-surface-container-highest, #e6e0e9));border-color:var(--md-switch-hover-track-outline-color, var(--md-sys-color-outline, #79747e))}.unselected:focus-visible .track::before{background-color:var(--md-switch-focus-track-color, var(--md-sys-color-surface-container-highest, #e6e0e9));border-color:var(--md-switch-focus-track-outline-color, var(--md-sys-color-outline, #79747e))}.unselected:active .track::before{background-color:var(--md-switch-pressed-track-color, var(--md-sys-color-surface-container-highest, #e6e0e9));border-color:var(--md-switch-pressed-track-outline-color, var(--md-sys-color-outline, #79747e))}.unselected.disabled .track::before{background-color:var(--md-switch-disabled-track-color, var(--md-sys-color-surface-container-highest, #e6e0e9));border-color:var(--md-switch-disabled-track-outline-color, var(--md-sys-color-on-surface, #1d1b20))}}@layer hcm{@media(forced-colors: active){.selected .track::before{background:ButtonText;border-color:ButtonText}.disabled .track::before{border-color:GrayText;opacity:1}.disabled.selected .track::before{background:GrayText}}}@layer styles{.handle-container{display:flex;place-content:center;place-items:center;position:relative;transition:margin 300ms cubic-bezier(0.175, 0.885, 0.32, 1.275)}.selected .handle-container{margin-inline-start:calc(var(--md-switch-track-width, 52px) - var(--md-switch-track-height, 32px))}.unselected .handle-container{margin-inline-end:calc(var(--md-switch-track-width, 52px) - var(--md-switch-track-height, 32px))}.disabled .handle-container{transition:none}.handle{border-start-start-radius:var(--md-switch-handle-shape-start-start, var(--md-switch-handle-shape, var(--md-sys-shape-corner-full, 9999px)));border-start-end-radius:var(--md-switch-handle-shape-start-end, var(--md-switch-handle-shape, var(--md-sys-shape-corner-full, 9999px)));border-end-end-radius:var(--md-switch-handle-shape-end-end, var(--md-switch-handle-shape, var(--md-sys-shape-corner-full, 9999px)));border-end-start-radius:var(--md-switch-handle-shape-end-start, var(--md-switch-handle-shape, var(--md-sys-shape-corner-full, 9999px)));height:var(--md-switch-handle-height, 16px);width:var(--md-switch-handle-width, 16px);transform-origin:center;transition-property:height,width;transition-duration:250ms,250ms;transition-timing-function:cubic-bezier(0.2, 0, 0, 1),cubic-bezier(0.2, 0, 0, 1);z-index:0}.handle::before{content:"";display:flex;inset:0;position:absolute;border-radius:inherit;box-sizing:border-box;transition:background-color 67ms linear}.disabled .handle,.disabled .handle::before{transition:none}.selected .handle{height:var(--md-switch-selected-handle-height, 24px);width:var(--md-switch-selected-handle-width, 24px)}.handle.with-icon{height:var(--md-switch-with-icon-handle-height, 24px);width:var(--md-switch-with-icon-handle-width, 24px)}.selected:not(.disabled):active .handle,.unselected:not(.disabled):active .handle{height:var(--md-switch-pressed-handle-height, 28px);width:var(--md-switch-pressed-handle-width, 28px);transition-timing-function:linear;transition-duration:100ms}.selected .handle::before{background-color:var(--md-switch-selected-handle-color, var(--md-sys-color-on-primary, #fff))}.selected:hover .handle::before{background-color:var(--md-switch-selected-hover-handle-color, var(--md-sys-color-primary-container, #eaddff))}.selected:focus-within .handle::before{background-color:var(--md-switch-selected-focus-handle-color, var(--md-sys-color-primary-container, #eaddff))}.selected:active .handle::before{background-color:var(--md-switch-selected-pressed-handle-color, var(--md-sys-color-primary-container, #eaddff))}.selected.disabled .handle::before{background-color:var(--md-switch-disabled-selected-handle-color, var(--md-sys-color-surface, #fef7ff));opacity:var(--md-switch-disabled-selected-handle-opacity, 1)}.unselected .handle::before{background-color:var(--md-switch-handle-color, var(--md-sys-color-outline, #79747e))}.unselected:hover .handle::before{background-color:var(--md-switch-hover-handle-color, var(--md-sys-color-on-surface-variant, #49454f))}.unselected:focus-within .handle::before{background-color:var(--md-switch-focus-handle-color, var(--md-sys-color-on-surface-variant, #49454f))}.unselected:active .handle::before{background-color:var(--md-switch-pressed-handle-color, var(--md-sys-color-on-surface-variant, #49454f))}.unselected.disabled .handle::before{background-color:var(--md-switch-disabled-handle-color, var(--md-sys-color-on-surface, #1d1b20));opacity:var(--md-switch-disabled-handle-opacity, 0.38)}md-ripple{border-radius:var(--md-switch-state-layer-shape, var(--md-sys-shape-corner-full, 9999px));height:var(--md-switch-state-layer-size, 40px);inset:unset;width:var(--md-switch-state-layer-size, 40px)}.selected md-ripple{--md-ripple-hover-color: var(--md-switch-selected-hover-state-layer-color, var(--md-sys-color-primary, #6750a4));--md-ripple-pressed-color: var(--md-switch-selected-pressed-state-layer-color, var(--md-sys-color-primary, #6750a4));--md-ripple-hover-opacity: var(--md-switch-selected-hover-state-layer-opacity, 0.08);--md-ripple-pressed-opacity: var(--md-switch-selected-pressed-state-layer-opacity, 0.12)}.unselected md-ripple{--md-ripple-hover-color: var(--md-switch-hover-state-layer-color, var(--md-sys-color-on-surface, #1d1b20));--md-ripple-pressed-color: var(--md-switch-pressed-state-layer-color, var(--md-sys-color-on-surface, #1d1b20));--md-ripple-hover-opacity: var(--md-switch-hover-state-layer-opacity, 0.08);--md-ripple-pressed-opacity: var(--md-switch-pressed-state-layer-opacity, 0.12)}}@layer hcm{@media(forced-colors: active){.unselected .handle::before{background:ButtonText}.disabled .handle::before{opacity:1}.disabled.unselected .handle::before{background:GrayText}}}@layer styles{.icons{position:relative;height:100%;width:100%}.icon{position:absolute;inset:0;margin:auto;display:flex;align-items:center;justify-content:center;fill:currentColor;transition:fill 67ms linear,opacity 33ms linear,transform 167ms cubic-bezier(0.2, 0, 0, 1);opacity:0}.disabled .icon{transition:none}.selected .icon--on,.unselected .icon--off{opacity:1}.unselected .handle:not(.with-icon) .icon--on{transform:rotate(-45deg)}.icon--off{width:var(--md-switch-icon-size, 16px);height:var(--md-switch-icon-size, 16px);color:var(--md-switch-icon-color, var(--md-sys-color-surface-container-highest, #e6e0e9))}.unselected:hover .icon--off{color:var(--md-switch-hover-icon-color, var(--md-sys-color-surface-container-highest, #e6e0e9))}.unselected:focus-within .icon--off{color:var(--md-switch-focus-icon-color, var(--md-sys-color-surface-container-highest, #e6e0e9))}.unselected:active .icon--off{color:var(--md-switch-pressed-icon-color, var(--md-sys-color-surface-container-highest, #e6e0e9))}.unselected.disabled .icon--off{color:var(--md-switch-disabled-icon-color, var(--md-sys-color-surface-container-highest, #e6e0e9));opacity:var(--md-switch-disabled-icon-opacity, 0.38)}.icon--on{width:var(--md-switch-selected-icon-size, 16px);height:var(--md-switch-selected-icon-size, 16px);color:var(--md-switch-selected-icon-color, var(--md-sys-color-on-primary-container, #21005d))}.selected:hover .icon--on{color:var(--md-switch-selected-hover-icon-color, var(--md-sys-color-on-primary-container, #21005d))}.selected:focus-within .icon--on{color:var(--md-switch-selected-focus-icon-color, var(--md-sys-color-on-primary-container, #21005d))}.selected:active .icon--on{color:var(--md-switch-selected-pressed-icon-color, var(--md-sys-color-on-primary-container, #21005d))}.selected.disabled .icon--on{color:var(--md-switch-disabled-selected-icon-color, var(--md-sys-color-on-surface, #1d1b20));opacity:var(--md-switch-disabled-selected-icon-opacity, 0.38)}}@layer hcm{@media(forced-colors: active){.icon--off{fill:Canvas}.icon--on{fill:ButtonText}.disabled.unselected .icon--off,.disabled.selected .icon--on{opacity:1}.disabled .icon--on{fill:GrayText}}}
`;

/**
 * @license
 * Copyright 2021 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @summary Switches toggle the state of a single item on or off.
 *
 * @description
 * There's one type of switch in Material. Use this selection control when the
 * user needs to toggle a single item on or off.
 *
 * @final
 * @suppress {visibility}
 */
let MdSwitch = class MdSwitch extends Switch {};
MdSwitch.styles = [styles$2];
MdSwitch = __decorate([t$1('md-switch')], MdSwitch);

/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
const CHIME_CLUSTER_ID = 1366;
const ATTR_INSTALLED_SOUNDS = 0;
const ATTR_SELECTED_CHIME = 1;
const ATTR_ENABLED = 2;
const ATTR_CLUSTER_REVISION = 65533;
function readAttr(node, endpoint, attrId) {
  return node.attributes[`${endpoint}/${CHIME_CLUSTER_ID}/${attrId}`];
}
function readSounds(node, endpoint) {
  const raw = readAttr(node, endpoint, ATTR_INSTALLED_SOUNDS);
  if (!Array.isArray(raw)) return [];
  const out = new Array();
  for (const item of raw) {
    const obj = asObject(item);
    if (!obj) continue;
    const id = pickNumber(obj, "chimeId") ?? pickNumber(obj, "0");
    const name = pickString(obj, "name") ?? pickString(obj, "1");
    if (id !== null && name !== null) out.push({
      chimeId: id,
      name
    });
  }
  return out;
}
function readSelected(node, endpoint) {
  const v = readAttr(node, endpoint, ATTR_SELECTED_CHIME);
  return typeof v === "number" ? v : null;
}
function readEnabled(node, endpoint) {
  const v = readAttr(node, endpoint, ATTR_ENABLED);
  return v === true;
}
function readRevision(node, endpoint) {
  const v = readAttr(node, endpoint, ATTR_CLUSTER_REVISION);
  return typeof v === "number" ? v : 1;
}
async function setEnabled(client, nodeId, endpoint, enabled) {
  await client.writeAttribute(nodeId, `${endpoint}/${CHIME_CLUSTER_ID}/${ATTR_ENABLED}`, enabled);
}
async function setSelected(client, nodeId, endpoint, chimeId) {
  await client.writeAttribute(nodeId, `${endpoint}/${CHIME_CLUSTER_ID}/${ATTR_SELECTED_CHIME}`, chimeId);
}
async function play(client, nodeId, endpoint, chimeId) {
  const payload = chimeId !== void 0 ? {
    chimeID: chimeId
  } : {};
  await client.deviceCommand(nodeId, endpoint, CHIME_CLUSTER_ID, "PlayChimeSound", payload);
}

var __defProp$d = Object.defineProperty;
var __getOwnPropDesc$f = Object.getOwnPropertyDescriptor;
var __decorateClass$g = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$f(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp$d(target, key, result);
  return result;
};
let ChimeClusterCommands = class extends BaseClusterCommands {
  constructor() {
    super(...arguments);
    this._lastPlayed = null;
    this._playDisabledUntil = 0;
  }
  updated(changedProperties) {
    super.updated(changedProperties);
    if (changedProperties.has("client") && this.client && !this._unsubscribeNodes) {
      this._unsubscribeNodes = this.client.addEventListener("nodes_changed", () => {
        this.requestUpdate();
      });
      this._unsubscribeEvents = this.client.addNodeEventListener(ev => {
        if (ev.cluster_id !== CHIME_CLUSTER_ID || ev.endpoint_id !== this.endpoint || String(ev.node_id) !== String(this.node.node_id) || ev.event_id !== 0) {
          return;
        }
        const raw = ev.data;
        if (raw === null || typeof raw !== "object") return;
        const d = raw;
        const named = d["chimeID"];
        const tagged = d["0"];
        const chimeId = typeof named === "number" ? named : typeof tagged === "number" ? tagged : null;
        if (chimeId !== null) this.onChimeStartedPlaying(chimeId);
      });
    }
  }
  disconnectedCallback() {
    super.disconnectedCallback();
    this._unsubscribeNodes?.();
    this._unsubscribeEvents?.();
    this._lastPlayed = null;
  }
  render() {
    if (!this.node || this.cluster !== CHIME_CLUSTER_ID) return A;
    const sounds = readSounds(this.node, this.endpoint);
    const selected = readSelected(this.node, this.endpoint);
    const enabled = readEnabled(this.node, this.endpoint);
    const revision = readRevision(this.node, this.endpoint);
    const showPerRowPlay = revision >= 2;
    const showLastPlayed = revision >= 2 && this._lastPlayed !== null;
    const playLocked = Date.now() < this._playDisabledUntil;
    const lastSoundName = showLastPlayed ? sounds.find(s => s.chimeId === this._lastPlayed.chimeId)?.name ?? `#${this._lastPlayed.chimeId}` : null;
    return b`
            <details class="command-panel" open>
                <summary>Chime</summary>
                <div class="command-content">
                    <div class="top-row">
                        <label class="enabled">
                            <md-switch
                                ?selected=${enabled}
                                @change=${handleAsyncEvent(e => setEnabled(this.client, this.node.node_id, this.endpoint,
    // md-switch exposes `.selected` but has no typed CustomEvent subclass
    e.target.selected))}
                            ></md-switch>
                            <span>Enabled</span>
                        </label>
                        <div class="selected">
                            <span class="muted">Selected:</span>
                            <md-outlined-select
                                .value=${selected !== null ? String(selected) : ""}
                                ?disabled=${sounds.length === 0}
                                @change=${handleAsyncEvent(e => {
      const v = Number(e.target.value);
      return setSelected(this.client, this.node.node_id, this.endpoint, v);
    })}
                            >
                                ${sounds.map(s => b`
                                        <md-select-option value=${String(s.chimeId)}>
                                            <div slot="headline">${s.name}</div>
                                        </md-select-option>
                                    `)}
                            </md-outlined-select>
                        </div>
                        <md-filled-button
                            ?disabled=${!enabled || selected === null || playLocked}
                            @click=${handleAsync(() => this._handlePlay())}
                        >
                            <ha-svg-icon slot="icon" .path=${mdiPlay}></ha-svg-icon>
                            Play
                        </md-filled-button>
                    </div>

                    <div class="sounds">
                        <div class="sounds-header">Installed sounds (${sounds.length})</div>
                        ${sounds.length === 0 ? b`<div class="muted empty">No sounds installed.</div>` : sounds.map(s => b`
                                      <div
                                          class="sound-row ${s.chimeId === selected ? "selected" : ""}"
                                          @click=${handleAsync(() => setSelected(this.client, this.node.node_id, this.endpoint, s.chimeId))}
                                      >
                                          <span class="pid">#${s.chimeId}</span>
                                          <span class="pname">${s.name}</span>
                                          ${s.chimeId === selected ? b`<span class="muted">✓ selected</span>` : A}
                                          <span class="grow"></span>
                                          ${showPerRowPlay ? b`<md-icon-button
                                                    ?disabled=${!enabled}
                                                    @click=${handleAsyncEvent(e => {
      e.stopPropagation();
      return play(this.client, this.node.node_id, this.endpoint, s.chimeId);
    })}
                                                >
                                                    <ha-svg-icon .path=${mdiPlay}></ha-svg-icon>
                                                </md-icon-button>` : A}
                                      </div>
                                  `)}
                    </div>

                    ${showLastPlayed ? b`<div class="last-played">
                              Last played: ${lastSoundName} · ${new Date(this._lastPlayed.at).toLocaleTimeString()}
                          </div>` : A}
                </div>
            </details>
        `;
  }
  onChimeStartedPlaying(chimeId) {
    this._lastPlayed = {
      chimeId,
      at: Date.now()
    };
  }
  async _handlePlay() {
    this._playDisabledUntil = Date.now() + 1e3;
    this.requestUpdate();
    try {
      await play(this.client, this.node.node_id, this.endpoint);
    } finally {
      setTimeout(() => this.requestUpdate(), 1e3);
    }
  }
};
ChimeClusterCommands.styles = [...(Array.isArray(BaseClusterCommands.styles) ? BaseClusterCommands.styles : [BaseClusterCommands.styles]), i$7`
            .top-row {
                display: flex;
                align-items: center;
                gap: 16px;
                flex-wrap: wrap;
                padding-bottom: 12px;
            }
            .enabled {
                display: inline-flex;
                align-items: center;
                gap: 8px;
            }
            .selected {
                display: inline-flex;
                align-items: center;
                gap: 8px;
                flex: 1;
                min-width: 200px;
            }
            .muted {
                color: var(--md-sys-color-on-surface-variant);
            }
            .sounds {
                border-top: 1px solid var(--md-sys-color-outline-variant);
                padding-top: 8px;
            }
            .sounds-header {
                font-weight: 500;
                margin-bottom: 6px;
            }
            .sound-row {
                display: flex;
                align-items: center;
                gap: 12px;
                padding: 6px 8px;
                border-radius: 4px;
                cursor: pointer;
            }
            .sound-row:hover {
                background: var(--md-sys-color-surface-container-high);
            }
            .sound-row.selected {
                background: var(--md-sys-color-secondary-container);
            }
            .pid {
                font-family: var(--monospace-font, monospace);
                color: var(--md-sys-color-on-surface-variant);
                font-size: 0.85rem;
            }
            .pname {
                font-weight: 500;
            }
            .grow {
                flex: 1;
            }
            .empty {
                font-style: italic;
            }
            .last-played {
                margin-top: 12px;
                padding-top: 8px;
                border-top: 1px solid var(--md-sys-color-outline-variant);
                font-size: 0.85rem;
                color: var(--md-sys-color-on-surface-variant);
            }
        `];
__decorateClass$g([r$3()], ChimeClusterCommands.prototype, "_lastPlayed", 2);
__decorateClass$g([r$3()], ChimeClusterCommands.prototype, "_playDisabledUntil", 2);
ChimeClusterCommands = __decorateClass$g([t$1("chime-cluster-commands")], ChimeClusterCommands);
registerClusterCommands(CHIME_CLUSTER_ID, "chime-cluster-commands");

var __defProp$c = Object.defineProperty;
var __getOwnPropDesc$e = Object.getOwnPropertyDescriptor;
var __decorateClass$f = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$e(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp$c(target, key, result);
  return result;
};
const CLUSTER_ID$1 = 8;
let LevelControlClusterCommands = class extends BaseClusterCommands {
  constructor() {
    super(...arguments);
    this._targetLevel = 128;
    this._transitionTime = 0;
    this._executeIfOff = false;
  }
  render() {
    return b`
            <details class="command-panel">
                <summary>Level Control Commands</summary>
                <div class="command-content">
                    <div class="command-row">
                        <label for="targetLevel">Level:</label>
                        <input
                            id="targetLevel"
                            type="number"
                            min="1"
                            max="254"
                            .value=${String(this._targetLevel)}
                            @input=${this._handleTargetLevelChange}
                        />
                        <label for="transitionTime">Transition (0.1s):</label>
                        <input
                            id="transitionTime"
                            type="number"
                            min="0"
                            max="65535"
                            .value=${String(this._transitionTime)}
                            @input=${this._handleTransitionTimeChange}
                        />
                        <label for="executeIfOff">
                            <input
                                id="executeIfOff"
                                type="checkbox"
                                .checked=${this._executeIfOff}
                                @change=${this._handleExecuteIfOffChange}
                            />
                            Execute if Off
                        </label>
                        <md-outlined-button @click=${handleAsync(() => this._handleMoveToLevel())}
                            >MoveToLevel</md-outlined-button
                        >
                        <md-outlined-button @click=${handleAsync(() => this._handleMoveToLevelWithOnOff())}
                            >MoveToLevelWithOnOff</md-outlined-button
                        >
                    </div>
                </div>
            </details>
        `;
  }
  _handleTargetLevelChange(e) {
    const input = e.target;
    let value = parseInt(input.value, 10);
    if (isNaN(value)) value = 1;
    if (value < 1) value = 1;
    if (value > 254) value = 254;
    this._targetLevel = value;
  }
  _handleTransitionTimeChange(e) {
    const input = e.target;
    let value = parseInt(input.value, 10);
    if (isNaN(value)) value = 0;
    if (value < 0) value = 0;
    if (value > 65535) value = 65535;
    this._transitionTime = value;
  }
  _handleExecuteIfOffChange(e) {
    const input = e.target;
    this._executeIfOff = input.checked;
  }
  async _handleMoveToLevel() {
    const optionsMask = this._executeIfOff ? {
      executeIfOff: true
    } : {};
    const optionsOverride = this._executeIfOff ? {
      executeIfOff: true
    } : {};
    await this.sendCommand("MoveToLevel", {
      level: this._targetLevel,
      transitionTime: this._transitionTime,
      optionsMask,
      optionsOverride
    });
  }
  async _handleMoveToLevelWithOnOff() {
    const optionsMask = this._executeIfOff ? {
      executeIfOff: true
    } : {};
    const optionsOverride = this._executeIfOff ? {
      executeIfOff: true
    } : {};
    await this.sendCommand("MoveToLevelWithOnOff", {
      level: this._targetLevel,
      transitionTime: this._transitionTime,
      optionsMask,
      optionsOverride
    });
  }
};
__decorateClass$f([r$3()], LevelControlClusterCommands.prototype, "_targetLevel", 2);
__decorateClass$f([r$3()], LevelControlClusterCommands.prototype, "_transitionTime", 2);
__decorateClass$f([r$3()], LevelControlClusterCommands.prototype, "_executeIfOff", 2);
LevelControlClusterCommands = __decorateClass$f([t$1("level-control-cluster-commands")], LevelControlClusterCommands);
registerClusterCommands(CLUSTER_ID$1, "level-control-cluster-commands");

var __getOwnPropDesc$d = Object.getOwnPropertyDescriptor;
var __decorateClass$e = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$d(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (decorator(result)) || result;
  return result;
};
const CLUSTER_ID = 6;
let OnOffClusterCommands = class extends BaseClusterCommands {
  render() {
    return b`
            <details class="command-panel">
                <summary>OnOff Commands</summary>
                <div class="command-content">
                    <div class="command-row">
                        <md-outlined-button @click=${handleAsync(() => this._handleOn())}>On</md-outlined-button>
                        <md-outlined-button @click=${handleAsync(() => this._handleOff())}>Off</md-outlined-button>
                        <md-outlined-button @click=${handleAsync(() => this._handleToggle())}
                            >Toggle</md-outlined-button
                        >
                    </div>
                </div>
            </details>
        `;
  }
  async _handleOn() {
    await this.sendCommand("On");
  }
  async _handleOff() {
    await this.sendCommand("Off");
  }
  async _handleToggle() {
    await this.sendCommand("Toggle");
  }
};
OnOffClusterCommands = __decorateClass$e([t$1("on-off-cluster-commands")], OnOffClusterCommands);
registerClusterCommands(CLUSTER_ID, "on-off-cluster-commands");

var __defProp$b = Object.defineProperty;
var __getOwnPropDesc$c = Object.getOwnPropertyDescriptor;
var __decorateClass$d = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$c(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp$b(target, key, result);
  return result;
};
const GLOBAL_ATTRIBUTE_MIN = 65520;
const GLOBAL_ATTRIBUTE_MAX = 65535;
const ACCEPTED_COMMAND_LIST_ATTR = 65529;
const REFRESH_SUCCESS_MS = 600;
function isGlobalAttribute(id) {
  return id >= GLOBAL_ATTRIBUTE_MIN && id <= GLOBAL_ATTRIBUTE_MAX;
}
function clusterAttributes(attributes, endpoint, cluster) {
  return Object.keys(attributes).filter(key => key.startsWith(`${endpoint}/${cluster}/`)).map(key => {
    const attributeKey = Number(key.split("/")[2]);
    return {
      key: attributeKey,
      value: attributes[key]
    };
  }).sort((a, b) => {
    const aIsGlobal = isGlobalAttribute(a.key);
    const bIsGlobal = isGlobalAttribute(b.key);
    if (aIsGlobal !== bIsGlobal) {
      return aIsGlobal ? 1 : -1;
    }
    return a.key - b.key;
  });
}
let MatterClusterView = class extends i$4 {
  constructor() {
    super(...arguments);
    this._tick = 0;
    this._devMode = DevModeService.active;
    this._refreshState = {};
  }
  connectedCallback() {
    super.connectedCallback();
    this._unsubscribeDev = DevModeService.subscribe(active => {
      this._devMode = active;
    });
  }
  disconnectedCallback() {
    super.disconnectedCallback();
    this._unsubscribeDev?.();
  }
  render() {
    if (!this.node || this.endpoint == void 0 || this.cluster == void 0) {
      return b`
                <dashboard-header title="Not found" backButton="#"></dashboard-header>
                <div class="not-found">
                    <ha-svg-icon .path=${mdiAlertCircleOutline}></ha-svg-icon>
                    <p>Node, endpoint, or cluster not found</p>
                    <md-outlined-button @click=${this._goBack}>Back</md-outlined-button>
                </div>
            `;
    }
    const fabricIndex = getEffectiveFabricIndex(this.client.serverInfo.fabric_index, isTestNodeId(this.node.node_id));
    const nodeHex = formatNodeAddress(fabricIndex, this.node.node_id);
    const clusterName = clusters[this.cluster]?.label ?? "Custom/Unknown Cluster";
    return b`
            <dashboard-header
                .title=${`Node ${this.node.node_id} ${nodeHex}  |  Endpoint ${this.endpoint}  |  Cluster ${this.cluster} (${clusterName})`}
                .backButton=${`#node/${this.node.node_id}/${this.endpoint}`}
            ></dashboard-header>

            <!-- node details section -->
            <div class="container">
                <node-details .node=${this.node}></node-details>
            </div>

            <!-- Cluster commands section (if available for this cluster) -->
            ${this._renderClusterCommands()}

            <!-- Developer-mode commands panel -->
            ${this._devMode ? this._renderDevCommandsPanel() : A}

            <!-- Cluster attributes listing -->
            <div class="container">
                <md-list>
                    <md-list-item>
                        <div slot="headline">
                            <b
                                >Attributes of ${clusters[this.cluster]?.label ?? "Custom/Unknown Cluster"} Cluster on
                                Endpoint ${this.endpoint}</b
                            >
                        </div>
                        <div slot="supporting-text">ClusterId ${this.cluster} (${formatHex(this.cluster)})</div>
                    </md-list-item>
                    <md-divider></md-divider>
                    ${clusterAttributes(this.node.attributes, this.endpoint, this.cluster).map((attribute, index) => b`
                            <md-list-item class=${index % 2 === 1 ? "alternate-row" : ""}>
                                <div slot="headline">
                                    ${clusters[this.cluster]?.attributes[attribute.key]?.label ?? "Custom/Unknown Attribute"}
                                </div>
                                <div slot="supporting-text">
                                    AttributeId: ${attribute.key} (${formatHex(attribute.key)}) - Value type:
                                    ${clusters[this.cluster]?.attributes[attribute.key]?.type ?? "unknown"}
                                </div>
                                <div slot="end" class="row-end">
                                    ${this._devMode ? this._renderAttributeDevActions(attribute.key, attribute.value) : A}
                                    ${toBigIntAwareJson(attribute.value).length > 30 ? b`<md-outlined-button
                                              @click=${() => {
      this._showAttributeValue(attribute.value);
    }}
                                          >
                                              Show value
                                          </md-outlined-button>` : b`<code>${toBigIntAwareJson(attribute.value)}</code>`}
                                </div>
                            </md-list-item>
                        `)}
                </md-list>
            </div>
        `;
  }
  _renderAttributeDevActions(attributeId, currentValue) {
    const meta = clusters[this.cluster]?.attributes[attributeId];
    const online = this.node?.available === true;
    const state2 = this._refreshState[attributeId] ?? "idle";
    const refreshClasses = `dev-action refresh refresh-${state2}`;
    return b`
            <span class="dev-actions">
                <md-outlined-icon-button
                    class=${refreshClasses}
                    title="Read attribute now"
                    aria-label="Read attribute now"
                    ?disabled=${!online || state2 === "loading"}
                    @click=${() => this._refreshAttribute(attributeId)}
                >
                    <ha-svg-icon .path=${mdiRefresh}></ha-svg-icon>
                </md-outlined-icon-button>
                ${meta?.writable ? b`
                          <md-outlined-icon-button
                              class="dev-action pencil"
                              title="Write attribute…"
                              aria-label="Write attribute"
                              ?disabled=${!online}
                              @click=${() => this._openAttributeWriteDialog(attributeId, currentValue, meta.label)}
                          >
                              <ha-svg-icon .path=${mdiPencil}></ha-svg-icon>
                          </md-outlined-icon-button>
                      ` : A}
            </span>
        `;
  }
  async _refreshAttribute(attributeId) {
    if (!this.node) return;
    const nodeId = this.node.node_id;
    const endpoint = this.endpoint;
    const cluster = this.cluster;
    const path = `${endpoint}/${cluster}/${attributeId}`;
    const isSameContext = () => this.isConnected && this.node?.node_id === nodeId && this.endpoint === endpoint && this.cluster === cluster;
    this._refreshState = {
      ...this._refreshState,
      [attributeId]: "loading"
    };
    try {
      const result = await this.client.readAttribute(nodeId, path);
      if (!isSameContext()) return;
      for (const [key, value] of Object.entries(result)) {
        this.node.attributes[key] = value;
      }
      this.requestUpdate();
      this._refreshState = {
        ...this._refreshState,
        [attributeId]: "success"
      };
      setTimeout(() => {
        if (!isSameContext()) return;
        if (this._refreshState[attributeId] === "success") {
          this._refreshState = {
            ...this._refreshState,
            [attributeId]: "idle"
          };
        }
      }, REFRESH_SUCCESS_MS);
    } catch (err) {
      if (!isSameContext()) return;
      this._refreshState = {
        ...this._refreshState,
        [attributeId]: "idle"
      };
      const message = err instanceof Error ? err.message : String(err);
      showAlertDialog({
        title: "Read failed",
        text: message
      });
    }
  }
  _openAttributeWriteDialog(attributeId, currentValue, label) {
    if (!this.node || this.cluster === void 0) return;
    showAttributeWriteDialog({
      client: this.client,
      nodeId: this.node.node_id,
      endpointId: this.endpoint,
      clusterId: this.cluster,
      attributeId,
      label,
      currentValue
    });
  }
  _renderDevCommandsPanel() {
    const clusterMeta = this.cluster !== void 0 ? clusters[this.cluster] : void 0;
    const rawAcceptedList = this.node?.attributes[`${this.endpoint}/${this.cluster}/${ACCEPTED_COMMAND_LIST_ATTR}`];
    const acceptedList = Array.isArray(rawAcceptedList) ? rawAcceptedList : [];
    const commands = acceptedList.map(id => clusterMeta?.commands[id]).filter(cmd => cmd !== void 0).sort((a, b) => a.id - b.id);
    const online = this.node?.available === true;
    return b`
            <div class="container">
                <details class="dev-commands-panel">
                    <summary>
                        <span class="dev-chip">DEV</span>
                        Commands
                    </summary>
                    <div class="dev-commands-content">
                        ${commands.length === 0 ? b`<p class="empty">No invokable commands for this cluster.</p>` : b`
                                  <ul class="command-list">
                                      ${commands.map(cmd => b`
                                              <li class="command-row">
                                                  <div class="command-meta">
                                                      <span class="command-label">${cmd.label}</span>
                                                      <span class="command-sub"
                                                          >CommandId ${cmd.id} (${formatHex(cmd.id)}) ·
                                                          <code>${cmd.name}</code></span
                                                      >
                                                  </div>
                                                  <md-outlined-button
                                                      class="dev-invoke-button"
                                                      ?disabled=${!online}
                                                      @click=${() => this._openCommandInvokeDialog(cmd.id, cmd.name)}
                                                  >
                                                      <ha-svg-icon slot="icon" .path=${mdiPlay}></ha-svg-icon>
                                                      Invoke
                                                  </md-outlined-button>
                                              </li>
                                          `)}
                                  </ul>
                              `}
                    </div>
                </details>
            </div>
        `;
  }
  _openCommandInvokeDialog(commandId, commandName) {
    if (!this.node || this.cluster === void 0) return;
    showCommandInvokeDialog({
      client: this.client,
      nodeId: this.node.node_id,
      endpointId: this.endpoint,
      clusterId: this.cluster,
      commandId,
      commandName
    });
  }
  async _showAttributeValue(value) {
    showAlertDialog({
      title: "Attribute value",
      text: toBigIntAwareJson(value),
      asCodeBlock: true
    });
  }
  _renderClusterCommands() {
    if (this.cluster === void 0) return b``;
    const RENDER_WHEN_OFFLINE = /* @__PURE__ */new Set([30, 31]);
    if (!this.node?.available && !RENDER_WHEN_OFFLINE.has(this.cluster)) return b``;
    const tagName = getClusterCommandsTag(this.cluster);
    if (!tagName) return b``;
    const componentHtml = `<${tagName}></${tagName}>`;
    const element = o$3(componentHtml);
    return b`
            <div class="container">
                <div id="cluster-commands-container">${element}</div>
            </div>
        `;
  }
  updated(changedProperties) {
    super.updated(changedProperties);
    if (changedProperties.has("cluster") || changedProperties.has("endpoint")) {
      this._refreshState = {};
    }
    const container = this.shadowRoot?.getElementById("cluster-commands-container");
    if (container && this.node && this.endpoint !== void 0 && this.cluster !== void 0) {
      const commandsElement = container.firstElementChild;
      if (commandsElement instanceof BaseClusterCommands) {
        commandsElement.node = this.node;
        commandsElement.endpoint = this.endpoint;
        commandsElement.cluster = this.cluster;
      }
    }
  }
  _goBack() {
    history.back();
  }
};
MatterClusterView.styles = [notFoundStyles, i$7`
            :host {
                display: block;
                background-color: var(--md-sys-color-background);
                color: var(--md-sys-color-on-background);
            }

            .header {
                background-color: var(--md-sys-color-primary);
                color: var(--md-sys-color-on-primary);
                --icon-primary-color: var(--md-sys-color-on-primary);
                font-weight: 400;
                display: flex;
                align-items: center;
                padding-right: 8px;
                height: 48px;
            }

            md-icon-button {
                margin-right: 8px;
            }

            .flex {
                flex: 1;
            }

            .container {
                padding: 16px;
                max-width: 95%;
                margin: 0 auto;
            }

            .status {
                color: var(--danger-color);
                font-weight: bold;
                font-size: 0.8em;
            }

            md-list-item.alternate-row {
                background-color: var(--md-sys-color-surface-container-low);
            }

            .row-end {
                display: flex;
                align-items: center;
                gap: 8px;
            }

            /* Framed dev-mode actions, clearly separated from the value display. */
            .dev-actions {
                display: inline-flex;
                align-items: center;
                gap: 6px;
                padding-right: 10px;
                margin-right: 2px;
                border-right: 1px solid var(--md-sys-color-outline-variant);
            }

            .dev-action {
                /* Compact, visible outlined frame in dev-mode accent (deep violet). */
                --md-outlined-icon-button-container-width: 32px;
                --md-outlined-icon-button-container-height: 32px;
                --md-outlined-icon-button-icon-size: 18px;
                --md-outlined-icon-button-outline-color: var(--dev-color);
                --md-outlined-icon-button-outline-width: 1px;
                --md-outlined-icon-button-icon-color: var(--dev-color);
                --md-outlined-icon-button-hover-state-layer-color: var(--dev-color);
                --md-outlined-icon-button-focus-state-layer-color: var(--dev-color);
                --md-outlined-icon-button-pressed-state-layer-color: var(--dev-color);
                --icon-primary-color: var(--dev-color);
                /* Round container kept constant so the success-fill transitions smoothly. */
                border-radius: 9999px;
                background: transparent;
                margin-right: 0;
                transition: background 300ms ease-out;
            }

            .dev-action.refresh-loading ha-svg-icon {
                animation: dev-spin 0.9s linear infinite;
            }

            .dev-action.refresh-success {
                --md-outlined-icon-button-icon-color: var(--dev-on-color);
                --icon-primary-color: var(--dev-on-color);
                background: var(--dev-color);
            }

            @keyframes dev-spin {
                from {
                    transform: rotate(0deg);
                }
                to {
                    transform: rotate(360deg);
                }
            }

            @media (prefers-reduced-motion: reduce) {
                .dev-action.refresh-loading ha-svg-icon {
                    animation: none;
                }
            }

            details.dev-commands-panel {
                background-color: var(--md-sys-color-surface-container);
                border: 1px solid var(--dev-color);
                border-radius: 12px;
                overflow: hidden;
            }

            details.dev-commands-panel summary {
                padding: 14px 16px;
                font-weight: 500;
                color: var(--md-sys-color-on-surface);
                cursor: pointer;
                user-select: none;
                display: flex;
                align-items: center;
                gap: 10px;
            }

            details.dev-commands-panel summary:hover {
                background-color: color-mix(in srgb, var(--dev-color) 8%, transparent);
            }

            details.dev-commands-panel summary::before {
                content: "▶";
                font-size: 12px;
                color: var(--dev-color);
                transition: transform 0.2s ease;
            }

            details.dev-commands-panel[open] summary::before {
                transform: rotate(90deg);
            }

            details.dev-commands-panel summary::-webkit-details-marker {
                display: none;
            }

            .dev-chip {
                font-family: var(--monospace-font);
                font-size: 0.7rem;
                font-weight: 600;
                letter-spacing: 0.08em;
                padding: 2px 6px;
                border-radius: 4px;
                background: var(--dev-color);
                color: var(--dev-on-color);
                line-height: 1;
            }

            .dev-commands-content {
                padding: 0 16px 16px 16px;
            }

            .empty {
                color: var(--md-sys-color-on-surface-variant);
                font-size: 0.9rem;
                margin: 0;
            }

            .command-list {
                list-style: none;
                margin: 0;
                padding: 0;
                display: flex;
                flex-direction: column;
                gap: 8px;
            }

            .command-row {
                display: flex;
                align-items: center;
                justify-content: space-between;
                gap: 16px;
                padding: 8px 12px;
                background: var(--md-sys-color-surface-container-low);
                border-radius: 8px;
                transition: background 120ms ease-out;
            }

            .command-row:hover {
                background: color-mix(in srgb, var(--dev-color) 12%, var(--md-sys-color-surface-container-low));
            }

            .dev-invoke-button {
                --md-outlined-button-outline-color: var(--dev-color);
                --md-outlined-button-label-text-color: var(--dev-color);
                --md-outlined-button-hover-state-layer-color: var(--dev-color);
                --md-outlined-button-focus-state-layer-color: var(--dev-color);
                --md-outlined-button-pressed-state-layer-color: var(--dev-color);
                --md-outlined-button-icon-color: var(--dev-color);
                --md-outlined-button-hover-label-text-color: var(--dev-color);
                --md-outlined-button-focus-label-text-color: var(--dev-color);
                --md-outlined-button-pressed-label-text-color: var(--dev-color);
            }

            .command-meta {
                display: flex;
                flex-direction: column;
                gap: 2px;
                min-width: 0;
            }

            .command-label {
                font-weight: 500;
                color: var(--md-sys-color-on-surface);
            }

            .command-sub {
                font-size: 0.825rem;
                color: var(--md-sys-color-on-surface-variant);
            }

            .command-sub code {
                font-family: var(--monospace-font);
                background: var(--md-sys-color-surface-container-high);
                padding: 0 4px;
                border-radius: 3px;
            }
        `];
__decorateClass$d([c$5({
  context: clientContext
})], MatterClusterView.prototype, "client", 2);
__decorateClass$d([c$5({
  context: tickContext,
  subscribe: true
})], MatterClusterView.prototype, "_tick", 2);
__decorateClass$d([n$5()], MatterClusterView.prototype, "node", 2);
__decorateClass$d([e$b({
  context: bindingContext
}), n$5()], MatterClusterView.prototype, "endpoint", 2);
__decorateClass$d([n$5()], MatterClusterView.prototype, "cluster", 2);
__decorateClass$d([r$3()], MatterClusterView.prototype, "_devMode", 2);
__decorateClass$d([r$3()], MatterClusterView.prototype, "_refreshState", 2);
MatterClusterView = __decorateClass$d([t$1("matter-cluster-view")], MatterClusterView);

/**
 * @license
 * Copyright 2018 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
const e = {},
  i = e$4(class extends i$3 {
    constructor() {
      super(...arguments), this.ot = e;
    }
    render(r, t) {
      return t();
    }
    update(t, [s, e]) {
      if (Array.isArray(s)) {
        if (Array.isArray(this.ot) && this.ot.length === s.length && s.every((r, t) => r === this.ot[t])) return E;
      } else if (this.ot === s) return E;
      return this.ot = Array.isArray(s) ? Array.from(s) : s, this.render(s, e);
    }
  });

var __defProp$a = Object.defineProperty;
var __getOwnPropDesc$b = Object.getOwnPropertyDescriptor;
var __decorateClass$c = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$b(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp$a(target, key, result);
  return result;
};
function getUniqueClusters(node, endpoint) {
  return Array.from(new Set(Object.keys(node.attributes).filter(key => key.startsWith(`${endpoint.toString()}/`)).map(key => Number(key.split("/")[1])))).sort((a, b) => {
    return a - b;
  });
}
let MatterEndpointView = class extends i$4 {
  constructor() {
    super(...arguments);
    this._tick = 0;
  }
  render() {
    if (!this.node || this.endpoint == void 0) {
      return b`
                <dashboard-header title="Not found" backButton="#"></dashboard-header>
                <div class="not-found">
                    <ha-svg-icon .path=${mdiAlertCircleOutline}></ha-svg-icon>
                    <p>Node or endpoint not found</p>
                    <md-outlined-button @click=${this._goBack}>Back</md-outlined-button>
                </div>
            `;
    }
    const fabricIndex = getEffectiveFabricIndex(this.client.serverInfo.fabric_index, isTestNodeId(this.node.node_id));
    const nodeHex = formatNodeAddress(fabricIndex, this.node.node_id);
    return b`
            <dashboard-header
                .title=${`Node ${this.node.node_id} ${nodeHex}  |  Endpoint ${this.endpoint}`}
                .backButton=${`#node/${this.node.node_id}`}
            ></dashboard-header>

            <!-- node details section -->
            <div class="container">
                <node-details .node=${this.node}></node-details>
            </div>

            <!-- Binding editor (when this endpoint has a Binding cluster) -->
            ${getUniqueClusters(this.node, this.endpoint).includes(30) ? b`<div class="container">
                      <binding-cluster-commands
                          .node=${this.node}
                          .endpoint=${this.endpoint}
                          .cluster=${30}
                      ></binding-cluster-commands>
                  </div>` : A}

            <!-- Endpoint clusters listing -->
            <div class="container">
                <md-list>
                    <md-list-item>
                        <div slot="headline">
                            <b>Clusters on Endpoint ${this.endpoint}</b>
                        </div>
                        <div slot="supporting-text">
                            Device Type(s):
                            ${getEndpointDeviceTypes(this.node, this.endpoint).map(deviceType => {
      return deviceType.label;
    }).join(" / ")}
                        </div>
                    </md-list-item>
                    ${i([this.node?.attributes.length], () => getUniqueClusters(this.node, this.endpoint).map(cluster => {
      return b`
                                <md-list-item
                                    type="link"
                                    href=${`#node/${this.node.node_id}/${this.endpoint}/${cluster}`}
                                >
                                    <div slot="headline">${clusters[cluster]?.label ?? "Custom/Unknown Cluster"}</div>
                                    <div slot="supporting-text">ClusterId ${cluster} (${formatHex(cluster)})</div>
                                    <ha-svg-icon slot="end" .path=${mdiChevronRight}></ha-svg-icon>
                                </md-list-item>
                            `;
    }))}
                </md-list>
            </div>
        `;
  }
  _goBack() {
    history.back();
  }
};
MatterEndpointView.styles = [notFoundStyles, i$7`
            :host {
                display: block;
                background-color: var(--md-sys-color-background);
            }

            .header {
                background-color: var(--md-sys-color-primary);
                color: var(--md-sys-color-on-primary);
                --icon-primary-color: var(--md-sys-color-on-primary);
                font-weight: 400;
                display: flex;
                align-items: center;
                padding-right: 8px;
                height: 48px;
            }

            md-icon-button {
                margin-right: 8px;
            }

            .flex {
                flex: 1;
            }

            .container {
                padding: 16px;
                max-width: 95%;
                margin: 0 auto;
            }

            .status {
                color: var(--danger-color);
                font-weight: bold;
                font-size: 0.8em;
            }
        `];
__decorateClass$c([c$5({
  context: clientContext
})], MatterEndpointView.prototype, "client", 2);
__decorateClass$c([c$5({
  context: tickContext,
  subscribe: true
})], MatterEndpointView.prototype, "_tick", 2);
__decorateClass$c([n$5()], MatterEndpointView.prototype, "node", 2);
__decorateClass$c([e$b({
  context: bindingContext
}), n$5()], MatterEndpointView.prototype, "endpoint", 2);
MatterEndpointView = __decorateClass$c([t$1("matter-endpoint-view")], MatterEndpointView);

var __getOwnPropDesc$a = Object.getOwnPropertyDescriptor;
var __decorateClass$b = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$a(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (decorator(result)) || result;
  return result;
};
let DashboardFooter = class extends i$4 {
  render() {
    return b`
            <div class="footer">
                The OHF Matter Server is a project by the Open Home Foundation.
                <a href="https://www.openhomefoundation.org/structure/#support-our-work" target="_blank"
                    >Support development</a
                >
            </div>
        `;
  }
};
DashboardFooter.styles = i$7`
        .footer {
            padding: 4px 16px;
            text-align: center;
            font-size: 0.75em;
            color: var(--md-sys-color-on-surface-variant);
            flex-shrink: 0;
        }

        .footer a {
            color: var(--md-sys-color-on-surface);
        }
    `;
DashboardFooter = __decorateClass$b([t$1("dashboard-footer")], DashboardFooter);

/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
class BorderRouterStore {
  // Replaced (not mutated) on every refresh so Lit consumers passing this map as a
  // @property() detect the snapshot change via the default `===` identity compare and
  // re-render. Mutating in place would keep the same reference and silently skip updates.
  #entries = /* @__PURE__ */new Map();
  get entries() {
    return this.#entries;
  }
  async refresh(client) {
    const list = await client.sendCommand("get_thread_border_routers", 0, {});
    const next = /* @__PURE__ */new Map();
    for (const entry of list) {
      next.set(entry.extAddressHex.toUpperCase(), entry);
    }
    this.#entries = next;
  }
  reset() {
    this.#entries = /* @__PURE__ */new Map();
  }
}

/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
const WIFI_FEATURE = 1 << 0;
const THREAD_FEATURE = 1 << 1;
const ETHERNET_FEATURE = 1 << 2;
const SIGNAL_STRONG_THRESHOLD = -70;
const SIGNAL_MEDIUM_THRESHOLD = -85;
const LQI_STRONG_THRESHOLD = 2;
const LQI_MEDIUM_THRESHOLD = 1;
function getSignalColorStrong() {
  return getCssVar("--signal-color-strong", "#4caf50");
}
function getSignalColorMedium() {
  return getCssVar("--signal-color-medium", "#ff9800");
}
function getSignalColorWeak() {
  return getCssVar("--signal-color-weak", "#f44336");
}
function getSignalColorNone() {
  return getCssVar("--signal-color-none", "#9e9e9e");
}
function base64ToBigInt(base64) {
  try {
    const binary = atob(base64);
    let result = 0n;
    const start = binary.length > 8 ? binary.length - 8 : 0;
    for (let i = start; i < binary.length; i++) {
      result = result << 8n | BigInt(binary.charCodeAt(i));
    }
    return result;
  } catch {
    return 0n;
  }
}
function normalizeExtAddress(value) {
  if (typeof value === "bigint") {
    return value;
  }
  if (typeof value === "string") {
    return base64ToBigInt(value);
  }
  if (typeof value === "number") {
    return BigInt(value);
  }
  return 0n;
}
function getNetworkType(node) {
  const featureMap = node.attributes["0/49/65532"];
  if (featureMap === void 0) {
    return "unknown";
  }
  if (featureMap & THREAD_FEATURE) {
    return "thread";
  }
  if (featureMap & WIFI_FEATURE) {
    return "wifi";
  }
  if (featureMap & ETHERNET_FEATURE) {
    return "ethernet";
  }
  return "unknown";
}
const THREAD_VERSION_NAMES = {
  1: "1.0",
  2: "1.1",
  3: "1.2",
  4: "1.3",
  5: "1.4"
};
function getThreadVersion(node) {
  const v = node.attributes["0/49/10"];
  return typeof v === "number" ? v : void 0;
}
function formatThreadVersion(tlv) {
  const name = THREAD_VERSION_NAMES[tlv];
  return name !== void 0 ? `Thread ${name}` : `Thread unknown (${tlv})`;
}
function categorizeDevices(nodes) {
  const result = {
    thread: [],
    wifi: [],
    ethernet: [],
    unknown: []
  };
  for (const node of Object.values(nodes)) {
    const nodeId = String(node.node_id);
    const networkType = getNetworkType(node);
    result[networkType].push(nodeId);
  }
  return result;
}
function getThreadRole(node) {
  const v = node.attributes["0/53/1"];
  return typeof v === "number" ? v : void 0;
}
function getThreadChannel(node) {
  const v = node.attributes["0/53/0"];
  return typeof v === "number" ? v : void 0;
}
function getThreadExtendedPanId(node) {
  const v = node.attributes["0/53/4"];
  if (typeof v === "bigint") return v;
  if (typeof v === "number" && Number.isInteger(v)) return BigInt(v);
  return void 0;
}
function getThreadExtendedAddress(node) {
  const networkInterfaces = node.attributes["0/51/0"];
  if (!Array.isArray(networkInterfaces) || networkInterfaces.length === 0) {
    return void 0;
  }
  const threadIface = networkInterfaces.find(i => i["7"] === 4) || networkInterfaces[0];
  if (!threadIface) {
    return void 0;
  }
  const hwAddrB64 = threadIface["4"];
  if (typeof hwAddrB64 !== "string" || !hwAddrB64) {
    return void 0;
  }
  const extAddr = base64ToBigInt(hwAddrB64);
  return extAddr !== 0n ? extAddr : void 0;
}
function getThreadExtendedAddressHex(node) {
  const extAddr = getThreadExtendedAddress(node);
  if (extAddr !== void 0) {
    return extAddr.toString(16).padStart(16, "0").toUpperCase();
  }
  return void 0;
}
function getNeighborTableLength(node) {
  const neighborTable = node.attributes["0/53/7"];
  return Array.isArray(neighborTable) ? neighborTable.length : 0;
}
function parseNeighborTable(node) {
  const neighborTable = node.attributes["0/53/7"];
  if (!Array.isArray(neighborTable)) {
    return [];
  }
  return neighborTable.map(entry => {
    const rawExtAddr = entry["0"] ?? entry.extAddress;
    const extAddress = normalizeExtAddress(rawExtAddr);
    return {
      extAddress,
      // Field 1: age
      age: entry["1"] ?? entry.age ?? 0,
      // Field 2: rloc16
      rloc16: entry["2"] ?? entry.rloc16 ?? 0,
      // Field 3: linkFrameCounter
      linkFrameCounter: entry["3"] ?? entry.linkFrameCounter ?? 0,
      // Field 4: mleFrameCounter
      mleFrameCounter: entry["4"] ?? entry.mleFrameCounter ?? 0,
      // Field 5: lqi
      lqi: entry["5"] ?? entry.lqi ?? 0,
      // Field 6: averageRssi (nullable)
      avgRssi: entry["6"] ?? entry.averageRssi ?? null,
      // Field 7: lastRssi (nullable)
      lastRssi: entry["7"] ?? entry.lastRssi ?? null,
      // Field 8: frameErrorRate
      frameErrorRate: entry["8"] ?? entry.frameErrorRate ?? 0,
      // Field 9: messageErrorRate
      messageErrorRate: entry["9"] ?? entry.messageErrorRate ?? 0,
      // Field 10: rxOnWhenIdle
      rxOnWhenIdle: entry["10"] ?? entry.rxOnWhenIdle ?? false,
      // Field 11: fullThreadDevice
      fullThreadDevice: entry["11"] ?? entry.fullThreadDevice ?? false,
      // Field 12: fullNetworkData
      fullNetworkData: entry["12"] ?? entry.fullNetworkData ?? false,
      // Field 13: isChild
      isChild: entry["13"] ?? entry.isChild ?? false
    };
  });
}
function parseRouteTable(node) {
  const routeTable = node.attributes["0/53/8"];
  if (!Array.isArray(routeTable)) {
    return [];
  }
  return routeTable.map(entry => {
    const rawExtAddr = entry["0"] ?? entry.extAddress;
    const extAddress = normalizeExtAddress(rawExtAddr);
    return {
      extAddress,
      // Field 1: rloc16
      rloc16: entry["1"] ?? entry.rloc16 ?? 0,
      // Field 2: routerId
      routerId: entry["2"] ?? entry.routerId ?? 0,
      // Field 3: nextHop
      nextHop: entry["3"] ?? entry.nextHop ?? 0,
      // Field 4: pathCost
      pathCost: entry["4"] ?? entry.pathCost ?? 0,
      // Field 5: lqiIn
      lqiIn: entry["5"] ?? entry.lqiIn ?? 0,
      // Field 6: lqiOut
      lqiOut: entry["6"] ?? entry.lqiOut ?? 0,
      // Field 7: age
      age: entry["7"] ?? entry.age ?? 0,
      // Field 8: allocated
      allocated: entry["8"] ?? entry.allocated ?? false,
      // Field 9: linkEstablished
      linkEstablished: entry["9"] ?? entry.linkEstablished ?? false
    };
  });
}
function findRouteByExtAddress(node, targetExtAddr) {
  const routes = parseRouteTable(node);
  return routes.find(route => route.extAddress === targetExtAddr && route.linkEstablished);
}
function getRoutableDestinationsCount(node) {
  const routes = parseRouteTable(node);
  return routes.filter(route => route.allocated && route.linkEstablished).length;
}
function getRouteBidirectionalLqi(route) {
  if (route.lqiIn > 0 && route.lqiOut > 0) {
    return Math.round((route.lqiIn + route.lqiOut) / 2);
  }
  if (route.lqiIn > 0) return route.lqiIn;
  if (route.lqiOut > 0) return route.lqiOut;
  return void 0;
}
function getThreadRloc16(node) {
  const value = node.attributes["0/53/64"];
  if (typeof value === "number") {
    return value;
  }
  return void 0;
}
function buildExtAddrMap(nodes) {
  const extAddrMap = /* @__PURE__ */new Map();
  for (const node of Object.values(nodes)) {
    const nodeId = String(node.node_id);
    const extAddr = getThreadExtendedAddress(node);
    if (extAddr !== void 0) {
      extAddrMap.set(extAddr, nodeId);
    }
  }
  return extAddrMap;
}
function buildRloc16Map(nodes) {
  const rloc16Map = /* @__PURE__ */new Map();
  for (const node of Object.values(nodes)) {
    const nodeId = String(node.node_id);
    const rloc16 = getThreadRloc16(node);
    if (rloc16 !== void 0) {
      rloc16Map.set(rloc16, nodeId);
    }
  }
  return rloc16Map;
}
function findUnknownDevices(nodes, extAddrMap, rloc16Map, borderRouters) {
  const aggregates = /* @__PURE__ */new Map();
  for (const node of Object.values(nodes)) {
    const nodeId = String(node.node_id);
    const neighbors = parseNeighborTable(node);
    const observerXp = getThreadExtendedPanId(node);
    const observerXpHex = observerXp !== void 0 ? observerXp.toString(16).padStart(16, "0").toUpperCase() : void 0;
    for (const neighbor of neighbors) {
      if (extAddrMap.has(neighbor.extAddress)) {
        continue;
      }
      if (neighbor.rloc16 !== 0 && rloc16Map.has(neighbor.rloc16)) {
        continue;
      }
      const extAddressHex = neighbor.extAddress.toString(16).padStart(16, "0").toUpperCase();
      let agg = aggregates.get(extAddressHex);
      if (agg === void 0) {
        agg = {
          extAddressHex,
          extAddress: neighbor.extAddress,
          seenBy: [],
          isRouter: false,
          bestRssi: null,
          extendedPanIdHex: observerXpHex
        };
        aggregates.set(extAddressHex, agg);
      } else if (agg.extendedPanIdHex === void 0 && observerXpHex !== void 0) {
        agg.extendedPanIdHex = observerXpHex;
      }
      if (!agg.seenBy.includes(nodeId)) {
        agg.seenBy.push(nodeId);
      }
      if (neighbor.rxOnWhenIdle) {
        agg.isRouter = true;
      }
      const rssi = neighbor.avgRssi ?? neighbor.lastRssi;
      if (rssi !== null && (agg.bestRssi === null || rssi > agg.bestRssi)) {
        agg.bestRssi = rssi;
      }
    }
  }
  const networkNameByXp = /* @__PURE__ */new Map();
  if (borderRouters !== void 0) {
    for (const br of borderRouters.values()) {
      if (br.extendedPanIdHex !== void 0 && br.networkName !== void 0) {
        networkNameByXp.set(br.extendedPanIdHex, br.networkName);
      }
    }
  }
  const out = new Array();
  for (const agg of aggregates.values()) {
    const br = borderRouters?.get(agg.extAddressHex);
    if (br !== void 0) {
      out.push({
        kind: "br",
        ...br,
        id: `br_${agg.extAddressHex}`,
        extAddressHex: agg.extAddressHex,
        extAddress: agg.extAddress,
        seenBy: agg.seenBy,
        isRouter: agg.isRouter,
        bestRssi: agg.bestRssi
      });
    } else {
      const networkName = agg.extendedPanIdHex !== void 0 ? networkNameByXp.get(agg.extendedPanIdHex) : void 0;
      out.push({
        kind: "unknown",
        id: `unknown_${agg.extAddressHex}`,
        extAddressHex: agg.extAddressHex,
        extAddress: agg.extAddress,
        seenBy: agg.seenBy,
        isRouter: agg.isRouter,
        bestRssi: agg.bestRssi,
        extendedPanIdHex: agg.extendedPanIdHex,
        networkName
      });
    }
  }
  return out;
}
const CONNECTION_MODE_LABELS = {
  0: "disabled",
  1: "PSKc / DTLS",
  2: "PSKd / DTLS",
  3: "vendor-defined",
  4: "X.509"
};
const THREAD_INTERFACE_STATUS_LABELS = {
  0: "not initialized",
  1: "initialized, inactive",
  2: "initialized, active"
};
const AVAILABILITY_LABELS = {
  0: "infrequent",
  1: "high"
};
const THREAD_ROLE_LABELS = {
  0: "detached",
  1: "child",
  2: "router",
  3: "leader"
};
const MULTI_AIL_STATE_LABELS = {
  0: "disabled",
  1: "not detected",
  2: "detected"
};
function decodeMeshcopStateBitmap(hex) {
  if (hex === void 0 || !/^[0-9a-fA-F]{1,8}$/.test(hex)) return void 0;
  const value = parseInt(hex, 16);
  if (!Number.isFinite(value)) return void 0;
  const connectionModeValue = value & 7;
  const threadInterfaceStatusValue = value >> 3 & 3;
  const availabilityValue = value >> 5 & 3;
  const bbr = (value >> 7 & 1) === 1;
  const bbrIsPrimary = (value >> 8 & 1) === 1;
  const threadRoleValue = value >> 9 & 3;
  const epskcSupported = (value >> 11 & 1) === 1;
  const multiAilStateValue = value >> 12 & 3;
  const reserved = value >>> 14 >>> 0;
  return {
    connectionModeValue,
    connectionMode: CONNECTION_MODE_LABELS[connectionModeValue],
    threadInterfaceStatusValue,
    threadInterfaceStatus: THREAD_INTERFACE_STATUS_LABELS[threadInterfaceStatusValue],
    availabilityValue,
    availability: AVAILABILITY_LABELS[availabilityValue],
    bbr,
    bbrFunction: bbr ? bbrIsPrimary ? "primary" : "secondary" : void 0,
    threadRoleValue,
    threadRole: THREAD_ROLE_LABELS[threadRoleValue],
    epskcSupported,
    multiAilStateValue,
    multiAilState: MULTI_AIL_STATE_LABELS[multiAilStateValue],
    reservedHex: reserved !== 0 ? reserved.toString(16).toUpperCase() : void 0
  };
}
function getSignalLevel(neighbor) {
  return getSignalLevelFromLqi(neighbor.lqi);
}
function getSignalLevelFromLqi(lqi) {
  if (lqi <= 0) return "none";
  if (lqi > LQI_STRONG_THRESHOLD) return "strong";
  if (lqi > LQI_MEDIUM_THRESHOLD) return "medium";
  return "weak";
}
function signalLevelToColor(level) {
  switch (level) {
    case "strong":
      return getSignalColorStrong();
    case "medium":
      return getSignalColorMedium();
    case "weak":
      return getSignalColorWeak();
    case "none":
      return getSignalColorNone();
  }
}
function getSignalColor(neighbor) {
  return getSignalColorFromLqi(neighbor.lqi);
}
function getSignalColorFromLqi(lqi) {
  return signalLevelToColor(getSignalLevelFromLqi(lqi));
}
function stripMdnsHostname(hostname) {
  return hostname.replace(/\.$/, "").replace(/\.local$/i, "");
}
function getThreadRoleName(role) {
  switch (role) {
    case 0:
      return "Unspecified";
    case 1:
      return "Unassigned";
    case 2:
      return "Sleepy End Device";
    case 3:
      return "End Device";
    case 4:
      return "REED";
    case 5:
      return "Router";
    case 6:
      return "Leader";
    default:
      return "Unknown";
  }
}
function getWiFiDiagnostics(node) {
  const bssidRaw = node.attributes["0/54/0"];
  let bssid = null;
  if (bssidRaw) {
    try {
      const binary = atob(bssidRaw);
      bssid = Array.from(binary).map(c => c.charCodeAt(0).toString(16).padStart(2, "0").toUpperCase()).join(":");
    } catch {
      bssid = null;
    }
  }
  const rssi = node.attributes["0/54/4"];
  const channel = node.attributes["0/54/3"];
  const securityType = node.attributes["0/54/1"];
  const wifiVersion = node.attributes["0/54/2"];
  return {
    bssid,
    rssi: rssi ?? null,
    channel: channel ?? null,
    securityType: securityType ?? null,
    wifiVersion: wifiVersion ?? null
  };
}
function getSignalColorFromRssi(rssi) {
  if (rssi === null) {
    return getSignalColorMedium();
  }
  if (rssi > SIGNAL_STRONG_THRESHOLD) {
    return getSignalColorStrong();
  }
  if (rssi > SIGNAL_MEDIUM_THRESHOLD) {
    return getSignalColorMedium();
  }
  return getSignalColorWeak();
}
function getWiFiSecurityTypeName(securityType) {
  switch (securityType) {
    case 0:
      return "Unspecified";
    case 1:
      return "None";
    case 2:
      return "WEP";
    case 3:
      return "WPA Personal";
    case 4:
      return "WPA2 Personal";
    case 5:
      return "WPA3 Personal";
    default:
      return "Unknown";
  }
}
function getWiFiVersionName(version) {
  switch (version) {
    case 0:
      return "802.11a";
    case 1:
      return "802.11b";
    case 2:
      return "802.11g";
    case 3:
      return "802.11n";
    case 4:
      return "802.11ac";
    case 5:
      return "802.11ax";
    case 6:
      return "802.11ah";
    default:
      return "Unknown";
  }
}
function makePairKey(a, b) {
  return a < b ? `${a}|${b}` : `${b}|${a}`;
}
function getEdgeSignalScore(conn) {
  const levelScore = conn.signalLevel === "strong" ? 3e3 : conn.signalLevel === "medium" ? 2e3 : conn.signalLevel === "weak" ? 1e3 : 0;
  const detail = conn.rssi !== null ? conn.rssi + 200 : conn.lqi;
  return levelScore + detail;
}
function buildThreadEdgePairs(nodes, extAddrMap, rloc16Map, unknownDevices) {
  const pairs = /* @__PURE__ */new Map();
  const unknownExtAddrMap = /* @__PURE__ */new Map();
  for (const unknown of unknownDevices) {
    unknownExtAddrMap.set(unknown.extAddress, unknown.id);
  }
  for (const node of Object.values(nodes)) {
    const fromNodeId = String(node.node_id);
    const neighbors = parseNeighborTable(node);
    for (const neighbor of neighbors) {
      let toNodeId = extAddrMap.get(neighbor.extAddress);
      if (toNodeId === void 0 && neighbor.rloc16 !== 0) {
        toNodeId = rloc16Map.get(neighbor.rloc16);
      }
      if (toNodeId === void 0) {
        toNodeId = unknownExtAddrMap.get(neighbor.extAddress);
      }
      if (toNodeId === void 0 || fromNodeId === toNodeId) continue;
      const pairKey = makePairKey(fromNodeId, toNodeId);
      if (!pairs.has(pairKey)) {
        const [nodeA, nodeB] = fromNodeId < toNodeId ? [fromNodeId, toNodeId] : [toNodeId, fromNodeId];
        pairs.set(pairKey, {
          pairKey,
          nodeA,
          nodeB
        });
      }
      const pair = pairs.get(pairKey);
      const isFromA = fromNodeId === pair.nodeA;
      if (isFromA && pair.edgeAB) continue;
      if (!isFromA && pair.edgeBA) continue;
      const routeEntry = findRouteByExtAddress(node, neighbor.extAddress);
      const bidirectionalLqi = routeEntry ? getRouteBidirectionalLqi(routeEntry) : void 0;
      const edge = {
        fromNodeId,
        toNodeId,
        signalColor: getSignalColor(neighbor),
        signalLevel: getSignalLevel(neighbor),
        lqi: neighbor.lqi,
        rssi: neighbor.avgRssi ?? neighbor.lastRssi,
        pathCost: routeEntry?.pathCost,
        bidirectionalLqi
      };
      if (isFromA) {
        pair.edgeAB = edge;
      } else {
        pair.edgeBA = edge;
      }
    }
    const routes = parseRouteTable(node);
    for (const route of routes) {
      if (!route.linkEstablished || !route.allocated) continue;
      let toNodeId = extAddrMap.get(route.extAddress);
      if (toNodeId === void 0 && route.rloc16 !== 0) {
        toNodeId = rloc16Map.get(route.rloc16);
      }
      if (toNodeId === void 0) {
        toNodeId = unknownExtAddrMap.get(route.extAddress);
      }
      if (toNodeId === void 0 || toNodeId === fromNodeId) continue;
      const pairKey = makePairKey(fromNodeId, toNodeId);
      if (!pairs.has(pairKey)) {
        const [nodeA, nodeB] = fromNodeId < toNodeId ? [fromNodeId, toNodeId] : [toNodeId, fromNodeId];
        pairs.set(pairKey, {
          pairKey,
          nodeA,
          nodeB
        });
      }
      const pair = pairs.get(pairKey);
      const isFromA = fromNodeId === pair.nodeA;
      if (isFromA && pair.edgeAB) continue;
      if (!isFromA && pair.edgeBA) continue;
      const bidirectionalLqi = getRouteBidirectionalLqi(route);
      const signalLevel = bidirectionalLqi !== void 0 ? getSignalLevelFromLqi(bidirectionalLqi) : "none";
      const edge = {
        fromNodeId,
        toNodeId,
        signalColor: signalLevelToColor(signalLevel),
        signalLevel,
        lqi: bidirectionalLqi ?? 0,
        rssi: null,
        pathCost: route.pathCost,
        bidirectionalLqi,
        fromRouteTable: true
      };
      if (isFromA) {
        pair.edgeAB = edge;
      } else {
        pair.edgeBA = edge;
      }
    }
  }
  return pairs;
}
function getNodeConnectionsFromPairs(nodeId, edgePairs, nodes, filters) {
  const connections = [];
  const hiddenNodeIds = /* @__PURE__ */new Set();
  if (filters?.hideOfflineNodes) {
    for (const node of Object.values(nodes)) {
      if (node.available === false) {
        hiddenNodeIds.add(String(node.node_id));
      }
    }
  }
  for (const pair of edgePairs.values()) {
    const isA = pair.nodeA === nodeId;
    const isB = pair.nodeB === nodeId;
    if (!isA && !isB) continue;
    const remoteId = isA ? pair.nodeB : pair.nodeA;
    const outgoing = isA ? pair.edgeAB : pair.edgeBA;
    const incoming = isA ? pair.edgeBA : pair.edgeAB;
    const survivors = [];
    for (const [conn, isOut] of [[outgoing, true], [incoming, false]]) {
      if (!conn) continue;
      if (filters) {
        const fromId = String(conn.fromNodeId);
        const toId = String(conn.toNodeId);
        if (hiddenNodeIds.has(fromId) || hiddenNodeIds.has(toId)) continue;
        if (filters.hideWeakSignalEdges && conn.signalLevel === "weak") continue;
        if (filters.hideMediumSignalEdges && conn.signalLevel === "medium") continue;
        if (filters.hideStrongSignalEdges && conn.signalLevel === "strong") continue;
      }
      survivors.push({
        conn,
        isOutgoing: isOut
      });
    }
    if (survivors.length === 0) continue;
    const liveSurvivors = survivors.filter(s => s.conn.signalLevel !== "none");
    const usable = liveSurvivors.length > 0 ? liveSurvivors : survivors;
    let winner;
    const outgoingSurvivor = usable.find(s => s.isOutgoing);
    if (outgoingSurvivor) {
      winner = outgoingSurvivor;
    } else {
      usable.sort((a, b) => getEdgeSignalScore(a.conn) - getEdgeSignalScore(b.conn));
      winner = usable[0];
    }
    const remoteNode = nodes[remoteId];
    const isExternalUnknown = remoteId.startsWith("unknown_");
    const isExternalBr = remoteId.startsWith("br_");
    const isUnknown = isExternalUnknown || isExternalBr;
    let extAddressHex;
    if (isExternalUnknown) {
      extAddressHex = remoteId.slice("unknown_".length);
    } else if (isExternalBr) {
      extAddressHex = remoteId.slice("br_".length);
    } else if (remoteNode) {
      extAddressHex = getThreadExtendedAddressHex(remoteNode) ?? "Unknown";
    } else {
      extAddressHex = "Unknown";
    }
    connections.push({
      connectedNodeId: remoteId,
      connectedNode: remoteNode,
      extAddressHex,
      signalColor: winner.conn.signalColor,
      signalLevel: winner.conn.signalLevel,
      lqi: winner.conn.lqi,
      rssi: winner.conn.rssi,
      isOutgoing: winner.isOutgoing,
      isReverseOnly: !outgoing,
      isUnknown,
      pathCost: winner.conn.pathCost,
      bidirectionalLqi: winner.conn.bidirectionalLqi
    });
  }
  return connections;
}

var __defProp$9 = Object.defineProperty;
var __getOwnPropDesc$9 = Object.getOwnPropertyDescriptor;
var __decorateClass$a = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$9(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp$9(target, key, result);
  return result;
};
let DevicePanel = class extends i$4 {
  constructor() {
    super(...arguments);
    this.type = "wifi";
    this.nodeIds = [];
    this.nodes = {};
    this.expanded = true;
    this._isExpanded = true;
  }
  willUpdate(changedProperties) {
    if (changedProperties.has("expanded")) {
      this._isExpanded = this.expanded;
    }
  }
  _getIcon() {
    switch (this.type) {
      case "wifi":
        return mdiWifi;
      case "ethernet":
        return mdiEthernet;
      case "bridges":
        return mdiRouter;
    }
  }
  _getTitle() {
    switch (this.type) {
      case "wifi":
        return "WiFi Devices";
      case "ethernet":
        return "Ethernet Devices";
      case "bridges":
        return "Bridges";
    }
  }
  _toggleExpanded() {
    this._isExpanded = !this._isExpanded;
  }
  _handleHeaderKeydown(event) {
    if (event.key === "Enter" || event.key === " ") {
      event.preventDefault();
      this._toggleExpanded();
    }
  }
  _handleNodeClick(nodeId) {
    this.dispatchEvent(new CustomEvent("node-selected", {
      detail: {
        nodeId
      },
      bubbles: true,
      composed: true
    }));
  }
  render() {
    if (this.nodeIds.length === 0) {
      return A;
    }
    return b`
            <div class="panel">
                <div
                    class="header"
                    role="button"
                    tabindex="0"
                    aria-expanded=${this._isExpanded}
                    @click=${this._toggleExpanded}
                    @keydown=${this._handleHeaderKeydown}
                >
                    <ha-svg-icon .path=${this._getIcon()} class="type-icon"></ha-svg-icon>
                    <span class="title">${this._getTitle()}</span>
                    <span class="count">(${this.nodeIds.length})</span>
                    <ha-svg-icon
                        .path=${this._isExpanded ? mdiChevronDown : mdiChevronRight}
                        class="expand-icon"
                    ></ha-svg-icon>
                </div>
                ${this._isExpanded ? b`
                          <md-list class="device-list">
                              ${this.nodeIds.map(nodeId => {
      const node = this.nodes[nodeId.toString()];
      if (!node) return A;
      return b`
                                      <md-list-item type="button" @click=${() => this._handleNodeClick(nodeId)}>
                                          <div slot="headline">Node ${nodeId}</div>
                                          <div slot="supporting-text">${getDeviceName(node)}</div>
                                          <ha-svg-icon slot="end" .path=${mdiChevronRight}></ha-svg-icon>
                                      </md-list-item>
                                  `;
    })}
                          </md-list>
                      ` : A}
            </div>
        `;
  }
};
DevicePanel.styles = i$7`
        :host {
            display: block;
        }

        .panel {
            background-color: var(--md-sys-color-surface, #fff);
            border-radius: 8px;
            border: 1px solid var(--md-sys-color-outline-variant, #ccc);
            overflow: hidden;
        }

        .header {
            display: flex;
            align-items: center;
            padding: 12px 16px;
            cursor: pointer;
            user-select: none;
            background-color: var(--md-sys-color-surface-container, #f5f5f5);
        }

        .header:hover {
            background-color: var(--md-sys-color-surface-container-high, #e8e8e8);
        }

        .header:focus-visible {
            outline: 2px solid var(--md-sys-color-primary);
            outline-offset: -2px;
        }

        .type-icon {
            --icon-primary-color: var(--md-sys-color-primary, #6200ee);
            margin-right: 12px;
        }

        .title {
            font-weight: 500;
            color: var(--md-sys-color-on-surface, #333);
        }

        .count {
            margin-left: 8px;
            color: var(--md-sys-color-on-surface-variant, #666);
            font-size: 0.875rem;
        }

        .expand-icon {
            margin-left: auto;
            --icon-primary-color: var(--md-sys-color-on-surface-variant, #666);
        }

        .device-list {
            --md-list-item-leading-space: 16px;
            --md-list-item-trailing-space: 16px;
        }

        md-list-item {
            --md-list-item-one-line-container-height: 48px;
        }
    `;
__decorateClass$a([n$5()], DevicePanel.prototype, "type", 2);
__decorateClass$a([n$5({
  type: Array
})], DevicePanel.prototype, "nodeIds", 2);
__decorateClass$a([n$5({
  type: Object
})], DevicePanel.prototype, "nodes", 2);
__decorateClass$a([n$5({
  type: Boolean
})], DevicePanel.prototype, "expanded", 2);
__decorateClass$a([r$3()], DevicePanel.prototype, "_isExpanded", 2);
DevicePanel = __decorateClass$a([t$1("device-panel")], DevicePanel);

/**
 * @license
 * Copyright 2019 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Separate variable needed for closure.
const checkboxBaseClass = mixinDelegatesAria(mixinConstraintValidation(mixinFormAssociated(mixinElementInternals(i$4))));
/**
 * A checkbox component.
 *
 *
 * @fires change {Event} The native `change` event on
 * [`<input>`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event)
 * --bubbles
 * @fires input {InputEvent} The native `input` event on
 * [`<input>`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event)
 * --bubbles --composed
 */
class Checkbox extends checkboxBaseClass {
  constructor() {
    super();
    /**
     * Whether or not the checkbox is selected.
     */
    this.checked = false;
    /**
     * Whether or not the checkbox is indeterminate.
     *
     * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox#indeterminate_state_checkboxes
     */
    this.indeterminate = false;
    /**
     * When true, require the checkbox to be selected when participating in
     * form submission.
     *
     * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox#validation
     */
    this.required = false;
    /**
     * The value of the checkbox that is submitted with a form when selected.
     *
     * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox#value
     */
    this.value = 'on';
    this.prevChecked = false;
    this.prevDisabled = false;
    this.prevIndeterminate = false;
    {
      this.addEventListener('click', event => {
        if (!isActivationClick(event) || !this.input) {
          return;
        }
        this.focus();
        dispatchActivationClick(this.input);
      });
    }
  }
  update(changed) {
    if (changed.has('checked') || changed.has('disabled') || changed.has('indeterminate')) {
      this.prevChecked = changed.get('checked') ?? this.checked;
      this.prevDisabled = changed.get('disabled') ?? this.disabled;
      this.prevIndeterminate = changed.get('indeterminate') ?? this.indeterminate;
    }
    super.update(changed);
  }
  render() {
    const prevNone = !this.prevChecked && !this.prevIndeterminate;
    const prevChecked = this.prevChecked && !this.prevIndeterminate;
    const prevIndeterminate = this.prevIndeterminate;
    const isChecked = this.checked && !this.indeterminate;
    const isIndeterminate = this.indeterminate;
    const containerClasses = e$3({
      'disabled': this.disabled,
      'selected': isChecked || isIndeterminate,
      'unselected': !isChecked && !isIndeterminate,
      'checked': isChecked,
      'indeterminate': isIndeterminate,
      'prev-unselected': prevNone,
      'prev-checked': prevChecked,
      'prev-indeterminate': prevIndeterminate,
      'prev-disabled': this.prevDisabled
    });
    // Needed for closure conformance
    const {
      ariaLabel,
      ariaInvalid
    } = this;
    // Note: <input> needs to be rendered before the <svg> for
    // form.reportValidity() to work in Chrome.
    return b`
      <div class="container ${containerClasses}">
        <input
          type="checkbox"
          id="input"
          aria-checked=${isIndeterminate ? 'mixed' : A}
          aria-label=${ariaLabel || A}
          aria-invalid=${ariaInvalid || A}
          ?disabled=${this.disabled}
          ?required=${this.required}
          .indeterminate=${this.indeterminate}
          .checked=${this.checked}
          @input=${this.handleInput}
          @change=${this.handleChange} />

        <div class="outline"></div>
        <div class="background"></div>
        <md-focus-ring part="focus-ring" for="input"></md-focus-ring>
        <md-ripple for="input" ?disabled=${this.disabled}></md-ripple>
        <svg class="icon" viewBox="0 0 18 18" aria-hidden="true">
          <rect class="mark short" />
          <rect class="mark long" />
        </svg>
      </div>
    `;
  }
  handleInput(event) {
    const target = event.target;
    this.checked = target.checked;
    this.indeterminate = target.indeterminate;
    // <input> 'input' event bubbles and is composed, don't re-dispatch it.
  }
  handleChange(event) {
    // <input> 'change' event is not composed, re-dispatch it.
    redispatchEvent(this, event);
  }
  [getFormValue]() {
    if (!this.checked || this.indeterminate) {
      return null;
    }
    return this.value;
  }
  [getFormState]() {
    return String(this.checked);
  }
  formResetCallback() {
    // The checked property does not reflect, so the original attribute set by
    // the user is used to determine the default value.
    this.checked = this.hasAttribute('checked');
  }
  formStateRestoreCallback(state) {
    this.checked = state === 'true';
  }
  [createValidator]() {
    return new CheckboxValidator(() => this);
  }
  [getValidityAnchor]() {
    return this.input;
  }
}
/** @nocollapse */
Checkbox.shadowRootOptions = {
  ...i$4.shadowRootOptions,
  delegatesFocus: true
};
__decorate([n$5({
  type: Boolean
})], Checkbox.prototype, "checked", void 0);
__decorate([n$5({
  type: Boolean
})], Checkbox.prototype, "indeterminate", void 0);
__decorate([n$5({
  type: Boolean
})], Checkbox.prototype, "required", void 0);
__decorate([n$5()], Checkbox.prototype, "value", void 0);
__decorate([r$3()], Checkbox.prototype, "prevChecked", void 0);
__decorate([r$3()], Checkbox.prototype, "prevDisabled", void 0);
__decorate([r$3()], Checkbox.prototype, "prevIndeterminate", void 0);
__decorate([e$6('input')], Checkbox.prototype, "input", void 0);

/**
 * @license
 * Copyright 2024 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Generated stylesheet for ./checkbox/internal/checkbox-styles.css.
const styles$1 = i$7`:host{border-start-start-radius:var(--md-checkbox-container-shape-start-start, var(--md-checkbox-container-shape, 2px));border-start-end-radius:var(--md-checkbox-container-shape-start-end, var(--md-checkbox-container-shape, 2px));border-end-end-radius:var(--md-checkbox-container-shape-end-end, var(--md-checkbox-container-shape, 2px));border-end-start-radius:var(--md-checkbox-container-shape-end-start, var(--md-checkbox-container-shape, 2px));display:inline-flex;height:var(--md-checkbox-container-size, 18px);position:relative;vertical-align:top;width:var(--md-checkbox-container-size, 18px);-webkit-tap-highlight-color:rgba(0,0,0,0);cursor:pointer}:host([disabled]){cursor:default}:host([touch-target=wrapper]){margin:max(0px,(48px - var(--md-checkbox-container-size, 18px))/2)}md-focus-ring{height:44px;inset:unset;width:44px}input{appearance:none;height:48px;margin:0;opacity:0;outline:none;position:absolute;width:48px;z-index:1;cursor:inherit}:host([touch-target=none]) input{height:100%;width:100%}.container{border-radius:inherit;display:flex;height:100%;place-content:center;place-items:center;position:relative;width:100%}.outline,.background,.icon{inset:0;position:absolute}.outline,.background{border-radius:inherit}.outline{border-color:var(--md-checkbox-outline-color, var(--md-sys-color-on-surface-variant, #49454f));border-style:solid;border-width:var(--md-checkbox-outline-width, 2px);box-sizing:border-box}.background{background-color:var(--md-checkbox-selected-container-color, var(--md-sys-color-primary, #6750a4))}.background,.icon{opacity:0;transition-duration:150ms,50ms;transition-property:transform,opacity;transition-timing-function:cubic-bezier(0.3, 0, 0.8, 0.15),linear;transform:scale(0.6)}:where(.selected) :is(.background,.icon){opacity:1;transition-duration:350ms,50ms;transition-timing-function:cubic-bezier(0.05, 0.7, 0.1, 1),linear;transform:scale(1)}md-ripple{border-radius:var(--md-checkbox-state-layer-shape, var(--md-sys-shape-corner-full, 9999px));height:var(--md-checkbox-state-layer-size, 40px);inset:unset;width:var(--md-checkbox-state-layer-size, 40px);--md-ripple-hover-color: var(--md-checkbox-hover-state-layer-color, var(--md-sys-color-on-surface, #1d1b20));--md-ripple-hover-opacity: var(--md-checkbox-hover-state-layer-opacity, 0.08);--md-ripple-pressed-color: var(--md-checkbox-pressed-state-layer-color, var(--md-sys-color-primary, #6750a4));--md-ripple-pressed-opacity: var(--md-checkbox-pressed-state-layer-opacity, 0.12)}.selected md-ripple{--md-ripple-hover-color: var(--md-checkbox-selected-hover-state-layer-color, var(--md-sys-color-primary, #6750a4));--md-ripple-hover-opacity: var(--md-checkbox-selected-hover-state-layer-opacity, 0.08);--md-ripple-pressed-color: var(--md-checkbox-selected-pressed-state-layer-color, var(--md-sys-color-on-surface, #1d1b20));--md-ripple-pressed-opacity: var(--md-checkbox-selected-pressed-state-layer-opacity, 0.12)}.icon{fill:var(--md-checkbox-selected-icon-color, var(--md-sys-color-on-primary, #fff));height:var(--md-checkbox-icon-size, 18px);width:var(--md-checkbox-icon-size, 18px)}.mark.short{height:2px;transition-property:transform,height;width:2px}.mark.long{height:2px;transition-property:transform,width;width:10px}.mark{animation-duration:150ms;animation-timing-function:cubic-bezier(0.3, 0, 0.8, 0.15);transition-duration:150ms;transition-timing-function:cubic-bezier(0.3, 0, 0.8, 0.15)}.selected .mark{animation-duration:350ms;animation-timing-function:cubic-bezier(0.05, 0.7, 0.1, 1);transition-duration:350ms;transition-timing-function:cubic-bezier(0.05, 0.7, 0.1, 1)}.checked .mark,.prev-checked.unselected .mark{transform:scaleY(-1) translate(7px, -14px) rotate(45deg)}.checked .mark.short,.prev-checked.unselected .mark.short{height:5.6568542495px}.checked .mark.long,.prev-checked.unselected .mark.long{width:11.313708499px}.indeterminate .mark,.prev-indeterminate.unselected .mark{transform:scaleY(-1) translate(4px, -10px) rotate(0deg)}.prev-unselected .mark{transition-property:none}.prev-unselected.checked .mark.long{animation-name:prev-unselected-to-checked}@keyframes prev-unselected-to-checked{from{width:0}}:where(:hover) .outline{border-color:var(--md-checkbox-hover-outline-color, var(--md-sys-color-on-surface, #1d1b20));border-width:var(--md-checkbox-hover-outline-width, 2px)}:where(:hover) .background{background:var(--md-checkbox-selected-hover-container-color, var(--md-sys-color-primary, #6750a4))}:where(:hover) .icon{fill:var(--md-checkbox-selected-hover-icon-color, var(--md-sys-color-on-primary, #fff))}:where(:focus-within) .outline{border-color:var(--md-checkbox-focus-outline-color, var(--md-sys-color-on-surface, #1d1b20));border-width:var(--md-checkbox-focus-outline-width, 2px)}:where(:focus-within) .background{background:var(--md-checkbox-selected-focus-container-color, var(--md-sys-color-primary, #6750a4))}:where(:focus-within) .icon{fill:var(--md-checkbox-selected-focus-icon-color, var(--md-sys-color-on-primary, #fff))}:where(:active) .outline{border-color:var(--md-checkbox-pressed-outline-color, var(--md-sys-color-on-surface, #1d1b20));border-width:var(--md-checkbox-pressed-outline-width, 2px)}:where(:active) .background{background:var(--md-checkbox-selected-pressed-container-color, var(--md-sys-color-primary, #6750a4))}:where(:active) .icon{fill:var(--md-checkbox-selected-pressed-icon-color, var(--md-sys-color-on-primary, #fff))}:where(.disabled,.prev-disabled) :is(.background,.icon,.mark){animation-duration:0s;transition-duration:0s}:where(.disabled) .outline{border-color:var(--md-checkbox-disabled-outline-color, var(--md-sys-color-on-surface, #1d1b20));border-width:var(--md-checkbox-disabled-outline-width, 2px);opacity:var(--md-checkbox-disabled-container-opacity, 0.38)}:where(.selected.disabled) .outline{visibility:hidden}:where(.selected.disabled) .background{background:var(--md-checkbox-selected-disabled-container-color, var(--md-sys-color-on-surface, #1d1b20));opacity:var(--md-checkbox-selected-disabled-container-opacity, 0.38)}:where(.disabled) .icon{fill:var(--md-checkbox-selected-disabled-icon-color, var(--md-sys-color-surface, #fef7ff))}@media(forced-colors: active){.background{background-color:CanvasText}.selected.disabled .background{background-color:GrayText;opacity:1}.outline{border-color:CanvasText}.disabled .outline{border-color:GrayText;opacity:1}.icon{fill:Canvas}}
`;

/**
 * @license
 * Copyright 2018 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @summary Checkboxes allow users to select one or more items from a set.
 * Checkboxes can turn an option on or off.
 *
 * @description
 * Use checkboxes to:
 * - Select one or more options from a list
 * - Present a list containing sub-selections
 * - Turn an item on or off in a desktop environment
 *
 * @final
 * @suppress {visibility}
 */
let MdCheckbox = class MdCheckbox extends Checkbox {};
MdCheckbox.styles = [styles$1];
MdCheckbox = __decorate([t$1('md-checkbox')], MdCheckbox);

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * The default dialog open animation.
 */
const DIALOG_DEFAULT_OPEN_ANIMATION = {
  dialog: [[
  // Dialog slide down
  [{
    'transform': 'translateY(-50px)'
  }, {
    'transform': 'translateY(0)'
  }], {
    duration: 500,
    easing: EASING.EMPHASIZED
  }]],
  scrim: [[
  // Scrim fade in
  [{
    'opacity': 0
  }, {
    'opacity': 0.32
  }], {
    duration: 500,
    easing: 'linear'
  }]],
  container: [[
  // Container fade in
  [{
    'opacity': 0
  }, {
    'opacity': 1
  }], {
    duration: 50,
    easing: 'linear',
    pseudoElement: '::before'
  }], [
  // Container grow
  // Note: current spec says to grow from 0dp->100% and shrink from
  // 100%->35%. We change this to 35%->100% to simplify the animation that
  // is supposed to clip content as it grows. From 0dp it's possible to see
  // text/actions appear before the container has fully grown.
  [{
    'height': '35%'
  }, {
    'height': '100%'
  }], {
    duration: 500,
    easing: EASING.EMPHASIZED,
    pseudoElement: '::before'
  }]],
  headline: [[
  // Headline fade in
  [{
    'opacity': 0
  }, {
    'opacity': 0,
    offset: 0.2
  }, {
    'opacity': 1
  }], {
    duration: 250,
    easing: 'linear',
    fill: 'forwards'
  }]],
  content: [[
  // Content fade in
  [{
    'opacity': 0
  }, {
    'opacity': 0,
    offset: 0.2
  }, {
    'opacity': 1
  }], {
    duration: 250,
    easing: 'linear',
    fill: 'forwards'
  }]],
  actions: [[
  // Actions fade in
  [{
    'opacity': 0
  }, {
    'opacity': 0,
    offset: 0.5
  }, {
    'opacity': 1
  }], {
    duration: 300,
    easing: 'linear',
    fill: 'forwards'
  }]]
};
/**
 * The default dialog close animation.
 */
const DIALOG_DEFAULT_CLOSE_ANIMATION = {
  dialog: [[
  // Dialog slide up
  [{
    'transform': 'translateY(0)'
  }, {
    'transform': 'translateY(-50px)'
  }], {
    duration: 150,
    easing: EASING.EMPHASIZED_ACCELERATE
  }]],
  scrim: [[
  // Scrim fade out
  [{
    'opacity': 0.32
  }, {
    'opacity': 0
  }], {
    duration: 150,
    easing: 'linear'
  }]],
  container: [[
  // Container shrink
  [{
    'height': '100%'
  }, {
    'height': '35%'
  }], {
    duration: 150,
    easing: EASING.EMPHASIZED_ACCELERATE,
    pseudoElement: '::before'
  }], [
  // Container fade out
  [{
    'opacity': '1'
  }, {
    'opacity': '0'
  }], {
    delay: 100,
    duration: 50,
    easing: 'linear',
    pseudoElement: '::before'
  }]],
  headline: [[
  // Headline fade out
  [{
    'opacity': 1
  }, {
    'opacity': 0
  }], {
    duration: 100,
    easing: 'linear',
    fill: 'forwards'
  }]],
  content: [[
  // Content fade out
  [{
    'opacity': 1
  }, {
    'opacity': 0
  }], {
    duration: 100,
    easing: 'linear',
    fill: 'forwards'
  }]],
  actions: [[
  // Actions fade out
  [{
    'opacity': 1
  }, {
    'opacity': 0
  }], {
    duration: 100,
    easing: 'linear',
    fill: 'forwards'
  }]]
};

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Separate variable needed for closure.
const dialogBaseClass = mixinDelegatesAria(i$4);
/**
 * A dialog component.
 *
 * @fires open {Event} Dispatched when the dialog is opening before any animations.
 * @fires opened {Event} Dispatched when the dialog has opened after any animations.
 * @fires close {Event} Dispatched when the dialog is closing before any animations.
 * @fires closed {Event} Dispatched when the dialog has closed after any animations.
 * @fires cancel {Event} Dispatched when the dialog has been canceled by clicking
 * on the scrim or pressing Escape.
 */
class Dialog extends dialogBaseClass {
  // We do not use `delegatesFocus: true` due to a Chromium bug with
  // selecting text.
  // See https://bugs.chromium.org/p/chromium/issues/detail?id=950357
  /**
   * Opens the dialog when set to `true` and closes it when set to `false`.
   */
  get open() {
    return this.isOpen;
  }
  set open(open) {
    if (open === this.isOpen) {
      return;
    }
    this.isOpen = open;
    if (open) {
      this.setAttribute('open', '');
      this.show();
    } else {
      this.removeAttribute('open');
      this.close();
    }
  }
  constructor() {
    super();
    /**
     * Skips the opening and closing animations.
     */
    this.quick = false;
    /**
     * Gets or sets the dialog's return value, usually to indicate which button
     * a user pressed to close it.
     *
     * https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement/returnValue
     */
    this.returnValue = '';
    /**
     * Disables focus trapping, which by default keeps keyboard Tab navigation
     * within the dialog.
     *
     * When disabled, after focusing the last element of a dialog, pressing Tab
     * again will release focus from the window back to the browser (such as the
     * URL bar).
     *
     * Focus trapping is recommended for accessibility, and should not typically
     * be disabled. Only turn this off if the use case of a dialog is more
     * accessible without focus trapping.
     */
    this.noFocusTrap = false;
    /**
     * Gets the opening animation for a dialog. Set to a new function to customize
     * the animation.
     */
    this.getOpenAnimation = () => DIALOG_DEFAULT_OPEN_ANIMATION;
    /**
     * Gets the closing animation for a dialog. Set to a new function to customize
     * the animation.
     */
    this.getCloseAnimation = () => DIALOG_DEFAULT_CLOSE_ANIMATION;
    this.isOpen = false;
    this.isOpening = false;
    this.isConnectedPromise = this.getIsConnectedPromise();
    this.isAtScrollTop = false;
    this.isAtScrollBottom = false;
    this.nextClickIsFromContent = false;
    // Dialogs should not be SSR'd while open, so we can just use runtime checks.
    this.hasHeadline = false;
    this.hasActions = false;
    this.hasIcon = false;
    // See https://bugs.chromium.org/p/chromium/issues/detail?id=1512224
    // Chrome v120 has a bug where escape keys do not trigger cancels. If we get
    // a dialog "close" event that is triggered without a "cancel" after an escape
    // keydown, then we need to manually trigger our closing logic.
    //
    // This bug occurs when pressing escape to close a dialog without first
    // interacting with the dialog's content.
    //
    // Cleanup tracking:
    // https://github.com/material-components/material-web/issues/5330
    // This can be removed when full CloseWatcher support added and the above bug
    // in Chromium is fixed to fire 'cancel' with one escape press and close with
    // multiple.
    this.escapePressedWithoutCancel = false;
    // This TreeWalker is used to walk through a dialog's children to find
    // focusable elements. TreeWalker is faster than `querySelectorAll('*')`.
    // We check for isServer because there isn't a "document" during an SSR
    // run.
    this.treewalker = document.createTreeWalker(this, NodeFilter.SHOW_ELEMENT);
    {
      this.addEventListener('submit', this.handleSubmit);
    }
  }
  /**
   * Opens the dialog and fires a cancelable `open` event. After a dialog's
   * animation, an `opened` event is fired.
   *
   * Add an `autofocus` attribute to a child of the dialog that should
   * receive focus after opening.
   *
   * @return A Promise that resolves after the animation is finished and the
   *     `opened` event was fired.
   */
  async show() {
    this.isOpening = true;
    // Dialogs can be opened before being attached to the DOM, so we need to
    // wait until we're connected before calling `showModal()`.
    await this.isConnectedPromise;
    await this.updateComplete;
    const dialog = this.dialog;
    // Check if already opened or if `dialog.close()` was called while awaiting.
    if (dialog.open || !this.isOpening) {
      this.isOpening = false;
      return;
    }
    const preventOpen = !this.dispatchEvent(new Event('open', {
      cancelable: true
    }));
    if (preventOpen) {
      this.open = false;
      this.isOpening = false;
      return;
    }
    // All Material dialogs are modal.
    dialog.showModal();
    this.open = true;
    // Reset scroll position if re-opening a dialog with the same content.
    if (this.scroller) {
      this.scroller.scrollTop = 0;
    }
    // Native modal dialogs ignore autofocus and instead force focus to the
    // first focusable child. Override this behavior if there is a child with
    // an autofocus attribute.
    this.querySelector('[autofocus]')?.focus();
    await this.animateDialog(this.getOpenAnimation());
    this.dispatchEvent(new Event('opened'));
    this.isOpening = false;
  }
  /**
   * Closes the dialog and fires a cancelable `close` event. After a dialog's
   * animation, a `closed` event is fired.
   *
   * @param returnValue A return value usually indicating which button was used
   *     to close a dialog. If a dialog is canceled by clicking the scrim or
   *     pressing Escape, it will not change the return value after closing.
   * @return A Promise that resolves after the animation is finished and the
   *     `closed` event was fired.
   */
  async close(returnValue = this.returnValue) {
    this.isOpening = false;
    if (!this.isConnected) {
      // Disconnected dialogs do not fire close events or animate.
      this.open = false;
      return;
    }
    await this.updateComplete;
    const dialog = this.dialog;
    // Check if already closed or if `dialog.show()` was called while awaiting.
    if (!dialog.open || this.isOpening) {
      this.open = false;
      return;
    }
    const prevReturnValue = this.returnValue;
    this.returnValue = returnValue;
    const preventClose = !this.dispatchEvent(new Event('close', {
      cancelable: true
    }));
    if (preventClose) {
      this.returnValue = prevReturnValue;
      return;
    }
    await this.animateDialog(this.getCloseAnimation());
    dialog.close(returnValue);
    this.open = false;
    this.dispatchEvent(new Event('closed'));
  }
  connectedCallback() {
    super.connectedCallback();
    this.isConnectedPromiseResolve();
  }
  disconnectedCallback() {
    super.disconnectedCallback();
    this.isConnectedPromise = this.getIsConnectedPromise();
  }
  render() {
    const scrollable = this.open && !(this.isAtScrollTop && this.isAtScrollBottom);
    const classes = {
      'has-headline': this.hasHeadline,
      'has-actions': this.hasActions,
      'has-icon': this.hasIcon,
      'scrollable': scrollable,
      'show-top-divider': scrollable && !this.isAtScrollTop,
      'show-bottom-divider': scrollable && !this.isAtScrollBottom
    };
    // The focus trap sentinels are only added after the dialog opens, since
    // dialog.showModal() will try to autofocus them, even with tabindex="-1".
    const showFocusTrap = this.open && !this.noFocusTrap;
    const focusTrap = b`
      <div
        class="focus-trap"
        tabindex="0"
        aria-hidden="true"
        @focus=${this.handleFocusTrapFocus}></div>
    `;
    const {
      ariaLabel
    } = this;
    return b`
      <div class="scrim"></div>
      <dialog
        class=${e$3(classes)}
        aria-label=${ariaLabel || A}
        aria-labelledby=${this.hasHeadline ? 'headline' : A}
        role=${this.type === 'alert' ? 'alertdialog' : A}
        @cancel=${this.handleCancel}
        @click=${this.handleDialogClick}
        @close=${this.handleClose}
        @keydown=${this.handleKeydown}
        .returnValue=${this.returnValue || A}>
        ${showFocusTrap ? focusTrap : A}
        <div class="container" @click=${this.handleContentClick}>
          <div class="headline">
            <div class="icon" aria-hidden="true">
              <slot name="icon" @slotchange=${this.handleIconChange}></slot>
            </div>
            <h2 id="headline" aria-hidden=${!this.hasHeadline || A}>
              <slot
                name="headline"
                @slotchange=${this.handleHeadlineChange}></slot>
            </h2>
            <md-divider></md-divider>
          </div>
          <div class="scroller">
            <div class="content">
              <div class="top anchor"></div>
              <slot name="content"></slot>
              <div class="bottom anchor"></div>
            </div>
          </div>
          <div class="actions">
            <md-divider></md-divider>
            <slot name="actions" @slotchange=${this.handleActionsChange}></slot>
          </div>
        </div>
        ${showFocusTrap ? focusTrap : A}
      </dialog>
    `;
  }
  firstUpdated() {
    this.intersectionObserver = new IntersectionObserver(entries => {
      for (const entry of entries) {
        this.handleAnchorIntersection(entry);
      }
    }, {
      root: this.scroller
    });
    this.intersectionObserver.observe(this.topAnchor);
    this.intersectionObserver.observe(this.bottomAnchor);
  }
  handleDialogClick() {
    if (this.nextClickIsFromContent) {
      // Avoid doing a layout calculation below if we know the click came from
      // content.
      this.nextClickIsFromContent = false;
      return;
    }
    // Click originated on the backdrop. Native `<dialog>`s will not cancel,
    // but Material dialogs do.
    const preventDefault = !this.dispatchEvent(new Event('cancel', {
      cancelable: true
    }));
    if (preventDefault) {
      return;
    }
    this.close();
  }
  handleContentClick() {
    this.nextClickIsFromContent = true;
  }
  handleSubmit(event) {
    const form = event.target;
    const {
      submitter
    } = event;
    if (form.getAttribute('method') !== 'dialog' || !submitter) {
      return;
    }
    // Close reason is the submitter's value attribute, or the dialog's
    // `returnValue` if there is no attribute.
    this.close(submitter.getAttribute('value') ?? this.returnValue);
  }
  handleCancel(event) {
    if (event.target !== this.dialog) {
      // Ignore any cancel events dispatched by content.
      return;
    }
    this.escapePressedWithoutCancel = false;
    const preventDefault = !redispatchEvent(this, event);
    // We always prevent default on the original dialog event since we'll
    // animate closing it before it actually closes.
    event.preventDefault();
    if (preventDefault) {
      return;
    }
    this.close();
  }
  handleClose() {
    if (!this.escapePressedWithoutCancel) {
      return;
    }
    this.escapePressedWithoutCancel = false;
    this.dialog?.dispatchEvent(new Event('cancel', {
      cancelable: true
    }));
  }
  handleKeydown(event) {
    if (event.key !== 'Escape') {
      return;
    }
    // An escape key was pressed. If a "close" event fires next without a
    // "cancel" event first, then we know we're in the Chrome v120 bug.
    this.escapePressedWithoutCancel = true;
    // Wait a full task for the cancel/close event listeners to fire, then
    // reset the flag.
    setTimeout(() => {
      this.escapePressedWithoutCancel = false;
    });
  }
  async animateDialog(animation) {
    // Always cancel the previous animations. Animations can include `fill`
    // modes that need to be cleared when `quick` is toggled. If not, content
    // that faded out will remain hidden when a `quick` dialog re-opens after
    // previously opening and closing without `quick`.
    this.cancelAnimations?.abort();
    this.cancelAnimations = new AbortController();
    if (this.quick) {
      return;
    }
    const {
      dialog,
      scrim,
      container,
      headline,
      content,
      actions
    } = this;
    if (!dialog || !scrim || !container || !headline || !content || !actions) {
      return;
    }
    const {
      container: containerAnimate,
      dialog: dialogAnimate,
      scrim: scrimAnimate,
      headline: headlineAnimate,
      content: contentAnimate,
      actions: actionsAnimate
    } = animation;
    const elementAndAnimation = [[dialog, dialogAnimate ?? []], [scrim, scrimAnimate ?? []], [container, containerAnimate ?? []], [headline, headlineAnimate ?? []], [content, contentAnimate ?? []], [actions, actionsAnimate ?? []]];
    const animations = [];
    for (const [element, animation] of elementAndAnimation) {
      for (const animateArgs of animation) {
        const animation = element.animate(...animateArgs);
        this.cancelAnimations.signal.addEventListener('abort', () => {
          animation.cancel();
        });
        animations.push(animation);
      }
    }
    await Promise.all(animations.map(animation => animation.finished.catch(() => {
      // Ignore intentional AbortErrors when calling `animation.cancel()`.
    })));
  }
  handleHeadlineChange(event) {
    const slot = event.target;
    this.hasHeadline = slot.assignedElements().length > 0;
  }
  handleActionsChange(event) {
    const slot = event.target;
    this.hasActions = slot.assignedElements().length > 0;
  }
  handleIconChange(event) {
    const slot = event.target;
    this.hasIcon = slot.assignedElements().length > 0;
  }
  handleAnchorIntersection(entry) {
    const {
      target,
      isIntersecting
    } = entry;
    if (target === this.topAnchor) {
      this.isAtScrollTop = isIntersecting;
    }
    if (target === this.bottomAnchor) {
      this.isAtScrollBottom = isIntersecting;
    }
  }
  getIsConnectedPromise() {
    return new Promise(resolve => {
      this.isConnectedPromiseResolve = resolve;
    });
  }
  handleFocusTrapFocus(event) {
    const [firstFocusableChild, lastFocusableChild] = this.getFirstAndLastFocusableChildren();
    if (!firstFocusableChild || !lastFocusableChild) {
      // When a dialog does not have focusable children, the dialog itself
      // receives focus.
      this.dialog?.focus();
      return;
    }
    // To determine which child to focus, we need to know which focus trap
    // received focus...
    const isFirstFocusTrap = event.target === this.firstFocusTrap;
    const isLastFocusTrap = !isFirstFocusTrap;
    // ...and where the focus came from (what was previously focused).
    const focusCameFromFirstChild = event.relatedTarget === firstFocusableChild;
    const focusCameFromLastChild = event.relatedTarget === lastFocusableChild;
    // Although this is a focus trap, focus can come from outside the trap.
    // This can happen when elements are programmatically `focus()`'d. It also
    // happens when focus leaves and returns to the window, such as clicking on
    // the browser's URL bar and pressing Tab, or switching focus between
    // iframes.
    const focusCameFromOutsideDialog = !focusCameFromFirstChild && !focusCameFromLastChild;
    // Focus the dialog's first child when we reach the end of the dialog and
    // focus is moving forward. Or, when focus is moving forwards into the
    // dialog from outside of the window.
    const shouldFocusFirstChild = isLastFocusTrap && focusCameFromLastChild || isFirstFocusTrap && focusCameFromOutsideDialog;
    if (shouldFocusFirstChild) {
      firstFocusableChild.focus();
      return;
    }
    // Focus the dialog's last child when we reach the beginning of the dialog
    // and focus is moving backward. Or, when focus is moving backwards into the
    // dialog from outside of the window.
    const shouldFocusLastChild = isFirstFocusTrap && focusCameFromFirstChild || isLastFocusTrap && focusCameFromOutsideDialog;
    if (shouldFocusLastChild) {
      lastFocusableChild.focus();
      return;
    }
    // The booleans above are verbose for readability, but code executation
    // won't actually reach here.
  }
  getFirstAndLastFocusableChildren() {
    if (!this.treewalker) {
      return [null, null];
    }
    let firstFocusableChild = null;
    let lastFocusableChild = null;
    // Reset the current node back to the root host element.
    this.treewalker.currentNode = this.treewalker.root;
    while (this.treewalker.nextNode()) {
      // Cast as Element since the TreeWalker filter only accepts Elements.
      const nextChild = this.treewalker.currentNode;
      if (!isFocusable(nextChild)) {
        continue;
      }
      if (!firstFocusableChild) {
        firstFocusableChild = nextChild;
      }
      lastFocusableChild = nextChild;
    }
    // We set lastFocusableChild immediately after finding a
    // firstFocusableChild, which means the pair is either both null or both
    // non-null. Cast since TypeScript does not recognize this.
    return [firstFocusableChild, lastFocusableChild];
  }
}
__decorate([n$5({
  type: Boolean
})], Dialog.prototype, "open", null);
__decorate([n$5({
  type: Boolean
})], Dialog.prototype, "quick", void 0);
__decorate([n$5({
  attribute: false
})], Dialog.prototype, "returnValue", void 0);
__decorate([n$5()], Dialog.prototype, "type", void 0);
__decorate([n$5({
  type: Boolean,
  attribute: 'no-focus-trap'
})], Dialog.prototype, "noFocusTrap", void 0);
__decorate([e$6('dialog')], Dialog.prototype, "dialog", void 0);
__decorate([e$6('.scrim')], Dialog.prototype, "scrim", void 0);
__decorate([e$6('.container')], Dialog.prototype, "container", void 0);
__decorate([e$6('.headline')], Dialog.prototype, "headline", void 0);
__decorate([e$6('.content')], Dialog.prototype, "content", void 0);
__decorate([e$6('.actions')], Dialog.prototype, "actions", void 0);
__decorate([r$3()], Dialog.prototype, "isAtScrollTop", void 0);
__decorate([r$3()], Dialog.prototype, "isAtScrollBottom", void 0);
__decorate([e$6('.scroller')], Dialog.prototype, "scroller", void 0);
__decorate([e$6('.top.anchor')], Dialog.prototype, "topAnchor", void 0);
__decorate([e$6('.bottom.anchor')], Dialog.prototype, "bottomAnchor", void 0);
__decorate([e$6('.focus-trap')], Dialog.prototype, "firstFocusTrap", void 0);
__decorate([r$3()], Dialog.prototype, "hasHeadline", void 0);
__decorate([r$3()], Dialog.prototype, "hasActions", void 0);
__decorate([r$3()], Dialog.prototype, "hasIcon", void 0);
function isFocusable(element) {
  // Check if the element is a known built-in focusable element:
  // - <a> and <area> with `href` attributes.
  // - Form controls that are not disabled.
  // - `contenteditable` elements.
  // - Anything with a non-negative `tabindex`.
  const knownFocusableElements = ':is(button,input,select,textarea,object,:is(a,area)[href],[tabindex],[contenteditable=true])';
  const notDisabled = ':not(:disabled,[disabled])';
  const notNegativeTabIndex = ':not([tabindex^="-"])';
  if (element.matches(knownFocusableElements + notDisabled + notNegativeTabIndex)) {
    return true;
  }
  const isCustomElement = element.localName.includes('-');
  if (!isCustomElement) {
    return false;
  }
  // If a custom element does not have a tabindex, it may still be focusable
  // if it delegates focus with a shadow root. We also need to check again if
  // the custom element is a disabled form control.
  if (!element.matches(notDisabled)) {
    return false;
  }
  return element.shadowRoot?.delegatesFocus ?? false;
}

/**
 * @license
 * Copyright 2024 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
// Generated stylesheet for ./dialog/internal/dialog-styles.css.
const styles = i$7`:host{border-start-start-radius:var(--md-dialog-container-shape-start-start, var(--md-dialog-container-shape, var(--md-sys-shape-corner-extra-large, 28px)));border-start-end-radius:var(--md-dialog-container-shape-start-end, var(--md-dialog-container-shape, var(--md-sys-shape-corner-extra-large, 28px)));border-end-end-radius:var(--md-dialog-container-shape-end-end, var(--md-dialog-container-shape, var(--md-sys-shape-corner-extra-large, 28px)));border-end-start-radius:var(--md-dialog-container-shape-end-start, var(--md-dialog-container-shape, var(--md-sys-shape-corner-extra-large, 28px)));display:contents;margin:auto;max-height:min(560px,100% - 48px);max-width:min(560px,100% - 48px);min-height:140px;min-width:280px;position:fixed;height:fit-content;width:fit-content}dialog{background:rgba(0,0,0,0);border:none;border-radius:inherit;flex-direction:column;height:inherit;margin:inherit;max-height:inherit;max-width:inherit;min-height:inherit;min-width:inherit;outline:none;overflow:visible;padding:0;width:inherit}dialog[open]{display:flex}::backdrop{background:none}.scrim{background:var(--md-sys-color-scrim, #000);display:none;inset:0;opacity:32%;pointer-events:none;position:fixed;z-index:1}:host([open]) .scrim{display:flex}h2{all:unset;align-self:stretch}.headline{align-items:center;color:var(--md-dialog-headline-color, var(--md-sys-color-on-surface, #1d1b20));display:flex;flex-direction:column;font-family:var(--md-dialog-headline-font, var(--md-sys-typescale-headline-small-font, var(--md-ref-typeface-brand, Roboto)));font-size:var(--md-dialog-headline-size, var(--md-sys-typescale-headline-small-size, 1.5rem));line-height:var(--md-dialog-headline-line-height, var(--md-sys-typescale-headline-small-line-height, 2rem));font-weight:var(--md-dialog-headline-weight, var(--md-sys-typescale-headline-small-weight, var(--md-ref-typeface-weight-regular, 400)));position:relative}slot[name=headline]::slotted(*){align-items:center;align-self:stretch;box-sizing:border-box;display:flex;gap:8px;padding:24px 24px 0}.icon{display:flex}slot[name=icon]::slotted(*){color:var(--md-dialog-icon-color, var(--md-sys-color-secondary, #625b71));fill:currentColor;font-size:var(--md-dialog-icon-size, 24px);margin-top:24px;height:var(--md-dialog-icon-size, 24px);width:var(--md-dialog-icon-size, 24px)}.has-icon slot[name=headline]::slotted(*){justify-content:center;padding-top:16px}.scrollable slot[name=headline]::slotted(*){padding-bottom:16px}.scrollable.has-headline slot[name=content]::slotted(*){padding-top:8px}.container{border-radius:inherit;display:flex;flex-direction:column;flex-grow:1;overflow:hidden;position:relative;transform-origin:top}.container::before{background:var(--md-dialog-container-color, var(--md-sys-color-surface-container-high, #ece6f0));border-radius:inherit;content:"";inset:0;position:absolute}.scroller{display:flex;flex:1;flex-direction:column;overflow:hidden;z-index:1}.scrollable .scroller{overflow-y:scroll}.content{color:var(--md-dialog-supporting-text-color, var(--md-sys-color-on-surface-variant, #49454f));font-family:var(--md-dialog-supporting-text-font, var(--md-sys-typescale-body-medium-font, var(--md-ref-typeface-plain, Roboto)));font-size:var(--md-dialog-supporting-text-size, var(--md-sys-typescale-body-medium-size, 0.875rem));line-height:var(--md-dialog-supporting-text-line-height, var(--md-sys-typescale-body-medium-line-height, 1.25rem));flex:1;font-weight:var(--md-dialog-supporting-text-weight, var(--md-sys-typescale-body-medium-weight, var(--md-ref-typeface-weight-regular, 400)));height:min-content;position:relative}slot[name=content]::slotted(*){box-sizing:border-box;padding:24px}.anchor{position:absolute}.top.anchor{top:0}.bottom.anchor{bottom:0}.actions{position:relative}slot[name=actions]::slotted(*){box-sizing:border-box;display:flex;gap:8px;justify-content:flex-end;padding:16px 24px 24px}.has-actions slot[name=content]::slotted(*){padding-bottom:8px}md-divider{display:none;position:absolute}.has-headline.show-top-divider .headline md-divider,.has-actions.show-bottom-divider .actions md-divider{display:flex}.headline md-divider{bottom:0}.actions md-divider{top:0}@media(forced-colors: active){dialog{outline:2px solid WindowText}}
`;

/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @summary Dialogs can require an action, communicate information, or help
 * users accomplish a task. There are two types of dialogs: basic and
 * full-screen.
 *
 * @description
 * A dialog is a modal window that appears in front of app content to provide
 * critical information or ask for a decision. Dialogs disable all app
 * functionality when they appear, and remain on screen until confirmed,
 * dismissed, or a required action has been taken.
 *
 * Dialogs are purposefully interruptive, so they should be used sparingly.
 * A less disruptive alternative is to use a menu, which provides options
 * without interrupting a user’s experience.
 *
 * On mobile devices only, complex dialogs should be displayed fullscreen.
 *
 * __Example usages:__
 * - Common use cases for basic dialogs include alerts, quick selection, and
 * confirmation.
 * - More complex dialogs may contain actions that require a series of tasks
 * to complete. One example is creating a calendar entry with the event title,
 * date, location, and time.
 *
 * @final
 * @suppress {visibility}
 */
let MdDialog = class MdDialog extends Dialog {};
MdDialog.styles = [styles];
MdDialog = __decorate([t$1('md-dialog')], MdDialog);

var __defProp$8 = Object.defineProperty;
var __getOwnPropDesc$8 = Object.getOwnPropertyDescriptor;
var __decorateClass$9 = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$8(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp$8(target, key, result);
  return result;
};
const THREAD_ATTRIBUTE_PATHS = ["0/53/7", "0/53/8", "0/51/0"];
const WIFI_ATTRIBUTE_PATHS = ["0/54/0", "0/54/3", "0/54/4"];
let UpdateConnectionsDialog = class extends i$4 {
  constructor() {
    super(...arguments);
    this._tick = 0;
    this.nodes = {};
    this.selectedNodeType = "online";
    this.selectedNodeName = "";
    this.selectedNodeId = null;
    this.onlineNeighborIds = [];
    this._includeNeighbors = false;
    this._isUpdating = false;
    /** Timeout ID for auto-close */
    this._timeoutId = null;
    /** Track if we've already dispatched close event to prevent double-firing */
    this._hasClosedEvent = false;
  }
  firstUpdated() {
    const dialog = this.shadowRoot?.querySelector("md-dialog");
    dialog?.show();
  }
  disconnectedCallback() {
    super.disconnectedCallback();
    if (this._timeoutId) {
      clearTimeout(this._timeoutId);
      this._timeoutId = null;
    }
  }
  /**
   * Get the number of nodes that will be updated.
   */
  get _updateCount() {
    if (this.selectedNodeType === "online") {
      return this._includeNeighbors ? 1 + this.onlineNeighborIds.length : 1;
    }
    return this.onlineNeighborIds.length;
  }
  /**
   * Get the attribute paths to read for a node based on its network type.
   */
  _getAttributePathsForNode(nodeId) {
    const node = this.nodes[nodeId];
    if (!node) return [];
    const networkType = getNetworkType(node);
    if (networkType === "thread") {
      return THREAD_ATTRIBUTE_PATHS;
    }
    if (networkType === "wifi") {
      return WIFI_ATTRIBUTE_PATHS;
    }
    return [];
  }
  /**
   * Get the list of node IDs to update based on current state.
   */
  _getNodeIdsToUpdate() {
    if (this.selectedNodeType === "online") {
      const nodeIds = [String(this.selectedNodeId)];
      if (this._includeNeighbors) {
        nodeIds.push(...this.onlineNeighborIds);
      }
      return nodeIds;
    }
    return this.onlineNeighborIds;
  }
  async _executeUpdate() {
    if (this._isUpdating || this._updateCount === 0) return;
    this._isUpdating = true;
    this._timeoutId = setTimeout(() => {
      console.warn("Update connections timed out after 30s");
      this._closeDialog();
    }, 3e4);
    try {
      const nodeIds = this._getNodeIdsToUpdate();
      const updatePromises = nodeIds.map(async nodeIdStr => {
        const node = this.nodes[nodeIdStr];
        if (!node) return;
        const paths = this._getAttributePathsForNode(nodeIdStr);
        if (paths.length === 0) return;
        await this.client.readAttribute(node.node_id, paths);
      });
      await Promise.all(updatePromises);
      this._closeDialog();
    } catch (error) {
      console.error("Failed to update connections:", error);
      this._closeDialog();
    } finally {
      if (this._timeoutId) {
        clearTimeout(this._timeoutId);
        this._timeoutId = null;
      }
      this._isUpdating = false;
    }
  }
  _closeDialog() {
    if (this._hasClosedEvent) return;
    this._hasClosedEvent = true;
    const dialog = this.shadowRoot?.querySelector("md-dialog");
    dialog?.close();
    this.dispatchEvent(new CustomEvent("dialog-closed", {
      bubbles: true,
      composed: true
    }));
  }
  /** Handle native dialog closed event (ESC key, backdrop click, etc.) */
  _handleDialogClosed() {
    this._closeDialog();
  }
  _handleCheckboxChange(e) {
    const checkbox = e.target;
    this._includeNeighbors = checkbox.checked;
  }
  _renderOnlineContent() {
    return b`
            <p>Refresh network information for "<strong>${this.selectedNodeName}</strong>".</p>
            ${this.onlineNeighborIds.length > 0 ? b`
                      <label class="checkbox-row">
                          <md-checkbox
                              ?checked=${this._includeNeighbors}
                              @change=${this._handleCheckboxChange}
                              ?disabled=${this._isUpdating}
                          ></md-checkbox>
                          <span
                              >Include ${this.onlineNeighborIds.length} connected online
                              neighbor${this.onlineNeighborIds.length !== 1 ? "s" : ""}</span
                          >
                      </label>
                  ` : A}
        `;
  }
  _renderOfflineContent() {
    return b`
            <p>"<strong>${this.selectedNodeName}</strong>" appears to be offline.</p>
            ${this.onlineNeighborIds.length > 0 ? b`
                      <p>
                          Update network data from its ${this.onlineNeighborIds.length} online
                          neighbor${this.onlineNeighborIds.length !== 1 ? "s" : ""} to refresh connection info.
                      </p>
                  ` : b` <p>No online neighbors available to update.</p> `}
        `;
  }
  _renderUnknownContent() {
    return b`
            <p>This device is not commissioned to this fabric and cannot be queried directly.</p>
            ${this.onlineNeighborIds.length > 0 ? b`
                      <p>
                          Update network data from ${this.onlineNeighborIds.length}
                          node${this.onlineNeighborIds.length !== 1 ? "s" : ""} that
                          see${this.onlineNeighborIds.length === 1 ? "s" : ""} this device to refresh info.
                      </p>
                  ` : b` <p>No online nodes available that see this device.</p> `}
        `;
  }
  render() {
    const buttonText = this._updateCount === 0 ? "No nodes to update" : `Update ${this._updateCount} node${this._updateCount !== 1 ? "s" : ""}`;
    return b`
            <md-dialog @closed=${this._handleDialogClosed}>
                <div slot="headline">Update Connection Data</div>
                <div slot="content">
                    ${this.selectedNodeType === "online" ? this._renderOnlineContent() : this.selectedNodeType === "offline" ? this._renderOfflineContent() : this._renderUnknownContent()}
                </div>
                <div slot="actions">
                    <md-text-button @click=${this._closeDialog} ?disabled=${this._isUpdating}>Cancel</md-text-button>
                    <md-filled-button
                        @click=${this._executeUpdate}
                        ?disabled=${this._isUpdating || this._updateCount === 0}
                    >
                        ${this._isUpdating ? b`<span class="updating-content"
                                  >${w`<svg class="spinner" viewBox="0 0 24 24" width="18" height="18"><path fill="currentColor" d="${mdiLoading}"/></svg>`}Updating...</span
                              >` : buttonText}
                    </md-filled-button>
                </div>
            </md-dialog>
        `;
  }
};
UpdateConnectionsDialog.styles = [reducedMotionStyles, i$7`
            md-dialog {
                --md-dialog-container-color: var(--md-sys-color-surface, #fff);
            }

            [slot="content"] {
                padding: 0 24px;
            }

            [slot="content"] p {
                margin: 0 0 16px 0;
                font-size: 0.875rem;
                line-height: 1.5;
                color: var(--md-sys-color-on-surface, #333);
            }

            [slot="content"] p:last-child {
                margin-bottom: 0;
            }

            .checkbox-row {
                display: flex;
                align-items: center;
                gap: 8px;
                cursor: pointer;
                font-size: 0.875rem;
                color: var(--md-sys-color-on-surface, #333);
            }

            .updating-content {
                display: inline-flex;
                align-items: center;
                gap: 8px;
            }

            .spinner {
                animation: spin 1s linear infinite;
                flex-shrink: 0;
            }

            .updating-content svg {
                color: inherit;
            }

            @keyframes spin {
                from {
                    transform: rotate(0deg);
                }
                to {
                    transform: rotate(360deg);
                }
            }

            md-filled-button {
                min-width: 140px;
            }
        `];
__decorateClass$9([c$5({
  context: clientContext
})], UpdateConnectionsDialog.prototype, "client", 2);
__decorateClass$9([c$5({
  context: tickContext,
  subscribe: true
})], UpdateConnectionsDialog.prototype, "_tick", 2);
__decorateClass$9([n$5({
  type: Object
})], UpdateConnectionsDialog.prototype, "nodes", 2);
__decorateClass$9([n$5({
  type: String
})], UpdateConnectionsDialog.prototype, "selectedNodeType", 2);
__decorateClass$9([n$5({
  type: String
})], UpdateConnectionsDialog.prototype, "selectedNodeName", 2);
__decorateClass$9([n$5()], UpdateConnectionsDialog.prototype, "selectedNodeId", 2);
__decorateClass$9([n$5({
  type: Array
})], UpdateConnectionsDialog.prototype, "onlineNeighborIds", 2);
__decorateClass$9([r$3()], UpdateConnectionsDialog.prototype, "_includeNeighbors", 2);
__decorateClass$9([r$3()], UpdateConnectionsDialog.prototype, "_isUpdating", 2);
UpdateConnectionsDialog = __decorateClass$9([t$1("update-connections-dialog")], UpdateConnectionsDialog);

var __defProp$7 = Object.defineProperty;
var __getOwnPropDesc$7 = Object.getOwnPropertyDescriptor;
var __decorateClass$8 = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$7(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp$7(target, key, result);
  return result;
};
let NetworkDetails = class extends i$4 {
  constructor() {
    super(...arguments);
    this.selectedNodeId = null;
    this.hideOfflineNodes = false;
    this.hideWeakSignalEdges = false;
    this.hideMediumSignalEdges = false;
    this.hideStrongSignalEdges = false;
    this.nodes = {};
    this.unknownDevices = /* @__PURE__ */new Map();
    this.borderRouters = /* @__PURE__ */new Map();
    this.wifiAccessPoints = /* @__PURE__ */new Map();
    this.threadEdgePairs = /* @__PURE__ */new Map();
    this._showUpdateDialog = false;
  }
  _handleClose() {
    this.dispatchEvent(new CustomEvent("close", {
      bubbles: true,
      composed: true
    }));
  }
  _handleSelectNode(nodeId) {
    this.dispatchEvent(new CustomEvent("select-node", {
      detail: {
        nodeId
      },
      bubbles: true,
      composed: true
    }));
  }
  /** Handle keyboard interaction for clickable elements (Enter/Space activates) */
  _handleKeyDown(event, nodeId) {
    if (event.key === "Enter" || event.key === " ") {
      event.preventDefault();
      this._handleSelectNode(nodeId);
    }
  }
  _getSignalIcon(level) {
    switch (level) {
      case "strong":
        return mdiSignalCellular3;
      case "medium":
        return mdiSignalCellular2;
      case "weak":
        return mdiSignalCellular1;
      case "none":
        return mdiLinkVariantOff;
    }
  }
  /**
   * Format a node ID as hex for Matter log format display.
   * Returns format like "@1:7b" for node ID 123.
   */
  _formatNodeIdHex(nodeId) {
    const node = this.nodes[String(nodeId)];
    const isTestNode = node ? isTestNodeId(node.node_id) : false;
    const fabricIndex = getEffectiveFabricIndex(this.client?.serverInfo?.fabric_index, isTestNode);
    return formatNodeAddressFromAny(fabricIndex, nodeId);
  }
  _getExternalDeviceLabel(conn) {
    const device = this.unknownDevices.get(String(conn.connectedNodeId));
    if (device?.kind === "br" && device.hostname) {
      return b`${stripMdnsHostname(device.hostname)}`;
    }
    return b`External: <span class="mono">${conn.extAddressHex}</span>`;
  }
  _renderWiFiInfo(node) {
    const wifiDiag = getWiFiDiagnostics(node);
    if (!wifiDiag.bssid && wifiDiag.rssi === null) {
      return A;
    }
    const signalColor = getSignalColorFromRssi(wifiDiag.rssi);
    return b`
            <div class="section">
                <h4>WiFi Network</h4>
                ${wifiDiag.bssid ? b`
                          <div class="info-row">
                              <span class="label">BSSID:</span>
                              <span class="value mono">${wifiDiag.bssid}</span>
                          </div>
                      ` : A}
                ${wifiDiag.rssi !== null ? b`
                          <div class="info-row">
                              <span class="label">Signal:</span>
                              <span class="value" style="color: ${signalColor}">${wifiDiag.rssi} dBm</span>
                          </div>
                      ` : A}
                ${wifiDiag.channel !== null ? b`
                          <div class="info-row">
                              <span class="label">Channel:</span>
                              <span class="value">${wifiDiag.channel}</span>
                          </div>
                      ` : A}
                ${wifiDiag.securityType !== null ? b`
                          <div class="info-row">
                              <span class="label">Security:</span>
                              <span class="value">${getWiFiSecurityTypeName(wifiDiag.securityType)}</span>
                          </div>
                      ` : A}
                ${wifiDiag.wifiVersion !== null ? b`
                          <div class="info-row">
                              <span class="label">WiFi Version:</span>
                              <span class="value">${getWiFiVersionName(wifiDiag.wifiVersion)}</span>
                          </div>
                      ` : A}
            </div>
        `;
  }
  _renderThreadInfo(node) {
    const threadRole = getThreadRole(node);
    const channel = getThreadChannel(node);
    const extAddressHex = getThreadExtendedAddressHex(node);
    const threadVersion = getThreadVersion(node);
    const nodeId = String(node.node_id);
    const connections = getNodeConnectionsFromPairs(nodeId, this.threadEdgePairs, this.nodes, {
      hideOfflineNodes: this.hideOfflineNodes,
      hideWeakSignalEdges: this.hideWeakSignalEdges,
      hideMediumSignalEdges: this.hideMediumSignalEdges,
      hideStrongSignalEdges: this.hideStrongSignalEdges
    });
    return b`
            <div class="section">
                <h4>Thread Network</h4>
                <div class="info-row">
                    <span class="label">Role:</span>
                    <span class="value">${getThreadRoleName(threadRole)}</span>
                </div>
                ${threadVersion !== void 0 ? b`
                          <div class="info-row">
                              <span class="label">Thread version:</span>
                              <span class="value">${formatThreadVersion(threadVersion)}</span>
                          </div>
                      ` : A}
                ${channel !== void 0 ? b`
                          <div class="info-row">
                              <span class="label">Channel:</span>
                              <span class="value">${channel}</span>
                          </div>
                      ` : A}
                ${extAddressHex ? b`
                          <div class="info-row">
                              <span class="label">Extended Address:</span>
                              <span class="value mono">${extAddressHex}</span>
                          </div>
                      ` : A}
                <div class="info-row">
                    <span class="label">Direct neighbors:</span>
                    <span class="value">${connections.length}</span>
                </div>
                ${(() => {
      const routableCount = getRoutableDestinationsCount(node);
      return routableCount > 0 ? b`
                              <div class="info-row">
                                  <span class="label">Routable destinations:</span>
                                  <span class="value">${routableCount}</span>
                              </div>
                          ` : A;
    })()}
            </div>

            ${connections.length > 0 ? b`
                      <md-divider></md-divider>
                      <div class="section">
                          <h4>Connections (${connections.length})</h4>
                          <div class="neighbors-list">
                              ${connections.toSorted((a, b) => {
      const score = conn => {
        if (conn.rssi !== null && conn.rssi !== void 0) {
          return conn.rssi;
        }
        if (conn.lqi !== null && conn.lqi !== void 0) {
          return conn.lqi;
        }
        return -Infinity;
      };
      return score(b) - score(a);
    }).map(conn => {
      return b`
                                          <div
                                              class="neighbor-item clickable"
                                              role="button"
                                              tabindex="0"
                                              @click=${() => this._handleSelectNode(conn.connectedNodeId)}
                                              @keydown=${e => this._handleKeyDown(e, conn.connectedNodeId)}
                                          >
                                              <ha-svg-icon
                                                  .path=${this._getSignalIcon(conn.signalLevel)}
                                                  style="--icon-primary-color: ${conn.signalColor}"
                                              ></ha-svg-icon>
                                              <div class="neighbor-info">
                                                  <div class="neighbor-name">
                                                      ${conn.connectedNode ? b`Node ${conn.connectedNodeId}
                                                                <span class="node-id-hex"
                                                                    >${this._formatNodeIdHex(conn.connectedNodeId)}</span
                                                                >: ${getDeviceName(conn.connectedNode)}` : this._getExternalDeviceLabel(conn)}
                                                  </div>
                                                  <div class="neighbor-signal">
                                                      ${conn.rssi !== null ? b`RSSI: ${conn.rssi} dBm` : A}${conn.rssi !== null && conn.lqi !== null ? ", " : A}${conn.lqi !== null ? b`LQI: ${conn.lqi}` : A}${conn.bidirectionalLqi !== void 0 ? b`<span class="route-info"
                                                                >, Bidir: ${conn.bidirectionalLqi}</span
                                                            >` : A}${conn.pathCost !== void 0 ? b`<span class="route-info"
                                                                >, Cost: ${conn.pathCost}</span
                                                            >` : A}
                                                      ${conn.isReverseOnly ? b`
                                                                <span
                                                                    class="direction-hint reverse-only"
                                                                    title="Peer reports this node but this node has no matching neighbor-table entry. Possible one-way visibility (range, TX power, or stale neighbor table)."
                                                                    >← one-way</span
                                                                >
                                                            ` : !conn.isOutgoing ? b` <span class="direction-hint">(reverse)</span> ` : A}
                                                  </div>
                                              </div>
                                          </div>
                                      `;
    })}
                          </div>
                      </div>
                  ` : A}
        `;
  }
  _renderNodeInfo(node) {
    const networkType = getNetworkType(node);
    return b`
            <div class="section">
                <h4>Device Info</h4>
                <div class="info-row">
                    <span class="label">Name:</span>
                    <span class="value">${getDeviceName(node)}</span>
                </div>
                <div class="info-row">
                    <span class="label">Vendor:</span>
                    <span class="value">${node.vendorName ?? "Unknown"}</span>
                </div>
                <div class="info-row">
                    <span class="label">Product:</span>
                    <span class="value">${node.productName ?? "Unknown"}</span>
                </div>
                ${node.serialNumber ? b`
                          <div class="info-row">
                              <span class="label">Serial:</span>
                              <span class="value mono">${node.serialNumber}</span>
                          </div>
                      ` : A}
                <div class="info-row">
                    <span class="label">Network:</span>
                    <span class="value">${networkType.charAt(0).toUpperCase() + networkType.slice(1)}</span>
                </div>
                <div class="info-row">
                    <span class="label">Status:</span>
                    <span class="value ${node.available ? "status-online" : "status-offline"}"
                        >${node.available ? "Online" : "Offline"}</span
                    >
                </div>
            </div>

            ${networkType === "thread" ? b`
                      <md-divider></md-divider>
                      ${this._renderThreadInfo(node)}
                  ` : A}
            ${networkType === "wifi" ? b`
                      <md-divider></md-divider>
                      ${this._renderWiFiInfo(node)}
                  ` : A}
        `;
  }
  _renderUnknownDeviceInfo(deviceId) {
    const device = this.unknownDevices.get(deviceId);
    if (!device || device.kind !== "unknown") {
      return b` <p>Unknown device data not available</p> `;
    }
    const unknown = device;
    return b`
            <div class="section">
                <h4>Unknown Device</h4>
                <div class="info-row">
                    <span class="label">Type:</span>
                    <span class="value">${unknown.isRouter ? "Router (external)" : "End Device (external)"}</span>
                </div>
                <div class="info-row">
                    <span class="label">Extended Address:</span>
                    <span class="value mono">${unknown.extAddressHex}</span>
                </div>
                ${unknown.networkName !== void 0 ? b`
                          <div class="info-row">
                              <span class="label">Thread Network:</span>
                              <span class="value">${unknown.networkName}</span>
                          </div>
                      ` : A}
                ${unknown.extendedPanIdHex !== void 0 ? b`
                          <div class="info-row">
                              <span class="label">Extended PAN ID:</span>
                              <span class="value mono">${unknown.extendedPanIdHex}</span>
                          </div>
                      ` : A}
                ${unknown.bestRssi !== null ? b`
                          <div class="info-row">
                              <span class="label">Best RSSI:</span>
                              <span class="value">${unknown.bestRssi} dBm</span>
                          </div>
                      ` : A}
            </div>

            ${this._renderExternalDeviceNeighbors(deviceId)}

            <md-divider></md-divider>
            <div class="section">
                <p class="hint-text">
                    This device appears in Thread neighbor tables but is not commissioned to this fabric. It may be a
                    Thread Border Router whose Thread radio MAC differs from its MeshCoP border-agent ID (common with
                    Apple and Aqara), or a device from another Matter ecosystem.
                </p>
            </div>
        `;
  }
  /**
   * Neighbor list shared by external-device panels (unknown + BR). Uses the
   * same edge pairs as the graph so panel and graph agree on which links
   * survive filtering. Sorted by best RSSI/LQI signal, descending.
   */
  _renderExternalDeviceNeighbors(deviceId) {
    const connections = getNodeConnectionsFromPairs(deviceId, this.threadEdgePairs, this.nodes, {
      hideOfflineNodes: this.hideOfflineNodes,
      hideWeakSignalEdges: this.hideWeakSignalEdges,
      hideMediumSignalEdges: this.hideMediumSignalEdges,
      hideStrongSignalEdges: this.hideStrongSignalEdges
    });
    if (connections.length === 0) return A;
    return b`
            <md-divider></md-divider>
            <div class="section">
                <h4>Neighbors (${connections.length})</h4>
                <div class="neighbors-list">
                    ${connections.toSorted((a, b) => {
      const score = conn => {
        if (conn.rssi !== null && conn.rssi !== void 0) return conn.rssi;
        if (conn.lqi !== null && conn.lqi !== void 0) return conn.lqi;
        return -Infinity;
      };
      return score(b) - score(a);
    }).map(conn => {
      if (!conn.connectedNode) return A;
      return b`
                                <div
                                    class="neighbor-item clickable"
                                    role="button"
                                    tabindex="0"
                                    @click=${() => this._handleSelectNode(conn.connectedNodeId)}
                                    @keydown=${e => this._handleKeyDown(e, conn.connectedNodeId)}
                                >
                                    <ha-svg-icon
                                        .path=${this._getSignalIcon(conn.signalLevel)}
                                        style="--icon-primary-color: ${conn.signalColor}"
                                    ></ha-svg-icon>
                                    <div class="neighbor-info">
                                        <div class="neighbor-name">
                                            Node ${conn.connectedNodeId}
                                            <span class="node-id-hex"
                                                >${this._formatNodeIdHex(conn.connectedNodeId)}</span
                                            >: ${getDeviceName(conn.connectedNode)}
                                        </div>
                                        <div class="neighbor-signal">
                                            ${conn.rssi !== null ? b`RSSI: ${conn.rssi} dBm, ` : A}
                                            ${conn.lqi !== null ? b`LQI: ${conn.lqi}` : A}
                                        </div>
                                    </div>
                                </div>
                            `;
    })}
                </div>
            </div>
        `;
  }
  /**
   * Identity rows for a Border Router (network name, vendor, model, Thread version, ext address).
   * Caller controls the surrounding <div class="section"> + heading.
   */
  _renderBorderRouterIdentityRows(br, includeExtAddr) {
    return b`
            ${br.networkName ? b`
                      <div class="info-row">
                          <span class="label">Network name:</span>
                          <span class="value">${br.networkName}</span>
                      </div>
                  ` : A}
            ${br.vendorName ? b`
                      <div class="info-row">
                          <span class="label">Vendor:</span>
                          <span class="value">${br.vendorName}</span>
                      </div>
                  ` : A}
            ${br.modelName ? b`
                      <div class="info-row">
                          <span class="label">Model:</span>
                          <span class="value">${br.modelName}</span>
                      </div>
                  ` : A}
            ${br.threadVersion ? b`
                      <div class="info-row">
                          <span class="label">Thread version:</span>
                          <span class="value">${br.threadVersion}</span>
                      </div>
                  ` : A}
            ${includeExtAddr ? b`
                      <div class="info-row">
                          <span class="label">Extended Address:</span>
                          <span class="value mono">${br.extAddressHex}</span>
                      </div>
                  ` : A}
        `;
  }
  /**
   * Render the MeshCoP state bitmap as decoded fields (BBR role, connection mode, Thread
   * interface status, availability, ePSKc) plus the raw hex underneath. Reserved values are
   * rendered as numeric so a future spec extension stays visible.
   */
  _renderStateBitmap(hex) {
    if (hex === void 0) return A;
    const decoded = decodeMeshcopStateBitmap(hex);
    if (decoded === void 0) {
      return b`
                <div class="info-row">
                    <span class="label">State bitmap:</span>
                    <span class="value mono">${hex}</span>
                </div>
            `;
    }
    const stateParts = new Array();
    stateParts.push(decoded.bbr ? `BBR (${decoded.bbrFunction ?? "?"})` : "not BBR");
    if (decoded.threadRole !== void 0) {
      stateParts.push(`Thread ${decoded.threadRole}`);
    }
    if (decoded.threadInterfaceStatus !== void 0) {
      stateParts.push(decoded.threadInterfaceStatus);
    }
    return b`
            <div class="info-row">
                <span class="label">State:</span>
                <span class="value">${stateParts.join(", ")}</span>
            </div>
            <div class="info-row">
                <span class="label">Connection:</span>
                <span class="value">${decoded.connectionMode ?? `reserved (${decoded.connectionModeValue})`}</span>
            </div>
            <div class="info-row">
                <span class="label">Availability:</span>
                <span class="value">${decoded.availability ?? `reserved (${decoded.availabilityValue})`}</span>
            </div>
            <div class="info-row">
                <span class="label">ePSKc:</span>
                <span class="value">${decoded.epskcSupported ? "supported" : "not supported"}</span>
            </div>
            ${decoded.multiAilStateValue !== 0 ? b`
                      <div class="info-row">
                          <span class="label">Multi-AIL:</span>
                          <span class="value">
                              ${decoded.multiAilState ?? `reserved (${decoded.multiAilStateValue})`}
                          </span>
                      </div>
                  ` : A}
            <div class="info-row">
                <span class="label">State bitmap (raw):</span>
                <span class="value mono">${hex}</span>
            </div>
        `;
  }
  /**
   * Network-info rows for a Border Router (extended PAN ID, partition, timestamps, state, domain, agent ID).
   * Returns nothing if no fields are populated, so the caller can skip the surrounding section.
   */
  _renderBorderRouterNetworkRows(br) {
    const hasAny = br.extendedPanIdHex !== void 0 || br.partitionIdHex !== void 0 || br.activeTimestampHex !== void 0 || br.stateBitmapHex !== void 0 || br.domainName !== void 0 || br.borderAgentIdHex !== void 0;
    if (!hasAny) return A;
    return b`
            ${br.extendedPanIdHex ? b`
                      <div class="info-row">
                          <span class="label">Extended PAN ID:</span>
                          <span class="value mono">${br.extendedPanIdHex}</span>
                      </div>
                  ` : A}
            ${br.partitionIdHex ? b`
                      <div class="info-row">
                          <span class="label">Partition ID:</span>
                          <span class="value mono">${br.partitionIdHex}</span>
                      </div>
                  ` : A}
            ${br.activeTimestampHex ? b`
                      <div class="info-row">
                          <span class="label">Active timestamp:</span>
                          <span class="value mono">${br.activeTimestampHex}</span>
                      </div>
                  ` : A}
            ${this._renderStateBitmap(br.stateBitmapHex)}
            ${br.domainName ? b`
                      <div class="info-row">
                          <span class="label">Domain:</span>
                          <span class="value">${br.domainName}</span>
                      </div>
                  ` : A}
            ${br.borderAgentIdHex ? b`
                      <div class="info-row">
                          <span class="label">Border agent ID:</span>
                          <span class="value mono">${br.borderAgentIdHex}</span>
                      </div>
                  ` : A}
        `;
  }
  /**
   * Address rows for a Border Router (hostname, IPs, ports, sources).
   */
  _renderBorderRouterAddressRows(br) {
    const hasAny = br.hostname !== void 0 || br.addresses.length > 0 || br.meshcopPort !== void 0 || br.trelPort !== void 0 || br.sources.length > 0;
    if (!hasAny) return A;
    return b`
            ${br.hostname ? b`
                      <div class="info-row">
                          <span class="label">Hostname:</span>
                          <span class="value mono">${br.hostname}</span>
                      </div>
                  ` : A}
            ${br.addresses.map(addr => b`
                    <div class="info-row">
                        <span class="label">Address:</span>
                        <span class="value mono">${addr}</span>
                    </div>
                `)}
            ${br.meshcopPort !== void 0 ? b`
                      <div class="info-row">
                          <span class="label">meshcop port:</span>
                          <span class="value">${br.meshcopPort}</span>
                      </div>
                  ` : A}
            ${br.trelPort !== void 0 ? b`
                      <div class="info-row">
                          <span class="label">trel port:</span>
                          <span class="value">${br.trelPort}</span>
                      </div>
                  ` : A}
            ${br.sources.length > 0 ? b`
                      <div class="info-row">
                          <span class="label">Sources:</span>
                          <span class="value">${br.sources.join(", ")}</span>
                      </div>
                  ` : A}
        `;
  }
  _renderBorderRouterInfo(deviceId) {
    const device = this.unknownDevices.get(deviceId);
    if (!device || device.kind !== "br") {
      return b` <p>Border router data not available</p> `;
    }
    const br = device;
    const networkRows = this._renderBorderRouterNetworkRows(br);
    const addressRows = this._renderBorderRouterAddressRows(br);
    return b`
            <div class="section">
                <h4>Border Router</h4>
                ${this._renderBorderRouterIdentityRows(br, true)}
                ${br.bestRssi !== null ? b`
                          <div class="info-row">
                              <span class="label">Best RSSI:</span>
                              <span class="value">${br.bestRssi} dBm</span>
                          </div>
                      ` : A}
            </div>

            ${networkRows !== A ? b`
                      <md-divider></md-divider>
                      <div class="section">
                          <h4>Thread Network</h4>
                          ${networkRows}
                      </div>
                  ` : A}
            ${addressRows !== A ? b`
                      <md-divider></md-divider>
                      <div class="section">
                          <h4>Addresses</h4>
                          ${addressRows}
                      </div>
                  ` : A}
            ${this._renderExternalDeviceNeighbors(deviceId)}
        `;
  }
  /**
   * Determine if update connections button should be shown.
   */
  _canUpdateConnections() {
    if (this.selectedNodeId === null) return false;
    const isAccessPoint = typeof this.selectedNodeId === "string" && this.selectedNodeId.startsWith("ap_");
    if (isAccessPoint) return false;
    const isExternal = typeof this.selectedNodeId === "string" && (this.selectedNodeId.startsWith("unknown_") || this.selectedNodeId.startsWith("br_"));
    if (isExternal) {
      return this._getOnlineSeenByNodes().length > 0;
    }
    const node = this.nodes[this.selectedNodeId.toString()];
    if (!node) return false;
    const networkType = getNetworkType(node);
    if (networkType === "ethernet" || networkType === "unknown") return false;
    return true;
  }
  /**
   * Get the type of the currently selected node for dialog variant.
   */
  _getSelectedNodeType() {
    if (typeof this.selectedNodeId === "string" && (this.selectedNodeId.startsWith("unknown_") || this.selectedNodeId.startsWith("br_"))) {
      return "unknown";
    }
    const node = this.nodes[this.selectedNodeId.toString()];
    if (!node || node.available === false) {
      return "offline";
    }
    return "online";
  }
  /**
   * Get online neighbors for a Thread node.
   */
  _getOnlineNeighbors(nodeId) {
    const node = this.nodes[nodeId];
    if (!node) return [];
    const networkType = getNetworkType(node);
    if (networkType === "thread") {
      const connections = getNodeConnectionsFromPairs(nodeId, this.threadEdgePairs, this.nodes);
      return connections.filter(conn => {
        if (conn.isUnknown) return false;
        return conn.connectedNode?.available === true;
      }).map(conn => String(conn.connectedNodeId));
    }
    return [];
  }
  /**
   * Get online nodes that see an unknown device.
   */
  _getOnlineSeenByNodes() {
    if (typeof this.selectedNodeId !== "string" || !this.selectedNodeId.startsWith("unknown_") && !this.selectedNodeId.startsWith("br_")) {
      return [];
    }
    const device = this.unknownDevices.get(this.selectedNodeId);
    if (!device) return [];
    return device.seenBy.filter(nodeId => {
      const node = this.nodes[nodeId.toString()];
      return node?.available === true;
    });
  }
  /**
   * Get the name of the selected node for display in dialog.
   */
  _getSelectedNodeName() {
    if (typeof this.selectedNodeId === "string") {
      if (this.selectedNodeId.startsWith("br_")) {
        const device = this.unknownDevices.get(this.selectedNodeId);
        if (!device || device.kind !== "br") return "Border Router";
        const label = device.networkName ?? device.vendorName ?? "Border Router";
        return `${label} (${device.extAddressHex.slice(-8)})`;
      }
      if (this.selectedNodeId.startsWith("unknown_")) {
        const device = this.unknownDevices.get(this.selectedNodeId);
        if (!device || device.kind !== "unknown") return "External Device";
        const typeLabel = device.isRouter ? "External Router" : "External Device";
        return `${typeLabel} (${device.extAddressHex.slice(-8)})`;
      }
    }
    const node = this.nodes[this.selectedNodeId.toString()];
    return node ? getDeviceName(node) : "Unknown";
  }
  _handleUpdateConnections() {
    this._showUpdateDialog = true;
  }
  _handleDialogClose() {
    this._showUpdateDialog = false;
    this.dispatchEvent(new CustomEvent("connections-updated", {
      bubbles: true,
      composed: true
    }));
  }
  _renderWiFiAccessPointInfo(apId) {
    const ap = this.wifiAccessPoints.get(apId);
    if (!ap) {
      return b` <p>Access point data not available</p> `;
    }
    return b`
            <div class="section">
                <h4>WiFi Access Point</h4>
                <div class="info-row">
                    <span class="label">BSSID:</span>
                    <span class="value mono">${ap.bssid}</span>
                </div>
                <div class="info-row">
                    <span class="label">Connected devices:</span>
                    <span class="value">${ap.connectedNodes.length}</span>
                </div>
            </div>
            ${ap.connectedNodes.length > 0 ? b`
                      <md-divider></md-divider>
                      <div class="section">
                          <h4>Connected Nodes</h4>
                          <div class="connected-nodes-list">
                              ${ap.connectedNodes.toSorted((a, b) => {
      const nodeA = this.nodes[a.toString()];
      const nodeB = this.nodes[b.toString()];
      const rssiA = nodeA ? getWiFiDiagnostics(nodeA)?.rssi ?? -Infinity : -Infinity;
      const rssiB = nodeB ? getWiFiDiagnostics(nodeB)?.rssi ?? -Infinity : -Infinity;
      return rssiB - rssiA;
    }).map(nodeId => {
      const node = this.nodes[nodeId.toString()];
      if (!node) return A;
      const wifiDiag = getWiFiDiagnostics(node);
      const signalColor = getSignalColorFromRssi(wifiDiag.rssi);
      return b`
                                          <div
                                              class="connected-node-item clickable"
                                              role="button"
                                              tabindex="0"
                                              @click=${() => this._handleSelectNode(nodeId)}
                                              @keydown=${e => this._handleKeyDown(e, nodeId)}
                                          >
                                              <div class="node-name">
                                                  Node ${nodeId}
                                                  <span class="node-id-hex">${this._formatNodeIdHex(nodeId)}</span>:
                                                  ${getDeviceName(node)}
                                              </div>
                                              ${wifiDiag.rssi !== null ? b`<div class="node-signal" style="color: ${signalColor}">
                                                        ${wifiDiag.rssi} dBm
                                                    </div>` : A}
                                          </div>
                                      `;
    })}
                          </div>
                      </div>
                  ` : A}
            <md-divider></md-divider>
            <div class="section">
                <p class="hint-text">
                    This is a WiFi access point that Matter devices connect to. It is not a Matter device itself.
                </p>
            </div>
        `;
  }
  /**
   * Annotation shown on a commissioned Thread node that is also a discovered Border Router.
   * Mirrors the BR Identity/Network/Addresses sections, sans the redundant ext-address row.
   */
  _renderCommissionedNodeBorderRouterAnnotation(node) {
    const xaHex = getThreadExtendedAddressHex(node);
    if (!xaHex) return A;
    const br = this.borderRouters.get(xaHex);
    if (!br) return A;
    const networkRows = this._renderBorderRouterNetworkRows(br);
    const addressRows = this._renderBorderRouterAddressRows(br);
    return b`
            <md-divider></md-divider>
            <div class="section">
                <h4>Also a Border Router</h4>
                ${this._renderBorderRouterIdentityRows(br, false)}
                ${networkRows !== A ? b`
                          <div class="subsection-label">Thread Network</div>
                          ${networkRows}
                      ` : A}
                ${addressRows !== A ? b`
                          <div class="subsection-label">Addresses</div>
                          ${addressRows}
                      ` : A}
            </div>
        `;
  }
  render() {
    if (this.selectedNodeId === null) {
      return b`
                <div class="empty-state">
                    <p>Select a device to view details</p>
                </div>
            `;
    }
    const isUnknown = typeof this.selectedNodeId === "string" && this.selectedNodeId.startsWith("unknown_");
    if (isUnknown) {
      const onlineSeenByNodes = this._getOnlineSeenByNodes();
      return b`
                <div class="details-panel">
                    <div class="header">
                        <h3>External Device</h3>
                        <div class="header-actions">
                            ${onlineSeenByNodes.length > 0 ? b`
                                      <button
                                          class="action-button"
                                          @click=${this._handleUpdateConnections}
                                          aria-label="Update connection data"
                                          title="Update connection data"
                                      >
                                          <ha-svg-icon .path=${mdiRefresh}></ha-svg-icon>
                                      </button>
                                  ` : A}
                            <button class="close-button" @click=${this._handleClose} aria-label="Close details panel">
                                <ha-svg-icon .path=${mdiClose}></ha-svg-icon>
                            </button>
                        </div>
                    </div>
                    <div class="content">${this._renderUnknownDeviceInfo(this.selectedNodeId)}</div>
                </div>
                ${this._showUpdateDialog ? b`
                          <update-connections-dialog
                              .nodes=${this.nodes}
                              selectedNodeType="unknown"
                              .selectedNodeName=${this._getSelectedNodeName()}
                              .selectedNodeId=${this.selectedNodeId}
                              .onlineNeighborIds=${onlineSeenByNodes}
                              @dialog-closed=${this._handleDialogClose}
                          ></update-connections-dialog>
                      ` : A}
            `;
    }
    const borderRouterId = typeof this.selectedNodeId === "string" && this.selectedNodeId.startsWith("br_") ? this.selectedNodeId : null;
    if (borderRouterId !== null) {
      const onlineSeenByNodes = this._getOnlineSeenByNodes();
      return b`
                <div class="details-panel">
                    <div class="header">
                        <h3>Border Router</h3>
                        <div class="header-actions">
                            ${onlineSeenByNodes.length > 0 ? b`
                                      <button
                                          class="action-button"
                                          @click=${this._handleUpdateConnections}
                                          aria-label="Update connection data"
                                          title="Update connection data"
                                      >
                                          <ha-svg-icon .path=${mdiRefresh}></ha-svg-icon>
                                      </button>
                                  ` : A}
                            <button class="close-button" @click=${this._handleClose} aria-label="Close details panel">
                                <ha-svg-icon .path=${mdiClose}></ha-svg-icon>
                            </button>
                        </div>
                    </div>
                    <div class="content">${this._renderBorderRouterInfo(borderRouterId)}</div>
                </div>
                ${this._showUpdateDialog ? b`
                          <update-connections-dialog
                              .nodes=${this.nodes}
                              selectedNodeType="unknown"
                              .selectedNodeName=${this._getSelectedNodeName()}
                              .selectedNodeId=${this.selectedNodeId}
                              .onlineNeighborIds=${onlineSeenByNodes}
                              @dialog-closed=${this._handleDialogClose}
                          ></update-connections-dialog>
                      ` : A}
            `;
    }
    const isAccessPoint = typeof this.selectedNodeId === "string" && this.selectedNodeId.startsWith("ap_");
    if (isAccessPoint) {
      return b`
                <div class="details-panel">
                    <div class="header">
                        <h3>Access Point</h3>
                        <button class="close-button" @click=${this._handleClose} aria-label="Close details panel">
                            <ha-svg-icon .path=${mdiClose}></ha-svg-icon>
                        </button>
                    </div>
                    <div class="content">${this._renderWiFiAccessPointInfo(this.selectedNodeId)}</div>
                </div>
            `;
    }
    const node = this.nodes[this.selectedNodeId.toString()];
    if (!node) {
      return b`
                <div class="empty-state">
                    <p>Device not found</p>
                </div>
            `;
    }
    const canUpdate = this._canUpdateConnections();
    const nodeType = this._getSelectedNodeType();
    const onlineNeighbors = this._getOnlineNeighbors(String(this.selectedNodeId));
    return b`
            <div class="details-panel">
                <div class="header">
                    <h3>
                        Node ${this.selectedNodeId}
                        <span class="node-id-hex">${this._formatNodeIdHex(this.selectedNodeId)}</span>
                    </h3>
                    <div class="header-actions">
                        ${canUpdate ? b`
                                  <button
                                      class="action-button"
                                      @click=${this._handleUpdateConnections}
                                      aria-label="Update connection data"
                                      title="Update connection data"
                                  >
                                      <ha-svg-icon .path=${mdiRefresh}></ha-svg-icon>
                                  </button>
                              ` : A}
                        <button class="close-button" @click=${this._handleClose} aria-label="Close details panel">
                            <ha-svg-icon .path=${mdiClose}></ha-svg-icon>
                        </button>
                    </div>
                </div>
                <div class="content">
                    ${this._renderNodeInfo(node)}${this._renderCommissionedNodeBorderRouterAnnotation(node)}
                </div>
                <div class="footer">
                    <a href="#node/${this.selectedNodeId}" class="view-link">View node details</a>
                </div>
            </div>
            ${this._showUpdateDialog ? b`
                      <update-connections-dialog
                          .nodes=${this.nodes}
                          .selectedNodeType=${nodeType}
                          .selectedNodeName=${this._getSelectedNodeName()}
                          .selectedNodeId=${this.selectedNodeId}
                          .onlineNeighborIds=${onlineNeighbors}
                          @dialog-closed=${this._handleDialogClose}
                      ></update-connections-dialog>
                  ` : A}
        `;
  }
};
NetworkDetails.styles = [reducedMotionStyles, i$7`
            :host {
                display: block;
                height: 100%;
            }

            .empty-state {
                display: flex;
                align-items: center;
                justify-content: center;
                height: 100%;
                color: var(--md-sys-color-on-surface-variant, #666);
                text-align: center;
                padding: 24px;
            }

            .details-panel {
                display: flex;
                flex-direction: column;
                height: 100%;
                background-color: var(--md-sys-color-surface, #fff);
                border-radius: 8px;
                border: 1px solid var(--md-sys-color-outline-variant, #ccc);
                overflow: hidden;
            }

            .header {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: 12px 16px;
                background-color: var(--md-sys-color-surface-container, #f5f5f5);
                border-bottom: 1px solid var(--md-sys-color-outline-variant, #ccc);
            }

            .header h3 {
                margin: 0;
                font-size: 1rem;
                font-weight: 500;
                color: var(--md-sys-color-on-surface, #333);
            }

            .node-id-hex {
                font-size: 0.75em;
                font-weight: 400;
                color: var(--md-sys-color-on-surface-variant, #666);
                font-family: var(--monospace-font, monospace);
            }

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

            .action-button {
                background: none;
                border: none;
                padding: 4px;
                cursor: pointer;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .action-button:hover {
                background-color: var(--md-sys-color-surface-container-high, #e8e8e8);
            }

            .action-button ha-svg-icon {
                --icon-primary-color: var(--md-sys-color-on-surface-variant, #666);
            }

            .close-button {
                background: none;
                border: none;
                padding: 4px;
                cursor: pointer;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .close-button:hover {
                background-color: var(--md-sys-color-surface-container-high, #e8e8e8);
            }

            .close-button ha-svg-icon {
                --icon-primary-color: var(--md-sys-color-on-surface-variant, #666);
            }

            .content {
                flex: 1;
                overflow-y: auto;
                padding: 0;
            }

            .section {
                padding: 16px;
            }

            .section h4 {
                margin: 0 0 12px 0;
                font-size: 0.875rem;
                font-weight: 500;
                color: var(--md-sys-color-primary, #6200ee);
                text-transform: uppercase;
                letter-spacing: 0.5px;
            }

            .subsection-label {
                margin: 12px 0 4px 0;
                font-size: 0.75rem;
                font-weight: 500;
                color: var(--md-sys-color-on-surface-variant, #666);
                text-transform: uppercase;
                letter-spacing: 0.4px;
            }

            .info-row {
                display: flex;
                justify-content: space-between;
                padding: 6px 0;
                font-size: 0.875rem;
            }

            .label {
                color: var(--md-sys-color-on-surface-variant, #666);
            }

            .value {
                color: var(--md-sys-color-on-surface, #333);
                font-weight: 500;
                text-align: right;
                word-break: break-all;
                max-width: 60%;
            }

            .value.mono {
                font-family: var(--monospace-font, monospace);
                font-size: 0.8rem;
            }

            .status-online {
                color: var(--signal-color-strong, #4caf50);
            }

            .status-offline {
                color: var(--danger-color, #f44336);
            }

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

            .neighbor-item {
                display: flex;
                align-items: flex-start;
                gap: 12px;
                padding: 8px;
                background-color: var(--md-sys-color-surface-container, #f5f5f5);
                border-radius: 4px;
            }

            .neighbor-item.clickable {
                cursor: pointer;
                transition: background-color 0.15s;
            }

            .neighbor-item.clickable:hover {
                background-color: var(--md-sys-color-surface-container-high, #e8e8e8);
            }

            .neighbor-item ha-svg-icon {
                flex-shrink: 0;
                margin-top: 2px;
            }

            .neighbor-info {
                flex: 1;
                min-width: 0;
            }

            .neighbor-name {
                font-size: 0.875rem;
                color: var(--md-sys-color-on-surface, #333);
                word-break: break-word;
            }

            .neighbor-signal {
                font-size: 0.75rem;
                color: var(--md-sys-color-on-surface-variant, #666);
                margin-top: 2px;
            }

            .direction-hint {
                font-style: italic;
                opacity: 0.8;
            }

            .direction-hint.reverse-only {
                font-style: normal;
                font-weight: 500;
                opacity: 1;
                color: var(--md-sys-color-error, #b3261e);
                cursor: help;
            }

            .route-info {
                color: var(--md-sys-color-tertiary, #7d5260);
                font-size: 0.85em;
            }

            .footer {
                padding: 12px 16px;
                border-top: 1px solid var(--md-sys-color-outline-variant, #ccc);
                text-align: center;
            }

            .view-link {
                color: var(--md-sys-color-primary, #6200ee);
                text-decoration: none;
                font-size: 0.875rem;
                font-weight: 500;
            }

            .view-link:hover {
                text-decoration: underline;
            }

            md-divider {
                --md-divider-color: var(--md-sys-color-outline-variant, #ccc);
            }

            .hint-text {
                font-size: 0.8rem;
                color: var(--md-sys-color-on-surface-variant, #666);
                line-height: 1.4;
                margin: 0;
            }

            .connected-nodes-list {
                display: flex;
                flex-direction: column;
                gap: 8px;
            }

            .connected-node-item {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: 8px;
                background-color: var(--md-sys-color-surface-container, #f5f5f5);
                border-radius: 4px;
            }

            .connected-node-item.clickable {
                cursor: pointer;
                transition: background-color 0.15s;
            }

            .connected-node-item.clickable:hover {
                background-color: var(--md-sys-color-surface-container-high, #e8e8e8);
            }

            .connected-node-item .node-name {
                font-size: 0.875rem;
                color: var(--md-sys-color-on-surface, #333);
                word-break: break-word;
            }

            .connected-node-item .node-signal {
                font-size: 0.8rem;
                font-weight: 500;
                flex-shrink: 0;
                margin-left: 8px;
            }
        `];
__decorateClass$8([n$5()], NetworkDetails.prototype, "selectedNodeId", 2);
__decorateClass$8([n$5({
  type: Boolean
})], NetworkDetails.prototype, "hideOfflineNodes", 2);
__decorateClass$8([n$5({
  type: Boolean
})], NetworkDetails.prototype, "hideWeakSignalEdges", 2);
__decorateClass$8([n$5({
  type: Boolean
})], NetworkDetails.prototype, "hideMediumSignalEdges", 2);
__decorateClass$8([n$5({
  type: Boolean
})], NetworkDetails.prototype, "hideStrongSignalEdges", 2);
__decorateClass$8([n$5({
  type: Object
})], NetworkDetails.prototype, "nodes", 2);
__decorateClass$8([n$5({
  type: Object
})], NetworkDetails.prototype, "unknownDevices", 2);
__decorateClass$8([n$5({
  attribute: false
})], NetworkDetails.prototype, "borderRouters", 2);
__decorateClass$8([n$5({
  type: Object
})], NetworkDetails.prototype, "wifiAccessPoints", 2);
__decorateClass$8([n$5({
  type: Object
})], NetworkDetails.prototype, "threadEdgePairs", 2);
__decorateClass$8([c$5({
  context: clientContext
})], NetworkDetails.prototype, "client", 2);
__decorateClass$8([r$3()], NetworkDetails.prototype, "_showUpdateDialog", 2);
NetworkDetails = __decorateClass$8([t$1("network-details")], NetworkDetails);

/**
 * vis-network
 * https://visjs.github.io/vis-network/
 *
 * A dynamic, browser-based visualization library.
 *
 * @version 10.1.0
 * @date    2026-05-15T16:46:11.466Z
 *
 * @copyright (c) 2011-2017 Almende B.V, http://almende.com
 * @copyright (c) 2017-2019 visjs contributors, https://github.com/visjs
 *
 * @license
 * vis.js is dual licensed under both
 *
 *   1. The Apache 2.0 License
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *   and
 *
 *   2. The MIT License
 *      http://opensource.org/licenses/MIT
 *
 * vis.js may be distributed under either license.
 */function styleInject(css,ref){if(ref===void 0)ref={};var insertAt=ref.insertAt;if(!css||typeof document==='undefined'){return;}var head=document.head||document.getElementsByTagName('head')[0];var style=document.createElement('style');style.type='text/css';if(insertAt==='top'){if(head.firstChild){head.insertBefore(style,head.firstChild);}else {head.appendChild(style);}}else {head.appendChild(style);}if(style.styleSheet){style.styleSheet.cssText=css;}else {style.appendChild(document.createTextNode(css));}}var css_248z$6="div.vis-network div.vis-manipulation {\n  box-sizing: content-box;\n\n  border-width: 0;\n  border-bottom: 1px;\n  border-style: solid;\n  border-color: #d6d9d8;\n  background: #ffffff; /* Old browsers */\n  background: -moz-linear-gradient(\n    top,\n    #ffffff 0%,\n    #fcfcfc 48%,\n    #fafafa 50%,\n    #fcfcfc 100%\n  ); /* FF3.6+ */\n  background: -webkit-gradient(\n    linear,\n    left top,\n    left bottom,\n    color-stop(0%, #ffffff),\n    color-stop(48%, #fcfcfc),\n    color-stop(50%, #fafafa),\n    color-stop(100%, #fcfcfc)\n  ); /* Chrome,Safari4+ */\n  background: -webkit-linear-gradient(\n    top,\n    #ffffff 0%,\n    #fcfcfc 48%,\n    #fafafa 50%,\n    #fcfcfc 100%\n  ); /* Chrome10+,Safari5.1+ */\n  background: -o-linear-gradient(\n    top,\n    #ffffff 0%,\n    #fcfcfc 48%,\n    #fafafa 50%,\n    #fcfcfc 100%\n  ); /* Opera 11.10+ */\n  background: -ms-linear-gradient(\n    top,\n    #ffffff 0%,\n    #fcfcfc 48%,\n    #fafafa 50%,\n    #fcfcfc 100%\n  ); /* IE10+ */\n  background: linear-gradient(\n    to bottom,\n    #ffffff 0%,\n    #fcfcfc 48%,\n    #fafafa 50%,\n    #fcfcfc 100%\n  ); /* W3C */\n  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#fcfcfc',GradientType=0 ); /* IE6-9 */\n\n  padding-top: 4px;\n  position: absolute;\n  left: 0;\n  top: 0;\n  width: 100%;\n  height: 28px;\n}\n\ndiv.vis-network div.vis-edit-mode,\ndiv.vis-network button.vis-edit-mode {\n  position: absolute;\n  left: 0;\n  top: 5px;\n  height: 30px;\n}\n\n/* FIXME: shouldn't the vis-close button be a child of the vis-manipulation div? */\n\ndiv.vis-network button.vis-close {\n  position: absolute;\n  right: 0;\n  top: 0;\n  width: 30px;\n  height: 30px;\n\n  background-color: transparent;\n  background-position: 20px 3px;\n  background-repeat: no-repeat;\n  background-image: url('data:image/png;base64, ');\n  border: none;\n  cursor: pointer;\n  -webkit-touch-callout: none;\n  -webkit-user-select: none;\n  -khtml-user-select: none;\n  -moz-user-select: none;\n  -ms-user-select: none;\n  user-select: none;\n}\n\ndiv.vis-network button.vis-close:hover {\n  opacity: 0.6;\n}\n\ndiv.vis-network div.vis-manipulation button.vis-button,\ndiv.vis-network div.vis-edit-mode button.vis-button {\n  float: left;\n  font-family: verdana;\n  font-size: 12px;\n  border: none;\n  box-sizing: content-box;\n  -moz-border-radius: 15px;\n  border-radius: 15px;\n  background-color: transparent;\n  background-position: 0px 0px;\n  background-repeat: no-repeat;\n  height: 24px;\n  margin-left: 10px;\n  cursor: pointer;\n  padding: 0px 8px 0px 8px;\n  -webkit-touch-callout: none;\n  -webkit-user-select: none;\n  -khtml-user-select: none;\n  -moz-user-select: none;\n  -ms-user-select: none;\n  user-select: none;\n}\n\ndiv.vis-network div.vis-manipulation button.vis-button:hover {\n  box-shadow: 1px 1px 8px rgba(0, 0, 0, 0.2);\n}\n\ndiv.vis-network div.vis-manipulation button.vis-button:active {\n  box-shadow: 1px 1px 8px rgba(0, 0, 0, 0.5);\n}\n\ndiv.vis-network div.vis-manipulation button.vis-button.vis-back {\n  background-image: url('data:image/png;base64, ');\n}\n\ndiv.vis-network div.vis-manipulation div.vis-none:hover {\n  box-shadow: 1px 1px 8px rgba(0, 0, 0, 0);\n  cursor: default;\n}\ndiv.vis-network div.vis-manipulation div.vis-none:active {\n  box-shadow: 1px 1px 8px rgba(0, 0, 0, 0);\n}\ndiv.vis-network div.vis-manipulation div.vis-none {\n  padding: 0px;\n  line-height: 23px;\n}\ndiv.vis-network div.vis-manipulation div.notification {\n  margin: 2px;\n  font-weight: bold;\n}\n\ndiv.vis-network div.vis-manipulation button.vis-button.vis-add {\n  background-image: url('data:image/png;base64, ');\n}\n\ndiv.vis-network div.vis-manipulation button.vis-button.vis-edit,\ndiv.vis-network div.vis-edit-mode button.vis-button.vis-edit {\n  background-image: url('data:image/png;base64, ');\n}\n\ndiv.vis-network div.vis-edit-mode button.vis-button.vis-edit.vis-edit-mode {\n  background-color: #fcfcfc;\n  border: 1px solid #cccccc;\n}\n\ndiv.vis-network div.vis-manipulation button.vis-button.vis-connect {\n  background-image: url('data:image/png;base64, ');\n}\n\ndiv.vis-network div.vis-manipulation button.vis-button.vis-delete {\n  background-image: url('data:image/png;base64, ');\n}\n/* top right bottom left */\ndiv.vis-network div.vis-manipulation div.vis-label,\ndiv.vis-network div.vis-edit-mode div.vis-label {\n  margin: 0 0 0 23px;\n  line-height: 25px;\n}\ndiv.vis-network div.vis-manipulation div.vis-separator-line {\n  float: left;\n  display: inline-block;\n  width: 1px;\n  height: 21px;\n  background-color: #bdbdbd;\n  margin: 0px 7px 0 15px; /*top right bottom left*/\n}\n\n/* TODO: is this redundant?\ndiv.network-navigation_wrapper {\n  position: absolute;\n  left: 0;\n  top: 0;\n  width: 100%;\n  height: 100%;\n}\n*/\n";styleInject(css_248z$6);var css_248z$5="div.vis-network div.vis-navigation div.vis-button {\n  width: 34px;\n  height: 34px;\n  -moz-border-radius: 17px;\n  border-radius: 17px;\n  position: absolute;\n  display: inline-block;\n  background-position: 2px 2px;\n  background-repeat: no-repeat;\n  cursor: pointer;\n  -webkit-touch-callout: none;\n  -webkit-user-select: none;\n  -khtml-user-select: none;\n  -moz-user-select: none;\n  -ms-user-select: none;\n  user-select: none;\n}\n\ndiv.vis-network div.vis-navigation div.vis-button:hover {\n  box-shadow: 0 0 3px 3px rgba(56, 207, 21, 0.3);\n}\n\ndiv.vis-network div.vis-navigation div.vis-button:active {\n  box-shadow: 0 0 1px 3px rgba(56, 207, 21, 0.95);\n}\n\ndiv.vis-network div.vis-navigation div.vis-button.vis-up {\n  background-image: url('data:image/png;base64, ');\n  bottom: 50px;\n  left: 55px;\n}\ndiv.vis-network div.vis-navigation div.vis-button.vis-down {\n  background-image: url('data:image/png;base64, ');\n  bottom: 10px;\n  left: 55px;\n}\ndiv.vis-network div.vis-navigation div.vis-button.vis-left {\n  background-image: url('data:image/png;base64, ');\n  bottom: 10px;\n  left: 15px;\n}\ndiv.vis-network div.vis-navigation div.vis-button.vis-right {\n  background-image: url('data:image/png;base64, ');\n  bottom: 10px;\n  left: 95px;\n}\ndiv.vis-network div.vis-navigation div.vis-button.vis-zoomIn {\n  background-image: url('data:image/png;base64, ');\n  bottom: 10px;\n  right: 15px;\n}\ndiv.vis-network div.vis-navigation div.vis-button.vis-zoomOut {\n  background-image: url('data:image/png;base64, ');\n  bottom: 10px;\n  right: 55px;\n}\ndiv.vis-network div.vis-navigation div.vis-button.vis-zoomExtends {\n  background-image: url('data:image/png;base64, ');\n  bottom: 50px;\n  right: 15px;\n}\n";styleInject(css_248z$5);var css_248z$4=".vis-overlay {\n  position: absolute;\n  top: 0px;\n  right: 0px;\n  bottom: 0px;\n  left: 0px;\n\n  /* Must be displayed above for example selected Timeline items */\n  z-index: 10;\n}\n\n.vis-active {\n  box-shadow: 0 0 10px #86d5f8;\n}\n";styleInject(css_248z$4);var css_248z$3="/* override some bootstrap styles screwing up the timelines css */\n\n.vis [class*=\"span\"] {\n  min-height: 0;\n  width: auto;\n}\n";styleInject(css_248z$3);var css_248z$2="div.vis-color-picker {\n  position: absolute;\n  top: 0px;\n  left: 30px;\n  margin-top: -140px;\n  margin-left: 30px;\n  width: 310px;\n  height: 444px;\n  z-index: 1;\n  padding: 10px;\n  border-radius: 15px;\n  background-color: #ffffff;\n  display: none;\n  box-shadow: rgba(0, 0, 0, 0.5) 0px 0px 10px 0px;\n}\n\ndiv.vis-color-picker div.vis-arrow {\n  position: absolute;\n  top: 147px;\n  left: 5px;\n}\n\ndiv.vis-color-picker div.vis-arrow::after,\ndiv.vis-color-picker div.vis-arrow::before {\n  right: 100%;\n  top: 50%;\n  border: solid transparent;\n  content: \" \";\n  height: 0;\n  width: 0;\n  position: absolute;\n  pointer-events: none;\n}\n\ndiv.vis-color-picker div.vis-arrow:after {\n  border-color: rgba(255, 255, 255, 0);\n  border-right-color: #ffffff;\n  border-width: 30px;\n  margin-top: -30px;\n}\n\ndiv.vis-color-picker div.vis-color {\n  position: absolute;\n  width: 289px;\n  height: 289px;\n  cursor: pointer;\n}\n\ndiv.vis-color-picker div.vis-brightness {\n  position: absolute;\n  top: 313px;\n}\n\ndiv.vis-color-picker div.vis-opacity {\n  position: absolute;\n  top: 350px;\n}\n\ndiv.vis-color-picker div.vis-selector {\n  position: absolute;\n  top: 137px;\n  left: 137px;\n  width: 15px;\n  height: 15px;\n  border-radius: 15px;\n  border: 1px solid #ffffff;\n  background: #4c4c4c; /* Old browsers */\n  background: -moz-linear-gradient(\n    top,\n    #4c4c4c 0%,\n    #595959 12%,\n    #666666 25%,\n    #474747 39%,\n    #2c2c2c 50%,\n    #000000 51%,\n    #111111 60%,\n    #2b2b2b 76%,\n    #1c1c1c 91%,\n    #131313 100%\n  ); /* FF3.6+ */\n  background: -webkit-gradient(\n    linear,\n    left top,\n    left bottom,\n    color-stop(0%, #4c4c4c),\n    color-stop(12%, #595959),\n    color-stop(25%, #666666),\n    color-stop(39%, #474747),\n    color-stop(50%, #2c2c2c),\n    color-stop(51%, #000000),\n    color-stop(60%, #111111),\n    color-stop(76%, #2b2b2b),\n    color-stop(91%, #1c1c1c),\n    color-stop(100%, #131313)\n  ); /* Chrome,Safari4+ */\n  background: -webkit-linear-gradient(\n    top,\n    #4c4c4c 0%,\n    #595959 12%,\n    #666666 25%,\n    #474747 39%,\n    #2c2c2c 50%,\n    #000000 51%,\n    #111111 60%,\n    #2b2b2b 76%,\n    #1c1c1c 91%,\n    #131313 100%\n  ); /* Chrome10+,Safari5.1+ */\n  background: -o-linear-gradient(\n    top,\n    #4c4c4c 0%,\n    #595959 12%,\n    #666666 25%,\n    #474747 39%,\n    #2c2c2c 50%,\n    #000000 51%,\n    #111111 60%,\n    #2b2b2b 76%,\n    #1c1c1c 91%,\n    #131313 100%\n  ); /* Opera 11.10+ */\n  background: -ms-linear-gradient(\n    top,\n    #4c4c4c 0%,\n    #595959 12%,\n    #666666 25%,\n    #474747 39%,\n    #2c2c2c 50%,\n    #000000 51%,\n    #111111 60%,\n    #2b2b2b 76%,\n    #1c1c1c 91%,\n    #131313 100%\n  ); /* IE10+ */\n  background: linear-gradient(\n    to bottom,\n    #4c4c4c 0%,\n    #595959 12%,\n    #666666 25%,\n    #474747 39%,\n    #2c2c2c 50%,\n    #000000 51%,\n    #111111 60%,\n    #2b2b2b 76%,\n    #1c1c1c 91%,\n    #131313 100%\n  ); /* W3C */\n  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#4c4c4c', endColorstr='#131313',GradientType=0 ); /* IE6-9 */\n}\n\ndiv.vis-color-picker div.vis-new-color {\n  position: absolute;\n  width: 140px;\n  height: 20px;\n  border: 1px solid rgba(0, 0, 0, 0.1);\n  border-radius: 5px;\n  top: 380px;\n  left: 159px;\n  text-align: right;\n  padding-right: 2px;\n  font-size: 10px;\n  color: rgba(0, 0, 0, 0.4);\n  vertical-align: middle;\n  line-height: 20px;\n}\n\ndiv.vis-color-picker div.vis-initial-color {\n  position: absolute;\n  width: 140px;\n  height: 20px;\n  border: 1px solid rgba(0, 0, 0, 0.1);\n  border-radius: 5px;\n  top: 380px;\n  left: 10px;\n  text-align: left;\n  padding-left: 2px;\n  font-size: 10px;\n  color: rgba(0, 0, 0, 0.4);\n  vertical-align: middle;\n  line-height: 20px;\n}\n\ndiv.vis-color-picker div.vis-label {\n  position: absolute;\n  width: 300px;\n  left: 10px;\n}\n\ndiv.vis-color-picker div.vis-label.vis-brightness {\n  top: 300px;\n}\n\ndiv.vis-color-picker div.vis-label.vis-opacity {\n  top: 338px;\n}\n\ndiv.vis-color-picker div.vis-button {\n  position: absolute;\n  width: 68px;\n  height: 25px;\n  border-radius: 10px;\n  vertical-align: middle;\n  text-align: center;\n  line-height: 25px;\n  top: 410px;\n  border: 2px solid #d9d9d9;\n  background-color: #f7f7f7;\n  cursor: pointer;\n}\n\ndiv.vis-color-picker div.vis-button.vis-cancel {\n  /*border:2px solid #ff4e33;*/\n  /*background-color: #ff7761;*/\n  left: 5px;\n}\ndiv.vis-color-picker div.vis-button.vis-load {\n  /*border:2px solid #a153e6;*/\n  /*background-color: #cb8dff;*/\n  left: 82px;\n}\ndiv.vis-color-picker div.vis-button.vis-apply {\n  /*border:2px solid #4588e6;*/\n  /*background-color: #82b6ff;*/\n  left: 159px;\n}\ndiv.vis-color-picker div.vis-button.vis-save {\n  /*border:2px solid #45e655;*/\n  /*background-color: #6dff7c;*/\n  left: 236px;\n}\n\ndiv.vis-color-picker input.vis-range {\n  width: 290px;\n  height: 20px;\n}\n\n/* TODO: is this redundant?\ndiv.vis-color-picker input.vis-range-brightness {\n  width: 289px !important;\n}\n\n\ndiv.vis-color-picker input.vis-saturation-range {\n  width: 289px !important;\n}*/\n";styleInject(css_248z$2);var css_248z$1="div.vis-configuration {\n  position: relative;\n  display: block;\n  float: left;\n  font-size: 12px;\n}\n\ndiv.vis-configuration-wrapper {\n  display: block;\n  width: 700px;\n}\n\ndiv.vis-configuration-wrapper::after {\n  clear: both;\n  content: \"\";\n  display: block;\n}\n\ndiv.vis-configuration.vis-config-option-container {\n  display: block;\n  width: 495px;\n  background-color: #ffffff;\n  border: 2px solid #f7f8fa;\n  border-radius: 4px;\n  margin-top: 20px;\n  left: 10px;\n  padding-left: 5px;\n}\n\ndiv.vis-configuration.vis-config-button {\n  display: block;\n  width: 495px;\n  height: 25px;\n  vertical-align: middle;\n  line-height: 25px;\n  background-color: #f7f8fa;\n  border: 2px solid #ceced0;\n  border-radius: 4px;\n  margin-top: 20px;\n  left: 10px;\n  padding-left: 5px;\n  cursor: pointer;\n  margin-bottom: 30px;\n}\n\ndiv.vis-configuration.vis-config-button.hover {\n  background-color: #4588e6;\n  border: 2px solid #214373;\n  color: #ffffff;\n}\n\ndiv.vis-configuration.vis-config-item {\n  display: block;\n  float: left;\n  width: 495px;\n  height: 25px;\n  vertical-align: middle;\n  line-height: 25px;\n}\n\ndiv.vis-configuration.vis-config-item.vis-config-s2 {\n  left: 10px;\n  background-color: #f7f8fa;\n  padding-left: 5px;\n  border-radius: 3px;\n}\ndiv.vis-configuration.vis-config-item.vis-config-s3 {\n  left: 20px;\n  background-color: #e4e9f0;\n  padding-left: 5px;\n  border-radius: 3px;\n}\ndiv.vis-configuration.vis-config-item.vis-config-s4 {\n  left: 30px;\n  background-color: #cfd8e6;\n  padding-left: 5px;\n  border-radius: 3px;\n}\n\ndiv.vis-configuration.vis-config-header {\n  font-size: 18px;\n  font-weight: bold;\n}\n\ndiv.vis-configuration.vis-config-label {\n  width: 120px;\n  height: 25px;\n  line-height: 25px;\n}\n\ndiv.vis-configuration.vis-config-label.vis-config-s3 {\n  width: 110px;\n}\ndiv.vis-configuration.vis-config-label.vis-config-s4 {\n  width: 100px;\n}\n\ndiv.vis-configuration.vis-config-colorBlock {\n  top: 1px;\n  width: 30px;\n  height: 19px;\n  border: 1px solid #444444;\n  border-radius: 2px;\n  padding: 0px;\n  margin: 0px;\n  cursor: pointer;\n}\n\ninput.vis-configuration.vis-config-checkbox {\n  left: -5px;\n}\n\ninput.vis-configuration.vis-config-rangeinput {\n  position: relative;\n  top: -5px;\n  width: 60px;\n  /*height:13px;*/\n  padding: 1px;\n  margin: 0;\n  pointer-events: none;\n}\n\ninput.vis-configuration.vis-config-range {\n  /*removes default webkit styles*/\n  -webkit-appearance: none;\n\n  /*fix for FF unable to apply focus style bug */\n  border: 0px solid white;\n  background-color: rgba(0, 0, 0, 0);\n\n  /*required for proper track sizing in FF*/\n  width: 300px;\n  height: 20px;\n}\ninput.vis-configuration.vis-config-range::-webkit-slider-runnable-track {\n  width: 300px;\n  height: 5px;\n  background: #dedede; /* Old browsers */\n  background: -moz-linear-gradient(top, #dedede 0%, #c8c8c8 99%); /* FF3.6+ */\n  background: -webkit-gradient(\n    linear,\n    left top,\n    left bottom,\n    color-stop(0%, #dedede),\n    color-stop(99%, #c8c8c8)\n  ); /* Chrome,Safari4+ */\n  background: -webkit-linear-gradient(\n    top,\n    #dedede 0%,\n    #c8c8c8 99%\n  ); /* Chrome10+,Safari5.1+ */\n  background: -o-linear-gradient(\n    top,\n    #dedede 0%,\n    #c8c8c8 99%\n  ); /* Opera 11.10+ */\n  background: -ms-linear-gradient(top, #dedede 0%, #c8c8c8 99%); /* IE10+ */\n  background: linear-gradient(to bottom, #dedede 0%, #c8c8c8 99%); /* W3C */\n  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#dedede', endColorstr='#c8c8c8',GradientType=0 ); /* IE6-9 */\n\n  border: 1px solid #999999;\n  box-shadow: #aaaaaa 0px 0px 3px 0px;\n  border-radius: 3px;\n}\ninput.vis-configuration.vis-config-range::-webkit-slider-thumb {\n  -webkit-appearance: none;\n  border: 1px solid #14334b;\n  height: 17px;\n  width: 17px;\n  border-radius: 50%;\n  background: #3876c2; /* Old browsers */\n  background: -moz-linear-gradient(top, #3876c2 0%, #385380 100%); /* FF3.6+ */\n  background: -webkit-gradient(\n    linear,\n    left top,\n    left bottom,\n    color-stop(0%, #3876c2),\n    color-stop(100%, #385380)\n  ); /* Chrome,Safari4+ */\n  background: -webkit-linear-gradient(\n    top,\n    #3876c2 0%,\n    #385380 100%\n  ); /* Chrome10+,Safari5.1+ */\n  background: -o-linear-gradient(\n    top,\n    #3876c2 0%,\n    #385380 100%\n  ); /* Opera 11.10+ */\n  background: -ms-linear-gradient(top, #3876c2 0%, #385380 100%); /* IE10+ */\n  background: linear-gradient(to bottom, #3876c2 0%, #385380 100%); /* W3C */\n  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#3876c2', endColorstr='#385380',GradientType=0 ); /* IE6-9 */\n  box-shadow: #111927 0px 0px 1px 0px;\n  margin-top: -7px;\n}\ninput.vis-configuration.vis-config-range:focus {\n  outline: none;\n}\ninput.vis-configuration.vis-config-range:focus::-webkit-slider-runnable-track {\n  background: #9d9d9d; /* Old browsers */\n  background: -moz-linear-gradient(top, #9d9d9d 0%, #c8c8c8 99%); /* FF3.6+ */\n  background: -webkit-gradient(\n    linear,\n    left top,\n    left bottom,\n    color-stop(0%, #9d9d9d),\n    color-stop(99%, #c8c8c8)\n  ); /* Chrome,Safari4+ */\n  background: -webkit-linear-gradient(\n    top,\n    #9d9d9d 0%,\n    #c8c8c8 99%\n  ); /* Chrome10+,Safari5.1+ */\n  background: -o-linear-gradient(\n    top,\n    #9d9d9d 0%,\n    #c8c8c8 99%\n  ); /* Opera 11.10+ */\n  background: -ms-linear-gradient(top, #9d9d9d 0%, #c8c8c8 99%); /* IE10+ */\n  background: linear-gradient(to bottom, #9d9d9d 0%, #c8c8c8 99%); /* W3C */\n  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#9d9d9d', endColorstr='#c8c8c8',GradientType=0 ); /* IE6-9 */\n}\n\ninput.vis-configuration.vis-config-range::-moz-range-track {\n  width: 300px;\n  height: 10px;\n  background: #dedede; /* Old browsers */\n  background: -moz-linear-gradient(top, #dedede 0%, #c8c8c8 99%); /* FF3.6+ */\n  background: -webkit-gradient(\n    linear,\n    left top,\n    left bottom,\n    color-stop(0%, #dedede),\n    color-stop(99%, #c8c8c8)\n  ); /* Chrome,Safari4+ */\n  background: -webkit-linear-gradient(\n    top,\n    #dedede 0%,\n    #c8c8c8 99%\n  ); /* Chrome10+,Safari5.1+ */\n  background: -o-linear-gradient(\n    top,\n    #dedede 0%,\n    #c8c8c8 99%\n  ); /* Opera 11.10+ */\n  background: -ms-linear-gradient(top, #dedede 0%, #c8c8c8 99%); /* IE10+ */\n  background: linear-gradient(to bottom, #dedede 0%, #c8c8c8 99%); /* W3C */\n  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#dedede', endColorstr='#c8c8c8',GradientType=0 ); /* IE6-9 */\n\n  border: 1px solid #999999;\n  box-shadow: #aaaaaa 0px 0px 3px 0px;\n  border-radius: 3px;\n}\ninput.vis-configuration.vis-config-range::-moz-range-thumb {\n  border: none;\n  height: 16px;\n  width: 16px;\n\n  border-radius: 50%;\n  background: #385380;\n}\n\n/*hide the outline behind the border*/\ninput.vis-configuration.vis-config-range:-moz-focusring {\n  outline: 1px solid white;\n  outline-offset: -1px;\n}\n\ninput.vis-configuration.vis-config-range::-ms-track {\n  width: 300px;\n  height: 5px;\n\n  /*remove bg colour from the track, we'll use ms-fill-lower and ms-fill-upper instead */\n  background: transparent;\n\n  /*leave room for the larger thumb to overflow with a transparent border */\n  border-color: transparent;\n  border-width: 6px 0;\n\n  /*remove default tick marks*/\n  color: transparent;\n}\ninput.vis-configuration.vis-config-range::-ms-fill-lower {\n  background: #777;\n  border-radius: 10px;\n}\ninput.vis-configuration.vis-config-range::-ms-fill-upper {\n  background: #ddd;\n  border-radius: 10px;\n}\ninput.vis-configuration.vis-config-range::-ms-thumb {\n  border: none;\n  height: 16px;\n  width: 16px;\n  border-radius: 50%;\n  background: #385380;\n}\ninput.vis-configuration.vis-config-range:focus::-ms-fill-lower {\n  background: #888;\n}\ninput.vis-configuration.vis-config-range:focus::-ms-fill-upper {\n  background: #ccc;\n}\n\n.vis-configuration-popup {\n  position: absolute;\n  background: rgba(57, 76, 89, 0.85);\n  border: 2px solid #f2faff;\n  line-height: 30px;\n  height: 30px;\n  width: 150px;\n  text-align: center;\n  color: #ffffff;\n  font-size: 14px;\n  border-radius: 4px;\n  -webkit-transition: opacity 0.3s ease-in-out;\n  -moz-transition: opacity 0.3s ease-in-out;\n  transition: opacity 0.3s ease-in-out;\n}\n.vis-configuration-popup:after,\n.vis-configuration-popup:before {\n  left: 100%;\n  top: 50%;\n  border: solid transparent;\n  content: \" \";\n  height: 0;\n  width: 0;\n  position: absolute;\n  pointer-events: none;\n}\n\n.vis-configuration-popup:after {\n  border-color: rgba(136, 183, 213, 0);\n  border-left-color: rgba(57, 76, 89, 0.85);\n  border-width: 8px;\n  margin-top: -8px;\n}\n.vis-configuration-popup:before {\n  border-color: rgba(194, 225, 245, 0);\n  border-left-color: #f2faff;\n  border-width: 12px;\n  margin-top: -12px;\n}\n";styleInject(css_248z$1);var css_248z="div.vis-tooltip {\n  position: absolute;\n  visibility: hidden;\n  padding: 5px;\n  white-space: nowrap;\n\n  font-family: verdana;\n  font-size: 14px;\n  color: #000000;\n  background-color: #f5f4ed;\n\n  -moz-border-radius: 3px;\n  -webkit-border-radius: 3px;\n  border-radius: 3px;\n  border: 1px solid #808074;\n\n  box-shadow: 3px 3px 10px rgba(0, 0, 0, 0.2);\n  pointer-events: none;\n\n  z-index: 5;\n}\n";styleInject(css_248z);var commonjsGlobal=typeof globalThis!=='undefined'?globalThis:typeof window!=='undefined'?window:typeof global!=='undefined'?global:typeof self!=='undefined'?self:{};function getDefaultExportFromCjs(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,'default')?x['default']:x;}var es_object_assign={};var globalThis_1;var hasRequiredGlobalThis;function requireGlobalThis(){if(hasRequiredGlobalThis)return globalThis_1;hasRequiredGlobalThis=1;var check=function(it){return it&&it.Math===Math&&it;};// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
globalThis_1=// eslint-disable-next-line es/no-global-this -- safe
check(typeof globalThis=='object'&&globalThis)||check(typeof window=='object'&&window)||// eslint-disable-next-line no-restricted-globals -- safe
check(typeof self=='object'&&self)||check(typeof commonjsGlobal=='object'&&commonjsGlobal)||check(typeof globalThis_1=='object'&&globalThis_1)||// eslint-disable-next-line no-new-func -- fallback
function(){return this;}()||Function('return this')();return globalThis_1;}var fails;var hasRequiredFails;function requireFails(){if(hasRequiredFails)return fails;hasRequiredFails=1;fails=function(exec){try{return !!exec();}catch(error){return true;}};return fails;}var functionBindNative;var hasRequiredFunctionBindNative;function requireFunctionBindNative(){if(hasRequiredFunctionBindNative)return functionBindNative;hasRequiredFunctionBindNative=1;var fails=/*@__PURE__*/requireFails();functionBindNative=!fails(function(){// eslint-disable-next-line es/no-function-prototype-bind -- safe
var test=function(){/* empty */}.bind();// eslint-disable-next-line no-prototype-builtins -- safe
return typeof test!='function'||test.hasOwnProperty('prototype');});return functionBindNative;}var functionApply;var hasRequiredFunctionApply;function requireFunctionApply(){if(hasRequiredFunctionApply)return functionApply;hasRequiredFunctionApply=1;var NATIVE_BIND=/*@__PURE__*/requireFunctionBindNative();var FunctionPrototype=Function.prototype;var apply=FunctionPrototype.apply;var call=FunctionPrototype.call;// eslint-disable-next-line es/no-function-prototype-bind, es/no-reflect -- safe
functionApply=typeof Reflect=='object'&&Reflect.apply||(NATIVE_BIND?call.bind(apply):function(){return call.apply(apply,arguments);});return functionApply;}var functionUncurryThis;var hasRequiredFunctionUncurryThis;function requireFunctionUncurryThis(){if(hasRequiredFunctionUncurryThis)return functionUncurryThis;hasRequiredFunctionUncurryThis=1;var NATIVE_BIND=/*@__PURE__*/requireFunctionBindNative();var FunctionPrototype=Function.prototype;var call=FunctionPrototype.call;// eslint-disable-next-line es/no-function-prototype-bind -- safe
var uncurryThisWithBind=NATIVE_BIND&&FunctionPrototype.bind.bind(call,call);functionUncurryThis=NATIVE_BIND?uncurryThisWithBind:function(fn){return function(){return call.apply(fn,arguments);};};return functionUncurryThis;}var classofRaw;var hasRequiredClassofRaw;function requireClassofRaw(){if(hasRequiredClassofRaw)return classofRaw;hasRequiredClassofRaw=1;var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var toString=uncurryThis({}.toString);var stringSlice=uncurryThis(''.slice);classofRaw=function(it){return stringSlice(toString(it),8,-1);};return classofRaw;}var functionUncurryThisClause;var hasRequiredFunctionUncurryThisClause;function requireFunctionUncurryThisClause(){if(hasRequiredFunctionUncurryThisClause)return functionUncurryThisClause;hasRequiredFunctionUncurryThisClause=1;var classofRaw=/*@__PURE__*/requireClassofRaw();var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();functionUncurryThisClause=function(fn){// Nashorn bug:
//   https://github.com/zloirock/core-js/issues/1128
//   https://github.com/zloirock/core-js/issues/1130
if(classofRaw(fn)==='Function')return uncurryThis(fn);};return functionUncurryThisClause;}var isCallable;var hasRequiredIsCallable;function requireIsCallable(){if(hasRequiredIsCallable)return isCallable;hasRequiredIsCallable=1;// https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot
var documentAll=typeof document=='object'&&document.all;// `IsCallable` abstract operation
// https://tc39.es/ecma262/#sec-iscallable
// eslint-disable-next-line unicorn/no-typeof-undefined -- required for testing
isCallable=typeof documentAll=='undefined'&&documentAll!==undefined?function(argument){return typeof argument=='function'||argument===documentAll;}:function(argument){return typeof argument=='function';};return isCallable;}var objectGetOwnPropertyDescriptor={};var descriptors;var hasRequiredDescriptors;function requireDescriptors(){if(hasRequiredDescriptors)return descriptors;hasRequiredDescriptors=1;var fails=/*@__PURE__*/requireFails();// Detect IE8's incomplete defineProperty implementation
descriptors=!fails(function(){// eslint-disable-next-line es/no-object-defineproperty -- required for testing
return Object.defineProperty({},1,{get:function(){return 7;}})[1]!==7;});return descriptors;}var functionCall;var hasRequiredFunctionCall;function requireFunctionCall(){if(hasRequiredFunctionCall)return functionCall;hasRequiredFunctionCall=1;var NATIVE_BIND=/*@__PURE__*/requireFunctionBindNative();var call=Function.prototype.call;// eslint-disable-next-line es/no-function-prototype-bind -- safe
functionCall=NATIVE_BIND?call.bind(call):function(){return call.apply(call,arguments);};return functionCall;}var objectPropertyIsEnumerable={};var hasRequiredObjectPropertyIsEnumerable;function requireObjectPropertyIsEnumerable(){if(hasRequiredObjectPropertyIsEnumerable)return objectPropertyIsEnumerable;hasRequiredObjectPropertyIsEnumerable=1;var $propertyIsEnumerable={}.propertyIsEnumerable;// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var getOwnPropertyDescriptor=Object.getOwnPropertyDescriptor;// Nashorn ~ JDK8 bug
var NASHORN_BUG=getOwnPropertyDescriptor&&!$propertyIsEnumerable.call({1:2},1);// `Object.prototype.propertyIsEnumerable` method implementation
// https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable
objectPropertyIsEnumerable.f=NASHORN_BUG?function propertyIsEnumerable(V){var descriptor=getOwnPropertyDescriptor(this,V);return !!descriptor&&descriptor.enumerable;}:$propertyIsEnumerable;return objectPropertyIsEnumerable;}var createPropertyDescriptor;var hasRequiredCreatePropertyDescriptor;function requireCreatePropertyDescriptor(){if(hasRequiredCreatePropertyDescriptor)return createPropertyDescriptor;hasRequiredCreatePropertyDescriptor=1;createPropertyDescriptor=function(bitmap,value){return {enumerable:!(bitmap&1),configurable:!(bitmap&2),writable:!(bitmap&4),value:value};};return createPropertyDescriptor;}var indexedObject;var hasRequiredIndexedObject;function requireIndexedObject(){if(hasRequiredIndexedObject)return indexedObject;hasRequiredIndexedObject=1;var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var fails=/*@__PURE__*/requireFails();var classof=/*@__PURE__*/requireClassofRaw();var $Object=Object;var split=uncurryThis(''.split);// fallback for non-array-like ES3 and non-enumerable old V8 strings
indexedObject=fails(function(){// throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
// eslint-disable-next-line no-prototype-builtins -- safe
return !$Object('z').propertyIsEnumerable(0);})?function(it){return classof(it)==='String'?split(it,''):$Object(it);}:$Object;return indexedObject;}var isNullOrUndefined;var hasRequiredIsNullOrUndefined;function requireIsNullOrUndefined(){if(hasRequiredIsNullOrUndefined)return isNullOrUndefined;hasRequiredIsNullOrUndefined=1;// we can't use just `it == null` since of `document.all` special case
// https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-aec
isNullOrUndefined=function(it){return it===null||it===undefined;};return isNullOrUndefined;}var requireObjectCoercible;var hasRequiredRequireObjectCoercible;function requireRequireObjectCoercible(){if(hasRequiredRequireObjectCoercible)return requireObjectCoercible;hasRequiredRequireObjectCoercible=1;var isNullOrUndefined=/*@__PURE__*/requireIsNullOrUndefined();var $TypeError=TypeError;// `RequireObjectCoercible` abstract operation
// https://tc39.es/ecma262/#sec-requireobjectcoercible
requireObjectCoercible=function(it){if(isNullOrUndefined(it))throw new $TypeError("Can't call method on "+it);return it;};return requireObjectCoercible;}var toIndexedObject;var hasRequiredToIndexedObject;function requireToIndexedObject(){if(hasRequiredToIndexedObject)return toIndexedObject;hasRequiredToIndexedObject=1;// toObject with fallback for non-array-like ES3 strings
var IndexedObject=/*@__PURE__*/requireIndexedObject();var requireObjectCoercible=/*@__PURE__*/requireRequireObjectCoercible();toIndexedObject=function(it){return IndexedObject(requireObjectCoercible(it));};return toIndexedObject;}var isObject$1;var hasRequiredIsObject;function requireIsObject(){if(hasRequiredIsObject)return isObject$1;hasRequiredIsObject=1;var isCallable=/*@__PURE__*/requireIsCallable();isObject$1=function(it){return typeof it=='object'?it!==null:isCallable(it);};return isObject$1;}var path;var hasRequiredPath;function requirePath(){if(hasRequiredPath)return path;hasRequiredPath=1;path={};return path;}var getBuiltIn;var hasRequiredGetBuiltIn;function requireGetBuiltIn(){if(hasRequiredGetBuiltIn)return getBuiltIn;hasRequiredGetBuiltIn=1;var path=/*@__PURE__*/requirePath();var globalThis=/*@__PURE__*/requireGlobalThis();var isCallable=/*@__PURE__*/requireIsCallable();var aFunction=function(variable){return isCallable(variable)?variable:undefined;};getBuiltIn=function(namespace,method){return arguments.length<2?aFunction(path[namespace])||aFunction(globalThis[namespace]):path[namespace]&&path[namespace][method]||globalThis[namespace]&&globalThis[namespace][method];};return getBuiltIn;}var objectIsPrototypeOf;var hasRequiredObjectIsPrototypeOf;function requireObjectIsPrototypeOf(){if(hasRequiredObjectIsPrototypeOf)return objectIsPrototypeOf;hasRequiredObjectIsPrototypeOf=1;var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();objectIsPrototypeOf=uncurryThis({}.isPrototypeOf);return objectIsPrototypeOf;}var environmentUserAgent;var hasRequiredEnvironmentUserAgent;function requireEnvironmentUserAgent(){if(hasRequiredEnvironmentUserAgent)return environmentUserAgent;hasRequiredEnvironmentUserAgent=1;var globalThis=/*@__PURE__*/requireGlobalThis();var navigator=globalThis.navigator;var userAgent=navigator&&navigator.userAgent;environmentUserAgent=userAgent?String(userAgent):'';return environmentUserAgent;}var environmentV8Version;var hasRequiredEnvironmentV8Version;function requireEnvironmentV8Version(){if(hasRequiredEnvironmentV8Version)return environmentV8Version;hasRequiredEnvironmentV8Version=1;var globalThis=/*@__PURE__*/requireGlobalThis();var userAgent=/*@__PURE__*/requireEnvironmentUserAgent();var process=globalThis.process;var Deno=globalThis.Deno;var versions=process&&process.versions||Deno&&Deno.version;var v8=versions&&versions.v8;var match,version;if(v8){match=v8.split('.');// in old Chrome, versions of V8 isn't V8 = Chrome / 10
// but their correct versions are not interesting for us
version=match[0]>0&&match[0]<4?1:+(match[0]+match[1]);}// BrowserFS NodeJS `process` polyfill incorrectly set `.v8` to `0.0`
// so check `userAgent` even if `.v8` exists, but 0
if(!version&&userAgent){match=userAgent.match(/Edge\/(\d+)/);if(!match||match[1]>=74){match=userAgent.match(/Chrome\/(\d+)/);if(match)version=+match[1];}}environmentV8Version=version;return environmentV8Version;}var symbolConstructorDetection;var hasRequiredSymbolConstructorDetection;function requireSymbolConstructorDetection(){if(hasRequiredSymbolConstructorDetection)return symbolConstructorDetection;hasRequiredSymbolConstructorDetection=1;/* eslint-disable es/no-symbol -- required for testing */var V8_VERSION=/*@__PURE__*/requireEnvironmentV8Version();var fails=/*@__PURE__*/requireFails();var globalThis=/*@__PURE__*/requireGlobalThis();var $String=globalThis.String;// eslint-disable-next-line es/no-object-getownpropertysymbols -- required for testing
symbolConstructorDetection=!!Object.getOwnPropertySymbols&&!fails(function(){var symbol=Symbol('symbol detection');// Chrome 38 Symbol has incorrect toString conversion
// `get-own-property-symbols` polyfill symbols converted to object are not Symbol instances
// nb: Do not call `String` directly to avoid this being optimized out to `symbol+''` which will,
// of course, fail.
return !$String(symbol)||!(Object(symbol)instanceof Symbol)||// Chrome 38-40 symbols are not inherited from DOM collections prototypes to instances
!Symbol.sham&&V8_VERSION&&V8_VERSION<41;});return symbolConstructorDetection;}var useSymbolAsUid;var hasRequiredUseSymbolAsUid;function requireUseSymbolAsUid(){if(hasRequiredUseSymbolAsUid)return useSymbolAsUid;hasRequiredUseSymbolAsUid=1;/* eslint-disable es/no-symbol -- required for testing */var NATIVE_SYMBOL=/*@__PURE__*/requireSymbolConstructorDetection();useSymbolAsUid=NATIVE_SYMBOL&&!Symbol.sham&&typeof Symbol.iterator=='symbol';return useSymbolAsUid;}var isSymbol;var hasRequiredIsSymbol;function requireIsSymbol(){if(hasRequiredIsSymbol)return isSymbol;hasRequiredIsSymbol=1;var getBuiltIn=/*@__PURE__*/requireGetBuiltIn();var isCallable=/*@__PURE__*/requireIsCallable();var isPrototypeOf=/*@__PURE__*/requireObjectIsPrototypeOf();var USE_SYMBOL_AS_UID=/*@__PURE__*/requireUseSymbolAsUid();var $Object=Object;isSymbol=USE_SYMBOL_AS_UID?function(it){return typeof it=='symbol';}:function(it){var $Symbol=getBuiltIn('Symbol');return isCallable($Symbol)&&isPrototypeOf($Symbol.prototype,$Object(it));};return isSymbol;}var tryToString;var hasRequiredTryToString;function requireTryToString(){if(hasRequiredTryToString)return tryToString;hasRequiredTryToString=1;var $String=String;tryToString=function(argument){try{return $String(argument);}catch(error){return 'Object';}};return tryToString;}var aCallable;var hasRequiredACallable;function requireACallable(){if(hasRequiredACallable)return aCallable;hasRequiredACallable=1;var isCallable=/*@__PURE__*/requireIsCallable();var tryToString=/*@__PURE__*/requireTryToString();var $TypeError=TypeError;// `Assert: IsCallable(argument) is true`
aCallable=function(argument){if(isCallable(argument))return argument;throw new $TypeError(tryToString(argument)+' is not a function');};return aCallable;}var getMethod;var hasRequiredGetMethod;function requireGetMethod(){if(hasRequiredGetMethod)return getMethod;hasRequiredGetMethod=1;var aCallable=/*@__PURE__*/requireACallable();var isNullOrUndefined=/*@__PURE__*/requireIsNullOrUndefined();// `GetMethod` abstract operation
// https://tc39.es/ecma262/#sec-getmethod
getMethod=function(V,P){var func=V[P];return isNullOrUndefined(func)?undefined:aCallable(func);};return getMethod;}var ordinaryToPrimitive;var hasRequiredOrdinaryToPrimitive;function requireOrdinaryToPrimitive(){if(hasRequiredOrdinaryToPrimitive)return ordinaryToPrimitive;hasRequiredOrdinaryToPrimitive=1;var call=/*@__PURE__*/requireFunctionCall();var isCallable=/*@__PURE__*/requireIsCallable();var isObject=/*@__PURE__*/requireIsObject();var $TypeError=TypeError;// `OrdinaryToPrimitive` abstract operation
// https://tc39.es/ecma262/#sec-ordinarytoprimitive
ordinaryToPrimitive=function(input,pref){var fn,val;if(pref==='string'&&isCallable(fn=input.toString)&&!isObject(val=call(fn,input)))return val;if(isCallable(fn=input.valueOf)&&!isObject(val=call(fn,input)))return val;if(pref!=='string'&&isCallable(fn=input.toString)&&!isObject(val=call(fn,input)))return val;throw new $TypeError("Can't convert object to primitive value");};return ordinaryToPrimitive;}var sharedStore={exports:{}};var isPure;var hasRequiredIsPure;function requireIsPure(){if(hasRequiredIsPure)return isPure;hasRequiredIsPure=1;isPure=true;return isPure;}var defineGlobalProperty;var hasRequiredDefineGlobalProperty;function requireDefineGlobalProperty(){if(hasRequiredDefineGlobalProperty)return defineGlobalProperty;hasRequiredDefineGlobalProperty=1;var globalThis=/*@__PURE__*/requireGlobalThis();// eslint-disable-next-line es/no-object-defineproperty -- safe
var defineProperty=Object.defineProperty;defineGlobalProperty=function(key,value){try{defineProperty(globalThis,key,{value:value,configurable:true,writable:true});}catch(error){globalThis[key]=value;}return value;};return defineGlobalProperty;}var hasRequiredSharedStore;function requireSharedStore(){if(hasRequiredSharedStore)return sharedStore.exports;hasRequiredSharedStore=1;var IS_PURE=/*@__PURE__*/requireIsPure();var globalThis=/*@__PURE__*/requireGlobalThis();var defineGlobalProperty=/*@__PURE__*/requireDefineGlobalProperty();var SHARED='__core-js_shared__';var store=sharedStore.exports=globalThis[SHARED]||defineGlobalProperty(SHARED,{});(store.versions||(store.versions=[])).push({version:'3.44.0',mode:IS_PURE?'pure':'global',copyright:'© 2014-2025 Denis Pushkarev (zloirock.ru)',license:'https://github.com/zloirock/core-js/blob/v3.44.0/LICENSE',source:'https://github.com/zloirock/core-js'});return sharedStore.exports;}var shared;var hasRequiredShared;function requireShared(){if(hasRequiredShared)return shared;hasRequiredShared=1;var store=/*@__PURE__*/requireSharedStore();shared=function(key,value){return store[key]||(store[key]=value||{});};return shared;}var toObject;var hasRequiredToObject;function requireToObject(){if(hasRequiredToObject)return toObject;hasRequiredToObject=1;var requireObjectCoercible=/*@__PURE__*/requireRequireObjectCoercible();var $Object=Object;// `ToObject` abstract operation
// https://tc39.es/ecma262/#sec-toobject
toObject=function(argument){return $Object(requireObjectCoercible(argument));};return toObject;}var hasOwnProperty_1;var hasRequiredHasOwnProperty;function requireHasOwnProperty(){if(hasRequiredHasOwnProperty)return hasOwnProperty_1;hasRequiredHasOwnProperty=1;var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var toObject=/*@__PURE__*/requireToObject();var hasOwnProperty=uncurryThis({}.hasOwnProperty);// `HasOwnProperty` abstract operation
// https://tc39.es/ecma262/#sec-hasownproperty
// eslint-disable-next-line es/no-object-hasown -- safe
hasOwnProperty_1=Object.hasOwn||function hasOwn(it,key){return hasOwnProperty(toObject(it),key);};return hasOwnProperty_1;}var uid;var hasRequiredUid;function requireUid(){if(hasRequiredUid)return uid;hasRequiredUid=1;var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var id=0;var postfix=Math.random();var toString=uncurryThis(1.1.toString);uid=function(key){return 'Symbol('+(key===undefined?'':key)+')_'+toString(++id+postfix,36);};return uid;}var wellKnownSymbol;var hasRequiredWellKnownSymbol;function requireWellKnownSymbol(){if(hasRequiredWellKnownSymbol)return wellKnownSymbol;hasRequiredWellKnownSymbol=1;var globalThis=/*@__PURE__*/requireGlobalThis();var shared=/*@__PURE__*/requireShared();var hasOwn=/*@__PURE__*/requireHasOwnProperty();var uid=/*@__PURE__*/requireUid();var NATIVE_SYMBOL=/*@__PURE__*/requireSymbolConstructorDetection();var USE_SYMBOL_AS_UID=/*@__PURE__*/requireUseSymbolAsUid();var Symbol=globalThis.Symbol;var WellKnownSymbolsStore=shared('wks');var createWellKnownSymbol=USE_SYMBOL_AS_UID?Symbol['for']||Symbol:Symbol&&Symbol.withoutSetter||uid;wellKnownSymbol=function(name){if(!hasOwn(WellKnownSymbolsStore,name)){WellKnownSymbolsStore[name]=NATIVE_SYMBOL&&hasOwn(Symbol,name)?Symbol[name]:createWellKnownSymbol('Symbol.'+name);}return WellKnownSymbolsStore[name];};return wellKnownSymbol;}var toPrimitive$6;var hasRequiredToPrimitive$5;function requireToPrimitive$5(){if(hasRequiredToPrimitive$5)return toPrimitive$6;hasRequiredToPrimitive$5=1;var call=/*@__PURE__*/requireFunctionCall();var isObject=/*@__PURE__*/requireIsObject();var isSymbol=/*@__PURE__*/requireIsSymbol();var getMethod=/*@__PURE__*/requireGetMethod();var ordinaryToPrimitive=/*@__PURE__*/requireOrdinaryToPrimitive();var wellKnownSymbol=/*@__PURE__*/requireWellKnownSymbol();var $TypeError=TypeError;var TO_PRIMITIVE=wellKnownSymbol('toPrimitive');// `ToPrimitive` abstract operation
// https://tc39.es/ecma262/#sec-toprimitive
toPrimitive$6=function(input,pref){if(!isObject(input)||isSymbol(input))return input;var exoticToPrim=getMethod(input,TO_PRIMITIVE);var result;if(exoticToPrim){if(pref===undefined)pref='default';result=call(exoticToPrim,input,pref);if(!isObject(result)||isSymbol(result))return result;throw new $TypeError("Can't convert object to primitive value");}if(pref===undefined)pref='number';return ordinaryToPrimitive(input,pref);};return toPrimitive$6;}var toPropertyKey$1;var hasRequiredToPropertyKey;function requireToPropertyKey(){if(hasRequiredToPropertyKey)return toPropertyKey$1;hasRequiredToPropertyKey=1;var toPrimitive=/*@__PURE__*/requireToPrimitive$5();var isSymbol=/*@__PURE__*/requireIsSymbol();// `ToPropertyKey` abstract operation
// https://tc39.es/ecma262/#sec-topropertykey
toPropertyKey$1=function(argument){var key=toPrimitive(argument,'string');return isSymbol(key)?key:key+'';};return toPropertyKey$1;}var documentCreateElement;var hasRequiredDocumentCreateElement;function requireDocumentCreateElement(){if(hasRequiredDocumentCreateElement)return documentCreateElement;hasRequiredDocumentCreateElement=1;var globalThis=/*@__PURE__*/requireGlobalThis();var isObject=/*@__PURE__*/requireIsObject();var document=globalThis.document;// typeof document.createElement is 'object' in old IE
var EXISTS=isObject(document)&&isObject(document.createElement);documentCreateElement=function(it){return EXISTS?document.createElement(it):{};};return documentCreateElement;}var ie8DomDefine;var hasRequiredIe8DomDefine;function requireIe8DomDefine(){if(hasRequiredIe8DomDefine)return ie8DomDefine;hasRequiredIe8DomDefine=1;var DESCRIPTORS=/*@__PURE__*/requireDescriptors();var fails=/*@__PURE__*/requireFails();var createElement=/*@__PURE__*/requireDocumentCreateElement();// Thanks to IE8 for its funny defineProperty
ie8DomDefine=!DESCRIPTORS&&!fails(function(){// eslint-disable-next-line es/no-object-defineproperty -- required for testing
return Object.defineProperty(createElement('div'),'a',{get:function(){return 7;}}).a!==7;});return ie8DomDefine;}var hasRequiredObjectGetOwnPropertyDescriptor;function requireObjectGetOwnPropertyDescriptor(){if(hasRequiredObjectGetOwnPropertyDescriptor)return objectGetOwnPropertyDescriptor;hasRequiredObjectGetOwnPropertyDescriptor=1;var DESCRIPTORS=/*@__PURE__*/requireDescriptors();var call=/*@__PURE__*/requireFunctionCall();var propertyIsEnumerableModule=/*@__PURE__*/requireObjectPropertyIsEnumerable();var createPropertyDescriptor=/*@__PURE__*/requireCreatePropertyDescriptor();var toIndexedObject=/*@__PURE__*/requireToIndexedObject();var toPropertyKey=/*@__PURE__*/requireToPropertyKey();var hasOwn=/*@__PURE__*/requireHasOwnProperty();var IE8_DOM_DEFINE=/*@__PURE__*/requireIe8DomDefine();// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var $getOwnPropertyDescriptor=Object.getOwnPropertyDescriptor;// `Object.getOwnPropertyDescriptor` method
// https://tc39.es/ecma262/#sec-object.getownpropertydescriptor
objectGetOwnPropertyDescriptor.f=DESCRIPTORS?$getOwnPropertyDescriptor:function getOwnPropertyDescriptor(O,P){O=toIndexedObject(O);P=toPropertyKey(P);if(IE8_DOM_DEFINE)try{return $getOwnPropertyDescriptor(O,P);}catch(error){/* empty */}if(hasOwn(O,P))return createPropertyDescriptor(!call(propertyIsEnumerableModule.f,O,P),O[P]);};return objectGetOwnPropertyDescriptor;}var isForced_1;var hasRequiredIsForced;function requireIsForced(){if(hasRequiredIsForced)return isForced_1;hasRequiredIsForced=1;var fails=/*@__PURE__*/requireFails();var isCallable=/*@__PURE__*/requireIsCallable();var replacement=/#|\.prototype\./;var isForced=function(feature,detection){var value=data[normalize(feature)];return value===POLYFILL?true:value===NATIVE?false:isCallable(detection)?fails(detection):!!detection;};var normalize=isForced.normalize=function(string){return String(string).replace(replacement,'.').toLowerCase();};var data=isForced.data={};var NATIVE=isForced.NATIVE='N';var POLYFILL=isForced.POLYFILL='P';isForced_1=isForced;return isForced_1;}var functionBindContext;var hasRequiredFunctionBindContext;function requireFunctionBindContext(){if(hasRequiredFunctionBindContext)return functionBindContext;hasRequiredFunctionBindContext=1;var uncurryThis=/*@__PURE__*/requireFunctionUncurryThisClause();var aCallable=/*@__PURE__*/requireACallable();var NATIVE_BIND=/*@__PURE__*/requireFunctionBindNative();var bind=uncurryThis(uncurryThis.bind);// optional / simple context binding
functionBindContext=function(fn,that){aCallable(fn);return that===undefined?fn:NATIVE_BIND?bind(fn,that):function/* ...args */(){return fn.apply(that,arguments);};};return functionBindContext;}var objectDefineProperty={};var v8PrototypeDefineBug;var hasRequiredV8PrototypeDefineBug;function requireV8PrototypeDefineBug(){if(hasRequiredV8PrototypeDefineBug)return v8PrototypeDefineBug;hasRequiredV8PrototypeDefineBug=1;var DESCRIPTORS=/*@__PURE__*/requireDescriptors();var fails=/*@__PURE__*/requireFails();// V8 ~ Chrome 36-
// https://bugs.chromium.org/p/v8/issues/detail?id=3334
v8PrototypeDefineBug=DESCRIPTORS&&fails(function(){// eslint-disable-next-line es/no-object-defineproperty -- required for testing
return Object.defineProperty(function(){/* empty */},'prototype',{value:42,writable:false}).prototype!==42;});return v8PrototypeDefineBug;}var anObject;var hasRequiredAnObject;function requireAnObject(){if(hasRequiredAnObject)return anObject;hasRequiredAnObject=1;var isObject=/*@__PURE__*/requireIsObject();var $String=String;var $TypeError=TypeError;// `Assert: Type(argument) is Object`
anObject=function(argument){if(isObject(argument))return argument;throw new $TypeError($String(argument)+' is not an object');};return anObject;}var hasRequiredObjectDefineProperty;function requireObjectDefineProperty(){if(hasRequiredObjectDefineProperty)return objectDefineProperty;hasRequiredObjectDefineProperty=1;var DESCRIPTORS=/*@__PURE__*/requireDescriptors();var IE8_DOM_DEFINE=/*@__PURE__*/requireIe8DomDefine();var V8_PROTOTYPE_DEFINE_BUG=/*@__PURE__*/requireV8PrototypeDefineBug();var anObject=/*@__PURE__*/requireAnObject();var toPropertyKey=/*@__PURE__*/requireToPropertyKey();var $TypeError=TypeError;// eslint-disable-next-line es/no-object-defineproperty -- safe
var $defineProperty=Object.defineProperty;// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var $getOwnPropertyDescriptor=Object.getOwnPropertyDescriptor;var ENUMERABLE='enumerable';var CONFIGURABLE='configurable';var WRITABLE='writable';// `Object.defineProperty` method
// https://tc39.es/ecma262/#sec-object.defineproperty
objectDefineProperty.f=DESCRIPTORS?V8_PROTOTYPE_DEFINE_BUG?function defineProperty(O,P,Attributes){anObject(O);P=toPropertyKey(P);anObject(Attributes);if(typeof O==='function'&&P==='prototype'&&'value'in Attributes&&WRITABLE in Attributes&&!Attributes[WRITABLE]){var current=$getOwnPropertyDescriptor(O,P);if(current&&current[WRITABLE]){O[P]=Attributes.value;Attributes={configurable:CONFIGURABLE in Attributes?Attributes[CONFIGURABLE]:current[CONFIGURABLE],enumerable:ENUMERABLE in Attributes?Attributes[ENUMERABLE]:current[ENUMERABLE],writable:false};}}return $defineProperty(O,P,Attributes);}:$defineProperty:function defineProperty(O,P,Attributes){anObject(O);P=toPropertyKey(P);anObject(Attributes);if(IE8_DOM_DEFINE)try{return $defineProperty(O,P,Attributes);}catch(error){/* empty */}if('get'in Attributes||'set'in Attributes)throw new $TypeError('Accessors not supported');if('value'in Attributes)O[P]=Attributes.value;return O;};return objectDefineProperty;}var createNonEnumerableProperty;var hasRequiredCreateNonEnumerableProperty;function requireCreateNonEnumerableProperty(){if(hasRequiredCreateNonEnumerableProperty)return createNonEnumerableProperty;hasRequiredCreateNonEnumerableProperty=1;var DESCRIPTORS=/*@__PURE__*/requireDescriptors();var definePropertyModule=/*@__PURE__*/requireObjectDefineProperty();var createPropertyDescriptor=/*@__PURE__*/requireCreatePropertyDescriptor();createNonEnumerableProperty=DESCRIPTORS?function(object,key,value){return definePropertyModule.f(object,key,createPropertyDescriptor(1,value));}:function(object,key,value){object[key]=value;return object;};return createNonEnumerableProperty;}var _export;var hasRequired_export;function require_export(){if(hasRequired_export)return _export;hasRequired_export=1;var globalThis=/*@__PURE__*/requireGlobalThis();var apply=/*@__PURE__*/requireFunctionApply();var uncurryThis=/*@__PURE__*/requireFunctionUncurryThisClause();var isCallable=/*@__PURE__*/requireIsCallable();var getOwnPropertyDescriptor=/*@__PURE__*/requireObjectGetOwnPropertyDescriptor().f;var isForced=/*@__PURE__*/requireIsForced();var path=/*@__PURE__*/requirePath();var bind=/*@__PURE__*/requireFunctionBindContext();var createNonEnumerableProperty=/*@__PURE__*/requireCreateNonEnumerableProperty();var hasOwn=/*@__PURE__*/requireHasOwnProperty();var wrapConstructor=function(NativeConstructor){var Wrapper=function(a,b,c){if(this instanceof Wrapper){switch(arguments.length){case 0:return new NativeConstructor();case 1:return new NativeConstructor(a);case 2:return new NativeConstructor(a,b);}return new NativeConstructor(a,b,c);}return apply(NativeConstructor,this,arguments);};Wrapper.prototype=NativeConstructor.prototype;return Wrapper;};/*
	  options.target         - name of the target object
	  options.global         - target is the global object
	  options.stat           - export as static methods of target
	  options.proto          - export as prototype methods of target
	  options.real           - real prototype method for the `pure` version
	  options.forced         - export even if the native feature is available
	  options.bind           - bind methods to the target, required for the `pure` version
	  options.wrap           - wrap constructors to preventing global pollution, required for the `pure` version
	  options.unsafe         - use the simple assignment of property instead of delete + defineProperty
	  options.sham           - add a flag to not completely full polyfills
	  options.enumerable     - export as enumerable property
	  options.dontCallGetSet - prevent calling a getter on target
	  options.name           - the .name of the function if it does not match the key
	*/_export=function(options,source){var TARGET=options.target;var GLOBAL=options.global;var STATIC=options.stat;var PROTO=options.proto;var nativeSource=GLOBAL?globalThis:STATIC?globalThis[TARGET]:globalThis[TARGET]&&globalThis[TARGET].prototype;var target=GLOBAL?path:path[TARGET]||createNonEnumerableProperty(path,TARGET,{})[TARGET];var targetPrototype=target.prototype;var FORCED,USE_NATIVE,VIRTUAL_PROTOTYPE;var key,sourceProperty,targetProperty,nativeProperty,resultProperty,descriptor;for(key in source){FORCED=isForced(GLOBAL?key:TARGET+(STATIC?'.':'#')+key,options.forced);// contains in native
USE_NATIVE=!FORCED&&nativeSource&&hasOwn(nativeSource,key);targetProperty=target[key];if(USE_NATIVE)if(options.dontCallGetSet){descriptor=getOwnPropertyDescriptor(nativeSource,key);nativeProperty=descriptor&&descriptor.value;}else nativeProperty=nativeSource[key];// export native or implementation
sourceProperty=USE_NATIVE&&nativeProperty?nativeProperty:source[key];if(!FORCED&&!PROTO&&typeof targetProperty==typeof sourceProperty)continue;// bind methods to global for calling from export context
if(options.bind&&USE_NATIVE)resultProperty=bind(sourceProperty,globalThis);// wrap global constructors for prevent changes in this version
else if(options.wrap&&USE_NATIVE)resultProperty=wrapConstructor(sourceProperty);// make static versions for prototype methods
else if(PROTO&&isCallable(sourceProperty))resultProperty=uncurryThis(sourceProperty);// default case
else resultProperty=sourceProperty;// add a flag to not completely full polyfills
if(options.sham||sourceProperty&&sourceProperty.sham||targetProperty&&targetProperty.sham){createNonEnumerableProperty(resultProperty,'sham',true);}createNonEnumerableProperty(target,key,resultProperty);if(PROTO){VIRTUAL_PROTOTYPE=TARGET+'Prototype';if(!hasOwn(path,VIRTUAL_PROTOTYPE)){createNonEnumerableProperty(path,VIRTUAL_PROTOTYPE,{});}// export virtual prototype methods
createNonEnumerableProperty(path[VIRTUAL_PROTOTYPE],key,sourceProperty);// export real prototype methods
if(options.real&&targetPrototype&&(FORCED||!targetPrototype[key])){createNonEnumerableProperty(targetPrototype,key,sourceProperty);}}}};return _export;}var mathTrunc;var hasRequiredMathTrunc;function requireMathTrunc(){if(hasRequiredMathTrunc)return mathTrunc;hasRequiredMathTrunc=1;var ceil=Math.ceil;var floor=Math.floor;// `Math.trunc` method
// https://tc39.es/ecma262/#sec-math.trunc
// eslint-disable-next-line es/no-math-trunc -- safe
mathTrunc=Math.trunc||function trunc(x){var n=+x;return (n>0?floor:ceil)(n);};return mathTrunc;}var toIntegerOrInfinity;var hasRequiredToIntegerOrInfinity;function requireToIntegerOrInfinity(){if(hasRequiredToIntegerOrInfinity)return toIntegerOrInfinity;hasRequiredToIntegerOrInfinity=1;var trunc=/*@__PURE__*/requireMathTrunc();// `ToIntegerOrInfinity` abstract operation
// https://tc39.es/ecma262/#sec-tointegerorinfinity
toIntegerOrInfinity=function(argument){var number=+argument;// eslint-disable-next-line no-self-compare -- NaN check
return number!==number||number===0?0:trunc(number);};return toIntegerOrInfinity;}var toAbsoluteIndex;var hasRequiredToAbsoluteIndex;function requireToAbsoluteIndex(){if(hasRequiredToAbsoluteIndex)return toAbsoluteIndex;hasRequiredToAbsoluteIndex=1;var toIntegerOrInfinity=/*@__PURE__*/requireToIntegerOrInfinity();var max=Math.max;var min=Math.min;// Helper for a popular repeating case of the spec:
// Let integer be ? ToInteger(index).
// If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).
toAbsoluteIndex=function(index,length){var integer=toIntegerOrInfinity(index);return integer<0?max(integer+length,0):min(integer,length);};return toAbsoluteIndex;}var toLength;var hasRequiredToLength;function requireToLength(){if(hasRequiredToLength)return toLength;hasRequiredToLength=1;var toIntegerOrInfinity=/*@__PURE__*/requireToIntegerOrInfinity();var min=Math.min;// `ToLength` abstract operation
// https://tc39.es/ecma262/#sec-tolength
toLength=function(argument){var len=toIntegerOrInfinity(argument);return len>0?min(len,0x1FFFFFFFFFFFFF):0;// 2 ** 53 - 1 == 9007199254740991
};return toLength;}var lengthOfArrayLike;var hasRequiredLengthOfArrayLike;function requireLengthOfArrayLike(){if(hasRequiredLengthOfArrayLike)return lengthOfArrayLike;hasRequiredLengthOfArrayLike=1;var toLength=/*@__PURE__*/requireToLength();// `LengthOfArrayLike` abstract operation
// https://tc39.es/ecma262/#sec-lengthofarraylike
lengthOfArrayLike=function(obj){return toLength(obj.length);};return lengthOfArrayLike;}var arrayIncludes;var hasRequiredArrayIncludes;function requireArrayIncludes(){if(hasRequiredArrayIncludes)return arrayIncludes;hasRequiredArrayIncludes=1;var toIndexedObject=/*@__PURE__*/requireToIndexedObject();var toAbsoluteIndex=/*@__PURE__*/requireToAbsoluteIndex();var lengthOfArrayLike=/*@__PURE__*/requireLengthOfArrayLike();// `Array.prototype.{ indexOf, includes }` methods implementation
var createMethod=function(IS_INCLUDES){return function($this,el,fromIndex){var O=toIndexedObject($this);var length=lengthOfArrayLike(O);if(length===0)return !IS_INCLUDES&&-1;var index=toAbsoluteIndex(fromIndex,length);var value;// Array#includes uses SameValueZero equality algorithm
// eslint-disable-next-line no-self-compare -- NaN check
if(IS_INCLUDES&&el!==el)while(length>index){value=O[index++];// eslint-disable-next-line no-self-compare -- NaN check
if(value!==value)return true;// Array#indexOf ignores holes, Array#includes - not
}else for(;length>index;index++){if((IS_INCLUDES||index in O)&&O[index]===el)return IS_INCLUDES||index||0;}return !IS_INCLUDES&&-1;};};arrayIncludes={// `Array.prototype.includes` method
// https://tc39.es/ecma262/#sec-array.prototype.includes
includes:createMethod(true),// `Array.prototype.indexOf` method
// https://tc39.es/ecma262/#sec-array.prototype.indexof
indexOf:createMethod(false)};return arrayIncludes;}var hiddenKeys;var hasRequiredHiddenKeys;function requireHiddenKeys(){if(hasRequiredHiddenKeys)return hiddenKeys;hasRequiredHiddenKeys=1;hiddenKeys={};return hiddenKeys;}var objectKeysInternal;var hasRequiredObjectKeysInternal;function requireObjectKeysInternal(){if(hasRequiredObjectKeysInternal)return objectKeysInternal;hasRequiredObjectKeysInternal=1;var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var hasOwn=/*@__PURE__*/requireHasOwnProperty();var toIndexedObject=/*@__PURE__*/requireToIndexedObject();var indexOf=/*@__PURE__*/requireArrayIncludes().indexOf;var hiddenKeys=/*@__PURE__*/requireHiddenKeys();var push=uncurryThis([].push);objectKeysInternal=function(object,names){var O=toIndexedObject(object);var i=0;var result=[];var key;for(key in O)!hasOwn(hiddenKeys,key)&&hasOwn(O,key)&&push(result,key);// Don't enum bug & hidden keys
while(names.length>i)if(hasOwn(O,key=names[i++])){~indexOf(result,key)||push(result,key);}return result;};return objectKeysInternal;}var enumBugKeys;var hasRequiredEnumBugKeys;function requireEnumBugKeys(){if(hasRequiredEnumBugKeys)return enumBugKeys;hasRequiredEnumBugKeys=1;// IE8- don't enum bug keys
enumBugKeys=['constructor','hasOwnProperty','isPrototypeOf','propertyIsEnumerable','toLocaleString','toString','valueOf'];return enumBugKeys;}var objectKeys;var hasRequiredObjectKeys;function requireObjectKeys(){if(hasRequiredObjectKeys)return objectKeys;hasRequiredObjectKeys=1;var internalObjectKeys=/*@__PURE__*/requireObjectKeysInternal();var enumBugKeys=/*@__PURE__*/requireEnumBugKeys();// `Object.keys` method
// https://tc39.es/ecma262/#sec-object.keys
// eslint-disable-next-line es/no-object-keys -- safe
objectKeys=Object.keys||function keys(O){return internalObjectKeys(O,enumBugKeys);};return objectKeys;}var objectGetOwnPropertySymbols={};var hasRequiredObjectGetOwnPropertySymbols;function requireObjectGetOwnPropertySymbols(){if(hasRequiredObjectGetOwnPropertySymbols)return objectGetOwnPropertySymbols;hasRequiredObjectGetOwnPropertySymbols=1;// eslint-disable-next-line es/no-object-getownpropertysymbols -- safe
objectGetOwnPropertySymbols.f=Object.getOwnPropertySymbols;return objectGetOwnPropertySymbols;}var objectAssign;var hasRequiredObjectAssign;function requireObjectAssign(){if(hasRequiredObjectAssign)return objectAssign;hasRequiredObjectAssign=1;var DESCRIPTORS=/*@__PURE__*/requireDescriptors();var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var call=/*@__PURE__*/requireFunctionCall();var fails=/*@__PURE__*/requireFails();var objectKeys=/*@__PURE__*/requireObjectKeys();var getOwnPropertySymbolsModule=/*@__PURE__*/requireObjectGetOwnPropertySymbols();var propertyIsEnumerableModule=/*@__PURE__*/requireObjectPropertyIsEnumerable();var toObject=/*@__PURE__*/requireToObject();var IndexedObject=/*@__PURE__*/requireIndexedObject();// eslint-disable-next-line es/no-object-assign -- safe
var $assign=Object.assign;// eslint-disable-next-line es/no-object-defineproperty -- required for testing
var defineProperty=Object.defineProperty;var concat=uncurryThis([].concat);// `Object.assign` method
// https://tc39.es/ecma262/#sec-object.assign
objectAssign=!$assign||fails(function(){// should have correct order of operations (Edge bug)
if(DESCRIPTORS&&$assign({b:1},$assign(defineProperty({},'a',{enumerable:true,get:function(){defineProperty(this,'b',{value:3,enumerable:false});}}),{b:2})).b!==1)return true;// should work with symbols and should have deterministic property order (V8 bug)
var A={};var B={};// eslint-disable-next-line es/no-symbol -- safe
var symbol=Symbol('assign detection');var alphabet='abcdefghijklmnopqrst';A[symbol]=7;// eslint-disable-next-line es/no-array-prototype-foreach -- safe
alphabet.split('').forEach(function(chr){B[chr]=chr;});return $assign({},A)[symbol]!==7||objectKeys($assign({},B)).join('')!==alphabet;})?function assign(target,source){// eslint-disable-line no-unused-vars -- required for `.length`
var T=toObject(target);var argumentsLength=arguments.length;var index=1;var getOwnPropertySymbols=getOwnPropertySymbolsModule.f;var propertyIsEnumerable=propertyIsEnumerableModule.f;while(argumentsLength>index){var S=IndexedObject(arguments[index++]);var keys=getOwnPropertySymbols?concat(objectKeys(S),getOwnPropertySymbols(S)):objectKeys(S);var length=keys.length;var j=0;var key;while(length>j){key=keys[j++];if(!DESCRIPTORS||call(propertyIsEnumerable,S,key))T[key]=S[key];}}return T;}:$assign;return objectAssign;}var hasRequiredEs_object_assign;function requireEs_object_assign(){if(hasRequiredEs_object_assign)return es_object_assign;hasRequiredEs_object_assign=1;var $=/*@__PURE__*/require_export();var assign=/*@__PURE__*/requireObjectAssign();// `Object.assign` method
// https://tc39.es/ecma262/#sec-object.assign
// eslint-disable-next-line es/no-object-assign -- required for testing
$({target:'Object',stat:true,arity:2,forced:Object.assign!==assign},{assign:assign});return es_object_assign;}var assign$4;var hasRequiredAssign$2;function requireAssign$2(){if(hasRequiredAssign$2)return assign$4;hasRequiredAssign$2=1;requireEs_object_assign();var path=/*@__PURE__*/requirePath();assign$4=path.Object.assign;return assign$4;}var assign$3;var hasRequiredAssign$1;function requireAssign$1(){if(hasRequiredAssign$1)return assign$3;hasRequiredAssign$1=1;var parent=/*@__PURE__*/requireAssign$2();assign$3=parent;return assign$3;}var assign$2;var hasRequiredAssign;function requireAssign(){if(hasRequiredAssign)return assign$2;hasRequiredAssign=1;assign$2=/*@__PURE__*/requireAssign$1();return assign$2;}var assignExports=requireAssign();var _Object$assign=/*@__PURE__*/getDefaultExportFromCjs(assignExports);var es_function_bind={};var arraySlice;var hasRequiredArraySlice;function requireArraySlice(){if(hasRequiredArraySlice)return arraySlice;hasRequiredArraySlice=1;var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();arraySlice=uncurryThis([].slice);return arraySlice;}var functionBind;var hasRequiredFunctionBind;function requireFunctionBind(){if(hasRequiredFunctionBind)return functionBind;hasRequiredFunctionBind=1;var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var aCallable=/*@__PURE__*/requireACallable();var isObject=/*@__PURE__*/requireIsObject();var hasOwn=/*@__PURE__*/requireHasOwnProperty();var arraySlice=/*@__PURE__*/requireArraySlice();var NATIVE_BIND=/*@__PURE__*/requireFunctionBindNative();var $Function=Function;var concat=uncurryThis([].concat);var join=uncurryThis([].join);var factories={};var construct=function(C,argsLength,args){if(!hasOwn(factories,argsLength)){var list=[];var i=0;for(;i<argsLength;i++)list[i]='a['+i+']';factories[argsLength]=$Function('C,a','return new C('+join(list,',')+')');}return factories[argsLength](C,args);};// `Function.prototype.bind` method implementation
// https://tc39.es/ecma262/#sec-function.prototype.bind
// eslint-disable-next-line es/no-function-prototype-bind -- detection
functionBind=NATIVE_BIND?$Function.bind:function bind(that/* , ...args */){var F=aCallable(this);var Prototype=F.prototype;var partArgs=arraySlice(arguments,1);var boundFunction=function bound(/* args... */){var args=concat(partArgs,arraySlice(arguments));return this instanceof boundFunction?construct(F,args.length,args):F.apply(that,args);};if(isObject(Prototype))boundFunction.prototype=Prototype;return boundFunction;};return functionBind;}var hasRequiredEs_function_bind;function requireEs_function_bind(){if(hasRequiredEs_function_bind)return es_function_bind;hasRequiredEs_function_bind=1;// TODO: Remove from `core-js@4`
var $=/*@__PURE__*/require_export();var bind=/*@__PURE__*/requireFunctionBind();// `Function.prototype.bind` method
// https://tc39.es/ecma262/#sec-function.prototype.bind
// eslint-disable-next-line es/no-function-prototype-bind -- detection
$({target:'Function',proto:true,forced:Function.bind!==bind},{bind:bind});return es_function_bind;}var getBuiltInPrototypeMethod;var hasRequiredGetBuiltInPrototypeMethod;function requireGetBuiltInPrototypeMethod(){if(hasRequiredGetBuiltInPrototypeMethod)return getBuiltInPrototypeMethod;hasRequiredGetBuiltInPrototypeMethod=1;var globalThis=/*@__PURE__*/requireGlobalThis();var path=/*@__PURE__*/requirePath();getBuiltInPrototypeMethod=function(CONSTRUCTOR,METHOD){var Namespace=path[CONSTRUCTOR+'Prototype'];var pureMethod=Namespace&&Namespace[METHOD];if(pureMethod)return pureMethod;var NativeConstructor=globalThis[CONSTRUCTOR];var NativePrototype=NativeConstructor&&NativeConstructor.prototype;return NativePrototype&&NativePrototype[METHOD];};return getBuiltInPrototypeMethod;}var bind$3;var hasRequiredBind$3;function requireBind$3(){if(hasRequiredBind$3)return bind$3;hasRequiredBind$3=1;requireEs_function_bind();var getBuiltInPrototypeMethod=/*@__PURE__*/requireGetBuiltInPrototypeMethod();bind$3=getBuiltInPrototypeMethod('Function','bind');return bind$3;}var bind$2;var hasRequiredBind$2;function requireBind$2(){if(hasRequiredBind$2)return bind$2;hasRequiredBind$2=1;var isPrototypeOf=/*@__PURE__*/requireObjectIsPrototypeOf();var method=/*@__PURE__*/requireBind$3();var FunctionPrototype=Function.prototype;bind$2=function(it){var own=it.bind;return it===FunctionPrototype||isPrototypeOf(FunctionPrototype,it)&&own===FunctionPrototype.bind?method:own;};return bind$2;}var bind$1;var hasRequiredBind$1;function requireBind$1(){if(hasRequiredBind$1)return bind$1;hasRequiredBind$1=1;var parent=/*@__PURE__*/requireBind$2();bind$1=parent;return bind$1;}var bind;var hasRequiredBind;function requireBind(){if(hasRequiredBind)return bind;hasRequiredBind=1;bind=/*@__PURE__*/requireBind$1();return bind;}var bindExports=requireBind();var _bindInstanceProperty=/*@__PURE__*/getDefaultExportFromCjs(bindExports);/**
 * Draw a circle.
 * @param ctx - The context this shape will be rendered to.
 * @param x - The position of the center on the x axis.
 * @param y - The position of the center on the y axis.
 * @param r - The radius of the circle.
 */function drawCircle(ctx,x,y,r){ctx.beginPath();ctx.arc(x,y,r,0,2*Math.PI,false);ctx.closePath();}/**
 * Draw a square.
 * @param ctx - The context this shape will be rendered to.
 * @param x - The position of the center on the x axis.
 * @param y - The position of the center on the y axis.
 * @param r - Half of the width and height of the square.
 */function drawSquare(ctx,x,y,r){ctx.beginPath();ctx.rect(x-r,y-r,r*2,r*2);ctx.closePath();}/**
 * Draw an equilateral triangle standing on a side.
 * @param ctx - The context this shape will be rendered to.
 * @param x - The position of the center on the x axis.
 * @param y - The position of the center on the y axis.
 * @param r - Half of the length of the sides.
 * @remarks
 * http://en.wikipedia.org/wiki/Equilateral_triangle
 */function drawTriangle(ctx,x,y,r){ctx.beginPath();// the change in radius and the offset is here to center the shape
r*=1.15;y+=0.275*r;const s=r*2;const s2=s/2;const ir=Math.sqrt(3)/6*s;// radius of inner circle
const h=Math.sqrt(s*s-s2*s2);// height
ctx.moveTo(x,y-(h-ir));ctx.lineTo(x+s2,y+ir);ctx.lineTo(x-s2,y+ir);ctx.lineTo(x,y-(h-ir));ctx.closePath();}/**
 * Draw an equilateral triangle standing on a vertex.
 * @param ctx - The context this shape will be rendered to.
 * @param x - The position of the center on the x axis.
 * @param y - The position of the center on the y axis.
 * @param r - Half of the length of the sides.
 * @remarks
 * http://en.wikipedia.org/wiki/Equilateral_triangle
 */function drawTriangleDown(ctx,x,y,r){ctx.beginPath();// the change in radius and the offset is here to center the shape
r*=1.15;y-=0.275*r;const s=r*2;const s2=s/2;const ir=Math.sqrt(3)/6*s;// radius of inner circle
const h=Math.sqrt(s*s-s2*s2);// height
ctx.moveTo(x,y+(h-ir));ctx.lineTo(x+s2,y-ir);ctx.lineTo(x-s2,y-ir);ctx.lineTo(x,y+(h-ir));ctx.closePath();}/**
 * Draw a star.
 * @param ctx - The context this shape will be rendered to.
 * @param x - The position of the center on the x axis.
 * @param y - The position of the center on the y axis.
 * @param r - The outer radius of the star.
 */function drawStar(ctx,x,y,r){// http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
ctx.beginPath();// the change in radius and the offset is here to center the shape
r*=0.82;y+=0.1*r;for(let n=0;n<10;n++){const radius=n%2===0?r*1.3:r*0.5;ctx.lineTo(x+radius*Math.sin(n*2*Math.PI/10),y-radius*Math.cos(n*2*Math.PI/10));}ctx.closePath();}/**
 * Draw a diamond.
 * @param ctx - The context this shape will be rendered to.
 * @param x - The position of the center on the x axis.
 * @param y - The position of the center on the y axis.
 * @param r - Half of the width and height of the diamond.
 * @remarks
 * http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
 */function drawDiamond(ctx,x,y,r){ctx.beginPath();ctx.lineTo(x,y+r);ctx.lineTo(x+r,y);ctx.lineTo(x,y-r);ctx.lineTo(x-r,y);ctx.closePath();}/**
 * Draw a rectangle with rounded corners.
 * @param ctx - The context this shape will be rendered to.
 * @param x - The position of the center on the x axis.
 * @param y - The position of the center on the y axis.
 * @param w - The width of the rectangle.
 * @param h - The height of the rectangle.
 * @param r - The radius of the corners.
 * @remarks
 * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
 */function drawRoundRect(ctx,x,y,w,h,r){const r2d=Math.PI/180;if(w-2*r<0){r=w/2;}//ensure that the radius isn't too large for x
if(h-2*r<0){r=h/2;}//ensure that the radius isn't too large for y
ctx.beginPath();ctx.moveTo(x+r,y);ctx.lineTo(x+w-r,y);ctx.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);ctx.lineTo(x+w,y+h-r);ctx.arc(x+w-r,y+h-r,r,0,r2d*90,false);ctx.lineTo(x+r,y+h);ctx.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);ctx.lineTo(x,y+r);ctx.arc(x+r,y+r,r,r2d*180,r2d*270,false);ctx.closePath();}/**
 * Draw an ellipse.
 * @param ctx - The context this shape will be rendered to.
 * @param x - The position of the center on the x axis.
 * @param y - The position of the center on the y axis.
 * @param w - The width of the ellipse.
 * @param h - The height of the ellipse.
 * @remarks
 * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
 *
 * Postfix '_vis' added to discern it from standard method ellipse().
 */function drawEllipse(ctx,x,y,w,h){const kappa=0.5522848,ox=w/2*kappa,// control point offset horizontal
oy=h/2*kappa,// control point offset vertical
xe=x+w,// x-end
ye=y+h,// y-end
xm=x+w/2,// x-middle
ym=y+h/2;// y-middle
ctx.beginPath();ctx.moveTo(x,ym);ctx.bezierCurveTo(x,ym-oy,xm-ox,y,xm,y);ctx.bezierCurveTo(xm+ox,y,xe,ym-oy,xe,ym);ctx.bezierCurveTo(xe,ym+oy,xm+ox,ye,xm,ye);ctx.bezierCurveTo(xm-ox,ye,x,ym+oy,x,ym);ctx.closePath();}/**
 * Draw an isometric cylinder.
 * @param ctx - The context this shape will be rendered to.
 * @param x - The position of the center on the x axis.
 * @param y - The position of the center on the y axis.
 * @param w - The width of the database.
 * @param h - The height of the database.
 * @remarks
 * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
 */function drawDatabase(ctx,x,y,w,h){const f=1/3;const wEllipse=w;const hEllipse=h*f;const kappa=0.5522848,ox=wEllipse/2*kappa,// control point offset horizontal
oy=hEllipse/2*kappa,// control point offset vertical
xe=x+wEllipse,// x-end
ye=y+hEllipse,// y-end
xm=x+wEllipse/2,// x-middle
ym=y+hEllipse/2,// y-middle
ymb=y+(h-hEllipse/2),// y-midlle, bottom ellipse
yeb=y+h;// y-end, bottom ellipse
ctx.beginPath();ctx.moveTo(xe,ym);ctx.bezierCurveTo(xe,ym+oy,xm+ox,ye,xm,ye);ctx.bezierCurveTo(xm-ox,ye,x,ym+oy,x,ym);ctx.bezierCurveTo(x,ym-oy,xm-ox,y,xm,y);ctx.bezierCurveTo(xm+ox,y,xe,ym-oy,xe,ym);ctx.lineTo(xe,ymb);ctx.bezierCurveTo(xe,ymb+oy,xm+ox,yeb,xm,yeb);ctx.bezierCurveTo(xm-ox,yeb,x,ymb+oy,x,ymb);ctx.lineTo(x,ym);}/**
 * Draw a dashed line.
 * @param ctx - The context this shape will be rendered to.
 * @param x - The start position on the x axis.
 * @param y - The start position on the y axis.
 * @param x2 - The end position on the x axis.
 * @param y2 - The end position on the y axis.
 * @param pattern - List of lengths starting with line and then alternating between space and line.
 * @author David Jordan
 * @remarks
 * date 2012-08-08
 * http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
 */function drawDashedLine(ctx,x,y,x2,y2,pattern){ctx.beginPath();ctx.moveTo(x,y);const patternLength=pattern.length;const dx=x2-x;const dy=y2-y;const slope=dy/dx;let distRemaining=Math.sqrt(dx*dx+dy*dy);let patternIndex=0;let draw=true;let xStep=0;let dashLength=+pattern[0];while(distRemaining>=0.1){dashLength=+pattern[patternIndex++%patternLength];if(dashLength>distRemaining){dashLength=distRemaining;}xStep=Math.sqrt(dashLength*dashLength/(1+slope*slope));xStep=dx<0?-xStep:xStep;x+=xStep;y+=slope*xStep;if(draw===true){ctx.lineTo(x,y);}else {ctx.moveTo(x,y);}distRemaining-=dashLength;draw=!draw;}}/**
 * Draw a hexagon.
 * @param ctx - The context this shape will be rendered to.
 * @param x - The position of the center on the x axis.
 * @param y - The position of the center on the y axis.
 * @param r - The radius of the hexagon.
 */function drawHexagon(ctx,x,y,r){ctx.beginPath();const sides=6;const a=Math.PI*2/sides;ctx.moveTo(x+r,y);for(let i=1;i<sides;i++){ctx.lineTo(x+r*Math.cos(a*i),y+r*Math.sin(a*i));}ctx.closePath();}const shapeMap={circle:drawCircle,dashedLine:drawDashedLine,database:drawDatabase,diamond:drawDiamond,ellipse:drawEllipse,ellipse_vis:drawEllipse,hexagon:drawHexagon,roundRect:drawRoundRect,square:drawSquare,star:drawStar,triangle:drawTriangle,triangleDown:drawTriangleDown};/**
 * Returns either custom or native drawing function base on supplied name.
 * @param name - The name of the function. Either the name of a
 * CanvasRenderingContext2D property or an export from shapes.ts without the
 * draw prefix.
 * @returns The function that can be used for rendering. In case of native
 * CanvasRenderingContext2D function the API is normalized to
 * `(ctx: CanvasRenderingContext2D, ...originalArgs) => void`.
 */function getShape(name){if(Object.prototype.hasOwnProperty.call(shapeMap,name)){return shapeMap[name];}else {return function(ctx){for(var _len=arguments.length,args=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){args[_key-1]=arguments[_key];}CanvasRenderingContext2D.prototype[name].call(ctx,args);};}}var componentEmitter={exports:{}};var hasRequiredComponentEmitter;function requireComponentEmitter(){if(hasRequiredComponentEmitter)return componentEmitter.exports;hasRequiredComponentEmitter=1;(function(module){/**
		 * Expose `Emitter`.
		 */{module.exports=Emitter;}/**
		 * Initialize a new `Emitter`.
		 *
		 * @api public
		 */function Emitter(obj){if(obj)return mixin(obj);}/**
		 * Mixin the emitter properties.
		 *
		 * @param {Object} obj
		 * @return {Object}
		 * @api private
		 */function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key];}return obj;}/**
		 * Listen on the given `event` with `fn`.
		 *
		 * @param {String} event
		 * @param {Function} fn
		 * @return {Emitter}
		 * @api public
		 */Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks['$'+event]=this._callbacks['$'+event]||[]).push(fn);return this;};/**
		 * Adds an `event` listener that will be invoked a single
		 * time then automatically removed.
		 *
		 * @param {String} event
		 * @param {Function} fn
		 * @return {Emitter}
		 * @api public
		 */Emitter.prototype.once=function(event,fn){function on(){this.off(event,on);fn.apply(this,arguments);}on.fn=fn;this.on(event,on);return this;};/**
		 * Remove the given callback for `event` or all
		 * registered callbacks.
		 *
		 * @param {String} event
		 * @param {Function} fn
		 * @return {Emitter}
		 * @api public
		 */Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};// all
if(0==arguments.length){this._callbacks={};return this;}// specific event
var callbacks=this._callbacks['$'+event];if(!callbacks)return this;// remove all handlers
if(1==arguments.length){delete this._callbacks['$'+event];return this;}// remove specific handler
var cb;for(var i=0;i<callbacks.length;i++){cb=callbacks[i];if(cb===fn||cb.fn===fn){callbacks.splice(i,1);break;}}// Remove event specific arrays for event types that no
// one is subscribed for to avoid memory leak.
if(callbacks.length===0){delete this._callbacks['$'+event];}return this;};/**
		 * Emit `event` with the given args.
		 *
		 * @param {String} event
		 * @param {Mixed} ...
		 * @return {Emitter}
		 */Emitter.prototype.emit=function(event){this._callbacks=this._callbacks||{};var args=new Array(arguments.length-1),callbacks=this._callbacks['$'+event];for(var i=1;i<arguments.length;i++){args[i-1]=arguments[i];}if(callbacks){callbacks=callbacks.slice(0);for(var i=0,len=callbacks.length;i<len;++i){callbacks[i].apply(this,args);}}return this;};/**
		 * Return array of callbacks for `event`.
		 *
		 * @param {String} event
		 * @return {Array}
		 * @api public
		 */Emitter.prototype.listeners=function(event){this._callbacks=this._callbacks||{};return this._callbacks['$'+event]||[];};/**
		 * Check if this emitter has `event` handlers.
		 *
		 * @param {String} event
		 * @return {Boolean}
		 * @api public
		 */Emitter.prototype.hasListeners=function(event){return !!this.listeners(event).length;};})(componentEmitter);return componentEmitter.exports;}var componentEmitterExports=requireComponentEmitter();var Emitter=/*@__PURE__*/getDefaultExportFromCjs(componentEmitterExports);var es_array_concat={};var isArray$3;var hasRequiredIsArray$3;function requireIsArray$3(){if(hasRequiredIsArray$3)return isArray$3;hasRequiredIsArray$3=1;var classof=/*@__PURE__*/requireClassofRaw();// `IsArray` abstract operation
// https://tc39.es/ecma262/#sec-isarray
// eslint-disable-next-line es/no-array-isarray -- safe
isArray$3=Array.isArray||function isArray(argument){return classof(argument)==='Array';};return isArray$3;}var doesNotExceedSafeInteger;var hasRequiredDoesNotExceedSafeInteger;function requireDoesNotExceedSafeInteger(){if(hasRequiredDoesNotExceedSafeInteger)return doesNotExceedSafeInteger;hasRequiredDoesNotExceedSafeInteger=1;var $TypeError=TypeError;var MAX_SAFE_INTEGER=0x1FFFFFFFFFFFFF;// 2 ** 53 - 1 == 9007199254740991
doesNotExceedSafeInteger=function(it){if(it>MAX_SAFE_INTEGER)throw $TypeError('Maximum allowed index exceeded');return it;};return doesNotExceedSafeInteger;}var createProperty;var hasRequiredCreateProperty;function requireCreateProperty(){if(hasRequiredCreateProperty)return createProperty;hasRequiredCreateProperty=1;var DESCRIPTORS=/*@__PURE__*/requireDescriptors();var definePropertyModule=/*@__PURE__*/requireObjectDefineProperty();var createPropertyDescriptor=/*@__PURE__*/requireCreatePropertyDescriptor();createProperty=function(object,key,value){if(DESCRIPTORS)definePropertyModule.f(object,key,createPropertyDescriptor(0,value));else object[key]=value;};return createProperty;}var toStringTagSupport;var hasRequiredToStringTagSupport;function requireToStringTagSupport(){if(hasRequiredToStringTagSupport)return toStringTagSupport;hasRequiredToStringTagSupport=1;var wellKnownSymbol=/*@__PURE__*/requireWellKnownSymbol();var TO_STRING_TAG=wellKnownSymbol('toStringTag');var test={};test[TO_STRING_TAG]='z';toStringTagSupport=String(test)==='[object z]';return toStringTagSupport;}var classof;var hasRequiredClassof;function requireClassof(){if(hasRequiredClassof)return classof;hasRequiredClassof=1;var TO_STRING_TAG_SUPPORT=/*@__PURE__*/requireToStringTagSupport();var isCallable=/*@__PURE__*/requireIsCallable();var classofRaw=/*@__PURE__*/requireClassofRaw();var wellKnownSymbol=/*@__PURE__*/requireWellKnownSymbol();var TO_STRING_TAG=wellKnownSymbol('toStringTag');var $Object=Object;// ES3 wrong here
var CORRECT_ARGUMENTS=classofRaw(function(){return arguments;}())==='Arguments';// fallback for IE11 Script Access Denied error
var tryGet=function(it,key){try{return it[key];}catch(error){/* empty */}};// getting tag from ES6+ `Object.prototype.toString`
classof=TO_STRING_TAG_SUPPORT?classofRaw:function(it){var O,tag,result;return it===undefined?'Undefined':it===null?'Null'// @@toStringTag case
:typeof(tag=tryGet(O=$Object(it),TO_STRING_TAG))=='string'?tag// builtinTag case
:CORRECT_ARGUMENTS?classofRaw(O)// ES3 arguments fallback
:(result=classofRaw(O))==='Object'&&isCallable(O.callee)?'Arguments':result;};return classof;}var inspectSource;var hasRequiredInspectSource;function requireInspectSource(){if(hasRequiredInspectSource)return inspectSource;hasRequiredInspectSource=1;var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var isCallable=/*@__PURE__*/requireIsCallable();var store=/*@__PURE__*/requireSharedStore();var functionToString=uncurryThis(Function.toString);// this helper broken in `core-js@3.4.1-3.4.4`, so we can't use `shared` helper
if(!isCallable(store.inspectSource)){store.inspectSource=function(it){return functionToString(it);};}inspectSource=store.inspectSource;return inspectSource;}var isConstructor;var hasRequiredIsConstructor;function requireIsConstructor(){if(hasRequiredIsConstructor)return isConstructor;hasRequiredIsConstructor=1;var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var fails=/*@__PURE__*/requireFails();var isCallable=/*@__PURE__*/requireIsCallable();var classof=/*@__PURE__*/requireClassof();var getBuiltIn=/*@__PURE__*/requireGetBuiltIn();var inspectSource=/*@__PURE__*/requireInspectSource();var noop=function(){/* empty */};var construct=getBuiltIn('Reflect','construct');var constructorRegExp=/^\s*(?:class|function)\b/;var exec=uncurryThis(constructorRegExp.exec);var INCORRECT_TO_STRING=!constructorRegExp.test(noop);var isConstructorModern=function isConstructor(argument){if(!isCallable(argument))return false;try{construct(noop,[],argument);return true;}catch(error){return false;}};var isConstructorLegacy=function isConstructor(argument){if(!isCallable(argument))return false;switch(classof(argument)){case 'AsyncFunction':case 'GeneratorFunction':case 'AsyncGeneratorFunction':return false;}try{// we can't check .prototype since constructors produced by .bind haven't it
// `Function#toString` throws on some built-it function in some legacy engines
// (for example, `DOMQuad` and similar in FF41-)
return INCORRECT_TO_STRING||!!exec(constructorRegExp,inspectSource(argument));}catch(error){return true;}};isConstructorLegacy.sham=true;// `IsConstructor` abstract operation
// https://tc39.es/ecma262/#sec-isconstructor
isConstructor=!construct||fails(function(){var called;return isConstructorModern(isConstructorModern.call)||!isConstructorModern(Object)||!isConstructorModern(function(){called=true;})||called;})?isConstructorLegacy:isConstructorModern;return isConstructor;}var arraySpeciesConstructor;var hasRequiredArraySpeciesConstructor;function requireArraySpeciesConstructor(){if(hasRequiredArraySpeciesConstructor)return arraySpeciesConstructor;hasRequiredArraySpeciesConstructor=1;var isArray=/*@__PURE__*/requireIsArray$3();var isConstructor=/*@__PURE__*/requireIsConstructor();var isObject=/*@__PURE__*/requireIsObject();var wellKnownSymbol=/*@__PURE__*/requireWellKnownSymbol();var SPECIES=wellKnownSymbol('species');var $Array=Array;// a part of `ArraySpeciesCreate` abstract operation
// https://tc39.es/ecma262/#sec-arrayspeciescreate
arraySpeciesConstructor=function(originalArray){var C;if(isArray(originalArray)){C=originalArray.constructor;// cross-realm fallback
if(isConstructor(C)&&(C===$Array||isArray(C.prototype)))C=undefined;else if(isObject(C)){C=C[SPECIES];if(C===null)C=undefined;}}return C===undefined?$Array:C;};return arraySpeciesConstructor;}var arraySpeciesCreate;var hasRequiredArraySpeciesCreate;function requireArraySpeciesCreate(){if(hasRequiredArraySpeciesCreate)return arraySpeciesCreate;hasRequiredArraySpeciesCreate=1;var arraySpeciesConstructor=/*@__PURE__*/requireArraySpeciesConstructor();// `ArraySpeciesCreate` abstract operation
// https://tc39.es/ecma262/#sec-arrayspeciescreate
arraySpeciesCreate=function(originalArray,length){return new(arraySpeciesConstructor(originalArray))(length===0?0:length);};return arraySpeciesCreate;}var arrayMethodHasSpeciesSupport;var hasRequiredArrayMethodHasSpeciesSupport;function requireArrayMethodHasSpeciesSupport(){if(hasRequiredArrayMethodHasSpeciesSupport)return arrayMethodHasSpeciesSupport;hasRequiredArrayMethodHasSpeciesSupport=1;var fails=/*@__PURE__*/requireFails();var wellKnownSymbol=/*@__PURE__*/requireWellKnownSymbol();var V8_VERSION=/*@__PURE__*/requireEnvironmentV8Version();var SPECIES=wellKnownSymbol('species');arrayMethodHasSpeciesSupport=function(METHOD_NAME){// We can't use this feature detection in V8 since it causes
// deoptimization and serious performance degradation
// https://github.com/zloirock/core-js/issues/677
return V8_VERSION>=51||!fails(function(){var array=[];var constructor=array.constructor={};constructor[SPECIES]=function(){return {foo:1};};return array[METHOD_NAME](Boolean).foo!==1;});};return arrayMethodHasSpeciesSupport;}var hasRequiredEs_array_concat;function requireEs_array_concat(){if(hasRequiredEs_array_concat)return es_array_concat;hasRequiredEs_array_concat=1;var $=/*@__PURE__*/require_export();var fails=/*@__PURE__*/requireFails();var isArray=/*@__PURE__*/requireIsArray$3();var isObject=/*@__PURE__*/requireIsObject();var toObject=/*@__PURE__*/requireToObject();var lengthOfArrayLike=/*@__PURE__*/requireLengthOfArrayLike();var doesNotExceedSafeInteger=/*@__PURE__*/requireDoesNotExceedSafeInteger();var createProperty=/*@__PURE__*/requireCreateProperty();var arraySpeciesCreate=/*@__PURE__*/requireArraySpeciesCreate();var arrayMethodHasSpeciesSupport=/*@__PURE__*/requireArrayMethodHasSpeciesSupport();var wellKnownSymbol=/*@__PURE__*/requireWellKnownSymbol();var V8_VERSION=/*@__PURE__*/requireEnvironmentV8Version();var IS_CONCAT_SPREADABLE=wellKnownSymbol('isConcatSpreadable');// We can't use this feature detection in V8 since it causes
// deoptimization and serious performance degradation
// https://github.com/zloirock/core-js/issues/679
var IS_CONCAT_SPREADABLE_SUPPORT=V8_VERSION>=51||!fails(function(){var array=[];array[IS_CONCAT_SPREADABLE]=false;return array.concat()[0]!==array;});var isConcatSpreadable=function(O){if(!isObject(O))return false;var spreadable=O[IS_CONCAT_SPREADABLE];return spreadable!==undefined?!!spreadable:isArray(O);};var FORCED=!IS_CONCAT_SPREADABLE_SUPPORT||!arrayMethodHasSpeciesSupport('concat');// `Array.prototype.concat` method
// https://tc39.es/ecma262/#sec-array.prototype.concat
// with adding support of @@isConcatSpreadable and @@species
$({target:'Array',proto:true,arity:1,forced:FORCED},{// eslint-disable-next-line no-unused-vars -- required for `.length`
concat:function concat(arg){var O=toObject(this);var A=arraySpeciesCreate(O,0);var n=0;var i,k,length,len,E;for(i=-1,length=arguments.length;i<length;i++){E=i===-1?O:arguments[i];if(isConcatSpreadable(E)){len=lengthOfArrayLike(E);doesNotExceedSafeInteger(n+len);for(k=0;k<len;k++,n++)if(k in E)createProperty(A,n,E[k]);}else {doesNotExceedSafeInteger(n+1);createProperty(A,n++,E);}}A.length=n;return A;}});return es_array_concat;}var es_symbol={};var es_symbol_constructor={};var toString;var hasRequiredToString;function requireToString(){if(hasRequiredToString)return toString;hasRequiredToString=1;var classof=/*@__PURE__*/requireClassof();var $String=String;toString=function(argument){if(classof(argument)==='Symbol')throw new TypeError('Cannot convert a Symbol value to a string');return $String(argument);};return toString;}var objectDefineProperties={};var hasRequiredObjectDefineProperties;function requireObjectDefineProperties(){if(hasRequiredObjectDefineProperties)return objectDefineProperties;hasRequiredObjectDefineProperties=1;var DESCRIPTORS=/*@__PURE__*/requireDescriptors();var V8_PROTOTYPE_DEFINE_BUG=/*@__PURE__*/requireV8PrototypeDefineBug();var definePropertyModule=/*@__PURE__*/requireObjectDefineProperty();var anObject=/*@__PURE__*/requireAnObject();var toIndexedObject=/*@__PURE__*/requireToIndexedObject();var objectKeys=/*@__PURE__*/requireObjectKeys();// `Object.defineProperties` method
// https://tc39.es/ecma262/#sec-object.defineproperties
// eslint-disable-next-line es/no-object-defineproperties -- safe
objectDefineProperties.f=DESCRIPTORS&&!V8_PROTOTYPE_DEFINE_BUG?Object.defineProperties:function defineProperties(O,Properties){anObject(O);var props=toIndexedObject(Properties);var keys=objectKeys(Properties);var length=keys.length;var index=0;var key;while(length>index)definePropertyModule.f(O,key=keys[index++],props[key]);return O;};return objectDefineProperties;}var html;var hasRequiredHtml;function requireHtml(){if(hasRequiredHtml)return html;hasRequiredHtml=1;var getBuiltIn=/*@__PURE__*/requireGetBuiltIn();html=getBuiltIn('document','documentElement');return html;}var sharedKey;var hasRequiredSharedKey;function requireSharedKey(){if(hasRequiredSharedKey)return sharedKey;hasRequiredSharedKey=1;var shared=/*@__PURE__*/requireShared();var uid=/*@__PURE__*/requireUid();var keys=shared('keys');sharedKey=function(key){return keys[key]||(keys[key]=uid(key));};return sharedKey;}var objectCreate;var hasRequiredObjectCreate;function requireObjectCreate(){if(hasRequiredObjectCreate)return objectCreate;hasRequiredObjectCreate=1;/* global ActiveXObject -- old IE, WSH */var anObject=/*@__PURE__*/requireAnObject();var definePropertiesModule=/*@__PURE__*/requireObjectDefineProperties();var enumBugKeys=/*@__PURE__*/requireEnumBugKeys();var hiddenKeys=/*@__PURE__*/requireHiddenKeys();var html=/*@__PURE__*/requireHtml();var documentCreateElement=/*@__PURE__*/requireDocumentCreateElement();var sharedKey=/*@__PURE__*/requireSharedKey();var GT='>';var LT='<';var PROTOTYPE='prototype';var SCRIPT='script';var IE_PROTO=sharedKey('IE_PROTO');var EmptyConstructor=function(){/* empty */};var scriptTag=function(content){return LT+SCRIPT+GT+content+LT+'/'+SCRIPT+GT;};// Create object with fake `null` prototype: use ActiveX Object with cleared prototype
var NullProtoObjectViaActiveX=function(activeXDocument){activeXDocument.write(scriptTag(''));activeXDocument.close();var temp=activeXDocument.parentWindow.Object;// eslint-disable-next-line no-useless-assignment -- avoid memory leak
activeXDocument=null;return temp;};// Create object with fake `null` prototype: use iframe Object with cleared prototype
var NullProtoObjectViaIFrame=function(){// Thrash, waste and sodomy: IE GC bug
var iframe=documentCreateElement('iframe');var JS='java'+SCRIPT+':';var iframeDocument;iframe.style.display='none';html.appendChild(iframe);// https://github.com/zloirock/core-js/issues/475
iframe.src=String(JS);iframeDocument=iframe.contentWindow.document;iframeDocument.open();iframeDocument.write(scriptTag('document.F=Object'));iframeDocument.close();return iframeDocument.F;};// Check for document.domain and active x support
// No need to use active x approach when document.domain is not set
// see https://github.com/es-shims/es5-shim/issues/150
// variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346
// avoid IE GC bug
var activeXDocument;var NullProtoObject=function(){try{activeXDocument=new ActiveXObject('htmlfile');}catch(error){/* ignore */}NullProtoObject=typeof document!='undefined'?document.domain&&activeXDocument?NullProtoObjectViaActiveX(activeXDocument)// old IE
:NullProtoObjectViaIFrame():NullProtoObjectViaActiveX(activeXDocument);// WSH
var length=enumBugKeys.length;while(length--)delete NullProtoObject[PROTOTYPE][enumBugKeys[length]];return NullProtoObject();};hiddenKeys[IE_PROTO]=true;// `Object.create` method
// https://tc39.es/ecma262/#sec-object.create
// eslint-disable-next-line es/no-object-create -- safe
objectCreate=Object.create||function create(O,Properties){var result;if(O!==null){EmptyConstructor[PROTOTYPE]=anObject(O);result=new EmptyConstructor();EmptyConstructor[PROTOTYPE]=null;// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO]=O;}else result=NullProtoObject();return Properties===undefined?result:definePropertiesModule.f(result,Properties);};return objectCreate;}var objectGetOwnPropertyNames={};var hasRequiredObjectGetOwnPropertyNames;function requireObjectGetOwnPropertyNames(){if(hasRequiredObjectGetOwnPropertyNames)return objectGetOwnPropertyNames;hasRequiredObjectGetOwnPropertyNames=1;var internalObjectKeys=/*@__PURE__*/requireObjectKeysInternal();var enumBugKeys=/*@__PURE__*/requireEnumBugKeys();var hiddenKeys=enumBugKeys.concat('length','prototype');// `Object.getOwnPropertyNames` method
// https://tc39.es/ecma262/#sec-object.getownpropertynames
// eslint-disable-next-line es/no-object-getownpropertynames -- safe
objectGetOwnPropertyNames.f=Object.getOwnPropertyNames||function getOwnPropertyNames(O){return internalObjectKeys(O,hiddenKeys);};return objectGetOwnPropertyNames;}var objectGetOwnPropertyNamesExternal={};var hasRequiredObjectGetOwnPropertyNamesExternal;function requireObjectGetOwnPropertyNamesExternal(){if(hasRequiredObjectGetOwnPropertyNamesExternal)return objectGetOwnPropertyNamesExternal;hasRequiredObjectGetOwnPropertyNamesExternal=1;/* eslint-disable es/no-object-getownpropertynames -- safe */var classof=/*@__PURE__*/requireClassofRaw();var toIndexedObject=/*@__PURE__*/requireToIndexedObject();var $getOwnPropertyNames=/*@__PURE__*/requireObjectGetOwnPropertyNames().f;var arraySlice=/*@__PURE__*/requireArraySlice();var windowNames=typeof window=='object'&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];var getWindowNames=function(it){try{return $getOwnPropertyNames(it);}catch(error){return arraySlice(windowNames);}};// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
objectGetOwnPropertyNamesExternal.f=function getOwnPropertyNames(it){return windowNames&&classof(it)==='Window'?getWindowNames(it):$getOwnPropertyNames(toIndexedObject(it));};return objectGetOwnPropertyNamesExternal;}var defineBuiltIn;var hasRequiredDefineBuiltIn;function requireDefineBuiltIn(){if(hasRequiredDefineBuiltIn)return defineBuiltIn;hasRequiredDefineBuiltIn=1;var createNonEnumerableProperty=/*@__PURE__*/requireCreateNonEnumerableProperty();defineBuiltIn=function(target,key,value,options){if(options&&options.enumerable)target[key]=value;else createNonEnumerableProperty(target,key,value);return target;};return defineBuiltIn;}var defineBuiltInAccessor;var hasRequiredDefineBuiltInAccessor;function requireDefineBuiltInAccessor(){if(hasRequiredDefineBuiltInAccessor)return defineBuiltInAccessor;hasRequiredDefineBuiltInAccessor=1;var defineProperty=/*@__PURE__*/requireObjectDefineProperty();defineBuiltInAccessor=function(target,name,descriptor){return defineProperty.f(target,name,descriptor);};return defineBuiltInAccessor;}var wellKnownSymbolWrapped={};var hasRequiredWellKnownSymbolWrapped;function requireWellKnownSymbolWrapped(){if(hasRequiredWellKnownSymbolWrapped)return wellKnownSymbolWrapped;hasRequiredWellKnownSymbolWrapped=1;var wellKnownSymbol=/*@__PURE__*/requireWellKnownSymbol();wellKnownSymbolWrapped.f=wellKnownSymbol;return wellKnownSymbolWrapped;}var wellKnownSymbolDefine;var hasRequiredWellKnownSymbolDefine;function requireWellKnownSymbolDefine(){if(hasRequiredWellKnownSymbolDefine)return wellKnownSymbolDefine;hasRequiredWellKnownSymbolDefine=1;var path=/*@__PURE__*/requirePath();var hasOwn=/*@__PURE__*/requireHasOwnProperty();var wrappedWellKnownSymbolModule=/*@__PURE__*/requireWellKnownSymbolWrapped();var defineProperty=/*@__PURE__*/requireObjectDefineProperty().f;wellKnownSymbolDefine=function(NAME){var Symbol=path.Symbol||(path.Symbol={});if(!hasOwn(Symbol,NAME))defineProperty(Symbol,NAME,{value:wrappedWellKnownSymbolModule.f(NAME)});};return wellKnownSymbolDefine;}var symbolDefineToPrimitive;var hasRequiredSymbolDefineToPrimitive;function requireSymbolDefineToPrimitive(){if(hasRequiredSymbolDefineToPrimitive)return symbolDefineToPrimitive;hasRequiredSymbolDefineToPrimitive=1;var call=/*@__PURE__*/requireFunctionCall();var getBuiltIn=/*@__PURE__*/requireGetBuiltIn();var wellKnownSymbol=/*@__PURE__*/requireWellKnownSymbol();var defineBuiltIn=/*@__PURE__*/requireDefineBuiltIn();symbolDefineToPrimitive=function(){var Symbol=getBuiltIn('Symbol');var SymbolPrototype=Symbol&&Symbol.prototype;var valueOf=SymbolPrototype&&SymbolPrototype.valueOf;var TO_PRIMITIVE=wellKnownSymbol('toPrimitive');if(SymbolPrototype&&!SymbolPrototype[TO_PRIMITIVE]){// `Symbol.prototype[@@toPrimitive]` method
// https://tc39.es/ecma262/#sec-symbol.prototype-@@toprimitive
// eslint-disable-next-line no-unused-vars -- required for .length
defineBuiltIn(SymbolPrototype,TO_PRIMITIVE,function(hint){return call(valueOf,this);},{arity:1});}};return symbolDefineToPrimitive;}var objectToString;var hasRequiredObjectToString;function requireObjectToString(){if(hasRequiredObjectToString)return objectToString;hasRequiredObjectToString=1;var TO_STRING_TAG_SUPPORT=/*@__PURE__*/requireToStringTagSupport();var classof=/*@__PURE__*/requireClassof();// `Object.prototype.toString` method implementation
// https://tc39.es/ecma262/#sec-object.prototype.tostring
objectToString=TO_STRING_TAG_SUPPORT?{}.toString:function toString(){return '[object '+classof(this)+']';};return objectToString;}var setToStringTag;var hasRequiredSetToStringTag;function requireSetToStringTag(){if(hasRequiredSetToStringTag)return setToStringTag;hasRequiredSetToStringTag=1;var TO_STRING_TAG_SUPPORT=/*@__PURE__*/requireToStringTagSupport();var defineProperty=/*@__PURE__*/requireObjectDefineProperty().f;var createNonEnumerableProperty=/*@__PURE__*/requireCreateNonEnumerableProperty();var hasOwn=/*@__PURE__*/requireHasOwnProperty();var toString=/*@__PURE__*/requireObjectToString();var wellKnownSymbol=/*@__PURE__*/requireWellKnownSymbol();var TO_STRING_TAG=wellKnownSymbol('toStringTag');setToStringTag=function(it,TAG,STATIC,SET_METHOD){var target=STATIC?it:it&&it.prototype;if(target){if(!hasOwn(target,TO_STRING_TAG)){defineProperty(target,TO_STRING_TAG,{configurable:true,value:TAG});}if(SET_METHOD&&!TO_STRING_TAG_SUPPORT){createNonEnumerableProperty(target,'toString',toString);}}};return setToStringTag;}var weakMapBasicDetection;var hasRequiredWeakMapBasicDetection;function requireWeakMapBasicDetection(){if(hasRequiredWeakMapBasicDetection)return weakMapBasicDetection;hasRequiredWeakMapBasicDetection=1;var globalThis=/*@__PURE__*/requireGlobalThis();var isCallable=/*@__PURE__*/requireIsCallable();var WeakMap=globalThis.WeakMap;weakMapBasicDetection=isCallable(WeakMap)&&/native code/.test(String(WeakMap));return weakMapBasicDetection;}var internalState;var hasRequiredInternalState;function requireInternalState(){if(hasRequiredInternalState)return internalState;hasRequiredInternalState=1;var NATIVE_WEAK_MAP=/*@__PURE__*/requireWeakMapBasicDetection();var globalThis=/*@__PURE__*/requireGlobalThis();var isObject=/*@__PURE__*/requireIsObject();var createNonEnumerableProperty=/*@__PURE__*/requireCreateNonEnumerableProperty();var hasOwn=/*@__PURE__*/requireHasOwnProperty();var shared=/*@__PURE__*/requireSharedStore();var sharedKey=/*@__PURE__*/requireSharedKey();var hiddenKeys=/*@__PURE__*/requireHiddenKeys();var OBJECT_ALREADY_INITIALIZED='Object already initialized';var TypeError=globalThis.TypeError;var WeakMap=globalThis.WeakMap;var set,get,has;var enforce=function(it){return has(it)?get(it):set(it,{});};var getterFor=function(TYPE){return function(it){var state;if(!isObject(it)||(state=get(it)).type!==TYPE){throw new TypeError('Incompatible receiver, '+TYPE+' required');}return state;};};if(NATIVE_WEAK_MAP||shared.state){var store=shared.state||(shared.state=new WeakMap());/* eslint-disable no-self-assign -- prototype methods protection */store.get=store.get;store.has=store.has;store.set=store.set;/* eslint-enable no-self-assign -- prototype methods protection */set=function(it,metadata){if(store.has(it))throw new TypeError(OBJECT_ALREADY_INITIALIZED);metadata.facade=it;store.set(it,metadata);return metadata;};get=function(it){return store.get(it)||{};};has=function(it){return store.has(it);};}else {var STATE=sharedKey('state');hiddenKeys[STATE]=true;set=function(it,metadata){if(hasOwn(it,STATE))throw new TypeError(OBJECT_ALREADY_INITIALIZED);metadata.facade=it;createNonEnumerableProperty(it,STATE,metadata);return metadata;};get=function(it){return hasOwn(it,STATE)?it[STATE]:{};};has=function(it){return hasOwn(it,STATE);};}internalState={set:set,get:get,has:has,enforce:enforce,getterFor:getterFor};return internalState;}var arrayIteration;var hasRequiredArrayIteration;function requireArrayIteration(){if(hasRequiredArrayIteration)return arrayIteration;hasRequiredArrayIteration=1;var bind=/*@__PURE__*/requireFunctionBindContext();var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var IndexedObject=/*@__PURE__*/requireIndexedObject();var toObject=/*@__PURE__*/requireToObject();var lengthOfArrayLike=/*@__PURE__*/requireLengthOfArrayLike();var arraySpeciesCreate=/*@__PURE__*/requireArraySpeciesCreate();var push=uncurryThis([].push);// `Array.prototype.{ forEach, map, filter, some, every, find, findIndex, filterReject }` methods implementation
var createMethod=function(TYPE){var IS_MAP=TYPE===1;var IS_FILTER=TYPE===2;var IS_SOME=TYPE===3;var IS_EVERY=TYPE===4;var IS_FIND_INDEX=TYPE===6;var IS_FILTER_REJECT=TYPE===7;var NO_HOLES=TYPE===5||IS_FIND_INDEX;return function($this,callbackfn,that,specificCreate){var O=toObject($this);var self=IndexedObject(O);var length=lengthOfArrayLike(self);var boundFunction=bind(callbackfn,that);var index=0;var create=specificCreate||arraySpeciesCreate;var target=IS_MAP?create($this,length):IS_FILTER||IS_FILTER_REJECT?create($this,0):undefined;var value,result;for(;length>index;index++)if(NO_HOLES||index in self){value=self[index];result=boundFunction(value,index,O);if(TYPE){if(IS_MAP)target[index]=result;// map
else if(result)switch(TYPE){case 3:return true;// some
case 5:return value;// find
case 6:return index;// findIndex
case 2:push(target,value);// filter
}else switch(TYPE){case 4:return false;// every
case 7:push(target,value);// filterReject
}}}return IS_FIND_INDEX?-1:IS_SOME||IS_EVERY?IS_EVERY:target;};};arrayIteration={// `Array.prototype.forEach` method
// https://tc39.es/ecma262/#sec-array.prototype.foreach
forEach:createMethod(0),// `Array.prototype.map` method
// https://tc39.es/ecma262/#sec-array.prototype.map
map:createMethod(1),// `Array.prototype.filter` method
// https://tc39.es/ecma262/#sec-array.prototype.filter
filter:createMethod(2),// `Array.prototype.some` method
// https://tc39.es/ecma262/#sec-array.prototype.some
some:createMethod(3),// `Array.prototype.every` method
// https://tc39.es/ecma262/#sec-array.prototype.every
every:createMethod(4),// `Array.prototype.find` method
// https://tc39.es/ecma262/#sec-array.prototype.find
find:createMethod(5),// `Array.prototype.findIndex` method
// https://tc39.es/ecma262/#sec-array.prototype.findIndex
findIndex:createMethod(6),// `Array.prototype.filterReject` method
// https://github.com/tc39/proposal-array-filtering
filterReject:createMethod(7)};return arrayIteration;}var hasRequiredEs_symbol_constructor;function requireEs_symbol_constructor(){if(hasRequiredEs_symbol_constructor)return es_symbol_constructor;hasRequiredEs_symbol_constructor=1;var $=/*@__PURE__*/require_export();var globalThis=/*@__PURE__*/requireGlobalThis();var call=/*@__PURE__*/requireFunctionCall();var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var IS_PURE=/*@__PURE__*/requireIsPure();var DESCRIPTORS=/*@__PURE__*/requireDescriptors();var NATIVE_SYMBOL=/*@__PURE__*/requireSymbolConstructorDetection();var fails=/*@__PURE__*/requireFails();var hasOwn=/*@__PURE__*/requireHasOwnProperty();var isPrototypeOf=/*@__PURE__*/requireObjectIsPrototypeOf();var anObject=/*@__PURE__*/requireAnObject();var toIndexedObject=/*@__PURE__*/requireToIndexedObject();var toPropertyKey=/*@__PURE__*/requireToPropertyKey();var $toString=/*@__PURE__*/requireToString();var createPropertyDescriptor=/*@__PURE__*/requireCreatePropertyDescriptor();var nativeObjectCreate=/*@__PURE__*/requireObjectCreate();var objectKeys=/*@__PURE__*/requireObjectKeys();var getOwnPropertyNamesModule=/*@__PURE__*/requireObjectGetOwnPropertyNames();var getOwnPropertyNamesExternal=/*@__PURE__*/requireObjectGetOwnPropertyNamesExternal();var getOwnPropertySymbolsModule=/*@__PURE__*/requireObjectGetOwnPropertySymbols();var getOwnPropertyDescriptorModule=/*@__PURE__*/requireObjectGetOwnPropertyDescriptor();var definePropertyModule=/*@__PURE__*/requireObjectDefineProperty();var definePropertiesModule=/*@__PURE__*/requireObjectDefineProperties();var propertyIsEnumerableModule=/*@__PURE__*/requireObjectPropertyIsEnumerable();var defineBuiltIn=/*@__PURE__*/requireDefineBuiltIn();var defineBuiltInAccessor=/*@__PURE__*/requireDefineBuiltInAccessor();var shared=/*@__PURE__*/requireShared();var sharedKey=/*@__PURE__*/requireSharedKey();var hiddenKeys=/*@__PURE__*/requireHiddenKeys();var uid=/*@__PURE__*/requireUid();var wellKnownSymbol=/*@__PURE__*/requireWellKnownSymbol();var wrappedWellKnownSymbolModule=/*@__PURE__*/requireWellKnownSymbolWrapped();var defineWellKnownSymbol=/*@__PURE__*/requireWellKnownSymbolDefine();var defineSymbolToPrimitive=/*@__PURE__*/requireSymbolDefineToPrimitive();var setToStringTag=/*@__PURE__*/requireSetToStringTag();var InternalStateModule=/*@__PURE__*/requireInternalState();var $forEach=/*@__PURE__*/requireArrayIteration().forEach;var HIDDEN=sharedKey('hidden');var SYMBOL='Symbol';var PROTOTYPE='prototype';var setInternalState=InternalStateModule.set;var getInternalState=InternalStateModule.getterFor(SYMBOL);var ObjectPrototype=Object[PROTOTYPE];var $Symbol=globalThis.Symbol;var SymbolPrototype=$Symbol&&$Symbol[PROTOTYPE];var RangeError=globalThis.RangeError;var TypeError=globalThis.TypeError;var QObject=globalThis.QObject;var nativeGetOwnPropertyDescriptor=getOwnPropertyDescriptorModule.f;var nativeDefineProperty=definePropertyModule.f;var nativeGetOwnPropertyNames=getOwnPropertyNamesExternal.f;var nativePropertyIsEnumerable=propertyIsEnumerableModule.f;var push=uncurryThis([].push);var AllSymbols=shared('symbols');var ObjectPrototypeSymbols=shared('op-symbols');var WellKnownSymbolsStore=shared('wks');// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
var USE_SETTER=!QObject||!QObject[PROTOTYPE]||!QObject[PROTOTYPE].findChild;// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var fallbackDefineProperty=function(O,P,Attributes){var ObjectPrototypeDescriptor=nativeGetOwnPropertyDescriptor(ObjectPrototype,P);if(ObjectPrototypeDescriptor)delete ObjectPrototype[P];nativeDefineProperty(O,P,Attributes);if(ObjectPrototypeDescriptor&&O!==ObjectPrototype){nativeDefineProperty(ObjectPrototype,P,ObjectPrototypeDescriptor);}};var setSymbolDescriptor=DESCRIPTORS&&fails(function(){return nativeObjectCreate(nativeDefineProperty({},'a',{get:function(){return nativeDefineProperty(this,'a',{value:7}).a;}})).a!==7;})?fallbackDefineProperty:nativeDefineProperty;var wrap=function(tag,description){var symbol=AllSymbols[tag]=nativeObjectCreate(SymbolPrototype);setInternalState(symbol,{type:SYMBOL,tag:tag,description:description});if(!DESCRIPTORS)symbol.description=description;return symbol;};var $defineProperty=function defineProperty(O,P,Attributes){if(O===ObjectPrototype)$defineProperty(ObjectPrototypeSymbols,P,Attributes);anObject(O);var key=toPropertyKey(P);anObject(Attributes);if(hasOwn(AllSymbols,key)){if(!Attributes.enumerable){if(!hasOwn(O,HIDDEN))nativeDefineProperty(O,HIDDEN,createPropertyDescriptor(1,nativeObjectCreate(null)));O[HIDDEN][key]=true;}else {if(hasOwn(O,HIDDEN)&&O[HIDDEN][key])O[HIDDEN][key]=false;Attributes=nativeObjectCreate(Attributes,{enumerable:createPropertyDescriptor(0,false)});}return setSymbolDescriptor(O,key,Attributes);}return nativeDefineProperty(O,key,Attributes);};var $defineProperties=function defineProperties(O,Properties){anObject(O);var properties=toIndexedObject(Properties);var keys=objectKeys(properties).concat($getOwnPropertySymbols(properties));$forEach(keys,function(key){if(!DESCRIPTORS||call($propertyIsEnumerable,properties,key))$defineProperty(O,key,properties[key]);});return O;};var $create=function create(O,Properties){return Properties===undefined?nativeObjectCreate(O):$defineProperties(nativeObjectCreate(O),Properties);};var $propertyIsEnumerable=function propertyIsEnumerable(V){var P=toPropertyKey(V);var enumerable=call(nativePropertyIsEnumerable,this,P);if(this===ObjectPrototype&&hasOwn(AllSymbols,P)&&!hasOwn(ObjectPrototypeSymbols,P))return false;return enumerable||!hasOwn(this,P)||!hasOwn(AllSymbols,P)||hasOwn(this,HIDDEN)&&this[HIDDEN][P]?enumerable:true;};var $getOwnPropertyDescriptor=function getOwnPropertyDescriptor(O,P){var it=toIndexedObject(O);var key=toPropertyKey(P);if(it===ObjectPrototype&&hasOwn(AllSymbols,key)&&!hasOwn(ObjectPrototypeSymbols,key))return;var descriptor=nativeGetOwnPropertyDescriptor(it,key);if(descriptor&&hasOwn(AllSymbols,key)&&!(hasOwn(it,HIDDEN)&&it[HIDDEN][key])){descriptor.enumerable=true;}return descriptor;};var $getOwnPropertyNames=function getOwnPropertyNames(O){var names=nativeGetOwnPropertyNames(toIndexedObject(O));var result=[];$forEach(names,function(key){if(!hasOwn(AllSymbols,key)&&!hasOwn(hiddenKeys,key))push(result,key);});return result;};var $getOwnPropertySymbols=function(O){var IS_OBJECT_PROTOTYPE=O===ObjectPrototype;var names=nativeGetOwnPropertyNames(IS_OBJECT_PROTOTYPE?ObjectPrototypeSymbols:toIndexedObject(O));var result=[];$forEach(names,function(key){if(hasOwn(AllSymbols,key)&&(!IS_OBJECT_PROTOTYPE||hasOwn(ObjectPrototype,key))){push(result,AllSymbols[key]);}});return result;};// `Symbol` constructor
// https://tc39.es/ecma262/#sec-symbol-constructor
if(!NATIVE_SYMBOL){$Symbol=function Symbol(){if(isPrototypeOf(SymbolPrototype,this))throw new TypeError('Symbol is not a constructor');var description=!arguments.length||arguments[0]===undefined?undefined:$toString(arguments[0]);var tag=uid(description);var setter=function(value){var $this=this===undefined?globalThis:this;if($this===ObjectPrototype)call(setter,ObjectPrototypeSymbols,value);if(hasOwn($this,HIDDEN)&&hasOwn($this[HIDDEN],tag))$this[HIDDEN][tag]=false;var descriptor=createPropertyDescriptor(1,value);try{setSymbolDescriptor($this,tag,descriptor);}catch(error){if(!(error instanceof RangeError))throw error;fallbackDefineProperty($this,tag,descriptor);}};if(DESCRIPTORS&&USE_SETTER)setSymbolDescriptor(ObjectPrototype,tag,{configurable:true,set:setter});return wrap(tag,description);};SymbolPrototype=$Symbol[PROTOTYPE];defineBuiltIn(SymbolPrototype,'toString',function toString(){return getInternalState(this).tag;});defineBuiltIn($Symbol,'withoutSetter',function(description){return wrap(uid(description),description);});propertyIsEnumerableModule.f=$propertyIsEnumerable;definePropertyModule.f=$defineProperty;definePropertiesModule.f=$defineProperties;getOwnPropertyDescriptorModule.f=$getOwnPropertyDescriptor;getOwnPropertyNamesModule.f=getOwnPropertyNamesExternal.f=$getOwnPropertyNames;getOwnPropertySymbolsModule.f=$getOwnPropertySymbols;wrappedWellKnownSymbolModule.f=function(name){return wrap(wellKnownSymbol(name),name);};if(DESCRIPTORS){// https://tc39.es/ecma262/#sec-symbol.prototype.description
defineBuiltInAccessor(SymbolPrototype,'description',{configurable:true,get:function description(){return getInternalState(this).description;}});if(!IS_PURE){defineBuiltIn(ObjectPrototype,'propertyIsEnumerable',$propertyIsEnumerable,{unsafe:true});}}}$({global:true,constructor:true,wrap:true,forced:!NATIVE_SYMBOL,sham:!NATIVE_SYMBOL},{Symbol:$Symbol});$forEach(objectKeys(WellKnownSymbolsStore),function(name){defineWellKnownSymbol(name);});$({target:SYMBOL,stat:true,forced:!NATIVE_SYMBOL},{useSetter:function(){USE_SETTER=true;},useSimple:function(){USE_SETTER=false;}});$({target:'Object',stat:true,forced:!NATIVE_SYMBOL,sham:!DESCRIPTORS},{// `Object.create` method
// https://tc39.es/ecma262/#sec-object.create
create:$create,// `Object.defineProperty` method
// https://tc39.es/ecma262/#sec-object.defineproperty
defineProperty:$defineProperty,// `Object.defineProperties` method
// https://tc39.es/ecma262/#sec-object.defineproperties
defineProperties:$defineProperties,// `Object.getOwnPropertyDescriptor` method
// https://tc39.es/ecma262/#sec-object.getownpropertydescriptors
getOwnPropertyDescriptor:$getOwnPropertyDescriptor});$({target:'Object',stat:true,forced:!NATIVE_SYMBOL},{// `Object.getOwnPropertyNames` method
// https://tc39.es/ecma262/#sec-object.getownpropertynames
getOwnPropertyNames:$getOwnPropertyNames});// `Symbol.prototype[@@toPrimitive]` method
// https://tc39.es/ecma262/#sec-symbol.prototype-@@toprimitive
defineSymbolToPrimitive();// `Symbol.prototype[@@toStringTag]` property
// https://tc39.es/ecma262/#sec-symbol.prototype-@@tostringtag
setToStringTag($Symbol,SYMBOL);hiddenKeys[HIDDEN]=true;return es_symbol_constructor;}var es_symbol_for={};var symbolRegistryDetection;var hasRequiredSymbolRegistryDetection;function requireSymbolRegistryDetection(){if(hasRequiredSymbolRegistryDetection)return symbolRegistryDetection;hasRequiredSymbolRegistryDetection=1;var NATIVE_SYMBOL=/*@__PURE__*/requireSymbolConstructorDetection();/* eslint-disable es/no-symbol -- safe */symbolRegistryDetection=NATIVE_SYMBOL&&!!Symbol['for']&&!!Symbol.keyFor;return symbolRegistryDetection;}var hasRequiredEs_symbol_for;function requireEs_symbol_for(){if(hasRequiredEs_symbol_for)return es_symbol_for;hasRequiredEs_symbol_for=1;var $=/*@__PURE__*/require_export();var getBuiltIn=/*@__PURE__*/requireGetBuiltIn();var hasOwn=/*@__PURE__*/requireHasOwnProperty();var toString=/*@__PURE__*/requireToString();var shared=/*@__PURE__*/requireShared();var NATIVE_SYMBOL_REGISTRY=/*@__PURE__*/requireSymbolRegistryDetection();var StringToSymbolRegistry=shared('string-to-symbol-registry');var SymbolToStringRegistry=shared('symbol-to-string-registry');// `Symbol.for` method
// https://tc39.es/ecma262/#sec-symbol.for
$({target:'Symbol',stat:true,forced:!NATIVE_SYMBOL_REGISTRY},{'for':function(key){var string=toString(key);if(hasOwn(StringToSymbolRegistry,string))return StringToSymbolRegistry[string];var symbol=getBuiltIn('Symbol')(string);StringToSymbolRegistry[string]=symbol;SymbolToStringRegistry[symbol]=string;return symbol;}});return es_symbol_for;}var es_symbol_keyFor={};var hasRequiredEs_symbol_keyFor;function requireEs_symbol_keyFor(){if(hasRequiredEs_symbol_keyFor)return es_symbol_keyFor;hasRequiredEs_symbol_keyFor=1;var $=/*@__PURE__*/require_export();var hasOwn=/*@__PURE__*/requireHasOwnProperty();var isSymbol=/*@__PURE__*/requireIsSymbol();var tryToString=/*@__PURE__*/requireTryToString();var shared=/*@__PURE__*/requireShared();var NATIVE_SYMBOL_REGISTRY=/*@__PURE__*/requireSymbolRegistryDetection();var SymbolToStringRegistry=shared('symbol-to-string-registry');// `Symbol.keyFor` method
// https://tc39.es/ecma262/#sec-symbol.keyfor
$({target:'Symbol',stat:true,forced:!NATIVE_SYMBOL_REGISTRY},{keyFor:function keyFor(sym){if(!isSymbol(sym))throw new TypeError(tryToString(sym)+' is not a symbol');if(hasOwn(SymbolToStringRegistry,sym))return SymbolToStringRegistry[sym];}});return es_symbol_keyFor;}var es_json_stringify={};var getJsonReplacerFunction;var hasRequiredGetJsonReplacerFunction;function requireGetJsonReplacerFunction(){if(hasRequiredGetJsonReplacerFunction)return getJsonReplacerFunction;hasRequiredGetJsonReplacerFunction=1;var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var isArray=/*@__PURE__*/requireIsArray$3();var isCallable=/*@__PURE__*/requireIsCallable();var classof=/*@__PURE__*/requireClassofRaw();var toString=/*@__PURE__*/requireToString();var push=uncurryThis([].push);getJsonReplacerFunction=function(replacer){if(isCallable(replacer))return replacer;if(!isArray(replacer))return;var rawLength=replacer.length;var keys=[];for(var i=0;i<rawLength;i++){var element=replacer[i];if(typeof element=='string')push(keys,element);else if(typeof element=='number'||classof(element)==='Number'||classof(element)==='String')push(keys,toString(element));}var keysLength=keys.length;var root=true;return function(key,value){if(root){root=false;return value;}if(isArray(this))return value;for(var j=0;j<keysLength;j++)if(keys[j]===key)return value;};};return getJsonReplacerFunction;}var hasRequiredEs_json_stringify;function requireEs_json_stringify(){if(hasRequiredEs_json_stringify)return es_json_stringify;hasRequiredEs_json_stringify=1;var $=/*@__PURE__*/require_export();var getBuiltIn=/*@__PURE__*/requireGetBuiltIn();var apply=/*@__PURE__*/requireFunctionApply();var call=/*@__PURE__*/requireFunctionCall();var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var fails=/*@__PURE__*/requireFails();var isCallable=/*@__PURE__*/requireIsCallable();var isSymbol=/*@__PURE__*/requireIsSymbol();var arraySlice=/*@__PURE__*/requireArraySlice();var getReplacerFunction=/*@__PURE__*/requireGetJsonReplacerFunction();var NATIVE_SYMBOL=/*@__PURE__*/requireSymbolConstructorDetection();var $String=String;var $stringify=getBuiltIn('JSON','stringify');var exec=uncurryThis(/./.exec);var charAt=uncurryThis(''.charAt);var charCodeAt=uncurryThis(''.charCodeAt);var replace=uncurryThis(''.replace);var numberToString=uncurryThis(1.1.toString);var tester=/[\uD800-\uDFFF]/g;var low=/^[\uD800-\uDBFF]$/;var hi=/^[\uDC00-\uDFFF]$/;var WRONG_SYMBOLS_CONVERSION=!NATIVE_SYMBOL||fails(function(){var symbol=getBuiltIn('Symbol')('stringify detection');// MS Edge converts symbol values to JSON as {}
return $stringify([symbol])!=='[null]'// WebKit converts symbol values to JSON as null
||$stringify({a:symbol})!=='{}'// V8 throws on boxed symbols
||$stringify(Object(symbol))!=='{}';});// https://github.com/tc39/proposal-well-formed-stringify
var ILL_FORMED_UNICODE=fails(function(){return $stringify('\uDF06\uD834')!=='"\\udf06\\ud834"'||$stringify('\uDEAD')!=='"\\udead"';});var stringifyWithSymbolsFix=function(it,replacer){var args=arraySlice(arguments);var $replacer=getReplacerFunction(replacer);if(!isCallable($replacer)&&(it===undefined||isSymbol(it)))return;// IE8 returns string on undefined
args[1]=function(key,value){// some old implementations (like WebKit) could pass numbers as keys
if(isCallable($replacer))value=call($replacer,this,$String(key),value);if(!isSymbol(value))return value;};return apply($stringify,null,args);};var fixIllFormed=function(match,offset,string){var prev=charAt(string,offset-1);var next=charAt(string,offset+1);if(exec(low,match)&&!exec(hi,next)||exec(hi,match)&&!exec(low,prev)){return '\\u'+numberToString(charCodeAt(match,0),16);}return match;};if($stringify){// `JSON.stringify` method
// https://tc39.es/ecma262/#sec-json.stringify
$({target:'JSON',stat:true,arity:3,forced:WRONG_SYMBOLS_CONVERSION||ILL_FORMED_UNICODE},{// eslint-disable-next-line no-unused-vars -- required for `.length`
stringify:function stringify(it,replacer,space){var args=arraySlice(arguments);var result=apply(WRONG_SYMBOLS_CONVERSION?stringifyWithSymbolsFix:$stringify,null,args);return ILL_FORMED_UNICODE&&typeof result=='string'?replace(result,tester,fixIllFormed):result;}});}return es_json_stringify;}var es_object_getOwnPropertySymbols={};var hasRequiredEs_object_getOwnPropertySymbols;function requireEs_object_getOwnPropertySymbols(){if(hasRequiredEs_object_getOwnPropertySymbols)return es_object_getOwnPropertySymbols;hasRequiredEs_object_getOwnPropertySymbols=1;var $=/*@__PURE__*/require_export();var NATIVE_SYMBOL=/*@__PURE__*/requireSymbolConstructorDetection();var fails=/*@__PURE__*/requireFails();var getOwnPropertySymbolsModule=/*@__PURE__*/requireObjectGetOwnPropertySymbols();var toObject=/*@__PURE__*/requireToObject();// V8 ~ Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives
// https://bugs.chromium.org/p/v8/issues/detail?id=3443
var FORCED=!NATIVE_SYMBOL||fails(function(){getOwnPropertySymbolsModule.f(1);});// `Object.getOwnPropertySymbols` method
// https://tc39.es/ecma262/#sec-object.getownpropertysymbols
$({target:'Object',stat:true,forced:FORCED},{getOwnPropertySymbols:function getOwnPropertySymbols(it){var $getOwnPropertySymbols=getOwnPropertySymbolsModule.f;return $getOwnPropertySymbols?$getOwnPropertySymbols(toObject(it)):[];}});return es_object_getOwnPropertySymbols;}var hasRequiredEs_symbol;function requireEs_symbol(){if(hasRequiredEs_symbol)return es_symbol;hasRequiredEs_symbol=1;// TODO: Remove this module from `core-js@4` since it's split to modules listed below
requireEs_symbol_constructor();requireEs_symbol_for();requireEs_symbol_keyFor();requireEs_json_stringify();requireEs_object_getOwnPropertySymbols();return es_symbol;}var es_symbol_asyncDispose={};var hasRequiredEs_symbol_asyncDispose;function requireEs_symbol_asyncDispose(){if(hasRequiredEs_symbol_asyncDispose)return es_symbol_asyncDispose;hasRequiredEs_symbol_asyncDispose=1;var defineWellKnownSymbol=/*@__PURE__*/requireWellKnownSymbolDefine();// `Symbol.asyncDispose` well-known symbol
// https://github.com/tc39/proposal-async-explicit-resource-management
defineWellKnownSymbol('asyncDispose');return es_symbol_asyncDispose;}var es_symbol_asyncIterator={};var hasRequiredEs_symbol_asyncIterator;function requireEs_symbol_asyncIterator(){if(hasRequiredEs_symbol_asyncIterator)return es_symbol_asyncIterator;hasRequiredEs_symbol_asyncIterator=1;var defineWellKnownSymbol=/*@__PURE__*/requireWellKnownSymbolDefine();// `Symbol.asyncIterator` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.asynciterator
defineWellKnownSymbol('asyncIterator');return es_symbol_asyncIterator;}var es_symbol_dispose={};var hasRequiredEs_symbol_dispose;function requireEs_symbol_dispose(){if(hasRequiredEs_symbol_dispose)return es_symbol_dispose;hasRequiredEs_symbol_dispose=1;var defineWellKnownSymbol=/*@__PURE__*/requireWellKnownSymbolDefine();// `Symbol.dispose` well-known symbol
// https://github.com/tc39/proposal-explicit-resource-management
defineWellKnownSymbol('dispose');return es_symbol_dispose;}var es_symbol_hasInstance={};var hasRequiredEs_symbol_hasInstance;function requireEs_symbol_hasInstance(){if(hasRequiredEs_symbol_hasInstance)return es_symbol_hasInstance;hasRequiredEs_symbol_hasInstance=1;var defineWellKnownSymbol=/*@__PURE__*/requireWellKnownSymbolDefine();// `Symbol.hasInstance` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.hasinstance
defineWellKnownSymbol('hasInstance');return es_symbol_hasInstance;}var es_symbol_isConcatSpreadable={};var hasRequiredEs_symbol_isConcatSpreadable;function requireEs_symbol_isConcatSpreadable(){if(hasRequiredEs_symbol_isConcatSpreadable)return es_symbol_isConcatSpreadable;hasRequiredEs_symbol_isConcatSpreadable=1;var defineWellKnownSymbol=/*@__PURE__*/requireWellKnownSymbolDefine();// `Symbol.isConcatSpreadable` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.isconcatspreadable
defineWellKnownSymbol('isConcatSpreadable');return es_symbol_isConcatSpreadable;}var es_symbol_iterator={};var hasRequiredEs_symbol_iterator;function requireEs_symbol_iterator(){if(hasRequiredEs_symbol_iterator)return es_symbol_iterator;hasRequiredEs_symbol_iterator=1;var defineWellKnownSymbol=/*@__PURE__*/requireWellKnownSymbolDefine();// `Symbol.iterator` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.iterator
defineWellKnownSymbol('iterator');return es_symbol_iterator;}var es_symbol_match={};var hasRequiredEs_symbol_match;function requireEs_symbol_match(){if(hasRequiredEs_symbol_match)return es_symbol_match;hasRequiredEs_symbol_match=1;var defineWellKnownSymbol=/*@__PURE__*/requireWellKnownSymbolDefine();// `Symbol.match` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.match
defineWellKnownSymbol('match');return es_symbol_match;}var es_symbol_matchAll={};var hasRequiredEs_symbol_matchAll;function requireEs_symbol_matchAll(){if(hasRequiredEs_symbol_matchAll)return es_symbol_matchAll;hasRequiredEs_symbol_matchAll=1;var defineWellKnownSymbol=/*@__PURE__*/requireWellKnownSymbolDefine();// `Symbol.matchAll` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.matchall
defineWellKnownSymbol('matchAll');return es_symbol_matchAll;}var es_symbol_replace={};var hasRequiredEs_symbol_replace;function requireEs_symbol_replace(){if(hasRequiredEs_symbol_replace)return es_symbol_replace;hasRequiredEs_symbol_replace=1;var defineWellKnownSymbol=/*@__PURE__*/requireWellKnownSymbolDefine();// `Symbol.replace` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.replace
defineWellKnownSymbol('replace');return es_symbol_replace;}var es_symbol_search={};var hasRequiredEs_symbol_search;function requireEs_symbol_search(){if(hasRequiredEs_symbol_search)return es_symbol_search;hasRequiredEs_symbol_search=1;var defineWellKnownSymbol=/*@__PURE__*/requireWellKnownSymbolDefine();// `Symbol.search` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.search
defineWellKnownSymbol('search');return es_symbol_search;}var es_symbol_species={};var hasRequiredEs_symbol_species;function requireEs_symbol_species(){if(hasRequiredEs_symbol_species)return es_symbol_species;hasRequiredEs_symbol_species=1;var defineWellKnownSymbol=/*@__PURE__*/requireWellKnownSymbolDefine();// `Symbol.species` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.species
defineWellKnownSymbol('species');return es_symbol_species;}var es_symbol_split={};var hasRequiredEs_symbol_split;function requireEs_symbol_split(){if(hasRequiredEs_symbol_split)return es_symbol_split;hasRequiredEs_symbol_split=1;var defineWellKnownSymbol=/*@__PURE__*/requireWellKnownSymbolDefine();// `Symbol.split` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.split
defineWellKnownSymbol('split');return es_symbol_split;}var es_symbol_toPrimitive={};var hasRequiredEs_symbol_toPrimitive;function requireEs_symbol_toPrimitive(){if(hasRequiredEs_symbol_toPrimitive)return es_symbol_toPrimitive;hasRequiredEs_symbol_toPrimitive=1;var defineWellKnownSymbol=/*@__PURE__*/requireWellKnownSymbolDefine();var defineSymbolToPrimitive=/*@__PURE__*/requireSymbolDefineToPrimitive();// `Symbol.toPrimitive` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.toprimitive
defineWellKnownSymbol('toPrimitive');// `Symbol.prototype[@@toPrimitive]` method
// https://tc39.es/ecma262/#sec-symbol.prototype-@@toprimitive
defineSymbolToPrimitive();return es_symbol_toPrimitive;}var es_symbol_toStringTag={};var hasRequiredEs_symbol_toStringTag;function requireEs_symbol_toStringTag(){if(hasRequiredEs_symbol_toStringTag)return es_symbol_toStringTag;hasRequiredEs_symbol_toStringTag=1;var getBuiltIn=/*@__PURE__*/requireGetBuiltIn();var defineWellKnownSymbol=/*@__PURE__*/requireWellKnownSymbolDefine();var setToStringTag=/*@__PURE__*/requireSetToStringTag();// `Symbol.toStringTag` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.tostringtag
defineWellKnownSymbol('toStringTag');// `Symbol.prototype[@@toStringTag]` property
// https://tc39.es/ecma262/#sec-symbol.prototype-@@tostringtag
setToStringTag(getBuiltIn('Symbol'),'Symbol');return es_symbol_toStringTag;}var es_symbol_unscopables={};var hasRequiredEs_symbol_unscopables;function requireEs_symbol_unscopables(){if(hasRequiredEs_symbol_unscopables)return es_symbol_unscopables;hasRequiredEs_symbol_unscopables=1;var defineWellKnownSymbol=/*@__PURE__*/requireWellKnownSymbolDefine();// `Symbol.unscopables` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.unscopables
defineWellKnownSymbol('unscopables');return es_symbol_unscopables;}var es_json_toStringTag={};var hasRequiredEs_json_toStringTag;function requireEs_json_toStringTag(){if(hasRequiredEs_json_toStringTag)return es_json_toStringTag;hasRequiredEs_json_toStringTag=1;var globalThis=/*@__PURE__*/requireGlobalThis();var setToStringTag=/*@__PURE__*/requireSetToStringTag();// JSON[@@toStringTag] property
// https://tc39.es/ecma262/#sec-json-@@tostringtag
setToStringTag(globalThis.JSON,'JSON',true);return es_json_toStringTag;}var symbol$5;var hasRequiredSymbol$5;function requireSymbol$5(){if(hasRequiredSymbol$5)return symbol$5;hasRequiredSymbol$5=1;requireEs_array_concat();requireEs_symbol();requireEs_symbol_asyncDispose();requireEs_symbol_asyncIterator();requireEs_symbol_dispose();requireEs_symbol_hasInstance();requireEs_symbol_isConcatSpreadable();requireEs_symbol_iterator();requireEs_symbol_match();requireEs_symbol_matchAll();requireEs_symbol_replace();requireEs_symbol_search();requireEs_symbol_species();requireEs_symbol_split();requireEs_symbol_toPrimitive();requireEs_symbol_toStringTag();requireEs_symbol_unscopables();requireEs_json_toStringTag();var path=/*@__PURE__*/requirePath();symbol$5=path.Symbol;return symbol$5;}var web_domCollections_iterator={};var addToUnscopables;var hasRequiredAddToUnscopables;function requireAddToUnscopables(){if(hasRequiredAddToUnscopables)return addToUnscopables;hasRequiredAddToUnscopables=1;addToUnscopables=function(){/* empty */};return addToUnscopables;}var iterators;var hasRequiredIterators;function requireIterators(){if(hasRequiredIterators)return iterators;hasRequiredIterators=1;iterators={};return iterators;}var functionName;var hasRequiredFunctionName;function requireFunctionName(){if(hasRequiredFunctionName)return functionName;hasRequiredFunctionName=1;var DESCRIPTORS=/*@__PURE__*/requireDescriptors();var hasOwn=/*@__PURE__*/requireHasOwnProperty();var FunctionPrototype=Function.prototype;// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var getDescriptor=DESCRIPTORS&&Object.getOwnPropertyDescriptor;var EXISTS=hasOwn(FunctionPrototype,'name');// additional protection from minified / mangled / dropped function names
var PROPER=EXISTS&&function something(){/* empty */}.name==='something';var CONFIGURABLE=EXISTS&&(!DESCRIPTORS||DESCRIPTORS&&getDescriptor(FunctionPrototype,'name').configurable);functionName={EXISTS:EXISTS,PROPER:PROPER,CONFIGURABLE:CONFIGURABLE};return functionName;}var correctPrototypeGetter;var hasRequiredCorrectPrototypeGetter;function requireCorrectPrototypeGetter(){if(hasRequiredCorrectPrototypeGetter)return correctPrototypeGetter;hasRequiredCorrectPrototypeGetter=1;var fails=/*@__PURE__*/requireFails();correctPrototypeGetter=!fails(function(){function F(){/* empty */}F.prototype.constructor=null;// eslint-disable-next-line es/no-object-getprototypeof -- required for testing
return Object.getPrototypeOf(new F())!==F.prototype;});return correctPrototypeGetter;}var objectGetPrototypeOf;var hasRequiredObjectGetPrototypeOf;function requireObjectGetPrototypeOf(){if(hasRequiredObjectGetPrototypeOf)return objectGetPrototypeOf;hasRequiredObjectGetPrototypeOf=1;var hasOwn=/*@__PURE__*/requireHasOwnProperty();var isCallable=/*@__PURE__*/requireIsCallable();var toObject=/*@__PURE__*/requireToObject();var sharedKey=/*@__PURE__*/requireSharedKey();var CORRECT_PROTOTYPE_GETTER=/*@__PURE__*/requireCorrectPrototypeGetter();var IE_PROTO=sharedKey('IE_PROTO');var $Object=Object;var ObjectPrototype=$Object.prototype;// `Object.getPrototypeOf` method
// https://tc39.es/ecma262/#sec-object.getprototypeof
// eslint-disable-next-line es/no-object-getprototypeof -- safe
objectGetPrototypeOf=CORRECT_PROTOTYPE_GETTER?$Object.getPrototypeOf:function(O){var object=toObject(O);if(hasOwn(object,IE_PROTO))return object[IE_PROTO];var constructor=object.constructor;if(isCallable(constructor)&&object instanceof constructor){return constructor.prototype;}return object instanceof $Object?ObjectPrototype:null;};return objectGetPrototypeOf;}var iteratorsCore;var hasRequiredIteratorsCore;function requireIteratorsCore(){if(hasRequiredIteratorsCore)return iteratorsCore;hasRequiredIteratorsCore=1;var fails=/*@__PURE__*/requireFails();var isCallable=/*@__PURE__*/requireIsCallable();var isObject=/*@__PURE__*/requireIsObject();var create=/*@__PURE__*/requireObjectCreate();var getPrototypeOf=/*@__PURE__*/requireObjectGetPrototypeOf();var defineBuiltIn=/*@__PURE__*/requireDefineBuiltIn();var wellKnownSymbol=/*@__PURE__*/requireWellKnownSymbol();var IS_PURE=/*@__PURE__*/requireIsPure();var ITERATOR=wellKnownSymbol('iterator');var BUGGY_SAFARI_ITERATORS=false;// `%IteratorPrototype%` object
// https://tc39.es/ecma262/#sec-%iteratorprototype%-object
var IteratorPrototype,PrototypeOfArrayIteratorPrototype,arrayIterator;/* eslint-disable es/no-array-prototype-keys -- safe */if([].keys){arrayIterator=[].keys();// Safari 8 has buggy iterators w/o `next`
if(!('next'in arrayIterator))BUGGY_SAFARI_ITERATORS=true;else {PrototypeOfArrayIteratorPrototype=getPrototypeOf(getPrototypeOf(arrayIterator));if(PrototypeOfArrayIteratorPrototype!==Object.prototype)IteratorPrototype=PrototypeOfArrayIteratorPrototype;}}var NEW_ITERATOR_PROTOTYPE=!isObject(IteratorPrototype)||fails(function(){var test={};// FF44- legacy iterators case
return IteratorPrototype[ITERATOR].call(test)!==test;});if(NEW_ITERATOR_PROTOTYPE)IteratorPrototype={};else if(IS_PURE)IteratorPrototype=create(IteratorPrototype);// `%IteratorPrototype%[@@iterator]()` method
// https://tc39.es/ecma262/#sec-%iteratorprototype%-@@iterator
if(!isCallable(IteratorPrototype[ITERATOR])){defineBuiltIn(IteratorPrototype,ITERATOR,function(){return this;});}iteratorsCore={IteratorPrototype:IteratorPrototype,BUGGY_SAFARI_ITERATORS:BUGGY_SAFARI_ITERATORS};return iteratorsCore;}var iteratorCreateConstructor;var hasRequiredIteratorCreateConstructor;function requireIteratorCreateConstructor(){if(hasRequiredIteratorCreateConstructor)return iteratorCreateConstructor;hasRequiredIteratorCreateConstructor=1;var IteratorPrototype=/*@__PURE__*/requireIteratorsCore().IteratorPrototype;var create=/*@__PURE__*/requireObjectCreate();var createPropertyDescriptor=/*@__PURE__*/requireCreatePropertyDescriptor();var setToStringTag=/*@__PURE__*/requireSetToStringTag();var Iterators=/*@__PURE__*/requireIterators();var returnThis=function(){return this;};iteratorCreateConstructor=function(IteratorConstructor,NAME,next,ENUMERABLE_NEXT){var TO_STRING_TAG=NAME+' Iterator';IteratorConstructor.prototype=create(IteratorPrototype,{next:createPropertyDescriptor(+!ENUMERABLE_NEXT,next)});setToStringTag(IteratorConstructor,TO_STRING_TAG,false,true);Iterators[TO_STRING_TAG]=returnThis;return IteratorConstructor;};return iteratorCreateConstructor;}var functionUncurryThisAccessor;var hasRequiredFunctionUncurryThisAccessor;function requireFunctionUncurryThisAccessor(){if(hasRequiredFunctionUncurryThisAccessor)return functionUncurryThisAccessor;hasRequiredFunctionUncurryThisAccessor=1;var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var aCallable=/*@__PURE__*/requireACallable();functionUncurryThisAccessor=function(object,key,method){try{// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
return uncurryThis(aCallable(Object.getOwnPropertyDescriptor(object,key)[method]));}catch(error){/* empty */}};return functionUncurryThisAccessor;}var isPossiblePrototype;var hasRequiredIsPossiblePrototype;function requireIsPossiblePrototype(){if(hasRequiredIsPossiblePrototype)return isPossiblePrototype;hasRequiredIsPossiblePrototype=1;var isObject=/*@__PURE__*/requireIsObject();isPossiblePrototype=function(argument){return isObject(argument)||argument===null;};return isPossiblePrototype;}var aPossiblePrototype;var hasRequiredAPossiblePrototype;function requireAPossiblePrototype(){if(hasRequiredAPossiblePrototype)return aPossiblePrototype;hasRequiredAPossiblePrototype=1;var isPossiblePrototype=/*@__PURE__*/requireIsPossiblePrototype();var $String=String;var $TypeError=TypeError;aPossiblePrototype=function(argument){if(isPossiblePrototype(argument))return argument;throw new $TypeError("Can't set "+$String(argument)+' as a prototype');};return aPossiblePrototype;}var objectSetPrototypeOf;var hasRequiredObjectSetPrototypeOf;function requireObjectSetPrototypeOf(){if(hasRequiredObjectSetPrototypeOf)return objectSetPrototypeOf;hasRequiredObjectSetPrototypeOf=1;/* eslint-disable no-proto -- safe */var uncurryThisAccessor=/*@__PURE__*/requireFunctionUncurryThisAccessor();var isObject=/*@__PURE__*/requireIsObject();var requireObjectCoercible=/*@__PURE__*/requireRequireObjectCoercible();var aPossiblePrototype=/*@__PURE__*/requireAPossiblePrototype();// `Object.setPrototypeOf` method
// https://tc39.es/ecma262/#sec-object.setprototypeof
// Works with __proto__ only. Old v8 can't work with null proto objects.
// eslint-disable-next-line es/no-object-setprototypeof -- safe
objectSetPrototypeOf=Object.setPrototypeOf||('__proto__'in{}?function(){var CORRECT_SETTER=false;var test={};var setter;try{setter=uncurryThisAccessor(Object.prototype,'__proto__','set');setter(test,[]);CORRECT_SETTER=test instanceof Array;}catch(error){/* empty */}return function setPrototypeOf(O,proto){requireObjectCoercible(O);aPossiblePrototype(proto);if(!isObject(O))return O;if(CORRECT_SETTER)setter(O,proto);else O.__proto__=proto;return O;};}():undefined);return objectSetPrototypeOf;}var iteratorDefine;var hasRequiredIteratorDefine;function requireIteratorDefine(){if(hasRequiredIteratorDefine)return iteratorDefine;hasRequiredIteratorDefine=1;var $=/*@__PURE__*/require_export();var call=/*@__PURE__*/requireFunctionCall();var IS_PURE=/*@__PURE__*/requireIsPure();var FunctionName=/*@__PURE__*/requireFunctionName();var isCallable=/*@__PURE__*/requireIsCallable();var createIteratorConstructor=/*@__PURE__*/requireIteratorCreateConstructor();var getPrototypeOf=/*@__PURE__*/requireObjectGetPrototypeOf();var setPrototypeOf=/*@__PURE__*/requireObjectSetPrototypeOf();var setToStringTag=/*@__PURE__*/requireSetToStringTag();var createNonEnumerableProperty=/*@__PURE__*/requireCreateNonEnumerableProperty();var defineBuiltIn=/*@__PURE__*/requireDefineBuiltIn();var wellKnownSymbol=/*@__PURE__*/requireWellKnownSymbol();var Iterators=/*@__PURE__*/requireIterators();var IteratorsCore=/*@__PURE__*/requireIteratorsCore();var PROPER_FUNCTION_NAME=FunctionName.PROPER;var CONFIGURABLE_FUNCTION_NAME=FunctionName.CONFIGURABLE;var IteratorPrototype=IteratorsCore.IteratorPrototype;var BUGGY_SAFARI_ITERATORS=IteratorsCore.BUGGY_SAFARI_ITERATORS;var ITERATOR=wellKnownSymbol('iterator');var KEYS='keys';var VALUES='values';var ENTRIES='entries';var returnThis=function(){return this;};iteratorDefine=function(Iterable,NAME,IteratorConstructor,next,DEFAULT,IS_SET,FORCED){createIteratorConstructor(IteratorConstructor,NAME,next);var getIterationMethod=function(KIND){if(KIND===DEFAULT&&defaultIterator)return defaultIterator;if(!BUGGY_SAFARI_ITERATORS&&KIND&&KIND in IterablePrototype)return IterablePrototype[KIND];switch(KIND){case KEYS:return function keys(){return new IteratorConstructor(this,KIND);};case VALUES:return function values(){return new IteratorConstructor(this,KIND);};case ENTRIES:return function entries(){return new IteratorConstructor(this,KIND);};}return function(){return new IteratorConstructor(this);};};var TO_STRING_TAG=NAME+' Iterator';var INCORRECT_VALUES_NAME=false;var IterablePrototype=Iterable.prototype;var nativeIterator=IterablePrototype[ITERATOR]||IterablePrototype['@@iterator']||DEFAULT&&IterablePrototype[DEFAULT];var defaultIterator=!BUGGY_SAFARI_ITERATORS&&nativeIterator||getIterationMethod(DEFAULT);var anyNativeIterator=NAME==='Array'?IterablePrototype.entries||nativeIterator:nativeIterator;var CurrentIteratorPrototype,methods,KEY;// fix native
if(anyNativeIterator){CurrentIteratorPrototype=getPrototypeOf(anyNativeIterator.call(new Iterable()));if(CurrentIteratorPrototype!==Object.prototype&&CurrentIteratorPrototype.next){if(!IS_PURE&&getPrototypeOf(CurrentIteratorPrototype)!==IteratorPrototype){if(setPrototypeOf){setPrototypeOf(CurrentIteratorPrototype,IteratorPrototype);}else if(!isCallable(CurrentIteratorPrototype[ITERATOR])){defineBuiltIn(CurrentIteratorPrototype,ITERATOR,returnThis);}}// Set @@toStringTag to native iterators
setToStringTag(CurrentIteratorPrototype,TO_STRING_TAG,true,true);if(IS_PURE)Iterators[TO_STRING_TAG]=returnThis;}}// fix Array.prototype.{ values, @@iterator }.name in V8 / FF
if(PROPER_FUNCTION_NAME&&DEFAULT===VALUES&&nativeIterator&&nativeIterator.name!==VALUES){if(!IS_PURE&&CONFIGURABLE_FUNCTION_NAME){createNonEnumerableProperty(IterablePrototype,'name',VALUES);}else {INCORRECT_VALUES_NAME=true;defaultIterator=function values(){return call(nativeIterator,this);};}}// export additional methods
if(DEFAULT){methods={values:getIterationMethod(VALUES),keys:IS_SET?defaultIterator:getIterationMethod(KEYS),entries:getIterationMethod(ENTRIES)};if(FORCED)for(KEY in methods){if(BUGGY_SAFARI_ITERATORS||INCORRECT_VALUES_NAME||!(KEY in IterablePrototype)){defineBuiltIn(IterablePrototype,KEY,methods[KEY]);}}else $({target:NAME,proto:true,forced:BUGGY_SAFARI_ITERATORS||INCORRECT_VALUES_NAME},methods);}// define iterator
if((!IS_PURE||FORCED)&&IterablePrototype[ITERATOR]!==defaultIterator){defineBuiltIn(IterablePrototype,ITERATOR,defaultIterator,{name:DEFAULT});}Iterators[NAME]=defaultIterator;return methods;};return iteratorDefine;}var createIterResultObject;var hasRequiredCreateIterResultObject;function requireCreateIterResultObject(){if(hasRequiredCreateIterResultObject)return createIterResultObject;hasRequiredCreateIterResultObject=1;// `CreateIterResultObject` abstract operation
// https://tc39.es/ecma262/#sec-createiterresultobject
createIterResultObject=function(value,done){return {value:value,done:done};};return createIterResultObject;}var es_array_iterator;var hasRequiredEs_array_iterator;function requireEs_array_iterator(){if(hasRequiredEs_array_iterator)return es_array_iterator;hasRequiredEs_array_iterator=1;var toIndexedObject=/*@__PURE__*/requireToIndexedObject();var addToUnscopables=/*@__PURE__*/requireAddToUnscopables();var Iterators=/*@__PURE__*/requireIterators();var InternalStateModule=/*@__PURE__*/requireInternalState();var defineProperty=/*@__PURE__*/requireObjectDefineProperty().f;var defineIterator=/*@__PURE__*/requireIteratorDefine();var createIterResultObject=/*@__PURE__*/requireCreateIterResultObject();var IS_PURE=/*@__PURE__*/requireIsPure();var DESCRIPTORS=/*@__PURE__*/requireDescriptors();var ARRAY_ITERATOR='Array Iterator';var setInternalState=InternalStateModule.set;var getInternalState=InternalStateModule.getterFor(ARRAY_ITERATOR);// `Array.prototype.entries` method
// https://tc39.es/ecma262/#sec-array.prototype.entries
// `Array.prototype.keys` method
// https://tc39.es/ecma262/#sec-array.prototype.keys
// `Array.prototype.values` method
// https://tc39.es/ecma262/#sec-array.prototype.values
// `Array.prototype[@@iterator]` method
// https://tc39.es/ecma262/#sec-array.prototype-@@iterator
// `CreateArrayIterator` internal method
// https://tc39.es/ecma262/#sec-createarrayiterator
es_array_iterator=defineIterator(Array,'Array',function(iterated,kind){setInternalState(this,{type:ARRAY_ITERATOR,target:toIndexedObject(iterated),// target
index:0,// next index
kind:kind// kind
});// `%ArrayIteratorPrototype%.next` method
// https://tc39.es/ecma262/#sec-%arrayiteratorprototype%.next
},function(){var state=getInternalState(this);var target=state.target;var index=state.index++;if(!target||index>=target.length){state.target=null;return createIterResultObject(undefined,true);}switch(state.kind){case 'keys':return createIterResultObject(index,false);case 'values':return createIterResultObject(target[index],false);}return createIterResultObject([index,target[index]],false);},'values');// argumentsList[@@iterator] is %ArrayProto_values%
// https://tc39.es/ecma262/#sec-createunmappedargumentsobject
// https://tc39.es/ecma262/#sec-createmappedargumentsobject
var values=Iterators.Arguments=Iterators.Array;// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables('keys');addToUnscopables('values');addToUnscopables('entries');// V8 ~ Chrome 45- bug
if(!IS_PURE&&DESCRIPTORS&&values.name!=='values')try{defineProperty(values,'name',{value:'values'});}catch(error){/* empty */}return es_array_iterator;}var domIterables;var hasRequiredDomIterables;function requireDomIterables(){if(hasRequiredDomIterables)return domIterables;hasRequiredDomIterables=1;// iterable DOM collections
// flag - `iterable` interface - 'entries', 'keys', 'values', 'forEach' methods
domIterables={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0};return domIterables;}var hasRequiredWeb_domCollections_iterator;function requireWeb_domCollections_iterator(){if(hasRequiredWeb_domCollections_iterator)return web_domCollections_iterator;hasRequiredWeb_domCollections_iterator=1;requireEs_array_iterator();var DOMIterables=/*@__PURE__*/requireDomIterables();var globalThis=/*@__PURE__*/requireGlobalThis();var setToStringTag=/*@__PURE__*/requireSetToStringTag();var Iterators=/*@__PURE__*/requireIterators();for(var COLLECTION_NAME in DOMIterables){setToStringTag(globalThis[COLLECTION_NAME],COLLECTION_NAME);Iterators[COLLECTION_NAME]=Iterators.Array;}return web_domCollections_iterator;}var symbol$4;var hasRequiredSymbol$4;function requireSymbol$4(){if(hasRequiredSymbol$4)return symbol$4;hasRequiredSymbol$4=1;var parent=/*@__PURE__*/requireSymbol$5();requireWeb_domCollections_iterator();symbol$4=parent;return symbol$4;}var symbol$3;var hasRequiredSymbol$3;function requireSymbol$3(){if(hasRequiredSymbol$3)return symbol$3;hasRequiredSymbol$3=1;symbol$3=/*@__PURE__*/requireSymbol$4();return symbol$3;}var symbolExports$1=requireSymbol$3();var _Symbol$1=/*@__PURE__*/getDefaultExportFromCjs(symbolExports$1);var es_array_slice={};var hasRequiredEs_array_slice;function requireEs_array_slice(){if(hasRequiredEs_array_slice)return es_array_slice;hasRequiredEs_array_slice=1;var $=/*@__PURE__*/require_export();var isArray=/*@__PURE__*/requireIsArray$3();var isConstructor=/*@__PURE__*/requireIsConstructor();var isObject=/*@__PURE__*/requireIsObject();var toAbsoluteIndex=/*@__PURE__*/requireToAbsoluteIndex();var lengthOfArrayLike=/*@__PURE__*/requireLengthOfArrayLike();var toIndexedObject=/*@__PURE__*/requireToIndexedObject();var createProperty=/*@__PURE__*/requireCreateProperty();var wellKnownSymbol=/*@__PURE__*/requireWellKnownSymbol();var arrayMethodHasSpeciesSupport=/*@__PURE__*/requireArrayMethodHasSpeciesSupport();var nativeSlice=/*@__PURE__*/requireArraySlice();var HAS_SPECIES_SUPPORT=arrayMethodHasSpeciesSupport('slice');var SPECIES=wellKnownSymbol('species');var $Array=Array;var max=Math.max;// `Array.prototype.slice` method
// https://tc39.es/ecma262/#sec-array.prototype.slice
// fallback for not array-like ES3 strings and DOM objects
$({target:'Array',proto:true,forced:!HAS_SPECIES_SUPPORT},{slice:function slice(start,end){var O=toIndexedObject(this);var length=lengthOfArrayLike(O);var k=toAbsoluteIndex(start,length);var fin=toAbsoluteIndex(end===undefined?length:end,length);// inline `ArraySpeciesCreate` for usage native `Array#slice` where it's possible
var Constructor,result,n;if(isArray(O)){Constructor=O.constructor;// cross-realm fallback
if(isConstructor(Constructor)&&(Constructor===$Array||isArray(Constructor.prototype))){Constructor=undefined;}else if(isObject(Constructor)){Constructor=Constructor[SPECIES];if(Constructor===null)Constructor=undefined;}if(Constructor===$Array||Constructor===undefined){return nativeSlice(O,k,fin);}}result=new(Constructor===undefined?$Array:Constructor)(max(fin-k,0));for(n=0;k<fin;k++,n++)if(k in O)createProperty(result,n,O[k]);result.length=n;return result;}});return es_array_slice;}var slice$3;var hasRequiredSlice$3;function requireSlice$3(){if(hasRequiredSlice$3)return slice$3;hasRequiredSlice$3=1;requireEs_array_slice();var getBuiltInPrototypeMethod=/*@__PURE__*/requireGetBuiltInPrototypeMethod();slice$3=getBuiltInPrototypeMethod('Array','slice');return slice$3;}var slice$2;var hasRequiredSlice$2;function requireSlice$2(){if(hasRequiredSlice$2)return slice$2;hasRequiredSlice$2=1;var isPrototypeOf=/*@__PURE__*/requireObjectIsPrototypeOf();var method=/*@__PURE__*/requireSlice$3();var ArrayPrototype=Array.prototype;slice$2=function(it){var own=it.slice;return it===ArrayPrototype||isPrototypeOf(ArrayPrototype,it)&&own===ArrayPrototype.slice?method:own;};return slice$2;}var slice$1;var hasRequiredSlice$1;function requireSlice$1(){if(hasRequiredSlice$1)return slice$1;hasRequiredSlice$1=1;var parent=/*@__PURE__*/requireSlice$2();slice$1=parent;return slice$1;}var slice;var hasRequiredSlice;function requireSlice(){if(hasRequiredSlice)return slice;hasRequiredSlice=1;slice=/*@__PURE__*/requireSlice$1();return slice;}var sliceExports=requireSlice();var _sliceInstanceProperty=/*@__PURE__*/getDefaultExportFromCjs(sliceExports);var es_reflect_ownKeys={};var ownKeys$8;var hasRequiredOwnKeys$3;function requireOwnKeys$3(){if(hasRequiredOwnKeys$3)return ownKeys$8;hasRequiredOwnKeys$3=1;var getBuiltIn=/*@__PURE__*/requireGetBuiltIn();var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var getOwnPropertyNamesModule=/*@__PURE__*/requireObjectGetOwnPropertyNames();var getOwnPropertySymbolsModule=/*@__PURE__*/requireObjectGetOwnPropertySymbols();var anObject=/*@__PURE__*/requireAnObject();var concat=uncurryThis([].concat);// all object keys, includes non-enumerable and symbols
ownKeys$8=getBuiltIn('Reflect','ownKeys')||function ownKeys(it){var keys=getOwnPropertyNamesModule.f(anObject(it));var getOwnPropertySymbols=getOwnPropertySymbolsModule.f;return getOwnPropertySymbols?concat(keys,getOwnPropertySymbols(it)):keys;};return ownKeys$8;}var hasRequiredEs_reflect_ownKeys;function requireEs_reflect_ownKeys(){if(hasRequiredEs_reflect_ownKeys)return es_reflect_ownKeys;hasRequiredEs_reflect_ownKeys=1;var $=/*@__PURE__*/require_export();var ownKeys=/*@__PURE__*/requireOwnKeys$3();// `Reflect.ownKeys` method
// https://tc39.es/ecma262/#sec-reflect.ownkeys
$({target:'Reflect',stat:true},{ownKeys:ownKeys});return es_reflect_ownKeys;}var ownKeys$7;var hasRequiredOwnKeys$2;function requireOwnKeys$2(){if(hasRequiredOwnKeys$2)return ownKeys$7;hasRequiredOwnKeys$2=1;requireEs_reflect_ownKeys();var path=/*@__PURE__*/requirePath();ownKeys$7=path.Reflect.ownKeys;return ownKeys$7;}var ownKeys$6;var hasRequiredOwnKeys$1;function requireOwnKeys$1(){if(hasRequiredOwnKeys$1)return ownKeys$6;hasRequiredOwnKeys$1=1;var parent=/*@__PURE__*/requireOwnKeys$2();ownKeys$6=parent;return ownKeys$6;}var ownKeys$5;var hasRequiredOwnKeys;function requireOwnKeys(){if(hasRequiredOwnKeys)return ownKeys$5;hasRequiredOwnKeys=1;ownKeys$5=/*@__PURE__*/requireOwnKeys$1();return ownKeys$5;}var ownKeysExports=requireOwnKeys();var _Reflect$ownKeys=/*@__PURE__*/getDefaultExportFromCjs(ownKeysExports);var es_array_isArray={};var hasRequiredEs_array_isArray;function requireEs_array_isArray(){if(hasRequiredEs_array_isArray)return es_array_isArray;hasRequiredEs_array_isArray=1;var $=/*@__PURE__*/require_export();var isArray=/*@__PURE__*/requireIsArray$3();// `Array.isArray` method
// https://tc39.es/ecma262/#sec-array.isarray
$({target:'Array',stat:true},{isArray:isArray});return es_array_isArray;}var isArray$2;var hasRequiredIsArray$2;function requireIsArray$2(){if(hasRequiredIsArray$2)return isArray$2;hasRequiredIsArray$2=1;requireEs_array_isArray();var path=/*@__PURE__*/requirePath();isArray$2=path.Array.isArray;return isArray$2;}var isArray$1;var hasRequiredIsArray$1;function requireIsArray$1(){if(hasRequiredIsArray$1)return isArray$1;hasRequiredIsArray$1=1;var parent=/*@__PURE__*/requireIsArray$2();isArray$1=parent;return isArray$1;}var isArray;var hasRequiredIsArray;function requireIsArray(){if(hasRequiredIsArray)return isArray;hasRequiredIsArray=1;isArray=/*@__PURE__*/requireIsArray$1();return isArray;}var isArrayExports=requireIsArray();var _Array$isArray=/*@__PURE__*/getDefaultExportFromCjs(isArrayExports);var es_array_map={};var hasRequiredEs_array_map;function requireEs_array_map(){if(hasRequiredEs_array_map)return es_array_map;hasRequiredEs_array_map=1;var $=/*@__PURE__*/require_export();var $map=/*@__PURE__*/requireArrayIteration().map;var arrayMethodHasSpeciesSupport=/*@__PURE__*/requireArrayMethodHasSpeciesSupport();var HAS_SPECIES_SUPPORT=arrayMethodHasSpeciesSupport('map');// `Array.prototype.map` method
// https://tc39.es/ecma262/#sec-array.prototype.map
// with adding support of @@species
$({target:'Array',proto:true,forced:!HAS_SPECIES_SUPPORT},{map:function map(callbackfn/* , thisArg */){return $map(this,callbackfn,arguments.length>1?arguments[1]:undefined);}});return es_array_map;}var map$6;var hasRequiredMap$6;function requireMap$6(){if(hasRequiredMap$6)return map$6;hasRequiredMap$6=1;requireEs_array_map();var getBuiltInPrototypeMethod=/*@__PURE__*/requireGetBuiltInPrototypeMethod();map$6=getBuiltInPrototypeMethod('Array','map');return map$6;}var map$5;var hasRequiredMap$5;function requireMap$5(){if(hasRequiredMap$5)return map$5;hasRequiredMap$5=1;var isPrototypeOf=/*@__PURE__*/requireObjectIsPrototypeOf();var method=/*@__PURE__*/requireMap$6();var ArrayPrototype=Array.prototype;map$5=function(it){var own=it.map;return it===ArrayPrototype||isPrototypeOf(ArrayPrototype,it)&&own===ArrayPrototype.map?method:own;};return map$5;}var map$4;var hasRequiredMap$4;function requireMap$4(){if(hasRequiredMap$4)return map$4;hasRequiredMap$4=1;var parent=/*@__PURE__*/requireMap$5();map$4=parent;return map$4;}var map$3;var hasRequiredMap$3;function requireMap$3(){if(hasRequiredMap$3)return map$3;hasRequiredMap$3=1;map$3=/*@__PURE__*/requireMap$4();return map$3;}var mapExports$1=requireMap$3();var _mapInstanceProperty=/*@__PURE__*/getDefaultExportFromCjs(mapExports$1);var es_object_keys={};var hasRequiredEs_object_keys;function requireEs_object_keys(){if(hasRequiredEs_object_keys)return es_object_keys;hasRequiredEs_object_keys=1;var $=/*@__PURE__*/require_export();var toObject=/*@__PURE__*/requireToObject();var nativeKeys=/*@__PURE__*/requireObjectKeys();var fails=/*@__PURE__*/requireFails();var FAILS_ON_PRIMITIVES=fails(function(){nativeKeys(1);});// `Object.keys` method
// https://tc39.es/ecma262/#sec-object.keys
$({target:'Object',stat:true,forced:FAILS_ON_PRIMITIVES},{keys:function keys(it){return nativeKeys(toObject(it));}});return es_object_keys;}var keys$6;var hasRequiredKeys$6;function requireKeys$6(){if(hasRequiredKeys$6)return keys$6;hasRequiredKeys$6=1;requireEs_object_keys();var path=/*@__PURE__*/requirePath();keys$6=path.Object.keys;return keys$6;}var keys$5;var hasRequiredKeys$5;function requireKeys$5(){if(hasRequiredKeys$5)return keys$5;hasRequiredKeys$5=1;var parent=/*@__PURE__*/requireKeys$6();keys$5=parent;return keys$5;}var keys$4;var hasRequiredKeys$4;function requireKeys$4(){if(hasRequiredKeys$4)return keys$4;hasRequiredKeys$4=1;keys$4=/*@__PURE__*/requireKeys$5();return keys$4;}var keysExports$1=requireKeys$4();var _Object$keys=/*@__PURE__*/getDefaultExportFromCjs(keysExports$1);var es_date_now={};var hasRequiredEs_date_now;function requireEs_date_now(){if(hasRequiredEs_date_now)return es_date_now;hasRequiredEs_date_now=1;// TODO: Remove from `core-js@4`
var $=/*@__PURE__*/require_export();var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var $Date=Date;var thisTimeValue=uncurryThis($Date.prototype.getTime);// `Date.now` method
// https://tc39.es/ecma262/#sec-date.now
$({target:'Date',stat:true},{now:function now(){return thisTimeValue(new $Date());}});return es_date_now;}var now$3;var hasRequiredNow$2;function requireNow$2(){if(hasRequiredNow$2)return now$3;hasRequiredNow$2=1;requireEs_date_now();var path=/*@__PURE__*/requirePath();now$3=path.Date.now;return now$3;}var now$2;var hasRequiredNow$1;function requireNow$1(){if(hasRequiredNow$1)return now$2;hasRequiredNow$1=1;var parent=/*@__PURE__*/requireNow$2();now$2=parent;return now$2;}var now$1;var hasRequiredNow;function requireNow(){if(hasRequiredNow)return now$1;hasRequiredNow=1;now$1=/*@__PURE__*/requireNow$1();return now$1;}var nowExports=requireNow();var _Date$now=/*@__PURE__*/getDefaultExportFromCjs(nowExports);var es_array_forEach={};var arrayMethodIsStrict;var hasRequiredArrayMethodIsStrict;function requireArrayMethodIsStrict(){if(hasRequiredArrayMethodIsStrict)return arrayMethodIsStrict;hasRequiredArrayMethodIsStrict=1;var fails=/*@__PURE__*/requireFails();arrayMethodIsStrict=function(METHOD_NAME,argument){var method=[][METHOD_NAME];return !!method&&fails(function(){// eslint-disable-next-line no-useless-call -- required for testing
method.call(null,argument||function(){return 1;},1);});};return arrayMethodIsStrict;}var arrayForEach;var hasRequiredArrayForEach;function requireArrayForEach(){if(hasRequiredArrayForEach)return arrayForEach;hasRequiredArrayForEach=1;var $forEach=/*@__PURE__*/requireArrayIteration().forEach;var arrayMethodIsStrict=/*@__PURE__*/requireArrayMethodIsStrict();var STRICT_METHOD=arrayMethodIsStrict('forEach');// `Array.prototype.forEach` method implementation
// https://tc39.es/ecma262/#sec-array.prototype.foreach
arrayForEach=!STRICT_METHOD?function forEach(callbackfn/* , thisArg */){return $forEach(this,callbackfn,arguments.length>1?arguments[1]:undefined);// eslint-disable-next-line es/no-array-prototype-foreach -- safe
}:[].forEach;return arrayForEach;}var hasRequiredEs_array_forEach;function requireEs_array_forEach(){if(hasRequiredEs_array_forEach)return es_array_forEach;hasRequiredEs_array_forEach=1;var $=/*@__PURE__*/require_export();var forEach=/*@__PURE__*/requireArrayForEach();// `Array.prototype.forEach` method
// https://tc39.es/ecma262/#sec-array.prototype.foreach
// eslint-disable-next-line es/no-array-prototype-foreach -- safe
$({target:'Array',proto:true,forced:[].forEach!==forEach},{forEach:forEach});return es_array_forEach;}var forEach$4;var hasRequiredForEach$3;function requireForEach$3(){if(hasRequiredForEach$3)return forEach$4;hasRequiredForEach$3=1;requireEs_array_forEach();var getBuiltInPrototypeMethod=/*@__PURE__*/requireGetBuiltInPrototypeMethod();forEach$4=getBuiltInPrototypeMethod('Array','forEach');return forEach$4;}var forEach$3;var hasRequiredForEach$2;function requireForEach$2(){if(hasRequiredForEach$2)return forEach$3;hasRequiredForEach$2=1;var parent=/*@__PURE__*/requireForEach$3();forEach$3=parent;return forEach$3;}var forEach$2;var hasRequiredForEach$1;function requireForEach$1(){if(hasRequiredForEach$1)return forEach$2;hasRequiredForEach$1=1;var classof=/*@__PURE__*/requireClassof();var hasOwn=/*@__PURE__*/requireHasOwnProperty();var isPrototypeOf=/*@__PURE__*/requireObjectIsPrototypeOf();var method=/*@__PURE__*/requireForEach$2();var ArrayPrototype=Array.prototype;var DOMIterables={DOMTokenList:true,NodeList:true};forEach$2=function(it){var own=it.forEach;return it===ArrayPrototype||isPrototypeOf(ArrayPrototype,it)&&own===ArrayPrototype.forEach||hasOwn(DOMIterables,classof(it))?method:own;};return forEach$2;}var forEach$1;var hasRequiredForEach;function requireForEach(){if(hasRequiredForEach)return forEach$1;hasRequiredForEach=1;forEach$1=/*@__PURE__*/requireForEach$1();return forEach$1;}var forEachExports=requireForEach();var _forEachInstanceProperty=/*@__PURE__*/getDefaultExportFromCjs(forEachExports);var es_array_reverse={};var hasRequiredEs_array_reverse;function requireEs_array_reverse(){if(hasRequiredEs_array_reverse)return es_array_reverse;hasRequiredEs_array_reverse=1;var $=/*@__PURE__*/require_export();var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var isArray=/*@__PURE__*/requireIsArray$3();var nativeReverse=uncurryThis([].reverse);var test=[1,2];// `Array.prototype.reverse` method
// https://tc39.es/ecma262/#sec-array.prototype.reverse
// fix for Safari 12.0 bug
// https://bugs.webkit.org/show_bug.cgi?id=188794
$({target:'Array',proto:true,forced:String(test)===String(test.reverse())},{reverse:function reverse(){// eslint-disable-next-line no-self-assign -- dirty hack
if(isArray(this))this.length=this.length;return nativeReverse(this);}});return es_array_reverse;}var reverse$3;var hasRequiredReverse$3;function requireReverse$3(){if(hasRequiredReverse$3)return reverse$3;hasRequiredReverse$3=1;requireEs_array_reverse();var getBuiltInPrototypeMethod=/*@__PURE__*/requireGetBuiltInPrototypeMethod();reverse$3=getBuiltInPrototypeMethod('Array','reverse');return reverse$3;}var reverse$2;var hasRequiredReverse$2;function requireReverse$2(){if(hasRequiredReverse$2)return reverse$2;hasRequiredReverse$2=1;var isPrototypeOf=/*@__PURE__*/requireObjectIsPrototypeOf();var method=/*@__PURE__*/requireReverse$3();var ArrayPrototype=Array.prototype;reverse$2=function(it){var own=it.reverse;return it===ArrayPrototype||isPrototypeOf(ArrayPrototype,it)&&own===ArrayPrototype.reverse?method:own;};return reverse$2;}var reverse$1;var hasRequiredReverse$1;function requireReverse$1(){if(hasRequiredReverse$1)return reverse$1;hasRequiredReverse$1=1;var parent=/*@__PURE__*/requireReverse$2();reverse$1=parent;return reverse$1;}var reverse;var hasRequiredReverse;function requireReverse(){if(hasRequiredReverse)return reverse;hasRequiredReverse=1;reverse=/*@__PURE__*/requireReverse$1();return reverse;}var reverseExports=requireReverse();var _reverseInstanceProperty=/*@__PURE__*/getDefaultExportFromCjs(reverseExports);var es_array_splice={};var arraySetLength;var hasRequiredArraySetLength;function requireArraySetLength(){if(hasRequiredArraySetLength)return arraySetLength;hasRequiredArraySetLength=1;var DESCRIPTORS=/*@__PURE__*/requireDescriptors();var isArray=/*@__PURE__*/requireIsArray$3();var $TypeError=TypeError;// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var getOwnPropertyDescriptor=Object.getOwnPropertyDescriptor;// Safari < 13 does not throw an error in this case
var SILENT_ON_NON_WRITABLE_LENGTH_SET=DESCRIPTORS&&!function(){// makes no sense without proper strict mode support
if(this!==undefined)return true;try{// eslint-disable-next-line es/no-object-defineproperty -- safe
Object.defineProperty([],'length',{writable:false}).length=1;}catch(error){return error instanceof TypeError;}}();arraySetLength=SILENT_ON_NON_WRITABLE_LENGTH_SET?function(O,length){if(isArray(O)&&!getOwnPropertyDescriptor(O,'length').writable){throw new $TypeError('Cannot set read only .length');}return O.length=length;}:function(O,length){return O.length=length;};return arraySetLength;}var deletePropertyOrThrow;var hasRequiredDeletePropertyOrThrow;function requireDeletePropertyOrThrow(){if(hasRequiredDeletePropertyOrThrow)return deletePropertyOrThrow;hasRequiredDeletePropertyOrThrow=1;var tryToString=/*@__PURE__*/requireTryToString();var $TypeError=TypeError;deletePropertyOrThrow=function(O,P){if(!delete O[P])throw new $TypeError('Cannot delete property '+tryToString(P)+' of '+tryToString(O));};return deletePropertyOrThrow;}var hasRequiredEs_array_splice;function requireEs_array_splice(){if(hasRequiredEs_array_splice)return es_array_splice;hasRequiredEs_array_splice=1;var $=/*@__PURE__*/require_export();var toObject=/*@__PURE__*/requireToObject();var toAbsoluteIndex=/*@__PURE__*/requireToAbsoluteIndex();var toIntegerOrInfinity=/*@__PURE__*/requireToIntegerOrInfinity();var lengthOfArrayLike=/*@__PURE__*/requireLengthOfArrayLike();var setArrayLength=/*@__PURE__*/requireArraySetLength();var doesNotExceedSafeInteger=/*@__PURE__*/requireDoesNotExceedSafeInteger();var arraySpeciesCreate=/*@__PURE__*/requireArraySpeciesCreate();var createProperty=/*@__PURE__*/requireCreateProperty();var deletePropertyOrThrow=/*@__PURE__*/requireDeletePropertyOrThrow();var arrayMethodHasSpeciesSupport=/*@__PURE__*/requireArrayMethodHasSpeciesSupport();var HAS_SPECIES_SUPPORT=arrayMethodHasSpeciesSupport('splice');var max=Math.max;var min=Math.min;// `Array.prototype.splice` method
// https://tc39.es/ecma262/#sec-array.prototype.splice
// with adding support of @@species
$({target:'Array',proto:true,forced:!HAS_SPECIES_SUPPORT},{splice:function splice(start,deleteCount/* , ...items */){var O=toObject(this);var len=lengthOfArrayLike(O);var actualStart=toAbsoluteIndex(start,len);var argumentsLength=arguments.length;var insertCount,actualDeleteCount,A,k,from,to;if(argumentsLength===0){insertCount=actualDeleteCount=0;}else if(argumentsLength===1){insertCount=0;actualDeleteCount=len-actualStart;}else {insertCount=argumentsLength-2;actualDeleteCount=min(max(toIntegerOrInfinity(deleteCount),0),len-actualStart);}doesNotExceedSafeInteger(len+insertCount-actualDeleteCount);A=arraySpeciesCreate(O,actualDeleteCount);for(k=0;k<actualDeleteCount;k++){from=actualStart+k;if(from in O)createProperty(A,k,O[from]);}A.length=actualDeleteCount;if(insertCount<actualDeleteCount){for(k=actualStart;k<len-actualDeleteCount;k++){from=k+actualDeleteCount;to=k+insertCount;if(from in O)O[to]=O[from];else deletePropertyOrThrow(O,to);}for(k=len;k>len-actualDeleteCount+insertCount;k--)deletePropertyOrThrow(O,k-1);}else if(insertCount>actualDeleteCount){for(k=len-actualDeleteCount;k>actualStart;k--){from=k+actualDeleteCount-1;to=k+insertCount-1;if(from in O)O[to]=O[from];else deletePropertyOrThrow(O,to);}}for(k=0;k<insertCount;k++){O[k+actualStart]=arguments[k+2];}setArrayLength(O,len-actualDeleteCount+insertCount);return A;}});return es_array_splice;}var splice$3;var hasRequiredSplice$3;function requireSplice$3(){if(hasRequiredSplice$3)return splice$3;hasRequiredSplice$3=1;requireEs_array_splice();var getBuiltInPrototypeMethod=/*@__PURE__*/requireGetBuiltInPrototypeMethod();splice$3=getBuiltInPrototypeMethod('Array','splice');return splice$3;}var splice$2;var hasRequiredSplice$2;function requireSplice$2(){if(hasRequiredSplice$2)return splice$2;hasRequiredSplice$2=1;var isPrototypeOf=/*@__PURE__*/requireObjectIsPrototypeOf();var method=/*@__PURE__*/requireSplice$3();var ArrayPrototype=Array.prototype;splice$2=function(it){var own=it.splice;return it===ArrayPrototype||isPrototypeOf(ArrayPrototype,it)&&own===ArrayPrototype.splice?method:own;};return splice$2;}var splice$1;var hasRequiredSplice$1;function requireSplice$1(){if(hasRequiredSplice$1)return splice$1;hasRequiredSplice$1=1;var parent=/*@__PURE__*/requireSplice$2();splice$1=parent;return splice$1;}var splice;var hasRequiredSplice;function requireSplice(){if(hasRequiredSplice)return splice;hasRequiredSplice=1;splice=/*@__PURE__*/requireSplice$1();return splice;}var spliceExports=requireSplice();var _spliceInstanceProperty=/*@__PURE__*/getDefaultExportFromCjs(spliceExports);var es_array_includes={};var hasRequiredEs_array_includes;function requireEs_array_includes(){if(hasRequiredEs_array_includes)return es_array_includes;hasRequiredEs_array_includes=1;var $=/*@__PURE__*/require_export();var $includes=/*@__PURE__*/requireArrayIncludes().includes;var fails=/*@__PURE__*/requireFails();var addToUnscopables=/*@__PURE__*/requireAddToUnscopables();// FF99+ bug
var BROKEN_ON_SPARSE=fails(function(){// eslint-disable-next-line es/no-array-prototype-includes -- detection
return !Array(1).includes();});// `Array.prototype.includes` method
// https://tc39.es/ecma262/#sec-array.prototype.includes
$({target:'Array',proto:true,forced:BROKEN_ON_SPARSE},{includes:function includes(el/* , fromIndex = 0 */){return $includes(this,el,arguments.length>1?arguments[1]:undefined);}});// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables('includes');return es_array_includes;}var includes$4;var hasRequiredIncludes$4;function requireIncludes$4(){if(hasRequiredIncludes$4)return includes$4;hasRequiredIncludes$4=1;requireEs_array_includes();var getBuiltInPrototypeMethod=/*@__PURE__*/requireGetBuiltInPrototypeMethod();includes$4=getBuiltInPrototypeMethod('Array','includes');return includes$4;}var es_string_includes={};var isRegexp;var hasRequiredIsRegexp;function requireIsRegexp(){if(hasRequiredIsRegexp)return isRegexp;hasRequiredIsRegexp=1;var isObject=/*@__PURE__*/requireIsObject();var classof=/*@__PURE__*/requireClassofRaw();var wellKnownSymbol=/*@__PURE__*/requireWellKnownSymbol();var MATCH=wellKnownSymbol('match');// `IsRegExp` abstract operation
// https://tc39.es/ecma262/#sec-isregexp
isRegexp=function(it){var isRegExp;return isObject(it)&&((isRegExp=it[MATCH])!==undefined?!!isRegExp:classof(it)==='RegExp');};return isRegexp;}var notARegexp;var hasRequiredNotARegexp;function requireNotARegexp(){if(hasRequiredNotARegexp)return notARegexp;hasRequiredNotARegexp=1;var isRegExp=/*@__PURE__*/requireIsRegexp();var $TypeError=TypeError;notARegexp=function(it){if(isRegExp(it)){throw new $TypeError("The method doesn't accept regular expressions");}return it;};return notARegexp;}var correctIsRegexpLogic;var hasRequiredCorrectIsRegexpLogic;function requireCorrectIsRegexpLogic(){if(hasRequiredCorrectIsRegexpLogic)return correctIsRegexpLogic;hasRequiredCorrectIsRegexpLogic=1;var wellKnownSymbol=/*@__PURE__*/requireWellKnownSymbol();var MATCH=wellKnownSymbol('match');correctIsRegexpLogic=function(METHOD_NAME){var regexp=/./;try{'/./'[METHOD_NAME](regexp);}catch(error1){try{regexp[MATCH]=false;return '/./'[METHOD_NAME](regexp);}catch(error2){/* empty */}}return false;};return correctIsRegexpLogic;}var hasRequiredEs_string_includes;function requireEs_string_includes(){if(hasRequiredEs_string_includes)return es_string_includes;hasRequiredEs_string_includes=1;var $=/*@__PURE__*/require_export();var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var notARegExp=/*@__PURE__*/requireNotARegexp();var requireObjectCoercible=/*@__PURE__*/requireRequireObjectCoercible();var toString=/*@__PURE__*/requireToString();var correctIsRegExpLogic=/*@__PURE__*/requireCorrectIsRegexpLogic();var stringIndexOf=uncurryThis(''.indexOf);// `String.prototype.includes` method
// https://tc39.es/ecma262/#sec-string.prototype.includes
$({target:'String',proto:true,forced:!correctIsRegExpLogic('includes')},{includes:function includes(searchString/* , position = 0 */){return !!~stringIndexOf(toString(requireObjectCoercible(this)),toString(notARegExp(searchString)),arguments.length>1?arguments[1]:undefined);}});return es_string_includes;}var includes$3;var hasRequiredIncludes$3;function requireIncludes$3(){if(hasRequiredIncludes$3)return includes$3;hasRequiredIncludes$3=1;requireEs_string_includes();var getBuiltInPrototypeMethod=/*@__PURE__*/requireGetBuiltInPrototypeMethod();includes$3=getBuiltInPrototypeMethod('String','includes');return includes$3;}var includes$2;var hasRequiredIncludes$2;function requireIncludes$2(){if(hasRequiredIncludes$2)return includes$2;hasRequiredIncludes$2=1;var isPrototypeOf=/*@__PURE__*/requireObjectIsPrototypeOf();var arrayMethod=/*@__PURE__*/requireIncludes$4();var stringMethod=/*@__PURE__*/requireIncludes$3();var ArrayPrototype=Array.prototype;var StringPrototype=String.prototype;includes$2=function(it){var own=it.includes;if(it===ArrayPrototype||isPrototypeOf(ArrayPrototype,it)&&own===ArrayPrototype.includes)return arrayMethod;if(typeof it=='string'||it===StringPrototype||isPrototypeOf(StringPrototype,it)&&own===StringPrototype.includes){return stringMethod;}return own;};return includes$2;}var includes$1;var hasRequiredIncludes$1;function requireIncludes$1(){if(hasRequiredIncludes$1)return includes$1;hasRequiredIncludes$1=1;var parent=/*@__PURE__*/requireIncludes$2();includes$1=parent;return includes$1;}var includes;var hasRequiredIncludes;function requireIncludes(){if(hasRequiredIncludes)return includes;hasRequiredIncludes=1;includes=/*@__PURE__*/requireIncludes$1();return includes;}var includesExports=requireIncludes();var _includesInstanceProperty=/*@__PURE__*/getDefaultExportFromCjs(includesExports);var es_object_getPrototypeOf={};var hasRequiredEs_object_getPrototypeOf;function requireEs_object_getPrototypeOf(){if(hasRequiredEs_object_getPrototypeOf)return es_object_getPrototypeOf;hasRequiredEs_object_getPrototypeOf=1;var $=/*@__PURE__*/require_export();var fails=/*@__PURE__*/requireFails();var toObject=/*@__PURE__*/requireToObject();var nativeGetPrototypeOf=/*@__PURE__*/requireObjectGetPrototypeOf();var CORRECT_PROTOTYPE_GETTER=/*@__PURE__*/requireCorrectPrototypeGetter();var FAILS_ON_PRIMITIVES=fails(function(){nativeGetPrototypeOf(1);});// `Object.getPrototypeOf` method
// https://tc39.es/ecma262/#sec-object.getprototypeof
$({target:'Object',stat:true,forced:FAILS_ON_PRIMITIVES,sham:!CORRECT_PROTOTYPE_GETTER},{getPrototypeOf:function getPrototypeOf(it){return nativeGetPrototypeOf(toObject(it));}});return es_object_getPrototypeOf;}var getPrototypeOf$2;var hasRequiredGetPrototypeOf$2;function requireGetPrototypeOf$2(){if(hasRequiredGetPrototypeOf$2)return getPrototypeOf$2;hasRequiredGetPrototypeOf$2=1;requireEs_object_getPrototypeOf();var path=/*@__PURE__*/requirePath();getPrototypeOf$2=path.Object.getPrototypeOf;return getPrototypeOf$2;}var getPrototypeOf$1;var hasRequiredGetPrototypeOf$1;function requireGetPrototypeOf$1(){if(hasRequiredGetPrototypeOf$1)return getPrototypeOf$1;hasRequiredGetPrototypeOf$1=1;var parent=/*@__PURE__*/requireGetPrototypeOf$2();getPrototypeOf$1=parent;return getPrototypeOf$1;}var getPrototypeOf;var hasRequiredGetPrototypeOf;function requireGetPrototypeOf(){if(hasRequiredGetPrototypeOf)return getPrototypeOf;hasRequiredGetPrototypeOf=1;getPrototypeOf=/*@__PURE__*/requireGetPrototypeOf$1();return getPrototypeOf;}var getPrototypeOfExports=requireGetPrototypeOf();var _Object$getPrototypeOf=/*@__PURE__*/getDefaultExportFromCjs(getPrototypeOfExports);var concat$3;var hasRequiredConcat$3;function requireConcat$3(){if(hasRequiredConcat$3)return concat$3;hasRequiredConcat$3=1;requireEs_array_concat();var getBuiltInPrototypeMethod=/*@__PURE__*/requireGetBuiltInPrototypeMethod();concat$3=getBuiltInPrototypeMethod('Array','concat');return concat$3;}var concat$2;var hasRequiredConcat$2;function requireConcat$2(){if(hasRequiredConcat$2)return concat$2;hasRequiredConcat$2=1;var isPrototypeOf=/*@__PURE__*/requireObjectIsPrototypeOf();var method=/*@__PURE__*/requireConcat$3();var ArrayPrototype=Array.prototype;concat$2=function(it){var own=it.concat;return it===ArrayPrototype||isPrototypeOf(ArrayPrototype,it)&&own===ArrayPrototype.concat?method:own;};return concat$2;}var concat$1;var hasRequiredConcat$1;function requireConcat$1(){if(hasRequiredConcat$1)return concat$1;hasRequiredConcat$1=1;var parent=/*@__PURE__*/requireConcat$2();concat$1=parent;return concat$1;}var concat;var hasRequiredConcat;function requireConcat(){if(hasRequiredConcat)return concat;hasRequiredConcat=1;concat=/*@__PURE__*/requireConcat$1();return concat;}var concatExports=requireConcat();var _concatInstanceProperty=/*@__PURE__*/getDefaultExportFromCjs(concatExports);var es_array_filter={};var hasRequiredEs_array_filter;function requireEs_array_filter(){if(hasRequiredEs_array_filter)return es_array_filter;hasRequiredEs_array_filter=1;var $=/*@__PURE__*/require_export();var $filter=/*@__PURE__*/requireArrayIteration().filter;var arrayMethodHasSpeciesSupport=/*@__PURE__*/requireArrayMethodHasSpeciesSupport();var HAS_SPECIES_SUPPORT=arrayMethodHasSpeciesSupport('filter');// `Array.prototype.filter` method
// https://tc39.es/ecma262/#sec-array.prototype.filter
// with adding support of @@species
$({target:'Array',proto:true,forced:!HAS_SPECIES_SUPPORT},{filter:function filter(callbackfn/* , thisArg */){return $filter(this,callbackfn,arguments.length>1?arguments[1]:undefined);}});return es_array_filter;}var filter$3;var hasRequiredFilter$3;function requireFilter$3(){if(hasRequiredFilter$3)return filter$3;hasRequiredFilter$3=1;requireEs_array_filter();var getBuiltInPrototypeMethod=/*@__PURE__*/requireGetBuiltInPrototypeMethod();filter$3=getBuiltInPrototypeMethod('Array','filter');return filter$3;}var filter$2;var hasRequiredFilter$2;function requireFilter$2(){if(hasRequiredFilter$2)return filter$2;hasRequiredFilter$2=1;var isPrototypeOf=/*@__PURE__*/requireObjectIsPrototypeOf();var method=/*@__PURE__*/requireFilter$3();var ArrayPrototype=Array.prototype;filter$2=function(it){var own=it.filter;return it===ArrayPrototype||isPrototypeOf(ArrayPrototype,it)&&own===ArrayPrototype.filter?method:own;};return filter$2;}var filter$1;var hasRequiredFilter$1;function requireFilter$1(){if(hasRequiredFilter$1)return filter$1;hasRequiredFilter$1=1;var parent=/*@__PURE__*/requireFilter$2();filter$1=parent;return filter$1;}var filter;var hasRequiredFilter;function requireFilter(){if(hasRequiredFilter)return filter;hasRequiredFilter=1;filter=/*@__PURE__*/requireFilter$1();return filter;}var filterExports=requireFilter();var _filterInstanceProperty=/*@__PURE__*/getDefaultExportFromCjs(filterExports);var es_object_values={};var objectToArray;var hasRequiredObjectToArray;function requireObjectToArray(){if(hasRequiredObjectToArray)return objectToArray;hasRequiredObjectToArray=1;var DESCRIPTORS=/*@__PURE__*/requireDescriptors();var fails=/*@__PURE__*/requireFails();var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var objectGetPrototypeOf=/*@__PURE__*/requireObjectGetPrototypeOf();var objectKeys=/*@__PURE__*/requireObjectKeys();var toIndexedObject=/*@__PURE__*/requireToIndexedObject();var $propertyIsEnumerable=/*@__PURE__*/requireObjectPropertyIsEnumerable().f;var propertyIsEnumerable=uncurryThis($propertyIsEnumerable);var push=uncurryThis([].push);// in some IE versions, `propertyIsEnumerable` returns incorrect result on integer keys
// of `null` prototype objects
var IE_BUG=DESCRIPTORS&&fails(function(){// eslint-disable-next-line es/no-object-create -- safe
var O=Object.create(null);O[2]=2;return !propertyIsEnumerable(O,2);});// `Object.{ entries, values }` methods implementation
var createMethod=function(TO_ENTRIES){return function(it){var O=toIndexedObject(it);var keys=objectKeys(O);var IE_WORKAROUND=IE_BUG&&objectGetPrototypeOf(O)===null;var length=keys.length;var i=0;var result=[];var key;while(length>i){key=keys[i++];if(!DESCRIPTORS||(IE_WORKAROUND?key in O:propertyIsEnumerable(O,key))){push(result,TO_ENTRIES?[key,O[key]]:O[key]);}}return result;};};objectToArray={// `Object.entries` method
// https://tc39.es/ecma262/#sec-object.entries
entries:createMethod(true),// `Object.values` method
// https://tc39.es/ecma262/#sec-object.values
values:createMethod(false)};return objectToArray;}var hasRequiredEs_object_values;function requireEs_object_values(){if(hasRequiredEs_object_values)return es_object_values;hasRequiredEs_object_values=1;var $=/*@__PURE__*/require_export();var $values=/*@__PURE__*/requireObjectToArray().values;// `Object.values` method
// https://tc39.es/ecma262/#sec-object.values
$({target:'Object',stat:true},{values:function values(O){return $values(O);}});return es_object_values;}var values$6;var hasRequiredValues$6;function requireValues$6(){if(hasRequiredValues$6)return values$6;hasRequiredValues$6=1;requireEs_object_values();var path=/*@__PURE__*/requirePath();values$6=path.Object.values;return values$6;}var values$5;var hasRequiredValues$5;function requireValues$5(){if(hasRequiredValues$5)return values$5;hasRequiredValues$5=1;var parent=/*@__PURE__*/requireValues$6();values$5=parent;return values$5;}var values$4;var hasRequiredValues$4;function requireValues$4(){if(hasRequiredValues$4)return values$4;hasRequiredValues$4=1;values$4=/*@__PURE__*/requireValues$5();return values$4;}var valuesExports$1=requireValues$4();var _Object$values=/*@__PURE__*/getDefaultExportFromCjs(valuesExports$1);var es_parseInt={};var whitespaces;var hasRequiredWhitespaces;function requireWhitespaces(){if(hasRequiredWhitespaces)return whitespaces;hasRequiredWhitespaces=1;// a string of all valid unicode whitespaces
whitespaces='\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u2000\u2001\u2002'+'\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF';return whitespaces;}var stringTrim;var hasRequiredStringTrim;function requireStringTrim(){if(hasRequiredStringTrim)return stringTrim;hasRequiredStringTrim=1;var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var requireObjectCoercible=/*@__PURE__*/requireRequireObjectCoercible();var toString=/*@__PURE__*/requireToString();var whitespaces=/*@__PURE__*/requireWhitespaces();var replace=uncurryThis(''.replace);var ltrim=RegExp('^['+whitespaces+']+');var rtrim=RegExp('(^|[^'+whitespaces+'])['+whitespaces+']+$');// `String.prototype.{ trim, trimStart, trimEnd, trimLeft, trimRight }` methods implementation
var createMethod=function(TYPE){return function($this){var string=toString(requireObjectCoercible($this));if(TYPE&1)string=replace(string,ltrim,'');if(TYPE&2)string=replace(string,rtrim,'$1');return string;};};stringTrim={// `String.prototype.{ trimLeft, trimStart }` methods
// https://tc39.es/ecma262/#sec-string.prototype.trimstart
start:createMethod(1),// `String.prototype.{ trimRight, trimEnd }` methods
// https://tc39.es/ecma262/#sec-string.prototype.trimend
end:createMethod(2),// `String.prototype.trim` method
// https://tc39.es/ecma262/#sec-string.prototype.trim
trim:createMethod(3)};return stringTrim;}var numberParseInt;var hasRequiredNumberParseInt;function requireNumberParseInt(){if(hasRequiredNumberParseInt)return numberParseInt;hasRequiredNumberParseInt=1;var globalThis=/*@__PURE__*/requireGlobalThis();var fails=/*@__PURE__*/requireFails();var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var toString=/*@__PURE__*/requireToString();var trim=/*@__PURE__*/requireStringTrim().trim;var whitespaces=/*@__PURE__*/requireWhitespaces();var $parseInt=globalThis.parseInt;var Symbol=globalThis.Symbol;var ITERATOR=Symbol&&Symbol.iterator;var hex=/^[+-]?0x/i;var exec=uncurryThis(hex.exec);var FORCED=$parseInt(whitespaces+'08')!==8||$parseInt(whitespaces+'0x16')!==22// MS Edge 18- broken with boxed symbols
||ITERATOR&&!fails(function(){$parseInt(Object(ITERATOR));});// `parseInt` method
// https://tc39.es/ecma262/#sec-parseint-string-radix
numberParseInt=FORCED?function parseInt(string,radix){var S=trim(toString(string));return $parseInt(S,radix>>>0||(exec(hex,S)?16:10));}:$parseInt;return numberParseInt;}var hasRequiredEs_parseInt;function requireEs_parseInt(){if(hasRequiredEs_parseInt)return es_parseInt;hasRequiredEs_parseInt=1;var $=/*@__PURE__*/require_export();var $parseInt=/*@__PURE__*/requireNumberParseInt();// `parseInt` method
// https://tc39.es/ecma262/#sec-parseint-string-radix
$({global:true,forced:parseInt!==$parseInt},{parseInt:$parseInt});return es_parseInt;}var _parseInt$3;var hasRequired_parseInt$2;function require_parseInt$2(){if(hasRequired_parseInt$2)return _parseInt$3;hasRequired_parseInt$2=1;requireEs_parseInt();var path=/*@__PURE__*/requirePath();_parseInt$3=path.parseInt;return _parseInt$3;}var _parseInt$2;var hasRequired_parseInt$1;function require_parseInt$1(){if(hasRequired_parseInt$1)return _parseInt$2;hasRequired_parseInt$1=1;var parent=/*@__PURE__*/require_parseInt$2();_parseInt$2=parent;return _parseInt$2;}var _parseInt$1;var hasRequired_parseInt;function require_parseInt(){if(hasRequired_parseInt)return _parseInt$1;hasRequired_parseInt=1;_parseInt$1=/*@__PURE__*/require_parseInt$1();return _parseInt$1;}var _parseIntExports=require_parseInt();var _parseInt=/*@__PURE__*/getDefaultExportFromCjs(_parseIntExports);var es_array_indexOf={};var hasRequiredEs_array_indexOf;function requireEs_array_indexOf(){if(hasRequiredEs_array_indexOf)return es_array_indexOf;hasRequiredEs_array_indexOf=1;/* eslint-disable es/no-array-prototype-indexof -- required for testing */var $=/*@__PURE__*/require_export();var uncurryThis=/*@__PURE__*/requireFunctionUncurryThisClause();var $indexOf=/*@__PURE__*/requireArrayIncludes().indexOf;var arrayMethodIsStrict=/*@__PURE__*/requireArrayMethodIsStrict();var nativeIndexOf=uncurryThis([].indexOf);var NEGATIVE_ZERO=!!nativeIndexOf&&1/nativeIndexOf([1],1,-0)<0;var FORCED=NEGATIVE_ZERO||!arrayMethodIsStrict('indexOf');// `Array.prototype.indexOf` method
// https://tc39.es/ecma262/#sec-array.prototype.indexof
$({target:'Array',proto:true,forced:FORCED},{indexOf:function indexOf(searchElement/* , fromIndex = 0 */){var fromIndex=arguments.length>1?arguments[1]:undefined;return NEGATIVE_ZERO// convert -0 to +0
?nativeIndexOf(this,searchElement,fromIndex)||0:$indexOf(this,searchElement,fromIndex);}});return es_array_indexOf;}var indexOf$3;var hasRequiredIndexOf$3;function requireIndexOf$3(){if(hasRequiredIndexOf$3)return indexOf$3;hasRequiredIndexOf$3=1;requireEs_array_indexOf();var getBuiltInPrototypeMethod=/*@__PURE__*/requireGetBuiltInPrototypeMethod();indexOf$3=getBuiltInPrototypeMethod('Array','indexOf');return indexOf$3;}var indexOf$2;var hasRequiredIndexOf$2;function requireIndexOf$2(){if(hasRequiredIndexOf$2)return indexOf$2;hasRequiredIndexOf$2=1;var isPrototypeOf=/*@__PURE__*/requireObjectIsPrototypeOf();var method=/*@__PURE__*/requireIndexOf$3();var ArrayPrototype=Array.prototype;indexOf$2=function(it){var own=it.indexOf;return it===ArrayPrototype||isPrototypeOf(ArrayPrototype,it)&&own===ArrayPrototype.indexOf?method:own;};return indexOf$2;}var indexOf$1;var hasRequiredIndexOf$1;function requireIndexOf$1(){if(hasRequiredIndexOf$1)return indexOf$1;hasRequiredIndexOf$1=1;var parent=/*@__PURE__*/requireIndexOf$2();indexOf$1=parent;return indexOf$1;}var indexOf;var hasRequiredIndexOf;function requireIndexOf(){if(hasRequiredIndexOf)return indexOf;hasRequiredIndexOf=1;indexOf=/*@__PURE__*/requireIndexOf$1();return indexOf;}var indexOfExports=requireIndexOf();var _indexOfInstanceProperty=/*@__PURE__*/getDefaultExportFromCjs(indexOfExports);var es_object_create={};var hasRequiredEs_object_create;function requireEs_object_create(){if(hasRequiredEs_object_create)return es_object_create;hasRequiredEs_object_create=1;// TODO: Remove from `core-js@4`
var $=/*@__PURE__*/require_export();var DESCRIPTORS=/*@__PURE__*/requireDescriptors();var create=/*@__PURE__*/requireObjectCreate();// `Object.create` method
// https://tc39.es/ecma262/#sec-object.create
$({target:'Object',stat:true,sham:!DESCRIPTORS},{create:create});return es_object_create;}var create$2;var hasRequiredCreate$2;function requireCreate$2(){if(hasRequiredCreate$2)return create$2;hasRequiredCreate$2=1;requireEs_object_create();var path=/*@__PURE__*/requirePath();var Object=path.Object;create$2=function create(P,D){return Object.create(P,D);};return create$2;}var create$1;var hasRequiredCreate$1;function requireCreate$1(){if(hasRequiredCreate$1)return create$1;hasRequiredCreate$1=1;var parent=/*@__PURE__*/requireCreate$2();create$1=parent;return create$1;}var create;var hasRequiredCreate;function requireCreate(){if(hasRequiredCreate)return create;hasRequiredCreate=1;create=/*@__PURE__*/requireCreate$1();return create;}var createExports=requireCreate();var _Object$create=/*@__PURE__*/getDefaultExportFromCjs(createExports);var es_date_toJson={};var stringRepeat;var hasRequiredStringRepeat;function requireStringRepeat(){if(hasRequiredStringRepeat)return stringRepeat;hasRequiredStringRepeat=1;var toIntegerOrInfinity=/*@__PURE__*/requireToIntegerOrInfinity();var toString=/*@__PURE__*/requireToString();var requireObjectCoercible=/*@__PURE__*/requireRequireObjectCoercible();var $RangeError=RangeError;// `String.prototype.repeat` method implementation
// https://tc39.es/ecma262/#sec-string.prototype.repeat
stringRepeat=function repeat(count){var str=toString(requireObjectCoercible(this));var result='';var n=toIntegerOrInfinity(count);if(n<0||n===Infinity)throw new $RangeError('Wrong number of repetitions');for(;n>0;(n>>>=1)&&(str+=str))if(n&1)result+=str;return result;};return stringRepeat;}var stringPad;var hasRequiredStringPad;function requireStringPad(){if(hasRequiredStringPad)return stringPad;hasRequiredStringPad=1;var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var toLength=/*@__PURE__*/requireToLength();var toString=/*@__PURE__*/requireToString();var $repeat=/*@__PURE__*/requireStringRepeat();var requireObjectCoercible=/*@__PURE__*/requireRequireObjectCoercible();var repeat=uncurryThis($repeat);var stringSlice=uncurryThis(''.slice);var ceil=Math.ceil;// `String.prototype.{ padStart, padEnd }` methods implementation
var createMethod=function(IS_END){return function($this,maxLength,fillString){var S=toString(requireObjectCoercible($this));var intMaxLength=toLength(maxLength);var stringLength=S.length;var fillStr=fillString===undefined?' ':toString(fillString);var fillLen,stringFiller;if(intMaxLength<=stringLength||fillStr==='')return S;fillLen=intMaxLength-stringLength;stringFiller=repeat(fillStr,ceil(fillLen/fillStr.length));if(stringFiller.length>fillLen)stringFiller=stringSlice(stringFiller,0,fillLen);return IS_END?S+stringFiller:stringFiller+S;};};stringPad={// `String.prototype.padStart` method
// https://tc39.es/ecma262/#sec-string.prototype.padstart
start:createMethod(false),// `String.prototype.padEnd` method
// https://tc39.es/ecma262/#sec-string.prototype.padend
end:createMethod(true)};return stringPad;}var dateToIsoString;var hasRequiredDateToIsoString;function requireDateToIsoString(){if(hasRequiredDateToIsoString)return dateToIsoString;hasRequiredDateToIsoString=1;var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var fails=/*@__PURE__*/requireFails();var padStart=/*@__PURE__*/requireStringPad().start;var $RangeError=RangeError;var $isFinite=isFinite;var abs=Math.abs;var DatePrototype=Date.prototype;var nativeDateToISOString=DatePrototype.toISOString;var thisTimeValue=uncurryThis(DatePrototype.getTime);var getUTCDate=uncurryThis(DatePrototype.getUTCDate);var getUTCFullYear=uncurryThis(DatePrototype.getUTCFullYear);var getUTCHours=uncurryThis(DatePrototype.getUTCHours);var getUTCMilliseconds=uncurryThis(DatePrototype.getUTCMilliseconds);var getUTCMinutes=uncurryThis(DatePrototype.getUTCMinutes);var getUTCMonth=uncurryThis(DatePrototype.getUTCMonth);var getUTCSeconds=uncurryThis(DatePrototype.getUTCSeconds);// `Date.prototype.toISOString` method implementation
// https://tc39.es/ecma262/#sec-date.prototype.toisostring
// PhantomJS / old WebKit fails here:
dateToIsoString=fails(function(){return nativeDateToISOString.call(new Date(-5e13-1))!=='0385-07-25T07:06:39.999Z';})||!fails(function(){nativeDateToISOString.call(new Date(NaN));})?function toISOString(){if(!$isFinite(thisTimeValue(this)))throw new $RangeError('Invalid time value');var date=this;var year=getUTCFullYear(date);var milliseconds=getUTCMilliseconds(date);var sign=year<0?'-':year>9999?'+':'';return sign+padStart(abs(year),sign?6:4,0)+'-'+padStart(getUTCMonth(date)+1,2,0)+'-'+padStart(getUTCDate(date),2,0)+'T'+padStart(getUTCHours(date),2,0)+':'+padStart(getUTCMinutes(date),2,0)+':'+padStart(getUTCSeconds(date),2,0)+'.'+padStart(milliseconds,3,0)+'Z';}:nativeDateToISOString;return dateToIsoString;}var hasRequiredEs_date_toJson;function requireEs_date_toJson(){if(hasRequiredEs_date_toJson)return es_date_toJson;hasRequiredEs_date_toJson=1;var $=/*@__PURE__*/require_export();var call=/*@__PURE__*/requireFunctionCall();var toObject=/*@__PURE__*/requireToObject();var toPrimitive=/*@__PURE__*/requireToPrimitive$5();var toISOString=/*@__PURE__*/requireDateToIsoString();var classof=/*@__PURE__*/requireClassofRaw();var fails=/*@__PURE__*/requireFails();var FORCED=fails(function(){return new Date(NaN).toJSON()!==null||call(Date.prototype.toJSON,{toISOString:function(){return 1;}})!==1;});// `Date.prototype.toJSON` method
// https://tc39.es/ecma262/#sec-date.prototype.tojson
$({target:'Date',proto:true,forced:FORCED},{// eslint-disable-next-line no-unused-vars -- required for `.length`
toJSON:function toJSON(key){var O=toObject(this);var pv=toPrimitive(O,'number');return typeof pv=='number'&&!isFinite(pv)?null:!('toISOString'in O)&&classof(O)==='Date'?call(toISOString,O):O.toISOString();}});return es_date_toJson;}var stringify$2;var hasRequiredStringify$2;function requireStringify$2(){if(hasRequiredStringify$2)return stringify$2;hasRequiredStringify$2=1;requireEs_date_toJson();requireEs_json_stringify();var path=/*@__PURE__*/requirePath();var apply=/*@__PURE__*/requireFunctionApply();// eslint-disable-next-line es/no-json -- safe
if(!path.JSON)path.JSON={stringify:JSON.stringify};// eslint-disable-next-line no-unused-vars -- required for `.length`
stringify$2=function stringify(it,replacer,space){return apply(path.JSON.stringify,null,arguments);};return stringify$2;}var stringify$1;var hasRequiredStringify$1;function requireStringify$1(){if(hasRequiredStringify$1)return stringify$1;hasRequiredStringify$1=1;var parent=/*@__PURE__*/requireStringify$2();stringify$1=parent;return stringify$1;}var stringify;var hasRequiredStringify;function requireStringify(){if(hasRequiredStringify)return stringify;hasRequiredStringify=1;stringify=/*@__PURE__*/requireStringify$1();return stringify;}var stringifyExports=requireStringify();var _JSON$stringify=/*@__PURE__*/getDefaultExportFromCjs(stringifyExports);var web_timers={};var web_setInterval={};var environment;var hasRequiredEnvironment;function requireEnvironment(){if(hasRequiredEnvironment)return environment;hasRequiredEnvironment=1;/* global Bun, Deno -- detection */var globalThis=/*@__PURE__*/requireGlobalThis();var userAgent=/*@__PURE__*/requireEnvironmentUserAgent();var classof=/*@__PURE__*/requireClassofRaw();var userAgentStartsWith=function(string){return userAgent.slice(0,string.length)===string;};environment=function(){if(userAgentStartsWith('Bun/'))return 'BUN';if(userAgentStartsWith('Cloudflare-Workers'))return 'CLOUDFLARE';if(userAgentStartsWith('Deno/'))return 'DENO';if(userAgentStartsWith('Node.js/'))return 'NODE';if(globalThis.Bun&&typeof Bun.version=='string')return 'BUN';if(globalThis.Deno&&typeof Deno.version=='object')return 'DENO';if(classof(globalThis.process)==='process')return 'NODE';if(globalThis.window&&globalThis.document)return 'BROWSER';return 'REST';}();return environment;}var validateArgumentsLength;var hasRequiredValidateArgumentsLength;function requireValidateArgumentsLength(){if(hasRequiredValidateArgumentsLength)return validateArgumentsLength;hasRequiredValidateArgumentsLength=1;var $TypeError=TypeError;validateArgumentsLength=function(passed,required){if(passed<required)throw new $TypeError('Not enough arguments');return passed;};return validateArgumentsLength;}var schedulersFix;var hasRequiredSchedulersFix;function requireSchedulersFix(){if(hasRequiredSchedulersFix)return schedulersFix;hasRequiredSchedulersFix=1;var globalThis=/*@__PURE__*/requireGlobalThis();var apply=/*@__PURE__*/requireFunctionApply();var isCallable=/*@__PURE__*/requireIsCallable();var ENVIRONMENT=/*@__PURE__*/requireEnvironment();var USER_AGENT=/*@__PURE__*/requireEnvironmentUserAgent();var arraySlice=/*@__PURE__*/requireArraySlice();var validateArgumentsLength=/*@__PURE__*/requireValidateArgumentsLength();var Function=globalThis.Function;// dirty IE9- and Bun 0.3.0- checks
var WRAP=/MSIE .\./.test(USER_AGENT)||ENVIRONMENT==='BUN'&&function(){var version=globalThis.Bun.version.split('.');return version.length<3||version[0]==='0'&&(version[1]<3||version[1]==='3'&&version[2]==='0');}();// IE9- / Bun 0.3.0- setTimeout / setInterval / setImmediate additional parameters fix
// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers
// https://github.com/oven-sh/bun/issues/1633
schedulersFix=function(scheduler,hasTimeArg){var firstParamIndex=hasTimeArg?2:1;return WRAP?function(handler,timeout/* , ...arguments */){var boundArgs=validateArgumentsLength(arguments.length,1)>firstParamIndex;var fn=isCallable(handler)?handler:Function(handler);var params=boundArgs?arraySlice(arguments,firstParamIndex):[];var callback=boundArgs?function(){apply(fn,this,params);}:fn;return hasTimeArg?scheduler(callback,timeout):scheduler(callback);}:scheduler;};return schedulersFix;}var hasRequiredWeb_setInterval;function requireWeb_setInterval(){if(hasRequiredWeb_setInterval)return web_setInterval;hasRequiredWeb_setInterval=1;var $=/*@__PURE__*/require_export();var globalThis=/*@__PURE__*/requireGlobalThis();var schedulersFix=/*@__PURE__*/requireSchedulersFix();var setInterval=schedulersFix(globalThis.setInterval,true);// Bun / IE9- setInterval additional parameters fix
// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-setinterval
$({global:true,bind:true,forced:globalThis.setInterval!==setInterval},{setInterval:setInterval});return web_setInterval;}var web_setTimeout={};var hasRequiredWeb_setTimeout;function requireWeb_setTimeout(){if(hasRequiredWeb_setTimeout)return web_setTimeout;hasRequiredWeb_setTimeout=1;var $=/*@__PURE__*/require_export();var globalThis=/*@__PURE__*/requireGlobalThis();var schedulersFix=/*@__PURE__*/requireSchedulersFix();var setTimeout=schedulersFix(globalThis.setTimeout,true);// Bun / IE9- setTimeout additional parameters fix
// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-settimeout
$({global:true,bind:true,forced:globalThis.setTimeout!==setTimeout},{setTimeout:setTimeout});return web_setTimeout;}var hasRequiredWeb_timers;function requireWeb_timers(){if(hasRequiredWeb_timers)return web_timers;hasRequiredWeb_timers=1;// TODO: Remove this module from `core-js@4` since it's split to modules listed below
requireWeb_setInterval();requireWeb_setTimeout();return web_timers;}var setTimeout$2;var hasRequiredSetTimeout$1;function requireSetTimeout$1(){if(hasRequiredSetTimeout$1)return setTimeout$2;hasRequiredSetTimeout$1=1;requireWeb_timers();var path=/*@__PURE__*/requirePath();setTimeout$2=path.setTimeout;return setTimeout$2;}var setTimeout$1;var hasRequiredSetTimeout;function requireSetTimeout(){if(hasRequiredSetTimeout)return setTimeout$1;hasRequiredSetTimeout=1;setTimeout$1=/*@__PURE__*/requireSetTimeout$1();return setTimeout$1;}var setTimeoutExports=requireSetTimeout();var _setTimeout=/*@__PURE__*/getDefaultExportFromCjs(setTimeoutExports);var es_array_fill={};var arrayFill;var hasRequiredArrayFill;function requireArrayFill(){if(hasRequiredArrayFill)return arrayFill;hasRequiredArrayFill=1;var toObject=/*@__PURE__*/requireToObject();var toAbsoluteIndex=/*@__PURE__*/requireToAbsoluteIndex();var lengthOfArrayLike=/*@__PURE__*/requireLengthOfArrayLike();// `Array.prototype.fill` method implementation
// https://tc39.es/ecma262/#sec-array.prototype.fill
arrayFill=function fill(value/* , start = 0, end = @length */){var O=toObject(this);var length=lengthOfArrayLike(O);var argumentsLength=arguments.length;var index=toAbsoluteIndex(argumentsLength>1?arguments[1]:undefined,length);var end=argumentsLength>2?arguments[2]:undefined;var endPos=end===undefined?length:toAbsoluteIndex(end,length);while(endPos>index)O[index++]=value;return O;};return arrayFill;}var hasRequiredEs_array_fill;function requireEs_array_fill(){if(hasRequiredEs_array_fill)return es_array_fill;hasRequiredEs_array_fill=1;var $=/*@__PURE__*/require_export();var fill=/*@__PURE__*/requireArrayFill();var addToUnscopables=/*@__PURE__*/requireAddToUnscopables();// `Array.prototype.fill` method
// https://tc39.es/ecma262/#sec-array.prototype.fill
$({target:'Array',proto:true},{fill:fill});// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables('fill');return es_array_fill;}var fill$3;var hasRequiredFill$3;function requireFill$3(){if(hasRequiredFill$3)return fill$3;hasRequiredFill$3=1;requireEs_array_fill();var getBuiltInPrototypeMethod=/*@__PURE__*/requireGetBuiltInPrototypeMethod();fill$3=getBuiltInPrototypeMethod('Array','fill');return fill$3;}var fill$2;var hasRequiredFill$2;function requireFill$2(){if(hasRequiredFill$2)return fill$2;hasRequiredFill$2=1;var isPrototypeOf=/*@__PURE__*/requireObjectIsPrototypeOf();var method=/*@__PURE__*/requireFill$3();var ArrayPrototype=Array.prototype;fill$2=function(it){var own=it.fill;return it===ArrayPrototype||isPrototypeOf(ArrayPrototype,it)&&own===ArrayPrototype.fill?method:own;};return fill$2;}var fill$1;var hasRequiredFill$1;function requireFill$1(){if(hasRequiredFill$1)return fill$1;hasRequiredFill$1=1;var parent=/*@__PURE__*/requireFill$2();fill$1=parent;return fill$1;}var fill;var hasRequiredFill;function requireFill(){if(hasRequiredFill)return fill;hasRequiredFill=1;fill=/*@__PURE__*/requireFill$1();return fill;}var fillExports=requireFill();var _fillInstanceProperty=/*@__PURE__*/getDefaultExportFromCjs(fillExports);/*! Hammer.JS - v2.0.17-rc - 2019-12-16
 * http://naver.github.io/egjs
 *
 * Forked By Naver egjs
 * Copyright (c) hammerjs
 * Licensed under the MIT license */function _extends(){_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};return _extends.apply(this,arguments);}function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype);subClass.prototype.constructor=subClass;subClass.__proto__=superClass;}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return self;}/**
 * @private
 * extend object.
 * means that properties in dest will be overwritten by the ones in src.
 * @param {Object} target
 * @param {...Object} objects_to_assign
 * @returns {Object} target
 */var assign;if(typeof Object.assign!=='function'){assign=function assign(target){if(target===undefined||target===null){throw new TypeError('Cannot convert undefined or null to object');}var output=Object(target);for(var index=1;index<arguments.length;index++){var source=arguments[index];if(source!==undefined&&source!==null){for(var nextKey in source){if(source.hasOwnProperty(nextKey)){output[nextKey]=source[nextKey];}}}}return output;};}else {assign=Object.assign;}var assign$1=assign;var VENDOR_PREFIXES=['','webkit','Moz','MS','ms','o'];var TEST_ELEMENT=typeof document==="undefined"?{style:{}}:document.createElement('div');var TYPE_FUNCTION='function';var round=Math.round,abs=Math.abs;var now=Date.now;/**
 * @private
 * get the prefixed property
 * @param {Object} obj
 * @param {String} property
 * @returns {String|Undefined} prefixed
 */function prefixed(obj,property){var prefix;var prop;var camelProp=property[0].toUpperCase()+property.slice(1);var i=0;while(i<VENDOR_PREFIXES.length){prefix=VENDOR_PREFIXES[i];prop=prefix?prefix+camelProp:property;if(prop in obj){return prop;}i++;}return undefined;}/* eslint-disable no-new-func, no-nested-ternary */var win;if(typeof window==="undefined"){// window is undefined in node.js
win={};}else {win=window;}var PREFIXED_TOUCH_ACTION=prefixed(TEST_ELEMENT.style,'touchAction');var NATIVE_TOUCH_ACTION=PREFIXED_TOUCH_ACTION!==undefined;function getTouchActionProps(){if(!NATIVE_TOUCH_ACTION){return false;}var touchMap={};var cssSupports=win.CSS&&win.CSS.supports;['auto','manipulation','pan-y','pan-x','pan-x pan-y','none'].forEach(function(val){// If css.supports is not supported but there is native touch-action assume it supports
// all values. This is the case for IE 10 and 11.
return touchMap[val]=cssSupports?win.CSS.supports('touch-action',val):true;});return touchMap;}var TOUCH_ACTION_COMPUTE='compute';var TOUCH_ACTION_AUTO='auto';var TOUCH_ACTION_MANIPULATION='manipulation';// not implemented
var TOUCH_ACTION_NONE='none';var TOUCH_ACTION_PAN_X='pan-x';var TOUCH_ACTION_PAN_Y='pan-y';var TOUCH_ACTION_MAP=getTouchActionProps();var MOBILE_REGEX=/mobile|tablet|ip(ad|hone|od)|android/i;var SUPPORT_TOUCH='ontouchstart'in win;var SUPPORT_POINTER_EVENTS=prefixed(win,'PointerEvent')!==undefined;var SUPPORT_ONLY_TOUCH=SUPPORT_TOUCH&&MOBILE_REGEX.test(navigator.userAgent);var INPUT_TYPE_TOUCH='touch';var INPUT_TYPE_PEN='pen';var INPUT_TYPE_MOUSE='mouse';var INPUT_TYPE_KINECT='kinect';var COMPUTE_INTERVAL=25;var INPUT_START=1;var INPUT_MOVE=2;var INPUT_END=4;var INPUT_CANCEL=8;var DIRECTION_NONE=1;var DIRECTION_LEFT=2;var DIRECTION_RIGHT=4;var DIRECTION_UP=8;var DIRECTION_DOWN=16;var DIRECTION_HORIZONTAL=DIRECTION_LEFT|DIRECTION_RIGHT;var DIRECTION_VERTICAL=DIRECTION_UP|DIRECTION_DOWN;var DIRECTION_ALL=DIRECTION_HORIZONTAL|DIRECTION_VERTICAL;var PROPS_XY=['x','y'];var PROPS_CLIENT_XY=['clientX','clientY'];/**
 * @private
 * walk objects and arrays
 * @param {Object} obj
 * @param {Function} iterator
 * @param {Object} context
 */function each(obj,iterator,context){var i;if(!obj){return;}if(obj.forEach){obj.forEach(iterator,context);}else if(obj.length!==undefined){i=0;while(i<obj.length){iterator.call(context,obj[i],i,obj);i++;}}else {for(i in obj){obj.hasOwnProperty(i)&&iterator.call(context,obj[i],i,obj);}}}/**
 * @private
 * let a boolean value also be a function that must return a boolean
 * this first item in args will be used as the context
 * @param {Boolean|Function} val
 * @param {Array} [args]
 * @returns {Boolean}
 */function boolOrFn(val,args){if(typeof val===TYPE_FUNCTION){return val.apply(args?args[0]||undefined:undefined,args);}return val;}/**
 * @private
 * small indexOf wrapper
 * @param {String} str
 * @param {String} find
 * @returns {Boolean} found
 */function inStr(str,find){return str.indexOf(find)>-1;}/**
 * @private
 * when the touchActions are collected they are not a valid value, so we need to clean things up. *
 * @param {String} actions
 * @returns {*}
 */function cleanTouchActions(actions){// none
if(inStr(actions,TOUCH_ACTION_NONE)){return TOUCH_ACTION_NONE;}var hasPanX=inStr(actions,TOUCH_ACTION_PAN_X);var hasPanY=inStr(actions,TOUCH_ACTION_PAN_Y);// if both pan-x and pan-y are set (different recognizers
// for different directions, e.g. horizontal pan but vertical swipe?)
// we need none (as otherwise with pan-x pan-y combined none of these
// recognizers will work, since the browser would handle all panning
if(hasPanX&&hasPanY){return TOUCH_ACTION_NONE;}// pan-x OR pan-y
if(hasPanX||hasPanY){return hasPanX?TOUCH_ACTION_PAN_X:TOUCH_ACTION_PAN_Y;}// manipulation
if(inStr(actions,TOUCH_ACTION_MANIPULATION)){return TOUCH_ACTION_MANIPULATION;}return TOUCH_ACTION_AUTO;}/**
 * @private
 * Touch Action
 * sets the touchAction property or uses the js alternative
 * @param {Manager} manager
 * @param {String} value
 * @constructor
 */var TouchAction=/*#__PURE__*/function(){function TouchAction(manager,value){this.manager=manager;this.set(value);}/**
   * @private
   * set the touchAction value on the element or enable the polyfill
   * @param {String} value
   */var _proto=TouchAction.prototype;_proto.set=function set(value){// find out the touch-action by the event handlers
if(value===TOUCH_ACTION_COMPUTE){value=this.compute();}if(NATIVE_TOUCH_ACTION&&this.manager.element.style&&TOUCH_ACTION_MAP[value]){this.manager.element.style[PREFIXED_TOUCH_ACTION]=value;}this.actions=value.toLowerCase().trim();};/**
   * @private
   * just re-set the touchAction value
   */_proto.update=function update(){this.set(this.manager.options.touchAction);};/**
   * @private
   * compute the value for the touchAction property based on the recognizer's settings
   * @returns {String} value
   */_proto.compute=function compute(){var actions=[];each(this.manager.recognizers,function(recognizer){if(boolOrFn(recognizer.options.enable,[recognizer])){actions=actions.concat(recognizer.getTouchAction());}});return cleanTouchActions(actions.join(' '));};/**
   * @private
   * this method is called on each input cycle and provides the preventing of the browser behavior
   * @param {Object} input
   */_proto.preventDefaults=function preventDefaults(input){var srcEvent=input.srcEvent;var direction=input.offsetDirection;// if the touch action did prevented once this session
if(this.manager.session.prevented){srcEvent.preventDefault();return;}var actions=this.actions;var hasNone=inStr(actions,TOUCH_ACTION_NONE)&&!TOUCH_ACTION_MAP[TOUCH_ACTION_NONE];var hasPanY=inStr(actions,TOUCH_ACTION_PAN_Y)&&!TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_Y];var hasPanX=inStr(actions,TOUCH_ACTION_PAN_X)&&!TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_X];if(hasNone){// do not prevent defaults if this is a tap gesture
var isTapPointer=input.pointers.length===1;var isTapMovement=input.distance<2;var isTapTouchTime=input.deltaTime<250;if(isTapPointer&&isTapMovement&&isTapTouchTime){return;}}if(hasPanX&&hasPanY){// `pan-x pan-y` means browser handles all scrolling/panning, do not prevent
return;}if(hasNone||hasPanY&&direction&DIRECTION_HORIZONTAL||hasPanX&&direction&DIRECTION_VERTICAL){return this.preventSrc(srcEvent);}};/**
   * @private
   * call preventDefault to prevent the browser's default behavior (scrolling in most cases)
   * @param {Object} srcEvent
   */_proto.preventSrc=function preventSrc(srcEvent){this.manager.session.prevented=true;srcEvent.preventDefault();};return TouchAction;}();/**
 * @private
 * find if a node is in the given parent
 * @method hasParent
 * @param {HTMLElement} node
 * @param {HTMLElement} parent
 * @return {Boolean} found
 */function hasParent(node,parent){while(node){if(node===parent){return true;}node=node.parentNode;}return false;}/**
 * @private
 * get the center of all the pointers
 * @param {Array} pointers
 * @return {Object} center contains `x` and `y` properties
 */function getCenter(pointers){var pointersLength=pointers.length;// no need to loop when only one touch
if(pointersLength===1){return {x:round(pointers[0].clientX),y:round(pointers[0].clientY)};}var x=0;var y=0;var i=0;while(i<pointersLength){x+=pointers[i].clientX;y+=pointers[i].clientY;i++;}return {x:round(x/pointersLength),y:round(y/pointersLength)};}/**
 * @private
 * create a simple clone from the input used for storage of firstInput and firstMultiple
 * @param {Object} input
 * @returns {Object} clonedInputData
 */function simpleCloneInputData(input){// make a simple copy of the pointers because we will get a reference if we don't
// we only need clientXY for the calculations
var pointers=[];var i=0;while(i<input.pointers.length){pointers[i]={clientX:round(input.pointers[i].clientX),clientY:round(input.pointers[i].clientY)};i++;}return {timeStamp:now(),pointers:pointers,center:getCenter(pointers),deltaX:input.deltaX,deltaY:input.deltaY};}/**
 * @private
 * calculate the absolute distance between two points
 * @param {Object} p1 {x, y}
 * @param {Object} p2 {x, y}
 * @param {Array} [props] containing x and y keys
 * @return {Number} distance
 */function getDistance(p1,p2,props){if(!props){props=PROPS_XY;}var x=p2[props[0]]-p1[props[0]];var y=p2[props[1]]-p1[props[1]];return Math.sqrt(x*x+y*y);}/**
 * @private
 * calculate the angle between two coordinates
 * @param {Object} p1
 * @param {Object} p2
 * @param {Array} [props] containing x and y keys
 * @return {Number} angle
 */function getAngle(p1,p2,props){if(!props){props=PROPS_XY;}var x=p2[props[0]]-p1[props[0]];var y=p2[props[1]]-p1[props[1]];return Math.atan2(y,x)*180/Math.PI;}/**
 * @private
 * get the direction between two points
 * @param {Number} x
 * @param {Number} y
 * @return {Number} direction
 */function getDirection(x,y){if(x===y){return DIRECTION_NONE;}if(abs(x)>=abs(y)){return x<0?DIRECTION_LEFT:DIRECTION_RIGHT;}return y<0?DIRECTION_UP:DIRECTION_DOWN;}function computeDeltaXY(session,input){var center=input.center;// let { offsetDelta:offset = {}, prevDelta = {}, prevInput = {} } = session;
// jscs throwing error on defalut destructured values and without defaults tests fail
var offset=session.offsetDelta||{};var prevDelta=session.prevDelta||{};var prevInput=session.prevInput||{};if(input.eventType===INPUT_START||prevInput.eventType===INPUT_END){prevDelta=session.prevDelta={x:prevInput.deltaX||0,y:prevInput.deltaY||0};offset=session.offsetDelta={x:center.x,y:center.y};}input.deltaX=prevDelta.x+(center.x-offset.x);input.deltaY=prevDelta.y+(center.y-offset.y);}/**
 * @private
 * calculate the velocity between two points. unit is in px per ms.
 * @param {Number} deltaTime
 * @param {Number} x
 * @param {Number} y
 * @return {Object} velocity `x` and `y`
 */function getVelocity(deltaTime,x,y){return {x:x/deltaTime||0,y:y/deltaTime||0};}/**
 * @private
 * calculate the scale factor between two pointersets
 * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
 * @param {Array} start array of pointers
 * @param {Array} end array of pointers
 * @return {Number} scale
 */function getScale(start,end){return getDistance(end[0],end[1],PROPS_CLIENT_XY)/getDistance(start[0],start[1],PROPS_CLIENT_XY);}/**
 * @private
 * calculate the rotation degrees between two pointersets
 * @param {Array} start array of pointers
 * @param {Array} end array of pointers
 * @return {Number} rotation
 */function getRotation(start,end){return getAngle(end[1],end[0],PROPS_CLIENT_XY)+getAngle(start[1],start[0],PROPS_CLIENT_XY);}/**
 * @private
 * velocity is calculated every x ms
 * @param {Object} session
 * @param {Object} input
 */function computeIntervalInputData(session,input){var last=session.lastInterval||input;var deltaTime=input.timeStamp-last.timeStamp;var velocity;var velocityX;var velocityY;var direction;if(input.eventType!==INPUT_CANCEL&&(deltaTime>COMPUTE_INTERVAL||last.velocity===undefined)){var deltaX=input.deltaX-last.deltaX;var deltaY=input.deltaY-last.deltaY;var v=getVelocity(deltaTime,deltaX,deltaY);velocityX=v.x;velocityY=v.y;velocity=abs(v.x)>abs(v.y)?v.x:v.y;direction=getDirection(deltaX,deltaY);session.lastInterval=input;}else {// use latest velocity info if it doesn't overtake a minimum period
velocity=last.velocity;velocityX=last.velocityX;velocityY=last.velocityY;direction=last.direction;}input.velocity=velocity;input.velocityX=velocityX;input.velocityY=velocityY;input.direction=direction;}/**
* @private
 * extend the data with some usable properties like scale, rotate, velocity etc
 * @param {Object} manager
 * @param {Object} input
 */function computeInputData(manager,input){var session=manager.session;var pointers=input.pointers;var pointersLength=pointers.length;// store the first input to calculate the distance and direction
if(!session.firstInput){session.firstInput=simpleCloneInputData(input);}// to compute scale and rotation we need to store the multiple touches
if(pointersLength>1&&!session.firstMultiple){session.firstMultiple=simpleCloneInputData(input);}else if(pointersLength===1){session.firstMultiple=false;}var firstInput=session.firstInput,firstMultiple=session.firstMultiple;var offsetCenter=firstMultiple?firstMultiple.center:firstInput.center;var center=input.center=getCenter(pointers);input.timeStamp=now();input.deltaTime=input.timeStamp-firstInput.timeStamp;input.angle=getAngle(offsetCenter,center);input.distance=getDistance(offsetCenter,center);computeDeltaXY(session,input);input.offsetDirection=getDirection(input.deltaX,input.deltaY);var overallVelocity=getVelocity(input.deltaTime,input.deltaX,input.deltaY);input.overallVelocityX=overallVelocity.x;input.overallVelocityY=overallVelocity.y;input.overallVelocity=abs(overallVelocity.x)>abs(overallVelocity.y)?overallVelocity.x:overallVelocity.y;input.scale=firstMultiple?getScale(firstMultiple.pointers,pointers):1;input.rotation=firstMultiple?getRotation(firstMultiple.pointers,pointers):0;input.maxPointers=!session.prevInput?input.pointers.length:input.pointers.length>session.prevInput.maxPointers?input.pointers.length:session.prevInput.maxPointers;computeIntervalInputData(session,input);// find the correct target
var target=manager.element;var srcEvent=input.srcEvent;var srcEventTarget;if(srcEvent.composedPath){srcEventTarget=srcEvent.composedPath()[0];}else if(srcEvent.path){srcEventTarget=srcEvent.path[0];}else {srcEventTarget=srcEvent.target;}if(hasParent(srcEventTarget,target)){target=srcEventTarget;}input.target=target;}/**
 * @private
 * handle input events
 * @param {Manager} manager
 * @param {String} eventType
 * @param {Object} input
 */function inputHandler(manager,eventType,input){var pointersLen=input.pointers.length;var changedPointersLen=input.changedPointers.length;var isFirst=eventType&INPUT_START&&pointersLen-changedPointersLen===0;var isFinal=eventType&(INPUT_END|INPUT_CANCEL)&&pointersLen-changedPointersLen===0;input.isFirst=!!isFirst;input.isFinal=!!isFinal;if(isFirst){manager.session={};}// source event is the normalized value of the domEvents
// like 'touchstart, mouseup, pointerdown'
input.eventType=eventType;// compute scale, rotation etc
computeInputData(manager,input);// emit secret event
manager.emit('hammer.input',input);manager.recognize(input);manager.session.prevInput=input;}/**
 * @private
 * split string on whitespace
 * @param {String} str
 * @returns {Array} words
 */function splitStr(str){return str.trim().split(/\s+/g);}/**
 * @private
 * addEventListener with multiple events at once
 * @param {EventTarget} target
 * @param {String} types
 * @param {Function} handler
 */function addEventListeners(target,types,handler){each(splitStr(types),function(type){target.addEventListener(type,handler,false);});}/**
 * @private
 * removeEventListener with multiple events at once
 * @param {EventTarget} target
 * @param {String} types
 * @param {Function} handler
 */function removeEventListeners(target,types,handler){each(splitStr(types),function(type){target.removeEventListener(type,handler,false);});}/**
 * @private
 * get the window object of an element
 * @param {HTMLElement} element
 * @returns {DocumentView|Window}
 */function getWindowForElement(element){var doc=element.ownerDocument||element;return doc.defaultView||doc.parentWindow||window;}/**
 * @private
 * create new input type manager
 * @param {Manager} manager
 * @param {Function} callback
 * @returns {Input}
 * @constructor
 */var Input=/*#__PURE__*/function(){function Input(manager,callback){var self=this;this.manager=manager;this.callback=callback;this.element=manager.element;this.target=manager.options.inputTarget;// smaller wrapper around the handler, for the scope and the enabled state of the manager,
// so when disabled the input events are completely bypassed.
this.domHandler=function(ev){if(boolOrFn(manager.options.enable,[manager])){self.handler(ev);}};this.init();}/**
   * @private
   * should handle the inputEvent data and trigger the callback
   * @virtual
   */var _proto=Input.prototype;_proto.handler=function handler(){};/**
   * @private
   * bind the events
   */_proto.init=function init(){this.evEl&&addEventListeners(this.element,this.evEl,this.domHandler);this.evTarget&&addEventListeners(this.target,this.evTarget,this.domHandler);this.evWin&&addEventListeners(getWindowForElement(this.element),this.evWin,this.domHandler);};/**
   * @private
   * unbind the events
   */_proto.destroy=function destroy(){this.evEl&&removeEventListeners(this.element,this.evEl,this.domHandler);this.evTarget&&removeEventListeners(this.target,this.evTarget,this.domHandler);this.evWin&&removeEventListeners(getWindowForElement(this.element),this.evWin,this.domHandler);};return Input;}();/**
 * @private
 * find if a array contains the object using indexOf or a simple polyFill
 * @param {Array} src
 * @param {String} find
 * @param {String} [findByKey]
 * @return {Boolean|Number} false when not found, or the index
 */function inArray(src,find,findByKey){if(src.indexOf&&!findByKey){return src.indexOf(find);}else {var i=0;while(i<src.length){if(findByKey&&src[i][findByKey]==find||!findByKey&&src[i]===find){// do not use === here, test fails
return i;}i++;}return  -1;}}var POINTER_INPUT_MAP={pointerdown:INPUT_START,pointermove:INPUT_MOVE,pointerup:INPUT_END,pointercancel:INPUT_CANCEL,pointerout:INPUT_CANCEL};// in IE10 the pointer types is defined as an enum
var IE10_POINTER_TYPE_ENUM={2:INPUT_TYPE_TOUCH,3:INPUT_TYPE_PEN,4:INPUT_TYPE_MOUSE,5:INPUT_TYPE_KINECT// see https://twitter.com/jacobrossi/status/480596438489890816
};var POINTER_ELEMENT_EVENTS='pointerdown';var POINTER_WINDOW_EVENTS='pointermove pointerup pointercancel';// IE10 has prefixed support, and case-sensitive
if(win.MSPointerEvent&&!win.PointerEvent){POINTER_ELEMENT_EVENTS='MSPointerDown';POINTER_WINDOW_EVENTS='MSPointerMove MSPointerUp MSPointerCancel';}/**
 * @private
 * Pointer events input
 * @constructor
 * @extends Input
 */var PointerEventInput=/*#__PURE__*/function(_Input){_inheritsLoose(PointerEventInput,_Input);function PointerEventInput(){var _this;var proto=PointerEventInput.prototype;proto.evEl=POINTER_ELEMENT_EVENTS;proto.evWin=POINTER_WINDOW_EVENTS;_this=_Input.apply(this,arguments)||this;_this.store=_this.manager.session.pointerEvents=[];return _this;}/**
   * @private
   * handle mouse events
   * @param {Object} ev
   */var _proto=PointerEventInput.prototype;_proto.handler=function handler(ev){var store=this.store;var removePointer=false;var eventTypeNormalized=ev.type.toLowerCase().replace('ms','');var eventType=POINTER_INPUT_MAP[eventTypeNormalized];var pointerType=IE10_POINTER_TYPE_ENUM[ev.pointerType]||ev.pointerType;var isTouch=pointerType===INPUT_TYPE_TOUCH;// get index of the event in the store
var storeIndex=inArray(store,ev.pointerId,'pointerId');// start and mouse must be down
if(eventType&INPUT_START&&(ev.button===0||isTouch)){if(storeIndex<0){store.push(ev);storeIndex=store.length-1;}}else if(eventType&(INPUT_END|INPUT_CANCEL)){removePointer=true;}// it not found, so the pointer hasn't been down (so it's probably a hover)
if(storeIndex<0){return;}// update the event in the store
store[storeIndex]=ev;this.callback(this.manager,eventType,{pointers:store,changedPointers:[ev],pointerType:pointerType,srcEvent:ev});if(removePointer){// remove from the store
store.splice(storeIndex,1);}};return PointerEventInput;}(Input);/**
 * @private
 * convert array-like objects to real arrays
 * @param {Object} obj
 * @returns {Array}
 */function toArray(obj){return Array.prototype.slice.call(obj,0);}/**
 * @private
 * unique array with objects based on a key (like 'id') or just by the array's value
 * @param {Array} src [{id:1},{id:2},{id:1}]
 * @param {String} [key]
 * @param {Boolean} [sort=False]
 * @returns {Array} [{id:1},{id:2}]
 */function uniqueArray(src,key,sort){var results=[];var values=[];var i=0;while(i<src.length){var val=key?src[i][key]:src[i];if(inArray(values,val)<0){results.push(src[i]);}values[i]=val;i++;}if(sort){if(!key){results=results.sort();}else {results=results.sort(function(a,b){return a[key]>b[key];});}}return results;}var TOUCH_INPUT_MAP={touchstart:INPUT_START,touchmove:INPUT_MOVE,touchend:INPUT_END,touchcancel:INPUT_CANCEL};var TOUCH_TARGET_EVENTS='touchstart touchmove touchend touchcancel';/**
 * @private
 * Multi-user touch events input
 * @constructor
 * @extends Input
 */var TouchInput=/*#__PURE__*/function(_Input){_inheritsLoose(TouchInput,_Input);function TouchInput(){var _this;TouchInput.prototype.evTarget=TOUCH_TARGET_EVENTS;_this=_Input.apply(this,arguments)||this;_this.targetIds={};// this.evTarget = TOUCH_TARGET_EVENTS;
return _this;}var _proto=TouchInput.prototype;_proto.handler=function handler(ev){var type=TOUCH_INPUT_MAP[ev.type];var touches=getTouches.call(this,ev,type);if(!touches){return;}this.callback(this.manager,type,{pointers:touches[0],changedPointers:touches[1],pointerType:INPUT_TYPE_TOUCH,srcEvent:ev});};return TouchInput;}(Input);function getTouches(ev,type){var allTouches=toArray(ev.touches);var targetIds=this.targetIds;// when there is only one touch, the process can be simplified
if(type&(INPUT_START|INPUT_MOVE)&&allTouches.length===1){targetIds[allTouches[0].identifier]=true;return [allTouches,allTouches];}var i;var targetTouches;var changedTouches=toArray(ev.changedTouches);var changedTargetTouches=[];var target=this.target;// get target touches from touches
targetTouches=allTouches.filter(function(touch){return hasParent(touch.target,target);});// collect touches
if(type===INPUT_START){i=0;while(i<targetTouches.length){targetIds[targetTouches[i].identifier]=true;i++;}}// filter changed touches to only contain touches that exist in the collected target ids
i=0;while(i<changedTouches.length){if(targetIds[changedTouches[i].identifier]){changedTargetTouches.push(changedTouches[i]);}// cleanup removed touches
if(type&(INPUT_END|INPUT_CANCEL)){delete targetIds[changedTouches[i].identifier];}i++;}if(!changedTargetTouches.length){return;}return [// merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel'
uniqueArray(targetTouches.concat(changedTargetTouches),'identifier',true),changedTargetTouches];}var MOUSE_INPUT_MAP={mousedown:INPUT_START,mousemove:INPUT_MOVE,mouseup:INPUT_END};var MOUSE_ELEMENT_EVENTS='mousedown';var MOUSE_WINDOW_EVENTS='mousemove mouseup';/**
 * @private
 * Mouse events input
 * @constructor
 * @extends Input
 */var MouseInput=/*#__PURE__*/function(_Input){_inheritsLoose(MouseInput,_Input);function MouseInput(){var _this;var proto=MouseInput.prototype;proto.evEl=MOUSE_ELEMENT_EVENTS;proto.evWin=MOUSE_WINDOW_EVENTS;_this=_Input.apply(this,arguments)||this;_this.pressed=false;// mousedown state
return _this;}/**
   * @private
   * handle mouse events
   * @param {Object} ev
   */var _proto=MouseInput.prototype;_proto.handler=function handler(ev){var eventType=MOUSE_INPUT_MAP[ev.type];// on start we want to have the left mouse button down
if(eventType&INPUT_START&&ev.button===0){this.pressed=true;}if(eventType&INPUT_MOVE&&ev.which!==1){eventType=INPUT_END;}// mouse must be down
if(!this.pressed){return;}if(eventType&INPUT_END){this.pressed=false;}this.callback(this.manager,eventType,{pointers:[ev],changedPointers:[ev],pointerType:INPUT_TYPE_MOUSE,srcEvent:ev});};return MouseInput;}(Input);/**
 * @private
 * Combined touch and mouse input
 *
 * Touch has a higher priority then mouse, and while touching no mouse events are allowed.
 * This because touch devices also emit mouse events while doing a touch.
 *
 * @constructor
 * @extends Input
 */var DEDUP_TIMEOUT=2500;var DEDUP_DISTANCE=25;function setLastTouch(eventData){var _eventData$changedPoi=eventData.changedPointers,touch=_eventData$changedPoi[0];if(touch.identifier===this.primaryTouch){var lastTouch={x:touch.clientX,y:touch.clientY};var lts=this.lastTouches;this.lastTouches.push(lastTouch);var removeLastTouch=function removeLastTouch(){var i=lts.indexOf(lastTouch);if(i>-1){lts.splice(i,1);}};setTimeout(removeLastTouch,DEDUP_TIMEOUT);}}function recordTouches(eventType,eventData){if(eventType&INPUT_START){this.primaryTouch=eventData.changedPointers[0].identifier;setLastTouch.call(this,eventData);}else if(eventType&(INPUT_END|INPUT_CANCEL)){setLastTouch.call(this,eventData);}}function isSyntheticEvent(eventData){var x=eventData.srcEvent.clientX;var y=eventData.srcEvent.clientY;for(var i=0;i<this.lastTouches.length;i++){var t=this.lastTouches[i];var dx=Math.abs(x-t.x);var dy=Math.abs(y-t.y);if(dx<=DEDUP_DISTANCE&&dy<=DEDUP_DISTANCE){return true;}}return false;}var TouchMouseInput=/*#__PURE__*/function(){var TouchMouseInput=/*#__PURE__*/function(_Input){_inheritsLoose(TouchMouseInput,_Input);function TouchMouseInput(_manager,callback){var _this;_this=_Input.call(this,_manager,callback)||this;_this.handler=function(manager,inputEvent,inputData){var isTouch=inputData.pointerType===INPUT_TYPE_TOUCH;var isMouse=inputData.pointerType===INPUT_TYPE_MOUSE;if(isMouse&&inputData.sourceCapabilities&&inputData.sourceCapabilities.firesTouchEvents){return;}// when we're in a touch event, record touches to  de-dupe synthetic mouse event
if(isTouch){recordTouches.call(_assertThisInitialized(_assertThisInitialized(_this)),inputEvent,inputData);}else if(isMouse&&isSyntheticEvent.call(_assertThisInitialized(_assertThisInitialized(_this)),inputData)){return;}_this.callback(manager,inputEvent,inputData);};_this.touch=new TouchInput(_this.manager,_this.handler);_this.mouse=new MouseInput(_this.manager,_this.handler);_this.primaryTouch=null;_this.lastTouches=[];return _this;}/**
     * @private
     * handle mouse and touch events
     * @param {Hammer} manager
     * @param {String} inputEvent
     * @param {Object} inputData
     */var _proto=TouchMouseInput.prototype;/**
     * @private
     * remove the event listeners
     */_proto.destroy=function destroy(){this.touch.destroy();this.mouse.destroy();};return TouchMouseInput;}(Input);return TouchMouseInput;}();/**
 * @private
 * create new input type manager
 * called by the Manager constructor
 * @param {Hammer} manager
 * @returns {Input}
 */function createInputInstance(manager){var Type;// let inputClass = manager.options.inputClass;
var inputClass=manager.options.inputClass;if(inputClass){Type=inputClass;}else if(SUPPORT_POINTER_EVENTS){Type=PointerEventInput;}else if(SUPPORT_ONLY_TOUCH){Type=TouchInput;}else if(!SUPPORT_TOUCH){Type=MouseInput;}else {Type=TouchMouseInput;}return new Type(manager,inputHandler);}/**
 * @private
 * if the argument is an array, we want to execute the fn on each entry
 * if it aint an array we don't want to do a thing.
 * this is used by all the methods that accept a single and array argument.
 * @param {*|Array} arg
 * @param {String} fn
 * @param {Object} [context]
 * @returns {Boolean}
 */function invokeArrayArg(arg,fn,context){if(Array.isArray(arg)){each(arg,context[fn],context);return true;}return false;}var STATE_POSSIBLE=1;var STATE_BEGAN=2;var STATE_CHANGED=4;var STATE_ENDED=8;var STATE_RECOGNIZED=STATE_ENDED;var STATE_CANCELLED=16;var STATE_FAILED=32;/**
 * @private
 * get a unique id
 * @returns {number} uniqueId
 */var _uniqueId=1;function uniqueId(){return _uniqueId++;}/**
 * @private
 * get a recognizer by name if it is bound to a manager
 * @param {Recognizer|String} otherRecognizer
 * @param {Recognizer} recognizer
 * @returns {Recognizer}
 */function getRecognizerByNameIfManager(otherRecognizer,recognizer){var manager=recognizer.manager;if(manager){return manager.get(otherRecognizer);}return otherRecognizer;}/**
 * @private
 * get a usable string, used as event postfix
 * @param {constant} state
 * @returns {String} state
 */function stateStr(state){if(state&STATE_CANCELLED){return 'cancel';}else if(state&STATE_ENDED){return 'end';}else if(state&STATE_CHANGED){return 'move';}else if(state&STATE_BEGAN){return 'start';}return '';}/**
 * @private
 * Recognizer flow explained; *
 * All recognizers have the initial state of POSSIBLE when a input session starts.
 * The definition of a input session is from the first input until the last input, with all it's movement in it. *
 * Example session for mouse-input: mousedown -> mousemove -> mouseup
 *
 * On each recognizing cycle (see Manager.recognize) the .recognize() method is executed
 * which determines with state it should be.
 *
 * If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to
 * POSSIBLE to give it another change on the next cycle.
 *
 *               Possible
 *                  |
 *            +-----+---------------+
 *            |                     |
 *      +-----+-----+               |
 *      |           |               |
 *   Failed      Cancelled          |
 *                          +-------+------+
 *                          |              |
 *                      Recognized       Began
 *                                         |
 *                                      Changed
 *                                         |
 *                                  Ended/Recognized
 *//**
 * @private
 * Recognizer
 * Every recognizer needs to extend from this class.
 * @constructor
 * @param {Object} options
 */var Recognizer=/*#__PURE__*/function(){function Recognizer(options){if(options===void 0){options={};}this.options=_extends({enable:true},options);this.id=uniqueId();this.manager=null;// default is enable true
this.state=STATE_POSSIBLE;this.simultaneous={};this.requireFail=[];}/**
   * @private
   * set options
   * @param {Object} options
   * @return {Recognizer}
   */var _proto=Recognizer.prototype;_proto.set=function set(options){assign$1(this.options,options);// also update the touchAction, in case something changed about the directions/enabled state
this.manager&&this.manager.touchAction.update();return this;};/**
   * @private
   * recognize simultaneous with an other recognizer.
   * @param {Recognizer} otherRecognizer
   * @returns {Recognizer} this
   */_proto.recognizeWith=function recognizeWith(otherRecognizer){if(invokeArrayArg(otherRecognizer,'recognizeWith',this)){return this;}var simultaneous=this.simultaneous;otherRecognizer=getRecognizerByNameIfManager(otherRecognizer,this);if(!simultaneous[otherRecognizer.id]){simultaneous[otherRecognizer.id]=otherRecognizer;otherRecognizer.recognizeWith(this);}return this;};/**
   * @private
   * drop the simultaneous link. it doesnt remove the link on the other recognizer.
   * @param {Recognizer} otherRecognizer
   * @returns {Recognizer} this
   */_proto.dropRecognizeWith=function dropRecognizeWith(otherRecognizer){if(invokeArrayArg(otherRecognizer,'dropRecognizeWith',this)){return this;}otherRecognizer=getRecognizerByNameIfManager(otherRecognizer,this);delete this.simultaneous[otherRecognizer.id];return this;};/**
   * @private
   * recognizer can only run when an other is failing
   * @param {Recognizer} otherRecognizer
   * @returns {Recognizer} this
   */_proto.requireFailure=function requireFailure(otherRecognizer){if(invokeArrayArg(otherRecognizer,'requireFailure',this)){return this;}var requireFail=this.requireFail;otherRecognizer=getRecognizerByNameIfManager(otherRecognizer,this);if(inArray(requireFail,otherRecognizer)===-1){requireFail.push(otherRecognizer);otherRecognizer.requireFailure(this);}return this;};/**
   * @private
   * drop the requireFailure link. it does not remove the link on the other recognizer.
   * @param {Recognizer} otherRecognizer
   * @returns {Recognizer} this
   */_proto.dropRequireFailure=function dropRequireFailure(otherRecognizer){if(invokeArrayArg(otherRecognizer,'dropRequireFailure',this)){return this;}otherRecognizer=getRecognizerByNameIfManager(otherRecognizer,this);var index=inArray(this.requireFail,otherRecognizer);if(index>-1){this.requireFail.splice(index,1);}return this;};/**
   * @private
   * has require failures boolean
   * @returns {boolean}
   */_proto.hasRequireFailures=function hasRequireFailures(){return this.requireFail.length>0;};/**
   * @private
   * if the recognizer can recognize simultaneous with an other recognizer
   * @param {Recognizer} otherRecognizer
   * @returns {Boolean}
   */_proto.canRecognizeWith=function canRecognizeWith(otherRecognizer){return !!this.simultaneous[otherRecognizer.id];};/**
   * @private
   * You should use `tryEmit` instead of `emit` directly to check
   * that all the needed recognizers has failed before emitting.
   * @param {Object} input
   */_proto.emit=function emit(input){var self=this;var state=this.state;function emit(event){self.manager.emit(event,input);}// 'panstart' and 'panmove'
if(state<STATE_ENDED){emit(self.options.event+stateStr(state));}emit(self.options.event);// simple 'eventName' events
if(input.additionalEvent){// additional event(panleft, panright, pinchin, pinchout...)
emit(input.additionalEvent);}// panend and pancancel
if(state>=STATE_ENDED){emit(self.options.event+stateStr(state));}};/**
   * @private
   * Check that all the require failure recognizers has failed,
   * if true, it emits a gesture event,
   * otherwise, setup the state to FAILED.
   * @param {Object} input
   */_proto.tryEmit=function tryEmit(input){if(this.canEmit()){return this.emit(input);}// it's failing anyway
this.state=STATE_FAILED;};/**
   * @private
   * can we emit?
   * @returns {boolean}
   */_proto.canEmit=function canEmit(){var i=0;while(i<this.requireFail.length){if(!(this.requireFail[i].state&(STATE_FAILED|STATE_POSSIBLE))){return false;}i++;}return true;};/**
   * @private
   * update the recognizer
   * @param {Object} inputData
   */_proto.recognize=function recognize(inputData){// make a new copy of the inputData
// so we can change the inputData without messing up the other recognizers
var inputDataClone=assign$1({},inputData);// is is enabled and allow recognizing?
if(!boolOrFn(this.options.enable,[this,inputDataClone])){this.reset();this.state=STATE_FAILED;return;}// reset when we've reached the end
if(this.state&(STATE_RECOGNIZED|STATE_CANCELLED|STATE_FAILED)){this.state=STATE_POSSIBLE;}this.state=this.process(inputDataClone);// the recognizer has recognized a gesture
// so trigger an event
if(this.state&(STATE_BEGAN|STATE_CHANGED|STATE_ENDED|STATE_CANCELLED)){this.tryEmit(inputDataClone);}};/**
   * @private
   * return the state of the recognizer
   * the actual recognizing happens in this method
   * @virtual
   * @param {Object} inputData
   * @returns {constant} STATE
   *//* jshint ignore:start */_proto.process=function process(inputData){};/* jshint ignore:end *//**
   * @private
   * return the preferred touch-action
   * @virtual
   * @returns {Array}
   */_proto.getTouchAction=function getTouchAction(){};/**
   * @private
   * called when the gesture isn't allowed to recognize
   * like when another is being recognized or it is disabled
   * @virtual
   */_proto.reset=function reset(){};return Recognizer;}();/**
 * @private
 * A tap is recognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur
 * between the given interval and position. The delay option can be used to recognize multi-taps without firing
 * a single tap.
 *
 * The eventData from the emitted event contains the property `tapCount`, which contains the amount of
 * multi-taps being recognized.
 * @constructor
 * @extends Recognizer
 */var TapRecognizer=/*#__PURE__*/function(_Recognizer){_inheritsLoose(TapRecognizer,_Recognizer);function TapRecognizer(options){var _this;if(options===void 0){options={};}_this=_Recognizer.call(this,_extends({event:'tap',pointers:1,taps:1,interval:300,// max time between the multi-tap taps
time:250,// max time of the pointer to be down (like finger on the screen)
threshold:9,// a minimal movement is ok, but keep it low
posThreshold:10},options))||this;// previous time and center,
// used for tap counting
_this.pTime=false;_this.pCenter=false;_this._timer=null;_this._input=null;_this.count=0;return _this;}var _proto=TapRecognizer.prototype;_proto.getTouchAction=function getTouchAction(){return [TOUCH_ACTION_MANIPULATION];};_proto.process=function process(input){var _this2=this;var options=this.options;var validPointers=input.pointers.length===options.pointers;var validMovement=input.distance<options.threshold;var validTouchTime=input.deltaTime<options.time;this.reset();if(input.eventType&INPUT_START&&this.count===0){return this.failTimeout();}// we only allow little movement
// and we've reached an end event, so a tap is possible
if(validMovement&&validTouchTime&&validPointers){if(input.eventType!==INPUT_END){return this.failTimeout();}var validInterval=this.pTime?input.timeStamp-this.pTime<options.interval:true;var validMultiTap=!this.pCenter||getDistance(this.pCenter,input.center)<options.posThreshold;this.pTime=input.timeStamp;this.pCenter=input.center;if(!validMultiTap||!validInterval){this.count=1;}else {this.count+=1;}this._input=input;// if tap count matches we have recognized it,
// else it has began recognizing...
var tapCount=this.count%options.taps;if(tapCount===0){// no failing requirements, immediately trigger the tap event
// or wait as long as the multitap interval to trigger
if(!this.hasRequireFailures()){return STATE_RECOGNIZED;}else {this._timer=setTimeout(function(){_this2.state=STATE_RECOGNIZED;_this2.tryEmit();},options.interval);return STATE_BEGAN;}}}return STATE_FAILED;};_proto.failTimeout=function failTimeout(){var _this3=this;this._timer=setTimeout(function(){_this3.state=STATE_FAILED;},this.options.interval);return STATE_FAILED;};_proto.reset=function reset(){clearTimeout(this._timer);};_proto.emit=function emit(){if(this.state===STATE_RECOGNIZED){this._input.tapCount=this.count;this.manager.emit(this.options.event,this._input);}};return TapRecognizer;}(Recognizer);/**
 * @private
 * This recognizer is just used as a base for the simple attribute recognizers.
 * @constructor
 * @extends Recognizer
 */var AttrRecognizer=/*#__PURE__*/function(_Recognizer){_inheritsLoose(AttrRecognizer,_Recognizer);function AttrRecognizer(options){if(options===void 0){options={};}return _Recognizer.call(this,_extends({pointers:1},options))||this;}/**
   * @private
   * Used to check if it the recognizer receives valid input, like input.distance > 10.
   * @memberof AttrRecognizer
   * @param {Object} input
   * @returns {Boolean} recognized
   */var _proto=AttrRecognizer.prototype;_proto.attrTest=function attrTest(input){var optionPointers=this.options.pointers;return optionPointers===0||input.pointers.length===optionPointers;};/**
   * @private
   * Process the input and return the state for the recognizer
   * @memberof AttrRecognizer
   * @param {Object} input
   * @returns {*} State
   */_proto.process=function process(input){var state=this.state;var eventType=input.eventType;var isRecognized=state&(STATE_BEGAN|STATE_CHANGED);var isValid=this.attrTest(input);// on cancel input and we've recognized before, return STATE_CANCELLED
if(isRecognized&&(eventType&INPUT_CANCEL||!isValid)){return state|STATE_CANCELLED;}else if(isRecognized||isValid){if(eventType&INPUT_END){return state|STATE_ENDED;}else if(!(state&STATE_BEGAN)){return STATE_BEGAN;}return state|STATE_CHANGED;}return STATE_FAILED;};return AttrRecognizer;}(Recognizer);/**
 * @private
 * direction cons to string
 * @param {constant} direction
 * @returns {String}
 */function directionStr(direction){if(direction===DIRECTION_DOWN){return 'down';}else if(direction===DIRECTION_UP){return 'up';}else if(direction===DIRECTION_LEFT){return 'left';}else if(direction===DIRECTION_RIGHT){return 'right';}return '';}/**
 * @private
 * Pan
 * Recognized when the pointer is down and moved in the allowed direction.
 * @constructor
 * @extends AttrRecognizer
 */var PanRecognizer=/*#__PURE__*/function(_AttrRecognizer){_inheritsLoose(PanRecognizer,_AttrRecognizer);function PanRecognizer(options){var _this;if(options===void 0){options={};}_this=_AttrRecognizer.call(this,_extends({event:'pan',threshold:10,pointers:1,direction:DIRECTION_ALL},options))||this;_this.pX=null;_this.pY=null;return _this;}var _proto=PanRecognizer.prototype;_proto.getTouchAction=function getTouchAction(){var direction=this.options.direction;var actions=[];if(direction&DIRECTION_HORIZONTAL){actions.push(TOUCH_ACTION_PAN_Y);}if(direction&DIRECTION_VERTICAL){actions.push(TOUCH_ACTION_PAN_X);}return actions;};_proto.directionTest=function directionTest(input){var options=this.options;var hasMoved=true;var distance=input.distance;var direction=input.direction;var x=input.deltaX;var y=input.deltaY;// lock to axis?
if(!(direction&options.direction)){if(options.direction&DIRECTION_HORIZONTAL){direction=x===0?DIRECTION_NONE:x<0?DIRECTION_LEFT:DIRECTION_RIGHT;hasMoved=x!==this.pX;distance=Math.abs(input.deltaX);}else {direction=y===0?DIRECTION_NONE:y<0?DIRECTION_UP:DIRECTION_DOWN;hasMoved=y!==this.pY;distance=Math.abs(input.deltaY);}}input.direction=direction;return hasMoved&&distance>options.threshold&&direction&options.direction;};_proto.attrTest=function attrTest(input){return AttrRecognizer.prototype.attrTest.call(this,input)&&(// replace with a super call
this.state&STATE_BEGAN||!(this.state&STATE_BEGAN)&&this.directionTest(input));};_proto.emit=function emit(input){this.pX=input.deltaX;this.pY=input.deltaY;var direction=directionStr(input.direction);if(direction){input.additionalEvent=this.options.event+direction;}_AttrRecognizer.prototype.emit.call(this,input);};return PanRecognizer;}(AttrRecognizer);/**
 * @private
 * Swipe
 * Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction.
 * @constructor
 * @extends AttrRecognizer
 */var SwipeRecognizer=/*#__PURE__*/function(_AttrRecognizer){_inheritsLoose(SwipeRecognizer,_AttrRecognizer);function SwipeRecognizer(options){if(options===void 0){options={};}return _AttrRecognizer.call(this,_extends({event:'swipe',threshold:10,velocity:0.3,direction:DIRECTION_HORIZONTAL|DIRECTION_VERTICAL,pointers:1},options))||this;}var _proto=SwipeRecognizer.prototype;_proto.getTouchAction=function getTouchAction(){return PanRecognizer.prototype.getTouchAction.call(this);};_proto.attrTest=function attrTest(input){var direction=this.options.direction;var velocity;if(direction&(DIRECTION_HORIZONTAL|DIRECTION_VERTICAL)){velocity=input.overallVelocity;}else if(direction&DIRECTION_HORIZONTAL){velocity=input.overallVelocityX;}else if(direction&DIRECTION_VERTICAL){velocity=input.overallVelocityY;}return _AttrRecognizer.prototype.attrTest.call(this,input)&&direction&input.offsetDirection&&input.distance>this.options.threshold&&input.maxPointers===this.options.pointers&&abs(velocity)>this.options.velocity&&input.eventType&INPUT_END;};_proto.emit=function emit(input){var direction=directionStr(input.offsetDirection);if(direction){this.manager.emit(this.options.event+direction,input);}this.manager.emit(this.options.event,input);};return SwipeRecognizer;}(AttrRecognizer);/**
 * @private
 * Pinch
 * Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out).
 * @constructor
 * @extends AttrRecognizer
 */var PinchRecognizer=/*#__PURE__*/function(_AttrRecognizer){_inheritsLoose(PinchRecognizer,_AttrRecognizer);function PinchRecognizer(options){if(options===void 0){options={};}return _AttrRecognizer.call(this,_extends({event:'pinch',threshold:0,pointers:2},options))||this;}var _proto=PinchRecognizer.prototype;_proto.getTouchAction=function getTouchAction(){return [TOUCH_ACTION_NONE];};_proto.attrTest=function attrTest(input){return _AttrRecognizer.prototype.attrTest.call(this,input)&&(Math.abs(input.scale-1)>this.options.threshold||this.state&STATE_BEGAN);};_proto.emit=function emit(input){if(input.scale!==1){var inOut=input.scale<1?'in':'out';input.additionalEvent=this.options.event+inOut;}_AttrRecognizer.prototype.emit.call(this,input);};return PinchRecognizer;}(AttrRecognizer);/**
 * @private
 * Rotate
 * Recognized when two or more pointer are moving in a circular motion.
 * @constructor
 * @extends AttrRecognizer
 */var RotateRecognizer=/*#__PURE__*/function(_AttrRecognizer){_inheritsLoose(RotateRecognizer,_AttrRecognizer);function RotateRecognizer(options){if(options===void 0){options={};}return _AttrRecognizer.call(this,_extends({event:'rotate',threshold:0,pointers:2},options))||this;}var _proto=RotateRecognizer.prototype;_proto.getTouchAction=function getTouchAction(){return [TOUCH_ACTION_NONE];};_proto.attrTest=function attrTest(input){return _AttrRecognizer.prototype.attrTest.call(this,input)&&(Math.abs(input.rotation)>this.options.threshold||this.state&STATE_BEGAN);};return RotateRecognizer;}(AttrRecognizer);/**
 * @private
 * Press
 * Recognized when the pointer is down for x ms without any movement.
 * @constructor
 * @extends Recognizer
 */var PressRecognizer=/*#__PURE__*/function(_Recognizer){_inheritsLoose(PressRecognizer,_Recognizer);function PressRecognizer(options){var _this;if(options===void 0){options={};}_this=_Recognizer.call(this,_extends({event:'press',pointers:1,time:251,// minimal time of the pointer to be pressed
threshold:9},options))||this;_this._timer=null;_this._input=null;return _this;}var _proto=PressRecognizer.prototype;_proto.getTouchAction=function getTouchAction(){return [TOUCH_ACTION_AUTO];};_proto.process=function process(input){var _this2=this;var options=this.options;var validPointers=input.pointers.length===options.pointers;var validMovement=input.distance<options.threshold;var validTime=input.deltaTime>options.time;this._input=input;// we only allow little movement
// and we've reached an end event, so a tap is possible
if(!validMovement||!validPointers||input.eventType&(INPUT_END|INPUT_CANCEL)&&!validTime){this.reset();}else if(input.eventType&INPUT_START){this.reset();this._timer=setTimeout(function(){_this2.state=STATE_RECOGNIZED;_this2.tryEmit();},options.time);}else if(input.eventType&INPUT_END){return STATE_RECOGNIZED;}return STATE_FAILED;};_proto.reset=function reset(){clearTimeout(this._timer);};_proto.emit=function emit(input){if(this.state!==STATE_RECOGNIZED){return;}if(input&&input.eventType&INPUT_END){this.manager.emit(this.options.event+"up",input);}else {this._input.timeStamp=now();this.manager.emit(this.options.event,this._input);}};return PressRecognizer;}(Recognizer);var defaults={/**
   * @private
   * set if DOM events are being triggered.
   * But this is slower and unused by simple implementations, so disabled by default.
   * @type {Boolean}
   * @default false
   */domEvents:false,/**
   * @private
   * The value for the touchAction property/fallback.
   * When set to `compute` it will magically set the correct value based on the added recognizers.
   * @type {String}
   * @default compute
   */touchAction:TOUCH_ACTION_COMPUTE,/**
   * @private
   * @type {Boolean}
   * @default true
   */enable:true,/**
   * @private
   * EXPERIMENTAL FEATURE -- can be removed/changed
   * Change the parent input target element.
   * If Null, then it is being set the to main element.
   * @type {Null|EventTarget}
   * @default null
   */inputTarget:null,/**
   * @private
   * force an input class
   * @type {Null|Function}
   * @default null
   */inputClass:null,/**
   * @private
   * Some CSS properties can be used to improve the working of Hammer.
   * Add them to this method and they will be set when creating a new Manager.
   * @namespace
   */cssProps:{/**
     * @private
     * Disables text selection to improve the dragging gesture. Mainly for desktop browsers.
     * @type {String}
     * @default 'none'
     */userSelect:"none",/**
     * @private
     * Disable the Windows Phone grippers when pressing an element.
     * @type {String}
     * @default 'none'
     */touchSelect:"none",/**
     * @private
     * Disables the default callout shown when you touch and hold a touch target.
     * On iOS, when you touch and hold a touch target such as a link, Safari displays
     * a callout containing information about the link. This property allows you to disable that callout.
     * @type {String}
     * @default 'none'
     */touchCallout:"none",/**
     * @private
     * Specifies whether zooming is enabled. Used by IE10>
     * @type {String}
     * @default 'none'
     */contentZooming:"none",/**
     * @private
     * Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers.
     * @type {String}
     * @default 'none'
     */userDrag:"none",/**
     * @private
     * Overrides the highlight color shown when the user taps a link or a JavaScript
     * clickable element in iOS. This property obeys the alpha value, if specified.
     * @type {String}
     * @default 'rgba(0,0,0,0)'
     */tapHighlightColor:"rgba(0,0,0,0)"}};/**
 * @private
 * Default recognizer setup when calling `Hammer()`
 * When creating a new Manager these will be skipped.
 * This is separated with other defaults because of tree-shaking.
 * @type {Array}
 */var preset=[[RotateRecognizer,{enable:false}],[PinchRecognizer,{enable:false},['rotate']],[SwipeRecognizer,{direction:DIRECTION_HORIZONTAL}],[PanRecognizer,{direction:DIRECTION_HORIZONTAL},['swipe']],[TapRecognizer],[TapRecognizer,{event:'doubletap',taps:2},['tap']],[PressRecognizer]];var STOP=1;var FORCED_STOP=2;/**
 * @private
 * add/remove the css properties as defined in manager.options.cssProps
 * @param {Manager} manager
 * @param {Boolean} add
 */function toggleCssProps(manager,add){var element=manager.element;if(!element.style){return;}var prop;each(manager.options.cssProps,function(value,name){prop=prefixed(element.style,name);if(add){manager.oldCssProps[prop]=element.style[prop];element.style[prop]=value;}else {element.style[prop]=manager.oldCssProps[prop]||"";}});if(!add){manager.oldCssProps={};}}/**
 * @private
 * trigger dom event
 * @param {String} event
 * @param {Object} data
 */function triggerDomEvent(event,data){var gestureEvent=document.createEvent("Event");gestureEvent.initEvent(event,true,true);gestureEvent.gesture=data;data.target.dispatchEvent(gestureEvent);}/**
* @private
 * Manager
 * @param {HTMLElement} element
 * @param {Object} [options]
 * @constructor
 */var Manager=/*#__PURE__*/function(){function Manager(element,options){var _this=this;this.options=assign$1({},defaults,options||{});this.options.inputTarget=this.options.inputTarget||element;this.handlers={};this.session={};this.recognizers=[];this.oldCssProps={};this.element=element;this.input=createInputInstance(this);this.touchAction=new TouchAction(this,this.options.touchAction);toggleCssProps(this,true);each(this.options.recognizers,function(item){var recognizer=_this.add(new item[0](item[1]));item[2]&&recognizer.recognizeWith(item[2]);item[3]&&recognizer.requireFailure(item[3]);},this);}/**
   * @private
   * set options
   * @param {Object} options
   * @returns {Manager}
   */var _proto=Manager.prototype;_proto.set=function set(options){assign$1(this.options,options);// Options that need a little more setup
if(options.touchAction){this.touchAction.update();}if(options.inputTarget){// Clean up existing event listeners and reinitialize
this.input.destroy();this.input.target=options.inputTarget;this.input.init();}return this;};/**
   * @private
   * stop recognizing for this session.
   * This session will be discarded, when a new [input]start event is fired.
   * When forced, the recognizer cycle is stopped immediately.
   * @param {Boolean} [force]
   */_proto.stop=function stop(force){this.session.stopped=force?FORCED_STOP:STOP;};/**
   * @private
   * run the recognizers!
   * called by the inputHandler function on every movement of the pointers (touches)
   * it walks through all the recognizers and tries to detect the gesture that is being made
   * @param {Object} inputData
   */_proto.recognize=function recognize(inputData){var session=this.session;if(session.stopped){return;}// run the touch-action polyfill
this.touchAction.preventDefaults(inputData);var recognizer;var recognizers=this.recognizers;// this holds the recognizer that is being recognized.
// so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED
// if no recognizer is detecting a thing, it is set to `null`
var curRecognizer=session.curRecognizer;// reset when the last recognizer is recognized
// or when we're in a new session
if(!curRecognizer||curRecognizer&&curRecognizer.state&STATE_RECOGNIZED){session.curRecognizer=null;curRecognizer=null;}var i=0;while(i<recognizers.length){recognizer=recognizers[i];// find out if we are allowed try to recognize the input for this one.
// 1.   allow if the session is NOT forced stopped (see the .stop() method)
// 2.   allow if we still haven't recognized a gesture in this session, or the this recognizer is the one
//      that is being recognized.
// 3.   allow if the recognizer is allowed to run simultaneous with the current recognized recognizer.
//      this can be setup with the `recognizeWith()` method on the recognizer.
if(session.stopped!==FORCED_STOP&&(// 1
!curRecognizer||recognizer===curRecognizer||// 2
recognizer.canRecognizeWith(curRecognizer))){// 3
recognizer.recognize(inputData);}else {recognizer.reset();}// if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the
// current active recognizer. but only if we don't already have an active recognizer
if(!curRecognizer&&recognizer.state&(STATE_BEGAN|STATE_CHANGED|STATE_ENDED)){session.curRecognizer=recognizer;curRecognizer=recognizer;}i++;}};/**
   * @private
   * get a recognizer by its event name.
   * @param {Recognizer|String} recognizer
   * @returns {Recognizer|Null}
   */_proto.get=function get(recognizer){if(recognizer instanceof Recognizer){return recognizer;}var recognizers=this.recognizers;for(var i=0;i<recognizers.length;i++){if(recognizers[i].options.event===recognizer){return recognizers[i];}}return null;};/**
   * @private add a recognizer to the manager
   * existing recognizers with the same event name will be removed
   * @param {Recognizer} recognizer
   * @returns {Recognizer|Manager}
   */_proto.add=function add(recognizer){if(invokeArrayArg(recognizer,"add",this)){return this;}// remove existing
var existing=this.get(recognizer.options.event);if(existing){this.remove(existing);}this.recognizers.push(recognizer);recognizer.manager=this;this.touchAction.update();return recognizer;};/**
   * @private
   * remove a recognizer by name or instance
   * @param {Recognizer|String} recognizer
   * @returns {Manager}
   */_proto.remove=function remove(recognizer){if(invokeArrayArg(recognizer,"remove",this)){return this;}var targetRecognizer=this.get(recognizer);// let's make sure this recognizer exists
if(recognizer){var recognizers=this.recognizers;var index=inArray(recognizers,targetRecognizer);if(index!==-1){recognizers.splice(index,1);this.touchAction.update();}}return this;};/**
   * @private
   * bind event
   * @param {String} events
   * @param {Function} handler
   * @returns {EventEmitter} this
   */_proto.on=function on(events,handler){if(events===undefined||handler===undefined){return this;}var handlers=this.handlers;each(splitStr(events),function(event){handlers[event]=handlers[event]||[];handlers[event].push(handler);});return this;};/**
   * @private unbind event, leave emit blank to remove all handlers
   * @param {String} events
   * @param {Function} [handler]
   * @returns {EventEmitter} this
   */_proto.off=function off(events,handler){if(events===undefined){return this;}var handlers=this.handlers;each(splitStr(events),function(event){if(!handler){delete handlers[event];}else {handlers[event]&&handlers[event].splice(inArray(handlers[event],handler),1);}});return this;};/**
   * @private emit event to the listeners
   * @param {String} event
   * @param {Object} data
   */_proto.emit=function emit(event,data){// we also want to trigger dom events
if(this.options.domEvents){triggerDomEvent(event,data);}// no handlers, so skip it all
var handlers=this.handlers[event]&&this.handlers[event].slice();if(!handlers||!handlers.length){return;}data.type=event;data.preventDefault=function(){data.srcEvent.preventDefault();};var i=0;while(i<handlers.length){handlers[i](data);i++;}};/**
   * @private
   * destroy the manager and unbinds all events
   * it doesn't unbind dom events, that is the user own responsibility
   */_proto.destroy=function destroy(){this.element&&toggleCssProps(this,false);this.handlers={};this.session={};this.input.destroy();this.element=null;};return Manager;}();var SINGLE_TOUCH_INPUT_MAP={touchstart:INPUT_START,touchmove:INPUT_MOVE,touchend:INPUT_END,touchcancel:INPUT_CANCEL};var SINGLE_TOUCH_TARGET_EVENTS='touchstart';var SINGLE_TOUCH_WINDOW_EVENTS='touchstart touchmove touchend touchcancel';/**
 * @private
 * Touch events input
 * @constructor
 * @extends Input
 */var SingleTouchInput=/*#__PURE__*/function(_Input){_inheritsLoose(SingleTouchInput,_Input);function SingleTouchInput(){var _this;var proto=SingleTouchInput.prototype;proto.evTarget=SINGLE_TOUCH_TARGET_EVENTS;proto.evWin=SINGLE_TOUCH_WINDOW_EVENTS;_this=_Input.apply(this,arguments)||this;_this.started=false;return _this;}var _proto=SingleTouchInput.prototype;_proto.handler=function handler(ev){var type=SINGLE_TOUCH_INPUT_MAP[ev.type];// should we handle the touch events?
if(type===INPUT_START){this.started=true;}if(!this.started){return;}var touches=normalizeSingleTouches.call(this,ev,type);// when done, reset the started state
if(type&(INPUT_END|INPUT_CANCEL)&&touches[0].length-touches[1].length===0){this.started=false;}this.callback(this.manager,type,{pointers:touches[0],changedPointers:touches[1],pointerType:INPUT_TYPE_TOUCH,srcEvent:ev});};return SingleTouchInput;}(Input);function normalizeSingleTouches(ev,type){var all=toArray(ev.touches);var changed=toArray(ev.changedTouches);if(type&(INPUT_END|INPUT_CANCEL)){all=uniqueArray(all.concat(changed),'identifier',true);}return [all,changed];}/**
 * @private
 * wrap a method with a deprecation warning and stack trace
 * @param {Function} method
 * @param {String} name
 * @param {String} message
 * @returns {Function} A new function wrapping the supplied method.
 */function deprecate(method,name,message){var deprecationMessage="DEPRECATED METHOD: "+name+"\n"+message+" AT \n";return function(){var e=new Error('get-stack-trace');var stack=e&&e.stack?e.stack.replace(/^[^\(]+?[\n$]/gm,'').replace(/^\s+at\s+/gm,'').replace(/^Object.<anonymous>\s*\(/gm,'{anonymous}()@'):'Unknown Stack Trace';var log=window.console&&(window.console.warn||window.console.log);if(log){log.call(window.console,deprecationMessage,stack);}return method.apply(this,arguments);};}/**
 * @private
 * extend object.
 * means that properties in dest will be overwritten by the ones in src.
 * @param {Object} dest
 * @param {Object} src
 * @param {Boolean} [merge=false]
 * @returns {Object} dest
 */var extend=deprecate(function(dest,src,merge){var keys=Object.keys(src);var i=0;while(i<keys.length){if(!merge||merge&&dest[keys[i]]===undefined){dest[keys[i]]=src[keys[i]];}i++;}return dest;},'extend','Use `assign`.');/**
 * @private
 * merge the values from src in the dest.
 * means that properties that exist in dest will not be overwritten by src
 * @param {Object} dest
 * @param {Object} src
 * @returns {Object} dest
 */var merge$1=deprecate(function(dest,src){return extend(dest,src,true);},'merge','Use `assign`.');/**
 * @private
 * simple class inheritance
 * @param {Function} child
 * @param {Function} base
 * @param {Object} [properties]
 */function inherit(child,base,properties){var baseP=base.prototype;var childP;childP=child.prototype=Object.create(baseP);childP.constructor=child;childP._super=baseP;if(properties){assign$1(childP,properties);}}/**
 * @private
 * simple function bind
 * @param {Function} fn
 * @param {Object} context
 * @returns {Function}
 */function bindFn(fn,context){return function boundFn(){return fn.apply(context,arguments);};}/**
 * @private
 * Simple way to create a manager with a default set of recognizers.
 * @param {HTMLElement} element
 * @param {Object} [options]
 * @constructor
 */var Hammer$2=/*#__PURE__*/function(){var Hammer=/**
    * @private
    * @const {string}
    */function Hammer(element,options){if(options===void 0){options={};}return new Manager(element,_extends({recognizers:preset.concat()},options));};Hammer.VERSION="2.0.17-rc";Hammer.DIRECTION_ALL=DIRECTION_ALL;Hammer.DIRECTION_DOWN=DIRECTION_DOWN;Hammer.DIRECTION_LEFT=DIRECTION_LEFT;Hammer.DIRECTION_RIGHT=DIRECTION_RIGHT;Hammer.DIRECTION_UP=DIRECTION_UP;Hammer.DIRECTION_HORIZONTAL=DIRECTION_HORIZONTAL;Hammer.DIRECTION_VERTICAL=DIRECTION_VERTICAL;Hammer.DIRECTION_NONE=DIRECTION_NONE;Hammer.DIRECTION_DOWN=DIRECTION_DOWN;Hammer.INPUT_START=INPUT_START;Hammer.INPUT_MOVE=INPUT_MOVE;Hammer.INPUT_END=INPUT_END;Hammer.INPUT_CANCEL=INPUT_CANCEL;Hammer.STATE_POSSIBLE=STATE_POSSIBLE;Hammer.STATE_BEGAN=STATE_BEGAN;Hammer.STATE_CHANGED=STATE_CHANGED;Hammer.STATE_ENDED=STATE_ENDED;Hammer.STATE_RECOGNIZED=STATE_RECOGNIZED;Hammer.STATE_CANCELLED=STATE_CANCELLED;Hammer.STATE_FAILED=STATE_FAILED;Hammer.Manager=Manager;Hammer.Input=Input;Hammer.TouchAction=TouchAction;Hammer.TouchInput=TouchInput;Hammer.MouseInput=MouseInput;Hammer.PointerEventInput=PointerEventInput;Hammer.TouchMouseInput=TouchMouseInput;Hammer.SingleTouchInput=SingleTouchInput;Hammer.Recognizer=Recognizer;Hammer.AttrRecognizer=AttrRecognizer;Hammer.Tap=TapRecognizer;Hammer.Pan=PanRecognizer;Hammer.Swipe=SwipeRecognizer;Hammer.Pinch=PinchRecognizer;Hammer.Rotate=RotateRecognizer;Hammer.Press=PressRecognizer;Hammer.on=addEventListeners;Hammer.off=removeEventListeners;Hammer.each=each;Hammer.merge=merge$1;Hammer.extend=extend;Hammer.bindFn=bindFn;Hammer.assign=assign$1;Hammer.inherit=inherit;Hammer.bindFn=bindFn;Hammer.prefixed=prefixed;Hammer.toArray=toArray;Hammer.inArray=inArray;Hammer.uniqueArray=uniqueArray;Hammer.splitStr=splitStr;Hammer.boolOrFn=boolOrFn;Hammer.hasParent=hasParent;Hammer.addEventListeners=addEventListeners;Hammer.removeEventListeners=removeEventListeners;Hammer.defaults=assign$1({},defaults,{preset:preset});return Hammer;}();//  style loader but by script tag, not by the loader.
Hammer$2.defaults;/**
 * Use this symbol to delete properies in deepObjectAssign.
 */const DELETE=_Symbol$1("DELETE");/**
 * Pure version of deepObjectAssign, it doesn't modify any of it's arguments.
 * @param base - The base object that fullfils the whole interface T.
 * @param updates - Updates that may change or delete props.
 * @returns A brand new instance with all the supplied objects deeply merged.
 */function pureDeepObjectAssign(base){for(var _len=arguments.length,updates=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){updates[_key-1]=arguments[_key];}return deepObjectAssign({},base,...updates);}/**
 * Deep version of object assign with additional deleting by the DELETE symbol.
 * @param values - Objects to be deeply merged.
 * @returns The first object from values.
 */function deepObjectAssign(){const merged=deepObjectAssignNonentry(...arguments);stripDelete(merged);return merged;}/**
 * Deep version of object assign with additional deleting by the DELETE symbol.
 * @remarks
 * This doesn't strip the DELETE symbols so they may end up in the final object.
 * @param values - Objects to be deeply merged.
 * @returns The first object from values.
 */function deepObjectAssignNonentry(){for(var _len2=arguments.length,values=new Array(_len2),_key2=0;_key2<_len2;_key2++){values[_key2]=arguments[_key2];}if(values.length<2){return values[0];}else if(values.length>2){return deepObjectAssignNonentry(deepObjectAssign(values[0],values[1]),..._sliceInstanceProperty(values).call(values,2));}const a=values[0];const b=values[1];if(a instanceof Date&&b instanceof Date){a.setTime(b.getTime());return a;}for(const prop of _Reflect$ownKeys(b)){if(!Object.prototype.propertyIsEnumerable.call(b,prop));else if(b[prop]===DELETE){delete a[prop];}else if(a[prop]!==null&&b[prop]!==null&&typeof a[prop]==="object"&&typeof b[prop]==="object"&&!_Array$isArray(a[prop])&&!_Array$isArray(b[prop])){a[prop]=deepObjectAssignNonentry(a[prop],b[prop]);}else {a[prop]=clone(b[prop]);}}return a;}/**
 * Deep clone given object or array. In case of primitive simply return.
 * @param a - Anything.
 * @returns Deep cloned object/array or unchanged a.
 */function clone(a){if(_Array$isArray(a)){return _mapInstanceProperty(a).call(a,value=>clone(value));}else if(typeof a==="object"&&a!==null){if(a instanceof Date){return new Date(a.getTime());}return deepObjectAssignNonentry({},a);}else {return a;}}/**
 * Strip DELETE from given object.
 * @param a - Object which may contain DELETE but won't after this is executed.
 */function stripDelete(a){for(const prop of _Object$keys(a)){if(a[prop]===DELETE){delete a[prop];}else if(typeof a[prop]==="object"&&a[prop]!==null){stripDelete(a[prop]);}}}/**
 * Seedable, fast and reasonably good (not crypto but more than okay for our
 * needs) random number generator.
 * @remarks
 * Adapted from {@link https://web.archive.org/web/20110429100736/http://baagoe.com:80/en/RandomMusings/javascript}.
 * Original algorithm created by Johannes Baagøe \<baagoe\@baagoe.com\> in 2010.
 *//**
 * Create a seeded pseudo random generator based on Alea by Johannes Baagøe.
 * @param seed - All supplied arguments will be used as a seed. In case nothing
 * is supplied the current time will be used to seed the generator.
 * @returns A ready to use seeded generator.
 */function Alea(){for(var _len3=arguments.length,seed=new Array(_len3),_key3=0;_key3<_len3;_key3++){seed[_key3]=arguments[_key3];}return AleaImplementation(seed.length?seed:[_Date$now()]);}/**
 * An implementation of [[Alea]] without user input validation.
 * @param seed - The data that will be used to seed the generator.
 * @returns A ready to use seeded generator.
 */function AleaImplementation(seed){let[s0,s1,s2]=mashSeed(seed);let c=1;const random=()=>{const t=2091639*s0+c*2.3283064365386963e-10;// 2^-32
s0=s1;s1=s2;return s2=t-(c=t|0);};random.uint32=()=>random()*0x100000000;// 2^32
random.fract53=()=>random()+(random()*0x200000|0)*1.1102230246251565e-16;// 2^-53
random.algorithm="Alea";random.seed=seed;random.version="0.9";return random;}/**
 * Turn arbitrary data into values [[AleaImplementation]] can use to generate
 * random numbers.
 * @param seed - Arbitrary data that will be used as the seed.
 * @returns Three numbers to use as initial values for [[AleaImplementation]].
 */function mashSeed(){const mash=Mash();let s0=mash(" ");let s1=mash(" ");let s2=mash(" ");for(let i=0;i<arguments.length;i++){s0-=mash(i<0||arguments.length<=i?undefined:arguments[i]);if(s0<0){s0+=1;}s1-=mash(i<0||arguments.length<=i?undefined:arguments[i]);if(s1<0){s1+=1;}s2-=mash(i<0||arguments.length<=i?undefined:arguments[i]);if(s2<0){s2+=1;}}return [s0,s1,s2];}/**
 * Create a new mash function.
 * @returns A nonpure function that takes arbitrary [[Mashable]] data and turns
 * them into numbers.
 */function Mash(){let n=0xefc8249d;return function(data){const string=data.toString();for(let i=0;i<string.length;i++){n+=string.charCodeAt(i);let h=0.02519603282416938*n;n=h>>>0;h-=n;h*=n;n=h>>>0;h-=n;n+=h*0x100000000;// 2^32
}return (n>>>0)*2.3283064365386963e-10;// 2^-32
};}/**
 * Setup a mock hammer.js object, for unit testing.
 *
 * Inspiration: https://github.com/uber/deck.gl/pull/658
 * @returns {{on: noop, off: noop, destroy: noop, emit: noop, get: get}}
 */function hammerMock(){const noop=()=>{};return {on:noop,off:noop,destroy:noop,emit:noop,get(){return {set:noop};}};}const Hammer$1=typeof window!=="undefined"?window.Hammer||Hammer$2:function(){// hammer.js is only available in a browser, not in node.js. Replacing it with a mock object.
return hammerMock();};/**
 * Turn an element into an clickToUse element.
 * When not active, the element has a transparent overlay. When the overlay is
 * clicked, the mode is changed to active.
 * When active, the element is displayed with a blue border around it, and
 * the interactive contents of the element can be used. When clicked outside
 * the element, the elements mode is changed to inactive.
 * @param {Element} container
 * @class Activator
 */function Activator$1(container){var _context;this._cleanupQueue=[];this.active=false;this._dom={container,overlay:document.createElement("div")};this._dom.overlay.classList.add("vis-overlay");this._dom.container.appendChild(this._dom.overlay);this._cleanupQueue.push(()=>{this._dom.overlay.parentNode.removeChild(this._dom.overlay);});const hammer=Hammer$1(this._dom.overlay);hammer.on("tap",_bindInstanceProperty(_context=this._onTapOverlay).call(_context,this));this._cleanupQueue.push(()=>{hammer.destroy();// FIXME: cleaning up hammer instances doesn't work (Timeline not removed
// from memory)
});// block all touch events (except tap)
const events=["tap","doubletap","press","pinch","pan","panstart","panmove","panend"];_forEachInstanceProperty(events).call(events,event=>{hammer.on(event,event=>{event.srcEvent.stopPropagation();});});// attach a click event to the window, in order to deactivate when clicking outside the timeline
if(document&&document.body){this._onClick=event=>{if(!_hasParent(event.target,container)){this.deactivate();}};document.body.addEventListener("click",this._onClick);this._cleanupQueue.push(()=>{document.body.removeEventListener("click",this._onClick);});}// prepare escape key listener for deactivating when active
this._escListener=event=>{if("key"in event?event.key==="Escape":event.keyCode===27/* the keyCode is for IE11 */){this.deactivate();}};}// turn into an event emitter
Emitter(Activator$1.prototype);// The currently active activator
Activator$1.current=null;/**
 * Destroy the activator. Cleans up all created DOM and event listeners
 */Activator$1.prototype.destroy=function(){this.deactivate();for(const callback of _reverseInstanceProperty(_context2=_spliceInstanceProperty(_context3=this._cleanupQueue).call(_context3,0)).call(_context2)){var _context2,_context3;callback();}};/**
 * Activate the element
 * Overlay is hidden, element is decorated with a blue shadow border
 */Activator$1.prototype.activate=function(){// we allow only one active activator at a time
if(Activator$1.current){Activator$1.current.deactivate();}Activator$1.current=this;this.active=true;this._dom.overlay.style.display="none";this._dom.container.classList.add("vis-active");this.emit("change");this.emit("activate");// ugly hack: bind ESC after emitting the events, as the Network rebinds all
// keyboard events on a 'change' event
document.body.addEventListener("keydown",this._escListener);};/**
 * Deactivate the element
 * Overlay is displayed on top of the element
 */Activator$1.prototype.deactivate=function(){this.active=false;this._dom.overlay.style.display="block";this._dom.container.classList.remove("vis-active");document.body.removeEventListener("keydown",this._escListener);this.emit("change");this.emit("deactivate");};/**
 * Handle a tap event: activate the container
 * @param {Event}  event   The event
 * @private
 */Activator$1.prototype._onTapOverlay=function(event){// activate the container
this.activate();event.srcEvent.stopPropagation();};/**
 * Test whether the element has the requested parent element somewhere in
 * its chain of parent nodes.
 * @param {HTMLElement} element
 * @param {HTMLElement} parent
 * @returns {boolean} Returns true when the parent is found somewhere in the
 *                    chain of parent nodes.
 * @private
 */function _hasParent(element,parent){while(element){if(element===parent){return true;}element=element.parentNode;}return false;}// Color REs
const fullHexRE=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;const shortHexRE=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;const rgbRE=/^rgb\( *(1?\d{1,2}|2[0-4]\d|25[0-5]) *, *(1?\d{1,2}|2[0-4]\d|25[0-5]) *, *(1?\d{1,2}|2[0-4]\d|25[0-5]) *\)$/i;const rgbaRE=/^rgba\( *(1?\d{1,2}|2[0-4]\d|25[0-5]) *, *(1?\d{1,2}|2[0-4]\d|25[0-5]) *, *(1?\d{1,2}|2[0-4]\d|25[0-5]) *, *([01]|0?\.\d+) *\)$/i;/**
 * Remove everything in the DOM object.
 * @param DOMobject - Node whose child nodes will be recursively deleted.
 */function recursiveDOMDelete(DOMobject){if(DOMobject){while(DOMobject.hasChildNodes()===true){const child=DOMobject.firstChild;if(child){recursiveDOMDelete(child);DOMobject.removeChild(child);}}}}/**
 * Test whether given object is a string.
 * @param value - Input value of unknown type.
 * @returns True if string, false otherwise.
 */function isString(value){return value instanceof String||typeof value==="string";}/**
 * Test whether given object is a object (not primitive or null).
 * @param value - Input value of unknown type.
 * @returns True if not null object, false otherwise.
 */function isObject(value){return typeof value==="object"&&value!==null;}/**
 * Copy property from b to a if property present in a.
 * If property in b explicitly set to null, delete it if `allowDeletion` set.
 *
 * Internal helper routine, should not be exported. Not added to `exports` for that reason.
 * @param a - Target object.
 * @param b - Source object.
 * @param prop - Name of property to copy from b to a.
 * @param allowDeletion - If true, delete property in a if explicitly set to null in b.
 */function copyOrDelete(a,b,prop,allowDeletion){let doDeletion=false;if(allowDeletion===true){doDeletion=b[prop]===null&&a[prop]!==undefined;}if(doDeletion){delete a[prop];}else {a[prop]=b[prop];// Remember, this is a reference copy!
}}/**
 * Fill an object with a possibly partially defined other object.
 *
 * Only copies values for the properties already present in a.
 * That means an object is not created on a property if only the b object has it.
 * @param a - The object that will have it's properties updated.
 * @param b - The object with property updates.
 * @param allowDeletion - If true, delete properties in a that are explicitly set to null in b.
 */function fillIfDefined(a,b){let allowDeletion=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;// NOTE: iteration of properties of a
// NOTE: prototype properties iterated over as well
for(const prop in a){if(b[prop]!==undefined){if(b[prop]===null||typeof b[prop]!=="object"){// Note: typeof null === 'object'
copyOrDelete(a,b,prop,allowDeletion);}else {const aProp=a[prop];const bProp=b[prop];if(isObject(aProp)&&isObject(bProp)){fillIfDefined(aProp,bProp,allowDeletion);}}}}}/**
 * Extend object a with selected properties of object b.
 * Only properties with defined values are copied.
 * @remarks
 * Previous version of this routine implied that multiple source objects could
 * be used; however, the implementation was **wrong**. Since multiple (\>1)
 * sources weren't used anywhere in the `vis.js` code, this has been removed
 * @param props - Names of first-level properties to copy over.
 * @param a - Target object.
 * @param b - Source object.
 * @param allowDeletion - If true, delete property in a if explicitly set to null in b.
 * @returns Argument a.
 */function selectiveDeepExtend(props,a,b){let allowDeletion=arguments.length>3&&arguments[3]!==undefined?arguments[3]:false;// TODO: add support for Arrays to deepExtend
if(_Array$isArray(b)){throw new TypeError("Arrays are not supported by deepExtend");}for(let p=0;p<props.length;p++){const prop=props[p];if(Object.prototype.hasOwnProperty.call(b,prop)){if(b[prop]&&b[prop].constructor===Object){if(a[prop]===undefined){a[prop]={};}if(a[prop].constructor===Object){deepExtend(a[prop],b[prop],false,allowDeletion);}else {copyOrDelete(a,b,prop,allowDeletion);}}else if(_Array$isArray(b[prop])){throw new TypeError("Arrays are not supported by deepExtend");}else {copyOrDelete(a,b,prop,allowDeletion);}}}return a;}/**
 * Extend object `a` with properties of object `b`, ignoring properties which
 * are explicitly specified to be excluded.
 * @remarks
 * The properties of `b` are considered for copying. Properties which are
 * themselves objects are are also extended. Only properties with defined
 * values are copied.
 * @param propsToExclude - Names of properties which should *not* be copied.
 * @param a - Object to extend.
 * @param b - Object to take properties from for extension.
 * @param allowDeletion - If true, delete properties in a that are explicitly
 * set to null in b.
 * @returns Argument a.
 */function selectiveNotDeepExtend(propsToExclude,a,b){let allowDeletion=arguments.length>3&&arguments[3]!==undefined?arguments[3]:false;// TODO: add support for Arrays to deepExtend
// NOTE: array properties have an else-below; apparently, there is a problem here.
if(_Array$isArray(b)){throw new TypeError("Arrays are not supported by deepExtend");}for(const prop in b){if(!Object.prototype.hasOwnProperty.call(b,prop)){continue;}// Handle local properties only
if(_includesInstanceProperty(propsToExclude).call(propsToExclude,prop)){continue;}// In exclusion list, skip
if(b[prop]&&b[prop].constructor===Object){if(a[prop]===undefined){a[prop]={};}if(a[prop].constructor===Object){deepExtend(a[prop],b[prop]);// NOTE: allowDeletion not propagated!
}else {copyOrDelete(a,b,prop,allowDeletion);}}else if(_Array$isArray(b[prop])){a[prop]=[];for(let i=0;i<b[prop].length;i++){a[prop].push(b[prop][i]);}}else {copyOrDelete(a,b,prop,allowDeletion);}}return a;}/**
 * Deep extend an object a with the properties of object b.
 * @param a - Target object.
 * @param b - Source object.
 * @param protoExtend - If true, the prototype values will also be extended.
 * (That is the options objects that inherit from others will also get the
 * inherited options).
 * @param allowDeletion - If true, the values of fields that are null will be deleted.
 * @returns Argument a.
 */function deepExtend(a,b){let protoExtend=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;let allowDeletion=arguments.length>3&&arguments[3]!==undefined?arguments[3]:false;for(const prop in b){if(Object.prototype.hasOwnProperty.call(b,prop)||protoExtend===true){if(typeof b[prop]==="object"&&b[prop]!==null&&_Object$getPrototypeOf(b[prop])===Object.prototype){if(a[prop]===undefined){a[prop]=deepExtend({},b[prop],protoExtend);// NOTE: allowDeletion not propagated!
}else if(typeof a[prop]==="object"&&a[prop]!==null&&_Object$getPrototypeOf(a[prop])===Object.prototype){deepExtend(a[prop],b[prop],protoExtend);// NOTE: allowDeletion not propagated!
}else {copyOrDelete(a,b,prop,allowDeletion);}}else if(_Array$isArray(b[prop])){var _context4;a[prop]=_sliceInstanceProperty(_context4=b[prop]).call(_context4);}else {copyOrDelete(a,b,prop,allowDeletion);}}}return a;}/**
 * Used to extend an array and copy it. This is used to propagate paths recursively.
 * @param arr - First part.
 * @param newValue - The value to be aadded into the array.
 * @returns A new array with all items from arr and newValue (which is last).
 */function copyAndExtendArray(arr,newValue){return [...arr,newValue];}/**
 * Used to extend an array and copy it. This is used to propagate paths recursively.
 * @param arr - The array to be copied.
 * @returns Shallow copy of arr.
 */function copyArray(arr){return _sliceInstanceProperty(arr).call(arr);}/**
 * Retrieve the absolute left value of a DOM element.
 * @param elem - A dom element, for example a div.
 * @returns The absolute left position of this element in the browser page.
 */function getAbsoluteLeft(elem){return elem.getBoundingClientRect().left;}/**
 * Retrieve the absolute top value of a DOM element.
 * @param elem - A dom element, for example a div.
 * @returns The absolute top position of this element in the browser page.
 */function getAbsoluteTop(elem){return elem.getBoundingClientRect().top;}/**
 * For each method for both arrays and objects.
 * In case of an array, the built-in Array.forEach() is applied (**No, it's not!**).
 * In case of an Object, the method loops over all properties of the object.
 * @param object - An Object or Array to be iterated over.
 * @param callback - Array.forEach-like callback.
 */function forEach(object,callback){if(_Array$isArray(object)){// array
const len=object.length;for(let i=0;i<len;i++){callback(object[i],i,object);}}else {// object
for(const key in object){if(Object.prototype.hasOwnProperty.call(object,key)){callback(object[key],key,object);}}}}/**
 * Convert hex color string into RGB color object.
 * @remarks
 * {@link http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb}
 * @param hex - Hex color string (3 or 6 digits, with or without #).
 * @returns RGB color object.
 */function hexToRGB(hex){let result;switch(hex.length){case 3:case 4:result=shortHexRE.exec(hex);return result?{r:_parseInt(result[1]+result[1],16),g:_parseInt(result[2]+result[2],16),b:_parseInt(result[3]+result[3],16)}:null;case 6:case 7:result=fullHexRE.exec(hex);return result?{r:_parseInt(result[1],16),g:_parseInt(result[2],16),b:_parseInt(result[3],16)}:null;default:return null;}}/**
 * This function takes string color in hex or RGB format and adds the opacity, RGBA is passed through unchanged.
 * @param color - The color string (hex, RGB, RGBA).
 * @param opacity - The new opacity.
 * @returns RGBA string, for example 'rgba(255, 0, 127, 0.3)'.
 */function overrideOpacity(color,opacity){if(_includesInstanceProperty(color).call(color,"rgba")){return color;}else if(_includesInstanceProperty(color).call(color,"rgb")){const rgb=color.substr(_indexOfInstanceProperty(color).call(color,"(")+1).replace(")","").split(",");return "rgba("+rgb[0]+","+rgb[1]+","+rgb[2]+","+opacity+")";}else {const rgb=hexToRGB(color);if(rgb==null){return color;}else {return "rgba("+rgb.r+","+rgb.g+","+rgb.b+","+opacity+")";}}}/**
 * Convert RGB \<0, 255\> into hex color string.
 * @param red - Red channel.
 * @param green - Green channel.
 * @param blue - Blue channel.
 * @returns Hex color string (for example: '#0acdc0').
 */function RGBToHex(red,green,blue){var _context5;return "#"+_sliceInstanceProperty(_context5=((1<<24)+(red<<16)+(green<<8)+blue).toString(16)).call(_context5,1);}/**
 * Parse a color property into an object with border, background, and highlight colors.
 * @param inputColor - Shorthand color string or input color object.
 * @param defaultColor - Full color object to fill in missing values in inputColor.
 * @returns Color object.
 */function parseColor(inputColor,defaultColor){if(isString(inputColor)){let colorStr=inputColor;if(isValidRGB(colorStr)){var _context6;const rgb=_mapInstanceProperty(_context6=colorStr.substr(4).substr(0,colorStr.length-5).split(",")).call(_context6,function(value){return _parseInt(value);});colorStr=RGBToHex(rgb[0],rgb[1],rgb[2]);}if(isValidHex(colorStr)===true){const hsv=hexToHSV(colorStr);const lighterColorHSV={h:hsv.h,s:hsv.s*0.8,v:Math.min(1,hsv.v*1.02)};const darkerColorHSV={h:hsv.h,s:Math.min(1,hsv.s*1.25),v:hsv.v*0.8};const darkerColorHex=HSVToHex(darkerColorHSV.h,darkerColorHSV.s,darkerColorHSV.v);const lighterColorHex=HSVToHex(lighterColorHSV.h,lighterColorHSV.s,lighterColorHSV.v);return {background:colorStr,border:darkerColorHex,highlight:{background:lighterColorHex,border:darkerColorHex},hover:{background:lighterColorHex,border:darkerColorHex}};}else {return {background:colorStr,border:colorStr,highlight:{background:colorStr,border:colorStr},hover:{background:colorStr,border:colorStr}};}}else {{const color={background:inputColor.background||undefined,border:inputColor.border||undefined,highlight:isString(inputColor.highlight)?{border:inputColor.highlight,background:inputColor.highlight}:{background:inputColor.highlight&&inputColor.highlight.background||undefined,border:inputColor.highlight&&inputColor.highlight.border||undefined},hover:isString(inputColor.hover)?{border:inputColor.hover,background:inputColor.hover}:{border:inputColor.hover&&inputColor.hover.border||undefined,background:inputColor.hover&&inputColor.hover.background||undefined}};return color;}}}/**
 * Convert RGB \<0, 255\> into HSV object.
 * @remarks
 * {@link http://www.javascripter.net/faq/rgb2hsv.htm}
 * @param red - Red channel.
 * @param green - Green channel.
 * @param blue - Blue channel.
 * @returns HSV color object.
 */function RGBToHSV(red,green,blue){red=red/255;green=green/255;blue=blue/255;const minRGB=Math.min(red,Math.min(green,blue));const maxRGB=Math.max(red,Math.max(green,blue));// Black-gray-white
if(minRGB===maxRGB){return {h:0,s:0,v:minRGB};}// Colors other than black-gray-white:
const d=red===minRGB?green-blue:blue===minRGB?red-green:blue-red;const h=red===minRGB?3:blue===minRGB?1:5;const hue=60*(h-d/(maxRGB-minRGB))/360;const saturation=(maxRGB-minRGB)/maxRGB;const value=maxRGB;return {h:hue,s:saturation,v:value};}/**
 * Convert HSV \<0, 1\> into RGB color object.
 * @remarks
 * {@link https://gist.github.com/mjijackson/5311256}
 * @param h - Hue.
 * @param s - Saturation.
 * @param v - Value.
 * @returns RGB color object.
 */function HSVToRGB(h,s,v){let r;let g;let b;const i=Math.floor(h*6);const f=h*6-i;const p=v*(1-s);const q=v*(1-f*s);const t=v*(1-(1-f)*s);switch(i%6){case 0:r=v,g=t,b=p;break;case 1:r=q,g=v,b=p;break;case 2:r=p,g=v,b=t;break;case 3:r=p,g=q,b=v;break;case 4:r=t,g=p,b=v;break;case 5:r=v,g=p,b=q;break;}return {r:Math.floor(r*255),g:Math.floor(g*255),b:Math.floor(b*255)};}/**
 * Convert HSV \<0, 1\> into hex color string.
 * @param h - Hue.
 * @param s - Saturation.
 * @param v - Value.
 * @returns Hex color string.
 */function HSVToHex(h,s,v){const rgb=HSVToRGB(h,s,v);return RGBToHex(rgb.r,rgb.g,rgb.b);}/**
 * Convert hex color string into HSV \<0, 1\>.
 * @param hex - Hex color string.
 * @returns HSV color object.
 */function hexToHSV(hex){const rgb=hexToRGB(hex);if(!rgb){throw new TypeError("'".concat(hex,"' is not a valid color."));}return RGBToHSV(rgb.r,rgb.g,rgb.b);}/**
 * Validate hex color string.
 * @param hex - Unknown string that may contain a color.
 * @returns True if the string is valid, false otherwise.
 */function isValidHex(hex){const isOk=/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex);return isOk;}/**
 * Validate RGB color string.
 * @param rgb - Unknown string that may contain a color.
 * @returns True if the string is valid, false otherwise.
 */function isValidRGB(rgb){return rgbRE.test(rgb);}/**
 * Validate RGBA color string.
 * @param rgba - Unknown string that may contain a color.
 * @returns True if the string is valid, false otherwise.
 */function isValidRGBA(rgba){return rgbaRE.test(rgba);}/**
 * This recursively redirects the prototype of JSON objects to the referenceObject.
 * This is used for default options.
 * @param referenceObject - The original object.
 * @returns The Element if the referenceObject is an Element, or a new object inheriting from the referenceObject.
 */function bridgeObject(referenceObject){if(referenceObject===null||typeof referenceObject!=="object"){return null;}if(referenceObject instanceof Element){// Avoid bridging DOM objects
return referenceObject;}const objectTo=_Object$create(referenceObject);for(const i in referenceObject){if(Object.prototype.hasOwnProperty.call(referenceObject,i)){if(typeof referenceObject[i]=="object"){objectTo[i]=bridgeObject(referenceObject[i]);}}}return objectTo;}/**
 * This is used to set the options of subobjects in the options object.
 *
 * A requirement of these subobjects is that they have an 'enabled' element
 * which is optional for the user but mandatory for the program.
 *
 * The added value here of the merge is that option 'enabled' is set as required.
 * @param mergeTarget - Either this.options or the options used for the groups.
 * @param options - Options.
 * @param option - Option key in the options argument.
 * @param globalOptions - Global options, passed in to determine value of option 'enabled'.
 */function mergeOptions(mergeTarget,options,option){let globalOptions=arguments.length>3&&arguments[3]!==undefined?arguments[3]:{};// Local helpers
const isPresent=function(obj){return obj!==null&&obj!==undefined;};const isObject=function(obj){return obj!==null&&typeof obj==="object";};// https://stackoverflow.com/a/34491287/1223531
const isEmpty=function(obj){for(const x in obj){if(Object.prototype.hasOwnProperty.call(obj,x)){return false;}}return true;};// Guards
if(!isObject(mergeTarget)){throw new Error("Parameter mergeTarget must be an object");}if(!isObject(options)){throw new Error("Parameter options must be an object");}if(!isPresent(option)){throw new Error("Parameter option must have a value");}if(!isObject(globalOptions)){throw new Error("Parameter globalOptions must be an object");}//
// Actual merge routine, separated from main logic
// Only a single level of options is merged. Deeper levels are ref'd. This may actually be an issue.
//
const doMerge=function(target,options,option){if(!isObject(target[option])){target[option]={};}const src=options[option];const dst=target[option];for(const prop in src){if(Object.prototype.hasOwnProperty.call(src,prop)){dst[prop]=src[prop];}}};// Local initialization
const srcOption=options[option];const globalPassed=isObject(globalOptions)&&!isEmpty(globalOptions);const globalOption=globalPassed?globalOptions[option]:undefined;const globalEnabled=globalOption?globalOption.enabled:undefined;/////////////////////////////////////////
// Main routine
/////////////////////////////////////////
if(srcOption===undefined){return;// Nothing to do
}if(typeof srcOption==="boolean"){if(!isObject(mergeTarget[option])){mergeTarget[option]={};}mergeTarget[option].enabled=srcOption;return;}if(srcOption===null&&!isObject(mergeTarget[option])){// If possible, explicit copy from globals
if(isPresent(globalOption)){mergeTarget[option]=_Object$create(globalOption);}else {return;// Nothing to do
}}if(!isObject(srcOption)){return;}//
// Ensure that 'enabled' is properly set. It is required internally
// Note that the value from options will always overwrite the existing value
//
let enabled=true;// default value
if(srcOption.enabled!==undefined){enabled=srcOption.enabled;}else {// Take from globals, if present
if(globalEnabled!==undefined){enabled=globalOption.enabled;}}doMerge(mergeTarget,options,option);mergeTarget[option].enabled=enabled;}/*
 * Easing Functions.
 * Only considering the t value for the range [0, 1] => [0, 1].
 *
 * Inspiration: from http://gizma.com/easing/
 * https://gist.github.com/gre/1650294
 */const easingFunctions={/**
   * Provides no easing and no acceleration.
   * @param t - Time.
   * @returns Value at time t.
   */linear(t){return t;},/**
   * Accelerate from zero velocity.
   * @param t - Time.
   * @returns Value at time t.
   */easeInQuad(t){return t*t;},/**
   * Decelerate to zero velocity.
   * @param t - Time.
   * @returns Value at time t.
   */easeOutQuad(t){return t*(2-t);},/**
   * Accelerate until halfway, then decelerate.
   * @param t - Time.
   * @returns Value at time t.
   */easeInOutQuad(t){return t<0.5?2*t*t:-1+(4-2*t)*t;},/**
   * Accelerate from zero velocity.
   * @param t - Time.
   * @returns Value at time t.
   */easeInCubic(t){return t*t*t;},/**
   * Decelerate to zero velocity.
   * @param t - Time.
   * @returns Value at time t.
   */easeOutCubic(t){return --t*t*t+1;},/**
   * Accelerate until halfway, then decelerate.
   * @param t - Time.
   * @returns Value at time t.
   */easeInOutCubic(t){return t<0.5?4*t*t*t:(t-1)*(2*t-2)*(2*t-2)+1;},/**
   * Accelerate from zero velocity.
   * @param t - Time.
   * @returns Value at time t.
   */easeInQuart(t){return t*t*t*t;},/**
   * Decelerate to zero velocity.
   * @param t - Time.
   * @returns Value at time t.
   */easeOutQuart(t){return 1- --t*t*t*t;},/**
   * Accelerate until halfway, then decelerate.
   * @param t - Time.
   * @returns Value at time t.
   */easeInOutQuart(t){return t<0.5?8*t*t*t*t:1-8*--t*t*t*t;},/**
   * Accelerate from zero velocity.
   * @param t - Time.
   * @returns Value at time t.
   */easeInQuint(t){return t*t*t*t*t;},/**
   * Decelerate to zero velocity.
   * @param t - Time.
   * @returns Value at time t.
   */easeOutQuint(t){return 1+--t*t*t*t*t;},/**
   * Accelerate until halfway, then decelerate.
   * @param t - Time.
   * @returns Value at time t.
   */easeInOutQuint(t){return t<0.5?16*t*t*t*t*t:1+16*--t*t*t*t*t;}};// @TODO: This doesn't work properly.
// It works only for single property objects,
// otherwise it combines all of the types in a union.
// export function topMost<K1 extends string, V1> (
//   pile: Record<K1, undefined | V1>[],
//   accessors: K1 | [K1]
// ): undefined | V1
// export function topMost<K1 extends string, K2 extends string, V1, V2> (
//   pile: Record<K1, undefined | V1 | Record<K2, undefined | V2>>[],
//   accessors: [K1, K2]
// ): undefined | V1 | V2
// export function topMost<K1 extends string, K2 extends string, K3 extends string, V1, V2, V3> (
//   pile: Record<K1, undefined | V1 | Record<K2, undefined | V2 | Record<K3, undefined | V3>>>[],
//   accessors: [K1, K2, K3]
// ): undefined | V1 | V2 | V3
/**
 * Get the top most property value from a pile of objects.
 * @param pile - Array of objects, no required format.
 * @param accessors - Array of property names.
 * For example `object['foo']['bar']` → `['foo', 'bar']`.
 * @returns Value of the property with given accessors path from the first pile item where it's not undefined.
 */function topMost(pile,accessors){let candidate;if(!_Array$isArray(accessors)){accessors=[accessors];}for(const member of pile){if(member){candidate=member[accessors[0]];for(let i=1;i<accessors.length;i++){if(candidate){candidate=candidate[accessors[i]];}}if(typeof candidate!=="undefined"){break;}}}return candidate;}const htmlColors={black:"#000000",navy:"#000080",darkblue:"#00008B",mediumblue:"#0000CD",blue:"#0000FF",darkgreen:"#006400",green:"#008000",teal:"#008080",darkcyan:"#008B8B",deepskyblue:"#00BFFF",darkturquoise:"#00CED1",mediumspringgreen:"#00FA9A",lime:"#00FF00",springgreen:"#00FF7F",aqua:"#00FFFF",cyan:"#00FFFF",midnightblue:"#191970",dodgerblue:"#1E90FF",lightseagreen:"#20B2AA",forestgreen:"#228B22",seagreen:"#2E8B57",darkslategray:"#2F4F4F",limegreen:"#32CD32",mediumseagreen:"#3CB371",turquoise:"#40E0D0",royalblue:"#4169E1",steelblue:"#4682B4",darkslateblue:"#483D8B",mediumturquoise:"#48D1CC",indigo:"#4B0082",darkolivegreen:"#556B2F",cadetblue:"#5F9EA0",cornflowerblue:"#6495ED",mediumaquamarine:"#66CDAA",dimgray:"#696969",slateblue:"#6A5ACD",olivedrab:"#6B8E23",slategray:"#708090",lightslategray:"#778899",mediumslateblue:"#7B68EE",lawngreen:"#7CFC00",chartreuse:"#7FFF00",aquamarine:"#7FFFD4",maroon:"#800000",purple:"#800080",olive:"#808000",gray:"#808080",skyblue:"#87CEEB",lightskyblue:"#87CEFA",blueviolet:"#8A2BE2",darkred:"#8B0000",darkmagenta:"#8B008B",saddlebrown:"#8B4513",darkseagreen:"#8FBC8F",lightgreen:"#90EE90",mediumpurple:"#9370D8",darkviolet:"#9400D3",palegreen:"#98FB98",darkorchid:"#9932CC",yellowgreen:"#9ACD32",sienna:"#A0522D",brown:"#A52A2A",darkgray:"#A9A9A9",lightblue:"#ADD8E6",greenyellow:"#ADFF2F",paleturquoise:"#AFEEEE",lightsteelblue:"#B0C4DE",powderblue:"#B0E0E6",firebrick:"#B22222",darkgoldenrod:"#B8860B",mediumorchid:"#BA55D3",rosybrown:"#BC8F8F",darkkhaki:"#BDB76B",silver:"#C0C0C0",mediumvioletred:"#C71585",indianred:"#CD5C5C",peru:"#CD853F",chocolate:"#D2691E",tan:"#D2B48C",lightgrey:"#D3D3D3",palevioletred:"#D87093",thistle:"#D8BFD8",orchid:"#DA70D6",goldenrod:"#DAA520",crimson:"#DC143C",gainsboro:"#DCDCDC",plum:"#DDA0DD",burlywood:"#DEB887",lightcyan:"#E0FFFF",lavender:"#E6E6FA",darksalmon:"#E9967A",violet:"#EE82EE",palegoldenrod:"#EEE8AA",lightcoral:"#F08080",khaki:"#F0E68C",aliceblue:"#F0F8FF",honeydew:"#F0FFF0",azure:"#F0FFFF",sandybrown:"#F4A460",wheat:"#F5DEB3",beige:"#F5F5DC",whitesmoke:"#F5F5F5",mintcream:"#F5FFFA",ghostwhite:"#F8F8FF",salmon:"#FA8072",antiquewhite:"#FAEBD7",linen:"#FAF0E6",lightgoldenrodyellow:"#FAFAD2",oldlace:"#FDF5E6",red:"#FF0000",fuchsia:"#FF00FF",magenta:"#FF00FF",deeppink:"#FF1493",orangered:"#FF4500",tomato:"#FF6347",hotpink:"#FF69B4",coral:"#FF7F50",darkorange:"#FF8C00",lightsalmon:"#FFA07A",orange:"#FFA500",lightpink:"#FFB6C1",pink:"#FFC0CB",gold:"#FFD700",peachpuff:"#FFDAB9",navajowhite:"#FFDEAD",moccasin:"#FFE4B5",bisque:"#FFE4C4",mistyrose:"#FFE4E1",blanchedalmond:"#FFEBCD",papayawhip:"#FFEFD5",lavenderblush:"#FFF0F5",seashell:"#FFF5EE",cornsilk:"#FFF8DC",lemonchiffon:"#FFFACD",floralwhite:"#FFFAF0",snow:"#FFFAFA",yellow:"#FFFF00",lightyellow:"#FFFFE0",ivory:"#FFFFF0",white:"#FFFFFF"};/**
 * @param {number} [pixelRatio=1]
 */let ColorPicker$1=class ColorPicker{/**
   * @param {number} [pixelRatio]
   */constructor(){let pixelRatio=arguments.length>0&&arguments[0]!==undefined?arguments[0]:1;this.pixelRatio=pixelRatio;this.generated=false;this.centerCoordinates={x:289/2,y:289/2};this.r=289*0.49;this.color={r:255,g:255,b:255,a:1.0};this.hueCircle=undefined;this.initialColor={r:255,g:255,b:255,a:1.0};this.previousColor=undefined;this.applied=false;// bound by
this.updateCallback=()=>{};this.closeCallback=()=>{};// create all DOM elements
this._create();}/**
   * this inserts the colorPicker into a div from the DOM
   * @param {Element} container
   */insertTo(container){if(this.hammer!==undefined){this.hammer.destroy();this.hammer=undefined;}this.container=container;this.container.appendChild(this.frame);this._bindHammer();this._setSize();}/**
   * the callback is executed on apply and save. Bind it to the application
   * @param {Function} callback
   */setUpdateCallback(callback){if(typeof callback==="function"){this.updateCallback=callback;}else {throw new Error("Function attempted to set as colorPicker update callback is not a function.");}}/**
   * the callback is executed on apply and save. Bind it to the application
   * @param {Function} callback
   */setCloseCallback(callback){if(typeof callback==="function"){this.closeCallback=callback;}else {throw new Error("Function attempted to set as colorPicker closing callback is not a function.");}}/**
   *
   * @param {string} color
   * @returns {string}
   * @private
   */_isColorString(color){if(typeof color==="string"){return htmlColors[color];}}/**
   * Set the color of the colorPicker
   * Supported formats:
   * 'red'                   --> HTML color string
   * '#ffffff'               --> hex string
   * 'rgb(255,255,255)'      --> rgb string
   * 'rgba(255,255,255,1.0)' --> rgba string
   * {r:255,g:255,b:255}     --> rgb object
   * {r:255,g:255,b:255,a:1.0} --> rgba object
   * @param {string | object} color
   * @param {boolean} [setInitial]
   */setColor(color){let setInitial=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;if(color==="none"){return;}let rgba;// if a html color shorthand is used, convert to hex
const htmlColor=this._isColorString(color);if(htmlColor!==undefined){color=htmlColor;}// check format
if(isString(color)===true){if(isValidRGB(color)===true){const rgbaArray=color.substr(4).substr(0,color.length-5).split(",");rgba={r:rgbaArray[0],g:rgbaArray[1],b:rgbaArray[2],a:1.0};}else if(isValidRGBA(color)===true){const rgbaArray=color.substr(5).substr(0,color.length-6).split(",");rgba={r:rgbaArray[0],g:rgbaArray[1],b:rgbaArray[2],a:rgbaArray[3]};}else if(isValidHex(color)===true){const rgbObj=hexToRGB(color);rgba={r:rgbObj.r,g:rgbObj.g,b:rgbObj.b,a:1.0};}}else {if(color instanceof Object){if(color.r!==undefined&&color.g!==undefined&&color.b!==undefined){const alpha=color.a!==undefined?color.a:"1.0";rgba={r:color.r,g:color.g,b:color.b,a:alpha};}}}// set color
if(rgba===undefined){throw new Error("Unknown color passed to the colorPicker. Supported are strings: rgb, hex, rgba. Object: rgb ({r:r,g:g,b:b,[a:a]}). Supplied: "+_JSON$stringify(color));}else {this._setColor(rgba,setInitial);}}/**
   * this shows the color picker.
   * The hue circle is constructed once and stored.
   */show(){if(this.closeCallback!==undefined){this.closeCallback();this.closeCallback=undefined;}this.applied=false;this.frame.style.display="block";this._generateHueCircle();}// ------------------------------------------ PRIVATE ----------------------------- //
/**
   * Hide the picker. Is called by the cancel button.
   * Optional boolean to store the previous color for easy access later on.
   * @param {boolean} [storePrevious]
   * @private
   */_hide(){let storePrevious=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;// store the previous color for next time;
if(storePrevious===true){this.previousColor=_Object$assign({},this.color);}if(this.applied===true){this.updateCallback(this.initialColor);}this.frame.style.display="none";// call the closing callback, restoring the onclick method.
// this is in a setTimeout because it will trigger the show again before the click is done.
_setTimeout(()=>{if(this.closeCallback!==undefined){this.closeCallback();this.closeCallback=undefined;}},0);}/**
   * bound to the save button. Saves and hides.
   * @private
   */_save(){this.updateCallback(this.color);this.applied=false;this._hide();}/**
   * Bound to apply button. Saves but does not close. Is undone by the cancel button.
   * @private
   */_apply(){this.applied=true;this.updateCallback(this.color);this._updatePicker(this.color);}/**
   * load the color from the previous session.
   * @private
   */_loadLast(){if(this.previousColor!==undefined){this.setColor(this.previousColor,false);}else {alert("There is no last color to load...");}}/**
   * set the color, place the picker
   * @param {object} rgba
   * @param {boolean} [setInitial]
   * @private
   */_setColor(rgba){let setInitial=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;// store the initial color
if(setInitial===true){this.initialColor=_Object$assign({},rgba);}this.color=rgba;const hsv=RGBToHSV(rgba.r,rgba.g,rgba.b);const angleConvert=2*Math.PI;const radius=this.r*hsv.s;const x=this.centerCoordinates.x+radius*Math.sin(angleConvert*hsv.h);const y=this.centerCoordinates.y+radius*Math.cos(angleConvert*hsv.h);this.colorPickerSelector.style.left=x-0.5*this.colorPickerSelector.clientWidth+"px";this.colorPickerSelector.style.top=y-0.5*this.colorPickerSelector.clientHeight+"px";this._updatePicker(rgba);}/**
   * bound to opacity control
   * @param {number} value
   * @private
   */_setOpacity(value){this.color.a=value/100;this._updatePicker(this.color);}/**
   * bound to brightness control
   * @param {number} value
   * @private
   */_setBrightness(value){const hsv=RGBToHSV(this.color.r,this.color.g,this.color.b);hsv.v=value/100;const rgba=HSVToRGB(hsv.h,hsv.s,hsv.v);rgba["a"]=this.color.a;this.color=rgba;this._updatePicker();}/**
   * update the color picker. A black circle overlays the hue circle to mimic the brightness decreasing.
   * @param {object} rgba
   * @private
   */_updatePicker(){let rgba=arguments.length>0&&arguments[0]!==undefined?arguments[0]:this.color;const hsv=RGBToHSV(rgba.r,rgba.g,rgba.b);const ctx=this.colorPickerCanvas.getContext("2d");if(this.pixelRation===undefined){this.pixelRatio=(window.devicePixelRatio||1)/(ctx.webkitBackingStorePixelRatio||ctx.mozBackingStorePixelRatio||ctx.msBackingStorePixelRatio||ctx.oBackingStorePixelRatio||ctx.backingStorePixelRatio||1);}ctx.setTransform(this.pixelRatio,0,0,this.pixelRatio,0,0);// clear the canvas
const w=this.colorPickerCanvas.clientWidth;const h=this.colorPickerCanvas.clientHeight;ctx.clearRect(0,0,w,h);ctx.putImageData(this.hueCircle,0,0);ctx.fillStyle="rgba(0,0,0,"+(1-hsv.v)+")";ctx.circle(this.centerCoordinates.x,this.centerCoordinates.y,this.r);_fillInstanceProperty(ctx).call(ctx);this.brightnessRange.value=100*hsv.v;this.opacityRange.value=100*rgba.a;this.initialColorDiv.style.backgroundColor="rgba("+this.initialColor.r+","+this.initialColor.g+","+this.initialColor.b+","+this.initialColor.a+")";this.newColorDiv.style.backgroundColor="rgba("+this.color.r+","+this.color.g+","+this.color.b+","+this.color.a+")";}/**
   * used by create to set the size of the canvas.
   * @private
   */_setSize(){this.colorPickerCanvas.style.width="100%";this.colorPickerCanvas.style.height="100%";this.colorPickerCanvas.width=289*this.pixelRatio;this.colorPickerCanvas.height=289*this.pixelRatio;}/**
   * create all dom elements
   * TODO: cleanup, lots of similar dom elements
   * @private
   */_create(){var _context7,_context8,_context9,_context0;this.frame=document.createElement("div");this.frame.className="vis-color-picker";this.colorPickerDiv=document.createElement("div");this.colorPickerSelector=document.createElement("div");this.colorPickerSelector.className="vis-selector";this.colorPickerDiv.appendChild(this.colorPickerSelector);this.colorPickerCanvas=document.createElement("canvas");this.colorPickerDiv.appendChild(this.colorPickerCanvas);if(!this.colorPickerCanvas.getContext){const noCanvas=document.createElement("DIV");noCanvas.style.color="red";noCanvas.style.fontWeight="bold";noCanvas.style.padding="10px";noCanvas.innerText="Error: your browser does not support HTML canvas";this.colorPickerCanvas.appendChild(noCanvas);}else {const ctx=this.colorPickerCanvas.getContext("2d");this.pixelRatio=(window.devicePixelRatio||1)/(ctx.webkitBackingStorePixelRatio||ctx.mozBackingStorePixelRatio||ctx.msBackingStorePixelRatio||ctx.oBackingStorePixelRatio||ctx.backingStorePixelRatio||1);this.colorPickerCanvas.getContext("2d").setTransform(this.pixelRatio,0,0,this.pixelRatio,0,0);}this.colorPickerDiv.className="vis-color";this.opacityDiv=document.createElement("div");this.opacityDiv.className="vis-opacity";this.brightnessDiv=document.createElement("div");this.brightnessDiv.className="vis-brightness";this.arrowDiv=document.createElement("div");this.arrowDiv.className="vis-arrow";this.opacityRange=document.createElement("input");try{this.opacityRange.type="range";// Not supported on IE9
this.opacityRange.min="0";this.opacityRange.max="100";}catch(err){// TODO: Add some error handling.
}this.opacityRange.value="100";this.opacityRange.className="vis-range";this.brightnessRange=document.createElement("input");try{this.brightnessRange.type="range";// Not supported on IE9
this.brightnessRange.min="0";this.brightnessRange.max="100";}catch(err){// TODO: Add some error handling.
}this.brightnessRange.value="100";this.brightnessRange.className="vis-range";this.opacityDiv.appendChild(this.opacityRange);this.brightnessDiv.appendChild(this.brightnessRange);const me=this;this.opacityRange.onchange=function(){me._setOpacity(this.value);};this.opacityRange.oninput=function(){me._setOpacity(this.value);};this.brightnessRange.onchange=function(){me._setBrightness(this.value);};this.brightnessRange.oninput=function(){me._setBrightness(this.value);};this.brightnessLabel=document.createElement("div");this.brightnessLabel.className="vis-label vis-brightness";this.brightnessLabel.innerText="brightness:";this.opacityLabel=document.createElement("div");this.opacityLabel.className="vis-label vis-opacity";this.opacityLabel.innerText="opacity:";this.newColorDiv=document.createElement("div");this.newColorDiv.className="vis-new-color";this.newColorDiv.innerText="new";this.initialColorDiv=document.createElement("div");this.initialColorDiv.className="vis-initial-color";this.initialColorDiv.innerText="initial";this.cancelButton=document.createElement("div");this.cancelButton.className="vis-button vis-cancel";this.cancelButton.innerText="cancel";this.cancelButton.onclick=_bindInstanceProperty(_context7=this._hide).call(_context7,this,false);this.applyButton=document.createElement("div");this.applyButton.className="vis-button vis-apply";this.applyButton.innerText="apply";this.applyButton.onclick=_bindInstanceProperty(_context8=this._apply).call(_context8,this);this.saveButton=document.createElement("div");this.saveButton.className="vis-button vis-save";this.saveButton.innerText="save";this.saveButton.onclick=_bindInstanceProperty(_context9=this._save).call(_context9,this);this.loadButton=document.createElement("div");this.loadButton.className="vis-button vis-load";this.loadButton.innerText="load last";this.loadButton.onclick=_bindInstanceProperty(_context0=this._loadLast).call(_context0,this);this.frame.appendChild(this.colorPickerDiv);this.frame.appendChild(this.arrowDiv);this.frame.appendChild(this.brightnessLabel);this.frame.appendChild(this.brightnessDiv);this.frame.appendChild(this.opacityLabel);this.frame.appendChild(this.opacityDiv);this.frame.appendChild(this.newColorDiv);this.frame.appendChild(this.initialColorDiv);this.frame.appendChild(this.cancelButton);this.frame.appendChild(this.applyButton);this.frame.appendChild(this.saveButton);this.frame.appendChild(this.loadButton);}/**
   * bind hammer to the color picker
   * @private
   */_bindHammer(){this.drag={};this.pinch={};this.hammer=new Hammer$1(this.colorPickerCanvas);this.hammer.get("pinch").set({enable:true});this.hammer.on("hammer.input",event=>{if(event.isFirst){this._moveSelector(event);}});this.hammer.on("tap",event=>{this._moveSelector(event);});this.hammer.on("panstart",event=>{this._moveSelector(event);});this.hammer.on("panmove",event=>{this._moveSelector(event);});this.hammer.on("panend",event=>{this._moveSelector(event);});}/**
   * generate the hue circle. This is relatively heavy (200ms) and is done only once on the first time it is shown.
   * @private
   */_generateHueCircle(){if(this.generated===false){const ctx=this.colorPickerCanvas.getContext("2d");if(this.pixelRation===undefined){this.pixelRatio=(window.devicePixelRatio||1)/(ctx.webkitBackingStorePixelRatio||ctx.mozBackingStorePixelRatio||ctx.msBackingStorePixelRatio||ctx.oBackingStorePixelRatio||ctx.backingStorePixelRatio||1);}ctx.setTransform(this.pixelRatio,0,0,this.pixelRatio,0,0);// clear the canvas
const w=this.colorPickerCanvas.clientWidth;const h=this.colorPickerCanvas.clientHeight;ctx.clearRect(0,0,w,h);// draw hue circle
let x,y,hue,sat;this.centerCoordinates={x:w*0.5,y:h*0.5};this.r=0.49*w;const angleConvert=2*Math.PI/360;const hfac=1/360;const sfac=1/this.r;let rgb;for(hue=0;hue<360;hue++){for(sat=0;sat<this.r;sat++){x=this.centerCoordinates.x+sat*Math.sin(angleConvert*hue);y=this.centerCoordinates.y+sat*Math.cos(angleConvert*hue);rgb=HSVToRGB(hue*hfac,sat*sfac,1);ctx.fillStyle="rgb("+rgb.r+","+rgb.g+","+rgb.b+")";ctx.fillRect(x-0.5,y-0.5,2,2);}}ctx.strokeStyle="rgba(0,0,0,1)";ctx.circle(this.centerCoordinates.x,this.centerCoordinates.y,this.r);ctx.stroke();this.hueCircle=ctx.getImageData(0,0,w,h);}this.generated=true;}/**
   * move the selector. This is called by hammer functions.
   * @param {Event}  event   The event
   * @private
   */_moveSelector(event){const rect=this.colorPickerDiv.getBoundingClientRect();const left=event.center.x-rect.left;const top=event.center.y-rect.top;const centerY=0.5*this.colorPickerDiv.clientHeight;const centerX=0.5*this.colorPickerDiv.clientWidth;const x=left-centerX;const y=top-centerY;const angle=Math.atan2(x,y);const radius=0.98*Math.min(Math.sqrt(x*x+y*y),centerX);const newTop=Math.cos(angle)*radius+centerY;const newLeft=Math.sin(angle)*radius+centerX;this.colorPickerSelector.style.top=newTop-0.5*this.colorPickerSelector.clientHeight+"px";this.colorPickerSelector.style.left=newLeft-0.5*this.colorPickerSelector.clientWidth+"px";// set color
let h=angle/(2*Math.PI);h=h<0?h+1:h;const s=radius/this.r;const hsv=RGBToHSV(this.color.r,this.color.g,this.color.b);hsv.h=h;hsv.s=s;const rgba=HSVToRGB(hsv.h,hsv.s,hsv.v);rgba["a"]=this.color.a;this.color=rgba;// update previews
this.initialColorDiv.style.backgroundColor="rgba("+this.initialColor.r+","+this.initialColor.g+","+this.initialColor.b+","+this.initialColor.a+")";this.newColorDiv.style.backgroundColor="rgba("+this.color.r+","+this.color.g+","+this.color.b+","+this.color.a+")";}};/**
 * Wrap given text (last argument) in HTML elements (all preceding arguments).
 * @param {...any} rest - List of tag names followed by inner text.
 * @returns An element or a text node.
 */function wrapInTag(){for(var _len5=arguments.length,rest=new Array(_len5),_key5=0;_key5<_len5;_key5++){rest[_key5]=arguments[_key5];}if(rest.length<1){throw new TypeError("Invalid arguments.");}else if(rest.length===1){return document.createTextNode(rest[0]);}else {const element=document.createElement(rest[0]);element.appendChild(wrapInTag(..._sliceInstanceProperty(rest).call(rest,1)));return element;}}/**
 * The way this works is for all properties of this.possible options, you can supply the property name in any form to list the options.
 * Boolean options are recognised as Boolean
 * Number options should be written as array: [default value, min value, max value, stepsize]
 * Colors should be written as array: ['color', '#ffffff']
 * Strings with should be written as array: [option1, option2, option3, ..]
 *
 * The options are matched with their counterparts in each of the modules and the values used in the configuration are
 */let Configurator$1=class Configurator{/**
   * @param {object} parentModule        | the location where parentModule.setOptions() can be called
   * @param {object} defaultContainer    | the default container of the module
   * @param {object} configureOptions    | the fully configured and predefined options set found in allOptions.js
   * @param {number} pixelRatio          | canvas pixel ratio
   * @param {Function} hideOption        | custom logic to dynamically hide options
   */constructor(parentModule,defaultContainer,configureOptions){let pixelRatio=arguments.length>3&&arguments[3]!==undefined?arguments[3]:1;let hideOption=arguments.length>4&&arguments[4]!==undefined?arguments[4]:()=>false;this.parent=parentModule;this.changedOptions=[];this.container=defaultContainer;this.allowCreation=false;this.hideOption=hideOption;this.options={};this.initialized=false;this.popupCounter=0;this.defaultOptions={enabled:false,filter:true,container:undefined,showButton:true};_Object$assign(this.options,this.defaultOptions);this.configureOptions=configureOptions;this.moduleOptions={};this.domElements=[];this.popupDiv={};this.popupLimit=5;this.popupHistory={};this.colorPicker=new ColorPicker$1(pixelRatio);this.wrapper=undefined;}/**
   * refresh all options.
   * Because all modules parse their options by themselves, we just use their options. We copy them here.
   * @param {object} options
   */setOptions(options){if(options!==undefined){// reset the popup history because the indices may have been changed.
this.popupHistory={};this._removePopup();let enabled=true;if(typeof options==="string"){this.options.filter=options;}else if(_Array$isArray(options)){this.options.filter=options.join();}else if(typeof options==="object"){if(options==null){throw new TypeError("options cannot be null");}if(options.container!==undefined){this.options.container=options.container;}if(_filterInstanceProperty(options)!==undefined){this.options.filter=_filterInstanceProperty(options);}if(options.showButton!==undefined){this.options.showButton=options.showButton;}if(options.enabled!==undefined){enabled=options.enabled;}}else if(typeof options==="boolean"){this.options.filter=true;enabled=options;}else if(typeof options==="function"){this.options.filter=options;enabled=true;}if(_filterInstanceProperty(this.options)===false){enabled=false;}this.options.enabled=enabled;}this._clean();}/**
   *
   * @param {object} moduleOptions
   */setModuleOptions(moduleOptions){this.moduleOptions=moduleOptions;if(this.options.enabled===true){this._clean();if(this.options.container!==undefined){this.container=this.options.container;}this._create();}}/**
   * Create all DOM elements
   * @private
   */_create(){this._clean();this.changedOptions=[];const filter=_filterInstanceProperty(this.options);let counter=0;let show=false;for(const option in this.configureOptions){if(Object.prototype.hasOwnProperty.call(this.configureOptions,option)){this.allowCreation=false;show=false;if(typeof filter==="function"){show=filter(option,[]);show=show||this._handleObject(this.configureOptions[option],[option],true);}else if(filter===true||_indexOfInstanceProperty(filter).call(filter,option)!==-1){show=true;}if(show!==false){this.allowCreation=true;// linebreak between categories
if(counter>0){this._makeItem([]);}// a header for the category
this._makeHeader(option);// get the sub options
this._handleObject(this.configureOptions[option],[option]);}counter++;}}this._makeButton();this._push();//~ this.colorPicker.insertTo(this.container);
}/**
   * draw all DOM elements on the screen
   * @private
   */_push(){this.wrapper=document.createElement("div");this.wrapper.className="vis-configuration-wrapper";this.container.appendChild(this.wrapper);for(let i=0;i<this.domElements.length;i++){this.wrapper.appendChild(this.domElements[i]);}this._showPopupIfNeeded();}/**
   * delete all DOM elements
   * @private
   */_clean(){for(let i=0;i<this.domElements.length;i++){this.wrapper.removeChild(this.domElements[i]);}if(this.wrapper!==undefined){this.container.removeChild(this.wrapper);this.wrapper=undefined;}this.domElements=[];this._removePopup();}/**
   * get the value from the actualOptions if it exists
   * @param {Array} path    | where to look for the actual option
   * @returns {*}
   * @private
   */_getValue(path){let base=this.moduleOptions;for(let i=0;i<path.length;i++){if(base[path[i]]!==undefined){base=base[path[i]];}else {base=undefined;break;}}return base;}/**
   * all option elements are wrapped in an item
   * @param {Array} path    | where to look for the actual option
   * @param {Array.<Element>} domElements
   * @returns {number}
   * @private
   */_makeItem(path){if(this.allowCreation===true){const item=document.createElement("div");item.className="vis-configuration vis-config-item vis-config-s"+path.length;for(var _len6=arguments.length,domElements=new Array(_len6>1?_len6-1:0),_key6=1;_key6<_len6;_key6++){domElements[_key6-1]=arguments[_key6];}_forEachInstanceProperty(domElements).call(domElements,element=>{item.appendChild(element);});this.domElements.push(item);return this.domElements.length;}return 0;}/**
   * header for major subjects
   * @param {string} name
   * @private
   */_makeHeader(name){const div=document.createElement("div");div.className="vis-configuration vis-config-header";div.innerText=name;this._makeItem([],div);}/**
   * make a label, if it is an object label, it gets different styling.
   * @param {string} name
   * @param {Array} path    | where to look for the actual option
   * @param {string} objectLabel
   * @returns {HTMLElement}
   * @private
   */_makeLabel(name,path){let objectLabel=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;const div=document.createElement("div");div.className="vis-configuration vis-config-label vis-config-s"+path.length;if(objectLabel===true){while(div.firstChild){div.removeChild(div.firstChild);}div.appendChild(wrapInTag("i","b",name));}else {div.innerText=name+":";}return div;}/**
   * make a dropdown list for multiple possible string optoins
   * @param {Array.<number>} arr
   * @param {number} value
   * @param {Array} path    | where to look for the actual option
   * @private
   */_makeDropdown(arr,value,path){const select=document.createElement("select");select.className="vis-configuration vis-config-select";let selectedValue=0;if(value!==undefined){if(_indexOfInstanceProperty(arr).call(arr,value)!==-1){selectedValue=_indexOfInstanceProperty(arr).call(arr,value);}}for(let i=0;i<arr.length;i++){const option=document.createElement("option");option.value=arr[i];if(i===selectedValue){option.selected="selected";}option.innerText=arr[i];select.appendChild(option);}const me=this;select.onchange=function(){me._update(this.value,path);};const label=this._makeLabel(path[path.length-1],path);this._makeItem(path,label,select);}/**
   * make a range object for numeric options
   * @param {Array.<number>} arr
   * @param {number} value
   * @param {Array} path    | where to look for the actual option
   * @private
   */_makeRange(arr,value,path){const defaultValue=arr[0];const min=arr[1];const max=arr[2];const step=arr[3];const range=document.createElement("input");range.className="vis-configuration vis-config-range";try{range.type="range";// not supported on IE9
range.min=min;range.max=max;}catch(err){// TODO: Add some error handling.
}range.step=step;// set up the popup settings in case they are needed.
let popupString="";let popupValue=0;if(value!==undefined){const factor=1.2;if(value<0&&value*factor<min){range.min=Math.ceil(value*factor);popupValue=range.min;popupString="range increased";}else if(value/factor<min){range.min=Math.ceil(value/factor);popupValue=range.min;popupString="range increased";}if(value*factor>max&&max!==1){range.max=Math.ceil(value*factor);popupValue=range.max;popupString="range increased";}range.value=value;}else {range.value=defaultValue;}const input=document.createElement("input");input.className="vis-configuration vis-config-rangeinput";input.value=range.value;const me=this;range.onchange=function(){input.value=this.value;me._update(Number(this.value),path);};range.oninput=function(){input.value=this.value;};const label=this._makeLabel(path[path.length-1],path);const itemIndex=this._makeItem(path,label,range,input);// if a popup is needed AND it has not been shown for this value, show it.
if(popupString!==""&&this.popupHistory[itemIndex]!==popupValue){this.popupHistory[itemIndex]=popupValue;this._setupPopup(popupString,itemIndex);}}/**
   * make a button object
   * @private
   */_makeButton(){if(this.options.showButton===true){const generateButton=document.createElement("div");generateButton.className="vis-configuration vis-config-button";generateButton.innerText="generate options";generateButton.onclick=()=>{this._printOptions();};generateButton.onmouseover=()=>{generateButton.className="vis-configuration vis-config-button hover";};generateButton.onmouseout=()=>{generateButton.className="vis-configuration vis-config-button";};this.optionsContainer=document.createElement("div");this.optionsContainer.className="vis-configuration vis-config-option-container";this.domElements.push(this.optionsContainer);this.domElements.push(generateButton);}}/**
   * prepare the popup
   * @param {string} string
   * @param {number} index
   * @private
   */_setupPopup(string,index){if(this.initialized===true&&this.allowCreation===true&&this.popupCounter<this.popupLimit){const div=document.createElement("div");div.id="vis-configuration-popup";div.className="vis-configuration-popup";div.innerText=string;div.onclick=()=>{this._removePopup();};this.popupCounter+=1;this.popupDiv={html:div,index:index};}}/**
   * remove the popup from the dom
   * @private
   */_removePopup(){if(this.popupDiv.html!==undefined){this.popupDiv.html.parentNode.removeChild(this.popupDiv.html);clearTimeout(this.popupDiv.hideTimeout);clearTimeout(this.popupDiv.deleteTimeout);this.popupDiv={};}}/**
   * Show the popup if it is needed.
   * @private
   */_showPopupIfNeeded(){if(this.popupDiv.html!==undefined){const correspondingElement=this.domElements[this.popupDiv.index];const rect=correspondingElement.getBoundingClientRect();this.popupDiv.html.style.left=rect.left+"px";this.popupDiv.html.style.top=rect.top-30+"px";// 30 is the height;
document.body.appendChild(this.popupDiv.html);this.popupDiv.hideTimeout=_setTimeout(()=>{this.popupDiv.html.style.opacity=0;},1500);this.popupDiv.deleteTimeout=_setTimeout(()=>{this._removePopup();},1800);}}/**
   * make a checkbox for boolean options.
   * @param {number} defaultValue
   * @param {number} value
   * @param {Array} path    | where to look for the actual option
   * @private
   */_makeCheckbox(defaultValue,value,path){const checkbox=document.createElement("input");checkbox.type="checkbox";checkbox.className="vis-configuration vis-config-checkbox";checkbox.checked=defaultValue;if(value!==undefined){checkbox.checked=value;if(value!==defaultValue){if(typeof defaultValue==="object"){if(value!==defaultValue.enabled){this.changedOptions.push({path:path,value:value});}}else {this.changedOptions.push({path:path,value:value});}}}const me=this;checkbox.onchange=function(){me._update(this.checked,path);};const label=this._makeLabel(path[path.length-1],path);this._makeItem(path,label,checkbox);}/**
   * make a text input field for string options.
   * @param {number} defaultValue
   * @param {number} value
   * @param {Array} path    | where to look for the actual option
   * @private
   */_makeTextInput(defaultValue,value,path){const checkbox=document.createElement("input");checkbox.type="text";checkbox.className="vis-configuration vis-config-text";checkbox.value=value;if(value!==defaultValue){this.changedOptions.push({path:path,value:value});}const me=this;checkbox.onchange=function(){me._update(this.value,path);};const label=this._makeLabel(path[path.length-1],path);this._makeItem(path,label,checkbox);}/**
   * make a color field with a color picker for color fields
   * @param {Array.<number>} arr
   * @param {number} value
   * @param {Array} path    | where to look for the actual option
   * @private
   */_makeColorField(arr,value,path){const defaultColor=arr[1];const div=document.createElement("div");value=value===undefined?defaultColor:value;if(value!=="none"){div.className="vis-configuration vis-config-colorBlock";div.style.backgroundColor=value;}else {div.className="vis-configuration vis-config-colorBlock none";}value=value===undefined?defaultColor:value;div.onclick=()=>{this._showColorPicker(value,div,path);};const label=this._makeLabel(path[path.length-1],path);this._makeItem(path,label,div);}/**
   * used by the color buttons to call the color picker.
   * @param {number} value
   * @param {HTMLElement} div
   * @param {Array} path    | where to look for the actual option
   * @private
   */_showColorPicker(value,div,path){// clear the callback from this div
div.onclick=function(){};this.colorPicker.insertTo(div);this.colorPicker.show();this.colorPicker.setColor(value);this.colorPicker.setUpdateCallback(color=>{const colorString="rgba("+color.r+","+color.g+","+color.b+","+color.a+")";div.style.backgroundColor=colorString;this._update(colorString,path);});// on close of the colorpicker, restore the callback.
this.colorPicker.setCloseCallback(()=>{div.onclick=()=>{this._showColorPicker(value,div,path);};});}/**
   * parse an object and draw the correct items
   * @param {object} obj
   * @param {Array} [path]    | where to look for the actual option
   * @param {boolean} [checkOnly]
   * @returns {boolean}
   * @private
   */_handleObject(obj){let path=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[];let checkOnly=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;let show=false;const filter=_filterInstanceProperty(this.options);let visibleInSet=false;for(const subObj in obj){if(Object.prototype.hasOwnProperty.call(obj,subObj)){show=true;const item=obj[subObj];const newPath=copyAndExtendArray(path,subObj);if(typeof filter==="function"){show=filter(subObj,path);// if needed we must go deeper into the object.
if(show===false){if(!_Array$isArray(item)&&typeof item!=="string"&&typeof item!=="boolean"&&item instanceof Object){this.allowCreation=false;show=this._handleObject(item,newPath,true);this.allowCreation=checkOnly===false;}}}if(show!==false){visibleInSet=true;const value=this._getValue(newPath);if(_Array$isArray(item)){this._handleArray(item,value,newPath);}else if(typeof item==="string"){this._makeTextInput(item,value,newPath);}else if(typeof item==="boolean"){this._makeCheckbox(item,value,newPath);}else if(item instanceof Object){// skip the options that are not enabled
if(!this.hideOption(path,subObj,this.moduleOptions)){// initially collapse options with an disabled enabled option.
if(item.enabled!==undefined){const enabledPath=copyAndExtendArray(newPath,"enabled");const enabledValue=this._getValue(enabledPath);if(enabledValue===true){const label=this._makeLabel(subObj,newPath,true);this._makeItem(newPath,label);visibleInSet=this._handleObject(item,newPath)||visibleInSet;}else {this._makeCheckbox(item,enabledValue,newPath);}}else {const label=this._makeLabel(subObj,newPath,true);this._makeItem(newPath,label);visibleInSet=this._handleObject(item,newPath)||visibleInSet;}}}else {console.error("dont know how to handle",item,subObj,newPath);}}}}return visibleInSet;}/**
   * handle the array type of option
   * @param {Array.<number>} arr
   * @param {number} value
   * @param {Array} path    | where to look for the actual option
   * @private
   */_handleArray(arr,value,path){if(typeof arr[0]==="string"&&arr[0]==="color"){this._makeColorField(arr,value,path);if(arr[1]!==value){this.changedOptions.push({path:path,value:value});}}else if(typeof arr[0]==="string"){this._makeDropdown(arr,value,path);if(arr[0]!==value){this.changedOptions.push({path:path,value:value});}}else if(typeof arr[0]==="number"){this._makeRange(arr,value,path);if(arr[0]!==value){this.changedOptions.push({path:path,value:Number(value)});}}}/**
   * called to update the network with the new settings.
   * @param {number} value
   * @param {Array} path    | where to look for the actual option
   * @private
   */_update(value,path){const options=this._constructOptions(value,path);if(this.parent.body&&this.parent.body.emitter&&this.parent.body.emitter.emit){this.parent.body.emitter.emit("configChange",options);}this.initialized=true;this.parent.setOptions(options);}/**
   *
   * @param {string | boolean} value
   * @param {Array.<string>} path
   * @param {{}} optionsObj
   * @returns {{}}
   * @private
   */_constructOptions(value,path){let optionsObj=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};let pointer=optionsObj;// when dropdown boxes can be string or boolean, we typecast it into correct types
value=value==="true"?true:value;value=value==="false"?false:value;for(let i=0;i<path.length;i++){if(path[i]!=="global"){if(pointer[path[i]]===undefined){pointer[path[i]]={};}if(i!==path.length-1){pointer=pointer[path[i]];}else {pointer[path[i]]=value;}}}return optionsObj;}/**
   * @private
   */_printOptions(){const options=this.getOptions();while(this.optionsContainer.firstChild){this.optionsContainer.removeChild(this.optionsContainer.firstChild);}this.optionsContainer.appendChild(wrapInTag("pre","const options = "+_JSON$stringify(options,null,2)));}/**
   *
   * @returns {{}} options
   */getOptions(){const options={};for(let i=0;i<this.changedOptions.length;i++){this._constructOptions(this.changedOptions[i].value,this.changedOptions[i].path,options);}return options;}};/**
 * Popup is a class to create a popup window with some text
 */let Popup$1=class Popup{/**
   * @param {Element} container       The container object.
   * @param {string}  overflowMethod  How the popup should act to overflowing ('flip' or 'cap')
   */constructor(container,overflowMethod){this.container=container;this.overflowMethod=overflowMethod||"cap";this.x=0;this.y=0;this.padding=5;this.hidden=false;// create the frame
this.frame=document.createElement("div");this.frame.className="vis-tooltip";this.container.appendChild(this.frame);}/**
   * @param {number} x   Horizontal position of the popup window
   * @param {number} y   Vertical position of the popup window
   */setPosition(x,y){this.x=_parseInt(x);this.y=_parseInt(y);}/**
   * Set the content for the popup window. This can be HTML code or text.
   * @param {string | Element} content
   */setText(content){if(content instanceof Element){while(this.frame.firstChild){this.frame.removeChild(this.frame.firstChild);}this.frame.appendChild(content);}else {// String containing literal text, element has to be used for HTML due to
// XSS risks associated with innerHTML (i.e. prevent XSS by accident).
this.frame.innerText=content;}}/**
   * Show the popup window
   * @param {boolean} [doShow]    Show or hide the window
   */show(doShow){if(doShow===undefined){doShow=true;}if(doShow===true){const height=this.frame.clientHeight;const width=this.frame.clientWidth;const maxHeight=this.frame.parentNode.clientHeight;const maxWidth=this.frame.parentNode.clientWidth;let left=0,top=0;if(this.overflowMethod=="flip"){let isLeft=false,isTop=true;// Where around the position it's located
if(this.y-height<this.padding){isTop=false;}if(this.x+width>maxWidth-this.padding){isLeft=true;}if(isLeft){left=this.x-width;}else {left=this.x;}if(isTop){top=this.y-height;}else {top=this.y;}}else {top=this.y-height;if(top+height+this.padding>maxHeight){top=maxHeight-height-this.padding;}if(top<this.padding){top=this.padding;}left=this.x;if(left+width+this.padding>maxWidth){left=maxWidth-width-this.padding;}if(left<this.padding){left=this.padding;}}this.frame.style.left=left+"px";this.frame.style.top=top+"px";this.frame.style.visibility="visible";this.hidden=false;}else {this.hide();}}/**
   * Hide the popup window
   */hide(){this.hidden=true;this.frame.style.left="0";this.frame.style.top="0";this.frame.style.visibility="hidden";}/**
   * Remove the popup window
   */destroy(){this.frame.parentNode.removeChild(this.frame);// Remove element from DOM
}};let errorFound=false;let allOptions$1;const VALIDATOR_PRINT_STYLE$1="background: #FFeeee; color: #dd0000";/**
 *  Used to validate options.
 */let Validator$1=class Validator{/**
   * Main function to be called
   * @param {object} options
   * @param {object} referenceOptions
   * @param {object} subObject
   * @returns {boolean}
   * @static
   */static validate(options,referenceOptions,subObject){errorFound=false;allOptions$1=referenceOptions;let usedOptions=referenceOptions;if(subObject!==undefined){usedOptions=referenceOptions[subObject];}Validator.parse(options,usedOptions,[]);return errorFound;}/**
   * Will traverse an object recursively and check every value
   * @param {object} options
   * @param {object} referenceOptions
   * @param {Array} path    | where to look for the actual option
   * @static
   */static parse(options,referenceOptions,path){for(const option in options){if(Object.prototype.hasOwnProperty.call(options,option)){Validator.check(option,options,referenceOptions,path);}}}/**
   * Check every value. If the value is an object, call the parse function on that object.
   * @param {string} option
   * @param {object} options
   * @param {object} referenceOptions
   * @param {Array} path    | where to look for the actual option
   * @static
   */static check(option,options,referenceOptions,path){if(referenceOptions[option]===undefined&&referenceOptions.__any__===undefined){Validator.getSuggestion(option,referenceOptions,path);return;}let referenceOption=option;let is_object=true;if(referenceOptions[option]===undefined&&referenceOptions.__any__!==undefined){// NOTE: This only triggers if the __any__ is in the top level of the options object.
//       THAT'S A REALLY BAD PLACE TO ALLOW IT!!!!
// TODO: Examine if needed, remove if possible
// __any__ is a wildcard. Any value is accepted and will be further analysed by reference.
referenceOption="__any__";// if the any-subgroup is not a predefined object in the configurator,
// we do not look deeper into the object.
is_object=Validator.getType(options[option])==="object";}let refOptionObj=referenceOptions[referenceOption];if(is_object&&refOptionObj.__type__!==undefined){refOptionObj=refOptionObj.__type__;}Validator.checkFields(option,options,referenceOptions,referenceOption,refOptionObj,path);}/**
   *
   * @param {string}  option           | the option property
   * @param {object}  options          | The supplied options object
   * @param {object}  referenceOptions | The reference options containing all options and their allowed formats
   * @param {string}  referenceOption  | Usually this is the same as option, except when handling an __any__ tag.
   * @param {string}  refOptionObj     | This is the type object from the reference options
   * @param {Array}   path             | where in the object is the option
   * @static
   */static checkFields(option,options,referenceOptions,referenceOption,refOptionObj,path){const log=function(message){console.error("%c"+message+Validator.printLocation(path,option),VALIDATOR_PRINT_STYLE$1);};const optionType=Validator.getType(options[option]);const refOptionType=refOptionObj[optionType];if(refOptionType!==undefined){// if the type is correct, we check if it is supposed to be one of a few select values
if(Validator.getType(refOptionType)==="array"&&_indexOfInstanceProperty(refOptionType).call(refOptionType,options[option])===-1){log('Invalid option detected in "'+option+'".'+" Allowed values are:"+Validator.print(refOptionType)+' not "'+options[option]+'". ');errorFound=true;}else if(optionType==="object"&&referenceOption!=="__any__"){path=copyAndExtendArray(path,option);Validator.parse(options[option],referenceOptions[referenceOption],path);}}else if(refOptionObj["any"]===undefined){// type of the field is incorrect and the field cannot be any
log('Invalid type received for "'+option+'". Expected: '+Validator.print(_Object$keys(refOptionObj))+". Received ["+optionType+'] "'+options[option]+'"');errorFound=true;}}/**
   *
   * @param {object | boolean | number | string | Array.<number> | Date | Node | Moment | undefined | null} object
   * @returns {string}
   * @static
   */static getType(object){const type=typeof object;if(type==="object"){if(object===null){return "null";}if(object instanceof Boolean){return "boolean";}if(object instanceof Number){return "number";}if(object instanceof String){return "string";}if(_Array$isArray(object)){return "array";}if(object instanceof Date){return "date";}if(object.nodeType!==undefined){return "dom";}if(object._isAMomentObject===true){return "moment";}return "object";}else if(type==="number"){return "number";}else if(type==="boolean"){return "boolean";}else if(type==="string"){return "string";}else if(type===undefined){return "undefined";}return type;}/**
   * @param {string} option
   * @param {object} options
   * @param {Array.<string>} path
   * @static
   */static getSuggestion(option,options,path){const localSearch=Validator.findInOptions(option,options,path,false);const globalSearch=Validator.findInOptions(option,allOptions$1,[],true);const localSearchThreshold=8;const globalSearchThreshold=4;let msg;if(localSearch.indexMatch!==undefined){msg=" in "+Validator.printLocation(localSearch.path,option,"")+'Perhaps it was incomplete? Did you mean: "'+localSearch.indexMatch+'"?\n\n';}else if(globalSearch.distance<=globalSearchThreshold&&localSearch.distance>globalSearch.distance){msg=" in "+Validator.printLocation(localSearch.path,option,"")+"Perhaps it was misplaced? Matching option found at: "+Validator.printLocation(globalSearch.path,globalSearch.closestMatch,"");}else if(localSearch.distance<=localSearchThreshold){msg='. Did you mean "'+localSearch.closestMatch+'"?'+Validator.printLocation(localSearch.path,option);}else {msg=". Did you mean one of these: "+Validator.print(_Object$keys(options))+Validator.printLocation(path,option);}console.error('%cUnknown option detected: "'+option+'"'+msg,VALIDATOR_PRINT_STYLE$1);errorFound=true;}/**
   * traverse the options in search for a match.
   * @param {string} option
   * @param {object} options
   * @param {Array} path    | where to look for the actual option
   * @param {boolean} [recursive]
   * @returns {{closestMatch: string, path: Array, distance: number}}
   * @static
   */static findInOptions(option,options,path){let recursive=arguments.length>3&&arguments[3]!==undefined?arguments[3]:false;let min=1e9;let closestMatch="";let closestMatchPath=[];const lowerCaseOption=option.toLowerCase();let indexMatch=undefined;for(const op in options){let distance;if(options[op].__type__!==undefined&&recursive===true){const result=Validator.findInOptions(option,options[op],copyAndExtendArray(path,op));if(min>result.distance){closestMatch=result.closestMatch;closestMatchPath=result.path;min=result.distance;indexMatch=result.indexMatch;}}else {var _context1;if(_indexOfInstanceProperty(_context1=op.toLowerCase()).call(_context1,lowerCaseOption)!==-1){indexMatch=op;}distance=Validator.levenshteinDistance(option,op);if(min>distance){closestMatch=op;closestMatchPath=copyArray(path);min=distance;}}}return {closestMatch:closestMatch,path:closestMatchPath,distance:min,indexMatch:indexMatch};}/**
   * @param {Array.<string>} path
   * @param {object} option
   * @param {string} prefix
   * @returns {string}
   * @static
   */static printLocation(path,option){let prefix=arguments.length>2&&arguments[2]!==undefined?arguments[2]:"Problem value found at: \n";let str="\n\n"+prefix+"options = {\n";for(let i=0;i<path.length;i++){for(let j=0;j<i+1;j++){str+="  ";}str+=path[i]+": {\n";}for(let j=0;j<path.length+1;j++){str+="  ";}str+=option+"\n";for(let i=0;i<path.length+1;i++){for(let j=0;j<path.length-i;j++){str+="  ";}str+="}\n";}return str+"\n\n";}/**
   * @param {object} options
   * @returns {string}
   * @static
   */static print(options){return _JSON$stringify(options).replace(/(")|(\[)|(\])|(,"__type__")/g,"").replace(/(,)/g,", ");}/**
   *  Compute the edit distance between the two given strings
   *  http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#JavaScript
   *
   *  Copyright (c) 2011 Andrei Mackenzie
   *
   *  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
   *
   *  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
   *
   *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
   * @param {string} a
   * @param {string} b
   * @returns {Array.<Array.<number>>}}
   * @static
   */static levenshteinDistance(a,b){if(a.length===0)return b.length;if(b.length===0)return a.length;const matrix=[];// increment along the first column of each row
let i;for(i=0;i<=b.length;i++){matrix[i]=[i];}// increment each column in the first row
let j;for(j=0;j<=a.length;j++){matrix[0][j]=j;}// Fill in the rest of the matrix
for(i=1;i<=b.length;i++){for(j=1;j<=a.length;j++){if(b.charAt(i-1)==a.charAt(j-1)){matrix[i][j]=matrix[i-1][j-1];}else {matrix[i][j]=Math.min(matrix[i-1][j-1]+1,// substitution
Math.min(matrix[i][j-1]+1,// insertion
matrix[i-1][j]+1));// deletion
}}}return matrix[b.length][a.length];}};const Activator=Activator$1;const Configurator=Configurator$1;const Hammer=Hammer$1;const Popup=Popup$1;const VALIDATOR_PRINT_STYLE=VALIDATOR_PRINT_STYLE$1;const Validator=Validator$1;/* eslint-disable no-prototype-builtins *//* eslint-disable no-unused-vars *//* eslint-disable no-var *//**
 * Parse a text source containing data in DOT language into a JSON object.
 * The object contains two lists: one with nodes and one with edges.
 *
 * DOT language reference: http://www.graphviz.org/doc/info/lang.html
 *
 * DOT language attributes: http://graphviz.org/content/attrs
 * @param {string} data     Text containing a graph in DOT-notation
 * @returns {object} graph   An object containing two parameters:
 *                          {Object[]} nodes
 *                          {Object[]} edges
 *
 * -------------------------------------------
 * TODO
 * ====
 *
 * For label handling, this is an incomplete implementation. From docs (quote #3015):
 *
 * > the escape sequences "\n", "\l" and "\r" divide the label into lines, centered,
 * > left-justified, and right-justified, respectively.
 *
 * Source: http://www.graphviz.org/content/attrs#kescString
 *
 * > As another aid for readability, dot allows double-quoted strings to span multiple physical
 * > lines using the standard C convention of a backslash immediately preceding a newline
 * > character
 * > In addition, double-quoted strings can be concatenated using a '+' operator.
 * > As HTML strings can contain newline characters, which are used solely for formatting,
 * > the language does not allow escaped newlines or concatenation operators to be used
 * > within them.
 *
 * - Currently, only '\\n' is handled
 * - Note that text explicitly says 'labels'; the dot parser currently handles escape
 *   sequences in **all** strings.
 */function parseDOT(data){dot=data;return parseGraph();}// mapping of attributes from DOT (the keys) to vis.js (the values)
var NODE_ATTR_MAPPING={fontsize:"font.size",fontcolor:"font.color",labelfontcolor:"font.color",fontname:"font.face",color:["color.border","color.background"],fillcolor:"color.background",tooltip:"title",labeltooltip:"title"};var EDGE_ATTR_MAPPING=_Object$create(NODE_ATTR_MAPPING);EDGE_ATTR_MAPPING.color="color.color";EDGE_ATTR_MAPPING.style="dashes";// token types enumeration
var TOKENTYPE={NULL:0,DELIMITER:1,IDENTIFIER:2,UNKNOWN:3};// map with all delimiters
var DELIMITERS={"{":true,"}":true,"[":true,"]":true,";":true,"=":true,",":true,"->":true,"--":true};var dot="";// current dot file
var index=0;// current index in dot file
var c="";// current token character in expr
var token="";// current token
var tokenType=TOKENTYPE.NULL;// type of the token
/**
 * Get the first character from the dot file.
 * The character is stored into the char c. If the end of the dot file is
 * reached, the function puts an empty string in c.
 */function first(){index=0;c=dot.charAt(0);}/**
 * Get the next character from the dot file.
 * The character is stored into the char c. If the end of the dot file is
 * reached, the function puts an empty string in c.
 */function next(){index++;c=dot.charAt(index);}/**
 * Preview the next character from the dot file.
 * @returns {string} cNext
 */function nextPreview(){return dot.charAt(index+1);}/**
 * Test whether given character is alphabetic or numeric ( a-zA-Z_0-9.:# )
 * @param {string} c
 * @returns {boolean} isAlphaNumeric
 */function isAlphaNumeric(c){var charCode=c.charCodeAt(0);if(charCode<47){// #.
return charCode===35||charCode===46;}if(charCode<59){// 0-9 and :
return charCode>47;}if(charCode<91){// A-Z
return charCode>64;}if(charCode<96){// _
return charCode===95;}if(charCode<123){// a-z
return charCode>96;}return false;}/**
 * Merge all options of object b into object b
 * @param {object} a
 * @param {object} b
 * @returns {object} a
 */function merge(a,b){if(!a){a={};}if(b){for(var name in b){if(b.hasOwnProperty(name)){a[name]=b[name];}}}return a;}/**
 * Set a value in an object, where the provided parameter name can be a
 * path with nested parameters. For example:
 *
 * var obj = {a: 2};
 * setValue(obj, 'b.c', 3);     // obj = {a: 2, b: {c: 3}}
 * @param {object} obj
 * @param {string} path  A parameter name or dot-separated parameter path,
 *                      like "color.highlight.border".
 * @param {*} value
 */function setValue(obj,path,value){var keys=path.split(".");var o=obj;while(keys.length){var key=keys.shift();if(keys.length){// this isn't the end point
if(!o[key]){o[key]={};}o=o[key];}else {// this is the end point
o[key]=value;}}}/**
 * Add a node to a graph object. If there is already a node with
 * the same id, their attributes will be merged.
 * @param {object} graph
 * @param {object} node
 */function addNode(graph,node){var i,len;var current=null;// find root graph (in case of subgraph)
var graphs=[graph];// list with all graphs from current graph to root graph
var root=graph;while(root.parent){graphs.push(root.parent);root=root.parent;}// find existing node (at root level) by its id
if(root.nodes){for(i=0,len=root.nodes.length;i<len;i++){if(node.id===root.nodes[i].id){current=root.nodes[i];break;}}}if(!current){// this is a new node
current={id:node.id};if(graph.node){// clone default attributes
current.attr=merge(current.attr,graph.node);}}// add node to this (sub)graph and all its parent graphs
for(i=graphs.length-1;i>=0;i--){var _context;var g=graphs[i];if(!g.nodes){g.nodes=[];}if(_indexOfInstanceProperty(_context=g.nodes).call(_context,current)===-1){g.nodes.push(current);}}// merge attributes
if(node.attr){current.attr=merge(current.attr,node.attr);}}/**
 * Add an edge to a graph object
 * @param {object} graph
 * @param {object} edge
 */function addEdge(graph,edge){if(!graph.edges){graph.edges=[];}graph.edges.push(edge);if(graph.edge){var attr=merge({},graph.edge);// clone default attributes
edge.attr=merge(attr,edge.attr);// merge attributes
}}/**
 * Create an edge to a graph object
 * @param {object} graph
 * @param {string | number | object} from
 * @param {string | number | object} to
 * @param {string} type
 * @param {object | null} attr
 * @returns {object} edge
 */function createEdge(graph,from,to,type,attr){var edge={from:from,to:to,type:type};if(graph.edge){edge.attr=merge({},graph.edge);// clone default attributes
}edge.attr=merge(edge.attr||{},attr);// merge attributes
// Move arrows attribute from attr to edge temporally created in
// parseAttributeList().
if(attr!=null){if(attr.hasOwnProperty("arrows")&&attr["arrows"]!=null){edge["arrows"]={to:{enabled:true,type:attr.arrows.type}};attr["arrows"]=null;}}return edge;}/**
 * Get next token in the current dot file.
 * The token and token type are available as token and tokenType
 */function getToken(){tokenType=TOKENTYPE.NULL;token="";// skip over whitespaces
while(c===" "||c==="\t"||c==="\n"||c==="\r"){// space, tab, enter
next();}do{var isComment=false;// skip comment
if(c==="#"){// find the previous non-space character
var i=index-1;while(dot.charAt(i)===" "||dot.charAt(i)==="\t"){i--;}if(dot.charAt(i)==="\n"||dot.charAt(i)===""){// the # is at the start of a line, this is indeed a line comment
while(c!=""&&c!="\n"){next();}isComment=true;}}if(c==="/"&&nextPreview()==="/"){// skip line comment
while(c!=""&&c!="\n"){next();}isComment=true;}if(c==="/"&&nextPreview()==="*"){// skip block comment
while(c!=""){if(c==="*"&&nextPreview()==="/"){// end of block comment found. skip these last two characters
next();next();break;}else {next();}}isComment=true;}// skip over whitespaces
while(c===" "||c==="\t"||c==="\n"||c==="\r"){// space, tab, enter
next();}}while(isComment);// check for end of dot file
if(c===""){// token is still empty
tokenType=TOKENTYPE.DELIMITER;return;}// check for delimiters consisting of 2 characters
var c2=c+nextPreview();if(DELIMITERS[c2]){tokenType=TOKENTYPE.DELIMITER;token=c2;next();next();return;}// check for delimiters consisting of 1 character
if(DELIMITERS[c]){tokenType=TOKENTYPE.DELIMITER;token=c;next();return;}// check for an identifier (number or string)
// TODO: more precise parsing of numbers/strings (and the port separator ':')
if(isAlphaNumeric(c)||c==="-"){token+=c;next();while(isAlphaNumeric(c)){token+=c;next();}if(token==="false"){token=false;// convert to boolean
}else if(token==="true"){token=true;// convert to boolean
}else if(!isNaN(Number(token))){token=Number(token);// convert to number
}tokenType=TOKENTYPE.IDENTIFIER;return;}// check for a string enclosed by double quotes
if(c==='"'){next();while(c!=""&&(c!='"'||c==='"'&&nextPreview()==='"')){if(c==='"'){// skip the escape character
token+=c;next();}else if(c==="\\"&&nextPreview()==="n"){// Honor a newline escape sequence
token+="\n";next();}else {token+=c;}next();}if(c!='"'){throw newSyntaxError('End of string " expected');}next();tokenType=TOKENTYPE.IDENTIFIER;return;}// something unknown is found, wrong characters, a syntax error
tokenType=TOKENTYPE.UNKNOWN;while(c!=""){token+=c;next();}throw new SyntaxError('Syntax error in part "'+chop(token,30)+'"');}/**
 * Parse a graph.
 * @returns {object} graph
 */function parseGraph(){var graph={};first();getToken();// optional strict keyword
if(token==="strict"){graph.strict=true;getToken();}// graph or digraph keyword
if(token==="graph"||token==="digraph"){graph.type=token;getToken();}// optional graph id
if(tokenType===TOKENTYPE.IDENTIFIER){graph.id=token;getToken();}// open angle bracket
if(token!="{"){throw newSyntaxError("Angle bracket { expected");}getToken();// statements
parseStatements(graph);// close angle bracket
if(token!="}"){throw newSyntaxError("Angle bracket } expected");}getToken();// end of file
if(token!==""){throw newSyntaxError("End of file expected");}getToken();// remove temporary default options
delete graph.node;delete graph.edge;delete graph.graph;return graph;}/**
 * Parse a list with statements.
 * @param {object} graph
 */function parseStatements(graph){while(token!==""&&token!="}"){parseStatement(graph);if(token===";"){getToken();}}}/**
 * Parse a single statement. Can be a an attribute statement, node
 * statement, a series of node statements and edge statements, or a
 * parameter.
 * @param {object} graph
 */function parseStatement(graph){// parse subgraph
var subgraph=parseSubgraph(graph);if(subgraph){// edge statements
parseEdge(graph,subgraph);return;}// parse an attribute statement
var attr=parseAttributeStatement(graph);if(attr){return;}// parse node
if(tokenType!=TOKENTYPE.IDENTIFIER){throw newSyntaxError("Identifier expected");}var id=token;// id can be a string or a number
getToken();if(token==="="){// id statement
getToken();if(tokenType!=TOKENTYPE.IDENTIFIER){throw newSyntaxError("Identifier expected");}graph[id]=token;getToken();// TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
}else {parseNodeStatement(graph,id);}}/**
 * Parse a subgraph
 * @param {object} graph    parent graph object
 * @returns {object | null} subgraph
 */function parseSubgraph(graph){var subgraph=null;// optional subgraph keyword
if(token==="subgraph"){subgraph={};subgraph.type="subgraph";getToken();// optional graph id
if(tokenType===TOKENTYPE.IDENTIFIER){subgraph.id=token;getToken();}}// open angle bracket
if(token==="{"){getToken();if(!subgraph){subgraph={};}subgraph.parent=graph;subgraph.node=graph.node;subgraph.edge=graph.edge;subgraph.graph=graph.graph;// statements
parseStatements(subgraph);// close angle bracket
if(token!="}"){throw newSyntaxError("Angle bracket } expected");}getToken();// remove temporary default options
delete subgraph.node;delete subgraph.edge;delete subgraph.graph;delete subgraph.parent;// register at the parent graph
if(!graph.subgraphs){graph.subgraphs=[];}graph.subgraphs.push(subgraph);}return subgraph;}/**
 * parse an attribute statement like "node [shape=circle fontSize=16]".
 * Available keywords are 'node', 'edge', 'graph'.
 * The previous list with default attributes will be replaced
 * @param {object} graph
 * @returns {string | null} keyword Returns the name of the parsed attribute
 *                                  (node, edge, graph), or null if nothing
 *                                  is parsed.
 */function parseAttributeStatement(graph){// attribute statements
if(token==="node"){getToken();// node attributes
graph.node=parseAttributeList();return "node";}else if(token==="edge"){getToken();// edge attributes
graph.edge=parseAttributeList();return "edge";}else if(token==="graph"){getToken();// graph attributes
graph.graph=parseAttributeList();return "graph";}return null;}/**
 * parse a node statement
 * @param {object} graph
 * @param {string | number} id
 */function parseNodeStatement(graph,id){// node statement
var node={id:id};var attr=parseAttributeList();if(attr){node.attr=attr;}addNode(graph,node);// edge statements
parseEdge(graph,id);}/**
 * Parse an edge or a series of edges
 * @param {object} graph
 * @param {string | number} from        Id of the from node
 */function parseEdge(graph,from){while(token==="->"||token==="--"){var to;var type=token;getToken();var subgraph=parseSubgraph(graph);if(subgraph){to=subgraph;}else {if(tokenType!=TOKENTYPE.IDENTIFIER){throw newSyntaxError("Identifier or subgraph expected");}to=token;addNode(graph,{id:to});getToken();}// parse edge attributes
var attr=parseAttributeList();// create edge
var edge=createEdge(graph,from,to,type,attr);addEdge(graph,edge);from=to;}}/**
 * Parse a set with attributes,
 * for example [label="1.000", shape=solid]
 * @returns {object | null} attr
 */function parseAttributeList(){var i;var attr=null;// edge styles of dot and vis
var edgeStyles={dashed:true,solid:false,dotted:[1,5]};/**
   * Define arrow types.
   * vis currently supports types defined in 'arrowTypes'.
   * Details of arrow shapes are described in
   * http://www.graphviz.org/content/arrow-shapes
   */var arrowTypes={dot:"circle",box:"box",crow:"crow",curve:"curve",icurve:"inv_curve",normal:"triangle",inv:"inv_triangle",diamond:"diamond",tee:"bar",vee:"vee"};/**
   * 'attr_list' contains attributes for checking if some of them are affected
   * later. For instance, both of 'arrowhead' and 'dir' (edge style defined
   * in DOT) make changes to 'arrows' attribute in vis.
   */var attr_list=new Array();var attr_names=new Array();// used for checking the case.
// parse attributes
while(token==="["){getToken();attr={};while(token!==""&&token!="]"){if(tokenType!=TOKENTYPE.IDENTIFIER){throw newSyntaxError("Attribute name expected");}var name=token;getToken();if(token!="="){throw newSyntaxError("Equal sign = expected");}getToken();if(tokenType!=TOKENTYPE.IDENTIFIER){throw newSyntaxError("Attribute value expected");}var value=token;// convert from dot style to vis
if(name==="style"){value=edgeStyles[value];}var arrowType;if(name==="arrowhead"){arrowType=arrowTypes[value];name="arrows";value={to:{enabled:true,type:arrowType}};}if(name==="arrowtail"){arrowType=arrowTypes[value];name="arrows";value={from:{enabled:true,type:arrowType}};}attr_list.push({attr:attr,name:name,value:value});attr_names.push(name);getToken();if(token==","){getToken();}}if(token!="]"){throw newSyntaxError("Bracket ] expected");}getToken();}/**
   * As explained in [1], graphviz has limitations for combination of
   * arrow[head|tail] and dir. If attribute list includes 'dir',
   * following cases just be supported.
   *   1. both or none + arrowhead, arrowtail
   *   2. forward + arrowhead (arrowtail is not affedted)
   *   3. back + arrowtail (arrowhead is not affected)
   * [1] https://www.graphviz.org/doc/info/attrs.html#h:undir_note
   */if(_includesInstanceProperty(attr_names).call(attr_names,"dir")){var idx={};// get index of 'arrows' and 'dir'
idx.arrows={};for(i=0;i<attr_list.length;i++){if(attr_list[i].name==="arrows"){if(attr_list[i].value.to!=null){idx.arrows.to=i;}else if(attr_list[i].value.from!=null){idx.arrows.from=i;}else {throw newSyntaxError("Invalid value of arrows");}}else if(attr_list[i].name==="dir"){idx.dir=i;}}// first, add default arrow shape if it is not assigned to avoid error
var dir_type=attr_list[idx.dir].value;if(!_includesInstanceProperty(attr_names).call(attr_names,"arrows")){if(dir_type==="both"){attr_list.push({attr:attr_list[idx.dir].attr,name:"arrows",value:{to:{enabled:true}}});idx.arrows.to=attr_list.length-1;attr_list.push({attr:attr_list[idx.dir].attr,name:"arrows",value:{from:{enabled:true}}});idx.arrows.from=attr_list.length-1;}else if(dir_type==="forward"){attr_list.push({attr:attr_list[idx.dir].attr,name:"arrows",value:{to:{enabled:true}}});idx.arrows.to=attr_list.length-1;}else if(dir_type==="back"){attr_list.push({attr:attr_list[idx.dir].attr,name:"arrows",value:{from:{enabled:true}}});idx.arrows.from=attr_list.length-1;}else if(dir_type==="none"){attr_list.push({attr:attr_list[idx.dir].attr,name:"arrows",value:""});idx.arrows.to=attr_list.length-1;}else {throw newSyntaxError('Invalid dir type "'+dir_type+'"');}}var from_type;var to_type;// update 'arrows' attribute from 'dir'.
if(dir_type==="both"){// both of shapes of 'from' and 'to' are given
if(idx.arrows.to&&idx.arrows.from){to_type=attr_list[idx.arrows.to].value.to.type;from_type=attr_list[idx.arrows.from].value.from.type;attr_list[idx.arrows.to]={attr:attr_list[idx.arrows.to].attr,name:attr_list[idx.arrows.to].name,value:{to:{enabled:true,type:to_type},from:{enabled:true,type:from_type}}};_spliceInstanceProperty(attr_list).call(attr_list,idx.arrows.from,1);// shape of 'to' is assigned and use default to 'from'
}else if(idx.arrows.to){to_type=attr_list[idx.arrows.to].value.to.type;from_type="arrow";attr_list[idx.arrows.to]={attr:attr_list[idx.arrows.to].attr,name:attr_list[idx.arrows.to].name,value:{to:{enabled:true,type:to_type},from:{enabled:true,type:from_type}}};// only shape of 'from' is assigned and use default for 'to'
}else if(idx.arrows.from){to_type="arrow";from_type=attr_list[idx.arrows.from].value.from.type;attr_list[idx.arrows.from]={attr:attr_list[idx.arrows.from].attr,name:attr_list[idx.arrows.from].name,value:{to:{enabled:true,type:to_type},from:{enabled:true,type:from_type}}};}}else if(dir_type==="back"){// given both of shapes, but use only 'from'
if(idx.arrows.to&&idx.arrows.from){to_type="";from_type=attr_list[idx.arrows.from].value.from.type;attr_list[idx.arrows.from]={attr:attr_list[idx.arrows.from].attr,name:attr_list[idx.arrows.from].name,value:{to:{enabled:true,type:to_type},from:{enabled:true,type:from_type}}};// given shape of 'to', but does not use it
}else if(idx.arrows.to){to_type="";from_type="arrow";idx.arrows.from=idx.arrows.to;attr_list[idx.arrows.from]={attr:attr_list[idx.arrows.from].attr,name:attr_list[idx.arrows.from].name,value:{to:{enabled:true,type:to_type},from:{enabled:true,type:from_type}}};// assign given 'from' shape
}else if(idx.arrows.from){to_type="";from_type=attr_list[idx.arrows.from].value.from.type;attr_list[idx.arrows.to]={attr:attr_list[idx.arrows.from].attr,name:attr_list[idx.arrows.from].name,value:{to:{enabled:true,type:to_type},from:{enabled:true,type:from_type}}};}attr_list[idx.arrows.from]={attr:attr_list[idx.arrows.from].attr,name:attr_list[idx.arrows.from].name,value:{from:{enabled:true,type:attr_list[idx.arrows.from].value.from.type}}};}else if(dir_type==="none"){var idx_arrow;if(idx.arrows.to){idx_arrow=idx.arrows.to;}else {idx_arrow=idx.arrows.from;}attr_list[idx_arrow]={attr:attr_list[idx_arrow].attr,name:attr_list[idx_arrow].name,value:""};}else if(dir_type==="forward"){// given both of shapes, but use only 'to'
if(idx.arrows.to&&idx.arrows.from){to_type=attr_list[idx.arrows.to].value.to.type;from_type="";attr_list[idx.arrows.to]={attr:attr_list[idx.arrows.to].attr,name:attr_list[idx.arrows.to].name,value:{to:{enabled:true,type:to_type},from:{enabled:true,type:from_type}}};// assign given 'to' shape
}else if(idx.arrows.to){to_type=attr_list[idx.arrows.to].value.to.type;from_type="";attr_list[idx.arrows.to]={attr:attr_list[idx.arrows.to].attr,name:attr_list[idx.arrows.to].name,value:{to:{enabled:true,type:to_type},from:{enabled:true,type:from_type}}};// given shape of 'from', but does not use it
}else if(idx.arrows.from){to_type="arrow";from_type="";idx.arrows.to=idx.arrows.from;attr_list[idx.arrows.to]={attr:attr_list[idx.arrows.to].attr,name:attr_list[idx.arrows.to].name,value:{to:{enabled:true,type:to_type},from:{enabled:true,type:from_type}}};}attr_list[idx.arrows.to]={attr:attr_list[idx.arrows.to].attr,name:attr_list[idx.arrows.to].name,value:{to:{enabled:true,type:attr_list[idx.arrows.to].value.to.type}}};}else {throw newSyntaxError('Invalid dir type "'+dir_type+'"');}// remove 'dir' attribute no need anymore
_spliceInstanceProperty(attr_list).call(attr_list,idx.dir,1);}// parse 'penwidth'
var nof_attr_list;if(_includesInstanceProperty(attr_names).call(attr_names,"penwidth")){var tmp_attr_list=[];nof_attr_list=attr_list.length;for(i=0;i<nof_attr_list;i++){// exclude 'width' from attr_list if 'penwidth' exists
if(attr_list[i].name!=="width"){if(attr_list[i].name==="penwidth"){attr_list[i].name="width";}tmp_attr_list.push(attr_list[i]);}}attr_list=tmp_attr_list;}nof_attr_list=attr_list.length;for(i=0;i<nof_attr_list;i++){setValue(attr_list[i].attr,attr_list[i].name,attr_list[i].value);}return attr;}/**
 * Create a syntax error with extra information on current token and index.
 * @param {string} message
 * @returns {SyntaxError} err
 */function newSyntaxError(message){return new SyntaxError(message+', got "'+chop(token,30)+'" (char '+index+")");}/**
 * Chop off text after a maximum length
 * @param {string} text
 * @param {number} maxLength
 * @returns {string}
 */function chop(text,maxLength){return text.length<=maxLength?text:text.substr(0,27)+"...";}/**
 * Execute a function fn for each pair of elements in two arrays
 * @param {Array | *} array1
 * @param {Array | *} array2
 * @param {Function} fn
 */function forEach2(array1,array2,fn){if(_Array$isArray(array1)){_forEachInstanceProperty(array1).call(array1,function(elem1){if(_Array$isArray(array2)){_forEachInstanceProperty(array2).call(array2,function(elem2){fn(elem1,elem2);});}else {fn(elem1,array2);}});}else {if(_Array$isArray(array2)){_forEachInstanceProperty(array2).call(array2,function(elem2){fn(array1,elem2);});}else {fn(array1,array2);}}}/**
 * Set a nested property on an object
 * When nested objects are missing, they will be created.
 * For example setProp({}, 'font.color', 'red') will return {font: {color: 'red'}}
 * @param {object} object
 * @param {string} path   A dot separated string like 'font.color'
 * @param {*} value       Value for the property
 * @returns {object} Returns the original object, allows for chaining.
 */function setProp(object,path,value){var names=path.split(".");var prop=names.pop();// traverse over the nested objects
var obj=object;for(var i=0;i<names.length;i++){var name=names[i];if(!(name in obj)){obj[name]={};}obj=obj[name];}// set the property value
obj[prop]=value;return object;}/**
 * Convert an object with DOT attributes to their vis.js equivalents.
 * @param {object} attr     Object with DOT attributes
 * @param {object} mapping
 * @returns {object}         Returns an object with vis.js attributes
 */function convertAttr(attr,mapping){var converted={};for(var prop in attr){if(attr.hasOwnProperty(prop)){var visProp=mapping[prop];if(_Array$isArray(visProp)){_forEachInstanceProperty(visProp).call(visProp,function(visPropI){setProp(converted,visPropI,attr[prop]);});}else if(typeof visProp==="string"){setProp(converted,visProp,attr[prop]);}else {setProp(converted,prop,attr[prop]);}}}return converted;}/**
 * Convert a string containing a graph in DOT language into a map containing
 * with nodes and edges in the format of graph.
 * @param {string} data         Text containing a graph in DOT-notation
 * @returns {object} graphData
 */function DOTToGraph(data){// parse the DOT file
var dotData=parseDOT(data);var graphData={nodes:[],edges:[],options:{}};// copy the nodes
if(dotData.nodes){var _context2;_forEachInstanceProperty(_context2=dotData.nodes).call(_context2,function(dotNode){var graphNode={id:dotNode.id,label:String(dotNode.label||dotNode.id)};merge(graphNode,convertAttr(dotNode.attr,NODE_ATTR_MAPPING));if(graphNode.image){graphNode.shape="image";}graphData.nodes.push(graphNode);});}// copy the edges
if(dotData.edges){var _context3;/**
     * Convert an edge in DOT format to an edge with VisGraph format
     * @param {object} dotEdge
     * @returns {object} graphEdge
     */var convertEdge=function(dotEdge){var graphEdge={from:dotEdge.from,to:dotEdge.to};merge(graphEdge,convertAttr(dotEdge.attr,EDGE_ATTR_MAPPING));// Add arrows attribute to default styled arrow.
// The reason why default style is not added in parseAttributeList() is
// because only default is cleared before here.
if(graphEdge.arrows==null&&dotEdge.type==="->"){graphEdge.arrows="to";}return graphEdge;};_forEachInstanceProperty(_context3=dotData.edges).call(_context3,function(dotEdge){var from,to;if(dotEdge.from instanceof Object){from=dotEdge.from.nodes;}else {from={id:dotEdge.from};}if(dotEdge.to instanceof Object){to=dotEdge.to.nodes;}else {to={id:dotEdge.to};}if(dotEdge.from instanceof Object&&dotEdge.from.edges){var _context4;_forEachInstanceProperty(_context4=dotEdge.from.edges).call(_context4,function(subEdge){var graphEdge=convertEdge(subEdge);graphData.edges.push(graphEdge);});}forEach2(from,to,function(from,to){var subEdge=createEdge(graphData,from.id,to.id,dotEdge.type,dotEdge.attr);var graphEdge=convertEdge(subEdge);graphData.edges.push(graphEdge);});if(dotEdge.to instanceof Object&&dotEdge.to.edges){var _context5;_forEachInstanceProperty(_context5=dotEdge.to.edges).call(_context5,function(subEdge){var graphEdge=convertEdge(subEdge);graphData.edges.push(graphEdge);});}});}// copy the options
if(dotData.attr){graphData.options=dotData.attr;}return graphData;}/**
 * Convert Gephi to Vis.
 * @param gephiJSON - The parsed JSON data in Gephi format.
 * @param optionsObj - Additional options.
 * @param optionsObj.fixed - If true, nodes will be fixed at the positions defined in Gephi.
 * @param optionsObj.inheritColor - If true, colors from Gephi will be ignored.
 * @param optionsObj.parseColor - If true, the single Gephi color will be parsed into different shades for border, highlight, and hover.
 * @returns The converted data ready to be used in Vis.
 */function parseGephi(gephiJSON){var _context;let{fixed:isNodePositionFixed=false,inheritColor:isEdgeColorInherited=false,parseColor:isNodeColorParsed=false}=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};const gEdges=gephiJSON.edges;const vEdges=_mapInstanceProperty(gEdges).call(gEdges,gEdge=>{const vEdge={from:gEdge.source,id:gEdge.id,to:gEdge.target};if(gEdge.attributes!=null){vEdge.attributes=gEdge.attributes;}if(gEdge.label!=null){vEdge.label=gEdge.label;}if(gEdge.attributes!=null&&gEdge.attributes.title!=null){vEdge.title=gEdge.attributes.title;}if(gEdge.type==="Directed"){vEdge.arrows="to";}// edge['value'] = gEdge.attributes != null ? gEdge.attributes.Weight : undefined;
// edge['width'] = edge['value'] != null ? undefined : edgegEdge.size;
if(gEdge.color&&isEdgeColorInherited===false){vEdge.color=gEdge.color;}return vEdge;});const vNodes=_mapInstanceProperty(_context=gephiJSON.nodes).call(_context,gNode=>{const vNode={id:gNode.id,fixed:isNodePositionFixed&&gNode.x!=null&&gNode.y!=null};if(gNode.attributes!=null){vNode.attributes=gNode.attributes;}if(gNode.label!=null){vNode.label=gNode.label;}if(gNode.size!=null){vNode.size=gNode.size;}if(gNode.attributes!=null&&gNode.attributes.title!=null){vNode.title=gNode.attributes.title;}if(gNode.title!=null){vNode.title=gNode.title;}if(gNode.x!=null){vNode.x=gNode.x;}if(gNode.y!=null){vNode.y=gNode.y;}if(gNode.color!=null){if(isNodeColorParsed===true){vNode.color=gNode.color;}else {vNode.color={background:gNode.color,border:gNode.color,highlight:{background:gNode.color,border:gNode.color},hover:{background:gNode.color,border:gNode.color}};}}return vNode;});return {nodes:vNodes,edges:vEdges};}const en={addDescription:"Click in an empty space to place a new node.",addEdge:"Add Edge",addNode:"Add Node",back:"Back",close:"Close",createEdgeError:"Cannot link edges to a cluster.",del:"Delete selected",deleteClusterError:"Clusters cannot be deleted.",edgeDescription:"Click on a node and drag the edge to another node to connect them.",edit:"Edit",editClusterError:"Clusters cannot be edited.",editEdge:"Edit Edge",editEdgeDescription:"Click on the control points and drag them to a node to connect to it.",editNode:"Edit Node"};// German
const de={addDescription:"Klicke auf eine freie Stelle, um einen neuen Knoten zu plazieren.",addEdge:"Kante hinzuf\u00fcgen",addNode:"Knoten hinzuf\u00fcgen",back:"Zur\u00fcck",close:"Schließen",createEdgeError:"Es ist nicht m\u00f6glich, Kanten mit Clustern zu verbinden.",del:"L\u00f6sche Auswahl",deleteClusterError:"Cluster k\u00f6nnen nicht gel\u00f6scht werden.",edgeDescription:"Klicke auf einen Knoten und ziehe die Kante zu einem anderen Knoten, um diese zu verbinden.",edit:"Editieren",editClusterError:"Cluster k\u00f6nnen nicht editiert werden.",editEdge:"Kante editieren",editEdgeDescription:"Klicke auf die Verbindungspunkte und ziehe diese auf einen Knoten, um sie zu verbinden.",editNode:"Knoten editieren"};// Spanish
const es={addDescription:"Haga clic en un lugar vac\u00edo para colocar un nuevo nodo.",addEdge:"A\u00f1adir arista",addNode:"A\u00f1adir nodo",back:"Atr\u00e1s",close:"Cerrar",createEdgeError:"No se puede conectar una arista a un grupo.",del:"Eliminar selecci\u00f3n",deleteClusterError:"No es posible eliminar grupos.",edgeDescription:"Haga clic en un nodo y arrastre la arista hacia otro nodo para conectarlos.",edit:"Editar",editClusterError:"No es posible editar grupos.",editEdge:"Editar arista",editEdgeDescription:"Haga clic en un punto de control y arrastrelo a un nodo para conectarlo.",editNode:"Editar nodo"};//Italiano
const it={addDescription:"Clicca per aggiungere un nuovo nodo",addEdge:"Aggiungi un vertice",addNode:"Aggiungi un nodo",back:"Indietro",close:"Chiudere",createEdgeError:"Non si possono collegare vertici ad un cluster",del:"Cancella la selezione",deleteClusterError:"I cluster non possono essere cancellati",edgeDescription:"Clicca su un nodo e trascinalo ad un altro nodo per connetterli.",edit:"Modifica",editClusterError:"I clusters non possono essere modificati.",editEdge:"Modifica il vertice",editEdgeDescription:"Clicca sui Punti di controllo e trascinali ad un nodo per connetterli.",editNode:"Modifica il nodo"};// Dutch
const nl={addDescription:"Klik op een leeg gebied om een nieuwe node te maken.",addEdge:"Link toevoegen",addNode:"Node toevoegen",back:"Terug",close:"Sluiten",createEdgeError:"Kan geen link maken naar een cluster.",del:"Selectie verwijderen",deleteClusterError:"Clusters kunnen niet worden verwijderd.",edgeDescription:"Klik op een node en sleep de link naar een andere node om ze te verbinden.",edit:"Wijzigen",editClusterError:"Clusters kunnen niet worden aangepast.",editEdge:"Link wijzigen",editEdgeDescription:"Klik op de verbindingspunten en sleep ze naar een node om daarmee te verbinden.",editNode:"Node wijzigen"};// Portuguese Brazil
const pt={addDescription:"Clique em um espaço em branco para adicionar um novo nó",addEdge:"Adicionar aresta",addNode:"Adicionar nó",back:"Voltar",close:"Fechar",createEdgeError:"Não foi possível linkar arestas a um cluster.",del:"Remover selecionado",deleteClusterError:"Clusters não puderam ser removidos.",edgeDescription:"Clique em um nó e arraste a aresta até outro nó para conectá-los",edit:"Editar",editClusterError:"Clusters não puderam ser editados.",editEdge:"Editar aresta",editEdgeDescription:"Clique nos pontos de controle e os arraste para um nó para conectá-los",editNode:"Editar nó"};// Russian
const ru={addDescription:"Кликните в свободное место, чтобы добавить новый узел.",addEdge:"Добавить ребро",addNode:"Добавить узел",back:"Назад",close:"Закрывать",createEdgeError:"Невозможно соединить ребра в кластер.",del:"Удалить выбранное",deleteClusterError:"Кластеры не могут быть удалены",edgeDescription:"Кликните на узел и протяните ребро к другому узлу, чтобы соединить их.",edit:"Редактировать",editClusterError:"Кластеры недоступны для редактирования.",editEdge:"Редактировать ребро",editEdgeDescription:"Кликните на контрольные точки и перетащите их в узел, чтобы подключиться к нему.",editNode:"Редактировать узел"};// Chinese
const cn={addDescription:"单击空白处放置新节点。",addEdge:"添加连接线",addNode:"添加节点",back:"返回",close:"關閉",createEdgeError:"无法将连接线连接到群集。",del:"删除选定",deleteClusterError:"无法删除群集。",edgeDescription:"单击某个节点并将该连接线拖动到另一个节点以连接它们。",edit:"编辑",editClusterError:"无法编辑群集。",editEdge:"编辑连接线",editEdgeDescription:"单击控制节点并将它们拖到节点上连接。",editNode:"编辑节点"};// Ukrainian
const uk={addDescription:"Kлікніть на вільне місце, щоб додати новий вузол.",addEdge:"Додати край",addNode:"Додати вузол",back:"Назад",close:"Закрити",createEdgeError:"Не можливо об'єднати краї в групу.",del:"Видалити обране",deleteClusterError:"Групи не можуть бути видалені.",edgeDescription:"Клікніть на вузол і перетягніть край до іншого вузла, щоб їх з'єднати.",edit:"Редагувати",editClusterError:"Групи недоступні для редагування.",editEdge:"Редагувати край",editEdgeDescription:"Клікніть на контрольні точки і перетягніть їх у вузол, щоб підключитися до нього.",editNode:"Редагувати вузол"};// French
const fr={addDescription:"Cliquez dans un endroit vide pour placer un nœud.",addEdge:"Ajouter un lien",addNode:"Ajouter un nœud",back:"Retour",close:"Fermer",createEdgeError:"Impossible de créer un lien vers un cluster.",del:"Effacer la sélection",deleteClusterError:"Les clusters ne peuvent pas être effacés.",edgeDescription:"Cliquez sur un nœud et glissez le lien vers un autre nœud pour les connecter.",edit:"Éditer",editClusterError:"Les clusters ne peuvent pas être édités.",editEdge:"Éditer le lien",editEdgeDescription:"Cliquez sur les points de contrôle et glissez-les pour connecter un nœud.",editNode:"Éditer le nœud"};// Czech
const cs={addDescription:"Kluknutím do prázdného prostoru můžete přidat nový vrchol.",addEdge:"Přidat hranu",addNode:"Přidat vrchol",back:"Zpět",close:"Zavřít",createEdgeError:"Nelze připojit hranu ke shluku.",del:"Smazat výběr",deleteClusterError:"Nelze mazat shluky.",edgeDescription:"Přetažením z jednoho vrcholu do druhého můžete spojit tyto vrcholy novou hranou.",edit:"Upravit",editClusterError:"Nelze upravovat shluky.",editEdge:"Upravit hranu",editEdgeDescription:"Přetažením kontrolního vrcholu hrany ji můžete připojit k jinému vrcholu.",editNode:"Upravit vrchol"};var locales=/*#__PURE__*/Object.freeze({__proto__:null,cn:cn,cs:cs,de:de,en:en,es:es,fr:fr,it:it,nl:nl,pt:pt,ru:ru,uk:uk});/**
 * Normalizes language code into the format used internally.
 * @param locales - All the available locales.
 * @param rawCode - The original code as supplied by the user.
 * @returns Language code in the format language-COUNTRY or language, eventually
 * fallbacks to en.
 */function normalizeLanguageCode(locales,rawCode){try{const[rawLanguage,rawCountry]=rawCode.split(/[-_ /]/,2);const language=rawLanguage!=null?rawLanguage.toLowerCase():null;const country=rawCountry!=null?rawCountry.toUpperCase():null;if(language&&country){const code=language+"-"+country;if(Object.prototype.hasOwnProperty.call(locales,code)){return code;}else {var _context;console.warn(_concatInstanceProperty(_context="Unknown variant ".concat(country," of language ")).call(_context,language,"."));}}if(language){const code=language;if(Object.prototype.hasOwnProperty.call(locales,code)){return code;}else {console.warn("Unknown language ".concat(language));}}console.warn("Unknown locale ".concat(rawCode,", falling back to English."));return "en";}catch(error){console.error(error);console.warn("Unexpected error while normalizing locale ".concat(rawCode,", falling back to English."));return "en";}}/**
 * Associates a canvas to a given image, containing a number of renderings
 * of the image at various sizes.
 *
 * This technique is known as 'mipmapping'.
 *
 * NOTE: Images can also be of type 'data:svg+xml`. This code also works
 * for svg, but the mipmapping may not be necessary.
 * @param {Image} image
 */class CachedImage{/**
   * @ignore
   */constructor(){this.NUM_ITERATIONS=4;// Number of items in the coordinates array
this.image=new Image();this.canvas=document.createElement("canvas");}/**
   * Called when the image has been successfully loaded.
   */init(){if(this.initialized())return;this.src=this.image.src;// For same interface with Image
const w=this.image.width;const h=this.image.height;// Ease external access
this.width=w;this.height=h;const h2=Math.floor(h/2);const h4=Math.floor(h/4);const h8=Math.floor(h/8);const h16=Math.floor(h/16);const w2=Math.floor(w/2);const w4=Math.floor(w/4);const w8=Math.floor(w/8);const w16=Math.floor(w/16);// Make canvas as small as possible
this.canvas.width=3*w4;this.canvas.height=h2;// Coordinates and sizes of images contained in the canvas
// Values per row:  [top x, left y, width, height]
this.coordinates=[[0,0,w2,h2],[w2,0,w4,h4],[w2,h4,w8,h8],[5*w8,h4,w16,h16]];this._fillMipMap();}/**
   * @returns {boolean} true if init() has been called, false otherwise.
   */initialized(){return this.coordinates!==undefined;}/**
   * Redraw main image in various sizes to the context.
   *
   * The rationale behind this is to reduce artefacts due to interpolation
   * at differing zoom levels.
   *
   * Source: http://stackoverflow.com/q/18761404/1223531
   *
   * This methods takes the resizing out of the drawing loop, in order to
   * reduce performance overhead.
   *
   * TODO: The code assumes that a 2D context can always be gotten. This is
   * not necessarily true! OTOH, if not true then usage of this class
   * is senseless.
   * @private
   */_fillMipMap(){const ctx=this.canvas.getContext("2d");// First zoom-level comes from the image
const to=this.coordinates[0];ctx.drawImage(this.image,to[0],to[1],to[2],to[3]);// The rest are copy actions internal to the canvas/context
for(let iterations=1;iterations<this.NUM_ITERATIONS;iterations++){const from=this.coordinates[iterations-1];const to=this.coordinates[iterations];ctx.drawImage(this.canvas,from[0],from[1],from[2],from[3],to[0],to[1],to[2],to[3]);}}/**
   * Draw the image, using the mipmap if necessary.
   *
   * MipMap is only used if param factor > 2; otherwise, original bitmap
   * is resized. This is also used to skip mipmap usage, e.g. by setting factor = 1
   *
   * Credits to 'Alex de Mulder' for original implementation.
   * @param {CanvasRenderingContext2D} ctx  context on which to draw zoomed image
   * @param {Float} factor scale factor at which to draw
   * @param {number} left
   * @param {number} top
   * @param {number} width
   * @param {number} height
   */drawImageAtPosition(ctx,factor,left,top,width,height){if(!this.initialized())return;//can't draw image yet not intialized
if(factor>2){// Determine which zoomed image to use
factor*=0.5;let iterations=0;while(factor>2&&iterations<this.NUM_ITERATIONS){factor*=0.5;iterations+=1;}if(iterations>=this.NUM_ITERATIONS){iterations=this.NUM_ITERATIONS-1;}//console.log("iterations: " + iterations);
const from=this.coordinates[iterations];ctx.drawImage(this.canvas,from[0],from[1],from[2],from[3],left,top,width,height);}else {// Draw image directly
ctx.drawImage(this.image,left,top,width,height);}}}/**
 * This callback is a callback that accepts an Image.
 * @callback ImageCallback
 * @param {Image} image
 *//**
 * This class loads images and keeps them stored.
 * @param {ImageCallback} callback
 */class Images{/**
   * @param {ImageCallback} callback
   */constructor(callback){this.images={};this.imageBroken={};this.callback=callback;}/**
   * @param {string} url                      The original Url that failed to load, if the broken image is successfully loaded it will be added to the cache using this Url as the key so that subsequent requests for this Url will return the broken image
   * @param {string} brokenUrl                Url the broken image to try and load
   * @param {Image} imageToLoadBrokenUrlOn   The image object
   */_tryloadBrokenUrl(url,brokenUrl,imageToLoadBrokenUrlOn){//If these parameters aren't specified then exit the function because nothing constructive can be done
if(url===undefined||imageToLoadBrokenUrlOn===undefined)return;if(brokenUrl===undefined){console.warn("No broken url image defined");return;}//Clear the old subscription to the error event and put a new in place that only handle errors in loading the brokenImageUrl
imageToLoadBrokenUrlOn.image.onerror=()=>{console.error("Could not load brokenImage:",brokenUrl);// cache item will contain empty image, this should be OK for default
};//Set the source of the image to the brokenUrl, this is actually what kicks off the loading of the broken image
imageToLoadBrokenUrlOn.image.src=brokenUrl;}/**
   *
   * @param {vis.Image} imageToRedrawWith
   * @private
   */_redrawWithImage(imageToRedrawWith){if(this.callback){this.callback(imageToRedrawWith);}}/**
   * @param {string} url          Url of the image
   * @param {string} brokenUrl    Url of an image to use if the url image is not found
   * @returns {Image} img          The image object
   */load(url,brokenUrl){//Try and get the image from the cache, if successful then return the cached image
const cachedImage=this.images[url];if(cachedImage)return cachedImage;//Create a new image
const img=new CachedImage();// Need to add to cache here, otherwise final return will spawn different copies of the same image,
// Also, there will be multiple loads of the same image.
this.images[url]=img;//Subscribe to the event that is raised if the image loads successfully
img.image.onload=()=>{// Properly init the cached item and then request a redraw
this._fixImageCoordinates(img.image);img.init();this._redrawWithImage(img);};//Subscribe to the event that is raised if the image fails to load
img.image.onerror=()=>{console.error("Could not load image:",url);//Try and load the image specified by the brokenUrl using
this._tryloadBrokenUrl(url,brokenUrl,img);};//Set the source of the image to the url, this is what actually kicks off the loading of the image
img.image.src=url;//Return the new image
return img;}/**
   * IE11 fix -- thanks dponch!
   *
   * Local helper function
   * @param {vis.Image} imageToCache
   * @private
   */_fixImageCoordinates(imageToCache){if(imageToCache.width===0){document.body.appendChild(imageToCache);imageToCache.width=imageToCache.offsetWidth;imageToCache.height=imageToCache.offsetHeight;document.body.removeChild(imageToCache);}}}var es_map={};var es_map_constructor={};var internalMetadata={exports:{}};var arrayBufferNonExtensible;var hasRequiredArrayBufferNonExtensible;function requireArrayBufferNonExtensible(){if(hasRequiredArrayBufferNonExtensible)return arrayBufferNonExtensible;hasRequiredArrayBufferNonExtensible=1;// FF26- bug: ArrayBuffers are non-extensible, but Object.isExtensible does not report it
var fails=/*@__PURE__*/requireFails();arrayBufferNonExtensible=fails(function(){if(typeof ArrayBuffer=='function'){var buffer=new ArrayBuffer(8);// eslint-disable-next-line es/no-object-isextensible, es/no-object-defineproperty -- safe
if(Object.isExtensible(buffer))Object.defineProperty(buffer,'a',{value:8});}});return arrayBufferNonExtensible;}var objectIsExtensible;var hasRequiredObjectIsExtensible;function requireObjectIsExtensible(){if(hasRequiredObjectIsExtensible)return objectIsExtensible;hasRequiredObjectIsExtensible=1;var fails=/*@__PURE__*/requireFails();var isObject=/*@__PURE__*/requireIsObject();var classof=/*@__PURE__*/requireClassofRaw();var ARRAY_BUFFER_NON_EXTENSIBLE=/*@__PURE__*/requireArrayBufferNonExtensible();// eslint-disable-next-line es/no-object-isextensible -- safe
var $isExtensible=Object.isExtensible;var FAILS_ON_PRIMITIVES=fails(function(){});// `Object.isExtensible` method
// https://tc39.es/ecma262/#sec-object.isextensible
objectIsExtensible=FAILS_ON_PRIMITIVES||ARRAY_BUFFER_NON_EXTENSIBLE?function isExtensible(it){if(!isObject(it))return false;if(ARRAY_BUFFER_NON_EXTENSIBLE&&classof(it)==='ArrayBuffer')return false;return $isExtensible?$isExtensible(it):true;}:$isExtensible;return objectIsExtensible;}var freezing;var hasRequiredFreezing;function requireFreezing(){if(hasRequiredFreezing)return freezing;hasRequiredFreezing=1;var fails=/*@__PURE__*/requireFails();freezing=!fails(function(){// eslint-disable-next-line es/no-object-isextensible, es/no-object-preventextensions -- required for testing
return Object.isExtensible(Object.preventExtensions({}));});return freezing;}var hasRequiredInternalMetadata;function requireInternalMetadata(){if(hasRequiredInternalMetadata)return internalMetadata.exports;hasRequiredInternalMetadata=1;var $=/*@__PURE__*/require_export();var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var hiddenKeys=/*@__PURE__*/requireHiddenKeys();var isObject=/*@__PURE__*/requireIsObject();var hasOwn=/*@__PURE__*/requireHasOwnProperty();var defineProperty=/*@__PURE__*/requireObjectDefineProperty().f;var getOwnPropertyNamesModule=/*@__PURE__*/requireObjectGetOwnPropertyNames();var getOwnPropertyNamesExternalModule=/*@__PURE__*/requireObjectGetOwnPropertyNamesExternal();var isExtensible=/*@__PURE__*/requireObjectIsExtensible();var uid=/*@__PURE__*/requireUid();var FREEZING=/*@__PURE__*/requireFreezing();var REQUIRED=false;var METADATA=uid('meta');var id=0;var setMetadata=function(it){defineProperty(it,METADATA,{value:{objectID:'O'+id++,// object ID
weakData:{}// weak collections IDs
}});};var fastKey=function(it,create){// return a primitive with prefix
if(!isObject(it))return typeof it=='symbol'?it:(typeof it=='string'?'S':'P')+it;if(!hasOwn(it,METADATA)){// can't set metadata to uncaught frozen object
if(!isExtensible(it))return 'F';// not necessary to add metadata
if(!create)return 'E';// add missing metadata
setMetadata(it);// return object ID
}return it[METADATA].objectID;};var getWeakData=function(it,create){if(!hasOwn(it,METADATA)){// can't set metadata to uncaught frozen object
if(!isExtensible(it))return true;// not necessary to add metadata
if(!create)return false;// add missing metadata
setMetadata(it);// return the store of weak collections IDs
}return it[METADATA].weakData;};// add metadata on freeze-family methods calling
var onFreeze=function(it){if(FREEZING&&REQUIRED&&isExtensible(it)&&!hasOwn(it,METADATA))setMetadata(it);return it;};var enable=function(){meta.enable=function(){/* empty */};REQUIRED=true;var getOwnPropertyNames=getOwnPropertyNamesModule.f;var splice=uncurryThis([].splice);var test={};test[METADATA]=1;// prevent exposing of metadata key
if(getOwnPropertyNames(test).length){getOwnPropertyNamesModule.f=function(it){var result=getOwnPropertyNames(it);for(var i=0,length=result.length;i<length;i++){if(result[i]===METADATA){splice(result,i,1);break;}}return result;};$({target:'Object',stat:true,forced:true},{getOwnPropertyNames:getOwnPropertyNamesExternalModule.f});}};var meta=internalMetadata.exports={enable:enable,fastKey:fastKey,getWeakData:getWeakData,onFreeze:onFreeze};hiddenKeys[METADATA]=true;return internalMetadata.exports;}var isArrayIteratorMethod;var hasRequiredIsArrayIteratorMethod;function requireIsArrayIteratorMethod(){if(hasRequiredIsArrayIteratorMethod)return isArrayIteratorMethod;hasRequiredIsArrayIteratorMethod=1;var wellKnownSymbol=/*@__PURE__*/requireWellKnownSymbol();var Iterators=/*@__PURE__*/requireIterators();var ITERATOR=wellKnownSymbol('iterator');var ArrayPrototype=Array.prototype;// check on default Array iterator
isArrayIteratorMethod=function(it){return it!==undefined&&(Iterators.Array===it||ArrayPrototype[ITERATOR]===it);};return isArrayIteratorMethod;}var getIteratorMethod;var hasRequiredGetIteratorMethod;function requireGetIteratorMethod(){if(hasRequiredGetIteratorMethod)return getIteratorMethod;hasRequiredGetIteratorMethod=1;var classof=/*@__PURE__*/requireClassof();var getMethod=/*@__PURE__*/requireGetMethod();var isNullOrUndefined=/*@__PURE__*/requireIsNullOrUndefined();var Iterators=/*@__PURE__*/requireIterators();var wellKnownSymbol=/*@__PURE__*/requireWellKnownSymbol();var ITERATOR=wellKnownSymbol('iterator');getIteratorMethod=function(it){if(!isNullOrUndefined(it))return getMethod(it,ITERATOR)||getMethod(it,'@@iterator')||Iterators[classof(it)];};return getIteratorMethod;}var getIterator$5;var hasRequiredGetIterator$6;function requireGetIterator$6(){if(hasRequiredGetIterator$6)return getIterator$5;hasRequiredGetIterator$6=1;var call=/*@__PURE__*/requireFunctionCall();var aCallable=/*@__PURE__*/requireACallable();var anObject=/*@__PURE__*/requireAnObject();var tryToString=/*@__PURE__*/requireTryToString();var getIteratorMethod=/*@__PURE__*/requireGetIteratorMethod();var $TypeError=TypeError;getIterator$5=function(argument,usingIterator){var iteratorMethod=arguments.length<2?getIteratorMethod(argument):usingIterator;if(aCallable(iteratorMethod))return anObject(call(iteratorMethod,argument));throw new $TypeError(tryToString(argument)+' is not iterable');};return getIterator$5;}var iteratorClose;var hasRequiredIteratorClose;function requireIteratorClose(){if(hasRequiredIteratorClose)return iteratorClose;hasRequiredIteratorClose=1;var call=/*@__PURE__*/requireFunctionCall();var anObject=/*@__PURE__*/requireAnObject();var getMethod=/*@__PURE__*/requireGetMethod();iteratorClose=function(iterator,kind,value){var innerResult,innerError;anObject(iterator);try{innerResult=getMethod(iterator,'return');if(!innerResult){if(kind==='throw')throw value;return value;}innerResult=call(innerResult,iterator);}catch(error){innerError=true;innerResult=error;}if(kind==='throw')throw value;if(innerError)throw innerResult;anObject(innerResult);return value;};return iteratorClose;}var iterate;var hasRequiredIterate;function requireIterate(){if(hasRequiredIterate)return iterate;hasRequiredIterate=1;var bind=/*@__PURE__*/requireFunctionBindContext();var call=/*@__PURE__*/requireFunctionCall();var anObject=/*@__PURE__*/requireAnObject();var tryToString=/*@__PURE__*/requireTryToString();var isArrayIteratorMethod=/*@__PURE__*/requireIsArrayIteratorMethod();var lengthOfArrayLike=/*@__PURE__*/requireLengthOfArrayLike();var isPrototypeOf=/*@__PURE__*/requireObjectIsPrototypeOf();var getIterator=/*@__PURE__*/requireGetIterator$6();var getIteratorMethod=/*@__PURE__*/requireGetIteratorMethod();var iteratorClose=/*@__PURE__*/requireIteratorClose();var $TypeError=TypeError;var Result=function(stopped,result){this.stopped=stopped;this.result=result;};var ResultPrototype=Result.prototype;iterate=function(iterable,unboundFunction,options){var that=options&&options.that;var AS_ENTRIES=!!(options&&options.AS_ENTRIES);var IS_RECORD=!!(options&&options.IS_RECORD);var IS_ITERATOR=!!(options&&options.IS_ITERATOR);var INTERRUPTED=!!(options&&options.INTERRUPTED);var fn=bind(unboundFunction,that);var iterator,iterFn,index,length,result,next,step;var stop=function(condition){if(iterator)iteratorClose(iterator,'normal');return new Result(true,condition);};var callFn=function(value){if(AS_ENTRIES){anObject(value);return INTERRUPTED?fn(value[0],value[1],stop):fn(value[0],value[1]);}return INTERRUPTED?fn(value,stop):fn(value);};if(IS_RECORD){iterator=iterable.iterator;}else if(IS_ITERATOR){iterator=iterable;}else {iterFn=getIteratorMethod(iterable);if(!iterFn)throw new $TypeError(tryToString(iterable)+' is not iterable');// optimisation for array iterators
if(isArrayIteratorMethod(iterFn)){for(index=0,length=lengthOfArrayLike(iterable);length>index;index++){result=callFn(iterable[index]);if(result&&isPrototypeOf(ResultPrototype,result))return result;}return new Result(false);}iterator=getIterator(iterable,iterFn);}next=IS_RECORD?iterable.next:iterator.next;while(!(step=call(next,iterator)).done){try{result=callFn(step.value);}catch(error){iteratorClose(iterator,'throw',error);}if(typeof result=='object'&&result&&isPrototypeOf(ResultPrototype,result))return result;}return new Result(false);};return iterate;}var anInstance;var hasRequiredAnInstance;function requireAnInstance(){if(hasRequiredAnInstance)return anInstance;hasRequiredAnInstance=1;var isPrototypeOf=/*@__PURE__*/requireObjectIsPrototypeOf();var $TypeError=TypeError;anInstance=function(it,Prototype){if(isPrototypeOf(Prototype,it))return it;throw new $TypeError('Incorrect invocation');};return anInstance;}var collection;var hasRequiredCollection;function requireCollection(){if(hasRequiredCollection)return collection;hasRequiredCollection=1;var $=/*@__PURE__*/require_export();var globalThis=/*@__PURE__*/requireGlobalThis();var InternalMetadataModule=/*@__PURE__*/requireInternalMetadata();var fails=/*@__PURE__*/requireFails();var createNonEnumerableProperty=/*@__PURE__*/requireCreateNonEnumerableProperty();var iterate=/*@__PURE__*/requireIterate();var anInstance=/*@__PURE__*/requireAnInstance();var isCallable=/*@__PURE__*/requireIsCallable();var isObject=/*@__PURE__*/requireIsObject();var isNullOrUndefined=/*@__PURE__*/requireIsNullOrUndefined();var setToStringTag=/*@__PURE__*/requireSetToStringTag();var defineProperty=/*@__PURE__*/requireObjectDefineProperty().f;var forEach=/*@__PURE__*/requireArrayIteration().forEach;var DESCRIPTORS=/*@__PURE__*/requireDescriptors();var InternalStateModule=/*@__PURE__*/requireInternalState();var setInternalState=InternalStateModule.set;var internalStateGetterFor=InternalStateModule.getterFor;collection=function(CONSTRUCTOR_NAME,wrapper,common){var IS_MAP=CONSTRUCTOR_NAME.indexOf('Map')!==-1;var IS_WEAK=CONSTRUCTOR_NAME.indexOf('Weak')!==-1;var ADDER=IS_MAP?'set':'add';var NativeConstructor=globalThis[CONSTRUCTOR_NAME];var NativePrototype=NativeConstructor&&NativeConstructor.prototype;var exported={};var Constructor;if(!DESCRIPTORS||!isCallable(NativeConstructor)||!(IS_WEAK||NativePrototype.forEach&&!fails(function(){new NativeConstructor().entries().next();}))){// create collection constructor
Constructor=common.getConstructor(wrapper,CONSTRUCTOR_NAME,IS_MAP,ADDER);InternalMetadataModule.enable();}else {Constructor=wrapper(function(target,iterable){setInternalState(anInstance(target,Prototype),{type:CONSTRUCTOR_NAME,collection:new NativeConstructor()});if(!isNullOrUndefined(iterable))iterate(iterable,target[ADDER],{that:target,AS_ENTRIES:IS_MAP});});var Prototype=Constructor.prototype;var getInternalState=internalStateGetterFor(CONSTRUCTOR_NAME);forEach(['add','clear','delete','forEach','get','has','set','keys','values','entries'],function(KEY){var IS_ADDER=KEY==='add'||KEY==='set';if(KEY in NativePrototype&&!(IS_WEAK&&KEY==='clear')){createNonEnumerableProperty(Prototype,KEY,function(a,b){var collection=getInternalState(this).collection;if(!IS_ADDER&&IS_WEAK&&!isObject(a))return KEY==='get'?undefined:false;var result=collection[KEY](a===0?0:a,b);return IS_ADDER?this:result;});}});IS_WEAK||defineProperty(Prototype,'size',{configurable:true,get:function(){return getInternalState(this).collection.size;}});}setToStringTag(Constructor,CONSTRUCTOR_NAME,false,true);exported[CONSTRUCTOR_NAME]=Constructor;$({global:true,forced:true},exported);if(!IS_WEAK)common.setStrong(Constructor,CONSTRUCTOR_NAME,IS_MAP);return Constructor;};return collection;}var defineBuiltIns;var hasRequiredDefineBuiltIns;function requireDefineBuiltIns(){if(hasRequiredDefineBuiltIns)return defineBuiltIns;hasRequiredDefineBuiltIns=1;var defineBuiltIn=/*@__PURE__*/requireDefineBuiltIn();defineBuiltIns=function(target,src,options){for(var key in src){if(options&&options.unsafe&&target[key])target[key]=src[key];else defineBuiltIn(target,key,src[key],options);}return target;};return defineBuiltIns;}var setSpecies;var hasRequiredSetSpecies;function requireSetSpecies(){if(hasRequiredSetSpecies)return setSpecies;hasRequiredSetSpecies=1;var getBuiltIn=/*@__PURE__*/requireGetBuiltIn();var defineBuiltInAccessor=/*@__PURE__*/requireDefineBuiltInAccessor();var wellKnownSymbol=/*@__PURE__*/requireWellKnownSymbol();var DESCRIPTORS=/*@__PURE__*/requireDescriptors();var SPECIES=wellKnownSymbol('species');setSpecies=function(CONSTRUCTOR_NAME){var Constructor=getBuiltIn(CONSTRUCTOR_NAME);if(DESCRIPTORS&&Constructor&&!Constructor[SPECIES]){defineBuiltInAccessor(Constructor,SPECIES,{configurable:true,get:function(){return this;}});}};return setSpecies;}var collectionStrong;var hasRequiredCollectionStrong;function requireCollectionStrong(){if(hasRequiredCollectionStrong)return collectionStrong;hasRequiredCollectionStrong=1;var create=/*@__PURE__*/requireObjectCreate();var defineBuiltInAccessor=/*@__PURE__*/requireDefineBuiltInAccessor();var defineBuiltIns=/*@__PURE__*/requireDefineBuiltIns();var bind=/*@__PURE__*/requireFunctionBindContext();var anInstance=/*@__PURE__*/requireAnInstance();var isNullOrUndefined=/*@__PURE__*/requireIsNullOrUndefined();var iterate=/*@__PURE__*/requireIterate();var defineIterator=/*@__PURE__*/requireIteratorDefine();var createIterResultObject=/*@__PURE__*/requireCreateIterResultObject();var setSpecies=/*@__PURE__*/requireSetSpecies();var DESCRIPTORS=/*@__PURE__*/requireDescriptors();var fastKey=/*@__PURE__*/requireInternalMetadata().fastKey;var InternalStateModule=/*@__PURE__*/requireInternalState();var setInternalState=InternalStateModule.set;var internalStateGetterFor=InternalStateModule.getterFor;collectionStrong={getConstructor:function(wrapper,CONSTRUCTOR_NAME,IS_MAP,ADDER){var Constructor=wrapper(function(that,iterable){anInstance(that,Prototype);setInternalState(that,{type:CONSTRUCTOR_NAME,index:create(null),first:null,last:null,size:0});if(!DESCRIPTORS)that.size=0;if(!isNullOrUndefined(iterable))iterate(iterable,that[ADDER],{that:that,AS_ENTRIES:IS_MAP});});var Prototype=Constructor.prototype;var getInternalState=internalStateGetterFor(CONSTRUCTOR_NAME);var define=function(that,key,value){var state=getInternalState(that);var entry=getEntry(that,key);var previous,index;// change existing entry
if(entry){entry.value=value;// create new entry
}else {state.last=entry={index:index=fastKey(key,true),key:key,value:value,previous:previous=state.last,next:null,removed:false};if(!state.first)state.first=entry;if(previous)previous.next=entry;if(DESCRIPTORS)state.size++;else that.size++;// add to index
if(index!=='F')state.index[index]=entry;}return that;};var getEntry=function(that,key){var state=getInternalState(that);// fast case
var index=fastKey(key);var entry;if(index!=='F')return state.index[index];// frozen object case
for(entry=state.first;entry;entry=entry.next){if(entry.key===key)return entry;}};defineBuiltIns(Prototype,{// `{ Map, Set }.prototype.clear()` methods
// https://tc39.es/ecma262/#sec-map.prototype.clear
// https://tc39.es/ecma262/#sec-set.prototype.clear
clear:function clear(){var that=this;var state=getInternalState(that);var entry=state.first;while(entry){entry.removed=true;if(entry.previous)entry.previous=entry.previous.next=null;entry=entry.next;}state.first=state.last=null;state.index=create(null);if(DESCRIPTORS)state.size=0;else that.size=0;},// `{ Map, Set }.prototype.delete(key)` methods
// https://tc39.es/ecma262/#sec-map.prototype.delete
// https://tc39.es/ecma262/#sec-set.prototype.delete
'delete':function(key){var that=this;var state=getInternalState(that);var entry=getEntry(that,key);if(entry){var next=entry.next;var prev=entry.previous;delete state.index[entry.index];entry.removed=true;if(prev)prev.next=next;if(next)next.previous=prev;if(state.first===entry)state.first=next;if(state.last===entry)state.last=prev;if(DESCRIPTORS)state.size--;else that.size--;}return !!entry;},// `{ Map, Set }.prototype.forEach(callbackfn, thisArg = undefined)` methods
// https://tc39.es/ecma262/#sec-map.prototype.foreach
// https://tc39.es/ecma262/#sec-set.prototype.foreach
forEach:function forEach(callbackfn/* , that = undefined */){var state=getInternalState(this);var boundFunction=bind(callbackfn,arguments.length>1?arguments[1]:undefined);var entry;while(entry=entry?entry.next:state.first){boundFunction(entry.value,entry.key,this);// revert to the last existing entry
while(entry&&entry.removed)entry=entry.previous;}},// `{ Map, Set}.prototype.has(key)` methods
// https://tc39.es/ecma262/#sec-map.prototype.has
// https://tc39.es/ecma262/#sec-set.prototype.has
has:function has(key){return !!getEntry(this,key);}});defineBuiltIns(Prototype,IS_MAP?{// `Map.prototype.get(key)` method
// https://tc39.es/ecma262/#sec-map.prototype.get
get:function get(key){var entry=getEntry(this,key);return entry&&entry.value;},// `Map.prototype.set(key, value)` method
// https://tc39.es/ecma262/#sec-map.prototype.set
set:function set(key,value){return define(this,key===0?0:key,value);}}:{// `Set.prototype.add(value)` method
// https://tc39.es/ecma262/#sec-set.prototype.add
add:function add(value){return define(this,value=value===0?0:value,value);}});if(DESCRIPTORS)defineBuiltInAccessor(Prototype,'size',{configurable:true,get:function(){return getInternalState(this).size;}});return Constructor;},setStrong:function(Constructor,CONSTRUCTOR_NAME,IS_MAP){var ITERATOR_NAME=CONSTRUCTOR_NAME+' Iterator';var getInternalCollectionState=internalStateGetterFor(CONSTRUCTOR_NAME);var getInternalIteratorState=internalStateGetterFor(ITERATOR_NAME);// `{ Map, Set }.prototype.{ keys, values, entries, @@iterator }()` methods
// https://tc39.es/ecma262/#sec-map.prototype.entries
// https://tc39.es/ecma262/#sec-map.prototype.keys
// https://tc39.es/ecma262/#sec-map.prototype.values
// https://tc39.es/ecma262/#sec-map.prototype-@@iterator
// https://tc39.es/ecma262/#sec-set.prototype.entries
// https://tc39.es/ecma262/#sec-set.prototype.keys
// https://tc39.es/ecma262/#sec-set.prototype.values
// https://tc39.es/ecma262/#sec-set.prototype-@@iterator
defineIterator(Constructor,CONSTRUCTOR_NAME,function(iterated,kind){setInternalState(this,{type:ITERATOR_NAME,target:iterated,state:getInternalCollectionState(iterated),kind:kind,last:null});},function(){var state=getInternalIteratorState(this);var kind=state.kind;var entry=state.last;// revert to the last existing entry
while(entry&&entry.removed)entry=entry.previous;// get next entry
if(!state.target||!(state.last=entry=entry?entry.next:state.state.first)){// or finish the iteration
state.target=null;return createIterResultObject(undefined,true);}// return step by kind
if(kind==='keys')return createIterResultObject(entry.key,false);if(kind==='values')return createIterResultObject(entry.value,false);return createIterResultObject([entry.key,entry.value],false);},IS_MAP?'entries':'values',!IS_MAP,true);// `{ Map, Set }.prototype[@@species]` accessors
// https://tc39.es/ecma262/#sec-get-map-@@species
// https://tc39.es/ecma262/#sec-get-set-@@species
setSpecies(CONSTRUCTOR_NAME);}};return collectionStrong;}var hasRequiredEs_map_constructor;function requireEs_map_constructor(){if(hasRequiredEs_map_constructor)return es_map_constructor;hasRequiredEs_map_constructor=1;var collection=/*@__PURE__*/requireCollection();var collectionStrong=/*@__PURE__*/requireCollectionStrong();// `Map` constructor
// https://tc39.es/ecma262/#sec-map-objects
collection('Map',function(init){return function Map(){return init(this,arguments.length?arguments[0]:undefined);};},collectionStrong);return es_map_constructor;}var hasRequiredEs_map;function requireEs_map(){if(hasRequiredEs_map)return es_map;hasRequiredEs_map=1;// TODO: Remove this module from `core-js@4` since it's replaced to module below
requireEs_map_constructor();return es_map;}var es_map_groupBy={};var caller;var hasRequiredCaller;function requireCaller(){if(hasRequiredCaller)return caller;hasRequiredCaller=1;caller=function(methodName,numArgs){return numArgs===1?function(object,arg){return object[methodName](arg);}:function(object,arg1,arg2){return object[methodName](arg1,arg2);};};return caller;}var mapHelpers;var hasRequiredMapHelpers;function requireMapHelpers(){if(hasRequiredMapHelpers)return mapHelpers;hasRequiredMapHelpers=1;var getBuiltIn=/*@__PURE__*/requireGetBuiltIn();var caller=/*@__PURE__*/requireCaller();var Map=getBuiltIn('Map');mapHelpers={Map:Map,set:caller('set',2),get:caller('get',1),has:caller('has',1),remove:caller('delete',1),proto:Map.prototype};return mapHelpers;}var hasRequiredEs_map_groupBy;function requireEs_map_groupBy(){if(hasRequiredEs_map_groupBy)return es_map_groupBy;hasRequiredEs_map_groupBy=1;var $=/*@__PURE__*/require_export();var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var aCallable=/*@__PURE__*/requireACallable();var requireObjectCoercible=/*@__PURE__*/requireRequireObjectCoercible();var iterate=/*@__PURE__*/requireIterate();var MapHelpers=/*@__PURE__*/requireMapHelpers();var IS_PURE=/*@__PURE__*/requireIsPure();var fails=/*@__PURE__*/requireFails();var Map=MapHelpers.Map;var has=MapHelpers.has;var get=MapHelpers.get;var set=MapHelpers.set;var push=uncurryThis([].push);// https://bugs.webkit.org/show_bug.cgi?id=271524
var DOES_NOT_WORK_WITH_PRIMITIVES=IS_PURE||fails(function(){return Map.groupBy('ab',function(it){return it;}).get('a').length!==1;});// `Map.groupBy` method
// https://tc39.es/ecma262/#sec-map.groupby
$({target:'Map',stat:true,forced:IS_PURE||DOES_NOT_WORK_WITH_PRIMITIVES},{groupBy:function groupBy(items,callbackfn){requireObjectCoercible(items);aCallable(callbackfn);var map=new Map();var k=0;iterate(items,function(value){var key=callbackfn(value,k++);if(!has(map,key))set(map,key,[value]);else push(get(map,key),value);});return map;}});return es_map_groupBy;}var es_string_iterator={};var stringMultibyte;var hasRequiredStringMultibyte;function requireStringMultibyte(){if(hasRequiredStringMultibyte)return stringMultibyte;hasRequiredStringMultibyte=1;var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var toIntegerOrInfinity=/*@__PURE__*/requireToIntegerOrInfinity();var toString=/*@__PURE__*/requireToString();var requireObjectCoercible=/*@__PURE__*/requireRequireObjectCoercible();var charAt=uncurryThis(''.charAt);var charCodeAt=uncurryThis(''.charCodeAt);var stringSlice=uncurryThis(''.slice);var createMethod=function(CONVERT_TO_STRING){return function($this,pos){var S=toString(requireObjectCoercible($this));var position=toIntegerOrInfinity(pos);var size=S.length;var first,second;if(position<0||position>=size)return CONVERT_TO_STRING?'':undefined;first=charCodeAt(S,position);return first<0xD800||first>0xDBFF||position+1===size||(second=charCodeAt(S,position+1))<0xDC00||second>0xDFFF?CONVERT_TO_STRING?charAt(S,position):first:CONVERT_TO_STRING?stringSlice(S,position,position+2):(first-0xD800<<10)+(second-0xDC00)+0x10000;};};stringMultibyte={// `String.prototype.codePointAt` method
// https://tc39.es/ecma262/#sec-string.prototype.codepointat
codeAt:createMethod(false),// `String.prototype.at` method
// https://github.com/mathiasbynens/String.prototype.at
charAt:createMethod(true)};return stringMultibyte;}var hasRequiredEs_string_iterator;function requireEs_string_iterator(){if(hasRequiredEs_string_iterator)return es_string_iterator;hasRequiredEs_string_iterator=1;var charAt=/*@__PURE__*/requireStringMultibyte().charAt;var toString=/*@__PURE__*/requireToString();var InternalStateModule=/*@__PURE__*/requireInternalState();var defineIterator=/*@__PURE__*/requireIteratorDefine();var createIterResultObject=/*@__PURE__*/requireCreateIterResultObject();var STRING_ITERATOR='String Iterator';var setInternalState=InternalStateModule.set;var getInternalState=InternalStateModule.getterFor(STRING_ITERATOR);// `String.prototype[@@iterator]` method
// https://tc39.es/ecma262/#sec-string.prototype-@@iterator
defineIterator(String,'String',function(iterated){setInternalState(this,{type:STRING_ITERATOR,string:toString(iterated),index:0});// `%StringIteratorPrototype%.next` method
// https://tc39.es/ecma262/#sec-%stringiteratorprototype%.next
},function next(){var state=getInternalState(this);var string=state.string;var index=state.index;var point;if(index>=string.length)return createIterResultObject(undefined,true);point=charAt(string,index);state.index+=point.length;return createIterResultObject(point,false);});return es_string_iterator;}var map$2;var hasRequiredMap$2;function requireMap$2(){if(hasRequiredMap$2)return map$2;hasRequiredMap$2=1;requireEs_array_iterator();requireEs_map();requireEs_map_groupBy();requireEs_string_iterator();var path=/*@__PURE__*/requirePath();map$2=path.Map;return map$2;}var map$1;var hasRequiredMap$1;function requireMap$1(){if(hasRequiredMap$1)return map$1;hasRequiredMap$1=1;var parent=/*@__PURE__*/requireMap$2();requireWeb_domCollections_iterator();map$1=parent;return map$1;}var map;var hasRequiredMap;function requireMap(){if(hasRequiredMap)return map;hasRequiredMap=1;map=/*@__PURE__*/requireMap$1();return map;}var mapExports=requireMap();var _Map=/*@__PURE__*/getDefaultExportFromCjs(mapExports);/**
 * This class can store groups and options specific for groups.
 */class Groups{/**
   * @ignore
   */constructor(){this.clear();this._defaultIndex=0;this._groupIndex=0;this._defaultGroups=[{border:"#2B7CE9",background:"#97C2FC",highlight:{border:"#2B7CE9",background:"#D2E5FF"},hover:{border:"#2B7CE9",background:"#D2E5FF"}},// 0: blue
{border:"#FFA500",background:"#FFFF00",highlight:{border:"#FFA500",background:"#FFFFA3"},hover:{border:"#FFA500",background:"#FFFFA3"}},// 1: yellow
{border:"#FA0A10",background:"#FB7E81",highlight:{border:"#FA0A10",background:"#FFAFB1"},hover:{border:"#FA0A10",background:"#FFAFB1"}},// 2: red
{border:"#41A906",background:"#7BE141",highlight:{border:"#41A906",background:"#A1EC76"},hover:{border:"#41A906",background:"#A1EC76"}},// 3: green
{border:"#E129F0",background:"#EB7DF4",highlight:{border:"#E129F0",background:"#F0B3F5"},hover:{border:"#E129F0",background:"#F0B3F5"}},// 4: magenta
{border:"#7C29F0",background:"#AD85E4",highlight:{border:"#7C29F0",background:"#D3BDF0"},hover:{border:"#7C29F0",background:"#D3BDF0"}},// 5: purple
{border:"#C37F00",background:"#FFA807",highlight:{border:"#C37F00",background:"#FFCA66"},hover:{border:"#C37F00",background:"#FFCA66"}},// 6: orange
{border:"#4220FB",background:"#6E6EFD",highlight:{border:"#4220FB",background:"#9B9BFD"},hover:{border:"#4220FB",background:"#9B9BFD"}},// 7: darkblue
{border:"#FD5A77",background:"#FFC0CB",highlight:{border:"#FD5A77",background:"#FFD1D9"},hover:{border:"#FD5A77",background:"#FFD1D9"}},// 8: pink
{border:"#4AD63A",background:"#C2FABC",highlight:{border:"#4AD63A",background:"#E6FFE3"},hover:{border:"#4AD63A",background:"#E6FFE3"}},// 9: mint
{border:"#990000",background:"#EE0000",highlight:{border:"#BB0000",background:"#FF3333"},hover:{border:"#BB0000",background:"#FF3333"}},// 10:bright red
{border:"#FF6000",background:"#FF6000",highlight:{border:"#FF6000",background:"#FF6000"},hover:{border:"#FF6000",background:"#FF6000"}},// 12: real orange
{border:"#97C2FC",background:"#2B7CE9",highlight:{border:"#D2E5FF",background:"#2B7CE9"},hover:{border:"#D2E5FF",background:"#2B7CE9"}},// 13: blue
{border:"#399605",background:"#255C03",highlight:{border:"#399605",background:"#255C03"},hover:{border:"#399605",background:"#255C03"}},// 14: green
{border:"#B70054",background:"#FF007E",highlight:{border:"#B70054",background:"#FF007E"},hover:{border:"#B70054",background:"#FF007E"}},// 15: magenta
{border:"#AD85E4",background:"#7C29F0",highlight:{border:"#D3BDF0",background:"#7C29F0"},hover:{border:"#D3BDF0",background:"#7C29F0"}},// 16: purple
{border:"#4557FA",background:"#000EA1",highlight:{border:"#6E6EFD",background:"#000EA1"},hover:{border:"#6E6EFD",background:"#000EA1"}},// 17: darkblue
{border:"#FFC0CB",background:"#FD5A77",highlight:{border:"#FFD1D9",background:"#FD5A77"},hover:{border:"#FFD1D9",background:"#FD5A77"}},// 18: pink
{border:"#C2FABC",background:"#74D66A",highlight:{border:"#E6FFE3",background:"#74D66A"},hover:{border:"#E6FFE3",background:"#74D66A"}},// 19: mint
{border:"#EE0000",background:"#990000",highlight:{border:"#FF3333",background:"#BB0000"},hover:{border:"#FF3333",background:"#BB0000"}}// 20:bright red
];this.options={};this.defaultOptions={useDefaultGroups:true};_Object$assign(this.options,this.defaultOptions);}/**
   *
   * @param {object} options
   */setOptions(options){const optionFields=["useDefaultGroups"];if(options!==undefined){for(const groupName in options){if(Object.prototype.hasOwnProperty.call(options,groupName)){if(_indexOfInstanceProperty(optionFields).call(optionFields,groupName)===-1){const group=options[groupName];this.add(groupName,group);}}}}}/**
   * Clear all groups
   */clear(){this._groups=new _Map();this._groupNames=[];}/**
   * Get group options of a groupname.
   * If groupname is not found, a new group may be created.
   * @param {*}       groupname     Can be a number, string, Date, etc.
   * @param {boolean} [shouldCreate] If true, create a new group
   * @returns {object} The found or created group
   */get(groupname){let shouldCreate=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;let group=this._groups.get(groupname);if(group===undefined&&shouldCreate){if(this.options.useDefaultGroups===false&&this._groupNames.length>0){// create new group
const index=this._groupIndex%this._groupNames.length;++this._groupIndex;group={};group.color=this._groups.get(this._groupNames[index]);this._groups.set(groupname,group);}else {// create new group
const index=this._defaultIndex%this._defaultGroups.length;this._defaultIndex++;group={};group.color=this._defaultGroups[index];this._groups.set(groupname,group);}}return group;}/**
   * Add custom group style.
   * @param {string} groupName - The name of the group, a new group will be
   * created if a group with the same name doesn't exist, otherwise the old
   * groups style will be overwritten.
   * @param {object} style - An object containing borderColor, backgroundColor,
   * etc.
   * @returns {object} The created group object.
   */add(groupName,style){// Only push group name once to prevent duplicates which would consume more
// RAM and also skew the distribution towards more often updated groups,
// neither of which is desirable.
if(!this._groups.has(groupName)){this._groupNames.push(groupName);}this._groups.set(groupName,style);return style;}}var es_number_isNan={};var hasRequiredEs_number_isNan;function requireEs_number_isNan(){if(hasRequiredEs_number_isNan)return es_number_isNan;hasRequiredEs_number_isNan=1;var $=/*@__PURE__*/require_export();// `Number.isNaN` method
// https://tc39.es/ecma262/#sec-number.isnan
$({target:'Number',stat:true},{isNaN:function isNaN(number){// eslint-disable-next-line no-self-compare -- NaN check
return number!==number;}});return es_number_isNan;}var isNan$2;var hasRequiredIsNan$2;function requireIsNan$2(){if(hasRequiredIsNan$2)return isNan$2;hasRequiredIsNan$2=1;requireEs_number_isNan();var path=/*@__PURE__*/requirePath();isNan$2=path.Number.isNaN;return isNan$2;}var isNan$1;var hasRequiredIsNan$1;function requireIsNan$1(){if(hasRequiredIsNan$1)return isNan$1;hasRequiredIsNan$1=1;var parent=/*@__PURE__*/requireIsNan$2();isNan$1=parent;return isNan$1;}var isNan;var hasRequiredIsNan;function requireIsNan(){if(hasRequiredIsNan)return isNan;hasRequiredIsNan=1;isNan=/*@__PURE__*/requireIsNan$1();return isNan;}var isNanExports=requireIsNan();var _Number$isNaN=/*@__PURE__*/getDefaultExportFromCjs(isNanExports);var es_number_isFinite={};var numberIsFinite;var hasRequiredNumberIsFinite;function requireNumberIsFinite(){if(hasRequiredNumberIsFinite)return numberIsFinite;hasRequiredNumberIsFinite=1;var globalThis=/*@__PURE__*/requireGlobalThis();var globalIsFinite=globalThis.isFinite;// `Number.isFinite` method
// https://tc39.es/ecma262/#sec-number.isfinite
// eslint-disable-next-line es/no-number-isfinite -- safe
numberIsFinite=Number.isFinite||function isFinite(it){return typeof it=='number'&&globalIsFinite(it);};return numberIsFinite;}var hasRequiredEs_number_isFinite;function requireEs_number_isFinite(){if(hasRequiredEs_number_isFinite)return es_number_isFinite;hasRequiredEs_number_isFinite=1;var $=/*@__PURE__*/require_export();var numberIsFinite=/*@__PURE__*/requireNumberIsFinite();// `Number.isFinite` method
// https://tc39.es/ecma262/#sec-number.isfinite
$({target:'Number',stat:true},{isFinite:numberIsFinite});return es_number_isFinite;}var _isFinite$2;var hasRequired_isFinite$2;function require_isFinite$2(){if(hasRequired_isFinite$2)return _isFinite$2;hasRequired_isFinite$2=1;requireEs_number_isFinite();var path=/*@__PURE__*/requirePath();_isFinite$2=path.Number.isFinite;return _isFinite$2;}var _isFinite$1;var hasRequired_isFinite$1;function require_isFinite$1(){if(hasRequired_isFinite$1)return _isFinite$1;hasRequired_isFinite$1=1;var parent=/*@__PURE__*/require_isFinite$2();_isFinite$1=parent;return _isFinite$1;}var _isFinite;var hasRequired_isFinite;function require_isFinite(){if(hasRequired_isFinite)return _isFinite;hasRequired_isFinite=1;_isFinite=/*@__PURE__*/require_isFinite$1();return _isFinite;}var _isFiniteExports=require_isFinite();var _Number$isFinite=/*@__PURE__*/getDefaultExportFromCjs(_isFiniteExports);var es_array_some={};var hasRequiredEs_array_some;function requireEs_array_some(){if(hasRequiredEs_array_some)return es_array_some;hasRequiredEs_array_some=1;var $=/*@__PURE__*/require_export();var $some=/*@__PURE__*/requireArrayIteration().some;var arrayMethodIsStrict=/*@__PURE__*/requireArrayMethodIsStrict();var STRICT_METHOD=arrayMethodIsStrict('some');// `Array.prototype.some` method
// https://tc39.es/ecma262/#sec-array.prototype.some
$({target:'Array',proto:true,forced:!STRICT_METHOD},{some:function some(callbackfn/* , thisArg */){return $some(this,callbackfn,arguments.length>1?arguments[1]:undefined);}});return es_array_some;}var some$3;var hasRequiredSome$3;function requireSome$3(){if(hasRequiredSome$3)return some$3;hasRequiredSome$3=1;requireEs_array_some();var getBuiltInPrototypeMethod=/*@__PURE__*/requireGetBuiltInPrototypeMethod();some$3=getBuiltInPrototypeMethod('Array','some');return some$3;}var some$2;var hasRequiredSome$2;function requireSome$2(){if(hasRequiredSome$2)return some$2;hasRequiredSome$2=1;var isPrototypeOf=/*@__PURE__*/requireObjectIsPrototypeOf();var method=/*@__PURE__*/requireSome$3();var ArrayPrototype=Array.prototype;some$2=function(it){var own=it.some;return it===ArrayPrototype||isPrototypeOf(ArrayPrototype,it)&&own===ArrayPrototype.some?method:own;};return some$2;}var some$1;var hasRequiredSome$1;function requireSome$1(){if(hasRequiredSome$1)return some$1;hasRequiredSome$1=1;var parent=/*@__PURE__*/requireSome$2();some$1=parent;return some$1;}var some;var hasRequiredSome;function requireSome(){if(hasRequiredSome)return some;hasRequiredSome=1;some=/*@__PURE__*/requireSome$1();return some;}var someExports=requireSome();var _someInstanceProperty=/*@__PURE__*/getDefaultExportFromCjs(someExports);var getOwnPropertySymbols$2;var hasRequiredGetOwnPropertySymbols$2;function requireGetOwnPropertySymbols$2(){if(hasRequiredGetOwnPropertySymbols$2)return getOwnPropertySymbols$2;hasRequiredGetOwnPropertySymbols$2=1;requireEs_symbol();var path=/*@__PURE__*/requirePath();getOwnPropertySymbols$2=path.Object.getOwnPropertySymbols;return getOwnPropertySymbols$2;}var getOwnPropertySymbols$1;var hasRequiredGetOwnPropertySymbols$1;function requireGetOwnPropertySymbols$1(){if(hasRequiredGetOwnPropertySymbols$1)return getOwnPropertySymbols$1;hasRequiredGetOwnPropertySymbols$1=1;var parent=/*@__PURE__*/requireGetOwnPropertySymbols$2();getOwnPropertySymbols$1=parent;return getOwnPropertySymbols$1;}var getOwnPropertySymbols;var hasRequiredGetOwnPropertySymbols;function requireGetOwnPropertySymbols(){if(hasRequiredGetOwnPropertySymbols)return getOwnPropertySymbols;hasRequiredGetOwnPropertySymbols=1;getOwnPropertySymbols=/*@__PURE__*/requireGetOwnPropertySymbols$1();return getOwnPropertySymbols;}var getOwnPropertySymbolsExports=requireGetOwnPropertySymbols();var _Object$getOwnPropertySymbols=/*@__PURE__*/getDefaultExportFromCjs(getOwnPropertySymbolsExports);var getOwnPropertyDescriptor$2={exports:{}};var es_object_getOwnPropertyDescriptor={};var hasRequiredEs_object_getOwnPropertyDescriptor;function requireEs_object_getOwnPropertyDescriptor(){if(hasRequiredEs_object_getOwnPropertyDescriptor)return es_object_getOwnPropertyDescriptor;hasRequiredEs_object_getOwnPropertyDescriptor=1;var $=/*@__PURE__*/require_export();var fails=/*@__PURE__*/requireFails();var toIndexedObject=/*@__PURE__*/requireToIndexedObject();var nativeGetOwnPropertyDescriptor=/*@__PURE__*/requireObjectGetOwnPropertyDescriptor().f;var DESCRIPTORS=/*@__PURE__*/requireDescriptors();var FORCED=!DESCRIPTORS||fails(function(){nativeGetOwnPropertyDescriptor(1);});// `Object.getOwnPropertyDescriptor` method
// https://tc39.es/ecma262/#sec-object.getownpropertydescriptor
$({target:'Object',stat:true,forced:FORCED,sham:!DESCRIPTORS},{getOwnPropertyDescriptor:function getOwnPropertyDescriptor(it,key){return nativeGetOwnPropertyDescriptor(toIndexedObject(it),key);}});return es_object_getOwnPropertyDescriptor;}var hasRequiredGetOwnPropertyDescriptor$2;function requireGetOwnPropertyDescriptor$2(){if(hasRequiredGetOwnPropertyDescriptor$2)return getOwnPropertyDescriptor$2.exports;hasRequiredGetOwnPropertyDescriptor$2=1;requireEs_object_getOwnPropertyDescriptor();var path=/*@__PURE__*/requirePath();var Object=path.Object;var getOwnPropertyDescriptor=getOwnPropertyDescriptor$2.exports=function getOwnPropertyDescriptor(it,key){return Object.getOwnPropertyDescriptor(it,key);};if(Object.getOwnPropertyDescriptor.sham)getOwnPropertyDescriptor.sham=true;return getOwnPropertyDescriptor$2.exports;}var getOwnPropertyDescriptor$1;var hasRequiredGetOwnPropertyDescriptor$1;function requireGetOwnPropertyDescriptor$1(){if(hasRequiredGetOwnPropertyDescriptor$1)return getOwnPropertyDescriptor$1;hasRequiredGetOwnPropertyDescriptor$1=1;var parent=/*@__PURE__*/requireGetOwnPropertyDescriptor$2();getOwnPropertyDescriptor$1=parent;return getOwnPropertyDescriptor$1;}var getOwnPropertyDescriptor;var hasRequiredGetOwnPropertyDescriptor;function requireGetOwnPropertyDescriptor(){if(hasRequiredGetOwnPropertyDescriptor)return getOwnPropertyDescriptor;hasRequiredGetOwnPropertyDescriptor=1;getOwnPropertyDescriptor=/*@__PURE__*/requireGetOwnPropertyDescriptor$1();return getOwnPropertyDescriptor;}var getOwnPropertyDescriptorExports=requireGetOwnPropertyDescriptor();var _Object$getOwnPropertyDescriptor=/*@__PURE__*/getDefaultExportFromCjs(getOwnPropertyDescriptorExports);var es_object_getOwnPropertyDescriptors={};var hasRequiredEs_object_getOwnPropertyDescriptors;function requireEs_object_getOwnPropertyDescriptors(){if(hasRequiredEs_object_getOwnPropertyDescriptors)return es_object_getOwnPropertyDescriptors;hasRequiredEs_object_getOwnPropertyDescriptors=1;var $=/*@__PURE__*/require_export();var DESCRIPTORS=/*@__PURE__*/requireDescriptors();var ownKeys=/*@__PURE__*/requireOwnKeys$3();var toIndexedObject=/*@__PURE__*/requireToIndexedObject();var getOwnPropertyDescriptorModule=/*@__PURE__*/requireObjectGetOwnPropertyDescriptor();var createProperty=/*@__PURE__*/requireCreateProperty();// `Object.getOwnPropertyDescriptors` method
// https://tc39.es/ecma262/#sec-object.getownpropertydescriptors
$({target:'Object',stat:true,sham:!DESCRIPTORS},{getOwnPropertyDescriptors:function getOwnPropertyDescriptors(object){var O=toIndexedObject(object);var getOwnPropertyDescriptor=getOwnPropertyDescriptorModule.f;var keys=ownKeys(O);var result={};var index=0;var key,descriptor;while(keys.length>index){descriptor=getOwnPropertyDescriptor(O,key=keys[index++]);if(descriptor!==undefined)createProperty(result,key,descriptor);}return result;}});return es_object_getOwnPropertyDescriptors;}var getOwnPropertyDescriptors$2;var hasRequiredGetOwnPropertyDescriptors$2;function requireGetOwnPropertyDescriptors$2(){if(hasRequiredGetOwnPropertyDescriptors$2)return getOwnPropertyDescriptors$2;hasRequiredGetOwnPropertyDescriptors$2=1;requireEs_object_getOwnPropertyDescriptors();var path=/*@__PURE__*/requirePath();getOwnPropertyDescriptors$2=path.Object.getOwnPropertyDescriptors;return getOwnPropertyDescriptors$2;}var getOwnPropertyDescriptors$1;var hasRequiredGetOwnPropertyDescriptors$1;function requireGetOwnPropertyDescriptors$1(){if(hasRequiredGetOwnPropertyDescriptors$1)return getOwnPropertyDescriptors$1;hasRequiredGetOwnPropertyDescriptors$1=1;var parent=/*@__PURE__*/requireGetOwnPropertyDescriptors$2();getOwnPropertyDescriptors$1=parent;return getOwnPropertyDescriptors$1;}var getOwnPropertyDescriptors;var hasRequiredGetOwnPropertyDescriptors;function requireGetOwnPropertyDescriptors(){if(hasRequiredGetOwnPropertyDescriptors)return getOwnPropertyDescriptors;hasRequiredGetOwnPropertyDescriptors=1;getOwnPropertyDescriptors=/*@__PURE__*/requireGetOwnPropertyDescriptors$1();return getOwnPropertyDescriptors;}var getOwnPropertyDescriptorsExports=requireGetOwnPropertyDescriptors();var _Object$getOwnPropertyDescriptors=/*@__PURE__*/getDefaultExportFromCjs(getOwnPropertyDescriptorsExports);var defineProperties$2={exports:{}};var es_object_defineProperties={};var hasRequiredEs_object_defineProperties;function requireEs_object_defineProperties(){if(hasRequiredEs_object_defineProperties)return es_object_defineProperties;hasRequiredEs_object_defineProperties=1;var $=/*@__PURE__*/require_export();var DESCRIPTORS=/*@__PURE__*/requireDescriptors();var defineProperties=/*@__PURE__*/requireObjectDefineProperties().f;// `Object.defineProperties` method
// https://tc39.es/ecma262/#sec-object.defineproperties
// eslint-disable-next-line es/no-object-defineproperties -- safe
$({target:'Object',stat:true,forced:Object.defineProperties!==defineProperties,sham:!DESCRIPTORS},{defineProperties:defineProperties});return es_object_defineProperties;}var hasRequiredDefineProperties$2;function requireDefineProperties$2(){if(hasRequiredDefineProperties$2)return defineProperties$2.exports;hasRequiredDefineProperties$2=1;requireEs_object_defineProperties();var path=/*@__PURE__*/requirePath();var Object=path.Object;var defineProperties=defineProperties$2.exports=function defineProperties(T,D){return Object.defineProperties(T,D);};if(Object.defineProperties.sham)defineProperties.sham=true;return defineProperties$2.exports;}var defineProperties$1;var hasRequiredDefineProperties$1;function requireDefineProperties$1(){if(hasRequiredDefineProperties$1)return defineProperties$1;hasRequiredDefineProperties$1=1;var parent=/*@__PURE__*/requireDefineProperties$2();defineProperties$1=parent;return defineProperties$1;}var defineProperties;var hasRequiredDefineProperties;function requireDefineProperties(){if(hasRequiredDefineProperties)return defineProperties;hasRequiredDefineProperties=1;defineProperties=/*@__PURE__*/requireDefineProperties$1();return defineProperties;}var definePropertiesExports=requireDefineProperties();var _Object$defineProperties=/*@__PURE__*/getDefaultExportFromCjs(definePropertiesExports);var defineProperty$5={exports:{}};var es_object_defineProperty={};var hasRequiredEs_object_defineProperty;function requireEs_object_defineProperty(){if(hasRequiredEs_object_defineProperty)return es_object_defineProperty;hasRequiredEs_object_defineProperty=1;var $=/*@__PURE__*/require_export();var DESCRIPTORS=/*@__PURE__*/requireDescriptors();var defineProperty=/*@__PURE__*/requireObjectDefineProperty().f;// `Object.defineProperty` method
// https://tc39.es/ecma262/#sec-object.defineproperty
// eslint-disable-next-line es/no-object-defineproperty -- safe
$({target:'Object',stat:true,forced:Object.defineProperty!==defineProperty,sham:!DESCRIPTORS},{defineProperty:defineProperty});return es_object_defineProperty;}var hasRequiredDefineProperty$5;function requireDefineProperty$5(){if(hasRequiredDefineProperty$5)return defineProperty$5.exports;hasRequiredDefineProperty$5=1;requireEs_object_defineProperty();var path=/*@__PURE__*/requirePath();var Object=path.Object;var defineProperty=defineProperty$5.exports=function defineProperty(it,key,desc){return Object.defineProperty(it,key,desc);};if(Object.defineProperty.sham)defineProperty.sham=true;return defineProperty$5.exports;}var defineProperty$4;var hasRequiredDefineProperty$4;function requireDefineProperty$4(){if(hasRequiredDefineProperty$4)return defineProperty$4;hasRequiredDefineProperty$4=1;var parent=/*@__PURE__*/requireDefineProperty$5();defineProperty$4=parent;return defineProperty$4;}var defineProperty$3;var hasRequiredDefineProperty$3;function requireDefineProperty$3(){if(hasRequiredDefineProperty$3)return defineProperty$3;hasRequiredDefineProperty$3=1;var parent=/*@__PURE__*/requireDefineProperty$4();defineProperty$3=parent;return defineProperty$3;}var defineProperty$2;var hasRequiredDefineProperty$2;function requireDefineProperty$2(){if(hasRequiredDefineProperty$2)return defineProperty$2;hasRequiredDefineProperty$2=1;var parent=/*@__PURE__*/requireDefineProperty$3();defineProperty$2=parent;return defineProperty$2;}var defineProperty$1;var hasRequiredDefineProperty$1;function requireDefineProperty$1(){if(hasRequiredDefineProperty$1)return defineProperty$1;hasRequiredDefineProperty$1=1;defineProperty$1=/*@__PURE__*/requireDefineProperty$2();return defineProperty$1;}var definePropertyExports$1=/*@__PURE__*/requireDefineProperty$1();var _Object$defineProperty$1=/*@__PURE__*/getDefaultExportFromCjs(definePropertyExports$1);var esnext_function_metadata={};var hasRequiredEsnext_function_metadata;function requireEsnext_function_metadata(){if(hasRequiredEsnext_function_metadata)return esnext_function_metadata;hasRequiredEsnext_function_metadata=1;var wellKnownSymbol=/*@__PURE__*/requireWellKnownSymbol();var defineProperty=/*@__PURE__*/requireObjectDefineProperty().f;var METADATA=wellKnownSymbol('metadata');var FunctionPrototype=Function.prototype;// Function.prototype[@@metadata]
// https://github.com/tc39/proposal-decorator-metadata
if(FunctionPrototype[METADATA]===undefined){defineProperty(FunctionPrototype,METADATA,{value:null});}return esnext_function_metadata;}var esnext_symbol_asyncDispose={};var hasRequiredEsnext_symbol_asyncDispose;function requireEsnext_symbol_asyncDispose(){if(hasRequiredEsnext_symbol_asyncDispose)return esnext_symbol_asyncDispose;hasRequiredEsnext_symbol_asyncDispose=1;// TODO: Remove from `core-js@4`
requireEs_symbol_asyncDispose();return esnext_symbol_asyncDispose;}var esnext_symbol_dispose={};var hasRequiredEsnext_symbol_dispose;function requireEsnext_symbol_dispose(){if(hasRequiredEsnext_symbol_dispose)return esnext_symbol_dispose;hasRequiredEsnext_symbol_dispose=1;// TODO: Remove from `core-js@4`
requireEs_symbol_dispose();return esnext_symbol_dispose;}var esnext_symbol_metadata={};var hasRequiredEsnext_symbol_metadata;function requireEsnext_symbol_metadata(){if(hasRequiredEsnext_symbol_metadata)return esnext_symbol_metadata;hasRequiredEsnext_symbol_metadata=1;var defineWellKnownSymbol=/*@__PURE__*/requireWellKnownSymbolDefine();// `Symbol.metadata` well-known symbol
// https://github.com/tc39/proposal-decorators
defineWellKnownSymbol('metadata');return esnext_symbol_metadata;}var symbol$2;var hasRequiredSymbol$2;function requireSymbol$2(){if(hasRequiredSymbol$2)return symbol$2;hasRequiredSymbol$2=1;var parent=/*@__PURE__*/requireSymbol$4();requireEsnext_function_metadata();requireEsnext_symbol_asyncDispose();requireEsnext_symbol_dispose();requireEsnext_symbol_metadata();symbol$2=parent;return symbol$2;}var esnext_symbol_isRegisteredSymbol={};var symbolIsRegistered;var hasRequiredSymbolIsRegistered;function requireSymbolIsRegistered(){if(hasRequiredSymbolIsRegistered)return symbolIsRegistered;hasRequiredSymbolIsRegistered=1;var getBuiltIn=/*@__PURE__*/requireGetBuiltIn();var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var Symbol=getBuiltIn('Symbol');var keyFor=Symbol.keyFor;var thisSymbolValue=uncurryThis(Symbol.prototype.valueOf);// `Symbol.isRegisteredSymbol` method
// https://tc39.es/proposal-symbol-predicates/#sec-symbol-isregisteredsymbol
symbolIsRegistered=Symbol.isRegisteredSymbol||function isRegisteredSymbol(value){try{return keyFor(thisSymbolValue(value))!==undefined;}catch(error){return false;}};return symbolIsRegistered;}var hasRequiredEsnext_symbol_isRegisteredSymbol;function requireEsnext_symbol_isRegisteredSymbol(){if(hasRequiredEsnext_symbol_isRegisteredSymbol)return esnext_symbol_isRegisteredSymbol;hasRequiredEsnext_symbol_isRegisteredSymbol=1;var $=/*@__PURE__*/require_export();var isRegisteredSymbol=/*@__PURE__*/requireSymbolIsRegistered();// `Symbol.isRegisteredSymbol` method
// https://tc39.es/proposal-symbol-predicates/#sec-symbol-isregisteredsymbol
$({target:'Symbol',stat:true},{isRegisteredSymbol:isRegisteredSymbol});return esnext_symbol_isRegisteredSymbol;}var esnext_symbol_isWellKnownSymbol={};var symbolIsWellKnown;var hasRequiredSymbolIsWellKnown;function requireSymbolIsWellKnown(){if(hasRequiredSymbolIsWellKnown)return symbolIsWellKnown;hasRequiredSymbolIsWellKnown=1;var shared=/*@__PURE__*/requireShared();var getBuiltIn=/*@__PURE__*/requireGetBuiltIn();var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var isSymbol=/*@__PURE__*/requireIsSymbol();var wellKnownSymbol=/*@__PURE__*/requireWellKnownSymbol();var Symbol=getBuiltIn('Symbol');var $isWellKnownSymbol=Symbol.isWellKnownSymbol;var getOwnPropertyNames=getBuiltIn('Object','getOwnPropertyNames');var thisSymbolValue=uncurryThis(Symbol.prototype.valueOf);var WellKnownSymbolsStore=shared('wks');for(var i=0,symbolKeys=getOwnPropertyNames(Symbol),symbolKeysLength=symbolKeys.length;i<symbolKeysLength;i++){// some old engines throws on access to some keys like `arguments` or `caller`
try{var symbolKey=symbolKeys[i];if(isSymbol(Symbol[symbolKey]))wellKnownSymbol(symbolKey);}catch(error){/* empty */}}// `Symbol.isWellKnownSymbol` method
// https://tc39.es/proposal-symbol-predicates/#sec-symbol-iswellknownsymbol
// We should patch it for newly added well-known symbols. If it's not required, this module just will not be injected
symbolIsWellKnown=function isWellKnownSymbol(value){if($isWellKnownSymbol&&$isWellKnownSymbol(value))return true;try{var symbol=thisSymbolValue(value);for(var j=0,keys=getOwnPropertyNames(WellKnownSymbolsStore),keysLength=keys.length;j<keysLength;j++){// eslint-disable-next-line eqeqeq -- polyfilled symbols case
if(WellKnownSymbolsStore[keys[j]]==symbol)return true;}}catch(error){/* empty */}return false;};return symbolIsWellKnown;}var hasRequiredEsnext_symbol_isWellKnownSymbol;function requireEsnext_symbol_isWellKnownSymbol(){if(hasRequiredEsnext_symbol_isWellKnownSymbol)return esnext_symbol_isWellKnownSymbol;hasRequiredEsnext_symbol_isWellKnownSymbol=1;var $=/*@__PURE__*/require_export();var isWellKnownSymbol=/*@__PURE__*/requireSymbolIsWellKnown();// `Symbol.isWellKnownSymbol` method
// https://tc39.es/proposal-symbol-predicates/#sec-symbol-iswellknownsymbol
// We should patch it for newly added well-known symbols. If it's not required, this module just will not be injected
$({target:'Symbol',stat:true,forced:true},{isWellKnownSymbol:isWellKnownSymbol});return esnext_symbol_isWellKnownSymbol;}var esnext_symbol_customMatcher={};var hasRequiredEsnext_symbol_customMatcher;function requireEsnext_symbol_customMatcher(){if(hasRequiredEsnext_symbol_customMatcher)return esnext_symbol_customMatcher;hasRequiredEsnext_symbol_customMatcher=1;var defineWellKnownSymbol=/*@__PURE__*/requireWellKnownSymbolDefine();// `Symbol.customMatcher` well-known symbol
// https://github.com/tc39/proposal-pattern-matching
defineWellKnownSymbol('customMatcher');return esnext_symbol_customMatcher;}var esnext_symbol_observable={};var hasRequiredEsnext_symbol_observable;function requireEsnext_symbol_observable(){if(hasRequiredEsnext_symbol_observable)return esnext_symbol_observable;hasRequiredEsnext_symbol_observable=1;var defineWellKnownSymbol=/*@__PURE__*/requireWellKnownSymbolDefine();// `Symbol.observable` well-known symbol
// https://github.com/tc39/proposal-observable
defineWellKnownSymbol('observable');return esnext_symbol_observable;}var esnext_symbol_isRegistered={};var hasRequiredEsnext_symbol_isRegistered;function requireEsnext_symbol_isRegistered(){if(hasRequiredEsnext_symbol_isRegistered)return esnext_symbol_isRegistered;hasRequiredEsnext_symbol_isRegistered=1;var $=/*@__PURE__*/require_export();var isRegisteredSymbol=/*@__PURE__*/requireSymbolIsRegistered();// `Symbol.isRegistered` method
// obsolete version of https://tc39.es/proposal-symbol-predicates/#sec-symbol-isregisteredsymbol
$({target:'Symbol',stat:true,name:'isRegisteredSymbol'},{isRegistered:isRegisteredSymbol});return esnext_symbol_isRegistered;}var esnext_symbol_isWellKnown={};var hasRequiredEsnext_symbol_isWellKnown;function requireEsnext_symbol_isWellKnown(){if(hasRequiredEsnext_symbol_isWellKnown)return esnext_symbol_isWellKnown;hasRequiredEsnext_symbol_isWellKnown=1;var $=/*@__PURE__*/require_export();var isWellKnownSymbol=/*@__PURE__*/requireSymbolIsWellKnown();// `Symbol.isWellKnown` method
// obsolete version of https://tc39.es/proposal-symbol-predicates/#sec-symbol-iswellknownsymbol
// We should patch it for newly added well-known symbols. If it's not required, this module just will not be injected
$({target:'Symbol',stat:true,name:'isWellKnownSymbol',forced:true},{isWellKnown:isWellKnownSymbol});return esnext_symbol_isWellKnown;}var esnext_symbol_matcher={};var hasRequiredEsnext_symbol_matcher;function requireEsnext_symbol_matcher(){if(hasRequiredEsnext_symbol_matcher)return esnext_symbol_matcher;hasRequiredEsnext_symbol_matcher=1;var defineWellKnownSymbol=/*@__PURE__*/requireWellKnownSymbolDefine();// `Symbol.matcher` well-known symbol
// https://github.com/tc39/proposal-pattern-matching
defineWellKnownSymbol('matcher');return esnext_symbol_matcher;}var esnext_symbol_metadataKey={};var hasRequiredEsnext_symbol_metadataKey;function requireEsnext_symbol_metadataKey(){if(hasRequiredEsnext_symbol_metadataKey)return esnext_symbol_metadataKey;hasRequiredEsnext_symbol_metadataKey=1;// TODO: Remove from `core-js@4`
var defineWellKnownSymbol=/*@__PURE__*/requireWellKnownSymbolDefine();// `Symbol.metadataKey` well-known symbol
// https://github.com/tc39/proposal-decorator-metadata
defineWellKnownSymbol('metadataKey');return esnext_symbol_metadataKey;}var esnext_symbol_patternMatch={};var hasRequiredEsnext_symbol_patternMatch;function requireEsnext_symbol_patternMatch(){if(hasRequiredEsnext_symbol_patternMatch)return esnext_symbol_patternMatch;hasRequiredEsnext_symbol_patternMatch=1;// TODO: remove from `core-js@4`
var defineWellKnownSymbol=/*@__PURE__*/requireWellKnownSymbolDefine();// `Symbol.patternMatch` well-known symbol
// https://github.com/tc39/proposal-pattern-matching
defineWellKnownSymbol('patternMatch');return esnext_symbol_patternMatch;}var esnext_symbol_replaceAll={};var hasRequiredEsnext_symbol_replaceAll;function requireEsnext_symbol_replaceAll(){if(hasRequiredEsnext_symbol_replaceAll)return esnext_symbol_replaceAll;hasRequiredEsnext_symbol_replaceAll=1;// TODO: remove from `core-js@4`
var defineWellKnownSymbol=/*@__PURE__*/requireWellKnownSymbolDefine();defineWellKnownSymbol('replaceAll');return esnext_symbol_replaceAll;}var symbol$1;var hasRequiredSymbol$1;function requireSymbol$1(){if(hasRequiredSymbol$1)return symbol$1;hasRequiredSymbol$1=1;var parent=/*@__PURE__*/requireSymbol$2();requireEsnext_symbol_isRegisteredSymbol();requireEsnext_symbol_isWellKnownSymbol();requireEsnext_symbol_customMatcher();requireEsnext_symbol_observable();// TODO: Remove from `core-js@4`
requireEsnext_symbol_isRegistered();requireEsnext_symbol_isWellKnown();requireEsnext_symbol_matcher();requireEsnext_symbol_metadataKey();requireEsnext_symbol_patternMatch();requireEsnext_symbol_replaceAll();symbol$1=parent;return symbol$1;}var symbol;var hasRequiredSymbol;function requireSymbol(){if(hasRequiredSymbol)return symbol;hasRequiredSymbol=1;symbol=/*@__PURE__*/requireSymbol$1();return symbol;}var symbolExports=/*@__PURE__*/requireSymbol();var _Symbol=/*@__PURE__*/getDefaultExportFromCjs(symbolExports);var iterator$5;var hasRequiredIterator$5;function requireIterator$5(){if(hasRequiredIterator$5)return iterator$5;hasRequiredIterator$5=1;requireEs_array_iterator();requireEs_string_iterator();requireEs_symbol_iterator();var WrappedWellKnownSymbolModule=/*@__PURE__*/requireWellKnownSymbolWrapped();iterator$5=WrappedWellKnownSymbolModule.f('iterator');return iterator$5;}var iterator$4;var hasRequiredIterator$4;function requireIterator$4(){if(hasRequiredIterator$4)return iterator$4;hasRequiredIterator$4=1;var parent=/*@__PURE__*/requireIterator$5();requireWeb_domCollections_iterator();iterator$4=parent;return iterator$4;}var iterator$3;var hasRequiredIterator$3;function requireIterator$3(){if(hasRequiredIterator$3)return iterator$3;hasRequiredIterator$3=1;var parent=/*@__PURE__*/requireIterator$4();iterator$3=parent;return iterator$3;}var iterator$2;var hasRequiredIterator$2;function requireIterator$2(){if(hasRequiredIterator$2)return iterator$2;hasRequiredIterator$2=1;var parent=/*@__PURE__*/requireIterator$3();iterator$2=parent;return iterator$2;}var iterator$1;var hasRequiredIterator$1;function requireIterator$1(){if(hasRequiredIterator$1)return iterator$1;hasRequiredIterator$1=1;iterator$1=/*@__PURE__*/requireIterator$2();return iterator$1;}var iteratorExports$1=/*@__PURE__*/requireIterator$1();var _Symbol$iterator$1=/*@__PURE__*/getDefaultExportFromCjs(iteratorExports$1);function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof _Symbol&&"symbol"==typeof _Symbol$iterator$1?function(o){return typeof o;}:function(o){return o&&"function"==typeof _Symbol&&o.constructor===_Symbol&&o!==_Symbol.prototype?"symbol":typeof o;},_typeof(o);}var toPrimitive$5;var hasRequiredToPrimitive$4;function requireToPrimitive$4(){if(hasRequiredToPrimitive$4)return toPrimitive$5;hasRequiredToPrimitive$4=1;requireEs_symbol_toPrimitive();var WrappedWellKnownSymbolModule=/*@__PURE__*/requireWellKnownSymbolWrapped();toPrimitive$5=WrappedWellKnownSymbolModule.f('toPrimitive');return toPrimitive$5;}var toPrimitive$4;var hasRequiredToPrimitive$3;function requireToPrimitive$3(){if(hasRequiredToPrimitive$3)return toPrimitive$4;hasRequiredToPrimitive$3=1;var parent=/*@__PURE__*/requireToPrimitive$4();toPrimitive$4=parent;return toPrimitive$4;}var toPrimitive$3;var hasRequiredToPrimitive$2;function requireToPrimitive$2(){if(hasRequiredToPrimitive$2)return toPrimitive$3;hasRequiredToPrimitive$2=1;var parent=/*@__PURE__*/requireToPrimitive$3();toPrimitive$3=parent;return toPrimitive$3;}var toPrimitive$2;var hasRequiredToPrimitive$1;function requireToPrimitive$1(){if(hasRequiredToPrimitive$1)return toPrimitive$2;hasRequiredToPrimitive$1=1;var parent=/*@__PURE__*/requireToPrimitive$2();toPrimitive$2=parent;return toPrimitive$2;}var toPrimitive$1;var hasRequiredToPrimitive;function requireToPrimitive(){if(hasRequiredToPrimitive)return toPrimitive$1;hasRequiredToPrimitive=1;toPrimitive$1=/*@__PURE__*/requireToPrimitive$1();return toPrimitive$1;}var toPrimitiveExports=/*@__PURE__*/requireToPrimitive();var _Symbol$toPrimitive=/*@__PURE__*/getDefaultExportFromCjs(toPrimitiveExports);function toPrimitive(t,r){if("object"!=_typeof(t)||!t)return t;var e=t[_Symbol$toPrimitive];if(void 0!==e){var i=e.call(t,r);if("object"!=_typeof(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.");}return ("string"===r?String:Number)(t);}function toPropertyKey(t){var i=toPrimitive(t,"string");return "symbol"==_typeof(i)?i:i+"";}function _defineProperty(e,r,t){return (r=toPropertyKey(r))in e?_Object$defineProperty$1(e,r,{value:t,enumerable:true,configurable:true,writable:true}):e[r]=t,e;}var es_array_reduce={};var arrayReduce;var hasRequiredArrayReduce;function requireArrayReduce(){if(hasRequiredArrayReduce)return arrayReduce;hasRequiredArrayReduce=1;var aCallable=/*@__PURE__*/requireACallable();var toObject=/*@__PURE__*/requireToObject();var IndexedObject=/*@__PURE__*/requireIndexedObject();var lengthOfArrayLike=/*@__PURE__*/requireLengthOfArrayLike();var $TypeError=TypeError;var REDUCE_EMPTY='Reduce of empty array with no initial value';// `Array.prototype.{ reduce, reduceRight }` methods implementation
var createMethod=function(IS_RIGHT){return function(that,callbackfn,argumentsLength,memo){var O=toObject(that);var self=IndexedObject(O);var length=lengthOfArrayLike(O);aCallable(callbackfn);if(length===0&&argumentsLength<2)throw new $TypeError(REDUCE_EMPTY);var index=IS_RIGHT?length-1:0;var i=IS_RIGHT?-1:1;if(argumentsLength<2)while(true){if(index in self){memo=self[index];index+=i;break;}index+=i;if(IS_RIGHT?index<0:length<=index){throw new $TypeError(REDUCE_EMPTY);}}for(;IS_RIGHT?index>=0:length>index;index+=i)if(index in self){memo=callbackfn(memo,self[index],index,O);}return memo;};};arrayReduce={// `Array.prototype.reduce` method
// https://tc39.es/ecma262/#sec-array.prototype.reduce
left:createMethod(false),// `Array.prototype.reduceRight` method
// https://tc39.es/ecma262/#sec-array.prototype.reduceright
right:createMethod(true)};return arrayReduce;}var environmentIsNode;var hasRequiredEnvironmentIsNode;function requireEnvironmentIsNode(){if(hasRequiredEnvironmentIsNode)return environmentIsNode;hasRequiredEnvironmentIsNode=1;var ENVIRONMENT=/*@__PURE__*/requireEnvironment();environmentIsNode=ENVIRONMENT==='NODE';return environmentIsNode;}var hasRequiredEs_array_reduce;function requireEs_array_reduce(){if(hasRequiredEs_array_reduce)return es_array_reduce;hasRequiredEs_array_reduce=1;var $=/*@__PURE__*/require_export();var $reduce=/*@__PURE__*/requireArrayReduce().left;var arrayMethodIsStrict=/*@__PURE__*/requireArrayMethodIsStrict();var CHROME_VERSION=/*@__PURE__*/requireEnvironmentV8Version();var IS_NODE=/*@__PURE__*/requireEnvironmentIsNode();// Chrome 80-82 has a critical bug
// https://bugs.chromium.org/p/chromium/issues/detail?id=1049982
var CHROME_BUG=!IS_NODE&&CHROME_VERSION>79&&CHROME_VERSION<83;var FORCED=CHROME_BUG||!arrayMethodIsStrict('reduce');// `Array.prototype.reduce` method
// https://tc39.es/ecma262/#sec-array.prototype.reduce
$({target:'Array',proto:true,forced:FORCED},{reduce:function reduce(callbackfn/* , initialValue */){var length=arguments.length;return $reduce(this,callbackfn,length,length>1?arguments[1]:undefined);}});return es_array_reduce;}var reduce$3;var hasRequiredReduce$3;function requireReduce$3(){if(hasRequiredReduce$3)return reduce$3;hasRequiredReduce$3=1;requireEs_array_reduce();var getBuiltInPrototypeMethod=/*@__PURE__*/requireGetBuiltInPrototypeMethod();reduce$3=getBuiltInPrototypeMethod('Array','reduce');return reduce$3;}var reduce$2;var hasRequiredReduce$2;function requireReduce$2(){if(hasRequiredReduce$2)return reduce$2;hasRequiredReduce$2=1;var isPrototypeOf=/*@__PURE__*/requireObjectIsPrototypeOf();var method=/*@__PURE__*/requireReduce$3();var ArrayPrototype=Array.prototype;reduce$2=function(it){var own=it.reduce;return it===ArrayPrototype||isPrototypeOf(ArrayPrototype,it)&&own===ArrayPrototype.reduce?method:own;};return reduce$2;}var reduce$1;var hasRequiredReduce$1;function requireReduce$1(){if(hasRequiredReduce$1)return reduce$1;hasRequiredReduce$1=1;var parent=/*@__PURE__*/requireReduce$2();reduce$1=parent;return reduce$1;}var reduce;var hasRequiredReduce;function requireReduce(){if(hasRequiredReduce)return reduce;hasRequiredReduce=1;reduce=/*@__PURE__*/requireReduce$1();return reduce;}var reduceExports=requireReduce();var _reduceInstanceProperty=/*@__PURE__*/getDefaultExportFromCjs(reduceExports);var iterator;var hasRequiredIterator;function requireIterator(){if(hasRequiredIterator)return iterator;hasRequiredIterator=1;iterator=/*@__PURE__*/requireIterator$4();return iterator;}var iteratorExports=requireIterator();var _Symbol$iterator=/*@__PURE__*/getDefaultExportFromCjs(iteratorExports);var es_set={};var es_set_constructor={};var hasRequiredEs_set_constructor;function requireEs_set_constructor(){if(hasRequiredEs_set_constructor)return es_set_constructor;hasRequiredEs_set_constructor=1;var collection=/*@__PURE__*/requireCollection();var collectionStrong=/*@__PURE__*/requireCollectionStrong();// `Set` constructor
// https://tc39.es/ecma262/#sec-set-objects
collection('Set',function(init){return function Set(){return init(this,arguments.length?arguments[0]:undefined);};},collectionStrong);return es_set_constructor;}var hasRequiredEs_set;function requireEs_set(){if(hasRequiredEs_set)return es_set;hasRequiredEs_set=1;// TODO: Remove this module from `core-js@4` since it's replaced to module below
requireEs_set_constructor();return es_set;}var es_set_difference_v2={};var aSet;var hasRequiredASet;function requireASet(){if(hasRequiredASet)return aSet;hasRequiredASet=1;var tryToString=/*@__PURE__*/requireTryToString();var $TypeError=TypeError;// Perform ? RequireInternalSlot(M, [[SetData]])
aSet=function(it){if(typeof it=='object'&&'size'in it&&'has'in it&&'add'in it&&'delete'in it&&'keys'in it)return it;throw new $TypeError(tryToString(it)+' is not a set');};return aSet;}var setHelpers;var hasRequiredSetHelpers;function requireSetHelpers(){if(hasRequiredSetHelpers)return setHelpers;hasRequiredSetHelpers=1;var getBuiltIn=/*@__PURE__*/requireGetBuiltIn();var caller=/*@__PURE__*/requireCaller();var Set=getBuiltIn('Set');var SetPrototype=Set.prototype;setHelpers={Set:Set,add:caller('add',1),has:caller('has',1),remove:caller('delete',1),proto:SetPrototype};return setHelpers;}var iterateSimple;var hasRequiredIterateSimple;function requireIterateSimple(){if(hasRequiredIterateSimple)return iterateSimple;hasRequiredIterateSimple=1;var call=/*@__PURE__*/requireFunctionCall();iterateSimple=function(record,fn,ITERATOR_INSTEAD_OF_RECORD){var iterator=ITERATOR_INSTEAD_OF_RECORD?record:record.iterator;var next=record.next;var step,result;while(!(step=call(next,iterator)).done){result=fn(step.value);if(result!==undefined)return result;}};return iterateSimple;}var setIterate;var hasRequiredSetIterate;function requireSetIterate(){if(hasRequiredSetIterate)return setIterate;hasRequiredSetIterate=1;var iterateSimple=/*@__PURE__*/requireIterateSimple();setIterate=function(set,fn,interruptible){return interruptible?iterateSimple(set.keys(),fn,true):set.forEach(fn);};return setIterate;}var setClone;var hasRequiredSetClone;function requireSetClone(){if(hasRequiredSetClone)return setClone;hasRequiredSetClone=1;var SetHelpers=/*@__PURE__*/requireSetHelpers();var iterate=/*@__PURE__*/requireSetIterate();var Set=SetHelpers.Set;var add=SetHelpers.add;setClone=function(set){var result=new Set();iterate(set,function(it){add(result,it);});return result;};return setClone;}var setSize;var hasRequiredSetSize;function requireSetSize(){if(hasRequiredSetSize)return setSize;hasRequiredSetSize=1;setSize=function(set){return set.size;};return setSize;}var getIteratorDirect;var hasRequiredGetIteratorDirect;function requireGetIteratorDirect(){if(hasRequiredGetIteratorDirect)return getIteratorDirect;hasRequiredGetIteratorDirect=1;// `GetIteratorDirect(obj)` abstract operation
// https://tc39.es/ecma262/#sec-getiteratordirect
getIteratorDirect=function(obj){return {iterator:obj,next:obj.next,done:false};};return getIteratorDirect;}var getSetRecord;var hasRequiredGetSetRecord;function requireGetSetRecord(){if(hasRequiredGetSetRecord)return getSetRecord;hasRequiredGetSetRecord=1;var aCallable=/*@__PURE__*/requireACallable();var anObject=/*@__PURE__*/requireAnObject();var call=/*@__PURE__*/requireFunctionCall();var toIntegerOrInfinity=/*@__PURE__*/requireToIntegerOrInfinity();var getIteratorDirect=/*@__PURE__*/requireGetIteratorDirect();var INVALID_SIZE='Invalid size';var $RangeError=RangeError;var $TypeError=TypeError;var max=Math.max;var SetRecord=function(set,intSize){this.set=set;this.size=max(intSize,0);this.has=aCallable(set.has);this.keys=aCallable(set.keys);};SetRecord.prototype={getIterator:function(){return getIteratorDirect(anObject(call(this.keys,this.set)));},includes:function(it){return call(this.has,this.set,it);}};// `GetSetRecord` abstract operation
// https://tc39.es/proposal-set-methods/#sec-getsetrecord
getSetRecord=function(obj){anObject(obj);var numSize=+obj.size;// NOTE: If size is undefined, then numSize will be NaN
// eslint-disable-next-line no-self-compare -- NaN check
if(numSize!==numSize)throw new $TypeError(INVALID_SIZE);var intSize=toIntegerOrInfinity(numSize);if(intSize<0)throw new $RangeError(INVALID_SIZE);return new SetRecord(obj,intSize);};return getSetRecord;}var setDifference;var hasRequiredSetDifference;function requireSetDifference(){if(hasRequiredSetDifference)return setDifference;hasRequiredSetDifference=1;var aSet=/*@__PURE__*/requireASet();var SetHelpers=/*@__PURE__*/requireSetHelpers();var clone=/*@__PURE__*/requireSetClone();var size=/*@__PURE__*/requireSetSize();var getSetRecord=/*@__PURE__*/requireGetSetRecord();var iterateSet=/*@__PURE__*/requireSetIterate();var iterateSimple=/*@__PURE__*/requireIterateSimple();var has=SetHelpers.has;var remove=SetHelpers.remove;// `Set.prototype.difference` method
// https://tc39.es/ecma262/#sec-set.prototype.difference
setDifference=function difference(other){var O=aSet(this);var otherRec=getSetRecord(other);var result=clone(O);if(size(O)<=otherRec.size)iterateSet(O,function(e){if(otherRec.includes(e))remove(result,e);});else iterateSimple(otherRec.getIterator(),function(e){if(has(result,e))remove(result,e);});return result;};return setDifference;}var setMethodAcceptSetLike;var hasRequiredSetMethodAcceptSetLike;function requireSetMethodAcceptSetLike(){if(hasRequiredSetMethodAcceptSetLike)return setMethodAcceptSetLike;hasRequiredSetMethodAcceptSetLike=1;setMethodAcceptSetLike=function(){return false;};return setMethodAcceptSetLike;}var hasRequiredEs_set_difference_v2;function requireEs_set_difference_v2(){if(hasRequiredEs_set_difference_v2)return es_set_difference_v2;hasRequiredEs_set_difference_v2=1;var $=/*@__PURE__*/require_export();var difference=/*@__PURE__*/requireSetDifference();var fails=/*@__PURE__*/requireFails();var setMethodAcceptSetLike=/*@__PURE__*/requireSetMethodAcceptSetLike();var SET_LIKE_INCORRECT_BEHAVIOR=!setMethodAcceptSetLike('difference',function(result){return result.size===0;});var FORCED=SET_LIKE_INCORRECT_BEHAVIOR||fails(function(){// https://bugs.webkit.org/show_bug.cgi?id=288595
var setLike={size:1,has:function(){return true;},keys:function(){var index=0;return {next:function(){var done=index++>1;if(baseSet.has(1))baseSet.clear();return {done:done,value:2};}};}};// eslint-disable-next-line es/no-set -- testing
var baseSet=new Set([1,2,3,4]);// eslint-disable-next-line es/no-set-prototype-difference -- testing
return baseSet.difference(setLike).size!==3;});// `Set.prototype.difference` method
// https://tc39.es/ecma262/#sec-set.prototype.difference
$({target:'Set',proto:true,real:true,forced:FORCED},{difference:difference});return es_set_difference_v2;}var es_set_intersection_v2={};var setIntersection;var hasRequiredSetIntersection;function requireSetIntersection(){if(hasRequiredSetIntersection)return setIntersection;hasRequiredSetIntersection=1;var aSet=/*@__PURE__*/requireASet();var SetHelpers=/*@__PURE__*/requireSetHelpers();var size=/*@__PURE__*/requireSetSize();var getSetRecord=/*@__PURE__*/requireGetSetRecord();var iterateSet=/*@__PURE__*/requireSetIterate();var iterateSimple=/*@__PURE__*/requireIterateSimple();var Set=SetHelpers.Set;var add=SetHelpers.add;var has=SetHelpers.has;// `Set.prototype.intersection` method
// https://tc39.es/ecma262/#sec-set.prototype.intersection
setIntersection=function intersection(other){var O=aSet(this);var otherRec=getSetRecord(other);var result=new Set();if(size(O)>otherRec.size){iterateSimple(otherRec.getIterator(),function(e){if(has(O,e))add(result,e);});}else {iterateSet(O,function(e){if(otherRec.includes(e))add(result,e);});}return result;};return setIntersection;}var hasRequiredEs_set_intersection_v2;function requireEs_set_intersection_v2(){if(hasRequiredEs_set_intersection_v2)return es_set_intersection_v2;hasRequiredEs_set_intersection_v2=1;var $=/*@__PURE__*/require_export();var fails=/*@__PURE__*/requireFails();var intersection=/*@__PURE__*/requireSetIntersection();var setMethodAcceptSetLike=/*@__PURE__*/requireSetMethodAcceptSetLike();var INCORRECT=!setMethodAcceptSetLike('intersection',function(result){return result.size===2&&result.has(1)&&result.has(2);})||fails(function(){// eslint-disable-next-line es/no-array-from, es/no-set, es/no-set-prototype-intersection -- testing
return String(Array.from(new Set([1,2,3]).intersection(new Set([3,2]))))!=='3,2';});// `Set.prototype.intersection` method
// https://tc39.es/ecma262/#sec-set.prototype.intersection
$({target:'Set',proto:true,real:true,forced:INCORRECT},{intersection:intersection});return es_set_intersection_v2;}var es_set_isDisjointFrom_v2={};var setIsDisjointFrom;var hasRequiredSetIsDisjointFrom;function requireSetIsDisjointFrom(){if(hasRequiredSetIsDisjointFrom)return setIsDisjointFrom;hasRequiredSetIsDisjointFrom=1;var aSet=/*@__PURE__*/requireASet();var has=/*@__PURE__*/requireSetHelpers().has;var size=/*@__PURE__*/requireSetSize();var getSetRecord=/*@__PURE__*/requireGetSetRecord();var iterateSet=/*@__PURE__*/requireSetIterate();var iterateSimple=/*@__PURE__*/requireIterateSimple();var iteratorClose=/*@__PURE__*/requireIteratorClose();// `Set.prototype.isDisjointFrom` method
// https://tc39.es/ecma262/#sec-set.prototype.isdisjointfrom
setIsDisjointFrom=function isDisjointFrom(other){var O=aSet(this);var otherRec=getSetRecord(other);if(size(O)<=otherRec.size)return iterateSet(O,function(e){if(otherRec.includes(e))return false;},true)!==false;var iterator=otherRec.getIterator();return iterateSimple(iterator,function(e){if(has(O,e))return iteratorClose(iterator,'normal',false);})!==false;};return setIsDisjointFrom;}var hasRequiredEs_set_isDisjointFrom_v2;function requireEs_set_isDisjointFrom_v2(){if(hasRequiredEs_set_isDisjointFrom_v2)return es_set_isDisjointFrom_v2;hasRequiredEs_set_isDisjointFrom_v2=1;var $=/*@__PURE__*/require_export();var isDisjointFrom=/*@__PURE__*/requireSetIsDisjointFrom();var setMethodAcceptSetLike=/*@__PURE__*/requireSetMethodAcceptSetLike();var INCORRECT=!setMethodAcceptSetLike('isDisjointFrom',function(result){return !result;});// `Set.prototype.isDisjointFrom` method
// https://tc39.es/ecma262/#sec-set.prototype.isdisjointfrom
$({target:'Set',proto:true,real:true,forced:INCORRECT},{isDisjointFrom:isDisjointFrom});return es_set_isDisjointFrom_v2;}var es_set_isSubsetOf_v2={};var setIsSubsetOf;var hasRequiredSetIsSubsetOf;function requireSetIsSubsetOf(){if(hasRequiredSetIsSubsetOf)return setIsSubsetOf;hasRequiredSetIsSubsetOf=1;var aSet=/*@__PURE__*/requireASet();var size=/*@__PURE__*/requireSetSize();var iterate=/*@__PURE__*/requireSetIterate();var getSetRecord=/*@__PURE__*/requireGetSetRecord();// `Set.prototype.isSubsetOf` method
// https://tc39.es/ecma262/#sec-set.prototype.issubsetof
setIsSubsetOf=function isSubsetOf(other){var O=aSet(this);var otherRec=getSetRecord(other);if(size(O)>otherRec.size)return false;return iterate(O,function(e){if(!otherRec.includes(e))return false;},true)!==false;};return setIsSubsetOf;}var hasRequiredEs_set_isSubsetOf_v2;function requireEs_set_isSubsetOf_v2(){if(hasRequiredEs_set_isSubsetOf_v2)return es_set_isSubsetOf_v2;hasRequiredEs_set_isSubsetOf_v2=1;var $=/*@__PURE__*/require_export();var isSubsetOf=/*@__PURE__*/requireSetIsSubsetOf();var setMethodAcceptSetLike=/*@__PURE__*/requireSetMethodAcceptSetLike();var INCORRECT=!setMethodAcceptSetLike('isSubsetOf',function(result){return result;});// `Set.prototype.isSubsetOf` method
// https://tc39.es/ecma262/#sec-set.prototype.issubsetof
$({target:'Set',proto:true,real:true,forced:INCORRECT},{isSubsetOf:isSubsetOf});return es_set_isSubsetOf_v2;}var es_set_isSupersetOf_v2={};var setIsSupersetOf;var hasRequiredSetIsSupersetOf;function requireSetIsSupersetOf(){if(hasRequiredSetIsSupersetOf)return setIsSupersetOf;hasRequiredSetIsSupersetOf=1;var aSet=/*@__PURE__*/requireASet();var has=/*@__PURE__*/requireSetHelpers().has;var size=/*@__PURE__*/requireSetSize();var getSetRecord=/*@__PURE__*/requireGetSetRecord();var iterateSimple=/*@__PURE__*/requireIterateSimple();var iteratorClose=/*@__PURE__*/requireIteratorClose();// `Set.prototype.isSupersetOf` method
// https://tc39.es/ecma262/#sec-set.prototype.issupersetof
setIsSupersetOf=function isSupersetOf(other){var O=aSet(this);var otherRec=getSetRecord(other);if(size(O)<otherRec.size)return false;var iterator=otherRec.getIterator();return iterateSimple(iterator,function(e){if(!has(O,e))return iteratorClose(iterator,'normal',false);})!==false;};return setIsSupersetOf;}var hasRequiredEs_set_isSupersetOf_v2;function requireEs_set_isSupersetOf_v2(){if(hasRequiredEs_set_isSupersetOf_v2)return es_set_isSupersetOf_v2;hasRequiredEs_set_isSupersetOf_v2=1;var $=/*@__PURE__*/require_export();var isSupersetOf=/*@__PURE__*/requireSetIsSupersetOf();var setMethodAcceptSetLike=/*@__PURE__*/requireSetMethodAcceptSetLike();var INCORRECT=!setMethodAcceptSetLike('isSupersetOf',function(result){return !result;});// `Set.prototype.isSupersetOf` method
// https://tc39.es/ecma262/#sec-set.prototype.issupersetof
$({target:'Set',proto:true,real:true,forced:INCORRECT},{isSupersetOf:isSupersetOf});return es_set_isSupersetOf_v2;}var es_set_symmetricDifference_v2={};var setSymmetricDifference;var hasRequiredSetSymmetricDifference;function requireSetSymmetricDifference(){if(hasRequiredSetSymmetricDifference)return setSymmetricDifference;hasRequiredSetSymmetricDifference=1;var aSet=/*@__PURE__*/requireASet();var SetHelpers=/*@__PURE__*/requireSetHelpers();var clone=/*@__PURE__*/requireSetClone();var getSetRecord=/*@__PURE__*/requireGetSetRecord();var iterateSimple=/*@__PURE__*/requireIterateSimple();var add=SetHelpers.add;var has=SetHelpers.has;var remove=SetHelpers.remove;// `Set.prototype.symmetricDifference` method
// https://tc39.es/ecma262/#sec-set.prototype.symmetricdifference
setSymmetricDifference=function symmetricDifference(other){var O=aSet(this);var keysIter=getSetRecord(other).getIterator();var result=clone(O);iterateSimple(keysIter,function(e){if(has(O,e))remove(result,e);else add(result,e);});return result;};return setSymmetricDifference;}var setMethodGetKeysBeforeCloningDetection;var hasRequiredSetMethodGetKeysBeforeCloningDetection;function requireSetMethodGetKeysBeforeCloningDetection(){if(hasRequiredSetMethodGetKeysBeforeCloningDetection)return setMethodGetKeysBeforeCloningDetection;hasRequiredSetMethodGetKeysBeforeCloningDetection=1;// Should get iterator record of a set-like object before cloning this
// https://bugs.webkit.org/show_bug.cgi?id=289430
setMethodGetKeysBeforeCloningDetection=function(METHOD_NAME){try{// eslint-disable-next-line es/no-set -- needed for test
var baseSet=new Set();var setLike={size:0,has:function(){return true;},keys:function(){// eslint-disable-next-line es/no-object-defineproperty -- needed for test
return Object.defineProperty({},'next',{get:function(){baseSet.clear();baseSet.add(4);return function(){return {done:true};};}});}};var result=baseSet[METHOD_NAME](setLike);return result.size===1&&result.values().next().value===4;}catch(error){return false;}};return setMethodGetKeysBeforeCloningDetection;}var hasRequiredEs_set_symmetricDifference_v2;function requireEs_set_symmetricDifference_v2(){if(hasRequiredEs_set_symmetricDifference_v2)return es_set_symmetricDifference_v2;hasRequiredEs_set_symmetricDifference_v2=1;var $=/*@__PURE__*/require_export();var symmetricDifference=/*@__PURE__*/requireSetSymmetricDifference();var setMethodGetKeysBeforeCloning=/*@__PURE__*/requireSetMethodGetKeysBeforeCloningDetection();var setMethodAcceptSetLike=/*@__PURE__*/requireSetMethodAcceptSetLike();var FORCED=!setMethodAcceptSetLike('symmetricDifference')||!setMethodGetKeysBeforeCloning('symmetricDifference');// `Set.prototype.symmetricDifference` method
// https://tc39.es/ecma262/#sec-set.prototype.symmetricdifference
$({target:'Set',proto:true,real:true,forced:FORCED},{symmetricDifference:symmetricDifference});return es_set_symmetricDifference_v2;}var es_set_union_v2={};var setUnion;var hasRequiredSetUnion;function requireSetUnion(){if(hasRequiredSetUnion)return setUnion;hasRequiredSetUnion=1;var aSet=/*@__PURE__*/requireASet();var add=/*@__PURE__*/requireSetHelpers().add;var clone=/*@__PURE__*/requireSetClone();var getSetRecord=/*@__PURE__*/requireGetSetRecord();var iterateSimple=/*@__PURE__*/requireIterateSimple();// `Set.prototype.union` method
// https://tc39.es/ecma262/#sec-set.prototype.union
setUnion=function union(other){var O=aSet(this);var keysIter=getSetRecord(other).getIterator();var result=clone(O);iterateSimple(keysIter,function(it){add(result,it);});return result;};return setUnion;}var hasRequiredEs_set_union_v2;function requireEs_set_union_v2(){if(hasRequiredEs_set_union_v2)return es_set_union_v2;hasRequiredEs_set_union_v2=1;var $=/*@__PURE__*/require_export();var union=/*@__PURE__*/requireSetUnion();var setMethodGetKeysBeforeCloning=/*@__PURE__*/requireSetMethodGetKeysBeforeCloningDetection();var setMethodAcceptSetLike=/*@__PURE__*/requireSetMethodAcceptSetLike();var FORCED=!setMethodAcceptSetLike('union')||!setMethodGetKeysBeforeCloning('union');// `Set.prototype.union` method
// https://tc39.es/ecma262/#sec-set.prototype.union
$({target:'Set',proto:true,real:true,forced:FORCED},{union:union});return es_set_union_v2;}var set$2;var hasRequiredSet$2;function requireSet$2(){if(hasRequiredSet$2)return set$2;hasRequiredSet$2=1;requireEs_array_iterator();requireEs_set();requireEs_set_difference_v2();requireEs_set_intersection_v2();requireEs_set_isDisjointFrom_v2();requireEs_set_isSubsetOf_v2();requireEs_set_isSupersetOf_v2();requireEs_set_symmetricDifference_v2();requireEs_set_union_v2();requireEs_string_iterator();var path=/*@__PURE__*/requirePath();set$2=path.Set;return set$2;}var set$1;var hasRequiredSet$1;function requireSet$1(){if(hasRequiredSet$1)return set$1;hasRequiredSet$1=1;var parent=/*@__PURE__*/requireSet$2();requireWeb_domCollections_iterator();set$1=parent;return set$1;}var set;var hasRequiredSet;function requireSet(){if(hasRequiredSet)return set;hasRequiredSet=1;set=/*@__PURE__*/requireSet$1();return set;}var setExports=requireSet();var _Set=/*@__PURE__*/getDefaultExportFromCjs(setExports);var getIterator_1;var hasRequiredGetIterator$5;function requireGetIterator$5(){if(hasRequiredGetIterator$5)return getIterator_1;hasRequiredGetIterator$5=1;requireEs_array_iterator();requireEs_string_iterator();var getIterator=/*@__PURE__*/requireGetIterator$6();getIterator_1=getIterator;return getIterator_1;}var getIterator$4;var hasRequiredGetIterator$4;function requireGetIterator$4(){if(hasRequiredGetIterator$4)return getIterator$4;hasRequiredGetIterator$4=1;var parent=/*@__PURE__*/requireGetIterator$5();requireWeb_domCollections_iterator();getIterator$4=parent;return getIterator$4;}var getIterator$3;var hasRequiredGetIterator$3;function requireGetIterator$3(){if(hasRequiredGetIterator$3)return getIterator$3;hasRequiredGetIterator$3=1;var parent=/*@__PURE__*/requireGetIterator$4();getIterator$3=parent;return getIterator$3;}var getIterator$2;var hasRequiredGetIterator$2;function requireGetIterator$2(){if(hasRequiredGetIterator$2)return getIterator$2;hasRequiredGetIterator$2=1;var parent=/*@__PURE__*/requireGetIterator$3();getIterator$2=parent;return getIterator$2;}var getIterator$1;var hasRequiredGetIterator$1;function requireGetIterator$1(){if(hasRequiredGetIterator$1)return getIterator$1;hasRequiredGetIterator$1=1;getIterator$1=/*@__PURE__*/requireGetIterator$2();return getIterator$1;}var getIterator;var hasRequiredGetIterator;function requireGetIterator(){if(hasRequiredGetIterator)return getIterator;hasRequiredGetIterator=1;getIterator=/*@__PURE__*/requireGetIterator$1();return getIterator;}var getIteratorExports=requireGetIterator();var _getIterator=/*@__PURE__*/getDefaultExportFromCjs(getIteratorExports);var es_array_sort={};var arraySort;var hasRequiredArraySort;function requireArraySort(){if(hasRequiredArraySort)return arraySort;hasRequiredArraySort=1;var arraySlice=/*@__PURE__*/requireArraySlice();var floor=Math.floor;var sort=function(array,comparefn){var length=array.length;if(length<8){// insertion sort
var i=1;var element,j;while(i<length){j=i;element=array[i];while(j&&comparefn(array[j-1],element)>0){array[j]=array[--j];}if(j!==i++)array[j]=element;}}else {// merge sort
var middle=floor(length/2);var left=sort(arraySlice(array,0,middle),comparefn);var right=sort(arraySlice(array,middle),comparefn);var llength=left.length;var rlength=right.length;var lindex=0;var rindex=0;while(lindex<llength||rindex<rlength){array[lindex+rindex]=lindex<llength&&rindex<rlength?comparefn(left[lindex],right[rindex])<=0?left[lindex++]:right[rindex++]:lindex<llength?left[lindex++]:right[rindex++];}}return array;};arraySort=sort;return arraySort;}var environmentFfVersion;var hasRequiredEnvironmentFfVersion;function requireEnvironmentFfVersion(){if(hasRequiredEnvironmentFfVersion)return environmentFfVersion;hasRequiredEnvironmentFfVersion=1;var userAgent=/*@__PURE__*/requireEnvironmentUserAgent();var firefox=userAgent.match(/firefox\/(\d+)/i);environmentFfVersion=!!firefox&&+firefox[1];return environmentFfVersion;}var environmentIsIeOrEdge;var hasRequiredEnvironmentIsIeOrEdge;function requireEnvironmentIsIeOrEdge(){if(hasRequiredEnvironmentIsIeOrEdge)return environmentIsIeOrEdge;hasRequiredEnvironmentIsIeOrEdge=1;var UA=/*@__PURE__*/requireEnvironmentUserAgent();environmentIsIeOrEdge=/MSIE|Trident/.test(UA);return environmentIsIeOrEdge;}var environmentWebkitVersion;var hasRequiredEnvironmentWebkitVersion;function requireEnvironmentWebkitVersion(){if(hasRequiredEnvironmentWebkitVersion)return environmentWebkitVersion;hasRequiredEnvironmentWebkitVersion=1;var userAgent=/*@__PURE__*/requireEnvironmentUserAgent();var webkit=userAgent.match(/AppleWebKit\/(\d+)\./);environmentWebkitVersion=!!webkit&&+webkit[1];return environmentWebkitVersion;}var hasRequiredEs_array_sort;function requireEs_array_sort(){if(hasRequiredEs_array_sort)return es_array_sort;hasRequiredEs_array_sort=1;var $=/*@__PURE__*/require_export();var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var aCallable=/*@__PURE__*/requireACallable();var toObject=/*@__PURE__*/requireToObject();var lengthOfArrayLike=/*@__PURE__*/requireLengthOfArrayLike();var deletePropertyOrThrow=/*@__PURE__*/requireDeletePropertyOrThrow();var toString=/*@__PURE__*/requireToString();var fails=/*@__PURE__*/requireFails();var internalSort=/*@__PURE__*/requireArraySort();var arrayMethodIsStrict=/*@__PURE__*/requireArrayMethodIsStrict();var FF=/*@__PURE__*/requireEnvironmentFfVersion();var IE_OR_EDGE=/*@__PURE__*/requireEnvironmentIsIeOrEdge();var V8=/*@__PURE__*/requireEnvironmentV8Version();var WEBKIT=/*@__PURE__*/requireEnvironmentWebkitVersion();var test=[];var nativeSort=uncurryThis(test.sort);var push=uncurryThis(test.push);// IE8-
var FAILS_ON_UNDEFINED=fails(function(){test.sort(undefined);});// V8 bug
var FAILS_ON_NULL=fails(function(){test.sort(null);});// Old WebKit
var STRICT_METHOD=arrayMethodIsStrict('sort');var STABLE_SORT=!fails(function(){// feature detection can be too slow, so check engines versions
if(V8)return V8<70;if(FF&&FF>3)return;if(IE_OR_EDGE)return true;if(WEBKIT)return WEBKIT<603;var result='';var code,chr,value,index;// generate an array with more 512 elements (Chakra and old V8 fails only in this case)
for(code=65;code<76;code++){chr=String.fromCharCode(code);switch(code){case 66:case 69:case 70:case 72:value=3;break;case 68:case 71:value=4;break;default:value=2;}for(index=0;index<47;index++){test.push({k:chr+index,v:value});}}test.sort(function(a,b){return b.v-a.v;});for(index=0;index<test.length;index++){chr=test[index].k.charAt(0);if(result.charAt(result.length-1)!==chr)result+=chr;}return result!=='DGBEFHACIJK';});var FORCED=FAILS_ON_UNDEFINED||!FAILS_ON_NULL||!STRICT_METHOD||!STABLE_SORT;var getSortCompare=function(comparefn){return function(x,y){if(y===undefined)return  -1;if(x===undefined)return 1;if(comparefn!==undefined)return +comparefn(x,y)||0;return toString(x)>toString(y)?1:-1;};};// `Array.prototype.sort` method
// https://tc39.es/ecma262/#sec-array.prototype.sort
$({target:'Array',proto:true,forced:FORCED},{sort:function sort(comparefn){if(comparefn!==undefined)aCallable(comparefn);var array=toObject(this);if(STABLE_SORT)return comparefn===undefined?nativeSort(array):nativeSort(array,comparefn);var items=[];var arrayLength=lengthOfArrayLike(array);var itemsLength,index;for(index=0;index<arrayLength;index++){if(index in array)push(items,array[index]);}internalSort(items,getSortCompare(comparefn));itemsLength=lengthOfArrayLike(items);index=0;while(index<itemsLength)array[index]=items[index++];while(index<arrayLength)deletePropertyOrThrow(array,index++);return array;}});return es_array_sort;}var sort$3;var hasRequiredSort$3;function requireSort$3(){if(hasRequiredSort$3)return sort$3;hasRequiredSort$3=1;requireEs_array_sort();var getBuiltInPrototypeMethod=/*@__PURE__*/requireGetBuiltInPrototypeMethod();sort$3=getBuiltInPrototypeMethod('Array','sort');return sort$3;}var sort$2;var hasRequiredSort$2;function requireSort$2(){if(hasRequiredSort$2)return sort$2;hasRequiredSort$2=1;var isPrototypeOf=/*@__PURE__*/requireObjectIsPrototypeOf();var method=/*@__PURE__*/requireSort$3();var ArrayPrototype=Array.prototype;sort$2=function(it){var own=it.sort;return it===ArrayPrototype||isPrototypeOf(ArrayPrototype,it)&&own===ArrayPrototype.sort?method:own;};return sort$2;}var sort$1;var hasRequiredSort$1;function requireSort$1(){if(hasRequiredSort$1)return sort$1;hasRequiredSort$1=1;var parent=/*@__PURE__*/requireSort$2();sort$1=parent;return sort$1;}var sort;var hasRequiredSort;function requireSort(){if(hasRequiredSort)return sort;hasRequiredSort=1;sort=/*@__PURE__*/requireSort$1();return sort;}var sortExports=requireSort();var _sortInstanceProperty=/*@__PURE__*/getDefaultExportFromCjs(sortExports);var keys$3;var hasRequiredKeys$3;function requireKeys$3(){if(hasRequiredKeys$3)return keys$3;hasRequiredKeys$3=1;requireEs_array_iterator();var getBuiltInPrototypeMethod=/*@__PURE__*/requireGetBuiltInPrototypeMethod();keys$3=getBuiltInPrototypeMethod('Array','keys');return keys$3;}var keys$2;var hasRequiredKeys$2;function requireKeys$2(){if(hasRequiredKeys$2)return keys$2;hasRequiredKeys$2=1;var parent=/*@__PURE__*/requireKeys$3();keys$2=parent;return keys$2;}var keys$1;var hasRequiredKeys$1;function requireKeys$1(){if(hasRequiredKeys$1)return keys$1;hasRequiredKeys$1=1;requireWeb_domCollections_iterator();var classof=/*@__PURE__*/requireClassof();var hasOwn=/*@__PURE__*/requireHasOwnProperty();var isPrototypeOf=/*@__PURE__*/requireObjectIsPrototypeOf();var method=/*@__PURE__*/requireKeys$2();var ArrayPrototype=Array.prototype;var DOMIterables={DOMTokenList:true,NodeList:true};keys$1=function(it){var own=it.keys;return it===ArrayPrototype||isPrototypeOf(ArrayPrototype,it)&&own===ArrayPrototype.keys||hasOwn(DOMIterables,classof(it))?method:own;};return keys$1;}var keys;var hasRequiredKeys;function requireKeys(){if(hasRequiredKeys)return keys;hasRequiredKeys=1;keys=/*@__PURE__*/requireKeys$1();return keys;}var keysExports=requireKeys();var _keysInstanceProperty=/*@__PURE__*/getDefaultExportFromCjs(keysExports);var values$3;var hasRequiredValues$3;function requireValues$3(){if(hasRequiredValues$3)return values$3;hasRequiredValues$3=1;requireEs_array_iterator();var getBuiltInPrototypeMethod=/*@__PURE__*/requireGetBuiltInPrototypeMethod();values$3=getBuiltInPrototypeMethod('Array','values');return values$3;}var values$2;var hasRequiredValues$2;function requireValues$2(){if(hasRequiredValues$2)return values$2;hasRequiredValues$2=1;var parent=/*@__PURE__*/requireValues$3();values$2=parent;return values$2;}var values$1;var hasRequiredValues$1;function requireValues$1(){if(hasRequiredValues$1)return values$1;hasRequiredValues$1=1;requireWeb_domCollections_iterator();var classof=/*@__PURE__*/requireClassof();var hasOwn=/*@__PURE__*/requireHasOwnProperty();var isPrototypeOf=/*@__PURE__*/requireObjectIsPrototypeOf();var method=/*@__PURE__*/requireValues$2();var ArrayPrototype=Array.prototype;var DOMIterables={DOMTokenList:true,NodeList:true};values$1=function(it){var own=it.values;return it===ArrayPrototype||isPrototypeOf(ArrayPrototype,it)&&own===ArrayPrototype.values||hasOwn(DOMIterables,classof(it))?method:own;};return values$1;}var values;var hasRequiredValues;function requireValues(){if(hasRequiredValues)return values;hasRequiredValues=1;values=/*@__PURE__*/requireValues$1();return values;}var valuesExports=requireValues();var _valuesInstanceProperty=/*@__PURE__*/getDefaultExportFromCjs(valuesExports);var entries$3;var hasRequiredEntries$3;function requireEntries$3(){if(hasRequiredEntries$3)return entries$3;hasRequiredEntries$3=1;requireEs_array_iterator();var getBuiltInPrototypeMethod=/*@__PURE__*/requireGetBuiltInPrototypeMethod();entries$3=getBuiltInPrototypeMethod('Array','entries');return entries$3;}var entries$2;var hasRequiredEntries$2;function requireEntries$2(){if(hasRequiredEntries$2)return entries$2;hasRequiredEntries$2=1;var parent=/*@__PURE__*/requireEntries$3();entries$2=parent;return entries$2;}var entries$1;var hasRequiredEntries$1;function requireEntries$1(){if(hasRequiredEntries$1)return entries$1;hasRequiredEntries$1=1;requireWeb_domCollections_iterator();var classof=/*@__PURE__*/requireClassof();var hasOwn=/*@__PURE__*/requireHasOwnProperty();var isPrototypeOf=/*@__PURE__*/requireObjectIsPrototypeOf();var method=/*@__PURE__*/requireEntries$2();var ArrayPrototype=Array.prototype;var DOMIterables={DOMTokenList:true,NodeList:true};entries$1=function(it){var own=it.entries;return it===ArrayPrototype||isPrototypeOf(ArrayPrototype,it)&&own===ArrayPrototype.entries||hasOwn(DOMIterables,classof(it))?method:own;};return entries$1;}var entries;var hasRequiredEntries;function requireEntries(){if(hasRequiredEntries)return entries;hasRequiredEntries=1;entries=/*@__PURE__*/requireEntries$1();return entries;}var entriesExports=requireEntries();var _entriesInstanceProperty=/*@__PURE__*/getDefaultExportFromCjs(entriesExports);var defineProperty;var hasRequiredDefineProperty;function requireDefineProperty(){if(hasRequiredDefineProperty)return defineProperty;hasRequiredDefineProperty=1;defineProperty=/*@__PURE__*/requireDefineProperty$4();return defineProperty;}var definePropertyExports=requireDefineProperty();var _Object$defineProperty=/*@__PURE__*/getDefaultExportFromCjs(definePropertyExports);const byteToHex=[];for(let i=0;i<256;++i){byteToHex.push((i+0x100).toString(16).slice(1));}function unsafeStringify(arr,offset=0){return (byteToHex[arr[offset+0]]+byteToHex[arr[offset+1]]+byteToHex[arr[offset+2]]+byteToHex[arr[offset+3]]+'-'+byteToHex[arr[offset+4]]+byteToHex[arr[offset+5]]+'-'+byteToHex[arr[offset+6]]+byteToHex[arr[offset+7]]+'-'+byteToHex[arr[offset+8]]+byteToHex[arr[offset+9]]+'-'+byteToHex[arr[offset+10]]+byteToHex[arr[offset+11]]+byteToHex[arr[offset+12]]+byteToHex[arr[offset+13]]+byteToHex[arr[offset+14]]+byteToHex[arr[offset+15]]).toLowerCase();}const rnds8=new Uint8Array(16);function rng(){return crypto.getRandomValues(rnds8);}function v4(options,buf,offset){if(crypto.randomUUID){return crypto.randomUUID();}return _v4(options);}function _v4(options,buf,offset){options=options||{};const rnds=options.random??options.rng?.()??rng();if(rnds.length<16){throw new Error('Random bytes length must be >= 16');}rnds[6]=rnds[6]&0x0f|0x40;rnds[8]=rnds[8]&0x3f|0x80;return unsafeStringify(rnds);}function ownKeys$4(e,r){var t=_Object$keys(e);if(_Object$getOwnPropertySymbols){var o=_Object$getOwnPropertySymbols(e);r&&(o=_filterInstanceProperty(o).call(o,function(r){return _Object$getOwnPropertyDescriptor(e,r).enumerable;})),t.push.apply(t,o);}return t;}function _objectSpread$4(e){for(var r=1;r<arguments.length;r++){var _context21,_context22;var t=null!=arguments[r]?arguments[r]:{};r%2?_forEachInstanceProperty(_context21=ownKeys$4(Object(t),true)).call(_context21,function(r){_defineProperty(e,r,t[r]);}):_Object$getOwnPropertyDescriptors?_Object$defineProperties(e,_Object$getOwnPropertyDescriptors(t)):_forEachInstanceProperty(_context22=ownKeys$4(Object(t))).call(_context22,function(r){_Object$defineProperty(e,r,_Object$getOwnPropertyDescriptor(t,r));});}return e;}/**
 * Determine whether a value can be used as an id.
 * @param value - Input value of unknown type.
 * @returns True if the value is valid id, false otherwise.
 */function isId(value){return typeof value==="string"||typeof value==="number";}/**
 * A queue.
 * @typeParam T - The type of method names to be replaced by queued versions.
 */class Queue{/**
   * Construct a new Queue.
   * @param options - Queue configuration.
   */constructor(options){/** Delay in milliseconds. If defined the queue will be periodically flushed. */_defineProperty(this,"delay",void 0);/** Maximum number of entries in the queue before it will be flushed. */_defineProperty(this,"max",void 0);_defineProperty(this,"_queue",[]);_defineProperty(this,"_timeout",null);_defineProperty(this,"_extended",null);// options
this.delay=null;this.max=Infinity;this.setOptions(options);}/**
   * Update the configuration of the queue.
   * @param options - Queue configuration.
   */setOptions(options){if(options&&typeof options.delay!=="undefined"){this.delay=options.delay;}if(options&&typeof options.max!=="undefined"){this.max=options.max;}this._flushIfNeeded();}/**
   * Extend an object with queuing functionality.
   * The object will be extended with a function flush, and the methods provided in options.replace will be replaced with queued ones.
   * @param object - The object to be extended.
   * @param options - Additional options.
   * @returns The created queue.
   */static extend(object,options){const queue=new Queue(options);if(object.flush!==undefined){throw new Error("Target object already has a property flush");}object.flush=()=>{queue.flush();};const methods=[{name:"flush",original:undefined}];if(options&&options.replace){for(let i=0;i<options.replace.length;i++){const name=options.replace[i];methods.push({name:name,// @TODO: better solution?
original:object[name]});// @TODO: better solution?
queue.replace(object,name);}}queue._extended={object:object,methods:methods};return queue;}/**
   * Destroy the queue. The queue will first flush all queued actions, and in case it has extended an object, will restore the original object.
   */destroy(){this.flush();if(this._extended){const object=this._extended.object;const methods=this._extended.methods;for(let i=0;i<methods.length;i++){const method=methods[i];if(method.original){// @TODO: better solution?
object[method.name]=method.original;}else {// @TODO: better solution?
delete object[method.name];}}this._extended=null;}}/**
   * Replace a method on an object with a queued version.
   * @param object - Object having the method.
   * @param method - The method name.
   */replace(object,method){/* eslint-disable-next-line @typescript-eslint/no-this-alias -- Function this is necessary in the function bellow, so class this has to be saved into a variable here. */const me=this;const original=object[method];if(!original){throw new Error("Method "+method+" undefined");}object[method]=function(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}// add this call to the queue
me.queue({args:args,fn:original,context:this});};}/**
   * Queue a call.
   * @param entry - The function or entry to be queued.
   */queue(entry){if(typeof entry==="function"){this._queue.push({fn:entry});}else {this._queue.push(entry);}this._flushIfNeeded();}/**
   * Check whether the queue needs to be flushed.
   */_flushIfNeeded(){// flush when the maximum is exceeded.
if(this._queue.length>this.max){this.flush();}// flush after a period of inactivity when a delay is configured
if(this._timeout!=null){clearTimeout(this._timeout);this._timeout=null;}if(this.queue.length>0&&typeof this.delay==="number"){this._timeout=_setTimeout(()=>{this.flush();},this.delay);}}/**
   * Flush all queued calls
   */flush(){var _context5,_context6;_forEachInstanceProperty(_context5=_spliceInstanceProperty(_context6=this._queue).call(_context6,0)).call(_context5,entry=>{entry.fn.apply(entry.context||entry.fn,entry.args||[]);});}}/**
 * {@link DataSet} code that can be reused in {@link DataView} or other similar implementations of {@link DataInterface}.
 * @typeParam Item - Item type that may or may not have an id.
 * @typeParam IdProp - Name of the property that contains the id.
 */class DataSetPart{constructor(){_defineProperty(this,"_subscribers",{"*":[],add:[],remove:[],update:[]});/**
     * @deprecated Use on instead (PS: DataView.subscribe === DataView.on).
     */_defineProperty(this,"subscribe",DataSetPart.prototype.on);/**
     * @deprecated Use off instead (PS: DataView.unsubscribe === DataView.off).
     */_defineProperty(this,"unsubscribe",DataSetPart.prototype.off);}/**
   * Trigger an event
   * @param event - Event name.
   * @param payload - Event payload.
   * @param senderId - Id of the sender.
   */_trigger(event,payload,senderId){var _context7;if(event==="*"){throw new Error("Cannot trigger event *");}_forEachInstanceProperty(_context7=[...this._subscribers[event],...this._subscribers["*"]]).call(_context7,subscriber=>{subscriber(event,payload,senderId!=null?senderId:null);});}/**
   * Subscribe to an event, add an event listener.
   * @remarks Non-function callbacks are ignored.
   * @param event - Event name.
   * @param callback - Callback method.
   */on(event,callback){if(typeof callback==="function"){this._subscribers[event].push(callback);}// @TODO: Maybe throw for invalid callbacks?
}/**
   * Unsubscribe from an event, remove an event listener.
   * @remarks If the same callback was subscribed more than once **all** occurences will be removed.
   * @param event - Event name.
   * @param callback - Callback method.
   */off(event,callback){var _context8;this._subscribers[event]=_filterInstanceProperty(_context8=this._subscribers[event]).call(_context8,subscriber=>subscriber!==callback);}}/**
 * Data stream
 * @remarks
 * {@link DataStream} offers an always up to date stream of items from a {@link DataSet} or {@link DataView}.
 * That means that the stream is evaluated at the time of iteration, conversion to another data type or when {@link cache} is called, not when the {@link DataStream} was created.
 * Multiple invocations of for example {@link toItemArray} may yield different results (if the data source like for example {@link DataSet} gets modified).
 * @typeParam Item - The item type this stream is going to work with.
 */class DataStream{/**
   * Create a new data stream.
   * @param pairs - The id, item pairs.
   */constructor(pairs){_defineProperty(this,"_pairs",void 0);this._pairs=pairs;}/**
   * Return an iterable of key, value pairs for every entry in the stream.
   */*[_Symbol$iterator](){for(const[id,item]of this._pairs){yield [id,item];}}/**
   * Return an iterable of key, value pairs for every entry in the stream.
   */*entries(){for(const[id,item]of this._pairs){yield [id,item];}}/**
   * Return an iterable of keys in the stream.
   */*keys(){for(const[id]of this._pairs){yield id;}}/**
   * Return an iterable of values in the stream.
   */*values(){for(const[,item]of this._pairs){yield item;}}/**
   * Return an array containing all the ids in this stream.
   * @remarks
   * The array may contain duplicities.
   * @returns The array with all ids from this stream.
   */toIdArray(){var _context9;return _mapInstanceProperty(_context9=[...this._pairs]).call(_context9,pair=>pair[0]);}/**
   * Return an array containing all the items in this stream.
   * @remarks
   * The array may contain duplicities.
   * @returns The array with all items from this stream.
   */toItemArray(){var _context0;return _mapInstanceProperty(_context0=[...this._pairs]).call(_context0,pair=>pair[1]);}/**
   * Return an array containing all the entries in this stream.
   * @remarks
   * The array may contain duplicities.
   * @returns The array with all entries from this stream.
   */toEntryArray(){return [...this._pairs];}/**
   * Return an object map containing all the items in this stream accessible by ids.
   * @remarks
   * In case of duplicate ids (coerced to string so `7 == '7'`) the last encoutered appears in the returned object.
   * @returns The object map of all id → item pairs from this stream.
   */toObjectMap(){const map=_Object$create(null);for(const[id,item]of this._pairs){map[id]=item;}return map;}/**
   * Return a map containing all the items in this stream accessible by ids.
   * @returns The map of all id → item pairs from this stream.
   */toMap(){return new _Map(this._pairs);}/**
   * Return a set containing all the (unique) ids in this stream.
   * @returns The set of all ids from this stream.
   */toIdSet(){return new _Set(this.toIdArray());}/**
   * Return a set containing all the (unique) items in this stream.
   * @returns The set of all items from this stream.
   */toItemSet(){return new _Set(this.toItemArray());}/**
   * Cache the items from this stream.
   * @remarks
   * This method allows for items to be fetched immediatelly and used (possibly multiple times) later.
   * It can also be used to optimize performance as {@link DataStream} would otherwise reevaluate everything upon each iteration.
   *
   * ## Example
   * ```javascript
   * const ds = new DataSet([…])
   *
   * const cachedStream = ds.stream()
   *   .filter(…)
   *   .sort(…)
   *   .map(…)
   *   .cached(…) // Data are fetched, processed and cached here.
   *
   * ds.clear()
   * chachedStream // Still has all the items.
   * ```
   * @returns A new {@link DataStream} with cached items (detached from the original {@link DataSet}).
   */cache(){return new DataStream([...this._pairs]);}/**
   * Get the distinct values of given property.
   * @param callback - The function that picks and possibly converts the property.
   * @typeParam T - The type of the distinct value.
   * @returns A set of all distinct properties.
   */distinct(callback){const set=new _Set();for(const[id,item]of this._pairs){set.add(callback(item,id));}return set;}/**
   * Filter the items of the stream.
   * @param callback - The function that decides whether an item will be included.
   * @returns A new data stream with the filtered items.
   */filter(callback){const pairs=this._pairs;return new DataStream({*[_Symbol$iterator](){for(const[id,item]of pairs){if(callback(item,id)){yield [id,item];}}}});}/**
   * Execute a callback for each item of the stream.
   * @param callback - The function that will be invoked for each item.
   */forEach(callback){for(const[id,item]of this._pairs){callback(item,id);}}/**
   * Map the items into a different type.
   * @param callback - The function that does the conversion.
   * @typeParam Mapped - The type of the item after mapping.
   * @returns A new data stream with the mapped items.
   */map(callback){const pairs=this._pairs;return new DataStream({*[_Symbol$iterator](){for(const[id,item]of pairs){yield [id,callback(item,id)];}}});}/**
   * Get the item with the maximum value of given property.
   * @param callback - The function that picks and possibly converts the property.
   * @returns The item with the maximum if found otherwise null.
   */max(callback){const iter=_getIterator(this._pairs);let curr=iter.next();if(curr.done){return null;}let maxItem=curr.value[1];let maxValue=callback(curr.value[1],curr.value[0]);while(!(curr=iter.next()).done){const[id,item]=curr.value;const value=callback(item,id);if(value>maxValue){maxValue=value;maxItem=item;}}return maxItem;}/**
   * Get the item with the minimum value of given property.
   * @param callback - The function that picks and possibly converts the property.
   * @returns The item with the minimum if found otherwise null.
   */min(callback){const iter=_getIterator(this._pairs);let curr=iter.next();if(curr.done){return null;}let minItem=curr.value[1];let minValue=callback(curr.value[1],curr.value[0]);while(!(curr=iter.next()).done){const[id,item]=curr.value;const value=callback(item,id);if(value<minValue){minValue=value;minItem=item;}}return minItem;}/**
   * Reduce the items into a single value.
   * @param callback - The function that does the reduction.
   * @param accumulator - The initial value of the accumulator.
   * @typeParam T - The type of the accumulated value.
   * @returns The reduced value.
   */reduce(callback,accumulator){for(const[id,item]of this._pairs){accumulator=callback(accumulator,item,id);}return accumulator;}/**
   * Sort the items.
   * @param callback - Item comparator.
   * @returns A new stream with sorted items.
   */sort(callback){return new DataStream({[_Symbol$iterator]:()=>{var _context1;return _getIterator(_sortInstanceProperty(_context1=[...this._pairs]).call(_context1,(_ref,_ref2)=>{let[idA,itemA]=_ref;let[idB,itemB]=_ref2;return callback(itemA,itemB,idA,idB);}));}});}}/**
 * Add an id to given item if it doesn't have one already.
 * @remarks
 * The item will be modified.
 * @param item - The item that will have an id after a call to this function.
 * @param idProp - The key of the id property.
 * @typeParam Item - Item type that may or may not have an id.
 * @typeParam IdProp - Name of the property that contains the id.
 * @returns true
 */function ensureFullItem(item,idProp){if(item[idProp]==null){// generate an id
item[idProp]=v4();}return item;}/**
 * # DataSet
 *
 * Vis.js comes with a flexible DataSet, which can be used to hold and
 * manipulate unstructured data and listen for changes in the data. The DataSet
 * is key/value based. Data items can be added, updated and removed from the
 * DataSet, and one can subscribe to changes in the DataSet. The data in the
 * DataSet can be filtered and ordered. Data can be normalized when appending it
 * to the DataSet as well.
 *
 * ## Example
 *
 * The following example shows how to use a DataSet.
 *
 * ```javascript
 * // create a DataSet
 * var options = {};
 * var data = new vis.DataSet(options);
 *
 * // add items
 * // note that the data items can contain different properties and data formats
 * data.add([
 * {id: 1, text: 'item 1', date: new Date(2013, 6, 20), group: 1, first: true},
 * {id: 2, text: 'item 2', date: '2013-06-23', group: 2},
 * {id: 3, text: 'item 3', date: '2013-06-25', group: 2},
 * {id: 4, text: 'item 4'}
 * ]);
 *
 * // subscribe to any change in the DataSet
 * data.on('*', function (event, properties, senderId) {
 * console.log('event', event, properties);
 * });
 *
 * // update an existing item
 * data.update({id: 2, group: 1});
 *
 * // remove an item
 * data.remove(4);
 *
 * // get all ids
 * var ids = data.getIds();
 * console.log('ids', ids);
 *
 * // get a specific item
 * var item1 = data.get(1);
 * console.log('item1', item1);
 *
 * // retrieve a filtered subset of the data
 * var items = data.get({
 * filter: function (item) {
 * return item.group == 1;
 * }
 * });
 * console.log('filtered items', items);
 * ```
 * @typeParam Item - Item type that may or may not have an id.
 * @typeParam IdProp - Name of the property that contains the id.
 */class DataSet extends DataSetPart{/** @inheritDoc */get idProp(){return this._idProp;}/**
   * Construct a new DataSet.
   * @param data - Initial data or options.
   * @param options - Options (type error if data is also options).
   */constructor(data,options){super();// correctly read optional arguments
/** Flush all queued calls. */_defineProperty(this,"flush",void 0);/** @inheritDoc */_defineProperty(this,"length",void 0);_defineProperty(this,"_options",void 0);_defineProperty(this,"_data",void 0);_defineProperty(this,"_idProp",void 0);_defineProperty(this,"_queue",null);if(data&&!_Array$isArray(data)){options=data;data=[];}this._options=options||{};this._data=new _Map();// map with data indexed by id
this.length=0;// number of items in the DataSet
this._idProp=this._options.fieldId||"id";// name of the field containing id
// add initial data when provided
if(data&&data.length){this.add(data);}this.setOptions(options);}/**
   * Set new options.
   * @param options - The new options.
   */setOptions(options){if(options&&options.queue!==undefined){if(options.queue===false){// delete queue if loaded
if(this._queue){this._queue.destroy();this._queue=null;}}else {// create queue and update its options
if(!this._queue){this._queue=Queue.extend(this,{replace:["add","update","remove"]});}if(options.queue&&typeof options.queue==="object"){this._queue.setOptions(options.queue);}}}}/**
   * Add a data item or an array with items.
   *
   * After the items are added to the DataSet, the DataSet will trigger an event `add`. When a `senderId` is provided, this id will be passed with the triggered event to all subscribers.
   *
   * ## Example
   *
   * ```javascript
   * // create a DataSet
   * const data = new vis.DataSet()
   *
   * // add items
   * const ids = data.add([
   * { id: 1, text: 'item 1' },
   * { id: 2, text: 'item 2' },
   * { text: 'item without an id' }
   * ])
   *
   * console.log(ids) // [1, 2, '<UUIDv4>']
   * ```
   * @param data - Items to be added (ids will be generated if missing).
   * @param senderId - Sender id.
   * @returns addedIds - Array with the ids (generated if not present) of the added items.
   * @throws When an item with the same id as any of the added items already exists.
   */add(data,senderId){const addedIds=[];let id;if(_Array$isArray(data)){// Array
const idsToAdd=_mapInstanceProperty(data).call(data,d=>d[this._idProp]);if(_someInstanceProperty(idsToAdd).call(idsToAdd,id=>this._data.has(id))){throw new Error("A duplicate id was found in the parameter array.");}for(let i=0,len=data.length;i<len;i++){id=this._addItem(data[i]);addedIds.push(id);}}else if(data&&typeof data==="object"){// Single item
id=this._addItem(data);addedIds.push(id);}else {throw new Error("Unknown dataType");}if(addedIds.length){this._trigger("add",{items:addedIds},senderId);}return addedIds;}/**
   * Update existing items. When an item does not exist, it will be created.
   * @remarks
   * The provided properties will be merged in the existing item. When an item does not exist, it will be created.
   *
   * After the items are updated, the DataSet will trigger an event `add` for the added items, and an event `update`. When a `senderId` is provided, this id will be passed with the triggered event to all subscribers.
   *
   * ## Example
   *
   * ```javascript
   * // create a DataSet
   * const data = new vis.DataSet([
   *   { id: 1, text: 'item 1' },
   *   { id: 2, text: 'item 2' },
   *   { id: 3, text: 'item 3' }
   * ])
   *
   * // update items
   * const ids = data.update([
   *   { id: 2, text: 'item 2 (updated)' },
   *   { id: 4, text: 'item 4 (new)' }
   * ])
   *
   * console.log(ids) // [2, 4]
   * ```
   *
   * ## Warning for TypeScript users
   * This method may introduce partial items into the data set. Use add or updateOnly instead for better type safety.
   * @param data - Items to be updated (if the id is already present) or added (if the id is missing).
   * @param senderId - Sender id.
   * @returns updatedIds - The ids of the added (these may be newly generated if there was no id in the item from the data) or updated items.
   * @throws When the supplied data is neither an item nor an array of items.
   */update(data,senderId){const addedIds=[];const updatedIds=[];const oldData=[];const updatedData=[];const idProp=this._idProp;const addOrUpdate=item=>{const origId=item[idProp];if(origId!=null&&this._data.has(origId)){const fullItem=item;// it has an id, therefore it is a fullitem
const oldItem=_Object$assign({},this._data.get(origId));// update item
const id=this._updateItem(fullItem);updatedIds.push(id);updatedData.push(fullItem);oldData.push(oldItem);}else {// add new item
const id=this._addItem(item);addedIds.push(id);}};if(_Array$isArray(data)){// Array
for(let i=0,len=data.length;i<len;i++){if(data[i]&&typeof data[i]==="object"){addOrUpdate(data[i]);}else {console.warn("Ignoring input item, which is not an object at index "+i);}}}else if(data&&typeof data==="object"){// Single item
addOrUpdate(data);}else {throw new Error("Unknown dataType");}if(addedIds.length){this._trigger("add",{items:addedIds},senderId);}if(updatedIds.length){const props={items:updatedIds,oldData:oldData,data:updatedData};// TODO: remove deprecated property 'data' some day
//Object.defineProperty(props, 'data', {
//  'get': (function() {
//    console.warn('Property data is deprecated. Use DataSet.get(ids) to retrieve the new data, use the oldData property on this object to get the old data');
//    return updatedData;
//  }).bind(this)
//});
this._trigger("update",props,senderId);}return _concatInstanceProperty(addedIds).call(addedIds,updatedIds);}/**
   * Update existing items. When an item does not exist, an error will be thrown.
   * @remarks
   * The provided properties will be deeply merged into the existing item.
   * When an item does not exist (id not present in the data set or absent), an error will be thrown and nothing will be changed.
   *
   * After the items are updated, the DataSet will trigger an event `update`.
   * When a `senderId` is provided, this id will be passed with the triggered event to all subscribers.
   *
   * ## Example
   *
   * ```javascript
   * // create a DataSet
   * const data = new vis.DataSet([
   *   { id: 1, text: 'item 1' },
   *   { id: 2, text: 'item 2' },
   *   { id: 3, text: 'item 3' },
   * ])
   *
   * // update items
   * const ids = data.update([
   *   { id: 2, text: 'item 2 (updated)' }, // works
   *   // { id: 4, text: 'item 4 (new)' }, // would throw
   *   // { text: 'item 4 (new)' }, // would also throw
   * ])
   *
   * console.log(ids) // [2]
   * ```
   * @param data - Updates (the id and optionally other props) to the items in this data set.
   * @param senderId - Sender id.
   * @returns updatedIds - The ids of the updated items.
   * @throws When the supplied data is neither an item nor an array of items, when the ids are missing.
   */updateOnly(data,senderId){var _context10;if(!_Array$isArray(data)){data=[data];}const updateEventData=_mapInstanceProperty(_context10=_mapInstanceProperty(data).call(data,update=>{const oldData=this._data.get(update[this._idProp]);if(oldData==null){throw new Error("Updating non-existent items is not allowed.");}return {oldData,update};})).call(_context10,_ref3=>{let{oldData,update}=_ref3;const id=oldData[this._idProp];const updatedData=pureDeepObjectAssign(oldData,update);this._data.set(id,updatedData);return {id,oldData:oldData,updatedData};});if(updateEventData.length){const props={items:_mapInstanceProperty(updateEventData).call(updateEventData,value=>value.id),oldData:_mapInstanceProperty(updateEventData).call(updateEventData,value=>value.oldData),data:_mapInstanceProperty(updateEventData).call(updateEventData,value=>value.updatedData)};// TODO: remove deprecated property 'data' some day
//Object.defineProperty(props, 'data', {
//  'get': (function() {
//    console.warn('Property data is deprecated. Use DataSet.get(ids) to retrieve the new data, use the oldData property on this object to get the old data');
//    return updatedData;
//  }).bind(this)
//});
this._trigger("update",props,senderId);return props.items;}else {return [];}}/** @inheritDoc */get(first,second){// @TODO: Woudn't it be better to split this into multiple methods?
// parse the arguments
let id=undefined;let ids=undefined;let options=undefined;if(isId(first)){// get(id [, options])
id=first;options=second;}else if(_Array$isArray(first)){// get(ids [, options])
ids=first;options=second;}else {// get([, options])
options=first;}// determine the return type
const returnType=options&&options.returnType==="Object"?"Object":"Array";// @TODO: WTF is this? Or am I missing something?
// var returnType
// if (options && options.returnType) {
//   var allowedValues = ['Array', 'Object']
//   returnType =
//     allowedValues.indexOf(options.returnType) == -1
//       ? 'Array'
//       : options.returnType
// } else {
//   returnType = 'Array'
// }
// build options
const filter=options&&_filterInstanceProperty(options);const items=[];let item=undefined;let itemIds=undefined;let itemId=undefined;// convert items
if(id!=null){// return a single item
item=this._data.get(id);if(item&&filter&&!filter(item)){item=undefined;}}else if(ids!=null){// return a subset of items
for(let i=0,len=ids.length;i<len;i++){item=this._data.get(ids[i]);if(item!=null&&(!filter||filter(item))){items.push(item);}}}else {var _context11;// return all items
itemIds=[..._keysInstanceProperty(_context11=this._data).call(_context11)];for(let i=0,len=itemIds.length;i<len;i++){itemId=itemIds[i];item=this._data.get(itemId);if(item!=null&&(!filter||filter(item))){items.push(item);}}}// order the results
if(options&&options.order&&id==undefined){this._sort(items,options.order);}// filter fields of the items
if(options&&options.fields){const fields=options.fields;if(id!=undefined&&item!=null){item=this._filterFields(item,fields);}else {for(let i=0,len=items.length;i<len;i++){items[i]=this._filterFields(items[i],fields);}}}// return the results
if(returnType=="Object"){const result={};for(let i=0,len=items.length;i<len;i++){const resultant=items[i];// @TODO: Shoudn't this be this._fieldId?
// result[resultant.id] = resultant
const id=resultant[this._idProp];result[id]=resultant;}return result;}else {if(id!=null){// a single item
return item!==null&&item!==void 0?item:null;}else {// just return our array
return items;}}}/** @inheritDoc */getIds(options){const data=this._data;const filter=options&&_filterInstanceProperty(options);const order=options&&options.order;const itemIds=[..._keysInstanceProperty(data).call(data)];const ids=[];if(filter){// get filtered items
if(order){// create ordered list
const items=[];for(let i=0,len=itemIds.length;i<len;i++){const id=itemIds[i];const item=this._data.get(id);if(item!=null&&filter(item)){items.push(item);}}this._sort(items,order);for(let i=0,len=items.length;i<len;i++){ids.push(items[i][this._idProp]);}}else {// create unordered list
for(let i=0,len=itemIds.length;i<len;i++){const id=itemIds[i];const item=this._data.get(id);if(item!=null&&filter(item)){ids.push(item[this._idProp]);}}}}else {// get all items
if(order){// create an ordered list
const items=[];for(let i=0,len=itemIds.length;i<len;i++){const id=itemIds[i];items.push(data.get(id));}this._sort(items,order);for(let i=0,len=items.length;i<len;i++){ids.push(items[i][this._idProp]);}}else {// create unordered list
for(let i=0,len=itemIds.length;i<len;i++){const id=itemIds[i];const item=data.get(id);if(item!=null){ids.push(item[this._idProp]);}}}}return ids;}/** @inheritDoc */getDataSet(){return this;}/** @inheritDoc */forEach(callback,options){const filter=options&&_filterInstanceProperty(options);const data=this._data;const itemIds=[..._keysInstanceProperty(data).call(data)];if(options&&options.order){// execute forEach on ordered list
const items=this.get(options);for(let i=0,len=items.length;i<len;i++){const item=items[i];const id=item[this._idProp];callback(item,id);}}else {// unordered
for(let i=0,len=itemIds.length;i<len;i++){const id=itemIds[i];const item=this._data.get(id);if(item!=null&&(!filter||filter(item))){callback(item,id);}}}}/** @inheritDoc */map(callback,options){const filter=options&&_filterInstanceProperty(options);const mappedItems=[];const data=this._data;const itemIds=[..._keysInstanceProperty(data).call(data)];// convert and filter items
for(let i=0,len=itemIds.length;i<len;i++){const id=itemIds[i];const item=this._data.get(id);if(item!=null&&(!filter||filter(item))){mappedItems.push(callback(item,id));}}// order items
if(options&&options.order){this._sort(mappedItems,options.order);}return mappedItems;}/**
   * Filter the fields of an item.
   * @param item - The item whose fields should be filtered.
   * @param fields - The names of the fields that will be kept.
   * @typeParam K - Field name type.
   * @returns The item without any additional fields.
   */_filterFields(item,fields){var _context12;if(!item){// item is null
return item;}return _reduceInstanceProperty(_context12=_Array$isArray(fields)?// Use the supplied array
fields:// Use the keys of the supplied object
_Object$keys(fields)).call(_context12,(filteredItem,field)=>{filteredItem[field]=item[field];return filteredItem;},{});}/**
   * Sort the provided array with items.
   * @param items - Items to be sorted in place.
   * @param order - A field name or custom sort function.
   * @typeParam T - The type of the items in the items array.
   */_sort(items,order){if(typeof order==="string"){// order by provided field name
const name=order;// field name
_sortInstanceProperty(items).call(items,(a,b)=>{// @TODO: How to treat missing properties?
const av=a[name];const bv=b[name];return av>bv?1:av<bv?-1:0;});}else if(typeof order==="function"){// order by sort function
_sortInstanceProperty(items).call(items,order);}else {// TODO: extend order by an Object {field:string, direction:string}
//       where direction can be 'asc' or 'desc'
throw new TypeError("Order must be a function or a string");}}/**
   * Remove an item or multiple items by “reference” (only the id is used) or by id.
   *
   * The method ignores removal of non-existing items, and returns an array containing the ids of the items which are actually removed from the DataSet.
   *
   * After the items are removed, the DataSet will trigger an event `remove` for the removed items. When a `senderId` is provided, this id will be passed with the triggered event to all subscribers.
   *
   * ## Example
   * ```javascript
   * // create a DataSet
   * const data = new vis.DataSet([
   * { id: 1, text: 'item 1' },
   * { id: 2, text: 'item 2' },
   * { id: 3, text: 'item 3' }
   * ])
   *
   * // remove items
   * const ids = data.remove([2, { id: 3 }, 4])
   *
   * console.log(ids) // [2, 3]
   * ```
   * @param id - One or more items or ids of items to be removed.
   * @param senderId - Sender id.
   * @returns The ids of the removed items.
   */remove(id,senderId){const removedIds=[];const removedItems=[];// force everything to be an array for simplicity
const ids=_Array$isArray(id)?id:[id];for(let i=0,len=ids.length;i<len;i++){const item=this._remove(ids[i]);if(item){const itemId=item[this._idProp];if(itemId!=null){removedIds.push(itemId);removedItems.push(item);}}}if(removedIds.length){this._trigger("remove",{items:removedIds,oldData:removedItems},senderId);}return removedIds;}/**
   * Remove an item by its id or reference.
   * @param id - Id of an item or the item itself.
   * @returns The removed item if removed, null otherwise.
   */_remove(id){// @TODO: It origianlly returned the item although the docs say id.
// The code expects the item, so probably an error in the docs.
let ident;// confirm the id to use based on the args type
if(isId(id)){ident=id;}else if(id&&typeof id==="object"){ident=id[this._idProp];// look for the identifier field using ._idProp
}// do the removing if the item is found
if(ident!=null&&this._data.has(ident)){const item=this._data.get(ident)||null;this._data.delete(ident);--this.length;return item;}return null;}/**
   * Clear the entire data set.
   *
   * After the items are removed, the {@link DataSet} will trigger an event `remove` for all removed items. When a `senderId` is provided, this id will be passed with the triggered event to all subscribers.
   * @param senderId - Sender id.
   * @returns removedIds - The ids of all removed items.
   */clear(senderId){var _context13;const ids=[..._keysInstanceProperty(_context13=this._data).call(_context13)];const items=[];for(let i=0,len=ids.length;i<len;i++){items.push(this._data.get(ids[i]));}this._data.clear();this.length=0;this._trigger("remove",{items:ids,oldData:items},senderId);return ids;}/**
   * Find the item with maximum value of a specified field.
   * @param field - Name of the property that should be searched for max value.
   * @returns Item containing max value, or null if no items.
   */max(field){let max=null;let maxField=null;for(const item of _valuesInstanceProperty(_context14=this._data).call(_context14)){var _context14;const itemField=item[field];if(typeof itemField==="number"&&(maxField==null||itemField>maxField)){max=item;maxField=itemField;}}return max||null;}/**
   * Find the item with minimum value of a specified field.
   * @param field - Name of the property that should be searched for min value.
   * @returns Item containing min value, or null if no items.
   */min(field){let min=null;let minField=null;for(const item of _valuesInstanceProperty(_context15=this._data).call(_context15)){var _context15;const itemField=item[field];if(typeof itemField==="number"&&(minField==null||itemField<minField)){min=item;minField=itemField;}}return min||null;}/**
   * Find all distinct values of a specified field
   * @param prop - The property name whose distinct values should be returned.
   * @returns Unordered array containing all distinct values. Items without specified property are ignored.
   */distinct(prop){const data=this._data;const itemIds=[..._keysInstanceProperty(data).call(data)];const values=[];let count=0;for(let i=0,len=itemIds.length;i<len;i++){const id=itemIds[i];const item=data.get(id);const value=item[prop];let exists=false;for(let j=0;j<count;j++){if(values[j]==value){exists=true;break;}}if(!exists&&value!==undefined){values[count]=value;count++;}}return values;}/**
   * Add a single item. Will fail when an item with the same id already exists.
   * @param item - A new item to be added.
   * @returns Added item's id. An id is generated when it is not present in the item.
   */_addItem(item){const fullItem=ensureFullItem(item,this._idProp);const id=fullItem[this._idProp];// check whether this id is already taken
if(this._data.has(id)){// item already exists
throw new Error("Cannot add item: item with id "+id+" already exists");}this._data.set(id,fullItem);++this.length;return id;}/**
   * Update a single item: merge with existing item.
   * Will fail when the item has no id, or when there does not exist an item with the same id.
   * @param update - The new item
   * @returns The id of the updated item.
   */_updateItem(update){const id=update[this._idProp];if(id==null){throw new Error("Cannot update item: item has no id (item: "+_JSON$stringify(update)+")");}const item=this._data.get(id);if(!item){// item doesn't exist
throw new Error("Cannot update item: no item with id "+id+" found");}this._data.set(id,_objectSpread$4(_objectSpread$4({},item),update));return id;}/** @inheritDoc */stream(ids){if(ids){const data=this._data;return new DataStream({*[_Symbol$iterator](){for(const id of ids){const item=data.get(id);if(item!=null){yield [id,item];}}}});}else {var _context16;return new DataStream({[_Symbol$iterator]:_bindInstanceProperty(_context16=_entriesInstanceProperty(this._data)).call(_context16,this._data)});}}}/**
 * Check that given value is compatible with Vis Data Set interface.
 * @param idProp - The expected property to contain item id.
 * @param v - The value to be tested.
 * @returns True if all expected values and methods match, false otherwise.
 */function isDataSetLike(idProp,v){return typeof v==="object"&&v!==null&&idProp===v.idProp&&typeof v.add==="function"&&typeof v.clear==="function"&&typeof v.distinct==="function"&&typeof _forEachInstanceProperty(v)==="function"&&typeof v.get==="function"&&typeof v.getDataSet==="function"&&typeof v.getIds==="function"&&typeof v.length==="number"&&typeof _mapInstanceProperty(v)==="function"&&typeof v.max==="function"&&typeof v.min==="function"&&typeof v.off==="function"&&typeof v.on==="function"&&typeof v.remove==="function"&&typeof v.setOptions==="function"&&typeof v.stream==="function"&&typeof v.update==="function"&&typeof v.updateOnly==="function";}/**
 * Check that given value is compatible with Vis Data View interface.
 * @param idProp - The expected property to contain item id.
 * @param v - The value to be tested.
 * @returns True if all expected values and methods match, false otherwise.
 */function isDataViewLike(idProp,v){return typeof v==="object"&&v!==null&&idProp===v.idProp&&typeof _forEachInstanceProperty(v)==="function"&&typeof v.get==="function"&&typeof v.getDataSet==="function"&&typeof v.getIds==="function"&&typeof v.length==="number"&&typeof _mapInstanceProperty(v)==="function"&&typeof v.off==="function"&&typeof v.on==="function"&&typeof v.stream==="function"&&isDataSetLike(idProp,v.getDataSet());}var es_parseFloat={};var numberParseFloat;var hasRequiredNumberParseFloat;function requireNumberParseFloat(){if(hasRequiredNumberParseFloat)return numberParseFloat;hasRequiredNumberParseFloat=1;var globalThis=/*@__PURE__*/requireGlobalThis();var fails=/*@__PURE__*/requireFails();var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var toString=/*@__PURE__*/requireToString();var trim=/*@__PURE__*/requireStringTrim().trim;var whitespaces=/*@__PURE__*/requireWhitespaces();var charAt=uncurryThis(''.charAt);var $parseFloat=globalThis.parseFloat;var Symbol=globalThis.Symbol;var ITERATOR=Symbol&&Symbol.iterator;var FORCED=1/$parseFloat(whitespaces+'-0')!==-Infinity// MS Edge 18- broken with boxed symbols
||ITERATOR&&!fails(function(){$parseFloat(Object(ITERATOR));});// `parseFloat` method
// https://tc39.es/ecma262/#sec-parsefloat-string
numberParseFloat=FORCED?function parseFloat(string){var trimmedString=trim(toString(string));var result=$parseFloat(trimmedString);return result===0&&charAt(trimmedString,0)==='-'?-0:result;}:$parseFloat;return numberParseFloat;}var hasRequiredEs_parseFloat;function requireEs_parseFloat(){if(hasRequiredEs_parseFloat)return es_parseFloat;hasRequiredEs_parseFloat=1;var $=/*@__PURE__*/require_export();var $parseFloat=/*@__PURE__*/requireNumberParseFloat();// `parseFloat` method
// https://tc39.es/ecma262/#sec-parsefloat-string
$({global:true,forced:parseFloat!==$parseFloat},{parseFloat:$parseFloat});return es_parseFloat;}var _parseFloat$3;var hasRequired_parseFloat$2;function require_parseFloat$2(){if(hasRequired_parseFloat$2)return _parseFloat$3;hasRequired_parseFloat$2=1;requireEs_parseFloat();var path=/*@__PURE__*/requirePath();_parseFloat$3=path.parseFloat;return _parseFloat$3;}var _parseFloat$2;var hasRequired_parseFloat$1;function require_parseFloat$1(){if(hasRequired_parseFloat$1)return _parseFloat$2;hasRequired_parseFloat$1=1;var parent=/*@__PURE__*/require_parseFloat$2();_parseFloat$2=parent;return _parseFloat$2;}var _parseFloat$1;var hasRequired_parseFloat;function require_parseFloat(){if(hasRequired_parseFloat)return _parseFloat$1;hasRequired_parseFloat=1;_parseFloat$1=/*@__PURE__*/require_parseFloat$1();return _parseFloat$1;}var _parseFloatExports=require_parseFloat();var _parseFloat=/*@__PURE__*/getDefaultExportFromCjs(_parseFloatExports);var es_object_getOwnPropertyNames={};var hasRequiredEs_object_getOwnPropertyNames;function requireEs_object_getOwnPropertyNames(){if(hasRequiredEs_object_getOwnPropertyNames)return es_object_getOwnPropertyNames;hasRequiredEs_object_getOwnPropertyNames=1;var $=/*@__PURE__*/require_export();var fails=/*@__PURE__*/requireFails();var getOwnPropertyNames=/*@__PURE__*/requireObjectGetOwnPropertyNamesExternal().f;// eslint-disable-next-line es/no-object-getownpropertynames -- required for testing
var FAILS_ON_PRIMITIVES=fails(function(){return !Object.getOwnPropertyNames(1);});// `Object.getOwnPropertyNames` method
// https://tc39.es/ecma262/#sec-object.getownpropertynames
$({target:'Object',stat:true,forced:FAILS_ON_PRIMITIVES},{getOwnPropertyNames:getOwnPropertyNames});return es_object_getOwnPropertyNames;}var getOwnPropertyNames$2;var hasRequiredGetOwnPropertyNames$2;function requireGetOwnPropertyNames$2(){if(hasRequiredGetOwnPropertyNames$2)return getOwnPropertyNames$2;hasRequiredGetOwnPropertyNames$2=1;requireEs_object_getOwnPropertyNames();var path=/*@__PURE__*/requirePath();var Object=path.Object;getOwnPropertyNames$2=function getOwnPropertyNames(it){return Object.getOwnPropertyNames(it);};return getOwnPropertyNames$2;}var getOwnPropertyNames$1;var hasRequiredGetOwnPropertyNames$1;function requireGetOwnPropertyNames$1(){if(hasRequiredGetOwnPropertyNames$1)return getOwnPropertyNames$1;hasRequiredGetOwnPropertyNames$1=1;var parent=/*@__PURE__*/requireGetOwnPropertyNames$2();getOwnPropertyNames$1=parent;return getOwnPropertyNames$1;}var getOwnPropertyNames;var hasRequiredGetOwnPropertyNames;function requireGetOwnPropertyNames(){if(hasRequiredGetOwnPropertyNames)return getOwnPropertyNames;hasRequiredGetOwnPropertyNames=1;getOwnPropertyNames=/*@__PURE__*/requireGetOwnPropertyNames$1();return getOwnPropertyNames;}var getOwnPropertyNamesExports=requireGetOwnPropertyNames();var _Object$getOwnPropertyNames=/*@__PURE__*/getDefaultExportFromCjs(getOwnPropertyNamesExports);/**
 * Helper functions for components
 *//**
 * Determine values to use for (sub)options of 'chosen'.
 *
 * This option is either a boolean or an object whose values should be examined further.
 * The relevant structures are:
 *
 * - chosen: <boolean value>
 * - chosen: { subOption: <boolean or function> }
 *
 * Where subOption is 'node', 'edge' or 'label'.
 *
 * The intention of this method appears to be to set a specific priority to the options;
 * Since most properties are either bridged or merged into the local options objects, there
 * is not much point in handling them separately.
 * TODO: examine if 'most' in previous sentence can be replaced with 'all'. In that case, we
 * should be able to get rid of this method.
 * @param {string}  subOption  option within object 'chosen' to consider; either 'node', 'edge' or 'label'
 * @param {object}  pile       array of options objects to consider
 * @returns {boolean | Function}  value for passed subOption of 'chosen' to use
 */function choosify(subOption,pile){// allowed values for subOption
const allowed=["node","edge","label"];let value=true;const chosen=topMost(pile,"chosen");if(typeof chosen==="boolean"){value=chosen;}else if(typeof chosen==="object"){if(_indexOfInstanceProperty(allowed).call(allowed,subOption)===-1){throw new Error("choosify: subOption '"+subOption+"' should be one of "+"'"+allowed.join("', '")+"'");}const chosenEdge=topMost(pile,["chosen",subOption]);if(typeof chosenEdge==="boolean"||typeof chosenEdge==="function"){value=chosenEdge;}}return value;}/**
 * Check if the point falls within the given rectangle.
 * @param {rect} rect
 * @param {point} point
 * @param {rotationPoint} [rotationPoint] if specified, the rotation that applies to the rectangle.
 * @returns {boolean}  true if point within rectangle, false otherwise
 */function pointInRect(rect,point,rotationPoint){if(rect.width<=0||rect.height<=0){return false;// early out
}if(rotationPoint!==undefined){// Rotate the point the same amount as the rectangle
const tmp={x:point.x-rotationPoint.x,y:point.y-rotationPoint.y};if(rotationPoint.angle!==0){// In order to get the coordinates the same, you need to
// rotate in the reverse direction
const angle=-rotationPoint.angle;const tmp2={x:Math.cos(angle)*tmp.x-Math.sin(angle)*tmp.y,y:Math.sin(angle)*tmp.x+Math.cos(angle)*tmp.y};point=tmp2;}else {point=tmp;}// Note that if a rotation is specified, the rectangle coordinates
// are **not* the full canvas coordinates. They are relative to the
// rotationPoint. Hence, the point coordinates need not be translated
// back in this case.
}const right=rect.x+rect.width;const bottom=rect.y+rect.width;return rect.left<point.x&&right>point.x&&rect.top<point.y&&bottom>point.y;}/**
 * Check if given value is acceptable as a label text.
 * @param {*} text value to check; can be anything at this point
 * @returns {boolean} true if valid label value, false otherwise
 */function isValidLabel(text){// Note that this is quite strict: types that *might* be converted to string are disallowed
return typeof text==="string"&&text!=="";}/**
 * Returns x, y of self reference circle based on provided angle
 * @param {object} ctx
 * @param {number} angle
 * @param {number} radius
 * @param {VisNode} node
 * @returns {object} x and y coordinates
 */function getSelfRefCoordinates(ctx,angle,radius,node){let x=node.x;let y=node.y;if(typeof node.distanceToBorder==="function"){//calculating opposite and adjacent
//distaneToBorder becomes Hypotenuse.
//Formulas sin(a) = Opposite / Hypotenuse and cos(a) = Adjacent / Hypotenuse
const toBorderDist=node.distanceToBorder(ctx,angle);const yFromNodeCenter=Math.sin(angle)*toBorderDist;const xFromNodeCenter=Math.cos(angle)*toBorderDist;//xFromNodeCenter is basically x and if xFromNodeCenter equals to the distance to border then it means
//that y does not need calculation because it is equal node.height / 2 or node.y
//same thing with yFromNodeCenter and if yFromNodeCenter equals to the distance to border then it means
//that x is equal node.width / 2 or node.x
if(xFromNodeCenter===toBorderDist){x+=toBorderDist;y=node.y;}else if(yFromNodeCenter===toBorderDist){x=node.x;y-=toBorderDist;}else {x+=xFromNodeCenter;y-=yFromNodeCenter;}}else if(node.shape.width>node.shape.height){x=node.x+node.shape.width*0.5;y=node.y-radius;}else {x=node.x+radius;y=node.y-node.shape.height*0.5;}return {x,y};}/**
 * Callback to determine text dimensions, using the parent label settings.
 * @callback MeasureText
 * @param {text} text
 * @param {text} mod
 * @returns {object} { width, values} width in pixels and font attributes
 *//**
 * Helper class for Label which collects results of splitting labels into lines and blocks.
 * @private
 */class LabelAccumulator{/**
   * @param {MeasureText} measureText
   */constructor(measureText){this.measureText=measureText;this.current=0;this.width=0;this.height=0;this.lines=[];}/**
   * Append given text to the given line.
   * @param {number}  l    index of line to add to
   * @param {string}  text string to append to line
   * @param {'bold'|'ital'|'boldital'|'mono'|'normal'} [mod]
   * @private
   */_add(l,text){let mod=arguments.length>2&&arguments[2]!==undefined?arguments[2]:"normal";if(this.lines[l]===undefined){this.lines[l]={width:0,height:0,blocks:[]};}// We still need to set a block for undefined and empty texts, hence return at this point
// This is necessary because we don't know at this point if we're at the
// start of an empty line or not.
// To compensate, empty blocks are removed in `finalize()`.
//
// Empty strings should still have a height
let tmpText=text;if(text===undefined||text==="")tmpText=" ";// Determine width and get the font properties
const result=this.measureText(tmpText,mod);const block=_Object$assign({},_valuesInstanceProperty(result));block.text=text;block.width=result.width;block.mod=mod;if(text===undefined||text===""){block.width=0;}this.lines[l].blocks.push(block);// Update the line width. We need this for determining if a string goes over max width
this.lines[l].width+=block.width;}/**
   * Returns the width in pixels of the current line.
   * @returns {number}
   */curWidth(){const line=this.lines[this.current];if(line===undefined)return 0;return line.width;}/**
   * Add text in block to current line
   * @param {string} text
   * @param {'bold'|'ital'|'boldital'|'mono'|'normal'} [mod]
   */append(text){let mod=arguments.length>1&&arguments[1]!==undefined?arguments[1]:"normal";this._add(this.current,text,mod);}/**
   * Add text in block to current line and start a new line
   * @param {string} text
   * @param {'bold'|'ital'|'boldital'|'mono'|'normal'} [mod]
   */newLine(text){let mod=arguments.length>1&&arguments[1]!==undefined?arguments[1]:"normal";this._add(this.current,text,mod);this.current++;}/**
   * Determine and set the heights of all the lines currently contained in this instance
   *
   * Note that width has already been set.
   * @private
   */determineLineHeights(){for(let k=0;k<this.lines.length;k++){const line=this.lines[k];// Looking for max height of blocks in line
let height=0;if(line.blocks!==undefined){// Can happen if text contains e.g. '\n '
for(let l=0;l<line.blocks.length;l++){const block=line.blocks[l];if(height<block.height){height=block.height;}}}line.height=height;}}/**
   * Determine the full size of the label text, as determined by current lines and blocks
   * @private
   */determineLabelSize(){let width=0;let height=0;for(let k=0;k<this.lines.length;k++){const line=this.lines[k];if(line.width>width){width=line.width;}height+=line.height;}this.width=width;this.height=height;}/**
   * Remove all empty blocks and empty lines we don't need
   *
   * This must be done after the width/height determination,
   * so that these are set properly for processing here.
   * @returns {Array<Line>} Lines with empty blocks (and some empty lines) removed
   * @private
   */removeEmptyBlocks(){const tmpLines=[];for(let k=0;k<this.lines.length;k++){const line=this.lines[k];// Note: an empty line in between text has width zero but is still relevant to layout.
// So we can't use width for testing empty line here
if(line.blocks.length===0)continue;// Discard final empty line always
if(k===this.lines.length-1){if(line.width===0)continue;}const tmpLine={};_Object$assign(tmpLine,line);tmpLine.blocks=[];let firstEmptyBlock;const tmpBlocks=[];for(let l=0;l<line.blocks.length;l++){const block=line.blocks[l];if(block.width!==0){tmpBlocks.push(block);}else {if(firstEmptyBlock===undefined){firstEmptyBlock=block;}}}// Ensure that there is *some* text present
if(tmpBlocks.length===0&&firstEmptyBlock!==undefined){tmpBlocks.push(firstEmptyBlock);}tmpLine.blocks=tmpBlocks;tmpLines.push(tmpLine);}return tmpLines;}/**
   * Set the sizes for all lines and the whole thing.
   * @returns {{width: (number|*), height: (number|*), lines: Array}}
   */finalize(){//console.log(JSON.stringify(this.lines, null, 2));
this.determineLineHeights();this.determineLabelSize();const tmpLines=this.removeEmptyBlocks();// Return a simple hash object for further processing.
return {width:this.width,height:this.height,lines:tmpLines};}}// Hash of prepared regexp's for tags
const tagPattern={// HTML
"<b>":/<b>/,"<i>":/<i>/,"<code>":/<code>/,"</b>":/<\/b>/,"</i>":/<\/i>/,"</code>":/<\/code>/,// Markdown
"*":/\*/,// bold
_:/_/,// ital
"`":/`/,// mono
afterBold:/[^*]/,afterItal:/[^_]/,afterMono:/[^`]/};/**
 * Internal helper class for parsing the markup tags for HTML and Markdown.
 *
 * NOTE: Sequences of tabs and spaces are reduced to single space.
 *       Scan usage of `this.spacing` within method
 */class MarkupAccumulator{/**
   * Create an instance
   * @param {string} text  text to parse for markup
   */constructor(text){this.text=text;this.bold=false;this.ital=false;this.mono=false;this.spacing=false;this.position=0;this.buffer="";this.modStack=[];this.blocks=[];}/**
   * Return the mod label currently on the top of the stack
   * @returns {string}  label of topmost mod
   * @private
   */mod(){return this.modStack.length===0?"normal":this.modStack[0];}/**
   * Return the mod label currently active
   * @returns {string}  label of active mod
   * @private
   */modName(){if(this.modStack.length===0)return "normal";else if(this.modStack[0]==="mono")return "mono";else {if(this.bold&&this.ital){return "boldital";}else if(this.bold){return "bold";}else if(this.ital){return "ital";}}}/**
   * @private
   */emitBlock(){if(this.spacing){this.add(" ");this.spacing=false;}if(this.buffer.length>0){this.blocks.push({text:this.buffer,mod:this.modName()});this.buffer="";}}/**
   * Output text to buffer
   * @param {string} text  text to add
   * @private
   */add(text){if(text===" "){this.spacing=true;}if(this.spacing){this.buffer+=" ";this.spacing=false;}if(text!=" "){this.buffer+=text;}}/**
   * Handle parsing of whitespace
   * @param {string} ch  the character to check
   * @returns {boolean} true if the character was processed as whitespace, false otherwise
   */parseWS(ch){if(/[ \t]/.test(ch)){if(!this.mono){this.spacing=true;}else {this.add(ch);}return true;}return false;}/**
   * @param {string} tagName  label for block type to set
   * @private
   */setTag(tagName){this.emitBlock();this[tagName]=true;this.modStack.unshift(tagName);}/**
   * @param {string} tagName  label for block type to unset
   * @private
   */unsetTag(tagName){this.emitBlock();this[tagName]=false;this.modStack.shift();}/**
   * @param {string} tagName label for block type we are currently processing
   * @param {string|RegExp} tag string to match in text
   * @returns {boolean} true if the tag was processed, false otherwise
   */parseStartTag(tagName,tag){// Note: if 'mono' passed as tagName, there is a double check here. This is OK
if(!this.mono&&!this[tagName]&&this.match(tag)){this.setTag(tagName);return true;}return false;}/**
   * @param {string|RegExp} tag
   * @param {number} [advance] if set, advance current position in text
   * @returns {boolean} true if match at given position, false otherwise
   * @private
   */match(tag){let advance=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;const[regExp,length]=this.prepareRegExp(tag);const matched=regExp.test(this.text.substr(this.position,length));if(matched&&advance){this.position+=length-1;}return matched;}/**
   * @param {string} tagName label for block type we are currently processing
   * @param {string|RegExp} tag string to match in text
   * @param {RegExp} [nextTag] regular expression to match for characters *following* the current tag
   * @returns {boolean} true if the tag was processed, false otherwise
   */parseEndTag(tagName,tag,nextTag){let checkTag=this.mod()===tagName;if(tagName==="mono"){// special handling for 'mono'
checkTag=checkTag&&this.mono;}else {checkTag=checkTag&&!this.mono;}if(checkTag&&this.match(tag)){if(nextTag!==undefined){// Purpose of the following match is to prevent a direct unset/set of a given tag
// E.g. '*bold **still bold*' => '*bold still bold*'
if(this.position===this.text.length-1||this.match(nextTag,false)){this.unsetTag(tagName);}}else {this.unsetTag(tagName);}return true;}return false;}/**
   * @param {string|RegExp} tag  string to match in text
   * @param {value} value  string to replace tag with, if found at current position
   * @returns {boolean} true if the tag was processed, false otherwise
   */replace(tag,value){if(this.match(tag)){this.add(value);this.position+=length-1;return true;}return false;}/**
   * Create a regular expression for the tag if it isn't already one.
   *
   * The return value is an array `[RegExp, number]`, with exactly two value, where:
   * - RegExp is the regular expression to use
   * - number is the lenth of the input string to match
   * @param {string|RegExp} tag  string to match in text
   * @returns {Array}  regular expression to use and length of input string to match
   * @private
   */prepareRegExp(tag){let length;let regExp;if(tag instanceof RegExp){regExp=tag;length=1;// ASSUMPTION: regexp only tests one character
}else {// use prepared regexp if present
const prepared=tagPattern[tag];if(prepared!==undefined){regExp=prepared;}else {regExp=new RegExp(tag);}length=tag.length;}return [regExp,length];}}/**
 * Helper class for Label which explodes the label text into lines and blocks within lines
 * @private
 */class LabelSplitter{/**
   * @param {CanvasRenderingContext2D} ctx Canvas rendering context
   * @param {Label} parent reference to the Label instance using current instance
   * @param {boolean} selected
   * @param {boolean} hover
   */constructor(ctx,parent,selected,hover){this.ctx=ctx;this.parent=parent;this.selected=selected;this.hover=hover;/**
     * Callback to determine text width; passed to LabelAccumulator instance
     * @param  {string} text string to determine width of
     * @param  {string} mod  font type to use for this text
     * @returns {object} { width, values} width in pixels and font attributes
     */const textWidth=(text,mod)=>{if(text===undefined)return 0;// TODO: This can be done more efficiently with caching
// This will set the ctx.font correctly, depending on selected/hover and mod - so that ctx.measureText() will be accurate.
const values=this.parent.getFormattingValues(ctx,selected,hover,mod);let width=0;if(text!==""){const measure=this.ctx.measureText(text);width=measure.width;}return {width,values:values};};this.lines=new LabelAccumulator(textWidth);}/**
   * Split passed text of a label into lines and blocks.
   *
   * # NOTE
   *
   * The handling of spacing is option dependent:
   *
   * - if `font.multi : false`, all spaces are retained
   * - if `font.multi : true`, every sequence of spaces is compressed to a single space
   *
   * This might not be the best way to do it, but this is as it has been working till now.
   * In order not to break existing functionality, for the time being this behaviour will
   * be retained in any code changes.
   * @param {string} text  text to split
   * @returns {Array<line>}
   */process(text){if(!isValidLabel(text)){return this.lines.finalize();}const font=this.parent.fontOptions;// Normalize the end-of-line's to a single representation - order important
text=text.replace(/\r\n/g,"\n");// Dos EOL's
text=text.replace(/\r/g,"\n");// Mac EOL's
// Note that at this point, there can be no \r's in the text.
// This is used later on splitStringIntoLines() to split multifont texts.
const nlLines=String(text).split("\n");const lineCount=nlLines.length;if(font.multi){// Multi-font case: styling tags active
for(let i=0;i<lineCount;i++){const blocks=this.splitBlocks(nlLines[i],font.multi);// Post: Sequences of tabs and spaces are reduced to single space
if(blocks===undefined)continue;if(blocks.length===0){this.lines.newLine("");continue;}if(font.maxWdt>0){// widthConstraint.maximum defined
//console.log('Running widthConstraint multi, max: ' + this.fontOptions.maxWdt);
for(let j=0;j<blocks.length;j++){const mod=blocks[j].mod;const text=blocks[j].text;this.splitStringIntoLines(text,mod,true);}}else {// widthConstraint.maximum NOT defined
for(let j=0;j<blocks.length;j++){const mod=blocks[j].mod;const text=blocks[j].text;this.lines.append(text,mod);}}this.lines.newLine();}}else {// Single-font case
if(font.maxWdt>0){// widthConstraint.maximum defined
// console.log('Running widthConstraint normal, max: ' + this.fontOptions.maxWdt);
for(let i=0;i<lineCount;i++){this.splitStringIntoLines(nlLines[i]);}}else {// widthConstraint.maximum NOT defined
for(let i=0;i<lineCount;i++){this.lines.newLine(nlLines[i]);}}}return this.lines.finalize();}/**
   * normalize the markup system
   * @param {boolean|'md'|'markdown'|'html'} markupSystem
   * @returns {string}
   */decodeMarkupSystem(markupSystem){let system="none";if(markupSystem==="markdown"||markupSystem==="md"){system="markdown";}else if(markupSystem===true||markupSystem==="html"){system="html";}return system;}/**
   *
   * @param {string} text
   * @returns {Array}
   */splitHtmlBlocks(text){const s=new MarkupAccumulator(text);const parseEntities=ch=>{if(/&/.test(ch)){const parsed=s.replace(s.text,"&lt;","<")||s.replace(s.text,"&amp;","&");if(!parsed){s.add("&");}return true;}return false;};while(s.position<s.text.length){const ch=s.text.charAt(s.position);const parsed=s.parseWS(ch)||/</.test(ch)&&(s.parseStartTag("bold","<b>")||s.parseStartTag("ital","<i>")||s.parseStartTag("mono","<code>")||s.parseEndTag("bold","</b>")||s.parseEndTag("ital","</i>")||s.parseEndTag("mono","</code>"))||parseEntities(ch);if(!parsed){s.add(ch);}s.position++;}s.emitBlock();return s.blocks;}/**
   *
   * @param {string} text
   * @returns {Array}
   */splitMarkdownBlocks(text){const s=new MarkupAccumulator(text);let beginable=true;const parseOverride=ch=>{if(/\\/.test(ch)){if(s.position<this.text.length+1){s.position++;ch=this.text.charAt(s.position);if(/ \t/.test(ch)){s.spacing=true;}else {s.add(ch);beginable=false;}}return true;}return false;};while(s.position<s.text.length){const ch=s.text.charAt(s.position);const parsed=s.parseWS(ch)||parseOverride(ch)||(beginable||s.spacing)&&(s.parseStartTag("bold","*")||s.parseStartTag("ital","_")||s.parseStartTag("mono","`"))||s.parseEndTag("bold","*","afterBold")||s.parseEndTag("ital","_","afterItal")||s.parseEndTag("mono","`","afterMono");if(!parsed){s.add(ch);beginable=false;}s.position++;}s.emitBlock();return s.blocks;}/**
   * Explodes a piece of text into single-font blocks using a given markup
   * @param {string} text
   * @param {boolean|'md'|'markdown'|'html'} markupSystem
   * @returns {Array.<{text: string, mod: string}>}
   * @private
   */splitBlocks(text,markupSystem){const system=this.decodeMarkupSystem(markupSystem);if(system==="none"){return [{text:text,mod:"normal"}];}else if(system==="markdown"){return this.splitMarkdownBlocks(text);}else if(system==="html"){return this.splitHtmlBlocks(text);}}/**
   * @param {string} text
   * @returns {boolean} true if text length over the current max with
   * @private
   */overMaxWidth(text){const width=this.ctx.measureText(text).width;return this.lines.curWidth()+width>this.parent.fontOptions.maxWdt;}/**
   * Determine the longest part of the sentence which still fits in the
   * current max width.
   * @param {Array} words  Array of strings signifying a text lines
   * @returns {number}      index of first item in string making string go over max
   * @private
   */getLongestFit(words){let text="";let w=0;while(w<words.length){const pre=text===""?"":" ";const newText=text+pre+words[w];if(this.overMaxWidth(newText))break;text=newText;w++;}return w;}/**
   * Determine the longest part of the string which still fits in the
   * current max width.
   * @param {Array} words Array of strings signifying a text lines
   * @returns {number} index of first item in string making string go over max
   */getLongestFitWord(words){let w=0;while(w<words.length){if(this.overMaxWidth(_sliceInstanceProperty(words).call(words,0,w)))break;w++;}return w;}/**
   * Split the passed text into lines, according to width constraint (if any).
   *
   * The method assumes that the input string is a single line, i.e. without lines break.
   *
   * This method retains spaces, if still present (case `font.multi: false`).
   * A space which falls on an internal line break, will be replaced by a newline.
   * There is no special handling of tabs; these go along with the flow.
   * @param {string} str
   * @param {string} [mod]
   * @param {boolean} [appendLast]
   * @private
   */splitStringIntoLines(str){let mod=arguments.length>1&&arguments[1]!==undefined?arguments[1]:"normal";let appendLast=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;// Set the canvas context font, based upon the current selected/hover state
// and the provided mod, so the text measurement performed by getLongestFit
// will be accurate - and not just use the font of whoever last used the canvas.
this.parent.getFormattingValues(this.ctx,this.selected,this.hover,mod);// Still-present spaces are relevant, retain them
str=str.replace(/^( +)/g,"$1\r");str=str.replace(/([^\r][^ ]*)( +)/g,"$1\r$2\r");let words=str.split("\r");while(words.length>0){let w=this.getLongestFit(words);if(w===0){// Special case: the first word is already larger than the max width.
const word=words[0];// Break the word to the largest part that fits the line
const x=this.getLongestFitWord(word);this.lines.newLine(_sliceInstanceProperty(word).call(word,0,x),mod);// Adjust the word, so that the rest will be done next iteration
words[0]=_sliceInstanceProperty(word).call(word,x);}else {// skip any space that is replaced by a newline
let newW=w;if(words[w-1]===" "){w--;}else if(words[newW]===" "){newW++;}const text=_sliceInstanceProperty(words).call(words,0,w).join("");if(w==words.length&&appendLast){this.lines.append(text,mod);}else {this.lines.newLine(text,mod);}// Adjust the word, so that the rest will be done next iteration
words=_sliceInstanceProperty(words).call(words,newW);}}}}/**
 * List of special styles for multi-fonts
 * @private
 */const multiFontStyle=["bold","ital","boldital","mono"];/**
 * A Label to be used for Nodes or Edges.
 */class Label{/**
   * @param {object} body
   * @param {object} options
   * @param {boolean} [edgelabel]
   */constructor(body,options){let edgelabel=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;this.body=body;this.pointToSelf=false;this.baseSize=undefined;this.fontOptions={};// instance variable containing the *instance-local* font options
this.setOptions(options);this.size={top:0,left:0,width:0,height:0,yLine:0};this.isEdgeLabel=edgelabel;}/**
   * @param {object} options the options of the parent Node-instance
   */setOptions(options){this.elementOptions=options;// Reference to the options of the parent Node-instance
this.initFontOptions(options.font);if(isValidLabel(options.label)){this.labelDirty=true;}else {// Bad label! Change the option value to prevent bad stuff happening
options.label=undefined;}if(options.font!==undefined&&options.font!==null){// font options can be deleted at various levels
if(typeof options.font==="string"){this.baseSize=this.fontOptions.size;}else if(typeof options.font==="object"){const size=options.font.size;if(size!==undefined){this.baseSize=size;}}}}/**
   * Init the font Options structure.
   *
   * Member fontOptions serves as an accumulator for the current font options.
   * As such, it needs to be completely separated from the node options.
   * @param {object} newFontOptions the new font options to process
   * @private
   */initFontOptions(newFontOptions){// Prepare the multi-font option objects.
// These will be filled in propagateFonts(), if required
forEach(multiFontStyle,style=>{this.fontOptions[style]={};});// Handle shorthand option, if present
if(Label.parseFontString(this.fontOptions,newFontOptions)){this.fontOptions.vadjust=0;return;}// Copy over the non-multifont options, if specified
forEach(newFontOptions,(prop,n)=>{if(prop!==undefined&&prop!==null&&typeof prop!=="object"){this.fontOptions[n]=prop;}});}/**
   * If in-variable is a string, parse it as a font specifier.
   *
   * Note that following is not done here and have to be done after the call:
   * - Not all font options are set (vadjust, mod)
   * @param {object} outOptions  out-parameter, object in which to store the parse results (if any)
   * @param {object} inOptions  font options to parse
   * @returns {boolean} true if font parsed as string, false otherwise
   * @static
   */static parseFontString(outOptions,inOptions){if(!inOptions||typeof inOptions!=="string")return false;const newOptionsArray=inOptions.split(" ");outOptions.size=+newOptionsArray[0].replace("px","");outOptions.face=newOptionsArray[1];outOptions.color=newOptionsArray[2];return true;}/**
   * Set the width and height constraints based on 'nearest' value
   * @param {Array} pile array of option objects to consider
   * @returns {object} the actual constraint values to use
   * @private
   */constrain(pile){// NOTE: constrainWidth and  constrainHeight never set!
// NOTE: for edge labels, only 'maxWdt' set
// Node labels can set all the fields
const fontOptions={constrainWidth:false,maxWdt:-1,minWdt:-1,constrainHeight:false,minHgt:-1,valign:"middle"};const widthConstraint=topMost(pile,"widthConstraint");if(typeof widthConstraint==="number"){fontOptions.maxWdt=Number(widthConstraint);fontOptions.minWdt=Number(widthConstraint);}else if(typeof widthConstraint==="object"){const widthConstraintMaximum=topMost(pile,["widthConstraint","maximum"]);if(typeof widthConstraintMaximum==="number"){fontOptions.maxWdt=Number(widthConstraintMaximum);}const widthConstraintMinimum=topMost(pile,["widthConstraint","minimum"]);if(typeof widthConstraintMinimum==="number"){fontOptions.minWdt=Number(widthConstraintMinimum);}}const heightConstraint=topMost(pile,"heightConstraint");if(typeof heightConstraint==="number"){fontOptions.minHgt=Number(heightConstraint);}else if(typeof heightConstraint==="object"){const heightConstraintMinimum=topMost(pile,["heightConstraint","minimum"]);if(typeof heightConstraintMinimum==="number"){fontOptions.minHgt=Number(heightConstraintMinimum);}const heightConstraintValign=topMost(pile,["heightConstraint","valign"]);if(typeof heightConstraintValign==="string"){if(heightConstraintValign==="top"||heightConstraintValign==="bottom"){fontOptions.valign=heightConstraintValign;}}}return fontOptions;}/**
   * Set options and update internal state
   * @param {object} options  options to set
   * @param {Array}  pile     array of option objects to consider for option 'chosen'
   */update(options,pile){this.setOptions(options,true);this.propagateFonts(pile);deepExtend(this.fontOptions,this.constrain(pile));this.fontOptions.chooser=choosify("label",pile);}/**
   * When margins are set in an element, adjust sizes is called to remove them
   * from the width/height constraints. This must be done prior to label sizing.
   * @param {{top: number, right: number, bottom: number, left: number}} margins
   */adjustSizes(margins){const widthBias=margins?margins.right+margins.left:0;if(this.fontOptions.constrainWidth){this.fontOptions.maxWdt-=widthBias;this.fontOptions.minWdt-=widthBias;}const heightBias=margins?margins.top+margins.bottom:0;if(this.fontOptions.constrainHeight){this.fontOptions.minHgt-=heightBias;}}/////////////////////////////////////////////////////////
// Methods for handling options piles
// Eventually, these will be moved to a separate class
/////////////////////////////////////////////////////////
/**
   * Add the font members of the passed list of option objects to the pile.
   * @param {Pile} dstPile  pile of option objects add to
   * @param {Pile} srcPile  pile of option objects to take font options from
   * @private
   */addFontOptionsToPile(dstPile,srcPile){for(let i=0;i<srcPile.length;++i){this.addFontToPile(dstPile,srcPile[i]);}}/**
   * Add given font option object to the list of objects (the 'pile') to consider for determining
   * multi-font option values.
   * @param {Pile} pile  pile of option objects to use
   * @param {object} options  instance to add to pile
   * @private
   */addFontToPile(pile,options){if(options===undefined)return;if(options.font===undefined||options.font===null)return;const item=options.font;pile.push(item);}/**
   * Collect all own-property values from the font pile that aren't multi-font option objectss.
   * @param {Pile} pile  pile of option objects to use
   * @returns {object} object with all current own basic font properties
   * @private
   */getBasicOptions(pile){const ret={};// Scans the whole pile to get all options present
for(let n=0;n<pile.length;++n){let fontOptions=pile[n];// Convert shorthand if necessary
const tmpShorthand={};if(Label.parseFontString(tmpShorthand,fontOptions)){fontOptions=tmpShorthand;}forEach(fontOptions,(opt,name)=>{if(opt===undefined)return;// multi-font option need not be present
if(Object.prototype.hasOwnProperty.call(ret,name))return;// Keep first value we encounter
if(_indexOfInstanceProperty(multiFontStyle).call(multiFontStyle,name)!==-1){// Skip multi-font properties but we do need the structure
ret[name]={};}else {ret[name]=opt;}});}return ret;}/**
   * Return the value for given option for the given multi-font.
   *
   * All available option objects are trawled in the set order to construct the option values.
   *
   * ---------------------------------------------------------------------
   * ## Traversal of pile for multi-fonts
   *
   * The determination of multi-font option values is a special case, because any values not
   * present in the multi-font options should by definition be taken from the main font options,
   * i.e. from the current 'parent' object of the multi-font option.
   *
   * ### Search order for multi-fonts
   *
   * 'bold' used as example:
   *
   * - search in option group 'bold' in local properties
   * - search in main font option group in local properties
   *
   * ---------------------------------------------------------------------
   * @param {Pile} pile  pile of option objects to use
   * @param {MultiFontStyle} multiName sub path for the multi-font
   * @param {string} option  the option to search for, for the given multi-font
   * @returns {string|number} the value for the given option
   * @private
   */getFontOption(pile,multiName,option){let multiFont;// Search multi font in local properties
for(let n=0;n<pile.length;++n){const fontOptions=pile[n];if(Object.prototype.hasOwnProperty.call(fontOptions,multiName)){multiFont=fontOptions[multiName];if(multiFont===undefined||multiFont===null)continue;// Convert shorthand if necessary
// TODO: inefficient to do this conversion every time; find a better way.
const tmpShorthand={};if(Label.parseFontString(tmpShorthand,multiFont)){multiFont=tmpShorthand;}if(Object.prototype.hasOwnProperty.call(multiFont,option)){return multiFont[option];}}}// Option is not mentioned in the multi font options; take it from the parent font options.
// These have already been converted with getBasicOptions(), so use the converted values.
if(Object.prototype.hasOwnProperty.call(this.fontOptions,option)){return this.fontOptions[option];}// A value **must** be found; you should never get here.
throw new Error("Did not find value for multi-font for property: '"+option+"'");}/**
   * Return all options values for the given multi-font.
   *
   * All available option objects are trawled in the set order to construct the option values.
   * @param {Pile} pile  pile of option objects to use
   * @param {MultiFontStyle} multiName sub path for the mod-font
   * @returns {MultiFontOptions}
   * @private
   */getFontOptions(pile,multiName){const result={};const optionNames=["color","size","face","mod","vadjust"];// List of allowed options per multi-font
for(let i=0;i<optionNames.length;++i){const mod=optionNames[i];result[mod]=this.getFontOption(pile,multiName,mod);}return result;}/////////////////////////////////////////////////////////
// End methods for handling options piles
/////////////////////////////////////////////////////////
/**
   * Collapse the font options for the multi-font to single objects, from
   * the chain of option objects passed (the 'pile').
   * @param {Pile} pile  sequence of option objects to consider.
   *                     First item in list assumed to be the newly set options.
   */propagateFonts(pile){const fontPile=[];// sequence of font objects to consider, order important
// Note that this.elementOptions is not used here.
this.addFontOptionsToPile(fontPile,pile);this.fontOptions=this.getBasicOptions(fontPile);// We set multifont values even if multi === false, for consistency (things break otherwise)
for(let i=0;i<multiFontStyle.length;++i){const mod=multiFontStyle[i];const modOptions=this.fontOptions[mod];const tmpMultiFontOptions=this.getFontOptions(fontPile,mod);// Copy over found values
forEach(tmpMultiFontOptions,(option,n)=>{modOptions[n]=option;});modOptions.size=Number(modOptions.size);modOptions.vadjust=Number(modOptions.vadjust);}}/**
   * Main function. This is called from anything that wants to draw a label.
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} x
   * @param {number} y
   * @param {boolean} selected
   * @param {boolean} hover
   * @param {string} [baseline]
   */draw(ctx,x,y,selected,hover){let baseline=arguments.length>5&&arguments[5]!==undefined?arguments[5]:"middle";// if no label, return
if(this.elementOptions.label===undefined)return;// check if we have to render the label
let viewFontSize=this.fontOptions.size*this.body.view.scale;if(this.elementOptions.label&&viewFontSize<this.elementOptions.scaling.label.drawThreshold-1)return;// This ensures that there will not be HUGE letters on screen
// by setting an upper limit on the visible text size (regardless of zoomLevel)
if(viewFontSize>=this.elementOptions.scaling.label.maxVisible){viewFontSize=Number(this.elementOptions.scaling.label.maxVisible)/this.body.view.scale;}// update the size cache if required
this.calculateLabelSize(ctx,selected,hover,x,y,baseline);this._drawBackground(ctx);this._drawText(ctx,x,this.size.yLine,baseline,viewFontSize);}/**
   * Draws the label background
   * @param {CanvasRenderingContext2D} ctx
   * @private
   */_drawBackground(ctx){if(this.fontOptions.background!==undefined&&this.fontOptions.background!=="none"){ctx.fillStyle=this.fontOptions.background;const size=this.getSize();ctx.fillRect(size.left,size.top,size.width,size.height);}}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} x
   * @param {number} y
   * @param {string} [baseline]
   * @param {number} viewFontSize
   * @private
   */_drawText(ctx,x,y){let baseline=arguments.length>3&&arguments[3]!==undefined?arguments[3]:"middle";let viewFontSize=arguments.length>4?arguments[4]:undefined;[x,y]=this._setAlignment(ctx,x,y,baseline);ctx.textAlign="left";x=x-this.size.width/2;// Shift label 1/2-distance to the left
if(this.fontOptions.valign&&this.size.height>this.size.labelHeight){if(this.fontOptions.valign==="top"){y-=(this.size.height-this.size.labelHeight)/2;}if(this.fontOptions.valign==="bottom"){y+=(this.size.height-this.size.labelHeight)/2;}}// draw the text
for(let i=0;i<this.lineCount;i++){const line=this.lines[i];if(line&&line.blocks){let width=0;if(this.isEdgeLabel||this.fontOptions.align==="center"){width+=(this.size.width-line.width)/2;}else if(this.fontOptions.align==="right"){width+=this.size.width-line.width;}for(let j=0;j<line.blocks.length;j++){const block=line.blocks[j];ctx.font=block.font;const[fontColor,strokeColor]=this._getColor(block.color,viewFontSize,block.strokeColor);if(block.strokeWidth>0){ctx.lineWidth=block.strokeWidth;ctx.strokeStyle=strokeColor;ctx.lineJoin="round";}ctx.fillStyle=fontColor;if(block.strokeWidth>0){ctx.strokeText(block.text,x+width,y+block.vadjust);}ctx.fillText(block.text,x+width,y+block.vadjust);width+=block.width;}y+=line.height;}}}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} x
   * @param {number} y
   * @param {string} baseline
   * @returns {Array.<number>}
   * @private
   */_setAlignment(ctx,x,y,baseline){// check for label alignment (for edges)
// TODO: make alignment for nodes
if(this.isEdgeLabel&&this.fontOptions.align!=="horizontal"&&this.pointToSelf===false){x=0;y=0;const lineMargin=2;if(this.fontOptions.align==="top"){ctx.textBaseline="alphabetic";y-=2*lineMargin;// distance from edge, required because we use alphabetic. Alphabetic has less difference between browsers
}else if(this.fontOptions.align==="bottom"){ctx.textBaseline="hanging";y+=2*lineMargin;// distance from edge, required because we use hanging. Hanging has less difference between browsers
}else {ctx.textBaseline="middle";}}else {ctx.textBaseline=baseline;}return [x,y];}/**
   * fade in when relative scale is between threshold and threshold - 1.
   * If the relative scale would be smaller than threshold -1 the draw function would have returned before coming here.
   * @param {string} color  The font color to use
   * @param {number} viewFontSize
   * @param {string} initialStrokeColor
   * @returns {Array.<string>} An array containing the font color and stroke color
   * @private
   */_getColor(color,viewFontSize,initialStrokeColor){let fontColor=color||"#000000";let strokeColor=initialStrokeColor||"#ffffff";if(viewFontSize<=this.elementOptions.scaling.label.drawThreshold){const opacity=Math.max(0,Math.min(1,1-(this.elementOptions.scaling.label.drawThreshold-viewFontSize)));fontColor=overrideOpacity(fontColor,opacity);strokeColor=overrideOpacity(strokeColor,opacity);}return [fontColor,strokeColor];}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {boolean} selected
   * @param {boolean} hover
   * @returns {{width: number, height: number}}
   */getTextSize(ctx){let selected=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;let hover=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;this._processLabel(ctx,selected,hover);return {width:this.size.width,height:this.size.height,lineCount:this.lineCount};}/**
   * Get the current dimensions of the label
   * @returns {rect}
   */getSize(){const lineMargin=2;let x=this.size.left;// default values which might be overridden below
let y=this.size.top-0.5*lineMargin;// idem
if(this.isEdgeLabel){const x2=-this.size.width*0.5;switch(this.fontOptions.align){case "middle":x=x2;y=-this.size.height*0.5;break;case "top":x=x2;y=-(this.size.height+lineMargin);break;case "bottom":x=x2;y=lineMargin;break;}}const ret={left:x,top:y,width:this.size.width,height:this.size.height};return ret;}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {boolean} selected
   * @param {boolean} hover
   * @param {number} [x]
   * @param {number} [y]
   * @param {'middle'|'hanging'} [baseline]
   */calculateLabelSize(ctx,selected,hover){let x=arguments.length>3&&arguments[3]!==undefined?arguments[3]:0;let y=arguments.length>4&&arguments[4]!==undefined?arguments[4]:0;let baseline=arguments.length>5&&arguments[5]!==undefined?arguments[5]:"middle";this._processLabel(ctx,selected,hover);this.size.left=x-this.size.width*0.5;this.size.top=y-this.size.height*0.5;this.size.yLine=y+(1-this.lineCount)*0.5*this.fontOptions.size;if(baseline==="hanging"){this.size.top+=0.5*this.fontOptions.size;this.size.top+=4;// distance from node, required because we use hanging. Hanging has less difference between browsers
this.size.yLine+=4;// distance from node
}}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {boolean} selected
   * @param {boolean} hover
   * @param {string} mod
   * @returns {{color, size, face, mod, vadjust, strokeWidth: *, strokeColor: (*|string|allOptions.edges.font.strokeColor|{string}|allOptions.nodes.font.strokeColor|Array)}}
   */getFormattingValues(ctx,selected,hover,mod){const getValue=function(fontOptions,mod,option){if(mod==="normal"){if(option==="mod")return "";return fontOptions[option];}if(fontOptions[mod][option]!==undefined){// Grumbl leaving out test on undefined equals false for ""
return fontOptions[mod][option];}else {// Take from parent font option
return fontOptions[option];}};const values={color:getValue(this.fontOptions,mod,"color"),size:getValue(this.fontOptions,mod,"size"),face:getValue(this.fontOptions,mod,"face"),mod:getValue(this.fontOptions,mod,"mod"),vadjust:getValue(this.fontOptions,mod,"vadjust"),strokeWidth:this.fontOptions.strokeWidth,strokeColor:this.fontOptions.strokeColor};if(selected||hover){if(mod==="normal"&&this.fontOptions.chooser===true&&this.elementOptions.labelHighlightBold){values.mod="bold";}else {if(typeof this.fontOptions.chooser==="function"){this.fontOptions.chooser(values,this.elementOptions.id,selected,hover);}}}let fontString="";if(values.mod!==undefined&&values.mod!==""){// safeguard for undefined - this happened
fontString+=values.mod+" ";}fontString+=values.size+"px "+values.face;ctx.font=fontString.replace(/"/g,"");values.font=ctx.font;values.height=values.size;return values;}/**
   *
   * @param {boolean} selected
   * @param {boolean} hover
   * @returns {boolean}
   */differentState(selected,hover){return selected!==this.selectedState||hover!==this.hoverState;}/**
   * This explodes the passed text into lines and determines the width, height and number of lines.
   * @param {CanvasRenderingContext2D} ctx
   * @param {boolean} selected
   * @param {boolean} hover
   * @param {string} inText  the text to explode
   * @returns {{width, height, lines}|*}
   * @private
   */_processLabelText(ctx,selected,hover,inText){const splitter=new LabelSplitter(ctx,this,selected,hover);return splitter.process(inText);}/**
   * This explodes the label string into lines and sets the width, height and number of lines.
   * @param {CanvasRenderingContext2D} ctx
   * @param {boolean} selected
   * @param {boolean} hover
   * @private
   */_processLabel(ctx,selected,hover){if(this.labelDirty===false&&!this.differentState(selected,hover))return;const state=this._processLabelText(ctx,selected,hover,this.elementOptions.label);if(this.fontOptions.minWdt>0&&state.width<this.fontOptions.minWdt){state.width=this.fontOptions.minWdt;}this.size.labelHeight=state.height;if(this.fontOptions.minHgt>0&&state.height<this.fontOptions.minHgt){state.height=this.fontOptions.minHgt;}this.lines=state.lines;this.lineCount=state.lines.length;this.size.width=state.width;this.size.height=state.height;this.selectedState=selected;this.hoverState=hover;this.labelDirty=false;}/**
   * Check if this label is visible
   * @returns {boolean} true if this label will be show, false otherwise
   */visible(){if(this.size.width===0||this.size.height===0||this.elementOptions.label===undefined){return false;// nothing to display
}const viewFontSize=this.fontOptions.size*this.body.view.scale;if(viewFontSize<this.elementOptions.scaling.label.drawThreshold-1){return false;// Too small or too far away to show
}return true;}}/**
 * The Base class for all Nodes.
 */class NodeBase{/**
   * @param {object} options
   * @param {object} body
   * @param {Label} labelModule
   */constructor(options,body,labelModule){this.body=body;this.labelModule=labelModule;this.setOptions(options);this.top=undefined;this.left=undefined;this.height=undefined;this.width=undefined;this.radius=undefined;this.margin=undefined;this.refreshNeeded=true;this.boundingBox={top:0,left:0,right:0,bottom:0};}/**
   *
   * @param {object} options
   */setOptions(options){this.options=options;}/**
   *
   * @param {Label} labelModule
   * @private
   */_setMargins(labelModule){this.margin={};if(this.options.margin){if(typeof this.options.margin=="object"){this.margin.top=this.options.margin.top;this.margin.right=this.options.margin.right;this.margin.bottom=this.options.margin.bottom;this.margin.left=this.options.margin.left;}else {this.margin.top=this.options.margin;this.margin.right=this.options.margin;this.margin.bottom=this.options.margin;this.margin.left=this.options.margin;}}labelModule.adjustSizes(this.margin);}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} angle
   * @returns {number}
   * @private
   */_distanceToBorder(ctx,angle){const borderWidth=this.options.borderWidth;if(ctx){this.resize(ctx);}return Math.min(Math.abs(this.width/2/Math.cos(angle)),Math.abs(this.height/2/Math.sin(angle)))+borderWidth;}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {ArrowOptions} values
   */enableShadow(ctx,values){if(values.shadow){ctx.shadowColor=values.shadowColor;ctx.shadowBlur=values.shadowSize;ctx.shadowOffsetX=values.shadowX;ctx.shadowOffsetY=values.shadowY;}}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {ArrowOptions} values
   */disableShadow(ctx,values){if(values.shadow){ctx.shadowColor="rgba(0,0,0,0)";ctx.shadowBlur=0;ctx.shadowOffsetX=0;ctx.shadowOffsetY=0;}}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {ArrowOptions} values
   */enableBorderDashes(ctx,values){if(values.borderDashes!==false){if(ctx.setLineDash!==undefined){let dashes=values.borderDashes;if(dashes===true){dashes=[5,15];}ctx.setLineDash(dashes);}else {console.warn("setLineDash is not supported in this browser. The dashed borders cannot be used.");this.options.shapeProperties.borderDashes=false;values.borderDashes=false;}}}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {ArrowOptions} values
   */disableBorderDashes(ctx,values){if(values.borderDashes!==false){if(ctx.setLineDash!==undefined){ctx.setLineDash([0]);}else {console.warn("setLineDash is not supported in this browser. The dashed borders cannot be used.");this.options.shapeProperties.borderDashes=false;values.borderDashes=false;}}}/**
   * Determine if the shape of a node needs to be recalculated.
   * @param {boolean} selected
   * @param {boolean} hover
   * @returns {boolean}
   * @protected
   */needsRefresh(selected,hover){if(this.refreshNeeded===true){// This is probably not the best location to reset this member.
// However, in the current logic, it is the most convenient one.
this.refreshNeeded=false;return true;}return this.width===undefined||this.labelModule.differentState(selected,hover);}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {ArrowOptions} values
   */initContextForDraw(ctx,values){const borderWidth=values.borderWidth/this.body.view.scale;ctx.lineWidth=Math.min(this.width,borderWidth);ctx.strokeStyle=values.borderColor;ctx.fillStyle=values.color;}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {ArrowOptions} values
   */performStroke(ctx,values){const borderWidth=values.borderWidth/this.body.view.scale;//draw dashed border if enabled, save and restore is required for firefox not to crash on unix.
ctx.save();// if borders are zero width, they will be drawn with width 1 by default. This prevents that
if(borderWidth>0){this.enableBorderDashes(ctx,values);//draw the border
ctx.stroke();//disable dashed border for other elements
this.disableBorderDashes(ctx,values);}ctx.restore();}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {ArrowOptions} values
   */performFill(ctx,values){ctx.save();ctx.fillStyle=values.color;// draw shadow if enabled
this.enableShadow(ctx,values);// draw the background
_fillInstanceProperty(ctx).call(ctx);// disable shadows for other elements.
this.disableShadow(ctx,values);ctx.restore();this.performStroke(ctx,values);}/**
   *
   * @param {number} margin
   * @private
   */_addBoundingBoxMargin(margin){this.boundingBox.left-=margin;this.boundingBox.top-=margin;this.boundingBox.bottom+=margin;this.boundingBox.right+=margin;}/**
   * Actual implementation of this method call.
   *
   * Doing it like this makes it easier to override
   * in the child classes.
   * @param {number} x width
   * @param {number} y height
   * @param {CanvasRenderingContext2D} ctx
   * @param {boolean} selected
   * @param {boolean} hover
   * @private
   */_updateBoundingBox(x,y,ctx,selected,hover){if(ctx!==undefined){this.resize(ctx,selected,hover);}this.left=x-this.width/2;this.top=y-this.height/2;this.boundingBox.left=this.left;this.boundingBox.top=this.top;this.boundingBox.bottom=this.top+this.height;this.boundingBox.right=this.left+this.width;}/**
   * Default implementation of this method call.
   * This acts as a stub which can be overridden.
   * @param {number} x width
   * @param {number} y height
   * @param {CanvasRenderingContext2D} ctx
   * @param {boolean} selected
   * @param {boolean} hover
   */updateBoundingBox(x,y,ctx,selected,hover){this._updateBoundingBox(x,y,ctx,selected,hover);}/**
   * Determine the dimensions to use for nodes with an internal label
   *
   * Currently, these are: Circle, Ellipse, Database, Box
   * The other nodes have external labels, and will not call this method
   *
   * If there is no label, decent default values are supplied.
   * @param {CanvasRenderingContext2D} ctx
   * @param {boolean} [selected]
   * @param {boolean} [hover]
   * @returns {{width:number, height:number}}
   */getDimensionsFromLabel(ctx,selected,hover){// NOTE: previously 'textSize' was not put in 'this' for Ellipse
// TODO: examine the consequences.
this.textSize=this.labelModule.getTextSize(ctx,selected,hover);let width=this.textSize.width;let height=this.textSize.height;const DEFAULT_SIZE=14;if(width===0){// This happens when there is no label text set
width=DEFAULT_SIZE;// use a decent default
height=DEFAULT_SIZE;// if width zero, then height also always zero
}return {width:width,height:height};}}/**
 * A Box Node/Cluster shape.
 * @augments NodeBase
 */let Box$1=class Box extends NodeBase{/**
   * @param {object} options
   * @param {object} body
   * @param {Label} labelModule
   */constructor(options,body,labelModule){super(options,body,labelModule);this._setMargins(labelModule);}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {boolean} [selected]
   * @param {boolean} [hover]
   */resize(ctx){let selected=arguments.length>1&&arguments[1]!==undefined?arguments[1]:this.selected;let hover=arguments.length>2&&arguments[2]!==undefined?arguments[2]:this.hover;if(this.needsRefresh(selected,hover)){const dimensions=this.getDimensionsFromLabel(ctx,selected,hover);this.width=dimensions.width+this.margin.right+this.margin.left;this.height=dimensions.height+this.margin.top+this.margin.bottom;this.radius=this.width/2;}}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} x width
   * @param {number} y height
   * @param {boolean} selected
   * @param {boolean} hover
   * @param {ArrowOptions} values
   */draw(ctx,x,y,selected,hover,values){this.resize(ctx,selected,hover);this.left=x-this.width/2;this.top=y-this.height/2;this.initContextForDraw(ctx,values);drawRoundRect(ctx,this.left,this.top,this.width,this.height,values.borderRadius);this.performFill(ctx,values);this.updateBoundingBox(x,y,ctx,selected,hover);this.labelModule.draw(ctx,this.left+this.textSize.width/2+this.margin.left,this.top+this.textSize.height/2+this.margin.top,selected,hover);}/**
   *
   * @param {number} x width
   * @param {number} y height
   * @param {CanvasRenderingContext2D} ctx
   * @param {boolean} selected
   * @param {boolean} hover
   */updateBoundingBox(x,y,ctx,selected,hover){this._updateBoundingBox(x,y,ctx,selected,hover);const borderRadius=this.options.shapeProperties.borderRadius;// only effective for box
this._addBoundingBoxMargin(borderRadius);}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} angle
   * @returns {number}
   */distanceToBorder(ctx,angle){if(ctx){this.resize(ctx);}const borderWidth=this.options.borderWidth;return Math.min(Math.abs(this.width/2/Math.cos(angle)),Math.abs(this.height/2/Math.sin(angle)))+borderWidth;}};/**
 * NOTE: This is a bad base class
 *
 * Child classes are:
 *
 * Image       - uses *only* image methods
 * Circle      - uses *only* _drawRawCircle
 * CircleImage - uses all
 *
 * TODO: Refactor, move _drawRawCircle to different module, derive Circle from NodeBase
 * Rename this to ImageBase
 * Consolidate common code in Image and CircleImage to base class
 * @augments NodeBase
 */class CircleImageBase extends NodeBase{/**
   * @param {object} options
   * @param {object} body
   * @param {Label} labelModule
   */constructor(options,body,labelModule){super(options,body,labelModule);this.labelOffset=0;this.selected=false;}/**
   *
   * @param {object} options
   * @param {object} [imageObj]
   * @param {object} [imageObjAlt]
   */setOptions(options,imageObj,imageObjAlt){this.options=options;if(!(imageObj===undefined&&imageObjAlt===undefined)){this.setImages(imageObj,imageObjAlt);}}/**
   * Set the images for this node.
   *
   * The images can be updated after the initial setting of options;
   * therefore, this method needs to be reentrant.
   *
   * For correct working in error cases, it is necessary to properly set
   * field 'nodes.brokenImage' in the options.
   * @param {Image} imageObj  required; main image to show for this node
   * @param {Image|undefined} imageObjAlt optional; image to show when node is selected
   */setImages(imageObj,imageObjAlt){if(imageObjAlt&&this.selected){this.imageObj=imageObjAlt;this.imageObjAlt=imageObj;}else {this.imageObj=imageObj;this.imageObjAlt=imageObjAlt;}}/**
   * Set selection and switch between the base and the selected image.
   *
   * Do the switch only if imageObjAlt exists.
   * @param {boolean} selected value of new selected state for current node
   */switchImages(selected){const selection_changed=selected&&!this.selected||!selected&&this.selected;this.selected=selected;// Remember new selection
if(this.imageObjAlt!==undefined&&selection_changed){const imageTmp=this.imageObj;this.imageObj=this.imageObjAlt;this.imageObjAlt=imageTmp;}}/**
   * Returns Image Padding from node options
   * @returns {{top: number,left: number,bottom: number,right: number}} image padding inside this shape
   * @private
   */_getImagePadding(){const imgPadding={top:0,right:0,bottom:0,left:0};if(this.options.imagePadding){const optImgPadding=this.options.imagePadding;if(typeof optImgPadding=="object"){imgPadding.top=optImgPadding.top;imgPadding.right=optImgPadding.right;imgPadding.bottom=optImgPadding.bottom;imgPadding.left=optImgPadding.left;}else {imgPadding.top=optImgPadding;imgPadding.right=optImgPadding;imgPadding.bottom=optImgPadding;imgPadding.left=optImgPadding;}}return imgPadding;}/**
   * Adjust the node dimensions for a loaded image.
   *
   * Pre: this.imageObj is valid
   */_resizeImage(){let width,height;if(this.options.shapeProperties.useImageSize===false){// Use the size property
let ratio_width=1;let ratio_height=1;// Only calculate the proper ratio if both width and height not zero
if(this.imageObj.width&&this.imageObj.height){if(this.imageObj.width>this.imageObj.height){ratio_width=this.imageObj.width/this.imageObj.height;}else {ratio_height=this.imageObj.height/this.imageObj.width;}}width=this.options.size*2*ratio_width;height=this.options.size*2*ratio_height;}else {// Use the image size with image padding
const imgPadding=this._getImagePadding();width=this.imageObj.width+imgPadding.left+imgPadding.right;height=this.imageObj.height+imgPadding.top+imgPadding.bottom;}this.width=width;this.height=height;this.radius=0.5*this.width;}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} x width
   * @param {number} y height
   * @param {ArrowOptions} values
   * @private
   */_drawRawCircle(ctx,x,y,values){this.initContextForDraw(ctx,values);drawCircle(ctx,x,y,values.size);this.performFill(ctx,values);}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {ArrowOptions} values
   * @private
   */_drawImageAtPosition(ctx,values){if(this.imageObj.width!=0){// draw the image
ctx.globalAlpha=values.opacity!==undefined?values.opacity:1;// draw shadow if enabled
this.enableShadow(ctx,values);let factor=1;if(this.options.shapeProperties.interpolation===true){factor=this.imageObj.width/this.width/this.body.view.scale;}const imgPadding=this._getImagePadding();const imgPosLeft=this.left+imgPadding.left;const imgPosTop=this.top+imgPadding.top;const imgWidth=this.width-imgPadding.left-imgPadding.right;const imgHeight=this.height-imgPadding.top-imgPadding.bottom;this.imageObj.drawImageAtPosition(ctx,factor,imgPosLeft,imgPosTop,imgWidth,imgHeight);// disable shadows for other elements.
this.disableShadow(ctx,values);}}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} x width
   * @param {number} y height
   * @param {boolean} selected
   * @param {boolean} hover
   * @private
   */_drawImageLabel(ctx,x,y,selected,hover){let offset=0;if(this.height!==undefined){offset=this.height*0.5;const labelDimensions=this.labelModule.getTextSize(ctx,selected,hover);if(labelDimensions.lineCount>=1){offset+=labelDimensions.height/2;}}const yLabel=y+offset;if(this.options.label){this.labelOffset=offset;}this.labelModule.draw(ctx,x,yLabel,selected,hover,"hanging");}}/**
 * A Circle Node/Cluster shape.
 * @augments CircleImageBase
 */let Circle$1=class Circle extends CircleImageBase{/**
   * @param {object} options
   * @param {object} body
   * @param {Label} labelModule
   */constructor(options,body,labelModule){super(options,body,labelModule);this._setMargins(labelModule);}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {boolean} [selected]
   * @param {boolean} [hover]
   */resize(ctx){let selected=arguments.length>1&&arguments[1]!==undefined?arguments[1]:this.selected;let hover=arguments.length>2&&arguments[2]!==undefined?arguments[2]:this.hover;if(this.needsRefresh(selected,hover)){const dimensions=this.getDimensionsFromLabel(ctx,selected,hover);const diameter=Math.max(dimensions.width+this.margin.right+this.margin.left,dimensions.height+this.margin.top+this.margin.bottom);this.options.size=diameter/2;// NOTE: this size field only set here, not in Ellipse, Database, Box
this.width=diameter;this.height=diameter;this.radius=this.width/2;}}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} x width
   * @param {number} y height
   * @param {boolean} selected
   * @param {boolean} hover
   * @param {ArrowOptions} values
   */draw(ctx,x,y,selected,hover,values){this.resize(ctx,selected,hover);this.left=x-this.width/2;this.top=y-this.height/2;this._drawRawCircle(ctx,x,y,values);this.updateBoundingBox(x,y);this.labelModule.draw(ctx,this.left+this.textSize.width/2+this.margin.left,y,selected,hover);}/**
   *
   * @param {number} x width
   * @param {number} y height
   */updateBoundingBox(x,y){this.boundingBox.top=y-this.options.size;this.boundingBox.left=x-this.options.size;this.boundingBox.right=x+this.options.size;this.boundingBox.bottom=y+this.options.size;}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @returns {number}
   */distanceToBorder(ctx){if(ctx){this.resize(ctx);}return this.width*0.5;}};/**
 * A CircularImage Node/Cluster shape.
 * @augments CircleImageBase
 */class CircularImage extends CircleImageBase{/**
   * @param {object} options
   * @param {object} body
   * @param {Label} labelModule
   * @param {Image} imageObj
   * @param {Image} imageObjAlt
   */constructor(options,body,labelModule,imageObj,imageObjAlt){super(options,body,labelModule);this.setImages(imageObj,imageObjAlt);}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {boolean} [selected]
   * @param {boolean} [hover]
   */resize(ctx){let selected=arguments.length>1&&arguments[1]!==undefined?arguments[1]:this.selected;let hover=arguments.length>2&&arguments[2]!==undefined?arguments[2]:this.hover;const imageAbsent=this.imageObj.src===undefined||this.imageObj.width===undefined||this.imageObj.height===undefined;if(imageAbsent){const diameter=this.options.size*2;this.width=diameter;this.height=diameter;this.radius=0.5*this.width;return;}// At this point, an image is present, i.e. this.imageObj is valid.
if(this.needsRefresh(selected,hover)){this._resizeImage();}}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} x width
   * @param {number} y height
   * @param {boolean} selected
   * @param {boolean} hover
   * @param {ArrowOptions} values
   */draw(ctx,x,y,selected,hover,values){this.switchImages(selected);this.resize();let labelX=x,labelY=y;if(this.options.shapeProperties.coordinateOrigin==="top-left"){this.left=x;this.top=y;labelX+=this.width/2;labelY+=this.height/2;}else {this.left=x-this.width/2;this.top=y-this.height/2;}// draw the background circle. IMPORTANT: the stroke in this method is used by the clip method below.
this._drawRawCircle(ctx,labelX,labelY,values);// now we draw in the circle, we save so we can revert the clip operation after drawing.
ctx.save();// clip is used to use the stroke in drawRawCircle as an area that we can draw in.
ctx.clip();// draw the image
this._drawImageAtPosition(ctx,values);// restore so we can again draw on the full canvas
ctx.restore();this._drawImageLabel(ctx,labelX,labelY,selected,hover);this.updateBoundingBox(x,y);}// TODO: compare with Circle.updateBoundingBox(), consolidate? More stuff is happening here
/**
   *
   * @param {number} x width
   * @param {number} y height
   */updateBoundingBox(x,y){if(this.options.shapeProperties.coordinateOrigin==="top-left"){this.boundingBox.top=y;this.boundingBox.left=x;this.boundingBox.right=x+this.options.size*2;this.boundingBox.bottom=y+this.options.size*2;}else {this.boundingBox.top=y-this.options.size;this.boundingBox.left=x-this.options.size;this.boundingBox.right=x+this.options.size;this.boundingBox.bottom=y+this.options.size;}// TODO: compare with Image.updateBoundingBox(), consolidate?
this.boundingBox.left=Math.min(this.boundingBox.left,this.labelModule.size.left);this.boundingBox.right=Math.max(this.boundingBox.right,this.labelModule.size.left+this.labelModule.size.width);this.boundingBox.bottom=Math.max(this.boundingBox.bottom,this.boundingBox.bottom+this.labelOffset);}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @returns {number}
   */distanceToBorder(ctx){if(ctx){this.resize(ctx);}return this.width*0.5;}}/**
 * Base class for constructing Node/Cluster Shapes.
 * @augments NodeBase
 */class ShapeBase extends NodeBase{/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {boolean} [selected]
   * @param {boolean} [hover]
   * @param {object} [values]
   */resize(ctx){let selected=arguments.length>1&&arguments[1]!==undefined?arguments[1]:this.selected;let hover=arguments.length>2&&arguments[2]!==undefined?arguments[2]:this.hover;let values=arguments.length>3&&arguments[3]!==undefined?arguments[3]:{size:this.options.size};if(this.needsRefresh(selected,hover)){var _this$customSizeWidth,_this$customSizeHeigh;this.labelModule.getTextSize(ctx,selected,hover);const size=2*values.size;this.width=(_this$customSizeWidth=this.customSizeWidth)!==null&&_this$customSizeWidth!==void 0?_this$customSizeWidth:size;this.height=(_this$customSizeHeigh=this.customSizeHeight)!==null&&_this$customSizeHeigh!==void 0?_this$customSizeHeigh:size;this.radius=0.5*this.width;}}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {string} shape
   * @param {number} sizeMultiplier - Unused! TODO: Remove next major release
   * @param {number} x
   * @param {number} y
   * @param {boolean} selected
   * @param {boolean} hover
   * @param {ArrowOptions} values
   * @private
   * @returns {object} Callbacks to draw later on higher layers.
   */_drawShape(ctx,shape,sizeMultiplier,x,y,selected,hover,values){this.resize(ctx,selected,hover,values);this.left=x-this.width/2;this.top=y-this.height/2;this.initContextForDraw(ctx,values);getShape(shape)(ctx,x,y,values.size);this.performFill(ctx,values);if(this.options.icon!==undefined){if(this.options.icon.code!==undefined){ctx.font=(selected?"bold ":"")+this.height/2+"px "+(this.options.icon.face||"FontAwesome");ctx.fillStyle=this.options.icon.color||"black";ctx.textAlign="center";ctx.textBaseline="middle";ctx.fillText(this.options.icon.code,x,y);}}return {drawExternalLabel:()=>{if(this.options.label!==undefined){// Need to call following here in order to ensure value for
// `this.labelModule.size.height`.
this.labelModule.calculateLabelSize(ctx,selected,hover,x,y,"hanging");const yLabel=y+0.5*this.height+0.5*this.labelModule.size.height;this.labelModule.draw(ctx,x,yLabel,selected,hover,"hanging");}this.updateBoundingBox(x,y);}};}/**
   *
   * @param {number} x
   * @param {number} y
   */updateBoundingBox(x,y){this.boundingBox.top=y-this.options.size;this.boundingBox.left=x-this.options.size;this.boundingBox.right=x+this.options.size;this.boundingBox.bottom=y+this.options.size;if(this.options.label!==undefined&&this.labelModule.size.width>0){this.boundingBox.left=Math.min(this.boundingBox.left,this.labelModule.size.left);this.boundingBox.right=Math.max(this.boundingBox.right,this.labelModule.size.left+this.labelModule.size.width);this.boundingBox.bottom=Math.max(this.boundingBox.bottom,this.boundingBox.bottom+this.labelModule.size.height);}}}function ownKeys$3(e,r){var t=_Object$keys(e);if(_Object$getOwnPropertySymbols){var o=_Object$getOwnPropertySymbols(e);r&&(o=_filterInstanceProperty(o).call(o,function(r){return _Object$getOwnPropertyDescriptor(e,r).enumerable;})),t.push.apply(t,o);}return t;}function _objectSpread$3(e){for(var r=1;r<arguments.length;r++){var _context,_context2;var t=null!=arguments[r]?arguments[r]:{};r%2?_forEachInstanceProperty(_context=ownKeys$3(Object(t),true)).call(_context,function(r){_defineProperty(e,r,t[r]);}):_Object$getOwnPropertyDescriptors?_Object$defineProperties(e,_Object$getOwnPropertyDescriptors(t)):_forEachInstanceProperty(_context2=ownKeys$3(Object(t))).call(_context2,function(r){_Object$defineProperty(e,r,_Object$getOwnPropertyDescriptor(t,r));});}return e;}/**
 * A CustomShape Node/Cluster shape.
 * @augments ShapeBase
 */class CustomShape extends ShapeBase{/**
   * @param {object} options
   * @param {object} body
   * @param {Label} labelModule
   * @param {Function} ctxRenderer
   */constructor(options,body,labelModule,ctxRenderer){super(options,body,labelModule,ctxRenderer);this.ctxRenderer=ctxRenderer;}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} x width
   * @param {number} y height
   * @param {boolean} selected
   * @param {boolean} hover
   * @param {ArrowOptions} values
   * @returns {object} Callbacks to draw later on different layers.
   */draw(ctx,x,y,selected,hover,values){this.resize(ctx,selected,hover,values);this.left=x-this.width/2;this.top=y-this.height/2;// Guard right away because someone may just draw in the function itself.
ctx.save();const drawLater=this.ctxRenderer({ctx,id:this.options.id,x,y,state:{selected,hover},style:_objectSpread$3({},values),label:this.options.label});// Render the node shape bellow arrows.
if(drawLater.drawNode!=null){drawLater.drawNode();}ctx.restore();if(drawLater.drawExternalLabel){// Guard the external label (above arrows) drawing function.
const drawExternalLabel=drawLater.drawExternalLabel;drawLater.drawExternalLabel=()=>{ctx.save();drawExternalLabel();ctx.restore();};}if(drawLater.nodeDimensions){this.customSizeWidth=drawLater.nodeDimensions.width;this.customSizeHeight=drawLater.nodeDimensions.height;}return drawLater;}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} angle
   * @returns {number}
   */distanceToBorder(ctx,angle){return this._distanceToBorder(ctx,angle);}}/**
 * A Database Node/Cluster shape.
 * @augments NodeBase
 */class Database extends NodeBase{/**
   * @param {object} options
   * @param {object} body
   * @param {Label} labelModule
   */constructor(options,body,labelModule){super(options,body,labelModule);this._setMargins(labelModule);}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {boolean} selected
   * @param {boolean} hover
   */resize(ctx,selected,hover){if(this.needsRefresh(selected,hover)){const dimensions=this.getDimensionsFromLabel(ctx,selected,hover);const size=dimensions.width+this.margin.right+this.margin.left;this.width=size;this.height=size;this.radius=this.width/2;}}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} x width
   * @param {number} y height
   * @param {boolean} selected
   * @param {boolean} hover
   * @param {ArrowOptions} values
   */draw(ctx,x,y,selected,hover,values){this.resize(ctx,selected,hover);this.left=x-this.width/2;this.top=y-this.height/2;this.initContextForDraw(ctx,values);drawDatabase(ctx,x-this.width/2,y-this.height/2,this.width,this.height);this.performFill(ctx,values);this.updateBoundingBox(x,y,ctx,selected,hover);this.labelModule.draw(ctx,this.left+this.textSize.width/2+this.margin.left,this.top+this.textSize.height/2+this.margin.top,selected,hover);}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} angle
   * @returns {number}
   */distanceToBorder(ctx,angle){return this._distanceToBorder(ctx,angle);}}/**
 * A Diamond Node/Cluster shape.
 * @augments ShapeBase
 */let Diamond$1=class Diamond extends ShapeBase{/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} x width
   * @param {number} y height
   * @param {boolean} selected
   * @param {boolean} hover
   * @param {ArrowOptions} values
   * @returns {object} Callbacks to draw later on higher layers.
   */draw(ctx,x,y,selected,hover,values){return this._drawShape(ctx,"diamond",4,x,y,selected,hover,values);}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} angle
   * @returns {number}
   */distanceToBorder(ctx,angle){return this._distanceToBorder(ctx,angle);}};/**
 * A Dot Node/Cluster shape.
 * @augments ShapeBase
 */class Dot extends ShapeBase{/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} x width
   * @param {number} y height
   * @param {boolean} selected
   * @param {boolean} hover
   * @param {ArrowOptions} values
   * @returns {object} Callbacks to draw later on higher layers.
   */draw(ctx,x,y,selected,hover,values){return this._drawShape(ctx,"circle",2,x,y,selected,hover,values);}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @returns {number}
   */distanceToBorder(ctx){if(ctx){this.resize(ctx);}return this.options.size;}}/**
 * Am Ellipse Node/Cluster shape.
 * @augments NodeBase
 */class Ellipse extends NodeBase{/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {boolean} [selected]
   * @param {boolean} [hover]
   */resize(ctx){let selected=arguments.length>1&&arguments[1]!==undefined?arguments[1]:this.selected;let hover=arguments.length>2&&arguments[2]!==undefined?arguments[2]:this.hover;if(this.needsRefresh(selected,hover)){const dimensions=this.getDimensionsFromLabel(ctx,selected,hover);this.height=dimensions.height*2;this.width=dimensions.width+dimensions.height;this.radius=0.5*this.width;}}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} x width
   * @param {number} y height
   * @param {boolean} selected
   * @param {boolean} hover
   * @param {ArrowOptions} values
   */draw(ctx,x,y,selected,hover,values){this.resize(ctx,selected,hover);this.left=x-this.width*0.5;this.top=y-this.height*0.5;this.initContextForDraw(ctx,values);drawEllipse(ctx,this.left,this.top,this.width,this.height);this.performFill(ctx,values);this.updateBoundingBox(x,y,ctx,selected,hover);this.labelModule.draw(ctx,x,y,selected,hover);}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} angle
   * @returns {number}
   */distanceToBorder(ctx,angle){if(ctx){this.resize(ctx);}const a=this.width*0.5;const b=this.height*0.5;const w=Math.sin(angle)*a;const h=Math.cos(angle)*b;return a*b/Math.sqrt(w*w+h*h);}}/**
 * An icon replacement for the default Node shape.
 * @augments NodeBase
 */class Icon extends NodeBase{/**
   * @param {object} options
   * @param {object} body
   * @param {Label} labelModule
   */constructor(options,body,labelModule){super(options,body,labelModule);this._setMargins(labelModule);}/**
   *
   * @param {CanvasRenderingContext2D} ctx - Unused.
   * @param {boolean} [selected]
   * @param {boolean} [hover]
   */resize(ctx,selected,hover){if(this.needsRefresh(selected,hover)){this.iconSize={width:Number(this.options.icon.size),height:Number(this.options.icon.size)};this.width=this.iconSize.width+this.margin.right+this.margin.left;this.height=this.iconSize.height+this.margin.top+this.margin.bottom;this.radius=0.5*this.width;}}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} x width
   * @param {number} y height
   * @param {boolean} selected
   * @param {boolean} hover
   * @param {ArrowOptions} values
   * @returns {object} Callbacks to draw later on higher layers.
   */draw(ctx,x,y,selected,hover,values){this.resize(ctx,selected,hover);this.options.icon.size=this.options.icon.size||50;this.left=x-this.width/2;this.top=y-this.height/2;this._icon(ctx,x,y,selected,hover,values);return {drawExternalLabel:()=>{if(this.options.label!==undefined){const iconTextSpacing=5;this.labelModule.draw(ctx,this.left+this.iconSize.width/2+this.margin.left,y+this.height/2+iconTextSpacing,selected);}this.updateBoundingBox(x,y);}};}/**
   *
   * @param {number} x
   * @param {number} y
   */updateBoundingBox(x,y){this.boundingBox.top=y-this.options.icon.size*0.5;this.boundingBox.left=x-this.options.icon.size*0.5;this.boundingBox.right=x+this.options.icon.size*0.5;this.boundingBox.bottom=y+this.options.icon.size*0.5;if(this.options.label!==undefined&&this.labelModule.size.width>0){const iconTextSpacing=5;this.boundingBox.left=Math.min(this.boundingBox.left,this.labelModule.size.left);this.boundingBox.right=Math.max(this.boundingBox.right,this.labelModule.size.left+this.labelModule.size.width);this.boundingBox.bottom=Math.max(this.boundingBox.bottom,this.boundingBox.bottom+this.labelModule.size.height+iconTextSpacing);}}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} x width
   * @param {number} y height
   * @param {boolean} selected
   * @param {boolean} hover - Unused
   * @param {ArrowOptions} values
   */_icon(ctx,x,y,selected,hover,values){const iconSize=Number(this.options.icon.size);if(this.options.icon.code!==undefined){ctx.font=[this.options.icon.weight!=null?this.options.icon.weight:selected?"bold":"",// If the weight is forced (for example to make Font Awesome 5 work
// properly) substitute slightly bigger size for bold font face.
(this.options.icon.weight!=null&&selected?5:0)+iconSize+"px",this.options.icon.face].join(" ");// draw icon
ctx.fillStyle=this.options.icon.color||"black";ctx.textAlign="center";ctx.textBaseline="middle";// draw shadow if enabled
this.enableShadow(ctx,values);ctx.fillText(this.options.icon.code,x,y);// disable shadows for other elements.
this.disableShadow(ctx,values);}else {console.error("When using the icon shape, you need to define the code in the icon options object. This can be done per node or globally.");}}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} angle
   * @returns {number}
   */distanceToBorder(ctx,angle){return this._distanceToBorder(ctx,angle);}}/**
 * An image-based replacement for the default Node shape.
 * @augments CircleImageBase
 */let Image$2=class Image extends CircleImageBase{/**
   * @param {object} options
   * @param {object} body
   * @param {Label} labelModule
   * @param {Image} imageObj
   * @param {Image} imageObjAlt
   */constructor(options,body,labelModule,imageObj,imageObjAlt){super(options,body,labelModule);this.setImages(imageObj,imageObjAlt);}/**
   *
   * @param {CanvasRenderingContext2D} ctx - Unused.
   * @param {boolean} [selected]
   * @param {boolean} [hover]
   */resize(ctx){let selected=arguments.length>1&&arguments[1]!==undefined?arguments[1]:this.selected;let hover=arguments.length>2&&arguments[2]!==undefined?arguments[2]:this.hover;const imageAbsent=this.imageObj.src===undefined||this.imageObj.width===undefined||this.imageObj.height===undefined;if(imageAbsent){const side=this.options.size*2;this.width=side;this.height=side;return;}if(this.needsRefresh(selected,hover)){this._resizeImage();}}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} x width
   * @param {number} y height
   * @param {boolean} selected
   * @param {boolean} hover
   * @param {ArrowOptions} values
   */draw(ctx,x,y,selected,hover,values){ctx.save();this.switchImages(selected);this.resize();let labelX=x,labelY=y;if(this.options.shapeProperties.coordinateOrigin==="top-left"){this.left=x;this.top=y;labelX+=this.width/2;labelY+=this.height/2;}else {this.left=x-this.width/2;this.top=y-this.height/2;}if(this.options.shapeProperties.useBorderWithImage===true){const neutralborderWidth=this.options.borderWidth;const selectionLineWidth=this.options.borderWidthSelected||2*this.options.borderWidth;const borderWidth=(selected?selectionLineWidth:neutralborderWidth)/this.body.view.scale;ctx.lineWidth=Math.min(this.width,borderWidth);ctx.beginPath();let strokeStyle=selected?this.options.color.highlight.border:hover?this.options.color.hover.border:this.options.color.border;let fillStyle=selected?this.options.color.highlight.background:hover?this.options.color.hover.background:this.options.color.background;if(values.opacity!==undefined){strokeStyle=overrideOpacity(strokeStyle,values.opacity);fillStyle=overrideOpacity(fillStyle,values.opacity);}// setup the line properties.
ctx.strokeStyle=strokeStyle;// set a fillstyle
ctx.fillStyle=fillStyle;// draw a rectangle to form the border around. This rectangle is filled so the opacity of a picture (in future vis releases?) can be used to tint the image
ctx.rect(this.left-0.5*ctx.lineWidth,this.top-0.5*ctx.lineWidth,this.width+ctx.lineWidth,this.height+ctx.lineWidth);_fillInstanceProperty(ctx).call(ctx);this.performStroke(ctx,values);ctx.closePath();}this._drawImageAtPosition(ctx,values);this._drawImageLabel(ctx,labelX,labelY,selected,hover);this.updateBoundingBox(x,y);ctx.restore();}/**
   *
   * @param {number} x
   * @param {number} y
   */updateBoundingBox(x,y){this.resize();if(this.options.shapeProperties.coordinateOrigin==="top-left"){this.left=x;this.top=y;}else {this.left=x-this.width/2;this.top=y-this.height/2;}this.boundingBox.left=this.left;this.boundingBox.top=this.top;this.boundingBox.bottom=this.top+this.height;this.boundingBox.right=this.left+this.width;if(this.options.label!==undefined&&this.labelModule.size.width>0){this.boundingBox.left=Math.min(this.boundingBox.left,this.labelModule.size.left);this.boundingBox.right=Math.max(this.boundingBox.right,this.labelModule.size.left+this.labelModule.size.width);this.boundingBox.bottom=Math.max(this.boundingBox.bottom,this.boundingBox.bottom+this.labelOffset);}}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} angle
   * @returns {number}
   */distanceToBorder(ctx,angle){return this._distanceToBorder(ctx,angle);}};/**
 * A Square Node/Cluster shape.
 * @augments ShapeBase
 */class Square extends ShapeBase{/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} x width
   * @param {number} y height
   * @param {boolean} selected
   * @param {boolean} hover
   * @param {ArrowOptions} values
   * @returns {object} Callbacks to draw later on higher layers.
   */draw(ctx,x,y,selected,hover,values){return this._drawShape(ctx,"square",2,x,y,selected,hover,values);}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} angle
   * @returns {number}
   */distanceToBorder(ctx,angle){return this._distanceToBorder(ctx,angle);}}/**
 * A Hexagon Node/Cluster shape.
 * @augments ShapeBase
 */class Hexagon extends ShapeBase{/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} x width
   * @param {number} y height
   * @param {boolean} selected
   * @param {boolean} hover
   * @param {ArrowOptions} values
   * @returns {object} Callbacks to draw later on higher layers.
   */draw(ctx,x,y,selected,hover,values){return this._drawShape(ctx,"hexagon",4,x,y,selected,hover,values);}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} angle
   * @returns {number}
   */distanceToBorder(ctx,angle){return this._distanceToBorder(ctx,angle);}}/**
 * A Star Node/Cluster shape.
 * @augments ShapeBase
 */class Star extends ShapeBase{/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} x width
   * @param {number} y height
   * @param {boolean} selected
   * @param {boolean} hover
   * @param {ArrowOptions} values
   * @returns {object} Callbacks to draw later on higher layers.
   */draw(ctx,x,y,selected,hover,values){return this._drawShape(ctx,"star",4,x,y,selected,hover,values);}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} angle
   * @returns {number}
   */distanceToBorder(ctx,angle){return this._distanceToBorder(ctx,angle);}}/**
 * A text-based replacement for the default Node shape.
 * @augments NodeBase
 */class Text extends NodeBase{/**
   * @param {object} options
   * @param {object} body
   * @param {Label} labelModule
   */constructor(options,body,labelModule){super(options,body,labelModule);this._setMargins(labelModule);}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {boolean} selected
   * @param {boolean} hover
   */resize(ctx,selected,hover){if(this.needsRefresh(selected,hover)){this.textSize=this.labelModule.getTextSize(ctx,selected,hover);this.width=this.textSize.width+this.margin.right+this.margin.left;this.height=this.textSize.height+this.margin.top+this.margin.bottom;this.radius=0.5*this.width;}}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} x width
   * @param {number} y height
   * @param {boolean} selected
   * @param {boolean} hover
   * @param {ArrowOptions} values
   */draw(ctx,x,y,selected,hover,values){this.resize(ctx,selected,hover);this.left=x-this.width/2;this.top=y-this.height/2;// draw shadow if enabled
this.enableShadow(ctx,values);this.labelModule.draw(ctx,this.left+this.textSize.width/2+this.margin.left,this.top+this.textSize.height/2+this.margin.top,selected,hover);// disable shadows for other elements.
this.disableShadow(ctx,values);this.updateBoundingBox(x,y,ctx,selected,hover);}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} angle
   * @returns {number}
   */distanceToBorder(ctx,angle){return this._distanceToBorder(ctx,angle);}}/**
 * A Triangle Node/Cluster shape.
 * @augments ShapeBase
 */let Triangle$1=class Triangle extends ShapeBase{/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} x
   * @param {number} y
   * @param {boolean} selected
   * @param {boolean} hover
   * @param {ArrowOptions} values
   * @returns {object} Callbacks to draw later on higher layers.
   */draw(ctx,x,y,selected,hover,values){return this._drawShape(ctx,"triangle",3,x,y,selected,hover,values);}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} angle
   * @returns {number}
   */distanceToBorder(ctx,angle){return this._distanceToBorder(ctx,angle);}};/**
 * A downward facing Triangle Node/Cluster shape.
 * @augments ShapeBase
 */class TriangleDown extends ShapeBase{/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} x
   * @param {number} y
   * @param {boolean} selected
   * @param {boolean} hover
   * @param {ArrowOptions} values
   * @returns {object} Callbacks to draw later on higher layers.
   */draw(ctx,x,y,selected,hover,values){return this._drawShape(ctx,"triangleDown",3,x,y,selected,hover,values);}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {number} angle
   * @returns {number}
   */distanceToBorder(ctx,angle){return this._distanceToBorder(ctx,angle);}}function ownKeys$2(e,r){var t=_Object$keys(e);if(_Object$getOwnPropertySymbols){var o=_Object$getOwnPropertySymbols(e);r&&(o=_filterInstanceProperty(o).call(o,function(r){return _Object$getOwnPropertyDescriptor(e,r).enumerable;})),t.push.apply(t,o);}return t;}function _objectSpread$2(e){for(var r=1;r<arguments.length;r++){var _context5,_context6;var t=null!=arguments[r]?arguments[r]:{};r%2?_forEachInstanceProperty(_context5=ownKeys$2(Object(t),true)).call(_context5,function(r){_defineProperty(e,r,t[r]);}):_Object$getOwnPropertyDescriptors?_Object$defineProperties(e,_Object$getOwnPropertyDescriptors(t)):_forEachInstanceProperty(_context6=ownKeys$2(Object(t))).call(_context6,function(r){_Object$defineProperty(e,r,_Object$getOwnPropertyDescriptor(t,r));});}return e;}/**
 * A node. A node can be connected to other nodes via one or multiple edges.
 */let Node$1 = class Node{/**
   *
   * @param {object} options An object containing options for the node. All
   *                            options are optional, except for the id.
   *                              {number} id     Id of the node. Required
   *                              {string} label  Text label for the node
   *                              {number} x      Horizontal position of the node
   *                              {number} y      Vertical position of the node
   *                              {string} shape  Node shape
   *                              {string} image  An image url
   *                              {string} title  A title text, can be HTML
   *                              {anytype} group A group name or number
   * @param {object} body               Shared state of current network instance
   * @param {Network.Images} imagelist  A list with images. Only needed when the node has an image
   * @param {Groups} grouplist          A list with groups. Needed for retrieving group options
   * @param {object} globalOptions      Current global node options; these serve as defaults for the node instance
   * @param {object} defaultOptions     Global default options for nodes; note that this is also the prototype
   *                                    for parameter `globalOptions`.
   */constructor(options,body,imagelist,grouplist,globalOptions,defaultOptions){this.options=bridgeObject(globalOptions);this.globalOptions=globalOptions;this.defaultOptions=defaultOptions;this.body=body;this.edges=[];// all edges connected to this node
// set defaults for the options
this.id=undefined;this.imagelist=imagelist;this.grouplist=grouplist;// state options
this.x=undefined;this.y=undefined;this.baseSize=this.options.size;this.baseFontSize=this.options.font.size;this.predefinedPosition=false;// used to check if initial fit should just take the range or approximate
this.selected=false;this.hover=false;this.labelModule=new Label(this.body,this.options,false/* Not edge label */);this.setOptions(options);}/**
   * Attach a edge to the node
   * @param {Edge} edge
   */attachEdge(edge){var _context;if(_indexOfInstanceProperty(_context=this.edges).call(_context,edge)===-1){this.edges.push(edge);}}/**
   * Detach a edge from the node
   * @param {Edge} edge
   */detachEdge(edge){var _context2;const index=_indexOfInstanceProperty(_context2=this.edges).call(_context2,edge);if(index!=-1){var _context3;_spliceInstanceProperty(_context3=this.edges).call(_context3,index,1);}}/**
   * Set or overwrite options for the node
   * @param {object} options an object with options
   * @returns {null|boolean}
   */setOptions(options){const currentShape=this.options.shape;if(!options){return;// Note that the return value will be 'undefined'! This is OK.
}// Save the color for later.
// This is necessary in order to prevent local color from being overwritten by group color.
// TODO: To prevent such workarounds the way options are handled should be rewritten from scratch.
// This is not the only problem with current options handling.
if(typeof options.color!=="undefined"){this._localColor=options.color;}// basic options
if(options.id!==undefined){this.id=options.id;}if(this.id===undefined){throw new Error("Node must have an id");}Node.checkMass(options,this.id);// set these options locally
// clear x and y positions
if(options.x!==undefined){if(options.x===null){this.x=undefined;this.predefinedPosition=false;}else {this.x=_parseInt(options.x);this.predefinedPosition=true;}}if(options.y!==undefined){if(options.y===null){this.y=undefined;this.predefinedPosition=false;}else {this.y=_parseInt(options.y);this.predefinedPosition=true;}}if(options.size!==undefined){this.baseSize=options.size;}if(options.value!==undefined){options.value=_parseFloat(options.value);}// this transforms all shorthands into fully defined options
Node.parseOptions(this.options,options,true,this.globalOptions,this.grouplist);const pile=[options,this.options,this.defaultOptions];this.chooser=choosify("node",pile);this._load_images();this.updateLabelModule(options);// Need to set local opacity after `this.updateLabelModule(options);` because `this.updateLabelModule(options);` overrites local opacity with group opacity
if(options.opacity!==undefined&&Node.checkOpacity(options.opacity)){this.options.opacity=options.opacity;}this.updateShape(currentShape);return options.hidden!==undefined||options.physics!==undefined;}/**
   * Load the images from the options, for the nodes that need them.
   *
   * Images are always loaded, even if they are not used in the current shape.
   * The user may switch to an image shape later on.
   * @private
   */_load_images(){if(this.options.shape==="circularImage"||this.options.shape==="image"){if(this.options.image===undefined){throw new Error("Option image must be defined for node type '"+this.options.shape+"'");}}if(this.options.image===undefined){return;}if(this.imagelist===undefined){throw new Error("Internal Error: No images provided");}if(typeof this.options.image==="string"){this.imageObj=this.imagelist.load(this.options.image,this.options.brokenImage,this.id);}else {if(this.options.image.unselected===undefined){throw new Error("No unselected image provided");}this.imageObj=this.imagelist.load(this.options.image.unselected,this.options.brokenImage,this.id);if(this.options.image.selected!==undefined){this.imageObjAlt=this.imagelist.load(this.options.image.selected,this.options.brokenImage,this.id);}else {this.imageObjAlt=undefined;}}}/**
   * Check that opacity is only between 0 and 1
   * @param {number} opacity
   * @returns {boolean}
   */static checkOpacity(opacity){return 0<=opacity&&opacity<=1;}/**
   * Check that origin is 'center' or 'top-left'
   * @param {string} origin
   * @returns {boolean}
   */static checkCoordinateOrigin(origin){return origin===undefined||origin==="center"||origin==="top-left";}/**
   * Copy group option values into the node options.
   *
   * The group options override the global node options, so the copy of group options
   * must happen *after* the global node options have been set.
   *
   * This method must also be called also if the global node options have changed and the group options did not.
   * @param {object} parentOptions
   * @param {object} newOptions  new values for the options, currently only passed in for check
   * @param {object} groupList
   */static updateGroupOptions(parentOptions,newOptions,groupList){var _context4;if(groupList===undefined)return;// No groups, nothing to do
const group=parentOptions.group;// paranoia: the selected group is already merged into node options, check.
if(newOptions!==undefined&&newOptions.group!==undefined&&group!==newOptions.group){throw new Error("updateGroupOptions: group values in options don't match.");}const hasGroup=typeof group==="number"||typeof group==="string"&&group!="";if(!hasGroup)return;// current node has no group, no need to merge
const groupObj=groupList.get(group);if(groupObj.opacity!==undefined&&newOptions.opacity===undefined){if(!Node.checkOpacity(groupObj.opacity)){console.error("Invalid option for node opacity. Value must be between 0 and 1, found: "+groupObj.opacity);groupObj.opacity=undefined;}}// Skip any new option to avoid them being overridden by the group options.
const skipProperties=_filterInstanceProperty(_context4=_Object$getOwnPropertyNames(newOptions)).call(_context4,p=>newOptions[p]!=null);// Always skip merging group font options into parent; these are required to be distinct for labels
skipProperties.push("font");selectiveNotDeepExtend(skipProperties,parentOptions,groupObj);// the color object needs to be completely defined.
// Since groups can partially overwrite the colors, we parse it again, just in case.
parentOptions.color=parseColor(parentOptions.color);}/**
   * This process all possible shorthands in the new options and makes sure that the parentOptions are fully defined.
   * Static so it can also be used by the handler.
   * @param {object} parentOptions
   * @param {object} newOptions
   * @param {boolean} [allowDeletion]
   * @param {object} [globalOptions]
   * @param {object} [groupList]
   * @static
   */static parseOptions(parentOptions,newOptions){let allowDeletion=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;let globalOptions=arguments.length>3&&arguments[3]!==undefined?arguments[3]:{};let groupList=arguments.length>4?arguments[4]:undefined;const fields=["color","fixed","shadow"];selectiveNotDeepExtend(fields,parentOptions,newOptions,allowDeletion);Node.checkMass(newOptions);if(parentOptions.opacity!==undefined){if(!Node.checkOpacity(parentOptions.opacity)){console.error("Invalid option for node opacity. Value must be between 0 and 1, found: "+parentOptions.opacity);parentOptions.opacity=undefined;}}if(newOptions.opacity!==undefined){if(!Node.checkOpacity(newOptions.opacity)){console.error("Invalid option for node opacity. Value must be between 0 and 1, found: "+newOptions.opacity);newOptions.opacity=undefined;}}if(newOptions.shapeProperties&&!Node.checkCoordinateOrigin(newOptions.shapeProperties.coordinateOrigin)){console.error("Invalid option for node coordinateOrigin, found: "+newOptions.shapeProperties.coordinateOrigin);}// merge the shadow options into the parent.
mergeOptions(parentOptions,newOptions,"shadow",globalOptions);// individual shape newOptions
if(newOptions.color!==undefined&&newOptions.color!==null){const parsedColor=parseColor(newOptions.color);fillIfDefined(parentOptions.color,parsedColor);}else if(allowDeletion===true&&newOptions.color===null){parentOptions.color=bridgeObject(globalOptions.color);// set the object back to the global options
}// handle the fixed options
if(newOptions.fixed!==undefined&&newOptions.fixed!==null){if(typeof newOptions.fixed==="boolean"){parentOptions.fixed.x=newOptions.fixed;parentOptions.fixed.y=newOptions.fixed;}else {if(newOptions.fixed.x!==undefined&&typeof newOptions.fixed.x==="boolean"){parentOptions.fixed.x=newOptions.fixed.x;}if(newOptions.fixed.y!==undefined&&typeof newOptions.fixed.y==="boolean"){parentOptions.fixed.y=newOptions.fixed.y;}}}if(allowDeletion===true&&newOptions.font===null){parentOptions.font=bridgeObject(globalOptions.font);// set the object back to the global options
}Node.updateGroupOptions(parentOptions,newOptions,groupList);// handle the scaling options, specifically the label part
if(newOptions.scaling!==undefined){mergeOptions(parentOptions.scaling,newOptions.scaling,"label",globalOptions.scaling);}}/**
   *
   * @returns {{color: *, borderWidth: *, borderColor: *, size: *, borderDashes: (boolean|Array|allOptions.nodes.shapeProperties.borderDashes|{boolean, array}), borderRadius: (number|allOptions.nodes.shapeProperties.borderRadius|{number}|Array), shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *}}
   */getFormattingValues(){const values={color:this.options.color.background,opacity:this.options.opacity,borderWidth:this.options.borderWidth,borderColor:this.options.color.border,size:this.options.size,borderDashes:this.options.shapeProperties.borderDashes,borderRadius:this.options.shapeProperties.borderRadius,shadow:this.options.shadow.enabled,shadowColor:this.options.shadow.color,shadowSize:this.options.shadow.size,shadowX:this.options.shadow.x,shadowY:this.options.shadow.y};if(this.selected||this.hover){if(this.chooser===true){if(this.selected){if(this.options.borderWidthSelected!=null){values.borderWidth=this.options.borderWidthSelected;}else {values.borderWidth*=2;}values.color=this.options.color.highlight.background;values.borderColor=this.options.color.highlight.border;values.shadow=this.options.shadow.enabled;}else if(this.hover){values.color=this.options.color.hover.background;values.borderColor=this.options.color.hover.border;values.shadow=this.options.shadow.enabled;}}else if(typeof this.chooser==="function"){this.chooser(values,this.options.id,this.selected,this.hover);if(values.shadow===false){if(values.shadowColor!==this.options.shadow.color||values.shadowSize!==this.options.shadow.size||values.shadowX!==this.options.shadow.x||values.shadowY!==this.options.shadow.y){values.shadow=true;}}}}else {values.shadow=this.options.shadow.enabled;}if(this.options.opacity!==undefined){const opacity=this.options.opacity;values.borderColor=overrideOpacity(values.borderColor,opacity);values.color=overrideOpacity(values.color,opacity);values.shadowColor=overrideOpacity(values.shadowColor,opacity);}return values;}/**
   *
   * @param {object} options
   */updateLabelModule(options){if(this.options.label===undefined||this.options.label===null){this.options.label="";}Node.updateGroupOptions(this.options,_objectSpread$2(_objectSpread$2({},options),{},{color:options&&options.color||this._localColor||undefined}),this.grouplist);//
// Note:The prototype chain for this.options is:
//
// this.options ->    NodesHandler.options    -> NodesHandler.defaultOptions
//                 (also: this.globalOptions)
//
// Note that the prototypes are mentioned explicitly in the pile list below;
// WE DON'T WANT THE ORDER OF THE PROTOTYPES!!!! At least, not for font handling of labels.
// This is a good indication that the prototype usage of options is deficient.
//
const currentGroup=this.grouplist.get(this.options.group,false);const pile=[options,// new options
this.options,// current node options, see comment above for prototype
currentGroup,// group options, if any
this.globalOptions,// Currently set global node options
this.defaultOptions// Default global node options
];this.labelModule.update(this.options,pile);if(this.labelModule.baseSize!==undefined){this.baseFontSize=this.labelModule.baseSize;}}/**
   *
   * @param {string} currentShape
   */updateShape(currentShape){if(currentShape===this.options.shape&&this.shape){this.shape.setOptions(this.options,this.imageObj,this.imageObjAlt);}else {// choose draw method depending on the shape
switch(this.options.shape){case "box":this.shape=new Box$1(this.options,this.body,this.labelModule);break;case "circle":this.shape=new Circle$1(this.options,this.body,this.labelModule);break;case "circularImage":this.shape=new CircularImage(this.options,this.body,this.labelModule,this.imageObj,this.imageObjAlt);break;case "custom":this.shape=new CustomShape(this.options,this.body,this.labelModule,this.options.ctxRenderer);break;case "database":this.shape=new Database(this.options,this.body,this.labelModule);break;case "diamond":this.shape=new Diamond$1(this.options,this.body,this.labelModule);break;case "dot":this.shape=new Dot(this.options,this.body,this.labelModule);break;case "ellipse":this.shape=new Ellipse(this.options,this.body,this.labelModule);break;case "icon":this.shape=new Icon(this.options,this.body,this.labelModule);break;case "image":this.shape=new Image$2(this.options,this.body,this.labelModule,this.imageObj,this.imageObjAlt);break;case "square":this.shape=new Square(this.options,this.body,this.labelModule);break;case "hexagon":this.shape=new Hexagon(this.options,this.body,this.labelModule);break;case "star":this.shape=new Star(this.options,this.body,this.labelModule);break;case "text":this.shape=new Text(this.options,this.body,this.labelModule);break;case "triangle":this.shape=new Triangle$1(this.options,this.body,this.labelModule);break;case "triangleDown":this.shape=new TriangleDown(this.options,this.body,this.labelModule);break;default:this.shape=new Ellipse(this.options,this.body,this.labelModule);break;}}this.needsRefresh();}/**
   * select this node
   */select(){this.selected=true;this.needsRefresh();}/**
   * unselect this node
   */unselect(){this.selected=false;this.needsRefresh();}/**
   * Reset the calculated size of the node, forces it to recalculate its size
   */needsRefresh(){this.shape.refreshNeeded=true;}/**
   * get the title of this node.
   * @returns {string} title    The title of the node, or undefined when no title
   *                           has been set.
   */getTitle(){return this.options.title;}/**
   * Calculate the distance to the border of the Node
   * @param {CanvasRenderingContext2D}   ctx
   * @param {number} angle        Angle in radians
   * @returns {number} distance   Distance to the border in pixels
   */distanceToBorder(ctx,angle){return this.shape.distanceToBorder(ctx,angle);}/**
   * Check if this node has a fixed x and y position
   * @returns {boolean}      true if fixed, false if not
   */isFixed(){return this.options.fixed.x&&this.options.fixed.y;}/**
   * check if this node is selecte
   * @returns {boolean} selected   True if node is selected, else false
   */isSelected(){return this.selected;}/**
   * Retrieve the value of the node. Can be undefined
   * @returns {number} value
   */getValue(){return this.options.value;}/**
   * Get the current dimensions of the label
   * @returns {rect}
   */getLabelSize(){return this.labelModule.size();}/**
   * Adjust the value range of the node. The node will adjust it's size
   * based on its value.
   * @param {number} min
   * @param {number} max
   * @param {number} total
   */setValueRange(min,max,total){if(this.options.value!==undefined){const scale=this.options.scaling.customScalingFunction(min,max,total,this.options.value);const sizeDiff=this.options.scaling.max-this.options.scaling.min;if(this.options.scaling.label.enabled===true){const fontDiff=this.options.scaling.label.max-this.options.scaling.label.min;this.options.font.size=this.options.scaling.label.min+scale*fontDiff;}this.options.size=this.options.scaling.min+scale*sizeDiff;}else {this.options.size=this.baseSize;this.options.font.size=this.baseFontSize;}this.updateLabelModule();}/**
   * Draw this node in the given canvas
   * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
   * @param {CanvasRenderingContext2D}   ctx
   * @returns {object} Callbacks to draw later on higher layers.
   */draw(ctx){const values=this.getFormattingValues();return this.shape.draw(ctx,this.x,this.y,this.selected,this.hover,values)||{};}/**
   * Update the bounding box of the shape
   * @param {CanvasRenderingContext2D}   ctx
   */updateBoundingBox(ctx){this.shape.updateBoundingBox(this.x,this.y,ctx);}/**
   * Recalculate the size of this node in the given canvas
   * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
   * @param {CanvasRenderingContext2D}   ctx
   */resize(ctx){const values=this.getFormattingValues();this.shape.resize(ctx,this.selected,this.hover,values);}/**
   * Determine all visual elements of this node instance, in which the given
   * point falls within the bounding shape.
   * @param {point} point
   * @returns {Array.<nodeClickItem|nodeLabelClickItem>} list with the items which are on the point
   */getItemsOnPoint(point){const ret=[];if(this.labelModule.visible()){if(pointInRect(this.labelModule.getSize(),point)){ret.push({nodeId:this.id,labelId:0});}}if(pointInRect(this.shape.boundingBox,point)){ret.push({nodeId:this.id});}return ret;}/**
   * Check if this object is overlapping with the provided object
   * @param {object} obj   an object with parameters left, top, right, bottom
   * @returns {boolean}     True if location is located on node
   */isOverlappingWith(obj){return this.shape.left<obj.right&&this.shape.left+this.shape.width>obj.left&&this.shape.top<obj.bottom&&this.shape.top+this.shape.height>obj.top;}/**
   * Check if this object is overlapping with the provided object
   * @param {object} obj   an object with parameters left, top, right, bottom
   * @returns {boolean}     True if location is located on node
   */isBoundingBoxOverlappingWith(obj){return this.shape.boundingBox.left<obj.right&&this.shape.boundingBox.right>obj.left&&this.shape.boundingBox.top<obj.bottom&&this.shape.boundingBox.bottom>obj.top;}/**
   * Check valid values for mass
   *
   * The mass may not be negative or zero. If it is, reset to 1
   * @param {object} options
   * @param {Node.id} id
   * @static
   */static checkMass(options,id){if(options.mass!==undefined&&options.mass<=0){let strId="";if(id!==undefined){strId=" in node id: "+id;}console.error("%cNegative or zero mass disallowed"+strId+", setting mass to 1.",VALIDATOR_PRINT_STYLE);options.mass=1;}}};/**
 * Handler for Nodes
 */class NodesHandler{/**
   * @param {object} body
   * @param {Images} images
   * @param {Array.<Group>} groups
   * @param {LayoutEngine} layoutEngine
   */constructor(body,images,groups,layoutEngine){var _context;this.body=body;this.images=images;this.groups=groups;this.layoutEngine=layoutEngine;// create the node API in the body container
this.body.functions.createNode=_bindInstanceProperty(_context=this.create).call(_context,this);this.nodesListeners={add:(event,params)=>{this.add(params.items);},update:(event,params)=>{this.update(params.items,params.data,params.oldData);},remove:(event,params)=>{this.remove(params.items);}};this.defaultOptions={borderWidth:1,borderWidthSelected:undefined,brokenImage:undefined,color:{border:"#2B7CE9",background:"#97C2FC",highlight:{border:"#2B7CE9",background:"#D2E5FF"},hover:{border:"#2B7CE9",background:"#D2E5FF"}},opacity:undefined,// number between 0 and 1
fixed:{x:false,y:false},font:{color:"#343434",size:14,// px
face:"arial",background:"none",strokeWidth:0,// px
strokeColor:"#ffffff",align:"center",vadjust:0,multi:false,bold:{mod:"bold"},boldital:{mod:"bold italic"},ital:{mod:"italic"},mono:{mod:"",size:15,// px
face:"monospace",vadjust:2}},group:undefined,hidden:false,icon:{face:"FontAwesome",//'FontAwesome',
code:undefined,//'\uf007',
size:50,//50,
color:"#2B7CE9"//'#aa00ff'
},image:undefined,// --> URL
imagePadding:{// only for image shape
top:0,right:0,bottom:0,left:0},label:undefined,labelHighlightBold:true,level:undefined,margin:{top:5,right:5,bottom:5,left:5},mass:1,physics:true,scaling:{min:10,max:30,label:{enabled:false,min:14,max:30,maxVisible:30,drawThreshold:5},customScalingFunction:function(min,max,total,value){if(max===min){return 0.5;}else {const scale=1/(max-min);return Math.max(0,(value-min)*scale);}}},shadow:{enabled:false,color:"rgba(0,0,0,0.5)",size:10,x:5,y:5},shape:"ellipse",shapeProperties:{borderDashes:false,// only for borders
borderRadius:6,// only for box shape
interpolation:true,// only for image and circularImage shapes
useImageSize:false,// only for image and circularImage shapes
useBorderWithImage:false,// only for image shape
coordinateOrigin:"center"// only for image and circularImage shapes
},size:25,title:undefined,value:undefined,x:undefined,y:undefined};// Protect from idiocy
if(this.defaultOptions.mass<=0){throw "Internal error: mass in defaultOptions of NodesHandler may not be zero or negative";}this.options=bridgeObject(this.defaultOptions);this.bindEventListeners();}/**
   * Binds event listeners
   */bindEventListeners(){var _context2,_context3;// refresh the nodes. Used when reverting from hierarchical layout
this.body.emitter.on("refreshNodes",_bindInstanceProperty(_context2=this.refresh).call(_context2,this));this.body.emitter.on("refresh",_bindInstanceProperty(_context3=this.refresh).call(_context3,this));this.body.emitter.on("destroy",()=>{forEach(this.nodesListeners,(callback,event)=>{if(this.body.data.nodes)this.body.data.nodes.off(event,callback);});delete this.body.functions.createNode;delete this.nodesListeners.add;delete this.nodesListeners.update;delete this.nodesListeners.remove;delete this.nodesListeners;});}/**
   *
   * @param {object} options
   */setOptions(options){if(options!==undefined){Node$1.parseOptions(this.options,options);// Need to set opacity here because Node.parseOptions is also used for groups,
// if you set opacity in Node.parseOptions it overwrites group opacity.
if(options.opacity!==undefined){if(_Number$isNaN(options.opacity)||!_Number$isFinite(options.opacity)||options.opacity<0||options.opacity>1){console.error("Invalid option for node opacity. Value must be between 0 and 1, found: "+options.opacity);}else {this.options.opacity=options.opacity;}}// update the shape in all nodes
if(options.shape!==undefined){for(const nodeId in this.body.nodes){if(Object.prototype.hasOwnProperty.call(this.body.nodes,nodeId)){this.body.nodes[nodeId].updateShape();}}}// Update the labels of nodes if any relevant options changed.
if(typeof options.font!=="undefined"||typeof options.widthConstraint!=="undefined"||typeof options.heightConstraint!=="undefined"){for(const nodeId of _Object$keys(this.body.nodes)){this.body.nodes[nodeId].updateLabelModule();this.body.nodes[nodeId].needsRefresh();}}// update the shape size in all nodes
if(options.size!==undefined){for(const nodeId in this.body.nodes){if(Object.prototype.hasOwnProperty.call(this.body.nodes,nodeId)){this.body.nodes[nodeId].needsRefresh();}}}// update the state of the variables if needed
if(options.hidden!==undefined||options.physics!==undefined){this.body.emitter.emit("_dataChanged");}}}/**
   * Set a data set with nodes for the network
   * @param {Array | DataSet | DataView} nodes         The data containing the nodes.
   * @param {boolean} [doNotEmit] - Suppress data changed event.
   * @private
   */setData(nodes){let doNotEmit=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;const oldNodesData=this.body.data.nodes;if(isDataViewLike("id",nodes)){this.body.data.nodes=nodes;}else if(_Array$isArray(nodes)){this.body.data.nodes=new DataSet();this.body.data.nodes.add(nodes);}else if(!nodes){this.body.data.nodes=new DataSet();}else {throw new TypeError("Array or DataSet expected");}if(oldNodesData){// unsubscribe from old dataset
forEach(this.nodesListeners,function(callback,event){oldNodesData.off(event,callback);});}// remove drawn nodes
this.body.nodes={};if(this.body.data.nodes){// subscribe to new dataset
const me=this;forEach(this.nodesListeners,function(callback,event){me.body.data.nodes.on(event,callback);});// draw all new nodes
const ids=this.body.data.nodes.getIds();this.add(ids,true);}if(doNotEmit===false){this.body.emitter.emit("_dataChanged");}}/**
   * Add nodes
   * @param {number[] | string[]} ids
   * @param {boolean} [doNotEmit]
   * @private
   */add(ids){let doNotEmit=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;let id;const newNodes=[];for(let i=0;i<ids.length;i++){id=ids[i];const properties=this.body.data.nodes.get(id);const node=this.create(properties);newNodes.push(node);this.body.nodes[id]=node;// note: this may replace an existing node
}this.layoutEngine.positionInitially(newNodes);if(doNotEmit===false){this.body.emitter.emit("_dataChanged");}}/**
   * Update existing nodes, or create them when not yet existing
   * @param {number[] | string[]} ids id's of changed nodes
   * @param {Array} changedData array with changed data
   * @param {Array|undefined} oldData optional; array with previous data
   * @private
   */update(ids,changedData,oldData){const nodes=this.body.nodes;let dataChanged=false;for(let i=0;i<ids.length;i++){const id=ids[i];let node=nodes[id];const data=changedData[i];if(node!==undefined){// update node
if(node.setOptions(data)){dataChanged=true;}}else {dataChanged=true;// create node
node=this.create(data);nodes[id]=node;}}if(!dataChanged&&oldData!==undefined){// Check for any changes which should trigger a layout recalculation
// For now, this is just 'level' for hierarchical layout
// Assumption: old and new data arranged in same order; at time of writing, this holds.
dataChanged=_someInstanceProperty(changedData).call(changedData,function(newValue,index){const oldValue=oldData[index];return oldValue&&oldValue.level!==newValue.level;});}if(dataChanged===true){this.body.emitter.emit("_dataChanged");}else {this.body.emitter.emit("_dataUpdated");}}/**
   * Remove existing nodes. If nodes do not exist, the method will just ignore it.
   * @param {number[] | string[]} ids
   * @private
   */remove(ids){const nodes=this.body.nodes;for(let i=0;i<ids.length;i++){const id=ids[i];delete nodes[id];}this.body.emitter.emit("_dataChanged");}/**
   * create a node
   * @param {object} properties
   * @param {class} [constructorClass]
   * @returns {*}
   */create(properties){let constructorClass=arguments.length>1&&arguments[1]!==undefined?arguments[1]:Node$1;return new constructorClass(properties,this.body,this.images,this.groups,this.options,this.defaultOptions);}/**
   *
   * @param {boolean} [clearPositions]
   */refresh(){let clearPositions=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;forEach(this.body.nodes,(node,nodeId)=>{const data=this.body.data.nodes.get(nodeId);if(data!==undefined){if(clearPositions===true){node.setOptions({x:null,y:null});}node.setOptions({fixed:false});node.setOptions(data);}});}/**
   * Returns the positions of the nodes.
   * @param {Array.<Node.id> | string} [ids]  --> optional, can be array of nodeIds, can be string
   * @returns {{}}
   */getPositions(ids){const dataArray={};if(ids!==undefined){if(_Array$isArray(ids)===true){for(let i=0;i<ids.length;i++){if(this.body.nodes[ids[i]]!==undefined){const node=this.body.nodes[ids[i]];dataArray[ids[i]]={x:Math.round(node.x),y:Math.round(node.y)};}}}else {if(this.body.nodes[ids]!==undefined){const node=this.body.nodes[ids];dataArray[ids]={x:Math.round(node.x),y:Math.round(node.y)};}}}else {for(let i=0;i<this.body.nodeIndices.length;i++){const node=this.body.nodes[this.body.nodeIndices[i]];dataArray[this.body.nodeIndices[i]]={x:Math.round(node.x),y:Math.round(node.y)};}}return dataArray;}/**
   * Retrieves the x y position of a specific id.
   * @param {string} id The id to retrieve.
   * @throws {TypeError} If no id is included.
   * @throws {ReferenceError} If an invalid id is provided.
   * @returns {{ x: number, y: number }} Returns X, Y canvas position of the node with given id.
   */getPosition(id){if(id==undefined){throw new TypeError("No id was specified for getPosition method.");}else if(this.body.nodes[id]==undefined){throw new ReferenceError("NodeId provided for getPosition does not exist. Provided: ".concat(id));}else {return {x:Math.round(this.body.nodes[id].x),y:Math.round(this.body.nodes[id].y)};}}/**
   * Load the XY positions of the nodes into the dataset.
   */storePositions(){// todo: add support for clusters and hierarchical.
const dataArray=[];const dataset=this.body.data.nodes.getDataSet();for(const dsNode of dataset.get()){const id=dsNode.id;const bodyNode=this.body.nodes[id];const x=Math.round(bodyNode.x);const y=Math.round(bodyNode.y);if(dsNode.x!==x||dsNode.y!==y){dataArray.push({id,x,y});}}dataset.update(dataArray);}/**
   * get the bounding box of a node.
   * @param {Node.id} nodeId
   * @returns {j|*}
   */getBoundingBox(nodeId){if(this.body.nodes[nodeId]!==undefined){return this.body.nodes[nodeId].shape.boundingBox;}}/**
   * Get the Ids of nodes connected to this node.
   * @param {Node.id} nodeId
   * @param {'to'|'from'|undefined} direction values 'from' and 'to' select respectively parent and child nodes only.
   *                                          Any other value returns both parent and child nodes.
   * @returns {Array}
   */getConnectedNodes(nodeId,direction){const nodeList=[];if(this.body.nodes[nodeId]!==undefined){const node=this.body.nodes[nodeId];const nodeObj={};// used to quickly check if node already exists
for(let i=0;i<node.edges.length;i++){const edge=node.edges[i];if(direction!=="to"&&edge.toId==node.id){// these are double equals since ids can be numeric or string
if(nodeObj[edge.fromId]===undefined){nodeList.push(edge.fromId);nodeObj[edge.fromId]=true;}}else if(direction!=="from"&&edge.fromId==node.id){// these are double equals since ids can be numeric or string
if(nodeObj[edge.toId]===undefined){nodeList.push(edge.toId);nodeObj[edge.toId]=true;}}}}return nodeList;}/**
   * Get the ids of the edges connected to this node.
   * @param {Node.id} nodeId
   * @returns {*}
   */getConnectedEdges(nodeId){const edgeList=[];if(this.body.nodes[nodeId]!==undefined){const node=this.body.nodes[nodeId];for(let i=0;i<node.edges.length;i++){edgeList.push(node.edges[i].id);}}else {console.error("NodeId provided for getConnectedEdges does not exist. Provided: ",nodeId);}return edgeList;}/**
   * Move a node.
   * @param {Node.id} nodeId
   * @param {number} x
   * @param {number} y
   */moveNode(nodeId,x,y){if(this.body.nodes[nodeId]!==undefined){this.body.nodes[nodeId].x=Number(x);this.body.nodes[nodeId].y=Number(y);_setTimeout(()=>{this.body.emitter.emit("startSimulation");},0);}else {console.error("Node id supplied to moveNode does not exist. Provided: ",nodeId);}}}var es_math_hypot={};var hasRequiredEs_math_hypot;function requireEs_math_hypot(){if(hasRequiredEs_math_hypot)return es_math_hypot;hasRequiredEs_math_hypot=1;var $=/*@__PURE__*/require_export();// eslint-disable-next-line es/no-math-hypot -- required for testing
var $hypot=Math.hypot;var abs=Math.abs;var sqrt=Math.sqrt;// Chrome 77 bug
// https://bugs.chromium.org/p/v8/issues/detail?id=9546
var FORCED=!!$hypot&&$hypot(Infinity,NaN)!==Infinity;// `Math.hypot` method
// https://tc39.es/ecma262/#sec-math.hypot
$({target:'Math',stat:true,arity:2,forced:FORCED},{// eslint-disable-next-line no-unused-vars -- required for `.length`
hypot:function hypot(value1,value2){var sum=0;var i=0;var aLen=arguments.length;var larg=0;var arg,div;while(i<aLen){arg=abs(arguments[i++]);if(larg<arg){div=larg/arg;sum=sum*div*div+1;larg=arg;}else if(arg>0){div=arg/larg;sum+=div*div;}else sum+=arg;}return larg===Infinity?Infinity:larg*sqrt(sum);}});return es_math_hypot;}var hypot$2;var hasRequiredHypot$2;function requireHypot$2(){if(hasRequiredHypot$2)return hypot$2;hasRequiredHypot$2=1;requireEs_math_hypot();var path=/*@__PURE__*/requirePath();hypot$2=path.Math.hypot;return hypot$2;}var hypot$1;var hasRequiredHypot$1;function requireHypot$1(){if(hasRequiredHypot$1)return hypot$1;hasRequiredHypot$1=1;var parent=/*@__PURE__*/requireHypot$2();hypot$1=parent;return hypot$1;}var hypot;var hasRequiredHypot;function requireHypot(){if(hasRequiredHypot)return hypot;hasRequiredHypot=1;hypot=/*@__PURE__*/requireHypot$1();return hypot;}var hypotExports=requireHypot();var _Math$hypot=/*@__PURE__*/getDefaultExportFromCjs(hypotExports);/**
 * Common methods for endpoints
 * @class
 */class EndPoint{/**
   * Apply transformation on points for display.
   *
   * The following is done:
   * - rotate by the specified angle
   * - multiply the (normalized) coordinates by the passed length
   * - offset by the target coordinates
   * @param points - The point(s) to be transformed.
   * @param arrowData - The data determining the result of the transformation.
   */static transform(points,arrowData){if(!_Array$isArray(points)){points=[points];}const x=arrowData.point.x;const y=arrowData.point.y;const angle=arrowData.angle;const length=arrowData.length;for(let i=0;i<points.length;++i){const p=points[i];const xt=p.x*Math.cos(angle)-p.y*Math.sin(angle);const yt=p.x*Math.sin(angle)+p.y*Math.cos(angle);p.x=x+length*xt;p.y=y+length*yt;}}/**
   * Draw a closed path using the given real coordinates.
   * @param ctx - The path will be rendered into this context.
   * @param points - The points of the path.
   */static drawPath(ctx,points){ctx.beginPath();ctx.moveTo(points[0].x,points[0].y);for(let i=1;i<points.length;++i){ctx.lineTo(points[i].x,points[i].y);}ctx.closePath();}}/**
 * Drawing methods for the arrow endpoint.
 */let Image$1=class Image extends EndPoint{/**
   * Draw this shape at the end of a line.
   * @param ctx - The shape will be rendered into this context.
   * @param arrowData - The data determining the shape.
   * @returns False as there is no way to fill an image.
   */static draw(ctx,arrowData){if(arrowData.image){ctx.save();ctx.translate(arrowData.point.x,arrowData.point.y);ctx.rotate(Math.PI/2+arrowData.angle);const width=arrowData.imageWidth!=null?arrowData.imageWidth:arrowData.image.width;const height=arrowData.imageHeight!=null?arrowData.imageHeight:arrowData.image.height;arrowData.image.drawImageAtPosition(ctx,1,// scale
-width/2,// x
0,// y
width,height);ctx.restore();}return false;}};/**
 * Drawing methods for the arrow endpoint.
 */class Arrow extends EndPoint{/**
   * Draw this shape at the end of a line.
   * @param ctx - The shape will be rendered into this context.
   * @param arrowData - The data determining the shape.
   * @returns True because ctx.fill() can be used to fill the arrow.
   */static draw(ctx,arrowData){// Normalized points of closed path, in the order that they should be drawn.
// (0, 0) is the attachment point, and the point around which should be rotated
const points=[{x:0,y:0},{x:-1,y:0.3},{x:-0.9,y:0},{x:-1,y:-0.3}];EndPoint.transform(points,arrowData);EndPoint.drawPath(ctx,points);return true;}}/**
 * Drawing methods for the crow endpoint.
 */class Crow{/**
   * Draw this shape at the end of a line.
   * @param ctx - The shape will be rendered into this context.
   * @param arrowData - The data determining the shape.
   * @returns True because ctx.fill() can be used to fill the arrow.
   */static draw(ctx,arrowData){// Normalized points of closed path, in the order that they should be drawn.
// (0, 0) is the attachment point, and the point around which should be rotated
const points=[{x:-1,y:0},{x:0,y:0.3},{x:-0.4,y:0},{x:0,y:-0.3}];EndPoint.transform(points,arrowData);EndPoint.drawPath(ctx,points);return true;}}/**
 * Drawing methods for the curve endpoint.
 */class Curve{/**
   * Draw this shape at the end of a line.
   * @param ctx - The shape will be rendered into this context.
   * @param arrowData - The data determining the shape.
   * @returns True because ctx.fill() can be used to fill the arrow.
   */static draw(ctx,arrowData){// Normalized points of closed path, in the order that they should be drawn.
// (0, 0) is the attachment point, and the point around which should be rotated
const point={x:-0.4,y:0};EndPoint.transform(point,arrowData);// Update endpoint style for drawing transparent arc.
ctx.strokeStyle=ctx.fillStyle;ctx.fillStyle="rgba(0, 0, 0, 0)";// Define curve endpoint as semicircle.
const pi=Math.PI;const startAngle=arrowData.angle-pi/2;const endAngle=arrowData.angle+pi/2;ctx.beginPath();ctx.arc(point.x,point.y,arrowData.length*0.4,startAngle,endAngle,false);ctx.stroke();return true;}}/**
 * Drawing methods for the inverted curve endpoint.
 */class InvertedCurve{/**
   * Draw this shape at the end of a line.
   * @param ctx - The shape will be rendered into this context.
   * @param arrowData - The data determining the shape.
   * @returns True because ctx.fill() can be used to fill the arrow.
   */static draw(ctx,arrowData){// Normalized points of closed path, in the order that they should be drawn.
// (0, 0) is the attachment point, and the point around which should be rotated
const point={x:-0.3,y:0};EndPoint.transform(point,arrowData);// Update endpoint style for drawing transparent arc.
ctx.strokeStyle=ctx.fillStyle;ctx.fillStyle="rgba(0, 0, 0, 0)";// Define inverted curve endpoint as semicircle.
const pi=Math.PI;const startAngle=arrowData.angle+pi/2;const endAngle=arrowData.angle+3*pi/2;ctx.beginPath();ctx.arc(point.x,point.y,arrowData.length*0.4,startAngle,endAngle,false);ctx.stroke();return true;}}/**
 * Drawing methods for the trinagle endpoint.
 */class Triangle{/**
   * Draw this shape at the end of a line.
   * @param ctx - The shape will be rendered into this context.
   * @param arrowData - The data determining the shape.
   * @returns True because ctx.fill() can be used to fill the arrow.
   */static draw(ctx,arrowData){// Normalized points of closed path, in the order that they should be drawn.
// (0, 0) is the attachment point, and the point around which should be rotated
const points=[{x:0.02,y:0},{x:-1,y:0.3},{x:-1,y:-0.3}];EndPoint.transform(points,arrowData);EndPoint.drawPath(ctx,points);return true;}}/**
 * Drawing methods for the inverted trinagle endpoint.
 */class InvertedTriangle{/**
   * Draw this shape at the end of a line.
   * @param ctx - The shape will be rendered into this context.
   * @param arrowData - The data determining the shape.
   * @returns True because ctx.fill() can be used to fill the arrow.
   */static draw(ctx,arrowData){// Normalized points of closed path, in the order that they should be drawn.
// (0, 0) is the attachment point, and the point around which should be rotated
const points=[{x:0,y:0.3},{x:0,y:-0.3},{x:-1,y:0}];EndPoint.transform(points,arrowData);EndPoint.drawPath(ctx,points);return true;}}/**
 * Drawing methods for the circle endpoint.
 */class Circle{/**
   * Draw this shape at the end of a line.
   * @param ctx - The shape will be rendered into this context.
   * @param arrowData - The data determining the shape.
   * @returns True because ctx.fill() can be used to fill the arrow.
   */static draw(ctx,arrowData){const point={x:-0.4,y:0};EndPoint.transform(point,arrowData);drawCircle(ctx,point.x,point.y,arrowData.length*0.4);return true;}}/**
 * Drawing methods for the bar endpoint.
 */class Bar{/**
   * Draw this shape at the end of a line.
   * @param ctx - The shape will be rendered into this context.
   * @param arrowData - The data determining the shape.
   * @returns True because ctx.fill() can be used to fill the arrow.
   */static draw(ctx,arrowData){/*
    var points = [
      {x:0, y:0.5},
      {x:0, y:-0.5}
    ];
         EndPoint.transform(points, arrowData);
    ctx.beginPath();
    ctx.moveTo(points[0].x, points[0].y);
    ctx.lineTo(points[1].x, points[1].y);
    ctx.stroke();
    */const points=[{x:0,y:0.5},{x:0,y:-0.5},{x:-0.15,y:-0.5},{x:-0.15,y:0.5}];EndPoint.transform(points,arrowData);EndPoint.drawPath(ctx,points);return true;}}/**
 * Drawing methods for the box endpoint.
 */class Box{/**
   * Draw this shape at the end of a line.
   * @param ctx - The shape will be rendered into this context.
   * @param arrowData - The data determining the shape.
   * @returns True because ctx.fill() can be used to fill the arrow.
   */static draw(ctx,arrowData){const points=[{x:0,y:0.3},{x:0,y:-0.3},{x:-0.6,y:-0.3},{x:-0.6,y:0.3}];EndPoint.transform(points,arrowData);EndPoint.drawPath(ctx,points);return true;}}/**
 * Drawing methods for the diamond endpoint.
 */class Diamond{/**
   * Draw this shape at the end of a line.
   * @param ctx - The shape will be rendered into this context.
   * @param arrowData - The data determining the shape.
   * @returns True because ctx.fill() can be used to fill the arrow.
   */static draw(ctx,arrowData){const points=[{x:0,y:0},{x:-0.5,y:-0.3},{x:-1,y:0},{x:-0.5,y:0.3}];EndPoint.transform(points,arrowData);EndPoint.drawPath(ctx,points);return true;}}/**
 * Drawing methods for the vee endpoint.
 */class Vee{/**
   * Draw this shape at the end of a line.
   * @param ctx - The shape will be rendered into this context.
   * @param arrowData - The data determining the shape.
   * @returns True because ctx.fill() can be used to fill the arrow.
   */static draw(ctx,arrowData){// Normalized points of closed path, in the order that they should be drawn.
// (0, 0) is the attachment point, and the point around which should be rotated
const points=[{x:-1,y:0.3},{x:-0.5,y:0},{x:-1,y:-0.3},{x:0,y:0}];EndPoint.transform(points,arrowData);EndPoint.drawPath(ctx,points);return true;}}/**
 * Drawing methods for the endpoints.
 */class EndPoints{/**
   * Draw an endpoint.
   * @param ctx - The shape will be rendered into this context.
   * @param arrowData - The data determining the shape.
   * @returns True if ctx.fill() can be used to fill the arrow, false otherwise.
   */static draw(ctx,arrowData){let type;if(arrowData.type){type=arrowData.type.toLowerCase();}switch(type){case "image":return Image$1.draw(ctx,arrowData);case "circle":return Circle.draw(ctx,arrowData);case "box":return Box.draw(ctx,arrowData);case "crow":return Crow.draw(ctx,arrowData);case "curve":return Curve.draw(ctx,arrowData);case "diamond":return Diamond.draw(ctx,arrowData);case "inv_curve":return InvertedCurve.draw(ctx,arrowData);case "triangle":return Triangle.draw(ctx,arrowData);case "inv_triangle":return InvertedTriangle.draw(ctx,arrowData);case "bar":return Bar.draw(ctx,arrowData);case "vee":return Vee.draw(ctx,arrowData);case "arrow":// fall-through
default:return Arrow.draw(ctx,arrowData);}}}function ownKeys$1(e,r){var t=_Object$keys(e);if(_Object$getOwnPropertySymbols){var o=_Object$getOwnPropertySymbols(e);r&&(o=_filterInstanceProperty(o).call(o,function(r){return _Object$getOwnPropertyDescriptor(e,r).enumerable;})),t.push.apply(t,o);}return t;}function _objectSpread$1(e){for(var r=1;r<arguments.length;r++){var _context2,_context3;var t=null!=arguments[r]?arguments[r]:{};r%2?_forEachInstanceProperty(_context2=ownKeys$1(Object(t),true)).call(_context2,function(r){_defineProperty(e,r,t[r]);}):_Object$getOwnPropertyDescriptors?_Object$defineProperties(e,_Object$getOwnPropertyDescriptors(t)):_forEachInstanceProperty(_context3=ownKeys$1(Object(t))).call(_context3,function(r){_Object$defineProperty(e,r,_Object$getOwnPropertyDescriptor(t,r));});}return e;}/**
 * The Base Class for all edges.
 */class EdgeBase{/**
   * Create a new instance.
   * @param options - The options object of given edge.
   * @param body - The body of the network.
   * @param labelModule - Label module.
   */constructor(options,body,labelModule){// Initialized in setOptions
// Initialized in setOptions
_defineProperty(this,"color",{});_defineProperty(this,"colorDirty",true);// Initialized in setOptions
_defineProperty(this,"hoverWidth",1.5);_defineProperty(this,"selectionWidth",2);this._body=body;this._labelModule=labelModule;this.setOptions(options);this.fromPoint=this.from;this.toPoint=this.to;}/** @inheritDoc */connect(){this.from=this._body.nodes[this.options.from];this.to=this._body.nodes[this.options.to];}/** @inheritDoc */cleanup(){return false;}/**
   * Set new edge options.
   * @param options - The new edge options object.
   */setOptions(options){this.options=options;this.from=this._body.nodes[this.options.from];this.to=this._body.nodes[this.options.to];this.id=this.options.id;}/** @inheritDoc */drawLine(ctx,values,_selected,_hover){let viaNode=arguments.length>4&&arguments[4]!==undefined?arguments[4]:this.getViaNode();// set style
ctx.strokeStyle=this.getColor(ctx,values);ctx.lineWidth=values.width;if(values.dashes!==false){this._drawDashedLine(ctx,values,viaNode);}else {this._drawLine(ctx,values,viaNode);}}/**
   * Draw a line with given style between two nodes through supplied node(s).
   * @param ctx - The context that will be used for rendering.
   * @param values - Formatting values like color, opacity or shadow.
   * @param viaNode - Additional control point(s) for the edge.
   * @param fromPoint - TODO: Seems ignored, remove?
   * @param toPoint - TODO: Seems ignored, remove?
   */_drawLine(ctx,values,viaNode,fromPoint,toPoint){if(this.from!=this.to){// draw line
this._line(ctx,values,viaNode,fromPoint,toPoint);}else {const[x,y,radius]=this._getCircleData(ctx);this._circle(ctx,values,x,y,radius);}}/**
   * Draw a dashed line with given style between two nodes through supplied node(s).
   * @param ctx - The context that will be used for rendering.
   * @param values - Formatting values like color, opacity or shadow.
   * @param viaNode - Additional control point(s) for the edge.
   * @param _fromPoint - Ignored (TODO: remove in the future).
   * @param _toPoint - Ignored (TODO: remove in the future).
   */_drawDashedLine(ctx,values,viaNode,_fromPoint,_toPoint){ctx.lineCap="round";const pattern=_Array$isArray(values.dashes)?values.dashes:[5,5];// only firefox and chrome support this method, else we use the legacy one.
if(ctx.setLineDash!==undefined){ctx.save();// set dash settings for chrome or firefox
ctx.setLineDash(pattern);ctx.lineDashOffset=0;// draw the line
if(this.from!=this.to){// draw line
this._line(ctx,values,viaNode);}else {const[x,y,radius]=this._getCircleData(ctx);this._circle(ctx,values,x,y,radius);}// restore the dash settings.
ctx.setLineDash([0]);ctx.lineDashOffset=0;ctx.restore();}else {// unsupporting smooth lines
if(this.from!=this.to){// draw line
drawDashedLine(ctx,this.from.x,this.from.y,this.to.x,this.to.y,pattern);}else {const[x,y,radius]=this._getCircleData(ctx);this._circle(ctx,values,x,y,radius);}// draw shadow if enabled
this.enableShadow(ctx,values);ctx.stroke();// disable shadows for other elements.
this.disableShadow(ctx,values);}}/**
   * Find the intersection between the border of the node and the edge.
   * @param node - The node (either from or to node of the edge).
   * @param ctx - The context that will be used for rendering.
   * @param options - Additional options.
   * @returns Cartesian coordinates of the intersection between the border of the node and the edge.
   */findBorderPosition(node,ctx,options){if(this.from!=this.to){return this._findBorderPosition(node,ctx,options);}else {return this._findBorderPositionCircle(node,ctx,options);}}/** @inheritDoc */findBorderPositions(ctx){if(this.from!=this.to){return {from:this._findBorderPosition(this.from,ctx),to:this._findBorderPosition(this.to,ctx)};}else {var _context;const[x,y]=_sliceInstanceProperty(_context=this._getCircleData(ctx)).call(_context,0,2);return {from:this._findBorderPositionCircle(this.from,ctx,{x,y,low:0.25,high:0.6,direction:-1}),to:this._findBorderPositionCircle(this.from,ctx,{x,y,low:0.6,high:0.8,direction:1})};}}/**
   * Compute the center point and radius of an edge connected to the same node at both ends.
   * @param ctx - The context that will be used for rendering.
   * @returns `[x, y, radius]`
   */_getCircleData(ctx){const radius=this.options.selfReference.size;if(ctx!==undefined){if(this.from.shape.width===undefined){this.from.shape.resize(ctx);}}// get circle coordinates
const coordinates=getSelfRefCoordinates(ctx,this.options.selfReference.angle,radius,this.from);return [coordinates.x,coordinates.y,radius];}/**
   * Get a point on a circle.
   * @param x - Center of the circle on the x axis.
   * @param y - Center of the circle on the y axis.
   * @param radius - Radius of the circle.
   * @param position - Value between 0 (line start) and 1 (line end).
   * @returns Cartesian coordinates of requested point on the circle.
   */_pointOnCircle(x,y,radius,position){const angle=position*2*Math.PI;return {x:x+radius*Math.cos(angle),y:y-radius*Math.sin(angle)};}/**
   * Find the intersection between the border of the node and the edge.
   * @remarks
   * This function uses binary search to look for the point where the circle crosses the border of the node.
   * @param nearNode - The node (either from or to node of the edge).
   * @param ctx - The context that will be used for rendering.
   * @param options - Additional options.
   * @returns Cartesian coordinates of the intersection between the border of the node and the edge.
   */_findBorderPositionCircle(nearNode,ctx,options){const x=options.x;const y=options.y;let low=options.low;let high=options.high;const direction=options.direction;const maxIterations=10;const radius=this.options.selfReference.size;const threshold=0.05;let pos;let middle=(low+high)*0.5;let endPointOffset=0;if(this.options.arrowStrikethrough===true){if(direction===-1){endPointOffset=this.options.endPointOffset.from;}else if(direction===1){endPointOffset=this.options.endPointOffset.to;}}let iteration=0;do{middle=(low+high)*0.5;pos=this._pointOnCircle(x,y,radius,middle);const angle=Math.atan2(nearNode.y-pos.y,nearNode.x-pos.x);const distanceToBorder=nearNode.distanceToBorder(ctx,angle)+endPointOffset;const distanceToPoint=Math.sqrt(Math.pow(pos.x-nearNode.x,2)+Math.pow(pos.y-nearNode.y,2));const difference=distanceToBorder-distanceToPoint;if(Math.abs(difference)<threshold){break;// found
}else if(difference>0){// distance to nodes is larger than distance to border --> t needs to be bigger if we're looking at the to node.
if(direction>0){low=middle;}else {high=middle;}}else {if(direction>0){high=middle;}else {low=middle;}}++iteration;}while(low<=high&&iteration<maxIterations);return _objectSpread$1(_objectSpread$1({},pos),{},{t:middle});}/**
   * Get the line width of the edge. Depends on width and whether one of the connected nodes is selected.
   * @param selected - Determines wheter the line is selected.
   * @param hover - Determines wheter the line is being hovered, only applies if selected is false.
   * @returns The width of the line.
   */getLineWidth(selected,hover){if(selected===true){return Math.max(this.selectionWidth,0.3/this._body.view.scale);}else if(hover===true){return Math.max(this.hoverWidth,0.3/this._body.view.scale);}else {return Math.max(this.options.width,0.3/this._body.view.scale);}}/**
   * Compute the color or gradient for given edge.
   * @param ctx - The context that will be used for rendering.
   * @param values - Formatting values like color, opacity or shadow.
   * @param _selected - Ignored (TODO: remove in the future).
   * @param _hover - Ignored (TODO: remove in the future).
   * @returns Color string if single color is inherited or gradient if two.
   */getColor(ctx,values){if(values.inheritsColor!==false){// when this is a loop edge, just use the 'from' method
if(values.inheritsColor==="both"&&this.from.id!==this.to.id){const grd=ctx.createLinearGradient(this.from.x,this.from.y,this.to.x,this.to.y);let fromColor=this.from.options.color.highlight.border;let toColor=this.to.options.color.highlight.border;if(this.from.selected===false&&this.to.selected===false){fromColor=overrideOpacity(this.from.options.color.border,values.opacity);toColor=overrideOpacity(this.to.options.color.border,values.opacity);}else if(this.from.selected===true&&this.to.selected===false){toColor=this.to.options.color.border;}else if(this.from.selected===false&&this.to.selected===true){fromColor=this.from.options.color.border;}grd.addColorStop(0,fromColor);grd.addColorStop(1,toColor);// -------------------- this returns -------------------- //
return grd;}if(values.inheritsColor==="to"){return overrideOpacity(this.to.options.color.border,values.opacity);}else {// "from"
return overrideOpacity(this.from.options.color.border,values.opacity);}}else {return overrideOpacity(values.color,values.opacity);}}/**
   * Draw a line from a node to itself, a circle.
   * @param ctx - The context that will be used for rendering.
   * @param values - Formatting values like color, opacity or shadow.
   * @param x - Center of the circle on the x axis.
   * @param y - Center of the circle on the y axis.
   * @param radius - Radius of the circle.
   */_circle(ctx,values,x,y,radius){// draw shadow if enabled
this.enableShadow(ctx,values);//full circle
let angleFrom=0;let angleTo=Math.PI*2;if(!this.options.selfReference.renderBehindTheNode){//render only parts which are not overlaping with parent node
//need to find x,y of from point and x,y to point
//calculating radians
const low=this.options.selfReference.angle;const high=this.options.selfReference.angle+Math.PI;const pointTFrom=this._findBorderPositionCircle(this.from,ctx,{x,y,low,high,direction:-1});const pointTTo=this._findBorderPositionCircle(this.from,ctx,{x,y,low,high,direction:1});angleFrom=Math.atan2(pointTFrom.y-y,pointTFrom.x-x);angleTo=Math.atan2(pointTTo.y-y,pointTTo.x-x);}// draw a circle
ctx.beginPath();ctx.arc(x,y,radius,angleFrom,angleTo,false);ctx.stroke();// disable shadows for other elements.
this.disableShadow(ctx,values);}/**
   * @inheritDoc
   * @remarks
   * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
   */getDistanceToEdge(x1,y1,x2,y2,x3,y3){if(this.from!=this.to){return this._getDistanceToEdge(x1,y1,x2,y2,x3,y3);}else {const[x,y,radius]=this._getCircleData(undefined);const dx=x-x3;const dy=y-y3;return Math.abs(Math.sqrt(dx*dx+dy*dy)-radius);}}/**
   * Calculate the distance between a point (x3, y3) and a line segment from (x1, y1) to (x2, y2).
   * @param x1 - First end of the line segment on the x axis.
   * @param y1 - First end of the line segment on the y axis.
   * @param x2 - Second end of the line segment on the x axis.
   * @param y2 - Second end of the line segment on the y axis.
   * @param x3 - Position of the point on the x axis.
   * @param y3 - Position of the point on the y axis.
   * @returns The distance between the line segment and the point.
   */_getDistanceToLine(x1,y1,x2,y2,x3,y3){const px=x2-x1;const py=y2-y1;const something=px*px+py*py;let u=((x3-x1)*px+(y3-y1)*py)/something;if(u>1){u=1;}else if(u<0){u=0;}const x=x1+u*px;const y=y1+u*py;const dx=x-x3;const dy=y-y3;//# Note: If the actual distance does not matter,
//# if you only want to compare what this function
//# returns to other results of this function, you
//# can just return the squared distance instead
//# (i.e. remove the sqrt) to gain a little performance
return Math.sqrt(dx*dx+dy*dy);}/** @inheritDoc */getArrowData(ctx,position,viaNode,_selected,_hover,values){// set lets
let angle;let arrowPoint;let node1;let node2;let reversed;let scaleFactor;let type;const lineWidth=values.width;if(position==="from"){node1=this.from;node2=this.to;reversed=values.fromArrowScale<0;scaleFactor=Math.abs(values.fromArrowScale);type=values.fromArrowType;}else if(position==="to"){node1=this.to;node2=this.from;reversed=values.toArrowScale<0;scaleFactor=Math.abs(values.toArrowScale);type=values.toArrowType;}else {node1=this.to;node2=this.from;reversed=values.middleArrowScale<0;scaleFactor=Math.abs(values.middleArrowScale);type=values.middleArrowType;}const length=15*scaleFactor+3*lineWidth;// 3* lineWidth is the width of the edge.
// if not connected to itself
if(node1!=node2){const approximateEdgeLength=_Math$hypot(node1.x-node2.x,node1.y-node2.y);const relativeLength=length/approximateEdgeLength;if(position!=="middle"){// draw arrow head
if(this.options.smooth.enabled===true){const pointT=this._findBorderPosition(node1,ctx,{via:viaNode});const guidePos=this.getPoint(pointT.t+relativeLength*(position==="from"?1:-1),viaNode);angle=Math.atan2(pointT.y-guidePos.y,pointT.x-guidePos.x);arrowPoint=pointT;}else {angle=Math.atan2(node1.y-node2.y,node1.x-node2.x);arrowPoint=this._findBorderPosition(node1,ctx);}}else {// Negative half length reverses arrow direction.
const halfLength=(reversed?-relativeLength:relativeLength)/2;const guidePos1=this.getPoint(0.5+halfLength,viaNode);const guidePos2=this.getPoint(0.5-halfLength,viaNode);angle=Math.atan2(guidePos1.y-guidePos2.y,guidePos1.x-guidePos2.x);arrowPoint=this.getPoint(0.5,viaNode);}}else {// draw circle
const[x,y,radius]=this._getCircleData(ctx);if(position==="from"){const low=this.options.selfReference.angle;const high=this.options.selfReference.angle+Math.PI;const pointT=this._findBorderPositionCircle(this.from,ctx,{x,y,low,high,direction:-1});angle=pointT.t*-2*Math.PI+1.5*Math.PI+0.1*Math.PI;arrowPoint=pointT;}else if(position==="to"){const low=this.options.selfReference.angle;const high=this.options.selfReference.angle+Math.PI;const pointT=this._findBorderPositionCircle(this.from,ctx,{x,y,low,high,direction:1});angle=pointT.t*-2*Math.PI+1.5*Math.PI-1.1*Math.PI;arrowPoint=pointT;}else {const pos=this.options.selfReference.angle/(2*Math.PI);arrowPoint=this._pointOnCircle(x,y,radius,pos);angle=pos*-2*Math.PI+1.5*Math.PI+0.1*Math.PI;}}const xi=arrowPoint.x-length*0.9*Math.cos(angle);const yi=arrowPoint.y-length*0.9*Math.sin(angle);const arrowCore={x:xi,y:yi};return {point:arrowPoint,core:arrowCore,angle:angle,length:length,type:type};}/** @inheritDoc */drawArrowHead(ctx,values,_selected,_hover,arrowData){// set style
ctx.strokeStyle=this.getColor(ctx,values);ctx.fillStyle=ctx.strokeStyle;ctx.lineWidth=values.width;const canFill=EndPoints.draw(ctx,arrowData);if(canFill){// draw shadow if enabled
this.enableShadow(ctx,values);_fillInstanceProperty(ctx).call(ctx);// disable shadows for other elements.
this.disableShadow(ctx,values);}}/**
   * Set the shadow formatting values in the context if enabled, do nothing otherwise.
   * @param ctx - The context that will be used for rendering.
   * @param values - Formatting values for the shadow.
   */enableShadow(ctx,values){if(values.shadow===true){ctx.shadowColor=values.shadowColor;ctx.shadowBlur=values.shadowSize;ctx.shadowOffsetX=values.shadowX;ctx.shadowOffsetY=values.shadowY;}}/**
   * Reset the shadow formatting values in the context if enabled, do nothing otherwise.
   * @param ctx - The context that will be used for rendering.
   * @param values - Formatting values for the shadow.
   */disableShadow(ctx,values){if(values.shadow===true){ctx.shadowColor="rgba(0,0,0,0)";ctx.shadowBlur=0;ctx.shadowOffsetX=0;ctx.shadowOffsetY=0;}}/**
   * Render the background according to the formatting values.
   * @param ctx - The context that will be used for rendering.
   * @param values - Formatting values for the background.
   */drawBackground(ctx,values){if(values.background!==false){// save original line attrs
const origCtxAttr={strokeStyle:ctx.strokeStyle,lineWidth:ctx.lineWidth,dashes:ctx.dashes};ctx.strokeStyle=values.backgroundColor;ctx.lineWidth=values.backgroundSize;this.setStrokeDashed(ctx,values.backgroundDashes);ctx.stroke();// restore original line attrs
ctx.strokeStyle=origCtxAttr.strokeStyle;ctx.lineWidth=origCtxAttr.lineWidth;ctx.dashes=origCtxAttr.dashes;this.setStrokeDashed(ctx,values.dashes);}}/**
   * Set the line dash pattern if supported. Logs a warning to the console if it isn't supported.
   * @param ctx - The context that will be used for rendering.
   * @param dashes - The pattern [line, space, line…], true for default dashed line or false for normal line.
   */setStrokeDashed(ctx,dashes){if(dashes!==false){if(ctx.setLineDash!==undefined){const pattern=_Array$isArray(dashes)?dashes:[5,5];ctx.setLineDash(pattern);}else {console.warn("setLineDash is not supported in this browser. The dashed stroke cannot be used.");}}else {if(ctx.setLineDash!==undefined){ctx.setLineDash([]);}else {console.warn("setLineDash is not supported in this browser. The dashed stroke cannot be used.");}}}}function ownKeys(e,r){var t=_Object$keys(e);if(_Object$getOwnPropertySymbols){var o=_Object$getOwnPropertySymbols(e);r&&(o=_filterInstanceProperty(o).call(o,function(r){return _Object$getOwnPropertyDescriptor(e,r).enumerable;})),t.push.apply(t,o);}return t;}function _objectSpread(e){for(var r=1;r<arguments.length;r++){var _context,_context2;var t=null!=arguments[r]?arguments[r]:{};r%2?_forEachInstanceProperty(_context=ownKeys(Object(t),true)).call(_context,function(r){_defineProperty(e,r,t[r]);}):_Object$getOwnPropertyDescriptors?_Object$defineProperties(e,_Object$getOwnPropertyDescriptors(t)):_forEachInstanceProperty(_context2=ownKeys(Object(t))).call(_context2,function(r){_Object$defineProperty(e,r,_Object$getOwnPropertyDescriptor(t,r));});}return e;}/**
 * The Base Class for all Bezier edges.
 * Bezier curves are used to model smooth gradual curves in paths between nodes.
 */class BezierEdgeBase extends EdgeBase{/**
   * Find the intersection between the border of the node and the edge.
   * @remarks
   * This function uses binary search to look for the point where the bezier curve crosses the border of the node.
   * @param nearNode - The node (either from or to node of the edge).
   * @param ctx - The context that will be used for rendering.
   * @param viaNode - Additional node(s) the edge passes through.
   * @returns Cartesian coordinates of the intersection between the border of the node and the edge.
   */_findBorderPositionBezier(nearNode,ctx){let viaNode=arguments.length>2&&arguments[2]!==undefined?arguments[2]:this._getViaCoordinates();const maxIterations=10;const threshold=0.2;let from=false;let high=1;let low=0;let node=this.to;let pos;let middle;let endPointOffset=this.options.endPointOffset?this.options.endPointOffset.to:0;if(nearNode.id===this.from.id){node=this.from;from=true;endPointOffset=this.options.endPointOffset?this.options.endPointOffset.from:0;}if(this.options.arrowStrikethrough===false){endPointOffset=0;}let iteration=0;do{middle=(low+high)*0.5;pos=this.getPoint(middle,viaNode);const angle=Math.atan2(node.y-pos.y,node.x-pos.x);const distanceToBorder=node.distanceToBorder(ctx,angle)+endPointOffset;const distanceToPoint=Math.sqrt(Math.pow(pos.x-node.x,2)+Math.pow(pos.y-node.y,2));const difference=distanceToBorder-distanceToPoint;if(Math.abs(difference)<threshold){break;// found
}else if(difference<0){// distance to nodes is larger than distance to border --> t needs to be bigger if we're looking at the to node.
if(from===false){low=middle;}else {high=middle;}}else {if(from===false){high=middle;}else {low=middle;}}++iteration;}while(low<=high&&iteration<maxIterations);return _objectSpread(_objectSpread({},pos),{},{t:middle});}/**
   * Calculate the distance between a point (x3,y3) and a line segment from (x1,y1) to (x2,y2).
   * @remarks
   * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
   * @param x1 - First end of the line segment on the x axis.
   * @param y1 - First end of the line segment on the y axis.
   * @param x2 - Second end of the line segment on the x axis.
   * @param y2 - Second end of the line segment on the y axis.
   * @param x3 - Position of the point on the x axis.
   * @param y3 - Position of the point on the y axis.
   * @param via - The control point for the edge.
   * @returns The distance between the line segment and the point.
   */_getDistanceToBezierEdge(x1,y1,x2,y2,x3,y3,via){// x3,y3 is the point
let minDistance=1e9;let distance;let i,t,x,y;let lastX=x1;let lastY=y1;for(i=1;i<10;i++){t=0.1*i;x=Math.pow(1-t,2)*x1+2*t*(1-t)*via.x+Math.pow(t,2)*x2;y=Math.pow(1-t,2)*y1+2*t*(1-t)*via.y+Math.pow(t,2)*y2;if(i>0){distance=this._getDistanceToLine(lastX,lastY,x,y,x3,y3);minDistance=distance<minDistance?distance:minDistance;}lastX=x;lastY=y;}return minDistance;}/**
   * Render a bezier curve between two nodes.
   * @remarks
   * The method accepts zero, one or two control points.
   * Passing zero control points just draws a straight line.
   * @param ctx - The context that will be used for rendering.
   * @param values - Style options for edge drawing.
   * @param viaNode1 - First control point for curve drawing.
   * @param viaNode2 - Second control point for curve drawing.
   */_bezierCurve(ctx,values,viaNode1,viaNode2){ctx.beginPath();ctx.moveTo(this.fromPoint.x,this.fromPoint.y);if(viaNode1!=null&&viaNode1.x!=null){if(viaNode2!=null&&viaNode2.x!=null){ctx.bezierCurveTo(viaNode1.x,viaNode1.y,viaNode2.x,viaNode2.y,this.toPoint.x,this.toPoint.y);}else {ctx.quadraticCurveTo(viaNode1.x,viaNode1.y,this.toPoint.x,this.toPoint.y);}}else {// fallback to normal straight edge
ctx.lineTo(this.toPoint.x,this.toPoint.y);}// draw a background
this.drawBackground(ctx,values);// draw shadow if enabled
this.enableShadow(ctx,values);ctx.stroke();this.disableShadow(ctx,values);}/** @inheritDoc */getViaNode(){return this._getViaCoordinates();}}/**
 * A Dynamic Bezier Edge. Bezier curves are used to model smooth gradual
 * curves in paths between nodes. The Dynamic piece refers to how the curve
 * reacts to physics changes.
 * @augments BezierEdgeBase
 */class BezierEdgeDynamic extends BezierEdgeBase{/**
   * Create a new instance.
   * @param options - The options object of given edge.
   * @param body - The body of the network.
   * @param labelModule - Label module.
   */constructor(options,body,labelModule){//this.via = undefined; // Here for completeness but not allowed to defined before super() is invoked.
super(options,body,labelModule);// --> this calls the setOptions below
// @ts-expect-error constructor → super → super → setOptions → setupSupportNode
_defineProperty(this,"via",this.via);this._boundFunction=()=>{this.positionBezierNode();};this._body.emitter.on("_repositionBezierNodes",this._boundFunction);}/** @inheritDoc */setOptions(options){super.setOptions(options);// check if the physics has changed.
let physicsChange=false;if(this.options.physics!==options.physics){physicsChange=true;}// set the options and the to and from nodes
this.options=options;this.id=this.options.id;this.from=this._body.nodes[this.options.from];this.to=this._body.nodes[this.options.to];// setup the support node and connect
this.setupSupportNode();this.connect();// when we change the physics state of the edge, we reposition the support node.
if(physicsChange===true){this.via.setOptions({physics:this.options.physics});this.positionBezierNode();}}/** @inheritDoc */connect(){this.from=this._body.nodes[this.options.from];this.to=this._body.nodes[this.options.to];if(this.from===undefined||this.to===undefined||this.options.physics===false){this.via.setOptions({physics:false});}else {// fix weird behaviour where a self referencing node has physics enabled
if(this.from.id===this.to.id){this.via.setOptions({physics:false});}else {this.via.setOptions({physics:true});}}}/** @inheritDoc */cleanup(){this._body.emitter.off("_repositionBezierNodes",this._boundFunction);if(this.via!==undefined){delete this._body.nodes[this.via.id];this.via=undefined;return true;}return false;}/**
   * Create and add a support node if not already present.
   * @remarks
   * Bezier curves require an anchor point to calculate the smooth flow.
   * These points are nodes.
   * These nodes are invisible but are used for the force calculation.
   *
   * The changed data is not called, if needed, it is returned by the main edge constructor.
   */setupSupportNode(){if(this.via===undefined){const nodeId="edgeId:"+this.id;const node=this._body.functions.createNode({id:nodeId,shape:"circle",physics:true,hidden:true});this._body.nodes[nodeId]=node;this.via=node;this.via.parentEdgeId=this.id;this.positionBezierNode();}}/**
   * Position bezier node.
   */positionBezierNode(){if(this.via!==undefined&&this.from!==undefined&&this.to!==undefined){this.via.x=0.5*(this.from.x+this.to.x);this.via.y=0.5*(this.from.y+this.to.y);}else if(this.via!==undefined){this.via.x=0;this.via.y=0;}}/** @inheritDoc */_line(ctx,values,viaNode){this._bezierCurve(ctx,values,viaNode);}/** @inheritDoc */_getViaCoordinates(){return this.via;}/** @inheritDoc */getViaNode(){return this.via;}/** @inheritDoc */getPoint(position){let viaNode=arguments.length>1&&arguments[1]!==undefined?arguments[1]:this.via;if(this.from===this.to){const[cx,cy,cr]=this._getCircleData();const a=2*Math.PI*(1-position);return {x:cx+cr*Math.sin(a),y:cy+cr-cr*(1-Math.cos(a))};}else {return {x:Math.pow(1-position,2)*this.fromPoint.x+2*position*(1-position)*viaNode.x+Math.pow(position,2)*this.toPoint.x,y:Math.pow(1-position,2)*this.fromPoint.y+2*position*(1-position)*viaNode.y+Math.pow(position,2)*this.toPoint.y};}}/** @inheritDoc */_findBorderPosition(nearNode,ctx){return this._findBorderPositionBezier(nearNode,ctx,this.via);}/** @inheritDoc */_getDistanceToEdge(x1,y1,x2,y2,x3,y3){// x3,y3 is the point
return this._getDistanceToBezierEdge(x1,y1,x2,y2,x3,y3,this.via);}}/**
 * A Static Bezier Edge. Bezier curves are used to model smooth gradual curves in paths between nodes.
 */class BezierEdgeStatic extends BezierEdgeBase{/** @inheritDoc */_line(ctx,values,viaNode){this._bezierCurve(ctx,values,viaNode);}/** @inheritDoc */getViaNode(){return this._getViaCoordinates();}/**
   * Compute the coordinates of the via node.
   * @remarks
   * We do not use the to and fromPoints here to make the via nodes the same as edges without arrows.
   * @returns Cartesian coordinates of the via node.
   */_getViaCoordinates(){// Assumption: x/y coordinates in from/to always defined
const factor=this.options.smooth.roundness;const type=this.options.smooth.type;let dx=Math.abs(this.from.x-this.to.x);let dy=Math.abs(this.from.y-this.to.y);if(type==="discrete"||type==="diagonalCross"){let stepX;let stepY;if(dx<=dy){stepX=stepY=factor*dy;}else {stepX=stepY=factor*dx;}if(this.from.x>this.to.x){stepX=-stepX;}if(this.from.y>=this.to.y){stepY=-stepY;}let xVia=this.from.x+stepX;let yVia=this.from.y+stepY;if(type==="discrete"){if(dx<=dy){xVia=dx<factor*dy?this.from.x:xVia;}else {yVia=dy<factor*dx?this.from.y:yVia;}}return {x:xVia,y:yVia};}else if(type==="straightCross"){let stepX=(1-factor)*dx;let stepY=(1-factor)*dy;if(dx<=dy){// up - down
stepX=0;if(this.from.y<this.to.y){stepY=-stepY;}}else {// left - right
if(this.from.x<this.to.x){stepX=-stepX;}stepY=0;}return {x:this.to.x+stepX,y:this.to.y+stepY};}else if(type==="horizontal"){let stepX=(1-factor)*dx;if(this.from.x<this.to.x){stepX=-stepX;}return {x:this.to.x+stepX,y:this.from.y};}else if(type==="vertical"){let stepY=(1-factor)*dy;if(this.from.y<this.to.y){stepY=-stepY;}return {x:this.from.x,y:this.to.y+stepY};}else if(type==="curvedCW"){dx=this.to.x-this.from.x;dy=this.from.y-this.to.y;const radius=Math.sqrt(dx*dx+dy*dy);const pi=Math.PI;const originalAngle=Math.atan2(dy,dx);const myAngle=(originalAngle+(factor*0.5+0.5)*pi)%(2*pi);return {x:this.from.x+(factor*0.5+0.5)*radius*Math.sin(myAngle),y:this.from.y+(factor*0.5+0.5)*radius*Math.cos(myAngle)};}else if(type==="curvedCCW"){dx=this.to.x-this.from.x;dy=this.from.y-this.to.y;const radius=Math.sqrt(dx*dx+dy*dy);const pi=Math.PI;const originalAngle=Math.atan2(dy,dx);const myAngle=(originalAngle+(-factor*0.5+0.5)*pi)%(2*pi);return {x:this.from.x+(factor*0.5+0.5)*radius*Math.sin(myAngle),y:this.from.y+(factor*0.5+0.5)*radius*Math.cos(myAngle)};}else {// continuous
let stepX;let stepY;if(dx<=dy){stepX=stepY=factor*dy;}else {stepX=stepY=factor*dx;}if(this.from.x>this.to.x){stepX=-stepX;}if(this.from.y>=this.to.y){stepY=-stepY;}let xVia=this.from.x+stepX;let yVia=this.from.y+stepY;if(dx<=dy){if(this.from.x<=this.to.x){xVia=this.to.x<xVia?this.to.x:xVia;}else {xVia=this.to.x>xVia?this.to.x:xVia;}}else {if(this.from.y>=this.to.y){yVia=this.to.y>yVia?this.to.y:yVia;}else {yVia=this.to.y<yVia?this.to.y:yVia;}}return {x:xVia,y:yVia};}}/** @inheritDoc */_findBorderPosition(nearNode,ctx){let options=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};return this._findBorderPositionBezier(nearNode,ctx,options.via);}/** @inheritDoc */_getDistanceToEdge(x1,y1,x2,y2,x3,y3){let viaNode=arguments.length>6&&arguments[6]!==undefined?arguments[6]:this._getViaCoordinates();// x3,y3 is the point
return this._getDistanceToBezierEdge(x1,y1,x2,y2,x3,y3,viaNode);}/** @inheritDoc */getPoint(position){let viaNode=arguments.length>1&&arguments[1]!==undefined?arguments[1]:this._getViaCoordinates();const t=position;const x=Math.pow(1-t,2)*this.fromPoint.x+2*t*(1-t)*viaNode.x+Math.pow(t,2)*this.toPoint.x;const y=Math.pow(1-t,2)*this.fromPoint.y+2*t*(1-t)*viaNode.y+Math.pow(t,2)*this.toPoint.y;return {x:x,y:y};}}/**
 * A Base Class for all Cubic Bezier Edges. Bezier curves are used to model
 * smooth gradual curves in paths between nodes.
 * @augments BezierEdgeBase
 */class CubicBezierEdgeBase extends BezierEdgeBase{/**
   * Calculate the distance between a point (x3,y3) and a line segment from (x1,y1) to (x2,y2).
   * @remarks
   * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
   * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
   * @param x1 - First end of the line segment on the x axis.
   * @param y1 - First end of the line segment on the y axis.
   * @param x2 - Second end of the line segment on the x axis.
   * @param y2 - Second end of the line segment on the y axis.
   * @param x3 - Position of the point on the x axis.
   * @param y3 - Position of the point on the y axis.
   * @param via1 - The first point this edge passes through.
   * @param via2 - The second point this edge passes through.
   * @returns The distance between the line segment and the point.
   */_getDistanceToBezierEdge2(x1,y1,x2,y2,x3,y3,via1,via2){// x3,y3 is the point
let minDistance=1e9;let lastX=x1;let lastY=y1;const vec=[0,0,0,0];for(let i=1;i<10;i++){const t=0.1*i;vec[0]=Math.pow(1-t,3);vec[1]=3*t*Math.pow(1-t,2);vec[2]=3*Math.pow(t,2)*(1-t);vec[3]=Math.pow(t,3);const x=vec[0]*x1+vec[1]*via1.x+vec[2]*via2.x+vec[3]*x2;const y=vec[0]*y1+vec[1]*via1.y+vec[2]*via2.y+vec[3]*y2;if(i>0){const distance=this._getDistanceToLine(lastX,lastY,x,y,x3,y3);minDistance=distance<minDistance?distance:minDistance;}lastX=x;lastY=y;}return minDistance;}}/**
 * A Cubic Bezier Edge. Bezier curves are used to model smooth gradual curves in paths between nodes.
 */class CubicBezierEdge extends CubicBezierEdgeBase{/** @inheritDoc */_line(ctx,values,viaNodes){// get the coordinates of the support points.
const via1=viaNodes[0];const via2=viaNodes[1];this._bezierCurve(ctx,values,via1,via2);}/**
   * Compute the additional points the edge passes through.
   * @returns Cartesian coordinates of the points the edge passes through.
   */_getViaCoordinates(){const dx=this.from.x-this.to.x;const dy=this.from.y-this.to.y;let x1;let y1;let x2;let y2;const roundness=this.options.smooth.roundness;// horizontal if x > y or if direction is forced or if direction is horizontal
if((Math.abs(dx)>Math.abs(dy)||this.options.smooth.forceDirection===true||this.options.smooth.forceDirection==="horizontal")&&this.options.smooth.forceDirection!=="vertical"){y1=this.from.y;y2=this.to.y;x1=this.from.x-roundness*dx;x2=this.to.x+roundness*dx;}else {y1=this.from.y-roundness*dy;y2=this.to.y+roundness*dy;x1=this.from.x;x2=this.to.x;}return [{x:x1,y:y1},{x:x2,y:y2}];}/** @inheritDoc */getViaNode(){return this._getViaCoordinates();}/** @inheritDoc */_findBorderPosition(nearNode,ctx){return this._findBorderPositionBezier(nearNode,ctx);}/** @inheritDoc */_getDistanceToEdge(x1,y1,x2,y2,x3,y3){let[via1,via2]=arguments.length>6&&arguments[6]!==undefined?arguments[6]:this._getViaCoordinates();// x3,y3 is the point
return this._getDistanceToBezierEdge2(x1,y1,x2,y2,x3,y3,via1,via2);}/** @inheritDoc */getPoint(position){let[via1,via2]=arguments.length>1&&arguments[1]!==undefined?arguments[1]:this._getViaCoordinates();const t=position;const vec=[Math.pow(1-t,3),3*t*Math.pow(1-t,2),3*Math.pow(t,2)*(1-t),Math.pow(t,3)];const x=vec[0]*this.fromPoint.x+vec[1]*via1.x+vec[2]*via2.x+vec[3]*this.toPoint.x;const y=vec[0]*this.fromPoint.y+vec[1]*via1.y+vec[2]*via2.y+vec[3]*this.toPoint.y;return {x:x,y:y};}}/**
 * A Straight Edge.
 */class StraightEdge extends EdgeBase{/** @inheritDoc */_line(ctx,values){// draw a straight line
ctx.beginPath();ctx.moveTo(this.fromPoint.x,this.fromPoint.y);ctx.lineTo(this.toPoint.x,this.toPoint.y);// draw shadow if enabled
this.enableShadow(ctx,values);ctx.stroke();this.disableShadow(ctx,values);}/** @inheritDoc */getViaNode(){return undefined;}/** @inheritDoc */getPoint(position){return {x:(1-position)*this.fromPoint.x+position*this.toPoint.x,y:(1-position)*this.fromPoint.y+position*this.toPoint.y};}/** @inheritDoc */_findBorderPosition(nearNode,ctx){let node1=this.to;let node2=this.from;if(nearNode.id===this.from.id){node1=this.from;node2=this.to;}const angle=Math.atan2(node1.y-node2.y,node1.x-node2.x);const dx=node1.x-node2.x;const dy=node1.y-node2.y;const edgeSegmentLength=Math.sqrt(dx*dx+dy*dy);const toBorderDist=nearNode.distanceToBorder(ctx,angle);const toBorderPoint=(edgeSegmentLength-toBorderDist)/edgeSegmentLength;return {x:(1-toBorderPoint)*node2.x+toBorderPoint*node1.x,y:(1-toBorderPoint)*node2.y+toBorderPoint*node1.y,t:0};}/** @inheritDoc */_getDistanceToEdge(x1,y1,x2,y2,x3,y3){// x3,y3 is the point
return this._getDistanceToLine(x1,y1,x2,y2,x3,y3);}}/**
 * An edge connects two nodes and has a specific direction.
 */class Edge{/**
   * @param {object} options        values specific to this edge, must contain at least 'from' and 'to'
   * @param {object} body           shared state from Network instance
   * @param {Network.Images} imagelist  A list with images. Only needed when the edge has image arrows.
   * @param {object} globalOptions  options from the EdgesHandler instance
   * @param {object} defaultOptions default options from the EdgeHandler instance. Value and reference are constant
   */constructor(options,body,imagelist,globalOptions,defaultOptions){if(body===undefined){throw new Error("No body provided");}// Since globalOptions is constant in values as well as reference,
// Following needs to be done only once.
this.options=bridgeObject(globalOptions);this.globalOptions=globalOptions;this.defaultOptions=defaultOptions;this.body=body;this.imagelist=imagelist;// initialize variables
this.id=undefined;this.fromId=undefined;this.toId=undefined;this.selected=false;this.hover=false;this.labelDirty=true;this.baseWidth=this.options.width;this.baseFontSize=this.options.font.size;this.from=undefined;// a node
this.to=undefined;// a node
this.edgeType=undefined;this.connected=false;this.labelModule=new Label(this.body,this.options,true/* It's an edge label */);this.setOptions(options);}/**
   * Set or overwrite options for the edge
   * @param {object} options  an object with options
   * @returns {undefined|boolean} undefined if no options, true if layout affecting data changed, false otherwise.
   */setOptions(options){if(!options){return;}// Following options if changed affect the layout.
let affectsLayout=typeof options.physics!=="undefined"&&this.options.physics!==options.physics||typeof options.hidden!=="undefined"&&(this.options.hidden||false)!==(options.hidden||false)||typeof options.from!=="undefined"&&this.options.from!==options.from||typeof options.to!=="undefined"&&this.options.to!==options.to;Edge.parseOptions(this.options,options,true,this.globalOptions);if(options.id!==undefined){this.id=options.id;}if(options.from!==undefined){this.fromId=options.from;}if(options.to!==undefined){this.toId=options.to;}if(options.title!==undefined){this.title=options.title;}if(options.value!==undefined){options.value=_parseFloat(options.value);}const pile=[options,this.options,this.defaultOptions];this.chooser=choosify("edge",pile);// update label Module
this.updateLabelModule(options);// Update edge type, this if changed affects the layout.
affectsLayout=this.updateEdgeType()||affectsLayout;// if anything has been updates, reset the selection width and the hover width
this._setInteractionWidths();// A node is connected when it has a from and to node that both exist in the network.body.nodes.
this.connect();return affectsLayout;}/**
   *
   * @param {object} parentOptions
   * @param {object} newOptions
   * @param {boolean} [allowDeletion]
   * @param {object} [globalOptions]
   * @param {boolean} [copyFromGlobals]
   */static parseOptions(parentOptions,newOptions){let allowDeletion=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;let globalOptions=arguments.length>3&&arguments[3]!==undefined?arguments[3]:{};let copyFromGlobals=arguments.length>4&&arguments[4]!==undefined?arguments[4]:false;const fields=["endPointOffset","arrowStrikethrough","id","from","hidden","hoverWidth","labelHighlightBold","length","line","opacity","physics","scaling","selectionWidth","selfReferenceSize","selfReference","to","title","value","width","font","chosen","widthConstraint"];// only deep extend the items in the field array. These do not have shorthand.
selectiveDeepExtend(fields,parentOptions,newOptions,allowDeletion);// Only use endPointOffset values (from and to) if it's valid values
if(newOptions.endPointOffset!==undefined&&newOptions.endPointOffset.from!==undefined){if(_Number$isFinite(newOptions.endPointOffset.from)){parentOptions.endPointOffset.from=newOptions.endPointOffset.from;}else {parentOptions.endPointOffset.from=globalOptions.endPointOffset.from!==undefined?globalOptions.endPointOffset.from:0;console.error("endPointOffset.from is not a valid number");}}if(newOptions.endPointOffset!==undefined&&newOptions.endPointOffset.to!==undefined){if(_Number$isFinite(newOptions.endPointOffset.to)){parentOptions.endPointOffset.to=newOptions.endPointOffset.to;}else {parentOptions.endPointOffset.to=globalOptions.endPointOffset.to!==undefined?globalOptions.endPointOffset.to:0;console.error("endPointOffset.to is not a valid number");}}// Only copy label if it's a legal value.
if(isValidLabel(newOptions.label)){parentOptions.label=newOptions.label;}else if(!isValidLabel(parentOptions.label)){parentOptions.label=undefined;}mergeOptions(parentOptions,newOptions,"smooth",globalOptions);mergeOptions(parentOptions,newOptions,"shadow",globalOptions);mergeOptions(parentOptions,newOptions,"background",globalOptions);if(newOptions.dashes!==undefined&&newOptions.dashes!==null){parentOptions.dashes=newOptions.dashes;}else if(allowDeletion===true&&newOptions.dashes===null){parentOptions.dashes=_Object$create(globalOptions.dashes);// this sets the pointer of the option back to the global option.
}// set the scaling newOptions
if(newOptions.scaling!==undefined&&newOptions.scaling!==null){if(newOptions.scaling.min!==undefined){parentOptions.scaling.min=newOptions.scaling.min;}if(newOptions.scaling.max!==undefined){parentOptions.scaling.max=newOptions.scaling.max;}mergeOptions(parentOptions.scaling,newOptions.scaling,"label",globalOptions.scaling);}else if(allowDeletion===true&&newOptions.scaling===null){parentOptions.scaling=_Object$create(globalOptions.scaling);// this sets the pointer of the option back to the global option.
}// handle multiple input cases for arrows
if(newOptions.arrows!==undefined&&newOptions.arrows!==null){if(typeof newOptions.arrows==="string"){const arrows=newOptions.arrows.toLowerCase();parentOptions.arrows.to.enabled=_indexOfInstanceProperty(arrows).call(arrows,"to")!=-1;parentOptions.arrows.middle.enabled=_indexOfInstanceProperty(arrows).call(arrows,"middle")!=-1;parentOptions.arrows.from.enabled=_indexOfInstanceProperty(arrows).call(arrows,"from")!=-1;}else if(typeof newOptions.arrows==="object"){mergeOptions(parentOptions.arrows,newOptions.arrows,"to",globalOptions.arrows);mergeOptions(parentOptions.arrows,newOptions.arrows,"middle",globalOptions.arrows);mergeOptions(parentOptions.arrows,newOptions.arrows,"from",globalOptions.arrows);}else {throw new Error("The arrow newOptions can only be an object or a string. Refer to the documentation. You used:"+_JSON$stringify(newOptions.arrows));}}else if(allowDeletion===true&&newOptions.arrows===null){parentOptions.arrows=_Object$create(globalOptions.arrows);// this sets the pointer of the option back to the global option.
}// handle multiple input cases for color
if(newOptions.color!==undefined&&newOptions.color!==null){const fromColor=isString(newOptions.color)?{color:newOptions.color,highlight:newOptions.color,hover:newOptions.color,inherit:false,opacity:1}:newOptions.color;const toColor=parentOptions.color;// If passed, fill in values from default options - required in the case of no prototype bridging
if(copyFromGlobals){deepExtend(toColor,globalOptions.color,false,allowDeletion);}else {// Clear local properties - need to do it like this in order to retain prototype bridges
for(const i in toColor){if(Object.prototype.hasOwnProperty.call(toColor,i)){delete toColor[i];}}}if(isString(toColor)){toColor.color=toColor;toColor.highlight=toColor;toColor.hover=toColor;toColor.inherit=false;if(fromColor.opacity===undefined){toColor.opacity=1.0;// set default
}}else {let colorsDefined=false;if(fromColor.color!==undefined){toColor.color=fromColor.color;colorsDefined=true;}if(fromColor.highlight!==undefined){toColor.highlight=fromColor.highlight;colorsDefined=true;}if(fromColor.hover!==undefined){toColor.hover=fromColor.hover;colorsDefined=true;}if(fromColor.inherit!==undefined){toColor.inherit=fromColor.inherit;}if(fromColor.opacity!==undefined){toColor.opacity=Math.min(1,Math.max(0,fromColor.opacity));}if(colorsDefined===true){toColor.inherit=false;}else {if(toColor.inherit===undefined){toColor.inherit="from";// Set default
}}}}else if(allowDeletion===true&&newOptions.color===null){parentOptions.color=bridgeObject(globalOptions.color);// set the object back to the global options
}if(allowDeletion===true&&newOptions.font===null){parentOptions.font=bridgeObject(globalOptions.font);// set the object back to the global options
}if(Object.prototype.hasOwnProperty.call(newOptions,"selfReferenceSize")){console.warn("The selfReferenceSize property has been deprecated. Please use selfReference property instead. The selfReference can be set like thise selfReference:{size:30, angle:Math.PI / 4}");parentOptions.selfReference.size=newOptions.selfReferenceSize;}}/**
   *
   * @returns {ArrowOptions}
   */getFormattingValues(){const toArrow=this.options.arrows.to===true||this.options.arrows.to.enabled===true;const fromArrow=this.options.arrows.from===true||this.options.arrows.from.enabled===true;const middleArrow=this.options.arrows.middle===true||this.options.arrows.middle.enabled===true;const inheritsColor=this.options.color.inherit;const values={toArrow:toArrow,toArrowScale:this.options.arrows.to.scaleFactor,toArrowType:this.options.arrows.to.type,toArrowSrc:this.options.arrows.to.src,toArrowImageWidth:this.options.arrows.to.imageWidth,toArrowImageHeight:this.options.arrows.to.imageHeight,middleArrow:middleArrow,middleArrowScale:this.options.arrows.middle.scaleFactor,middleArrowType:this.options.arrows.middle.type,middleArrowSrc:this.options.arrows.middle.src,middleArrowImageWidth:this.options.arrows.middle.imageWidth,middleArrowImageHeight:this.options.arrows.middle.imageHeight,fromArrow:fromArrow,fromArrowScale:this.options.arrows.from.scaleFactor,fromArrowType:this.options.arrows.from.type,fromArrowSrc:this.options.arrows.from.src,fromArrowImageWidth:this.options.arrows.from.imageWidth,fromArrowImageHeight:this.options.arrows.from.imageHeight,arrowStrikethrough:this.options.arrowStrikethrough,color:inheritsColor?undefined:this.options.color.color,inheritsColor:inheritsColor,opacity:this.options.color.opacity,hidden:this.options.hidden,length:this.options.length,shadow:this.options.shadow.enabled,shadowColor:this.options.shadow.color,shadowSize:this.options.shadow.size,shadowX:this.options.shadow.x,shadowY:this.options.shadow.y,dashes:this.options.dashes,width:this.options.width,background:this.options.background.enabled,backgroundColor:this.options.background.color,backgroundSize:this.options.background.size,backgroundDashes:this.options.background.dashes};if(this.selected||this.hover){if(this.chooser===true){if(this.selected){const selectedWidth=this.options.selectionWidth;if(typeof selectedWidth==="function"){values.width=selectedWidth(values.width);}else if(typeof selectedWidth==="number"){values.width+=selectedWidth;}values.width=Math.max(values.width,0.3/this.body.view.scale);values.color=this.options.color.highlight;values.shadow=this.options.shadow.enabled;}else if(this.hover){const hoverWidth=this.options.hoverWidth;if(typeof hoverWidth==="function"){values.width=hoverWidth(values.width);}else if(typeof hoverWidth==="number"){values.width+=hoverWidth;}values.width=Math.max(values.width,0.3/this.body.view.scale);values.color=this.options.color.hover;values.shadow=this.options.shadow.enabled;}}else if(typeof this.chooser==="function"){this.chooser(values,this.options.id,this.selected,this.hover);if(values.color!==undefined){values.inheritsColor=false;}if(values.shadow===false){if(values.shadowColor!==this.options.shadow.color||values.shadowSize!==this.options.shadow.size||values.shadowX!==this.options.shadow.x||values.shadowY!==this.options.shadow.y){values.shadow=true;}}}}else {values.shadow=this.options.shadow.enabled;values.width=Math.max(values.width,0.3/this.body.view.scale);}return values;}/**
   * update the options in the label module
   * @param {object} options
   */updateLabelModule(options){const pile=[options,this.options,this.globalOptions,// Currently set global edge options
this.defaultOptions];this.labelModule.update(this.options,pile);if(this.labelModule.baseSize!==undefined){this.baseFontSize=this.labelModule.baseSize;}}/**
   * update the edge type, set the options
   * @returns {boolean}
   */updateEdgeType(){const smooth=this.options.smooth;let dataChanged=false;let changeInType=true;if(this.edgeType!==undefined){if(this.edgeType instanceof BezierEdgeDynamic&&smooth.enabled===true&&smooth.type==="dynamic"||this.edgeType instanceof CubicBezierEdge&&smooth.enabled===true&&smooth.type==="cubicBezier"||this.edgeType instanceof BezierEdgeStatic&&smooth.enabled===true&&smooth.type!=="dynamic"&&smooth.type!=="cubicBezier"||this.edgeType instanceof StraightEdge&&smooth.type.enabled===false){changeInType=false;}if(changeInType===true){dataChanged=this.cleanup();}}if(changeInType===true){if(smooth.enabled===true){if(smooth.type==="dynamic"){dataChanged=true;this.edgeType=new BezierEdgeDynamic(this.options,this.body,this.labelModule);}else if(smooth.type==="cubicBezier"){this.edgeType=new CubicBezierEdge(this.options,this.body,this.labelModule);}else {this.edgeType=new BezierEdgeStatic(this.options,this.body,this.labelModule);}}else {this.edgeType=new StraightEdge(this.options,this.body,this.labelModule);}}else {// if nothing changes, we just set the options.
this.edgeType.setOptions(this.options);}return dataChanged;}/**
   * Connect an edge to its nodes
   */connect(){this.disconnect();this.from=this.body.nodes[this.fromId]||undefined;this.to=this.body.nodes[this.toId]||undefined;this.connected=this.from!==undefined&&this.to!==undefined;if(this.connected===true){this.from.attachEdge(this);this.to.attachEdge(this);}else {if(this.from){this.from.detachEdge(this);}if(this.to){this.to.detachEdge(this);}}this.edgeType.connect();}/**
   * Disconnect an edge from its nodes
   */disconnect(){if(this.from){this.from.detachEdge(this);this.from=undefined;}if(this.to){this.to.detachEdge(this);this.to=undefined;}this.connected=false;}/**
   * get the title of this edge.
   * @returns {string} title    The title of the edge, or undefined when no title
   *                           has been set.
   */getTitle(){return this.title;}/**
   * check if this node is selecte
   * @returns {boolean} selected   True if node is selected, else false
   */isSelected(){return this.selected;}/**
   * Retrieve the value of the edge. Can be undefined
   * @returns {number} value
   */getValue(){return this.options.value;}/**
   * Adjust the value range of the edge. The edge will adjust it's width
   * based on its value.
   * @param {number} min
   * @param {number} max
   * @param {number} total
   */setValueRange(min,max,total){if(this.options.value!==undefined){const scale=this.options.scaling.customScalingFunction(min,max,total,this.options.value);const widthDiff=this.options.scaling.max-this.options.scaling.min;if(this.options.scaling.label.enabled===true){const fontDiff=this.options.scaling.label.max-this.options.scaling.label.min;this.options.font.size=this.options.scaling.label.min+scale*fontDiff;}this.options.width=this.options.scaling.min+scale*widthDiff;}else {this.options.width=this.baseWidth;this.options.font.size=this.baseFontSize;}this._setInteractionWidths();this.updateLabelModule();}/**
   *
   * @private
   */_setInteractionWidths(){if(typeof this.options.hoverWidth==="function"){this.edgeType.hoverWidth=this.options.hoverWidth(this.options.width);}else {this.edgeType.hoverWidth=this.options.hoverWidth+this.options.width;}if(typeof this.options.selectionWidth==="function"){this.edgeType.selectionWidth=this.options.selectionWidth(this.options.width);}else {this.edgeType.selectionWidth=this.options.selectionWidth+this.options.width;}}/**
   * Redraw a edge
   * Draw this edge in the given canvas
   * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
   * @param {CanvasRenderingContext2D}   ctx
   */draw(ctx){const values=this.getFormattingValues();if(values.hidden){return;}// get the via node from the edge type
const viaNode=this.edgeType.getViaNode();// draw line and label
this.edgeType.drawLine(ctx,values,this.selected,this.hover,viaNode);this.drawLabel(ctx,viaNode);}/**
   * Redraw arrows
   * Draw this arrows in the given canvas
   * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
   * @param {CanvasRenderingContext2D}   ctx
   */drawArrows(ctx){const values=this.getFormattingValues();if(values.hidden){return;}// get the via node from the edge type
const viaNode=this.edgeType.getViaNode();const arrowData={};// restore edge targets to defaults
this.edgeType.fromPoint=this.edgeType.from;this.edgeType.toPoint=this.edgeType.to;// from and to arrows give a different end point for edges. we set them here
if(values.fromArrow){arrowData.from=this.edgeType.getArrowData(ctx,"from",viaNode,this.selected,this.hover,values);if(values.arrowStrikethrough===false)this.edgeType.fromPoint=arrowData.from.core;if(values.fromArrowSrc){arrowData.from.image=this.imagelist.load(values.fromArrowSrc);}if(values.fromArrowImageWidth){arrowData.from.imageWidth=values.fromArrowImageWidth;}if(values.fromArrowImageHeight){arrowData.from.imageHeight=values.fromArrowImageHeight;}}if(values.toArrow){arrowData.to=this.edgeType.getArrowData(ctx,"to",viaNode,this.selected,this.hover,values);if(values.arrowStrikethrough===false)this.edgeType.toPoint=arrowData.to.core;if(values.toArrowSrc){arrowData.to.image=this.imagelist.load(values.toArrowSrc);}if(values.toArrowImageWidth){arrowData.to.imageWidth=values.toArrowImageWidth;}if(values.toArrowImageHeight){arrowData.to.imageHeight=values.toArrowImageHeight;}}// the middle arrow depends on the line, which can depend on the to and from arrows so we do this one lastly.
if(values.middleArrow){arrowData.middle=this.edgeType.getArrowData(ctx,"middle",viaNode,this.selected,this.hover,values);if(values.middleArrowSrc){arrowData.middle.image=this.imagelist.load(values.middleArrowSrc);}if(values.middleArrowImageWidth){arrowData.middle.imageWidth=values.middleArrowImageWidth;}if(values.middleArrowImageHeight){arrowData.middle.imageHeight=values.middleArrowImageHeight;}}if(values.fromArrow){this.edgeType.drawArrowHead(ctx,values,this.selected,this.hover,arrowData.from);}if(values.middleArrow){this.edgeType.drawArrowHead(ctx,values,this.selected,this.hover,arrowData.middle);}if(values.toArrow){this.edgeType.drawArrowHead(ctx,values,this.selected,this.hover,arrowData.to);}}/**
   *
   * @param {CanvasRenderingContext2D} ctx
   * @param {Node} viaNode
   */drawLabel(ctx,viaNode){if(this.options.label!==undefined){// set style
const node1=this.from;const node2=this.to;if(this.labelModule.differentState(this.selected,this.hover)){this.labelModule.getTextSize(ctx,this.selected,this.hover);}let point;if(node1.id!=node2.id){this.labelModule.pointToSelf=false;point=this.edgeType.getPoint(0.5,viaNode);ctx.save();const rotationPoint=this._getRotation(ctx);if(rotationPoint.angle!=0){ctx.translate(rotationPoint.x,rotationPoint.y);ctx.rotate(rotationPoint.angle);}// draw the label
this.labelModule.draw(ctx,point.x,point.y,this.selected,this.hover);/*
        // Useful debug code: draw a border around the label
        // This should **not** be enabled in production!
        var size = this.labelModule.getSize();; // ;; intentional so lint catches it
        ctx.strokeStyle = "#ff0000";
        ctx.strokeRect(size.left, size.top, size.width, size.height);
        // End  debug code
        */ctx.restore();}else {// Ignore the orientations.
this.labelModule.pointToSelf=true;// get circle coordinates
const coordinates=getSelfRefCoordinates(ctx,this.options.selfReference.angle,this.options.selfReference.size,node1);point=this._pointOnCircle(coordinates.x,coordinates.y,this.options.selfReference.size,this.options.selfReference.angle);this.labelModule.draw(ctx,point.x,point.y,this.selected,this.hover);}}}/**
   * Determine all visual elements of this edge instance, in which the given
   * point falls within the bounding shape.
   * @param {point} point
   * @returns {Array.<edgeClickItem|edgeLabelClickItem>} list with the items which are on the point
   */getItemsOnPoint(point){const ret=[];if(this.labelModule.visible()){const rotationPoint=this._getRotation();if(pointInRect(this.labelModule.getSize(),point,rotationPoint)){ret.push({edgeId:this.id,labelId:0});}}const obj={left:point.x,top:point.y};if(this.isOverlappingWith(obj)){ret.push({edgeId:this.id});}return ret;}/**
   * Check if this object is overlapping with the provided object
   * @param {object} obj   an object with parameters left, top
   * @returns {boolean}     True if location is located on the edge
   */isOverlappingWith(obj){if(this.connected){const distMax=10;const xFrom=this.from.x;const yFrom=this.from.y;const xTo=this.to.x;const yTo=this.to.y;const xObj=obj.left;const yObj=obj.top;const dist=this.edgeType.getDistanceToEdge(xFrom,yFrom,xTo,yTo,xObj,yObj);return dist<distMax;}else {return false;}}/**
   * Determine the rotation point, if any.
   * @param {CanvasRenderingContext2D} [ctx] if passed, do a recalculation of the label size
   * @returns {rotationPoint} the point to rotate around and the angle in radians to rotate
   * @private
   */_getRotation(ctx){const viaNode=this.edgeType.getViaNode();const point=this.edgeType.getPoint(0.5,viaNode);if(ctx!==undefined){this.labelModule.calculateLabelSize(ctx,this.selected,this.hover,point.x,point.y);}const ret={x:point.x,y:this.labelModule.size.yLine,angle:0};if(!this.labelModule.visible()){return ret;// Don't even bother doing the atan2, there's nothing to draw
}if(this.options.font.align==="horizontal"){return ret;// No need to calculate angle
}const dy=this.from.y-this.to.y;const dx=this.from.x-this.to.x;let angle=Math.atan2(dy,dx);// radians
// rotate so that label is readable
if(angle<-1&&dx<0||angle>0&&dx<0){angle+=Math.PI;}ret.angle=angle;return ret;}/**
   * Get a point on a circle
   * @param {number} x
   * @param {number} y
   * @param {number} radius
   * @param {number} angle
   * @returns {object} point
   * @private
   */_pointOnCircle(x,y,radius,angle){return {x:x+radius*Math.cos(angle),y:y-radius*Math.sin(angle)};}/**
   * Sets selected state to true
   */select(){this.selected=true;}/**
   * Sets selected state to false
   */unselect(){this.selected=false;}/**
   * cleans all required things on delete
   * @returns {*}
   */cleanup(){return this.edgeType.cleanup();}/**
   * Remove edge from the list and perform necessary cleanup.
   */remove(){this.cleanup();this.disconnect();delete this.body.edges[this.id];}/**
   * Check if both connecting nodes exist
   * @returns {boolean}
   */endPointsValid(){return this.body.nodes[this.fromId]!==undefined&&this.body.nodes[this.toId]!==undefined;}}/**
 * Handler for Edges
 */class EdgesHandler{/**
   * @param {object} body
   * @param {Array.<Image>} images
   * @param {Array.<Group>} groups
   */constructor(body,images,groups){var _context;this.body=body;this.images=images;this.groups=groups;// create the edge API in the body container
this.body.functions.createEdge=_bindInstanceProperty(_context=this.create).call(_context,this);this.edgesListeners={add:(event,params)=>{this.add(params.items);},update:(event,params)=>{this.update(params.items);},remove:(event,params)=>{this.remove(params.items);}};this.options={};this.defaultOptions={arrows:{to:{enabled:false,scaleFactor:1,type:"arrow"},// boolean / {arrowScaleFactor:1} / {enabled: false, arrowScaleFactor:1}
middle:{enabled:false,scaleFactor:1,type:"arrow"},from:{enabled:false,scaleFactor:1,type:"arrow"}},endPointOffset:{from:0,to:0},arrowStrikethrough:true,color:{color:"#848484",highlight:"#848484",hover:"#848484",inherit:"from",opacity:1.0},dashes:false,font:{color:"#343434",size:14,// px
face:"arial",background:"none",strokeWidth:2,// px
strokeColor:"#ffffff",align:"horizontal",multi:false,vadjust:0,bold:{mod:"bold"},boldital:{mod:"bold italic"},ital:{mod:"italic"},mono:{mod:"",size:15,// px
face:"courier new",vadjust:2}},hidden:false,hoverWidth:1.5,label:undefined,labelHighlightBold:true,length:undefined,physics:true,scaling:{min:1,max:15,label:{enabled:true,min:14,max:30,maxVisible:30,drawThreshold:5},customScalingFunction:function(min,max,total,value){if(max===min){return 0.5;}else {const scale=1/(max-min);return Math.max(0,(value-min)*scale);}}},selectionWidth:1.5,selfReference:{size:20,angle:Math.PI/4,renderBehindTheNode:true},shadow:{enabled:false,color:"rgba(0,0,0,0.5)",size:10,x:5,y:5},background:{enabled:false,color:"rgba(111,111,111,1)",size:10,dashes:false},smooth:{enabled:true,type:"dynamic",forceDirection:"none",roundness:0.5},title:undefined,width:1,value:undefined};deepExtend(this.options,this.defaultOptions);this.bindEventListeners();}/**
   * Binds event listeners
   */bindEventListeners(){var _this=this,_context2,_context3;// this allows external modules to force all dynamic curves to turn static.
this.body.emitter.on("_forceDisableDynamicCurves",function(type){let emit=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;if(type==="dynamic"){type="continuous";}let dataChanged=false;for(const edgeId in _this.body.edges){if(Object.prototype.hasOwnProperty.call(_this.body.edges,edgeId)){const edge=_this.body.edges[edgeId];const edgeData=_this.body.data.edges.get(edgeId);// only forcibly remove the smooth curve if the data has been set of the edge has the smooth curves defined.
// this is because a change in the global would not affect these curves.
if(edgeData!=null){const smoothOptions=edgeData.smooth;if(smoothOptions!==undefined){if(smoothOptions.enabled===true&&smoothOptions.type==="dynamic"){if(type===undefined){edge.setOptions({smooth:false});}else {edge.setOptions({smooth:{type:type}});}dataChanged=true;}}}}}if(emit===true&&dataChanged===true){_this.body.emitter.emit("_dataChanged");}});// this is called when options of EXISTING nodes or edges have changed.
//
// NOTE: Not true, called when options have NOT changed, for both existing as well as new nodes.
//       See update() for logic.
// TODO: Verify and examine the consequences of this. It might still trigger when
//       non-option fields have changed, but then reconnecting edges is still useless.
//       Alternatively, it might also be called when edges are removed.
//
this.body.emitter.on("_dataUpdated",()=>{this.reconnectEdges();});// refresh the edges. Used when reverting from hierarchical layout
this.body.emitter.on("refreshEdges",_bindInstanceProperty(_context2=this.refresh).call(_context2,this));this.body.emitter.on("refresh",_bindInstanceProperty(_context3=this.refresh).call(_context3,this));this.body.emitter.on("destroy",()=>{forEach(this.edgesListeners,(callback,event)=>{if(this.body.data.edges)this.body.data.edges.off(event,callback);});delete this.body.functions.createEdge;delete this.edgesListeners.add;delete this.edgesListeners.update;delete this.edgesListeners.remove;delete this.edgesListeners;});}/**
   *
   * @param {object} options
   */setOptions(options){if(options!==undefined){// use the parser from the Edge class to fill in all shorthand notations
Edge.parseOptions(this.options,options,true,this.defaultOptions,true);// update smooth settings in all edges
let dataChanged=false;if(options.smooth!==undefined){for(const edgeId in this.body.edges){if(Object.prototype.hasOwnProperty.call(this.body.edges,edgeId)){dataChanged=this.body.edges[edgeId].updateEdgeType()||dataChanged;}}}// update fonts in all edges
if(options.font!==undefined){for(const edgeId in this.body.edges){if(Object.prototype.hasOwnProperty.call(this.body.edges,edgeId)){this.body.edges[edgeId].updateLabelModule();}}}// update the state of the variables if needed
if(options.hidden!==undefined||options.physics!==undefined||dataChanged===true){this.body.emitter.emit("_dataChanged");}}}/**
   * Load edges by reading the data table
   * @param {Array | DataSet | DataView} edges    The data containing the edges.
   * @param {boolean} [doNotEmit] - Suppress data changed event.
   * @private
   */setData(edges){let doNotEmit=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;const oldEdgesData=this.body.data.edges;if(isDataViewLike("id",edges)){this.body.data.edges=edges;}else if(_Array$isArray(edges)){this.body.data.edges=new DataSet();this.body.data.edges.add(edges);}else if(!edges){this.body.data.edges=new DataSet();}else {throw new TypeError("Array or DataSet expected");}// TODO: is this null or undefined or false?
if(oldEdgesData){// unsubscribe from old dataset
forEach(this.edgesListeners,(callback,event)=>{oldEdgesData.off(event,callback);});}// remove drawn edges
this.body.edges={};// TODO: is this null or undefined or false?
if(this.body.data.edges){// subscribe to new dataset
forEach(this.edgesListeners,(callback,event)=>{this.body.data.edges.on(event,callback);});// draw all new nodes
const ids=this.body.data.edges.getIds();this.add(ids,true);}this.body.emitter.emit("_adjustEdgesForHierarchicalLayout");if(doNotEmit===false){this.body.emitter.emit("_dataChanged");}}/**
   * Add edges
   * @param {number[] | string[]} ids
   * @param {boolean} [doNotEmit]
   * @private
   */add(ids){let doNotEmit=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;const edges=this.body.edges;const edgesData=this.body.data.edges;for(let i=0;i<ids.length;i++){const id=ids[i];const oldEdge=edges[id];if(oldEdge){oldEdge.disconnect();}const data=edgesData.get(id,{showInternalIds:true});edges[id]=this.create(data);}this.body.emitter.emit("_adjustEdgesForHierarchicalLayout");if(doNotEmit===false){this.body.emitter.emit("_dataChanged");}}/**
   * Update existing edges, or create them when not yet existing
   * @param {number[] | string[]} ids
   * @private
   */update(ids){const edges=this.body.edges;const edgesData=this.body.data.edges;let dataChanged=false;for(let i=0;i<ids.length;i++){const id=ids[i];const data=edgesData.get(id);const edge=edges[id];if(edge!==undefined){// update edge
edge.disconnect();dataChanged=edge.setOptions(data)||dataChanged;// if a support node is added, data can be changed.
edge.connect();}else {// create edge
this.body.edges[id]=this.create(data);dataChanged=true;}}if(dataChanged===true){this.body.emitter.emit("_adjustEdgesForHierarchicalLayout");this.body.emitter.emit("_dataChanged");}else {this.body.emitter.emit("_dataUpdated");}}/**
   * Remove existing edges. Non existing ids will be ignored
   * @param {number[] | string[]} ids
   * @param {boolean} [emit]
   * @private
   */remove(ids){let emit=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;if(ids.length===0)return;// early out
const edges=this.body.edges;forEach(ids,id=>{const edge=edges[id];if(edge!==undefined){edge.remove();}});if(emit){this.body.emitter.emit("_dataChanged");}}/**
   * Refreshes Edge Handler
   */refresh(){forEach(this.body.edges,(edge,edgeId)=>{const data=this.body.data.edges.get(edgeId);if(data!==undefined){edge.setOptions(data);}});}/**
   *
   * @param {object} properties
   * @returns {Edge}
   */create(properties){return new Edge(properties,this.body,this.images,this.options,this.defaultOptions);}/**
   * Reconnect all edges
   * @private
   */reconnectEdges(){let id;const nodes=this.body.nodes;const edges=this.body.edges;for(id in nodes){if(Object.prototype.hasOwnProperty.call(nodes,id)){nodes[id].edges=[];}}for(id in edges){if(Object.prototype.hasOwnProperty.call(edges,id)){const edge=edges[id];edge.from=null;edge.to=null;edge.connect();}}}/**
   *
   * @param {Edge.id} edgeId
   * @returns {Array}
   */getConnectedNodes(edgeId){const nodeList=[];if(this.body.edges[edgeId]!==undefined){const edge=this.body.edges[edgeId];if(edge.fromId!==undefined){nodeList.push(edge.fromId);}if(edge.toId!==undefined){nodeList.push(edge.toId);}}return nodeList;}/**
   * There is no direct relation between the nodes and the edges DataSet,
   * so the right place to do call this is in the handler for event `_dataUpdated`.
   */_updateState(){this._addMissingEdges();this._removeInvalidEdges();}/**
   * Scan for missing nodes and remove corresponding edges, if any.
   * @private
   */_removeInvalidEdges(){const edgesToDelete=[];forEach(this.body.edges,(edge,id)=>{const toNode=this.body.nodes[edge.toId];const fromNode=this.body.nodes[edge.fromId];// Skip clustering edges here, let the Clustering module handle those
if(toNode!==undefined&&toNode.isCluster===true||fromNode!==undefined&&fromNode.isCluster===true){return;}if(toNode===undefined||fromNode===undefined){edgesToDelete.push(id);}});this.remove(edgesToDelete,false);}/**
   * add all edges from dataset that are not in the cached state
   * @private
   */_addMissingEdges(){const edgesData=this.body.data.edges;if(edgesData===undefined||edgesData===null){return;// No edges DataSet yet; can happen on startup
}const edges=this.body.edges;const addIds=[];_forEachInstanceProperty(edgesData).call(edgesData,(edgeData,edgeId)=>{const edge=edges[edgeId];if(edge===undefined){addIds.push(edgeId);}});this.add(addIds,true);}}/**
 * Barnes Hut Solver
 */class BarnesHutSolver{/**
   * @param {object} body
   * @param {{physicsNodeIndices: Array, physicsEdgeIndices: Array, forces: {}, velocities: {}}} physicsBody
   * @param {object} options
   */constructor(body,physicsBody,options){this.body=body;this.physicsBody=physicsBody;this.setOptions(options);this._rng=Alea("BARNES HUT SOLVER");// debug: show grid
// this.body.emitter.on("afterDrawing", (ctx) => {this._debug(ctx,'#ff0000')})
}/**
   *
   * @param {object} options
   */setOptions(options){this.options=options;this.thetaInversed=1/this.options.theta;// if 1 then min distance = 0.5, if 0.5 then min distance = 0.5 + 0.5*node.shape.radius
this.overlapAvoidanceFactor=1-Math.max(0,Math.min(1,this.options.avoidOverlap));}/**
   * This function calculates the forces the nodes apply on each other based on a gravitational model.
   * The Barnes Hut method is used to speed up this N-body simulation.
   * @private
   */solve(){if(this.options.gravitationalConstant!==0&&this.physicsBody.physicsNodeIndices.length>0){let node;const nodes=this.body.nodes;const nodeIndices=this.physicsBody.physicsNodeIndices;const nodeCount=nodeIndices.length;// create the tree
const barnesHutTree=this._formBarnesHutTree(nodes,nodeIndices);// for debugging
this.barnesHutTree=barnesHutTree;// place the nodes one by one recursively
for(let i=0;i<nodeCount;i++){node=nodes[nodeIndices[i]];if(node.options.mass>0){// starting with root is irrelevant, it never passes the BarnesHutSolver condition
this._getForceContributions(barnesHutTree.root,node);}}}}/**
   * @param {object} parentBranch
   * @param {Node} node
   * @private
   */_getForceContributions(parentBranch,node){this._getForceContribution(parentBranch.children.NW,node);this._getForceContribution(parentBranch.children.NE,node);this._getForceContribution(parentBranch.children.SW,node);this._getForceContribution(parentBranch.children.SE,node);}/**
   * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass.
   * If a region contains a single node, we check if it is not itself, then we apply the force.
   * @param {object} parentBranch
   * @param {Node} node
   * @private
   */_getForceContribution(parentBranch,node){// we get no force contribution from an empty region
if(parentBranch.childrenCount>0){// get the distance from the center of mass to the node.
const dx=parentBranch.centerOfMass.x-node.x;const dy=parentBranch.centerOfMass.y-node.y;const distance=Math.sqrt(dx*dx+dy*dy);// BarnesHutSolver condition
// original condition : s/d < theta = passed  ===  d/s > 1/theta = passed
// calcSize = 1/s --> d * 1/s > 1/theta = passed
if(distance*parentBranch.calcSize>this.thetaInversed){this._calculateForces(distance,dx,dy,node,parentBranch);}else {// Did not pass the condition, go into children if available
if(parentBranch.childrenCount===4){this._getForceContributions(parentBranch,node);}else {// parentBranch must have only one node, if it was empty we wouldnt be here
if(parentBranch.children.data.id!=node.id){// if it is not self
this._calculateForces(distance,dx,dy,node,parentBranch);}}}}}/**
   * Calculate the forces based on the distance.
   * @param {number} distance
   * @param {number} dx
   * @param {number} dy
   * @param {Node} node
   * @param {object} parentBranch
   * @private
   */_calculateForces(distance,dx,dy,node,parentBranch){if(distance===0){distance=0.1;dx=distance;}if(this.overlapAvoidanceFactor<1&&node.shape.radius){distance=Math.max(0.1+this.overlapAvoidanceFactor*node.shape.radius,distance-node.shape.radius);}// the dividing by the distance cubed instead of squared allows us to get the fx and fy components without sines and cosines
// it is shorthand for gravityforce with distance squared and fx = dx/distance * gravityForce
const gravityForce=this.options.gravitationalConstant*parentBranch.mass*node.options.mass/Math.pow(distance,3);const fx=dx*gravityForce;const fy=dy*gravityForce;this.physicsBody.forces[node.id].x+=fx;this.physicsBody.forces[node.id].y+=fy;}/**
   * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes.
   * @param {Array.<Node>} nodes
   * @param {Array.<number>} nodeIndices
   * @returns {{root: {centerOfMass: {x: number, y: number}, mass: number, range: {minX: number, maxX: number, minY: number, maxY: number}, size: number, calcSize: number, children: {data: null}, maxWidth: number, level: number, childrenCount: number}}} BarnesHutTree
   * @private
   */_formBarnesHutTree(nodes,nodeIndices){let node;const nodeCount=nodeIndices.length;let minX=nodes[nodeIndices[0]].x;let minY=nodes[nodeIndices[0]].y;let maxX=nodes[nodeIndices[0]].x;let maxY=nodes[nodeIndices[0]].y;// get the range of the nodes
for(let i=1;i<nodeCount;i++){const node=nodes[nodeIndices[i]];const x=node.x;const y=node.y;if(node.options.mass>0){if(x<minX){minX=x;}if(x>maxX){maxX=x;}if(y<minY){minY=y;}if(y>maxY){maxY=y;}}}// make the range a square
const sizeDiff=Math.abs(maxX-minX)-Math.abs(maxY-minY);// difference between X and Y
if(sizeDiff>0){minY-=0.5*sizeDiff;maxY+=0.5*sizeDiff;}// xSize > ySize
else {minX+=0.5*sizeDiff;maxX-=0.5*sizeDiff;}// xSize < ySize
const minimumTreeSize=1e-5;const rootSize=Math.max(minimumTreeSize,Math.abs(maxX-minX));const halfRootSize=0.5*rootSize;const centerX=0.5*(minX+maxX),centerY=0.5*(minY+maxY);// construct the barnesHutTree
const barnesHutTree={root:{centerOfMass:{x:0,y:0},mass:0,range:{minX:centerX-halfRootSize,maxX:centerX+halfRootSize,minY:centerY-halfRootSize,maxY:centerY+halfRootSize},size:rootSize,calcSize:1/rootSize,children:{data:null},maxWidth:0,level:0,childrenCount:4}};this._splitBranch(barnesHutTree.root);// place the nodes one by one recursively
for(let i=0;i<nodeCount;i++){node=nodes[nodeIndices[i]];if(node.options.mass>0){this._placeInTree(barnesHutTree.root,node);}}// make global
return barnesHutTree;}/**
   * this updates the mass of a branch. this is increased by adding a node.
   * @param {object} parentBranch
   * @param {Node} node
   * @private
   */_updateBranchMass(parentBranch,node){const centerOfMass=parentBranch.centerOfMass;const totalMass=parentBranch.mass+node.options.mass;const totalMassInv=1/totalMass;centerOfMass.x=centerOfMass.x*parentBranch.mass+node.x*node.options.mass;centerOfMass.x*=totalMassInv;centerOfMass.y=centerOfMass.y*parentBranch.mass+node.y*node.options.mass;centerOfMass.y*=totalMassInv;parentBranch.mass=totalMass;const biggestSize=Math.max(Math.max(node.height,node.radius),node.width);parentBranch.maxWidth=parentBranch.maxWidth<biggestSize?biggestSize:parentBranch.maxWidth;}/**
   * determine in which branch the node will be placed.
   * @param {object} parentBranch
   * @param {Node} node
   * @param {boolean} skipMassUpdate
   * @private
   */_placeInTree(parentBranch,node,skipMassUpdate){if(skipMassUpdate!=true||skipMassUpdate===undefined){// update the mass of the branch.
this._updateBranchMass(parentBranch,node);}const range=parentBranch.children.NW.range;let region;if(range.maxX>node.x){// in NW or SW
if(range.maxY>node.y){region="NW";}else {region="SW";}}else {// in NE or SE
if(range.maxY>node.y){region="NE";}else {region="SE";}}this._placeInRegion(parentBranch,node,region);}/**
   * actually place the node in a region (or branch)
   * @param {object} parentBranch
   * @param {Node} node
   * @param {'NW'| 'NE' | 'SW' | 'SE'} region
   * @private
   */_placeInRegion(parentBranch,node,region){const children=parentBranch.children[region];switch(children.childrenCount){case 0:// place node here
children.children.data=node;children.childrenCount=1;this._updateBranchMass(children,node);break;case 1:// convert into children
// if there are two nodes exactly overlapping (on init, on opening of cluster etc.)
// we move one node a little bit and we do not put it in the tree.
if(children.children.data.x===node.x&&children.children.data.y===node.y){node.x+=this._rng();node.y+=this._rng();}else {this._splitBranch(children);this._placeInTree(children,node);}break;case 4:// place in branch
this._placeInTree(children,node);break;}}/**
   * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch
   * after the split is complete.
   * @param {object} parentBranch
   * @private
   */_splitBranch(parentBranch){// if the branch is shaded with a node, replace the node in the new subset.
let containedNode=null;if(parentBranch.childrenCount===1){containedNode=parentBranch.children.data;parentBranch.mass=0;parentBranch.centerOfMass.x=0;parentBranch.centerOfMass.y=0;}parentBranch.childrenCount=4;parentBranch.children.data=null;this._insertRegion(parentBranch,"NW");this._insertRegion(parentBranch,"NE");this._insertRegion(parentBranch,"SW");this._insertRegion(parentBranch,"SE");if(containedNode!=null){this._placeInTree(parentBranch,containedNode);}}/**
   * This function subdivides the region into four new segments.
   * Specifically, this inserts a single new segment.
   * It fills the children section of the parentBranch
   * @param {object} parentBranch
   * @param {'NW'| 'NE' | 'SW' | 'SE'} region
   * @private
   */_insertRegion(parentBranch,region){let minX,maxX,minY,maxY;const childSize=0.5*parentBranch.size;switch(region){case "NW":minX=parentBranch.range.minX;maxX=parentBranch.range.minX+childSize;minY=parentBranch.range.minY;maxY=parentBranch.range.minY+childSize;break;case "NE":minX=parentBranch.range.minX+childSize;maxX=parentBranch.range.maxX;minY=parentBranch.range.minY;maxY=parentBranch.range.minY+childSize;break;case "SW":minX=parentBranch.range.minX;maxX=parentBranch.range.minX+childSize;minY=parentBranch.range.minY+childSize;maxY=parentBranch.range.maxY;break;case "SE":minX=parentBranch.range.minX+childSize;maxX=parentBranch.range.maxX;minY=parentBranch.range.minY+childSize;maxY=parentBranch.range.maxY;break;}parentBranch.children[region]={centerOfMass:{x:0,y:0},mass:0,range:{minX:minX,maxX:maxX,minY:minY,maxY:maxY},size:0.5*parentBranch.size,calcSize:2*parentBranch.calcSize,children:{data:null},maxWidth:0,level:parentBranch.level+1,childrenCount:0};}//---------------------------  DEBUGGING BELOW  ---------------------------//
/**
   * This function is for debugging purposed, it draws the tree.
   * @param {CanvasRenderingContext2D} ctx
   * @param {string} color
   * @private
   */_debug(ctx,color){if(this.barnesHutTree!==undefined){ctx.lineWidth=1;this._drawBranch(this.barnesHutTree.root,ctx,color);}}/**
   * This function is for debugging purposes. It draws the branches recursively.
   * @param {object} branch
   * @param {CanvasRenderingContext2D} ctx
   * @param {string} color
   * @private
   */_drawBranch(branch,ctx,color){if(color===undefined){color="#FF0000";}if(branch.childrenCount===4){this._drawBranch(branch.children.NW,ctx);this._drawBranch(branch.children.NE,ctx);this._drawBranch(branch.children.SE,ctx);this._drawBranch(branch.children.SW,ctx);}ctx.strokeStyle=color;ctx.beginPath();ctx.moveTo(branch.range.minX,branch.range.minY);ctx.lineTo(branch.range.maxX,branch.range.minY);ctx.stroke();ctx.beginPath();ctx.moveTo(branch.range.maxX,branch.range.minY);ctx.lineTo(branch.range.maxX,branch.range.maxY);ctx.stroke();ctx.beginPath();ctx.moveTo(branch.range.maxX,branch.range.maxY);ctx.lineTo(branch.range.minX,branch.range.maxY);ctx.stroke();ctx.beginPath();ctx.moveTo(branch.range.minX,branch.range.maxY);ctx.lineTo(branch.range.minX,branch.range.minY);ctx.stroke();/*
     if (branch.mass > 0) {
     ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass);
     ctx.stroke();
     }
     */}}/**
 * Repulsion Solver
 */class RepulsionSolver{/**
   * @param {object} body
   * @param {{physicsNodeIndices: Array, physicsEdgeIndices: Array, forces: {}, velocities: {}}} physicsBody
   * @param {object} options
   */constructor(body,physicsBody,options){this._rng=Alea("REPULSION SOLVER");this.body=body;this.physicsBody=physicsBody;this.setOptions(options);}/**
   *
   * @param {object} options
   */setOptions(options){this.options=options;}/**
   * Calculate the forces the nodes apply on each other based on a repulsion field.
   * This field is linearly approximated.
   * @private
   */solve(){let dx,dy,distance,fx,fy,repulsingForce,node1,node2;const nodes=this.body.nodes;const nodeIndices=this.physicsBody.physicsNodeIndices;const forces=this.physicsBody.forces;// repulsing forces between nodes
const nodeDistance=this.options.nodeDistance;// approximation constants
const a=-2/3/nodeDistance;const b=4/3;// we loop from i over all but the last entree in the array
// j loops from i+1 to the last. This way we do not double count any of the indices, nor i === j
for(let i=0;i<nodeIndices.length-1;i++){node1=nodes[nodeIndices[i]];for(let j=i+1;j<nodeIndices.length;j++){node2=nodes[nodeIndices[j]];dx=node2.x-node1.x;dy=node2.y-node1.y;distance=Math.sqrt(dx*dx+dy*dy);// same condition as BarnesHutSolver, making sure nodes are never 100% overlapping.
if(distance===0){distance=0.1*this._rng();dx=distance;}if(distance<2*nodeDistance){if(distance<0.5*nodeDistance){repulsingForce=1.0;}else {repulsingForce=a*distance+b;// linear approx of  1 / (1 + Math.exp((distance / nodeDistance - 1) * steepness))
}repulsingForce=repulsingForce/distance;fx=dx*repulsingForce;fy=dy*repulsingForce;forces[node1.id].x-=fx;forces[node1.id].y-=fy;forces[node2.id].x+=fx;forces[node2.id].y+=fy;}}}}}/**
 * Hierarchical Repulsion Solver
 */class HierarchicalRepulsionSolver{/**
   * @param {object} body
   * @param {{physicsNodeIndices: Array, physicsEdgeIndices: Array, forces: {}, velocities: {}}} physicsBody
   * @param {object} options
   */constructor(body,physicsBody,options){this.body=body;this.physicsBody=physicsBody;this.setOptions(options);}/**
   *
   * @param {object} options
   */setOptions(options){this.options=options;this.overlapAvoidanceFactor=Math.max(0,Math.min(1,this.options.avoidOverlap||0));}/**
   * Calculate the forces the nodes apply on each other based on a repulsion field.
   * This field is linearly approximated.
   * @private
   */solve(){const nodes=this.body.nodes;const nodeIndices=this.physicsBody.physicsNodeIndices;const forces=this.physicsBody.forces;// repulsing forces between nodes
const nodeDistance=this.options.nodeDistance;// we loop from i over all but the last entree in the array
// j loops from i+1 to the last. This way we do not double count any of the indices, nor i === j
for(let i=0;i<nodeIndices.length-1;i++){const node1=nodes[nodeIndices[i]];for(let j=i+1;j<nodeIndices.length;j++){const node2=nodes[nodeIndices[j]];// nodes only affect nodes on their level
if(node1.level===node2.level){const theseNodesDistance=nodeDistance+this.overlapAvoidanceFactor*((node1.shape.radius||0)/2+(node2.shape.radius||0)/2);const dx=node2.x-node1.x;const dy=node2.y-node1.y;const distance=Math.sqrt(dx*dx+dy*dy);const steepness=0.05;let repulsingForce;if(distance<theseNodesDistance){repulsingForce=-Math.pow(steepness*distance,2)+Math.pow(steepness*theseNodesDistance,2);}else {repulsingForce=0;}// normalize force with
if(distance!==0){repulsingForce=repulsingForce/distance;}const fx=dx*repulsingForce;const fy=dy*repulsingForce;forces[node1.id].x-=fx;forces[node1.id].y-=fy;forces[node2.id].x+=fx;forces[node2.id].y+=fy;}}}}}/**
 * Spring Solver
 */class SpringSolver{/**
   * @param {object} body
   * @param {{physicsNodeIndices: Array, physicsEdgeIndices: Array, forces: {}, velocities: {}}} physicsBody
   * @param {object} options
   */constructor(body,physicsBody,options){this.body=body;this.physicsBody=physicsBody;this.setOptions(options);}/**
   *
   * @param {object} options
   */setOptions(options){this.options=options;}/**
   * This function calculates the springforces on the nodes, accounting for the support nodes.
   * @private
   */solve(){let edgeLength,edge;const edgeIndices=this.physicsBody.physicsEdgeIndices;const edges=this.body.edges;let node1,node2,node3;// forces caused by the edges, modelled as springs
for(let i=0;i<edgeIndices.length;i++){edge=edges[edgeIndices[i]];if(edge.connected===true&&edge.toId!==edge.fromId){// only calculate forces if nodes are in the same sector
if(this.body.nodes[edge.toId]!==undefined&&this.body.nodes[edge.fromId]!==undefined){if(edge.edgeType.via!==undefined){edgeLength=edge.options.length===undefined?this.options.springLength:edge.options.length;node1=edge.to;node2=edge.edgeType.via;node3=edge.from;this._calculateSpringForce(node1,node2,0.5*edgeLength);this._calculateSpringForce(node2,node3,0.5*edgeLength);}else {// the * 1.5 is here so the edge looks as large as a smooth edge. It does not initially because the smooth edges use
// the support nodes which exert a repulsive force on the to and from nodes, making the edge appear larger.
edgeLength=edge.options.length===undefined?this.options.springLength*1.5:edge.options.length;this._calculateSpringForce(edge.from,edge.to,edgeLength);}}}}}/**
   * This is the code actually performing the calculation for the function above.
   * @param {Node} node1
   * @param {Node} node2
   * @param {number} edgeLength
   * @private
   */_calculateSpringForce(node1,node2,edgeLength){const dx=node1.x-node2.x;const dy=node1.y-node2.y;const distance=Math.max(Math.sqrt(dx*dx+dy*dy),0.01);// the 1/distance is so the fx and fy can be calculated without sine or cosine.
const springForce=this.options.springConstant*(edgeLength-distance)/distance;const fx=dx*springForce;const fy=dy*springForce;// handle the case where one node is not part of the physcis
if(this.physicsBody.forces[node1.id]!==undefined){this.physicsBody.forces[node1.id].x+=fx;this.physicsBody.forces[node1.id].y+=fy;}if(this.physicsBody.forces[node2.id]!==undefined){this.physicsBody.forces[node2.id].x-=fx;this.physicsBody.forces[node2.id].y-=fy;}}}/**
 * Hierarchical Spring Solver
 */class HierarchicalSpringSolver{/**
   * @param {object} body
   * @param {{physicsNodeIndices: Array, physicsEdgeIndices: Array, forces: {}, velocities: {}}} physicsBody
   * @param {object} options
   */constructor(body,physicsBody,options){this.body=body;this.physicsBody=physicsBody;this.setOptions(options);}/**
   *
   * @param {object} options
   */setOptions(options){this.options=options;}/**
   * This function calculates the springforces on the nodes, accounting for the support nodes.
   * @private
   */solve(){let edgeLength,edge;let dx,dy,fx,fy,springForce,distance;const edges=this.body.edges;const factor=0.5;const edgeIndices=this.physicsBody.physicsEdgeIndices;const nodeIndices=this.physicsBody.physicsNodeIndices;const forces=this.physicsBody.forces;// initialize the spring force counters
for(let i=0;i<nodeIndices.length;i++){const nodeId=nodeIndices[i];forces[nodeId].springFx=0;forces[nodeId].springFy=0;}// forces caused by the edges, modelled as springs
for(let i=0;i<edgeIndices.length;i++){edge=edges[edgeIndices[i]];if(edge.connected===true){edgeLength=edge.options.length===undefined?this.options.springLength:edge.options.length;dx=edge.from.x-edge.to.x;dy=edge.from.y-edge.to.y;distance=Math.sqrt(dx*dx+dy*dy);distance=distance===0?0.01:distance;// the 1/distance is so the fx and fy can be calculated without sine or cosine.
springForce=this.options.springConstant*(edgeLength-distance)/distance;fx=dx*springForce;fy=dy*springForce;if(edge.to.level!=edge.from.level){if(forces[edge.toId]!==undefined){forces[edge.toId].springFx-=fx;forces[edge.toId].springFy-=fy;}if(forces[edge.fromId]!==undefined){forces[edge.fromId].springFx+=fx;forces[edge.fromId].springFy+=fy;}}else {if(forces[edge.toId]!==undefined){forces[edge.toId].x-=factor*fx;forces[edge.toId].y-=factor*fy;}if(forces[edge.fromId]!==undefined){forces[edge.fromId].x+=factor*fx;forces[edge.fromId].y+=factor*fy;}}}}// normalize spring forces
springForce=1;let springFx,springFy;for(let i=0;i<nodeIndices.length;i++){const nodeId=nodeIndices[i];springFx=Math.min(springForce,Math.max(-springForce,forces[nodeId].springFx));springFy=Math.min(springForce,Math.max(-springForce,forces[nodeId].springFy));forces[nodeId].x+=springFx;forces[nodeId].y+=springFy;}// retain energy balance
let totalFx=0;let totalFy=0;for(let i=0;i<nodeIndices.length;i++){const nodeId=nodeIndices[i];totalFx+=forces[nodeId].x;totalFy+=forces[nodeId].y;}const correctionFx=totalFx/nodeIndices.length;const correctionFy=totalFy/nodeIndices.length;for(let i=0;i<nodeIndices.length;i++){const nodeId=nodeIndices[i];forces[nodeId].x-=correctionFx;forces[nodeId].y-=correctionFy;}}}/**
 * Central Gravity Solver
 */class CentralGravitySolver{/**
   * @param {object} body
   * @param {{physicsNodeIndices: Array, physicsEdgeIndices: Array, forces: {}, velocities: {}}} physicsBody
   * @param {object} options
   */constructor(body,physicsBody,options){this.body=body;this.physicsBody=physicsBody;this.setOptions(options);}/**
   *
   * @param {object} options
   */setOptions(options){this.options=options;}/**
   * Calculates forces for each node
   */solve(){let dx,dy,distance,node;const nodes=this.body.nodes;const nodeIndices=this.physicsBody.physicsNodeIndices;const forces=this.physicsBody.forces;for(let i=0;i<nodeIndices.length;i++){const nodeId=nodeIndices[i];node=nodes[nodeId];dx=-node.x;dy=-node.y;distance=Math.sqrt(dx*dx+dy*dy);this._calculateForces(distance,dx,dy,forces,node);}}/**
   * Calculate the forces based on the distance.
   * @param {number} distance
   * @param {number} dx
   * @param {number} dy
   * @param {Object<Node.id, vis.Node>} forces
   * @param {Node} node
   * @private
   */_calculateForces(distance,dx,dy,forces,node){const gravityForce=distance===0?0:this.options.centralGravity/distance;forces[node.id].x=dx*gravityForce;forces[node.id].y=dy*gravityForce;}}/**
 * @augments BarnesHutSolver
 */class ForceAtlas2BasedRepulsionSolver extends BarnesHutSolver{/**
   * @param {object} body
   * @param {{physicsNodeIndices: Array, physicsEdgeIndices: Array, forces: {}, velocities: {}}} physicsBody
   * @param {object} options
   */constructor(body,physicsBody,options){super(body,physicsBody,options);this._rng=Alea("FORCE ATLAS 2 BASED REPULSION SOLVER");}/**
   * Calculate the forces based on the distance.
   * @param {number} distance
   * @param {number} dx
   * @param {number} dy
   * @param {Node} node
   * @param {object} parentBranch
   * @private
   */_calculateForces(distance,dx,dy,node,parentBranch){if(distance===0){distance=0.1*this._rng();dx=distance;}if(this.overlapAvoidanceFactor<1&&node.shape.radius){distance=Math.max(0.1+this.overlapAvoidanceFactor*node.shape.radius,distance-node.shape.radius);}const degree=node.edges.length+1;// the dividing by the distance cubed instead of squared allows us to get the fx and fy components without sines and cosines
// it is shorthand for gravityforce with distance squared and fx = dx/distance * gravityForce
const gravityForce=this.options.gravitationalConstant*parentBranch.mass*node.options.mass*degree/Math.pow(distance,2);const fx=dx*gravityForce;const fy=dy*gravityForce;this.physicsBody.forces[node.id].x+=fx;this.physicsBody.forces[node.id].y+=fy;}}/**
 * @augments CentralGravitySolver
 */class ForceAtlas2BasedCentralGravitySolver extends CentralGravitySolver{/**
   * Calculate the forces based on the distance.
   * @param {number} distance
   * @param {number} dx
   * @param {number} dy
   * @param {Object<Node.id, Node>} forces
   * @param {Node} node
   * @private
   */_calculateForces(distance,dx,dy,forces,node){if(distance>0){const degree=node.edges.length+1;const gravityForce=this.options.centralGravity*degree*node.options.mass;forces[node.id].x=dx*gravityForce;forces[node.id].y=dy*gravityForce;}}}/**
 * The physics engine
 */class PhysicsEngine{/**
   * @param {object} body
   */constructor(body){this.body=body;this.physicsBody={physicsNodeIndices:[],physicsEdgeIndices:[],forces:{},velocities:{}};this.physicsEnabled=true;this.simulationInterval=1000/60;this.requiresTimeout=true;this.previousStates={};this.referenceState={};this.freezeCache={};this.renderTimer=undefined;// parameters for the adaptive timestep
this.adaptiveTimestep=false;this.adaptiveTimestepEnabled=false;this.adaptiveCounter=0;this.adaptiveInterval=3;this.stabilized=false;this.startedStabilization=false;this.stabilizationIterations=0;this.ready=false;// will be set to true if the stabilize
// default options
this.options={};this.defaultOptions={enabled:true,barnesHut:{theta:0.5,gravitationalConstant:-2e3,centralGravity:0.3,springLength:95,springConstant:0.04,damping:0.09,avoidOverlap:0},forceAtlas2Based:{theta:0.5,gravitationalConstant:-50,centralGravity:0.01,springConstant:0.08,springLength:100,damping:0.4,avoidOverlap:0},repulsion:{centralGravity:0.2,springLength:200,springConstant:0.05,nodeDistance:100,damping:0.09,avoidOverlap:0},hierarchicalRepulsion:{centralGravity:0.0,springLength:100,springConstant:0.01,nodeDistance:120,damping:0.09},maxVelocity:50,minVelocity:0.75,// px/s
solver:"barnesHut",stabilization:{enabled:true,iterations:1000,// maximum number of iteration to stabilize
updateInterval:50,onlyDynamicEdges:false,fit:true},timestep:0.5,adaptiveTimestep:true,wind:{x:0,y:0}};_Object$assign(this.options,this.defaultOptions);this.timestep=0.5;this.layoutFailed=false;this.bindEventListeners();}/**
   * Binds event listeners
   */bindEventListeners(){this.body.emitter.on("initPhysics",()=>{this.initPhysics();});this.body.emitter.on("_layoutFailed",()=>{this.layoutFailed=true;});this.body.emitter.on("resetPhysics",()=>{this.stopSimulation();this.ready=false;});this.body.emitter.on("disablePhysics",()=>{this.physicsEnabled=false;this.stopSimulation();});this.body.emitter.on("restorePhysics",()=>{this.setOptions(this.options);if(this.ready===true){this.startSimulation();}});this.body.emitter.on("startSimulation",()=>{if(this.ready===true){this.startSimulation();}});this.body.emitter.on("stopSimulation",()=>{this.stopSimulation();});this.body.emitter.on("destroy",()=>{this.stopSimulation(false);this.body.emitter.off();});this.body.emitter.on("_dataChanged",()=>{// Nodes and/or edges have been added or removed, update shortcut lists.
this.updatePhysicsData();});// debug: show forces
// this.body.emitter.on("afterDrawing", (ctx) => {this._drawForces(ctx);});
}/**
   * set the physics options
   * @param {object} options
   */setOptions(options){if(options!==undefined){if(options===false){this.options.enabled=false;this.physicsEnabled=false;this.stopSimulation();}else if(options===true){this.options.enabled=true;this.physicsEnabled=true;this.startSimulation();}else {this.physicsEnabled=true;selectiveNotDeepExtend(["stabilization"],this.options,options);mergeOptions(this.options,options,"stabilization");if(options.enabled===undefined){this.options.enabled=true;}if(this.options.enabled===false){this.physicsEnabled=false;this.stopSimulation();}const wind=this.options.wind;if(wind&&typeof wind!=="function"){if(typeof wind.x!=="number"||_Number$isNaN(wind.x)){wind.x=0;}if(typeof wind.y!=="number"||_Number$isNaN(wind.y)){wind.y=0;}}// set the timestep
this.timestep=this.options.timestep;}}this.init();}/**
   * configure the engine.
   */init(){let options;if(this.options.solver==="forceAtlas2Based"){options=this.options.forceAtlas2Based;this.nodesSolver=new ForceAtlas2BasedRepulsionSolver(this.body,this.physicsBody,options);this.edgesSolver=new SpringSolver(this.body,this.physicsBody,options);this.gravitySolver=new ForceAtlas2BasedCentralGravitySolver(this.body,this.physicsBody,options);}else if(this.options.solver==="repulsion"){options=this.options.repulsion;this.nodesSolver=new RepulsionSolver(this.body,this.physicsBody,options);this.edgesSolver=new SpringSolver(this.body,this.physicsBody,options);this.gravitySolver=new CentralGravitySolver(this.body,this.physicsBody,options);}else if(this.options.solver==="hierarchicalRepulsion"){options=this.options.hierarchicalRepulsion;this.nodesSolver=new HierarchicalRepulsionSolver(this.body,this.physicsBody,options);this.edgesSolver=new HierarchicalSpringSolver(this.body,this.physicsBody,options);this.gravitySolver=new CentralGravitySolver(this.body,this.physicsBody,options);}else {// barnesHut
options=this.options.barnesHut;this.nodesSolver=new BarnesHutSolver(this.body,this.physicsBody,options);this.edgesSolver=new SpringSolver(this.body,this.physicsBody,options);this.gravitySolver=new CentralGravitySolver(this.body,this.physicsBody,options);}this.modelOptions=options;}/**
   * initialize the engine
   */initPhysics(){if(this.physicsEnabled===true&&this.options.enabled===true){if(this.options.stabilization.enabled===true){this.stabilize();}else {this.stabilized=false;this.ready=true;this.body.emitter.emit("fit",{},this.layoutFailed);// if the layout failed, we use the approximation for the zoom
this.startSimulation();}}else {this.ready=true;this.body.emitter.emit("fit");}}/**
   * Start the simulation
   */startSimulation(){if(this.physicsEnabled===true&&this.options.enabled===true){this.stabilized=false;// when visible, adaptivity is disabled.
this.adaptiveTimestep=false;// this sets the width of all nodes initially which could be required for the avoidOverlap
this.body.emitter.emit("_resizeNodes");if(this.viewFunction===undefined){var _context;this.viewFunction=_bindInstanceProperty(_context=this.simulationStep).call(_context,this);this.body.emitter.on("initRedraw",this.viewFunction);this.body.emitter.emit("_startRendering");}}else {this.body.emitter.emit("_redraw");}}/**
   * Stop the simulation, force stabilization.
   * @param {boolean} [emit]
   */stopSimulation(){let emit=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;this.stabilized=true;if(emit===true){this._emitStabilized();}if(this.viewFunction!==undefined){this.body.emitter.off("initRedraw",this.viewFunction);this.viewFunction=undefined;if(emit===true){this.body.emitter.emit("_stopRendering");}}}/**
   * The viewFunction inserts this step into each render loop. It calls the physics tick and handles the cleanup at stabilized.
   *
   */simulationStep(){// check if the physics have settled
const startTime=_Date$now();this.physicsTick();const physicsTime=_Date$now()-startTime;// run double speed if it is a little graph
if((physicsTime<0.4*this.simulationInterval||this.runDoubleSpeed===true)&&this.stabilized===false){this.physicsTick();// this makes sure there is no jitter. The decision is taken once to run it at double speed.
this.runDoubleSpeed=true;}if(this.stabilized===true){this.stopSimulation();}}/**
   * trigger the stabilized event.
   * @param {number} [amountOfIterations]
   * @private
   */_emitStabilized(){let amountOfIterations=arguments.length>0&&arguments[0]!==undefined?arguments[0]:this.stabilizationIterations;if(this.stabilizationIterations>1||this.startedStabilization===true){_setTimeout(()=>{this.body.emitter.emit("stabilized",{iterations:amountOfIterations});this.startedStabilization=false;this.stabilizationIterations=0;},0);}}/**
   * Calculate the forces for one physics iteration and move the nodes.
   * @private
   */physicsStep(){this.gravitySolver.solve();this.nodesSolver.solve();this.edgesSolver.solve();this.moveNodes();}/**
   * Make dynamic adjustments to the timestep, based on current state.
   *
   * Helper function for physicsTick().
   * @private
   */adjustTimeStep(){const factor=1.2;// Factor for increasing the timestep on success.
// we compare the two steps. if it is acceptable we double the step.
if(this._evaluateStepQuality()===true){this.timestep=factor*this.timestep;}else {// if not, we decrease the step to a minimum of the options timestep.
// if the decreased timestep is smaller than the options step, we do not reset the counter
// we assume that the options timestep is stable enough.
if(this.timestep/factor<this.options.timestep){this.timestep=this.options.timestep;}else {// if the timestep was larger than 2 times the option one we check the adaptivity again to ensure
// that large instabilities do not form.
this.adaptiveCounter=-1;// check again next iteration
this.timestep=Math.max(this.options.timestep,this.timestep/factor);}}}/**
   * A single simulation step (or 'tick') in the physics simulation
   * @private
   */physicsTick(){this._startStabilizing();// this ensures that there is no start event when the network is already stable.
if(this.stabilized===true)return;// adaptivity means the timestep adapts to the situation, only applicable for stabilization
if(this.adaptiveTimestep===true&&this.adaptiveTimestepEnabled===true){// timestep remains stable for "interval" iterations.
const doAdaptive=this.adaptiveCounter%this.adaptiveInterval===0;if(doAdaptive){// first the big step and revert.
this.timestep=2*this.timestep;this.physicsStep();this.revert();// saves the reference state
// now the normal step. Since this is the last step, it is the more stable one and we will take this.
this.timestep=0.5*this.timestep;// since it's half the step, we do it twice.
this.physicsStep();this.physicsStep();this.adjustTimeStep();}else {this.physicsStep();// normal step, keeping timestep constant
}this.adaptiveCounter+=1;}else {// case for the static timestep, we reset it to the one in options and take a normal step.
this.timestep=this.options.timestep;this.physicsStep();}if(this.stabilized===true)this.revert();this.stabilizationIterations++;}/**
   * Nodes and edges can have the physics toggles on or off. A collection of indices is created here so we can skip the check all the time.
   * @private
   */updatePhysicsData(){this.physicsBody.forces={};this.physicsBody.physicsNodeIndices=[];this.physicsBody.physicsEdgeIndices=[];const nodes=this.body.nodes;const edges=this.body.edges;// get node indices for physics
for(const nodeId in nodes){if(Object.prototype.hasOwnProperty.call(nodes,nodeId)){if(nodes[nodeId].options.physics===true){this.physicsBody.physicsNodeIndices.push(nodes[nodeId].id);}}}// get edge indices for physics
for(const edgeId in edges){if(Object.prototype.hasOwnProperty.call(edges,edgeId)){if(edges[edgeId].options.physics===true){this.physicsBody.physicsEdgeIndices.push(edges[edgeId].id);}}}// get the velocity and the forces vector
for(let i=0;i<this.physicsBody.physicsNodeIndices.length;i++){const nodeId=this.physicsBody.physicsNodeIndices[i];this.physicsBody.forces[nodeId]={x:0,y:0};// forces can be reset because they are recalculated. Velocities have to persist.
if(this.physicsBody.velocities[nodeId]===undefined){this.physicsBody.velocities[nodeId]={x:0,y:0};}}// clean deleted nodes from the velocity vector
for(const nodeId in this.physicsBody.velocities){if(nodes[nodeId]===undefined){delete this.physicsBody.velocities[nodeId];}}}/**
   * Revert the simulation one step. This is done so after stabilization, every new start of the simulation will also say stabilized.
   */revert(){const nodeIds=_Object$keys(this.previousStates);const nodes=this.body.nodes;const velocities=this.physicsBody.velocities;this.referenceState={};for(let i=0;i<nodeIds.length;i++){const nodeId=nodeIds[i];if(nodes[nodeId]!==undefined){if(nodes[nodeId].options.physics===true){this.referenceState[nodeId]={positions:{x:nodes[nodeId].x,y:nodes[nodeId].y}};velocities[nodeId].x=this.previousStates[nodeId].vx;velocities[nodeId].y=this.previousStates[nodeId].vy;nodes[nodeId].x=this.previousStates[nodeId].x;nodes[nodeId].y=this.previousStates[nodeId].y;}}else {delete this.previousStates[nodeId];}}}/**
   * This compares the reference state to the current state
   * @returns {boolean}
   * @private
   */_evaluateStepQuality(){let dx,dy,dpos;const nodes=this.body.nodes;const reference=this.referenceState;const posThreshold=0.3;for(const nodeId in this.referenceState){if(Object.prototype.hasOwnProperty.call(this.referenceState,nodeId)&&nodes[nodeId]!==undefined){dx=nodes[nodeId].x-reference[nodeId].positions.x;dy=nodes[nodeId].y-reference[nodeId].positions.y;dpos=Math.sqrt(Math.pow(dx,2)+Math.pow(dy,2));if(dpos>posThreshold){return false;}}}return true;}/**
   * move the nodes one timestep and check if they are stabilized
   */moveNodes(){const nodeIndices=this.physicsBody.physicsNodeIndices;let maxNodeVelocity=0;let averageNodeVelocity=0;// the velocity threshold (energy in the system) for the adaptivity toggle
const velocityAdaptiveThreshold=5;for(let i=0;i<nodeIndices.length;i++){const nodeId=nodeIndices[i];const nodeVelocity=this._performStep(nodeId);// stabilized is true if stabilized is true and velocity is smaller than vmin --> all nodes must be stabilized
maxNodeVelocity=Math.max(maxNodeVelocity,nodeVelocity);averageNodeVelocity+=nodeVelocity;}// evaluating the stabilized and adaptiveTimestepEnabled conditions
this.adaptiveTimestepEnabled=averageNodeVelocity/nodeIndices.length<velocityAdaptiveThreshold;this.stabilized=maxNodeVelocity<this.options.minVelocity;}/**
   * Calculate new velocity for a coordinate direction
   * @param {number} v  velocity for current coordinate
   * @param {number} f  regular force for current coordinate
   * @param {number} m  mass of current node
   * @returns {number} new velocity for current coordinate
   * @private
   */calculateComponentVelocity(v,f,m){const df=this.modelOptions.damping*v;// damping force
const a=(f-df)/m;// acceleration
v+=a*this.timestep;// Put a limit on the velocities if it is really high
const maxV=this.options.maxVelocity||1e9;if(Math.abs(v)>maxV){v=v>0?maxV:-maxV;}return v;}/**
   * Perform the actual step
   * @param {Node.id} nodeId
   * @returns {number} the new velocity of given node
   * @private
   */_performStep(nodeId){const node=this.body.nodes[nodeId];const force=this.physicsBody.forces[nodeId];if(this.options.wind){if(typeof this.options.wind==="function"){const wind=this.options.wind(nodeId);if(wind&&typeof wind==="object"){if(typeof wind.x==="number"&&!_Number$isNaN(wind.x)){force.x+=wind.x;}if(typeof wind.y==="number"&&!_Number$isNaN(wind.y)){force.y+=wind.y;}}}else {force.x+=this.options.wind.x;force.y+=this.options.wind.y;}}const velocity=this.physicsBody.velocities[nodeId];// store the state so we can revert
this.previousStates[nodeId]={x:node.x,y:node.y,vx:velocity.x,vy:velocity.y};if(node.options.fixed.x===false){velocity.x=this.calculateComponentVelocity(velocity.x,force.x,node.options.mass);node.x+=velocity.x*this.timestep;}else {force.x=0;velocity.x=0;}if(node.options.fixed.y===false){velocity.y=this.calculateComponentVelocity(velocity.y,force.y,node.options.mass);node.y+=velocity.y*this.timestep;}else {force.y=0;velocity.y=0;}const totalVelocity=Math.sqrt(Math.pow(velocity.x,2)+Math.pow(velocity.y,2));return totalVelocity;}/**
   * When initializing and stabilizing, we can freeze nodes with a predefined position.
   * This greatly speeds up stabilization because only the supportnodes for the smoothCurves have to settle.
   * @private
   */_freezeNodes(){const nodes=this.body.nodes;for(const id in nodes){if(Object.prototype.hasOwnProperty.call(nodes,id)){if(nodes[id].x&&nodes[id].y){const fixed=nodes[id].options.fixed;this.freezeCache[id]={x:fixed.x,y:fixed.y};fixed.x=true;fixed.y=true;}}}}/**
   * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
   * @private
   */_restoreFrozenNodes(){const nodes=this.body.nodes;for(const id in nodes){if(Object.prototype.hasOwnProperty.call(nodes,id)){if(this.freezeCache[id]!==undefined){nodes[id].options.fixed.x=this.freezeCache[id].x;nodes[id].options.fixed.y=this.freezeCache[id].y;}}}this.freezeCache={};}/**
   * Find a stable position for all nodes
   * @param {number} [iterations]
   */stabilize(){let iterations=arguments.length>0&&arguments[0]!==undefined?arguments[0]:this.options.stabilization.iterations;if(typeof iterations!=="number"){iterations=this.options.stabilization.iterations;console.error("The stabilize method needs a numeric amount of iterations. Switching to default: ",iterations);}if(this.physicsBody.physicsNodeIndices.length===0){this.ready=true;return;}// enable adaptive timesteps
this.adaptiveTimestep=this.options.adaptiveTimestep;// this sets the width of all nodes initially which could be required for the avoidOverlap
this.body.emitter.emit("_resizeNodes");this.stopSimulation();// stop the render loop
this.stabilized=false;// block redraw requests
this.body.emitter.emit("_blockRedraw");this.targetIterations=iterations;// start the stabilization
if(this.options.stabilization.onlyDynamicEdges===true){this._freezeNodes();}this.stabilizationIterations=0;_setTimeout(()=>this._stabilizationBatch(),0);}/**
   * If not already stabilizing, start it and emit a start event.
   * @returns {boolean} true if stabilization started with this call
   * @private
   */_startStabilizing(){if(this.startedStabilization===true)return false;this.body.emitter.emit("startStabilizing");this.startedStabilization=true;return true;}/**
   * One batch of stabilization
   * @private
   */_stabilizationBatch(){const running=()=>this.stabilized===false&&this.stabilizationIterations<this.targetIterations;const sendProgress=()=>{this.body.emitter.emit("stabilizationProgress",{iterations:this.stabilizationIterations,total:this.targetIterations});};if(this._startStabilizing()){sendProgress();// Ensure that there is at least one start event.
}let count=0;while(running()&&count<this.options.stabilization.updateInterval){this.physicsTick();count++;}sendProgress();if(running()){var _context2;_setTimeout(_bindInstanceProperty(_context2=this._stabilizationBatch).call(_context2,this),0);}else {this._finalizeStabilization();}}/**
   * Wrap up the stabilization, fit and emit the events.
   * @private
   */_finalizeStabilization(){this.body.emitter.emit("_allowRedraw");if(this.options.stabilization.fit===true){this.body.emitter.emit("fit");}if(this.options.stabilization.onlyDynamicEdges===true){this._restoreFrozenNodes();}this.body.emitter.emit("stabilizationIterationsDone");this.body.emitter.emit("_requestRedraw");if(this.stabilized===true){this._emitStabilized();}else {this.startSimulation();}this.ready=true;}//---------------------------  DEBUGGING BELOW  ---------------------------//
/**
   * Debug function that display arrows for the forces currently active in the network.
   *
   * Use this when debugging only.
   * @param {CanvasRenderingContext2D} ctx
   * @private
   */_drawForces(ctx){for(let i=0;i<this.physicsBody.physicsNodeIndices.length;i++){const index=this.physicsBody.physicsNodeIndices[i];const node=this.body.nodes[index];const force=this.physicsBody.forces[index];const factor=20;const colorFactor=0.03;const forceSize=Math.sqrt(Math.pow(force.x,2)+Math.pow(force.x,2));const size=Math.min(Math.max(5,forceSize),15);const arrowSize=3*size;const color=HSVToHex((180-Math.min(1,Math.max(0,colorFactor*forceSize))*180)/360,1,1);const point={x:node.x+factor*force.x,y:node.y+factor*force.y};ctx.lineWidth=size;ctx.strokeStyle=color;ctx.beginPath();ctx.moveTo(node.x,node.y);ctx.lineTo(point.x,point.y);ctx.stroke();const angle=Math.atan2(force.y,force.x);ctx.fillStyle=color;EndPoints.draw(ctx,{type:"arrow",point:point,angle:angle,length:arrowSize});_fillInstanceProperty(ctx).call(ctx);}}}/**
 * Utility Class
 */class NetworkUtil{/**
   * Find the center position of the network considering the bounding boxes
   * @param {Array.<Node>} allNodes
   * @param {Array.<Node>} [specificNodes]
   * @returns {{minX: number, maxX: number, minY: number, maxY: number}}
   * @static
   */static getRange(allNodes){let specificNodes=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[];let minY=1e9,maxY=-1e9,minX=1e9,maxX=-1e9,node;if(specificNodes.length>0){for(let i=0;i<specificNodes.length;i++){node=allNodes[specificNodes[i]];if(minX>node.shape.boundingBox.left){minX=node.shape.boundingBox.left;}if(maxX<node.shape.boundingBox.right){maxX=node.shape.boundingBox.right;}if(minY>node.shape.boundingBox.top){minY=node.shape.boundingBox.top;}// top is negative, bottom is positive
if(maxY<node.shape.boundingBox.bottom){maxY=node.shape.boundingBox.bottom;}// top is negative, bottom is positive
}}if(minX===1e9&&maxX===-1e9&&minY===1e9&&maxY===-1e9){minY=0;maxY=0;minX=0;maxX=0;}return {minX:minX,maxX:maxX,minY:minY,maxY:maxY};}/**
   * Find the center position of the network
   * @param {Array.<Node>} allNodes
   * @param {Array.<Node>} [specificNodes]
   * @returns {{minX: number, maxX: number, minY: number, maxY: number}}
   * @static
   */static getRangeCore(allNodes){let specificNodes=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[];let minY=1e9,maxY=-1e9,minX=1e9,maxX=-1e9,node;if(specificNodes.length>0){for(let i=0;i<specificNodes.length;i++){node=allNodes[specificNodes[i]];if(minX>node.x){minX=node.x;}if(maxX<node.x){maxX=node.x;}if(minY>node.y){minY=node.y;}// top is negative, bottom is positive
if(maxY<node.y){maxY=node.y;}// top is negative, bottom is positive
}}if(minX===1e9&&maxX===-1e9&&minY===1e9&&maxY===-1e9){minY=0;maxY=0;minX=0;maxX=0;}return {minX:minX,maxX:maxX,minY:minY,maxY:maxY};}/**
   * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
   * @returns {{x: number, y: number}}
   * @static
   */static findCenter(range){return {x:0.5*(range.maxX+range.minX),y:0.5*(range.maxY+range.minY)};}/**
   * This returns a clone of the options or options of the edge or node to be used for construction of new edges or check functions for new nodes.
   * @param {vis.Item} item
   * @param {'node'|undefined} type
   * @returns {{}}
   * @static
   */static cloneOptions(item,type){const clonedOptions={};if(type===undefined||type==="node"){deepExtend(clonedOptions,item.options,true);clonedOptions.x=item.x;clonedOptions.y=item.y;clonedOptions.amountOfConnections=item.edges.length;}else {deepExtend(clonedOptions,item.options,true);}return clonedOptions;}}/**
 * A Cluster is a special Node that allows a group of Nodes positioned closely together
 * to be represented by a single Cluster Node.
 * @augments Node
 */class Cluster extends Node$1{/**
   * @param {object} options
   * @param {object} body
   * @param {Array.<HTMLImageElement>}imagelist
   * @param {Array} grouplist
   * @param {object} globalOptions
   * @param {object} defaultOptions     Global default options for nodes
   */constructor(options,body,imagelist,grouplist,globalOptions,defaultOptions){super(options,body,imagelist,grouplist,globalOptions,defaultOptions);this.isCluster=true;this.containedNodes={};this.containedEdges={};}/**
   * Transfer child cluster data to current and disconnect the child cluster.
   *
   * Please consult the header comment in 'Clustering.js' for the fields set here.
   * @param {string|number} childClusterId  id of child cluster to open
   */_openChildCluster(childClusterId){const childCluster=this.body.nodes[childClusterId];if(this.containedNodes[childClusterId]===undefined){throw new Error("node with id: "+childClusterId+" not in current cluster");}if(!childCluster.isCluster){throw new Error("node with id: "+childClusterId+" is not a cluster");}// Disconnect child cluster from current cluster
delete this.containedNodes[childClusterId];forEach(childCluster.edges,edge=>{delete this.containedEdges[edge.id];});// Transfer nodes and edges
forEach(childCluster.containedNodes,(node,nodeId)=>{this.containedNodes[nodeId]=node;});childCluster.containedNodes={};forEach(childCluster.containedEdges,(edge,edgeId)=>{this.containedEdges[edgeId]=edge;});childCluster.containedEdges={};// Transfer edges within cluster edges which are clustered
forEach(childCluster.edges,clusterEdge=>{forEach(this.edges,parentClusterEdge=>{var _context,_context2;// Assumption: a clustered edge can only be present in a single clustering edge
// Not tested here
const index=_indexOfInstanceProperty(_context=parentClusterEdge.clusteringEdgeReplacingIds).call(_context,clusterEdge.id);if(index===-1)return;forEach(clusterEdge.clusteringEdgeReplacingIds,srcId=>{parentClusterEdge.clusteringEdgeReplacingIds.push(srcId);// Maintain correct bookkeeping for transferred edge
this.body.edges[srcId].edgeReplacedById=parentClusterEdge.id;});// Remove cluster edge from parent cluster edge
_spliceInstanceProperty(_context2=parentClusterEdge.clusteringEdgeReplacingIds).call(_context2,index,1);});});childCluster.edges=[];}}/**
 * The clustering engine
 */class ClusterEngine{/**
   * @param {object} body
   */constructor(body){this.body=body;this.clusteredNodes={};// key: node id, value: { clusterId: <id of cluster>, node: <node instance>}
this.clusteredEdges={};// key: edge id, value: restore information for given edge
this.options={};this.defaultOptions={};_Object$assign(this.options,this.defaultOptions);this.body.emitter.on("_resetData",()=>{this.clusteredNodes={};this.clusteredEdges={};});}/**
   *
   * @param {number} hubsize
   * @param {object} options
   */clusterByHubsize(hubsize,options){if(hubsize===undefined){hubsize=this._getHubSize();}else if(typeof hubsize==="object"){options=this._checkOptions(hubsize);hubsize=this._getHubSize();}const nodesToCluster=[];for(let i=0;i<this.body.nodeIndices.length;i++){const node=this.body.nodes[this.body.nodeIndices[i]];if(node.edges.length>=hubsize){nodesToCluster.push(node.id);}}for(let i=0;i<nodesToCluster.length;i++){this.clusterByConnection(nodesToCluster[i],options,true);}this.body.emitter.emit("_dataChanged");}/**
   * loop over all nodes, check if they adhere to the condition and cluster if needed.
   * @param {object} options
   * @param {boolean} [refreshData]
   */cluster(){let options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};let refreshData=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;if(options.joinCondition===undefined){throw new Error("Cannot call clusterByNodeData without a joinCondition function in the options.");}// check if the options object is fine, append if needed
options=this._checkOptions(options);const childNodesObj={};const childEdgesObj={};// collect the nodes that will be in the cluster
forEach(this.body.nodes,(node,nodeId)=>{if(node.options&&options.joinCondition(node.options)===true){childNodesObj[nodeId]=node;// collect the edges that will be in the cluster
forEach(node.edges,edge=>{if(this.clusteredEdges[edge.id]===undefined){childEdgesObj[edge.id]=edge;}});}});this._cluster(childNodesObj,childEdgesObj,options,refreshData);}/**
   * Cluster all nodes in the network that have only X edges
   * @param {number} edgeCount
   * @param {object} options
   * @param {boolean} [refreshData]
   */clusterByEdgeCount(edgeCount,options){let refreshData=arguments.length>2&&arguments[2]!==undefined?arguments[2]:true;options=this._checkOptions(options);const clusters=[];const usedNodes={};let edge,edges,relevantEdgeCount;// collect the nodes that will be in the cluster
for(let i=0;i<this.body.nodeIndices.length;i++){const childNodesObj={};const childEdgesObj={};const nodeId=this.body.nodeIndices[i];const node=this.body.nodes[nodeId];// if this node is already used in another cluster this session, we do not have to re-evaluate it.
if(usedNodes[nodeId]===undefined){relevantEdgeCount=0;edges=[];for(let j=0;j<node.edges.length;j++){edge=node.edges[j];if(this.clusteredEdges[edge.id]===undefined){if(edge.toId!==edge.fromId){relevantEdgeCount++;}edges.push(edge);}}// this node qualifies, we collect its neighbours to start the clustering process.
if(relevantEdgeCount===edgeCount){const checkJoinCondition=function(node){if(options.joinCondition===undefined||options.joinCondition===null){return true;}const clonedOptions=NetworkUtil.cloneOptions(node);return options.joinCondition(clonedOptions);};let gatheringSuccessful=true;for(let j=0;j<edges.length;j++){edge=edges[j];const childNodeId=this._getConnectedId(edge,nodeId);// add the nodes to the list by the join condition.
if(checkJoinCondition(node)){childEdgesObj[edge.id]=edge;childNodesObj[nodeId]=node;childNodesObj[childNodeId]=this.body.nodes[childNodeId];usedNodes[nodeId]=true;}else {// this node does not qualify after all.
gatheringSuccessful=false;break;}}// add to the cluster queue
if(_Object$keys(childNodesObj).length>0&&_Object$keys(childEdgesObj).length>0&&gatheringSuccessful===true){/**
             * Search for cluster data that contains any of the node id's
             * @returns {boolean} true if no joinCondition, otherwise return value of joinCondition
             */const findClusterData=function(){for(let n=0;n<clusters.length;++n){// Search for a cluster containing any of the node id's
for(const m in childNodesObj){if(clusters[n].nodes[m]!==undefined){return clusters[n];}}}return undefined;};// If any of the found nodes is part of a cluster found in this method,
// add the current values to that cluster
const foundCluster=findClusterData();if(foundCluster!==undefined){// Add nodes to found cluster if not present
for(const m in childNodesObj){if(foundCluster.nodes[m]===undefined){foundCluster.nodes[m]=childNodesObj[m];}}// Add edges to found cluster, if not present
for(const m in childEdgesObj){if(foundCluster.edges[m]===undefined){foundCluster.edges[m]=childEdgesObj[m];}}}else {// Create a new cluster group
clusters.push({nodes:childNodesObj,edges:childEdgesObj});}}}}}for(let i=0;i<clusters.length;i++){this._cluster(clusters[i].nodes,clusters[i].edges,options,false);}if(refreshData===true){this.body.emitter.emit("_dataChanged");}}/**
   * Cluster all nodes in the network that have only 1 edge
   * @param {object} options
   * @param {boolean} [refreshData]
   */clusterOutliers(options){let refreshData=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;this.clusterByEdgeCount(1,options,refreshData);}/**
   * Cluster all nodes in the network that have only 2 edge
   * @param {object} options
   * @param {boolean} [refreshData]
   */clusterBridges(options){let refreshData=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;this.clusterByEdgeCount(2,options,refreshData);}/**
   * suck all connected nodes of a node into the node.
   * @param {Node.id} nodeId
   * @param {object} options
   * @param {boolean} [refreshData]
   */clusterByConnection(nodeId,options){var _context;let refreshData=arguments.length>2&&arguments[2]!==undefined?arguments[2]:true;// kill conditions
if(nodeId===undefined){throw new Error("No nodeId supplied to clusterByConnection!");}if(this.body.nodes[nodeId]===undefined){throw new Error("The nodeId given to clusterByConnection does not exist!");}const node=this.body.nodes[nodeId];options=this._checkOptions(options,node);if(options.clusterNodeProperties.x===undefined){options.clusterNodeProperties.x=node.x;}if(options.clusterNodeProperties.y===undefined){options.clusterNodeProperties.y=node.y;}if(options.clusterNodeProperties.fixed===undefined){options.clusterNodeProperties.fixed={};options.clusterNodeProperties.fixed.x=node.options.fixed.x;options.clusterNodeProperties.fixed.y=node.options.fixed.y;}const childNodesObj={};const childEdgesObj={};const parentNodeId=node.id;const parentClonedOptions=NetworkUtil.cloneOptions(node);childNodesObj[parentNodeId]=node;// collect the nodes that will be in the cluster
for(let i=0;i<node.edges.length;i++){const edge=node.edges[i];if(this.clusteredEdges[edge.id]===undefined){const childNodeId=this._getConnectedId(edge,parentNodeId);// if the child node is not in a cluster
if(this.clusteredNodes[childNodeId]===undefined){if(childNodeId!==parentNodeId){if(options.joinCondition===undefined){childEdgesObj[edge.id]=edge;childNodesObj[childNodeId]=this.body.nodes[childNodeId];}else {// clone the options and insert some additional parameters that could be interesting.
const childClonedOptions=NetworkUtil.cloneOptions(this.body.nodes[childNodeId]);if(options.joinCondition(parentClonedOptions,childClonedOptions)===true){childEdgesObj[edge.id]=edge;childNodesObj[childNodeId]=this.body.nodes[childNodeId];}}}else {// swallow the edge if it is self-referencing.
childEdgesObj[edge.id]=edge;}}}}const childNodeIDs=_mapInstanceProperty(_context=_Object$keys(childNodesObj)).call(_context,function(childNode){return childNodesObj[childNode].id;});for(const childNodeKey in childNodesObj){if(!Object.prototype.hasOwnProperty.call(childNodesObj,childNodeKey))continue;const childNode=childNodesObj[childNodeKey];for(let y=0;y<childNode.edges.length;y++){const childEdge=childNode.edges[y];if(_indexOfInstanceProperty(childNodeIDs).call(childNodeIDs,this._getConnectedId(childEdge,childNode.id))>-1){childEdgesObj[childEdge.id]=childEdge;}}}this._cluster(childNodesObj,childEdgesObj,options,refreshData);}/**
   * This function creates the edges that will be attached to the cluster
   * It looks for edges that are connected to the nodes from the "outside' of the cluster.
   * @param {{Node.id: vis.Node}} childNodesObj
   * @param {{vis.Edge.id: vis.Edge}} childEdgesObj
   * @param {object} clusterNodeProperties
   * @param {object} clusterEdgeProperties
   * @private
   */_createClusterEdges(childNodesObj,childEdgesObj,clusterNodeProperties,clusterEdgeProperties){let edge,childNodeId,childNode,toId,fromId,otherNodeId;// loop over all child nodes and their edges to find edges going out of the cluster
// these edges will be replaced by clusterEdges.
const childKeys=_Object$keys(childNodesObj);const createEdges=[];for(let i=0;i<childKeys.length;i++){childNodeId=childKeys[i];childNode=childNodesObj[childNodeId];// construct new edges from the cluster to others
for(let j=0;j<childNode.edges.length;j++){edge=childNode.edges[j];// we only handle edges that are visible to the system, not the disabled ones from the clustering process.
if(this.clusteredEdges[edge.id]===undefined){// self-referencing edges will be added to the "hidden" list
if(edge.toId==edge.fromId){childEdgesObj[edge.id]=edge;}else {// set up the from and to.
if(edge.toId==childNodeId){// this is a double equals because ints and strings can be interchanged here.
toId=clusterNodeProperties.id;fromId=edge.fromId;otherNodeId=fromId;}else {toId=edge.toId;fromId=clusterNodeProperties.id;otherNodeId=toId;}}// Only edges from the cluster outwards are being replaced.
if(childNodesObj[otherNodeId]===undefined){createEdges.push({edge:edge,fromId:fromId,toId:toId});}}}}//
// Here we actually create the replacement edges.
//
// We could not do this in the loop above as the creation process
// would add an edge to the edges array we are iterating over.
//
// NOTE: a clustered edge can have multiple base edges!
//
const newEdges=[];/**
     * Find a cluster edge which matches the given created edge.
     * @param {vis.Edge} createdEdge
     * @returns {vis.Edge}
     */const getNewEdge=function(createdEdge){for(let j=0;j<newEdges.length;j++){const newEdge=newEdges[j];// We replace both to and from edges with a single cluster edge
const matchToDirection=createdEdge.fromId===newEdge.fromId&&createdEdge.toId===newEdge.toId;const matchFromDirection=createdEdge.fromId===newEdge.toId&&createdEdge.toId===newEdge.fromId;if(matchToDirection||matchFromDirection){return newEdge;}}return null;};for(let j=0;j<createEdges.length;j++){const createdEdge=createEdges[j];const edge=createdEdge.edge;let newEdge=getNewEdge(createdEdge);if(newEdge===null){// Create a clustered edge for this connection
newEdge=this._createClusteredEdge(createdEdge.fromId,createdEdge.toId,edge,clusterEdgeProperties);newEdges.push(newEdge);}else {newEdge.clusteringEdgeReplacingIds.push(edge.id);}// also reference the new edge in the old edge
this.body.edges[edge.id].edgeReplacedById=newEdge.id;// hide the replaced edge
this._backupEdgeOptions(edge);edge.setOptions({physics:false});}}/**
   * This function checks the options that can be supplied to the different cluster functions
   * for certain fields and inserts defaults if needed
   * @param {object} options
   * @returns {*}
   * @private
   */_checkOptions(){let options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};if(options.clusterEdgeProperties===undefined){options.clusterEdgeProperties={};}if(options.clusterNodeProperties===undefined){options.clusterNodeProperties={};}return options;}/**
   *
   * @param {object}    childNodesObj         | object with node objects, id as keys, same as childNodes except it also contains a source node
   * @param {object}    childEdgesObj         | object with edge objects, id as keys
   * @param {Array}     options               | object with {clusterNodeProperties, clusterEdgeProperties, processProperties}
   * @param {boolean}   refreshData | when true, do not wrap up
   * @private
   */_cluster(childNodesObj,childEdgesObj,options){let refreshData=arguments.length>3&&arguments[3]!==undefined?arguments[3]:true;// Remove nodes which are already clustered
const tmpNodesToRemove=[];for(const nodeId in childNodesObj){if(Object.prototype.hasOwnProperty.call(childNodesObj,nodeId)){if(this.clusteredNodes[nodeId]!==undefined){tmpNodesToRemove.push(nodeId);}}}for(let n=0;n<tmpNodesToRemove.length;++n){delete childNodesObj[tmpNodesToRemove[n]];}// kill condition: no nodes don't bother
if(_Object$keys(childNodesObj).length==0){return;}// allow clusters of 1 if options allow
if(_Object$keys(childNodesObj).length==1&&options.clusterNodeProperties.allowSingleNodeCluster!=true){return;}let clusterNodeProperties=deepExtend({},options.clusterNodeProperties);// construct the clusterNodeProperties
if(options.processProperties!==undefined){// get the childNode options
const childNodesOptions=[];for(const nodeId in childNodesObj){if(Object.prototype.hasOwnProperty.call(childNodesObj,nodeId)){const clonedOptions=NetworkUtil.cloneOptions(childNodesObj[nodeId]);childNodesOptions.push(clonedOptions);}}// get cluster properties based on childNodes
const childEdgesOptions=[];for(const edgeId in childEdgesObj){if(Object.prototype.hasOwnProperty.call(childEdgesObj,edgeId)){// these cluster edges will be removed on creation of the cluster.
if(edgeId.substr(0,12)!=="clusterEdge:"){const clonedOptions=NetworkUtil.cloneOptions(childEdgesObj[edgeId],"edge");childEdgesOptions.push(clonedOptions);}}}clusterNodeProperties=options.processProperties(clusterNodeProperties,childNodesOptions,childEdgesOptions);if(!clusterNodeProperties){throw new Error("The processProperties function does not return properties!");}}// check if we have an unique id;
if(clusterNodeProperties.id===undefined){clusterNodeProperties.id="cluster:"+v4();}const clusterId=clusterNodeProperties.id;if(clusterNodeProperties.label===undefined){clusterNodeProperties.label="cluster";}// give the clusterNode a position if it does not have one.
let pos=undefined;if(clusterNodeProperties.x===undefined){pos=this._getClusterPosition(childNodesObj);clusterNodeProperties.x=pos.x;}if(clusterNodeProperties.y===undefined){if(pos===undefined){pos=this._getClusterPosition(childNodesObj);}clusterNodeProperties.y=pos.y;}// force the ID to remain the same
clusterNodeProperties.id=clusterId;// create the cluster Node
// Note that allowSingleNodeCluster, if present, is stored in the options as well
const clusterNode=this.body.functions.createNode(clusterNodeProperties,Cluster);clusterNode.containedNodes=childNodesObj;clusterNode.containedEdges=childEdgesObj;// cache a copy from the cluster edge properties if we have to reconnect others later on
clusterNode.clusterEdgeProperties=options.clusterEdgeProperties;// finally put the cluster node into global
this.body.nodes[clusterNodeProperties.id]=clusterNode;this._clusterEdges(childNodesObj,childEdgesObj,clusterNodeProperties,options.clusterEdgeProperties);// set ID to undefined so no duplicates arise
clusterNodeProperties.id=undefined;// wrap up
if(refreshData===true){this.body.emitter.emit("_dataChanged");}}/**
   *
   * @param {Edge} edge
   * @private
   */_backupEdgeOptions(edge){if(this.clusteredEdges[edge.id]===undefined){this.clusteredEdges[edge.id]={physics:edge.options.physics};}}/**
   *
   * @param {Edge} edge
   * @private
   */_restoreEdge(edge){const originalOptions=this.clusteredEdges[edge.id];if(originalOptions!==undefined){edge.setOptions({physics:originalOptions.physics});delete this.clusteredEdges[edge.id];}}/**
   * Check if a node is a cluster.
   * @param {Node.id} nodeId
   * @returns {*}
   */isCluster(nodeId){if(this.body.nodes[nodeId]!==undefined){return this.body.nodes[nodeId].isCluster===true;}else {console.error("Node does not exist.");return false;}}/**
   * get the position of the cluster node based on what's inside
   * @param {object} childNodesObj    | object with node objects, id as keys
   * @returns {{x: number, y: number}}
   * @private
   */_getClusterPosition(childNodesObj){const childKeys=_Object$keys(childNodesObj);let minX=childNodesObj[childKeys[0]].x;let maxX=childNodesObj[childKeys[0]].x;let minY=childNodesObj[childKeys[0]].y;let maxY=childNodesObj[childKeys[0]].y;let node;for(let i=1;i<childKeys.length;i++){node=childNodesObj[childKeys[i]];minX=node.x<minX?node.x:minX;maxX=node.x>maxX?node.x:maxX;minY=node.y<minY?node.y:minY;maxY=node.y>maxY?node.y:maxY;}return {x:0.5*(minX+maxX),y:0.5*(minY+maxY)};}/**
   * Open a cluster by calling this function.
   * @param {vis.Edge.id}  clusterNodeId | the ID of the cluster node
   * @param {object} options
   * @param {boolean} refreshData | wrap up afterwards if not true
   */openCluster(clusterNodeId,options){let refreshData=arguments.length>2&&arguments[2]!==undefined?arguments[2]:true;// kill conditions
if(clusterNodeId===undefined){throw new Error("No clusterNodeId supplied to openCluster.");}const clusterNode=this.body.nodes[clusterNodeId];if(clusterNode===undefined){throw new Error("The clusterNodeId supplied to openCluster does not exist.");}if(clusterNode.isCluster!==true||clusterNode.containedNodes===undefined||clusterNode.containedEdges===undefined){throw new Error("The node:"+clusterNodeId+" is not a valid cluster.");}// Check if current cluster is clustered itself
const stack=this.findNode(clusterNodeId);const parentIndex=_indexOfInstanceProperty(stack).call(stack,clusterNodeId)-1;if(parentIndex>=0){// Current cluster is clustered; transfer contained nodes and edges to parent
const parentClusterNodeId=stack[parentIndex];const parentClusterNode=this.body.nodes[parentClusterNodeId];// clustering.clusteredNodes and clustering.clusteredEdges remain unchanged
parentClusterNode._openChildCluster(clusterNodeId);// All components of child cluster node have been transferred. It can die now.
delete this.body.nodes[clusterNodeId];if(refreshData===true){this.body.emitter.emit("_dataChanged");}return;}// main body
const containedNodes=clusterNode.containedNodes;const containedEdges=clusterNode.containedEdges;// allow the user to position the nodes after release.
if(options!==undefined&&options.releaseFunction!==undefined&&typeof options.releaseFunction==="function"){const positions={};const clusterPosition={x:clusterNode.x,y:clusterNode.y};for(const nodeId in containedNodes){if(Object.prototype.hasOwnProperty.call(containedNodes,nodeId)){const containedNode=this.body.nodes[nodeId];positions[nodeId]={x:containedNode.x,y:containedNode.y};}}const newPositions=options.releaseFunction(clusterPosition,positions);for(const nodeId in containedNodes){if(Object.prototype.hasOwnProperty.call(containedNodes,nodeId)){const containedNode=this.body.nodes[nodeId];if(newPositions[nodeId]!==undefined){containedNode.x=newPositions[nodeId].x===undefined?clusterNode.x:newPositions[nodeId].x;containedNode.y=newPositions[nodeId].y===undefined?clusterNode.y:newPositions[nodeId].y;}}}}else {// copy the position from the cluster
forEach(containedNodes,function(containedNode){// inherit position
if(containedNode.options.fixed.x===false){containedNode.x=clusterNode.x;}if(containedNode.options.fixed.y===false){containedNode.y=clusterNode.y;}});}// release nodes
for(const nodeId in containedNodes){if(Object.prototype.hasOwnProperty.call(containedNodes,nodeId)){const containedNode=this.body.nodes[nodeId];// inherit speed
containedNode.vx=clusterNode.vx;containedNode.vy=clusterNode.vy;containedNode.setOptions({physics:true});delete this.clusteredNodes[nodeId];}}// copy the clusterNode edges because we cannot iterate over an object that we add or remove from.
const edgesToBeDeleted=[];for(let i=0;i<clusterNode.edges.length;i++){edgesToBeDeleted.push(clusterNode.edges[i]);}// actually handling the deleting.
for(let i=0;i<edgesToBeDeleted.length;i++){const edge=edgesToBeDeleted[i];const otherNodeId=this._getConnectedId(edge,clusterNodeId);const otherNode=this.clusteredNodes[otherNodeId];for(let j=0;j<edge.clusteringEdgeReplacingIds.length;j++){const transferId=edge.clusteringEdgeReplacingIds[j];const transferEdge=this.body.edges[transferId];if(transferEdge===undefined)continue;// if the other node is in another cluster, we transfer ownership of this edge to the other cluster
if(otherNode!==undefined){// transfer ownership:
const otherCluster=this.body.nodes[otherNode.clusterId];otherCluster.containedEdges[transferEdge.id]=transferEdge;// delete local reference
delete containedEdges[transferEdge.id];// get to and from
let fromId=transferEdge.fromId;let toId=transferEdge.toId;if(transferEdge.toId==otherNodeId){toId=otherNode.clusterId;}else {fromId=otherNode.clusterId;}// create new cluster edge from the otherCluster
this._createClusteredEdge(fromId,toId,transferEdge,otherCluster.clusterEdgeProperties,{hidden:false,physics:true});}else {this._restoreEdge(transferEdge);}}edge.remove();}// handle the releasing of the edges
for(const edgeId in containedEdges){if(Object.prototype.hasOwnProperty.call(containedEdges,edgeId)){this._restoreEdge(containedEdges[edgeId]);}}// remove clusterNode
delete this.body.nodes[clusterNodeId];if(refreshData===true){this.body.emitter.emit("_dataChanged");}}/**
   *
   * @param {Cluster.id} clusterId
   * @returns {Array.<Node.id>}
   */getNodesInCluster(clusterId){const nodesArray=[];if(this.isCluster(clusterId)===true){const containedNodes=this.body.nodes[clusterId].containedNodes;for(const nodeId in containedNodes){if(Object.prototype.hasOwnProperty.call(containedNodes,nodeId)){nodesArray.push(this.body.nodes[nodeId].id);}}}return nodesArray;}/**
   * Get the stack clusterId's that a certain node resides in. cluster A -> cluster B -> cluster C -> node
   *
   * If a node can't be found in the chain, return an empty array.
   * @param {string|number} nodeId
   * @returns {Array}
   */findNode(nodeId){const stack=[];const max=100;let counter=0;let node;while(this.clusteredNodes[nodeId]!==undefined&&counter<max){node=this.body.nodes[nodeId];if(node===undefined)return [];stack.push(node.id);nodeId=this.clusteredNodes[nodeId].clusterId;counter++;}node=this.body.nodes[nodeId];if(node===undefined)return [];stack.push(node.id);_reverseInstanceProperty(stack).call(stack);return stack;}/**
   * Using a clustered nodeId, update with the new options
   * @param {Node.id} clusteredNodeId
   * @param {object} newOptions
   */updateClusteredNode(clusteredNodeId,newOptions){if(clusteredNodeId===undefined){throw new Error("No clusteredNodeId supplied to updateClusteredNode.");}if(newOptions===undefined){throw new Error("No newOptions supplied to updateClusteredNode.");}if(this.body.nodes[clusteredNodeId]===undefined){throw new Error("The clusteredNodeId supplied to updateClusteredNode does not exist.");}this.body.nodes[clusteredNodeId].setOptions(newOptions);this.body.emitter.emit("_dataChanged");}/**
   * Using a base edgeId, update all related clustered edges with the new options
   * @param {vis.Edge.id} startEdgeId
   * @param {object} newOptions
   */updateEdge(startEdgeId,newOptions){if(startEdgeId===undefined){throw new Error("No startEdgeId supplied to updateEdge.");}if(newOptions===undefined){throw new Error("No newOptions supplied to updateEdge.");}if(this.body.edges[startEdgeId]===undefined){throw new Error("The startEdgeId supplied to updateEdge does not exist.");}const allEdgeIds=this.getClusteredEdges(startEdgeId);for(let i=0;i<allEdgeIds.length;i++){const edge=this.body.edges[allEdgeIds[i]];edge.setOptions(newOptions);}this.body.emitter.emit("_dataChanged");}/**
   * Get a stack of clusterEdgeId's (+base edgeid) that a base edge is the same as. cluster edge C -> cluster edge B -> cluster edge A -> base edge(edgeId)
   * @param {vis.Edge.id} edgeId
   * @returns {Array.<vis.Edge.id>}
   */getClusteredEdges(edgeId){const stack=[];const max=100;let counter=0;while(edgeId!==undefined&&this.body.edges[edgeId]!==undefined&&counter<max){stack.push(this.body.edges[edgeId].id);edgeId=this.body.edges[edgeId].edgeReplacedById;counter++;}_reverseInstanceProperty(stack).call(stack);return stack;}/**
   * Get the base edge id of clusterEdgeId. cluster edge (clusteredEdgeId) -> cluster edge B -> cluster edge C -> base edge
   * @param {vis.Edge.id} clusteredEdgeId
   * @returns {vis.Edge.id} baseEdgeId
   *
   * TODO: deprecate in 5.0.0. Method getBaseEdges() is the correct one to use.
   */getBaseEdge(clusteredEdgeId){// Just kludge this by returning the first base edge id found
return this.getBaseEdges(clusteredEdgeId)[0];}/**
   * Get all regular edges for this clustered edge id.
   * @param {vis.Edge.id} clusteredEdgeId
   * @returns {Array.<vis.Edge.id>} all baseEdgeId's under this clustered edge
   */getBaseEdges(clusteredEdgeId){const IdsToHandle=[clusteredEdgeId];const doneIds=[];const foundIds=[];const max=100;let counter=0;while(IdsToHandle.length>0&&counter<max){const nextId=IdsToHandle.pop();if(nextId===undefined)continue;// Paranoia here and onwards
const nextEdge=this.body.edges[nextId];if(nextEdge===undefined)continue;counter++;const replacingIds=nextEdge.clusteringEdgeReplacingIds;if(replacingIds===undefined){// nextId is a base id
foundIds.push(nextId);}else {// Another cluster edge, unravel this one as well
for(let i=0;i<replacingIds.length;++i){const replacingId=replacingIds[i];// Don't add if already handled
// TODO: never triggers; find a test-case which does
if(_indexOfInstanceProperty(IdsToHandle).call(IdsToHandle,replacingIds)!==-1||_indexOfInstanceProperty(doneIds).call(doneIds,replacingIds)!==-1){continue;}IdsToHandle.push(replacingId);}}doneIds.push(nextId);}return foundIds;}/**
   * Get the Id the node is connected to
   * @param {vis.Edge} edge
   * @param {Node.id} nodeId
   * @returns {*}
   * @private
   */_getConnectedId(edge,nodeId){if(edge.toId!=nodeId){return edge.toId;}else if(edge.fromId!=nodeId){return edge.fromId;}else {return edge.fromId;}}/**
   * We determine how many connections denote an important hub.
   * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
   * @returns {number}
   * @private
   */_getHubSize(){let average=0;let averageSquared=0;let hubCounter=0;let largestHub=0;for(let i=0;i<this.body.nodeIndices.length;i++){const node=this.body.nodes[this.body.nodeIndices[i]];if(node.edges.length>largestHub){largestHub=node.edges.length;}average+=node.edges.length;averageSquared+=Math.pow(node.edges.length,2);hubCounter+=1;}average=average/hubCounter;averageSquared=averageSquared/hubCounter;const variance=averageSquared-Math.pow(average,2);const standardDeviation=Math.sqrt(variance);let hubThreshold=Math.floor(average+2*standardDeviation);// always have at least one to cluster
if(hubThreshold>largestHub){hubThreshold=largestHub;}return hubThreshold;}/**
   * Create an edge for the cluster representation.
   * @param {Node.id} fromId
   * @param {Node.id} toId
   * @param {vis.Edge} baseEdge
   * @param {object} clusterEdgeProperties
   * @param {object} extraOptions
   * @returns {Edge} newly created clustered edge
   * @private
   */_createClusteredEdge(fromId,toId,baseEdge,clusterEdgeProperties,extraOptions){// copy the options of the edge we will replace
const clonedOptions=NetworkUtil.cloneOptions(baseEdge,"edge");// make sure the properties of clusterEdges are superimposed on it
deepExtend(clonedOptions,clusterEdgeProperties);// set up the edge
clonedOptions.from=fromId;clonedOptions.to=toId;clonedOptions.id="clusterEdge:"+v4();// apply the edge specific options to it if specified
if(extraOptions!==undefined){deepExtend(clonedOptions,extraOptions);}const newEdge=this.body.functions.createEdge(clonedOptions);newEdge.clusteringEdgeReplacingIds=[baseEdge.id];newEdge.connect();// Register the new edge
this.body.edges[newEdge.id]=newEdge;return newEdge;}/**
   * Add the passed child nodes and edges to the given cluster node.
   * @param {object | Node} childNodes  hash of nodes or single node to add in cluster
   * @param {object | Edge} childEdges  hash of edges or single edge to take into account when clustering
   * @param {Node} clusterNode  cluster node to add nodes and edges to
   * @param {object} [clusterEdgeProperties]
   * @private
   */_clusterEdges(childNodes,childEdges,clusterNode,clusterEdgeProperties){if(childEdges instanceof Edge){const edge=childEdges;const obj={};obj[edge.id]=edge;childEdges=obj;}if(childNodes instanceof Node$1){const node=childNodes;const obj={};obj[node.id]=node;childNodes=obj;}if(clusterNode===undefined||clusterNode===null){throw new Error("_clusterEdges: parameter clusterNode required");}if(clusterEdgeProperties===undefined){// Take the required properties from the cluster node
clusterEdgeProperties=clusterNode.clusterEdgeProperties;}// create the new edges that will connect to the cluster.
// All self-referencing edges will be added to childEdges here.
this._createClusterEdges(childNodes,childEdges,clusterNode,clusterEdgeProperties);// disable the childEdges
for(const edgeId in childEdges){if(Object.prototype.hasOwnProperty.call(childEdges,edgeId)){if(this.body.edges[edgeId]!==undefined){const edge=this.body.edges[edgeId];// cache the options before changing
this._backupEdgeOptions(edge);// disable physics and hide the edge
edge.setOptions({physics:false});}}}// disable the childNodes
for(const nodeId in childNodes){if(Object.prototype.hasOwnProperty.call(childNodes,nodeId)){this.clusteredNodes[nodeId]={clusterId:clusterNode.id,node:this.body.nodes[nodeId]};this.body.nodes[nodeId].setOptions({physics:false});}}}/**
   * Determine in which cluster given nodeId resides.
   *
   * If not in cluster, return undefined.
   *
   * NOTE: If you know a cleaner way to do this, please enlighten me (wimrijnders).
   * @param {Node.id} nodeId
   * @returns {Node|undefined} Node instance for cluster, if present
   * @private
   */_getClusterNodeForNode(nodeId){if(nodeId===undefined)return undefined;const clusteredNode=this.clusteredNodes[nodeId];// NOTE: If no cluster info found, it should actually be an error
if(clusteredNode===undefined)return undefined;const clusterId=clusteredNode.clusterId;if(clusterId===undefined)return undefined;return this.body.nodes[clusterId];}/**
   * Internal helper function for conditionally removing items in array
   *
   * Done like this because Array.filter() is not fully supported by all IE's.
   * @param {Array} arr
   * @param {Function} callback
   * @returns {Array}
   * @private
   */_filter(arr,callback){const ret=[];forEach(arr,item=>{if(callback(item)){ret.push(item);}});return ret;}/**
   * Scan all edges for changes in clustering and adjust this if necessary.
   *
   * Call this (internally) after there has been a change in node or edge data.
   *
   * Pre: States of this.body.nodes and this.body.edges consistent
   * Pre: this.clusteredNodes and this.clusteredEdge consistent with containedNodes and containedEdges
   *      of cluster nodes.
   */_updateState(){let nodeId;const deletedNodeIds=[];const deletedEdgeIds={};/**
     * Utility function to iterate over clustering nodes only
     * @param {Function} callback  function to call for each cluster node
     */const eachClusterNode=callback=>{forEach(this.body.nodes,node=>{if(node.isCluster===true){callback(node);}});};//
// Remove deleted regular nodes from clustering
//
// Determine the deleted nodes
for(nodeId in this.clusteredNodes){if(!Object.prototype.hasOwnProperty.call(this.clusteredNodes,nodeId))continue;const node=this.body.nodes[nodeId];if(node===undefined){deletedNodeIds.push(nodeId);}}// Remove nodes from cluster nodes
eachClusterNode(function(clusterNode){for(let n=0;n<deletedNodeIds.length;n++){delete clusterNode.containedNodes[deletedNodeIds[n]];}});// Remove nodes from cluster list
for(let n=0;n<deletedNodeIds.length;n++){delete this.clusteredNodes[deletedNodeIds[n]];}//
// Remove deleted edges from clustering
//
// Add the deleted clustered edges to the list
forEach(this.clusteredEdges,edgeId=>{const edge=this.body.edges[edgeId];if(edge===undefined||!edge.endPointsValid()){deletedEdgeIds[edgeId]=edgeId;}});// Cluster nodes can also contain edges which are not clustered,
// i.e. nodes 1-2 within cluster with an edge in between.
// So the cluster nodes also need to be scanned for invalid edges
eachClusterNode(function(clusterNode){forEach(clusterNode.containedEdges,(edge,edgeId)=>{if(!edge.endPointsValid()&&!deletedEdgeIds[edgeId]){deletedEdgeIds[edgeId]=edgeId;}});});// Also scan for cluster edges which need to be removed in the active list.
// Regular edges have been removed beforehand, so this only picks up the cluster edges.
forEach(this.body.edges,(edge,edgeId)=>{// Explicitly scan the contained edges for validity
let isValid=true;const replacedIds=edge.clusteringEdgeReplacingIds;if(replacedIds!==undefined){let numValid=0;forEach(replacedIds,containedEdgeId=>{const containedEdge=this.body.edges[containedEdgeId];if(containedEdge!==undefined&&containedEdge.endPointsValid()){numValid+=1;}});isValid=numValid>0;}if(!edge.endPointsValid()||!isValid){deletedEdgeIds[edgeId]=edgeId;}});// Remove edges from cluster nodes
eachClusterNode(clusterNode=>{forEach(deletedEdgeIds,deletedEdgeId=>{delete clusterNode.containedEdges[deletedEdgeId];forEach(clusterNode.edges,(edge,m)=>{if(edge.id===deletedEdgeId){clusterNode.edges[m]=null;// Don't want to directly delete here, because in the loop
return;}edge.clusteringEdgeReplacingIds=this._filter(edge.clusteringEdgeReplacingIds,function(id){return !deletedEdgeIds[id];});});// Clean up the nulls
clusterNode.edges=this._filter(clusterNode.edges,function(item){return item!==null;});});});// Remove from cluster list
forEach(deletedEdgeIds,edgeId=>{delete this.clusteredEdges[edgeId];});// Remove cluster edges from active list (this.body.edges).
// deletedEdgeIds still contains id of regular edges, but these should all
// be gone when you reach here.
forEach(deletedEdgeIds,edgeId=>{delete this.body.edges[edgeId];});//
// Check changed cluster state of edges
//
// Iterating over keys here, because edges may be removed in the loop
const ids=_Object$keys(this.body.edges);forEach(ids,edgeId=>{const edge=this.body.edges[edgeId];const shouldBeClustered=this._isClusteredNode(edge.fromId)||this._isClusteredNode(edge.toId);if(shouldBeClustered===this._isClusteredEdge(edge.id)){return;// all is well
}if(shouldBeClustered){// add edge to clustering
const clusterFrom=this._getClusterNodeForNode(edge.fromId);if(clusterFrom!==undefined){this._clusterEdges(this.body.nodes[edge.fromId],edge,clusterFrom);}const clusterTo=this._getClusterNodeForNode(edge.toId);if(clusterTo!==undefined){this._clusterEdges(this.body.nodes[edge.toId],edge,clusterTo);}// TODO: check that it works for both edges clustered
//       (This might be paranoia)
}else {delete this._clusterEdges[edgeId];this._restoreEdge(edge);// This should not be happening, the state should
// be properly updated at this point.
//
// If it *is* reached during normal operation, then we have to implement
// undo clustering for this edge here.
// throw new Error('remove edge from clustering not implemented!')
}});// Clusters may be nested to any level. Keep on opening until nothing to open
let changed=false;let continueLoop=true;while(continueLoop){const clustersToOpen=[];// Determine the id's of clusters that need opening
eachClusterNode(function(clusterNode){const numNodes=_Object$keys(clusterNode.containedNodes).length;const allowSingle=clusterNode.options.allowSingleNodeCluster===true;if(allowSingle&&numNodes<1||!allowSingle&&numNodes<2){clustersToOpen.push(clusterNode.id);}});// Open them
for(let n=0;n<clustersToOpen.length;++n){this.openCluster(clustersToOpen[n],{},false/* Don't refresh, we're in an refresh/update already */);}continueLoop=clustersToOpen.length>0;changed=changed||continueLoop;}if(changed){this._updateState();// Redo this method (recursion possible! should be safe)
}}/**
   * Determine if node with given id is part of a cluster.
   * @param {Node.id} nodeId
   * @returns {boolean} true if part of a cluster.
   */_isClusteredNode(nodeId){return this.clusteredNodes[nodeId]!==undefined;}/**
   * Determine if edge with given id is not visible due to clustering.
   *
   * An edge is considered clustered if:
   * - it is directly replaced by a clustering edge
   * - any of its connecting nodes is in a cluster
   * @param {vis.Edge.id} edgeId
   * @returns {boolean} true if part of a cluster.
   */_isClusteredEdge(edgeId){return this.clusteredEdges[edgeId]!==undefined;}}/**
 * The canvas renderer
 */class CanvasRenderer{/**
   * @param {object} body
   * @param {Canvas} canvas
   */constructor(body,canvas){this.body=body;this.canvas=canvas;this.redrawRequested=false;this.requestAnimationFrameRequestId=undefined;this.renderingActive=false;this.renderRequests=0;this.allowRedraw=true;this.dragging=false;this.zooming=false;this.options={};this.defaultOptions={hideEdgesOnDrag:false,hideEdgesOnZoom:false,hideNodesOnDrag:false};_Object$assign(this.options,this.defaultOptions);this.bindEventListeners();}/**
   * Binds event listeners
   */bindEventListeners(){var _context2;this.body.emitter.on("dragStart",()=>{this.dragging=true;});this.body.emitter.on("dragEnd",()=>{this.dragging=false;});this.body.emitter.on("zoom",()=>{this.zooming=true;window.clearTimeout(this.zoomTimeoutId);this.zoomTimeoutId=_setTimeout(()=>{var _context;this.zooming=false;_bindInstanceProperty(_context=this._requestRedraw).call(_context,this)();},250);});this.body.emitter.on("_resizeNodes",()=>{this._resizeNodes();});this.body.emitter.on("_redraw",()=>{if(this.renderingActive===false){this._redraw();}});this.body.emitter.on("_blockRedraw",()=>{this.allowRedraw=false;});this.body.emitter.on("_allowRedraw",()=>{this.allowRedraw=true;this.redrawRequested=false;});this.body.emitter.on("_requestRedraw",_bindInstanceProperty(_context2=this._requestRedraw).call(_context2,this));this.body.emitter.on("_startRendering",()=>{this.renderRequests+=1;this.renderingActive=true;this._startRendering();});this.body.emitter.on("_stopRendering",()=>{this.renderRequests-=1;this.renderingActive=this.renderRequests>0;this.requestAnimationFrameRequestId=undefined;});this.body.emitter.on("destroy",()=>{this.renderRequests=0;this.allowRedraw=false;this.renderingActive=false;window.cancelAnimationFrame(this.requestAnimationFrameRequestId);this.body.emitter.off();});}/**
   *
   * @param {object} options
   */setOptions(options){if(options!==undefined){const fields=["hideEdgesOnDrag","hideEdgesOnZoom","hideNodesOnDrag"];selectiveDeepExtend(fields,this.options,options);}}/**
   *
   * @private
   */_startRendering(){if(this.renderingActive===true){if(this.requestAnimationFrameRequestId===undefined){var _context3;this.requestAnimationFrameRequestId=window.requestAnimationFrame(_bindInstanceProperty(_context3=this._renderStep).call(_context3,this),this.simulationInterval);}}}/**
   *
   * @private
   */_renderStep(){if(this.renderingActive===true){// reset the requestAnimationFrameRequestId so a new scheduled animation step can be set
this.requestAnimationFrameRequestId=undefined;// this schedules a new simulation step
this._startRendering();this._redraw();}}/**
   * Redraw the network with the current data
   * chart will be resized too.
   */redraw(){this.body.emitter.emit("setSize");this._redraw();}/**
   * Redraw the network with the current data
   * @private
   */_requestRedraw(){if(this.redrawRequested!==true&&this.renderingActive===false&&this.allowRedraw===true){this.redrawRequested=true;window.requestAnimationFrame(()=>{this._redraw(false);});}}/**
   * Redraw the network with the current data
   * @param {boolean} [hidden] | Used to get the first estimate of the node sizes.
   *                                   Only the nodes are drawn after which they are quickly drawn over.
   * @private
   */_redraw(){let hidden=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;if(this.allowRedraw===true){this.body.emitter.emit("initRedraw");this.redrawRequested=false;const drawLater={drawExternalLabels:null};// when the container div was hidden, this fixes it back up!
if(this.canvas.frame.canvas.width===0||this.canvas.frame.canvas.height===0){this.canvas.setSize();}this.canvas.setTransform();const ctx=this.canvas.getContext();// clear the canvas
const w=this.canvas.frame.canvas.clientWidth;const h=this.canvas.frame.canvas.clientHeight;ctx.clearRect(0,0,w,h);// if the div is hidden, we stop the redraw here for performance.
if(this.canvas.frame.clientWidth===0){return;}// set scaling and translation
ctx.save();ctx.translate(this.body.view.translation.x,this.body.view.translation.y);ctx.scale(this.body.view.scale,this.body.view.scale);ctx.beginPath();this.body.emitter.emit("beforeDrawing",ctx);ctx.closePath();if(hidden===false){if((this.dragging===false||this.dragging===true&&this.options.hideEdgesOnDrag===false)&&(this.zooming===false||this.zooming===true&&this.options.hideEdgesOnZoom===false)){this._drawEdges(ctx);}}if(this.dragging===false||this.dragging===true&&this.options.hideNodesOnDrag===false){const{drawExternalLabels}=this._drawNodes(ctx,hidden);drawLater.drawExternalLabels=drawExternalLabels;}// draw the arrows last so they will be at the top
if(hidden===false){if((this.dragging===false||this.dragging===true&&this.options.hideEdgesOnDrag===false)&&(this.zooming===false||this.zooming===true&&this.options.hideEdgesOnZoom===false)){this._drawArrows(ctx);}}if(drawLater.drawExternalLabels!=null){drawLater.drawExternalLabels();}if(hidden===false){this._drawSelectionBox(ctx);}ctx.beginPath();this.body.emitter.emit("afterDrawing",ctx);ctx.closePath();// restore original scaling and translation
ctx.restore();if(hidden===true){ctx.clearRect(0,0,w,h);}}}/**
   * Redraw all nodes
   * @param {CanvasRenderingContext2D}   ctx
   * @param {boolean} [alwaysShow]
   * @private
   */_resizeNodes(){this.canvas.setTransform();const ctx=this.canvas.getContext();ctx.save();ctx.translate(this.body.view.translation.x,this.body.view.translation.y);ctx.scale(this.body.view.scale,this.body.view.scale);const nodes=this.body.nodes;let node;// resize all nodes
for(const nodeId in nodes){if(Object.prototype.hasOwnProperty.call(nodes,nodeId)){node=nodes[nodeId];node.resize(ctx);node.updateBoundingBox(ctx,node.selected);}}// restore original scaling and translation
ctx.restore();}/**
   * Redraw all nodes
   * @param {CanvasRenderingContext2D} ctx  2D context of a HTML canvas
   * @param {boolean} [alwaysShow]
   * @private
   * @returns {object} Callbacks to draw later on higher layers.
   */_drawNodes(ctx){let alwaysShow=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;const nodes=this.body.nodes;const nodeIndices=this.body.nodeIndices;let node;const selected=[];const hovered=[];const margin=20;const topLeft=this.canvas.DOMtoCanvas({x:-margin,y:-margin});const bottomRight=this.canvas.DOMtoCanvas({x:this.canvas.frame.canvas.clientWidth+margin,y:this.canvas.frame.canvas.clientHeight+margin});const viewableArea={top:topLeft.y,left:topLeft.x,bottom:bottomRight.y,right:bottomRight.x};const drawExternalLabels=[];// draw unselected nodes;
for(let i=0;i<nodeIndices.length;i++){node=nodes[nodeIndices[i]];// set selected and hovered nodes aside
if(node.hover){hovered.push(nodeIndices[i]);}else if(node.isSelected()){selected.push(nodeIndices[i]);}else {if(alwaysShow===true){const drawLater=node.draw(ctx);if(drawLater.drawExternalLabel!=null){drawExternalLabels.push(drawLater.drawExternalLabel);}}else if(node.isBoundingBoxOverlappingWith(viewableArea)===true){const drawLater=node.draw(ctx);if(drawLater.drawExternalLabel!=null){drawExternalLabels.push(drawLater.drawExternalLabel);}}else {node.updateBoundingBox(ctx,node.selected);}}}let i;const selectedLength=selected.length;const hoveredLength=hovered.length;// draw the selected nodes on top
for(i=0;i<selectedLength;i++){node=nodes[selected[i]];const drawLater=node.draw(ctx);if(drawLater.drawExternalLabel!=null){drawExternalLabels.push(drawLater.drawExternalLabel);}}// draw hovered nodes above everything else: fixes https://github.com/visjs/vis-network/issues/226
for(i=0;i<hoveredLength;i++){node=nodes[hovered[i]];const drawLater=node.draw(ctx);if(drawLater.drawExternalLabel!=null){drawExternalLabels.push(drawLater.drawExternalLabel);}}return {drawExternalLabels:()=>{for(const draw of drawExternalLabels){draw();}}};}/**
   * Redraw all edges
   * @param {CanvasRenderingContext2D} ctx  2D context of a HTML canvas
   * @private
   */_drawEdges(ctx){const edges=this.body.edges;const edgeIndices=this.body.edgeIndices;for(let i=0;i<edgeIndices.length;i++){const edge=edges[edgeIndices[i]];if(edge.connected===true){edge.draw(ctx);}}}/**
   * Redraw all arrows
   * @param {CanvasRenderingContext2D} ctx  2D context of a HTML canvas
   * @private
   */_drawArrows(ctx){const edges=this.body.edges;const edgeIndices=this.body.edgeIndices;for(let i=0;i<edgeIndices.length;i++){const edge=edges[edgeIndices[i]];if(edge.connected===true){edge.drawArrows(ctx);}}}/**
   * Redraw selection box
   * @param {CanvasRenderingContext2D} ctx  2D context of a HTML canvas
   * @private
   */_drawSelectionBox(ctx){if(this.body.selectionBox.show){ctx.beginPath();const width=this.body.selectionBox.position.end.x-this.body.selectionBox.position.start.x;const height=this.body.selectionBox.position.end.y-this.body.selectionBox.position.start.y;ctx.rect(this.body.selectionBox.position.start.x,this.body.selectionBox.position.start.y,width,height);ctx.fillStyle="rgba(151, 194, 252, 0.2)";ctx.fillRect(this.body.selectionBox.position.start.x,this.body.selectionBox.position.start.y,width,height);ctx.strokeStyle="rgba(151, 194, 252, 1)";ctx.stroke();}else {ctx.closePath();}}}var setInterval$1;var hasRequiredSetInterval$1;function requireSetInterval$1(){if(hasRequiredSetInterval$1)return setInterval$1;hasRequiredSetInterval$1=1;requireWeb_timers();var path=/*@__PURE__*/requirePath();setInterval$1=path.setInterval;return setInterval$1;}var setInterval;var hasRequiredSetInterval;function requireSetInterval(){if(hasRequiredSetInterval)return setInterval;hasRequiredSetInterval=1;setInterval=/*@__PURE__*/requireSetInterval$1();return setInterval;}var setIntervalExports=requireSetInterval();var _setInterval=/*@__PURE__*/getDefaultExportFromCjs(setIntervalExports);/**
 * Register a touch event, taking place before a gesture
 * @param {Hammer} hammer       A hammer instance
 * @param {Function} callback   Callback, called as callback(event)
 */function onTouch(hammer,callback){callback.inputHandler=function(event){if(event.isFirst){callback(event);}};hammer.on("hammer.input",callback.inputHandler);}/**
 * Register a release event, taking place after a gesture
 * @param {Hammer} hammer       A hammer instance
 * @param {Function} callback   Callback, called as callback(event)
 * @returns {*}
 */function onRelease(hammer,callback){callback.inputHandler=function(event){if(event.isFinal){callback(event);}};return hammer.on("hammer.input",callback.inputHandler);}/**
 * Create the main frame for the Network.
 * This function is executed once when a Network object is created. The frame
 * contains a canvas, and this canvas contains all objects like the axis and
 * nodes.
 */class Canvas{/**
   * @param {object} body
   */constructor(body){this.body=body;this.pixelRatio=1;this.cameraState={};this.initialized=false;this.canvasViewCenter={};this._cleanupCallbacks=[];this.options={};this.defaultOptions={autoResize:true,height:"100%",width:"100%"};_Object$assign(this.options,this.defaultOptions);this.bindEventListeners();}/**
   * Binds event listeners
   */bindEventListeners(){var _context;// bind the events
this.body.emitter.once("resize",obj=>{if(obj.width!==0){this.body.view.translation.x=obj.width*0.5;}if(obj.height!==0){this.body.view.translation.y=obj.height*0.5;}});this.body.emitter.on("setSize",_bindInstanceProperty(_context=this.setSize).call(_context,this));this.body.emitter.on("destroy",()=>{this.hammerFrame.destroy();this.hammer.destroy();this._cleanUp();});}/**
   * @param {object} options
   */setOptions(options){if(options!==undefined){const fields=["width","height","autoResize"];selectiveDeepExtend(fields,this.options,options);}// Automatically adapt to changing size of the container element.
this._cleanUp();if(this.options.autoResize===true){var _context2;if(window.ResizeObserver){// decent browsers, immediate reactions
const observer=new ResizeObserver(()=>{const changed=this.setSize();if(changed===true){this.body.emitter.emit("_requestRedraw");}});const{frame}=this;observer.observe(frame);this._cleanupCallbacks.push(()=>{observer.unobserve(frame);});}else {// IE11, continous polling
const resizeTimer=_setInterval(()=>{const changed=this.setSize();if(changed===true){this.body.emitter.emit("_requestRedraw");}},1000);this._cleanupCallbacks.push(()=>{clearInterval(resizeTimer);});}// Automatically adapt to changing size of the browser.
const resizeFunction=_bindInstanceProperty(_context2=this._onResize).call(_context2,this);window.addEventListener("resize",resizeFunction);this._cleanupCallbacks.push(()=>{window.removeEventListener("resize",resizeFunction);});}}/**
   * @private
   */_cleanUp(){var _context3,_context4,_context5;_forEachInstanceProperty(_context3=_reverseInstanceProperty(_context4=_spliceInstanceProperty(_context5=this._cleanupCallbacks).call(_context5,0)).call(_context4)).call(_context3,callback=>{try{callback();}catch(error){console.error(error);}});}/**
   * @private
   */_onResize(){this.setSize();this.body.emitter.emit("_redraw");}/**
   * Get and store the cameraState
   * @param {number} [pixelRatio]
   * @private
   */_getCameraState(){let pixelRatio=arguments.length>0&&arguments[0]!==undefined?arguments[0]:this.pixelRatio;if(this.initialized===true){this.cameraState.previousWidth=this.frame.canvas.width/pixelRatio;this.cameraState.previousHeight=this.frame.canvas.height/pixelRatio;this.cameraState.scale=this.body.view.scale;this.cameraState.position=this.DOMtoCanvas({x:0.5*this.frame.canvas.width/pixelRatio,y:0.5*this.frame.canvas.height/pixelRatio});}}/**
   * Set the cameraState
   * @private
   */_setCameraState(){if(this.cameraState.scale!==undefined&&this.frame.canvas.clientWidth!==0&&this.frame.canvas.clientHeight!==0&&this.pixelRatio!==0&&this.cameraState.previousWidth>0&&this.cameraState.previousHeight>0){const widthRatio=this.frame.canvas.width/this.pixelRatio/this.cameraState.previousWidth;const heightRatio=this.frame.canvas.height/this.pixelRatio/this.cameraState.previousHeight;let newScale=this.cameraState.scale;if(widthRatio!=1&&heightRatio!=1){newScale=this.cameraState.scale*0.5*(widthRatio+heightRatio);}else if(widthRatio!=1){newScale=this.cameraState.scale*widthRatio;}else if(heightRatio!=1){newScale=this.cameraState.scale*heightRatio;}this.body.view.scale=newScale;// this comes from the view module.
const currentViewCenter=this.DOMtoCanvas({x:0.5*this.frame.canvas.clientWidth,y:0.5*this.frame.canvas.clientHeight});const distanceFromCenter={// offset from view, distance view has to change by these x and y to center the node
x:currentViewCenter.x-this.cameraState.position.x,y:currentViewCenter.y-this.cameraState.position.y};this.body.view.translation.x+=distanceFromCenter.x*this.body.view.scale;this.body.view.translation.y+=distanceFromCenter.y*this.body.view.scale;}}/**
   *
   * @param {number|string} value
   * @returns {string}
   * @private
   */_prepareValue(value){if(typeof value==="number"){return value+"px";}else if(typeof value==="string"){if(_indexOfInstanceProperty(value).call(value,"%")!==-1||_indexOfInstanceProperty(value).call(value,"px")!==-1){return value;}else if(_indexOfInstanceProperty(value).call(value,"%")===-1){return value+"px";}}throw new Error("Could not use the value supplied for width or height:"+value);}/**
   * Create the HTML
   */_create(){// remove all elements from the container element.
while(this.body.container.hasChildNodes()){this.body.container.removeChild(this.body.container.firstChild);}this.frame=document.createElement("div");this.frame.className="vis-network";this.frame.style.position="relative";this.frame.style.overflow="hidden";this.frame.tabIndex=0;// tab index is required for keycharm to bind keystrokes to the div instead of the window
//////////////////////////////////////////////////////////////////
this.frame.canvas=document.createElement("canvas");this.frame.canvas.style.position="relative";this.frame.appendChild(this.frame.canvas);if(!this.frame.canvas.getContext){const noCanvas=document.createElement("DIV");noCanvas.style.color="red";noCanvas.style.fontWeight="bold";noCanvas.style.padding="10px";noCanvas.innerText="Error: your browser does not support HTML canvas";this.frame.canvas.appendChild(noCanvas);}else {this._setPixelRatio();this.setTransform();}// add the frame to the container element
this.body.container.appendChild(this.frame);this.body.view.scale=1;this.body.view.translation={x:0.5*this.frame.canvas.clientWidth,y:0.5*this.frame.canvas.clientHeight};this._bindHammer();}/**
   * This function binds hammer, it can be repeated over and over due to the uniqueness check.
   * @private
   */_bindHammer(){if(this.hammer!==undefined){this.hammer.destroy();}this.drag={};this.pinch={};// init hammer
this.hammer=new Hammer(this.frame.canvas);this.hammer.get("pinch").set({enable:true});// enable to get better response, todo: test on mobile.
this.hammer.get("pan").set({threshold:5,direction:Hammer.DIRECTION_ALL});onTouch(this.hammer,event=>{this.body.eventListeners.onTouch(event);});this.hammer.on("tap",event=>{this.body.eventListeners.onTap(event);});this.hammer.on("doubletap",event=>{this.body.eventListeners.onDoubleTap(event);});this.hammer.on("press",event=>{this.body.eventListeners.onHold(event);});this.hammer.on("panstart",event=>{this.body.eventListeners.onDragStart(event);});this.hammer.on("panmove",event=>{this.body.eventListeners.onDrag(event);});this.hammer.on("panend",event=>{this.body.eventListeners.onDragEnd(event);});this.hammer.on("pinch",event=>{this.body.eventListeners.onPinch(event);});// TODO: neatly cleanup these handlers when re-creating the Canvas, IF these are done with hammer, event.stopPropagation will not work?
this.frame.canvas.addEventListener("wheel",event=>{this.body.eventListeners.onMouseWheel(event);});this.frame.canvas.addEventListener("mousemove",event=>{this.body.eventListeners.onMouseMove(event);});this.frame.canvas.addEventListener("contextmenu",event=>{this.body.eventListeners.onContext(event);});this.hammerFrame=new Hammer(this.frame);onRelease(this.hammerFrame,event=>{this.body.eventListeners.onRelease(event);});}/**
   * Set a new size for the network
   * @param {string} width   Width in pixels or percentage (for example '800px'
   *                         or '50%')
   * @param {string} height  Height in pixels or percentage  (for example '400px'
   *                         or '30%')
   * @returns {boolean}
   */setSize(){let width=arguments.length>0&&arguments[0]!==undefined?arguments[0]:this.options.width;let height=arguments.length>1&&arguments[1]!==undefined?arguments[1]:this.options.height;width=this._prepareValue(width);height=this._prepareValue(height);let emitEvent=false;const oldWidth=this.frame.canvas.width;const oldHeight=this.frame.canvas.height;// update the pixel ratio
//
// NOTE: Comment in following is rather inconsistent; this is the ONLY place in the code
//       where it is assumed that the pixel ratio could change at runtime.
//       The only way I can think of this happening is a rotating screen or tablet; but then
//       there should be a mechanism for reloading the data (TODO: check if this is present).
//
//       If the assumption is true (i.e. pixel ratio can change at runtime), then *all* usage
//       of pixel ratio must be overhauled for this.
//
//       For the time being, I will humor the assumption here, and in the rest of the code assume it is
//       constant.
const previousRatio=this.pixelRatio;// we cache this because the camera state storage needs the old value
this._setPixelRatio();if(width!=this.options.width||height!=this.options.height||this.frame.style.width!=width||this.frame.style.height!=height){this._getCameraState(previousRatio);this.frame.style.width=width;this.frame.style.height=height;this.frame.canvas.style.width="100%";this.frame.canvas.style.height="100%";this.frame.canvas.width=Math.round(this.frame.canvas.clientWidth*this.pixelRatio);this.frame.canvas.height=Math.round(this.frame.canvas.clientHeight*this.pixelRatio);this.options.width=width;this.options.height=height;this.canvasViewCenter={x:0.5*this.frame.clientWidth,y:0.5*this.frame.clientHeight};emitEvent=true;}else {// this would adapt the width of the canvas to the width from 100% if and only if
// there is a change.
const newWidth=Math.round(this.frame.canvas.clientWidth*this.pixelRatio);const newHeight=Math.round(this.frame.canvas.clientHeight*this.pixelRatio);// store the camera if there is a change in size.
if(this.frame.canvas.width!==newWidth||this.frame.canvas.height!==newHeight){this._getCameraState(previousRatio);}if(this.frame.canvas.width!==newWidth){this.frame.canvas.width=newWidth;emitEvent=true;}if(this.frame.canvas.height!==newHeight){this.frame.canvas.height=newHeight;emitEvent=true;}}if(emitEvent===true){this.body.emitter.emit("resize",{width:Math.round(this.frame.canvas.width/this.pixelRatio),height:Math.round(this.frame.canvas.height/this.pixelRatio),oldWidth:Math.round(oldWidth/this.pixelRatio),oldHeight:Math.round(oldHeight/this.pixelRatio)});// restore the camera on change.
this._setCameraState();}// set initialized so the get and set camera will work from now on.
this.initialized=true;return emitEvent;}/**
   *
   * @returns {CanvasRenderingContext2D}
   */getContext(){return this.frame.canvas.getContext("2d");}/**
   * Determine the pixel ratio for various browsers.
   * @returns {number}
   * @private
   */_determinePixelRatio(){const ctx=this.getContext();if(ctx===undefined){throw new Error("Could not get canvax context");}let numerator=1;if(typeof window!=="undefined"){// (window !== undefined) doesn't work here!
// Protection during unit tests, where 'window' can be missing
numerator=window.devicePixelRatio||1;}const denominator=ctx.webkitBackingStorePixelRatio||ctx.mozBackingStorePixelRatio||ctx.msBackingStorePixelRatio||ctx.oBackingStorePixelRatio||ctx.backingStorePixelRatio||1;return numerator/denominator;}/**
   * Lazy determination of pixel ratio.
   * @private
   */_setPixelRatio(){this.pixelRatio=this._determinePixelRatio();}/**
   * Set the transform in the contained context, based on its pixelRatio
   */setTransform(){const ctx=this.getContext();if(ctx===undefined){throw new Error("Could not get canvax context");}ctx.setTransform(this.pixelRatio,0,0,this.pixelRatio,0,0);}/**
   * Convert the X coordinate in DOM-space (coordinate point in browser relative to the container div) to
   * the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
   * @param {number} x
   * @returns {number}
   * @private
   */_XconvertDOMtoCanvas(x){return (x-this.body.view.translation.x)/this.body.view.scale;}/**
   * Convert the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
   * the X coordinate in DOM-space (coordinate point in browser relative to the container div)
   * @param {number} x
   * @returns {number}
   * @private
   */_XconvertCanvasToDOM(x){return x*this.body.view.scale+this.body.view.translation.x;}/**
   * Convert the Y coordinate in DOM-space (coordinate point in browser relative to the container div) to
   * the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
   * @param {number} y
   * @returns {number}
   * @private
   */_YconvertDOMtoCanvas(y){return (y-this.body.view.translation.y)/this.body.view.scale;}/**
   * Convert the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
   * the Y coordinate in DOM-space (coordinate point in browser relative to the container div)
   * @param {number} y
   * @returns {number}
   * @private
   */_YconvertCanvasToDOM(y){return y*this.body.view.scale+this.body.view.translation.y;}/**
   * @param {point} pos
   * @returns {point}
   */canvasToDOM(pos){return {x:this._XconvertCanvasToDOM(pos.x),y:this._YconvertCanvasToDOM(pos.y)};}/**
   *
   * @param {point} pos
   * @returns {point}
   */DOMtoCanvas(pos){return {x:this._XconvertDOMtoCanvas(pos.x),y:this._YconvertDOMtoCanvas(pos.y)};}}/**
 * Validate the fit options, replace missing optional values by defaults etc.
 * @param rawOptions - The raw options.
 * @param allNodeIds - All node ids that will be used if nodes are omitted in
 * the raw options.
 * @returns Options with everything filled in and validated.
 */function normalizeFitOptions(rawOptions,allNodeIds){const options=_Object$assign({nodes:allNodeIds,minZoomLevel:Number.MIN_VALUE,maxZoomLevel:1},rawOptions!==null&&rawOptions!==void 0?rawOptions:{});if(!_Array$isArray(options.nodes)){throw new TypeError("Nodes has to be an array of ids.");}if(options.nodes.length===0){options.nodes=allNodeIds;}if(!(typeof options.minZoomLevel==="number"&&options.minZoomLevel>0)){throw new TypeError("Min zoom level has to be a number higher than zero.");}if(!(typeof options.maxZoomLevel==="number"&&options.minZoomLevel<=options.maxZoomLevel)){throw new TypeError("Max zoom level has to be a number higher than min zoom level.");}return options;}/**
 * The view
 */class View{/**
   * @param {object} body
   * @param {Canvas} canvas
   */constructor(body,canvas){var _context,_context2;this.body=body;this.canvas=canvas;this.animationSpeed=1/this.renderRefreshRate;this.animationEasingFunction="easeInOutQuint";this.easingTime=0;this.sourceScale=0;this.targetScale=0;this.sourceTranslation=0;this.targetTranslation=0;this.lockedOnNodeId=undefined;this.lockedOnNodeOffset=undefined;this.touchTime=0;this.viewFunction=undefined;this.body.emitter.on("fit",_bindInstanceProperty(_context=this.fit).call(_context,this));this.body.emitter.on("animationFinished",()=>{this.body.emitter.emit("_stopRendering");});this.body.emitter.on("unlockNode",_bindInstanceProperty(_context2=this.releaseNode).call(_context2,this));}/**
   *
   * @param {object} [options]
   */setOptions(){let options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};this.options=options;}/**
   * This function zooms out to fit all data on screen based on amount of nodes
   * @param {object} [options={{nodes=Array}}]
   * @param options
   * @param {boolean} [initialZoom]  | zoom based on fitted formula or range, true = fitted, default = false;
   */fit(options){let initialZoom=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;options=normalizeFitOptions(options,this.body.nodeIndices);const canvasWidth=this.canvas.frame.canvas.clientWidth;const canvasHeight=this.canvas.frame.canvas.clientHeight;let range;let zoomLevel;if(canvasWidth===0||canvasHeight===0){// There's no point in trying to fit into zero sized canvas. This could
// potentially even result in invalid values being computed. For example
// for network without nodes and zero sized canvas the zoom level would
// end up being computed as 0/0 which results in NaN. In any other case
// this would be 0/something which is again pointless to compute.
zoomLevel=1;range=NetworkUtil.getRange(this.body.nodes,options.nodes);}else if(initialZoom===true){// check if more than half of the nodes have a predefined position. If so, we use the range, not the approximation.
let positionDefined=0;for(const nodeId in this.body.nodes){if(Object.prototype.hasOwnProperty.call(this.body.nodes,nodeId)){const node=this.body.nodes[nodeId];if(node.predefinedPosition===true){positionDefined+=1;}}}if(positionDefined>0.5*this.body.nodeIndices.length){this.fit(options,false);return;}range=NetworkUtil.getRange(this.body.nodes,options.nodes);const numberOfNodes=this.body.nodeIndices.length;zoomLevel=12.662/(numberOfNodes+7.4147)+0.0964822;// this is obtained from fitting a dataset from 5 points with scale levels that looked good.
// correct for larger canvasses.
const factor=Math.min(canvasWidth/600,canvasHeight/600);zoomLevel*=factor;}else {this.body.emitter.emit("_resizeNodes");range=NetworkUtil.getRange(this.body.nodes,options.nodes);const xDistance=Math.abs(range.maxX-range.minX)*1.1;const yDistance=Math.abs(range.maxY-range.minY)*1.1;const xZoomLevel=canvasWidth/xDistance;const yZoomLevel=canvasHeight/yDistance;zoomLevel=xZoomLevel<=yZoomLevel?xZoomLevel:yZoomLevel;}if(zoomLevel>options.maxZoomLevel){zoomLevel=options.maxZoomLevel;}else if(zoomLevel<options.minZoomLevel){zoomLevel=options.minZoomLevel;}const center=NetworkUtil.findCenter(range);const animationOptions={position:center,scale:zoomLevel,animation:options.animation};this.moveTo(animationOptions);}// animation
/**
   * Center a node in view.
   * @param {number} nodeId
   * @param {number} [options]
   */focus(nodeId){let options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};if(this.body.nodes[nodeId]!==undefined){const nodePosition={x:this.body.nodes[nodeId].x,y:this.body.nodes[nodeId].y};options.position=nodePosition;options.lockedOnNode=nodeId;this.moveTo(options);}else {console.error("Node: "+nodeId+" cannot be found.");}}/**
   *
   * @param {object} options  |  options.offset   = {x:number, y:number}   // offset from the center in DOM pixels
   *                          |  options.scale    = number                 // scale to move to
   *                          |  options.position = {x:number, y:number}   // position to move to
   *                          |  options.animation = {duration:number, easingFunction:String} || Boolean   // position to move to
   */moveTo(options){if(options===undefined){options={};return;}if(options.offset!=null){if(options.offset.x!=null){// Coerce and verify that x is valid.
options.offset.x=+options.offset.x;if(!_Number$isFinite(options.offset.x)){throw new TypeError('The option "offset.x" has to be a finite number.');}}else {options.offset.x=0;}if(options.offset.y!=null){// Coerce and verify that y is valid.
options.offset.y=+options.offset.y;if(!_Number$isFinite(options.offset.y)){throw new TypeError('The option "offset.y" has to be a finite number.');}}else {options.offset.x=0;}}else {options.offset={x:0,y:0};}if(options.position!=null){if(options.position.x!=null){// Coerce and verify that x is valid.
options.position.x=+options.position.x;if(!_Number$isFinite(options.position.x)){throw new TypeError('The option "position.x" has to be a finite number.');}}else {options.position.x=0;}if(options.position.y!=null){// Coerce and verify that y is valid.
options.position.y=+options.position.y;if(!_Number$isFinite(options.position.y)){throw new TypeError('The option "position.y" has to be a finite number.');}}else {options.position.x=0;}}else {options.position=this.getViewPosition();}if(options.scale!=null){// Coerce and verify that the scale is valid.
options.scale=+options.scale;if(!(options.scale>0)){throw new TypeError('The option "scale" has to be a number greater than zero.');}}else {options.scale=this.body.view.scale;}if(options.animation===undefined){options.animation={duration:0};}if(options.animation===false){options.animation={duration:0};}if(options.animation===true){options.animation={};}if(options.animation.duration===undefined){options.animation.duration=1000;}// default duration
if(options.animation.easingFunction===undefined){options.animation.easingFunction="easeInOutQuad";}// default easing function
this.animateView(options);}/**
   *
   * @param {object} options  |  options.offset   = {x:number, y:number}   // offset from the center in DOM pixels
   *                          |  options.time     = number                 // animation time in milliseconds
   *                          |  options.scale    = number                 // scale to animate to
   *                          |  options.position = {x:number, y:number}   // position to animate to
   *                          |  options.easingFunction = String           // linear, easeInQuad, easeOutQuad, easeInOutQuad,
   *                                                                       // easeInCubic, easeOutCubic, easeInOutCubic,
   *                                                                       // easeInQuart, easeOutQuart, easeInOutQuart,
   *                                                                       // easeInQuint, easeOutQuint, easeInOutQuint
   */animateView(options){if(options===undefined){return;}this.animationEasingFunction=options.animation.easingFunction;// release if something focussed on the node
this.releaseNode();if(options.locked===true){this.lockedOnNodeId=options.lockedOnNode;this.lockedOnNodeOffset=options.offset;}// forcefully complete the old animation if it was still running
if(this.easingTime!=0){this._transitionRedraw(true);// by setting easingtime to 1, we finish the animation.
}this.sourceScale=this.body.view.scale;this.sourceTranslation=this.body.view.translation;this.targetScale=options.scale;// set the scale so the viewCenter is based on the correct zoom level. This is overridden in the transitionRedraw
// but at least then we'll have the target transition
this.body.view.scale=this.targetScale;const viewCenter=this.canvas.DOMtoCanvas({x:0.5*this.canvas.frame.canvas.clientWidth,y:0.5*this.canvas.frame.canvas.clientHeight});const distanceFromCenter={// offset from view, distance view has to change by these x and y to center the node
x:viewCenter.x-options.position.x,y:viewCenter.y-options.position.y};this.targetTranslation={x:this.sourceTranslation.x+distanceFromCenter.x*this.targetScale+options.offset.x,y:this.sourceTranslation.y+distanceFromCenter.y*this.targetScale+options.offset.y};// if the time is set to 0, don't do an animation
if(options.animation.duration===0){if(this.lockedOnNodeId!=undefined){var _context3;this.viewFunction=_bindInstanceProperty(_context3=this._lockedRedraw).call(_context3,this);this.body.emitter.on("initRedraw",this.viewFunction);}else {this.body.view.scale=this.targetScale;this.body.view.translation=this.targetTranslation;this.body.emitter.emit("_requestRedraw");}}else {var _context4;this.animationSpeed=1/(60*options.animation.duration*0.001)||1/60;// 60 for 60 seconds, 0.001 for milli's
this.animationEasingFunction=options.animation.easingFunction;this.viewFunction=_bindInstanceProperty(_context4=this._transitionRedraw).call(_context4,this);this.body.emitter.on("initRedraw",this.viewFunction);this.body.emitter.emit("_startRendering");}}/**
   * used to animate smoothly by hijacking the redraw function.
   * @private
   */_lockedRedraw(){const nodePosition={x:this.body.nodes[this.lockedOnNodeId].x,y:this.body.nodes[this.lockedOnNodeId].y};const viewCenter=this.canvas.DOMtoCanvas({x:0.5*this.canvas.frame.canvas.clientWidth,y:0.5*this.canvas.frame.canvas.clientHeight});const distanceFromCenter={// offset from view, distance view has to change by these x and y to center the node
x:viewCenter.x-nodePosition.x,y:viewCenter.y-nodePosition.y};const sourceTranslation=this.body.view.translation;const targetTranslation={x:sourceTranslation.x+distanceFromCenter.x*this.body.view.scale+this.lockedOnNodeOffset.x,y:sourceTranslation.y+distanceFromCenter.y*this.body.view.scale+this.lockedOnNodeOffset.y};this.body.view.translation=targetTranslation;}/**
   * Resets state of a locked on Node
   */releaseNode(){if(this.lockedOnNodeId!==undefined&&this.viewFunction!==undefined){this.body.emitter.off("initRedraw",this.viewFunction);this.lockedOnNodeId=undefined;this.lockedOnNodeOffset=undefined;}}/**
   * @param {boolean} [finished]
   * @private
   */_transitionRedraw(){let finished=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;this.easingTime+=this.animationSpeed;this.easingTime=finished===true?1.0:this.easingTime;const progress=easingFunctions[this.animationEasingFunction](this.easingTime);this.body.view.scale=this.sourceScale+(this.targetScale-this.sourceScale)*progress;this.body.view.translation={x:this.sourceTranslation.x+(this.targetTranslation.x-this.sourceTranslation.x)*progress,y:this.sourceTranslation.y+(this.targetTranslation.y-this.sourceTranslation.y)*progress};// cleanup
if(this.easingTime>=1.0){this.body.emitter.off("initRedraw",this.viewFunction);this.easingTime=0;if(this.lockedOnNodeId!=undefined){var _context5;this.viewFunction=_bindInstanceProperty(_context5=this._lockedRedraw).call(_context5,this);this.body.emitter.on("initRedraw",this.viewFunction);}this.body.emitter.emit("animationFinished");}}/**
   *
   * @returns {number}
   */getScale(){return this.body.view.scale;}/**
   *
   * @returns {{x: number, y: number}}
   */getViewPosition(){return this.canvas.DOMtoCanvas({x:0.5*this.canvas.frame.canvas.clientWidth,y:0.5*this.canvas.frame.canvas.clientHeight});}}/**
 * Created by Alex on 11/6/2014.
 */function keycharm(options){var preventDefault=options&&options.preventDefault||false;var container=options&&options.container||window;var _exportFunctions={};var _bound={keydown:{},keyup:{}};var _keys={};var i;// a - z
for(i=97;i<=122;i++){_keys[String.fromCharCode(i)]={code:65+(i-97),shift:false};}// A - Z
for(i=65;i<=90;i++){_keys[String.fromCharCode(i)]={code:i,shift:true};}// 0 - 9
for(i=0;i<=9;i++){_keys[''+i]={code:48+i,shift:false};}// F1 - F12
for(i=1;i<=12;i++){_keys['F'+i]={code:111+i,shift:false};}// num0 - num9
for(i=0;i<=9;i++){_keys['num'+i]={code:96+i,shift:false};}// numpad misc
_keys['num*']={code:106,shift:false};_keys['num+']={code:107,shift:false};_keys['num-']={code:109,shift:false};_keys['num/']={code:111,shift:false};_keys['num.']={code:110,shift:false};// arrows
_keys['left']={code:37,shift:false};_keys['up']={code:38,shift:false};_keys['right']={code:39,shift:false};_keys['down']={code:40,shift:false};// extra keys
_keys['space']={code:32,shift:false};_keys['enter']={code:13,shift:false};_keys['shift']={code:16,shift:undefined};_keys['esc']={code:27,shift:false};_keys['backspace']={code:8,shift:false};_keys['tab']={code:9,shift:false};_keys['ctrl']={code:17,shift:false};_keys['alt']={code:18,shift:false};_keys['delete']={code:46,shift:false};_keys['pageup']={code:33,shift:false};_keys['pagedown']={code:34,shift:false};// symbols
_keys['=']={code:187,shift:false};_keys['-']={code:189,shift:false};_keys[']']={code:221,shift:false};_keys['[']={code:219,shift:false};var down=function(event){handleEvent(event,'keydown');};var up=function(event){handleEvent(event,'keyup');};// handle the actualy bound key with the event
var handleEvent=function(event,type){if(_bound[type][event.keyCode]!==undefined){var bound=_bound[type][event.keyCode];for(var i=0;i<bound.length;i++){if(bound[i].shift===undefined){bound[i].fn(event);}else if(bound[i].shift==true&&event.shiftKey==true){bound[i].fn(event);}else if(bound[i].shift==false&&event.shiftKey==false){bound[i].fn(event);}}if(preventDefault==true){event.preventDefault();}}};// bind a key to a callback
_exportFunctions.bind=function(key,callback,type){if(type===undefined){type='keydown';}if(_keys[key]===undefined){throw new Error("unsupported key: "+key);}if(_bound[type][_keys[key].code]===undefined){_bound[type][_keys[key].code]=[];}_bound[type][_keys[key].code].push({fn:callback,shift:_keys[key].shift});};// bind all keys to a call back (demo purposes)
_exportFunctions.bindAll=function(callback,type){if(type===undefined){type='keydown';}for(var key in _keys){if(_keys.hasOwnProperty(key)){_exportFunctions.bind(key,callback,type);}}};// get the key label from an event
_exportFunctions.getKey=function(event){for(var key in _keys){if(_keys.hasOwnProperty(key)){if(event.shiftKey==true&&_keys[key].shift==true&&event.keyCode==_keys[key].code){return key;}else if(event.shiftKey==false&&_keys[key].shift==false&&event.keyCode==_keys[key].code){return key;}else if(event.keyCode==_keys[key].code&&key=='shift'){return key;}}}return "unknown key, currently not supported";};// unbind either a specific callback from a key or all of them (by leaving callback undefined)
_exportFunctions.unbind=function(key,callback,type){if(type===undefined){type='keydown';}if(_keys[key]===undefined){throw new Error("unsupported key: "+key);}if(callback!==undefined){var newBindings=[];var bound=_bound[type][_keys[key].code];if(bound!==undefined){for(var i=0;i<bound.length;i++){if(!(bound[i].fn==callback&&bound[i].shift==_keys[key].shift)){newBindings.push(_bound[type][_keys[key].code][i]);}}}_bound[type][_keys[key].code]=newBindings;}else {_bound[type][_keys[key].code]=[];}};// reset all bound variables.
_exportFunctions.reset=function(){_bound={keydown:{},keyup:{}};};// unbind all listeners and reset all variables.
_exportFunctions.destroy=function(){_bound={keydown:{},keyup:{}};container.removeEventListener('keydown',down,true);container.removeEventListener('keyup',up,true);};// create listeners.
container.addEventListener('keydown',down,true);container.addEventListener('keyup',up,true);// return the public functions.
return _exportFunctions;}/**
 * Navigation Handler
 */class NavigationHandler{/**
   * @param {object} body
   * @param {Canvas} canvas
   */constructor(body,canvas){this.body=body;this.canvas=canvas;this.iconsCreated=false;this.navigationHammers=[];this.boundFunctions={};this.touchTime=0;this.activated=false;this.body.emitter.on("activate",()=>{this.activated=true;this.configureKeyboardBindings();});this.body.emitter.on("deactivate",()=>{this.activated=false;this.configureKeyboardBindings();});this.body.emitter.on("destroy",()=>{if(this.keycharm!==undefined){this.keycharm.destroy();}});this.options={};}/**
   *
   * @param {object} options
   */setOptions(options){if(options!==undefined){this.options=options;this.create();}}/**
   * Creates or refreshes navigation and sets key bindings
   */create(){if(this.options.navigationButtons===true){if(this.iconsCreated===false){this.loadNavigationElements();}}else if(this.iconsCreated===true){this.cleanNavigation();}this.configureKeyboardBindings();}/**
   * Cleans up previous navigation items
   */cleanNavigation(){// clean hammer bindings
if(this.navigationHammers.length!=0){for(let i=0;i<this.navigationHammers.length;i++){this.navigationHammers[i].destroy();}this.navigationHammers=[];}// clean up previous navigation items
if(this.navigationDOM&&this.navigationDOM["wrapper"]&&this.navigationDOM["wrapper"].parentNode){this.navigationDOM["wrapper"].parentNode.removeChild(this.navigationDOM["wrapper"]);}this.iconsCreated=false;}/**
   * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation
   * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent
   * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false.
   * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas.
   * @private
   */loadNavigationElements(){this.cleanNavigation();this.navigationDOM={};const navigationDivs=["up","down","left","right","zoomIn","zoomOut","zoomExtends"];const navigationDivActions=["_moveUp","_moveDown","_moveLeft","_moveRight","_zoomIn","_zoomOut","_fit"];this.navigationDOM["wrapper"]=document.createElement("div");this.navigationDOM["wrapper"].className="vis-navigation";this.canvas.frame.appendChild(this.navigationDOM["wrapper"]);for(let i=0;i<navigationDivs.length;i++){this.navigationDOM[navigationDivs[i]]=document.createElement("div");this.navigationDOM[navigationDivs[i]].className="vis-button vis-"+navigationDivs[i];this.navigationDOM["wrapper"].appendChild(this.navigationDOM[navigationDivs[i]]);const hammer=new Hammer(this.navigationDOM[navigationDivs[i]]);if(navigationDivActions[i]==="_fit"){var _context;onTouch(hammer,_bindInstanceProperty(_context=this._fit).call(_context,this));}else {var _context2;onTouch(hammer,_bindInstanceProperty(_context2=this.bindToRedraw).call(_context2,this,navigationDivActions[i]));}this.navigationHammers.push(hammer);}// use a hammer for the release so we do not require the one used in the rest of the network
// the one the rest uses can be overloaded by the manipulation system.
const hammerFrame=new Hammer(this.canvas.frame);onRelease(hammerFrame,()=>{this._stopMovement();});this.navigationHammers.push(hammerFrame);this.iconsCreated=true;}/**
   *
   * @param {string} action
   */bindToRedraw(action){if(this.boundFunctions[action]===undefined){var _context3;this.boundFunctions[action]=_bindInstanceProperty(_context3=this[action]).call(_context3,this);this.body.emitter.on("initRedraw",this.boundFunctions[action]);this.body.emitter.emit("_startRendering");}}/**
   *
   * @param {string} action
   */unbindFromRedraw(action){if(this.boundFunctions[action]!==undefined){this.body.emitter.off("initRedraw",this.boundFunctions[action]);this.body.emitter.emit("_stopRendering");delete this.boundFunctions[action];}}/**
   * this stops all movement induced by the navigation buttons
   * @private
   */_fit(){if(new Date().valueOf()-this.touchTime>700){// TODO: fix ugly hack to avoid hammer's double fireing of event (because we use release?)
this.body.emitter.emit("fit",{duration:700});this.touchTime=new Date().valueOf();}}/**
   * this stops all movement induced by the navigation buttons
   * @private
   */_stopMovement(){for(const boundAction in this.boundFunctions){if(Object.prototype.hasOwnProperty.call(this.boundFunctions,boundAction)){this.body.emitter.off("initRedraw",this.boundFunctions[boundAction]);this.body.emitter.emit("_stopRendering");}}this.boundFunctions={};}/**
   *
   * @private
   */_moveUp(){this.body.view.translation.y+=this.options.keyboard.speed.y;}/**
   *
   * @private
   */_moveDown(){this.body.view.translation.y-=this.options.keyboard.speed.y;}/**
   *
   * @private
   */_moveLeft(){this.body.view.translation.x+=this.options.keyboard.speed.x;}/**
   *
   * @private
   */_moveRight(){this.body.view.translation.x-=this.options.keyboard.speed.x;}/**
   *
   * @private
   */_zoomIn(){const scaleOld=this.body.view.scale;const scale=this.body.view.scale*(1+this.options.keyboard.speed.zoom);const translation=this.body.view.translation;const scaleFrac=scale/scaleOld;const tx=(1-scaleFrac)*this.canvas.canvasViewCenter.x+translation.x*scaleFrac;const ty=(1-scaleFrac)*this.canvas.canvasViewCenter.y+translation.y*scaleFrac;this.body.view.scale=scale;this.body.view.translation={x:tx,y:ty};this.body.emitter.emit("zoom",{direction:"+",scale:this.body.view.scale,pointer:null});}/**
   *
   * @private
   */_zoomOut(){const scaleOld=this.body.view.scale;const scale=this.body.view.scale/(1+this.options.keyboard.speed.zoom);const translation=this.body.view.translation;const scaleFrac=scale/scaleOld;const tx=(1-scaleFrac)*this.canvas.canvasViewCenter.x+translation.x*scaleFrac;const ty=(1-scaleFrac)*this.canvas.canvasViewCenter.y+translation.y*scaleFrac;this.body.view.scale=scale;this.body.view.translation={x:tx,y:ty};this.body.emitter.emit("zoom",{direction:"-",scale:this.body.view.scale,pointer:null});}/**
   * bind all keys using keycharm.
   */configureKeyboardBindings(){if(this.keycharm!==undefined){this.keycharm.destroy();}if(this.options.keyboard.enabled===true){if(this.options.keyboard.bindToWindow===true){this.keycharm=keycharm({container:window,preventDefault:true});}else {this.keycharm=keycharm({container:this.canvas.frame,preventDefault:true});}this.keycharm.reset();if(this.activated===true){var _context4,_context5,_context6,_context7,_context8,_context9,_context0,_context1,_context10,_context11,_context12,_context13,_context14,_context15,_context16,_context17,_context18,_context19,_context20,_context21,_context22,_context23,_context24,_context25;_bindInstanceProperty(_context4=this.keycharm).call(_context4,"up",()=>{this.bindToRedraw("_moveUp");},"keydown");_bindInstanceProperty(_context5=this.keycharm).call(_context5,"down",()=>{this.bindToRedraw("_moveDown");},"keydown");_bindInstanceProperty(_context6=this.keycharm).call(_context6,"left",()=>{this.bindToRedraw("_moveLeft");},"keydown");_bindInstanceProperty(_context7=this.keycharm).call(_context7,"right",()=>{this.bindToRedraw("_moveRight");},"keydown");_bindInstanceProperty(_context8=this.keycharm).call(_context8,"=",()=>{this.bindToRedraw("_zoomIn");},"keydown");_bindInstanceProperty(_context9=this.keycharm).call(_context9,"num+",()=>{this.bindToRedraw("_zoomIn");},"keydown");_bindInstanceProperty(_context0=this.keycharm).call(_context0,"num-",()=>{this.bindToRedraw("_zoomOut");},"keydown");_bindInstanceProperty(_context1=this.keycharm).call(_context1,"-",()=>{this.bindToRedraw("_zoomOut");},"keydown");_bindInstanceProperty(_context10=this.keycharm).call(_context10,"[",()=>{this.bindToRedraw("_zoomOut");},"keydown");_bindInstanceProperty(_context11=this.keycharm).call(_context11,"]",()=>{this.bindToRedraw("_zoomIn");},"keydown");_bindInstanceProperty(_context12=this.keycharm).call(_context12,"pageup",()=>{this.bindToRedraw("_zoomIn");},"keydown");_bindInstanceProperty(_context13=this.keycharm).call(_context13,"pagedown",()=>{this.bindToRedraw("_zoomOut");},"keydown");_bindInstanceProperty(_context14=this.keycharm).call(_context14,"up",()=>{this.unbindFromRedraw("_moveUp");},"keyup");_bindInstanceProperty(_context15=this.keycharm).call(_context15,"down",()=>{this.unbindFromRedraw("_moveDown");},"keyup");_bindInstanceProperty(_context16=this.keycharm).call(_context16,"left",()=>{this.unbindFromRedraw("_moveLeft");},"keyup");_bindInstanceProperty(_context17=this.keycharm).call(_context17,"right",()=>{this.unbindFromRedraw("_moveRight");},"keyup");_bindInstanceProperty(_context18=this.keycharm).call(_context18,"=",()=>{this.unbindFromRedraw("_zoomIn");},"keyup");_bindInstanceProperty(_context19=this.keycharm).call(_context19,"num+",()=>{this.unbindFromRedraw("_zoomIn");},"keyup");_bindInstanceProperty(_context20=this.keycharm).call(_context20,"num-",()=>{this.unbindFromRedraw("_zoomOut");},"keyup");_bindInstanceProperty(_context21=this.keycharm).call(_context21,"-",()=>{this.unbindFromRedraw("_zoomOut");},"keyup");_bindInstanceProperty(_context22=this.keycharm).call(_context22,"[",()=>{this.unbindFromRedraw("_zoomOut");},"keyup");_bindInstanceProperty(_context23=this.keycharm).call(_context23,"]",()=>{this.unbindFromRedraw("_zoomIn");},"keyup");_bindInstanceProperty(_context24=this.keycharm).call(_context24,"pageup",()=>{this.unbindFromRedraw("_zoomIn");},"keyup");_bindInstanceProperty(_context25=this.keycharm).call(_context25,"pagedown",()=>{this.unbindFromRedraw("_zoomOut");},"keyup");}}}}/**
 * Handler for interactions
 */class InteractionHandler{/**
   * @param {object} body
   * @param {Canvas} canvas
   * @param {SelectionHandler} selectionHandler
   */constructor(body,canvas,selectionHandler){var _context,_context2,_context3,_context4,_context5,_context6,_context7,_context8,_context9,_context0,_context1,_context10,_context11;this.body=body;this.canvas=canvas;this.selectionHandler=selectionHandler;this.navigationHandler=new NavigationHandler(body,canvas);// bind the events from hammer to functions in this object
this.body.eventListeners.onTap=_bindInstanceProperty(_context=this.onTap).call(_context,this);this.body.eventListeners.onTouch=_bindInstanceProperty(_context2=this.onTouch).call(_context2,this);this.body.eventListeners.onDoubleTap=_bindInstanceProperty(_context3=this.onDoubleTap).call(_context3,this);this.body.eventListeners.onHold=_bindInstanceProperty(_context4=this.onHold).call(_context4,this);this.body.eventListeners.onDragStart=_bindInstanceProperty(_context5=this.onDragStart).call(_context5,this);this.body.eventListeners.onDrag=_bindInstanceProperty(_context6=this.onDrag).call(_context6,this);this.body.eventListeners.onDragEnd=_bindInstanceProperty(_context7=this.onDragEnd).call(_context7,this);this.body.eventListeners.onMouseWheel=_bindInstanceProperty(_context8=this.onMouseWheel).call(_context8,this);this.body.eventListeners.onPinch=_bindInstanceProperty(_context9=this.onPinch).call(_context9,this);this.body.eventListeners.onMouseMove=_bindInstanceProperty(_context0=this.onMouseMove).call(_context0,this);this.body.eventListeners.onRelease=_bindInstanceProperty(_context1=this.onRelease).call(_context1,this);this.body.eventListeners.onContext=_bindInstanceProperty(_context10=this.onContext).call(_context10,this);this.touchTime=0;this.drag={};this.pinch={};this.popup=undefined;this.popupObj=undefined;this.popupTimer=undefined;this.body.functions.getPointer=_bindInstanceProperty(_context11=this.getPointer).call(_context11,this);this.options={};this.defaultOptions={dragNodes:true,dragView:true,hover:false,keyboard:{enabled:false,speed:{x:10,y:10,zoom:0.02},bindToWindow:true,autoFocus:true},navigationButtons:false,tooltipDelay:300,zoomView:true,zoomSpeed:1};_Object$assign(this.options,this.defaultOptions);this.bindEventListeners();}/**
   * Binds event listeners
   */bindEventListeners(){this.body.emitter.on("destroy",()=>{clearTimeout(this.popupTimer);delete this.body.functions.getPointer;});}/**
   *
   * @param {object} options
   */setOptions(options){if(options!==undefined){// extend all but the values in fields
const fields=["hideEdgesOnDrag","hideEdgesOnZoom","hideNodesOnDrag","keyboard","multiselect","selectable","selectConnectedEdges"];selectiveNotDeepExtend(fields,this.options,options);// merge the keyboard options in.
mergeOptions(this.options,options,"keyboard");if(options.tooltip){_Object$assign(this.options.tooltip,options.tooltip);if(options.tooltip.color){this.options.tooltip.color=parseColor(options.tooltip.color);}}}this.navigationHandler.setOptions(this.options);}/**
   * Get the pointer location from a touch location
   * @param {{x: number, y: number}} touch
   * @returns {{x: number, y: number}} pointer
   * @private
   */getPointer(touch){return {x:touch.x-getAbsoluteLeft(this.canvas.frame.canvas),y:touch.y-getAbsoluteTop(this.canvas.frame.canvas)};}/**
   * On start of a touch gesture, store the pointer
   * @param {Event}  event   The event
   * @private
   */onTouch(event){if(new Date().valueOf()-this.touchTime>50){this.drag.pointer=this.getPointer(event.center);this.drag.pinched=false;this.pinch.scale=this.body.view.scale;// to avoid double fireing of this event because we have two hammer instances. (on canvas and on frame)
this.touchTime=new Date().valueOf();}}/**
   * handle tap/click event: select/unselect a node
   * @param {Event} event
   * @private
   */onTap(event){const pointer=this.getPointer(event.center);const multiselect=this.selectionHandler.options.multiselect&&(event.changedPointers[0].ctrlKey||event.changedPointers[0].metaKey);this.checkSelectionChanges(pointer,multiselect);this.selectionHandler.commitAndEmit(pointer,event);this.selectionHandler.generateClickEvent("click",event,pointer);}/**
   * handle doubletap event
   * @param {Event} event
   * @private
   */onDoubleTap(event){const pointer=this.getPointer(event.center);this.selectionHandler.generateClickEvent("doubleClick",event,pointer);}/**
   * handle long tap event: multi select nodes
   * @param {Event} event
   * @private
   */onHold(event){const pointer=this.getPointer(event.center);const multiselect=this.selectionHandler.options.multiselect;this.checkSelectionChanges(pointer,multiselect);this.selectionHandler.commitAndEmit(pointer,event);this.selectionHandler.generateClickEvent("click",event,pointer);this.selectionHandler.generateClickEvent("hold",event,pointer);}/**
   * handle the release of the screen
   * @param {Event} event
   * @private
   */onRelease(event){if(new Date().valueOf()-this.touchTime>10){const pointer=this.getPointer(event.center);this.selectionHandler.generateClickEvent("release",event,pointer);// to avoid double fireing of this event because we have two hammer instances. (on canvas and on frame)
this.touchTime=new Date().valueOf();}}/**
   *
   * @param {Event} event
   */onContext(event){const pointer=this.getPointer({x:event.clientX,y:event.clientY});this.selectionHandler.generateClickEvent("oncontext",event,pointer);}/**
   * Select and deselect nodes depending current selection change.
   * @param {{x: number, y: number}} pointer
   * @param {boolean} [add]
   */checkSelectionChanges(pointer){let add=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(add===true){this.selectionHandler.selectAdditionalOnPoint(pointer);}else {this.selectionHandler.selectOnPoint(pointer);}}/**
   * Remove all node and edge id's from the first set that are present in the second one.
   * @param {{nodes: Array.<Node>, edges: Array.<vis.Edge>}} firstSet
   * @param {{nodes: Array.<Node>, edges: Array.<vis.Edge>}} secondSet
   * @returns {{nodes: Array.<Node>, edges: Array.<vis.Edge>}}
   * @private
   */_determineDifference(firstSet,secondSet){const arrayDiff=function(firstArr,secondArr){const result=[];for(let i=0;i<firstArr.length;i++){const value=firstArr[i];if(_indexOfInstanceProperty(secondArr).call(secondArr,value)===-1){result.push(value);}}return result;};return {nodes:arrayDiff(firstSet.nodes,secondSet.nodes),edges:arrayDiff(firstSet.edges,secondSet.edges)};}/**
   * This function is called by onDragStart.
   * It is separated out because we can then overload it for the datamanipulation system.
   * @param {Event} event
   * @private
   */onDragStart(event){// if already dragging, do not start
// this can happen on touch screens with multiple fingers
if(this.drag.dragging){return;}//in case the touch event was triggered on an external div, do the initial touch now.
if(this.drag.pointer===undefined){this.onTouch(event);}// note: drag.pointer is set in onTouch to get the initial touch location
const node=this.selectionHandler.getNodeAt(this.drag.pointer);this.drag.dragging=true;this.drag.selection=[];this.drag.translation=_Object$assign({},this.body.view.translation);// copy the object
this.drag.nodeId=undefined;if(event.srcEvent.shiftKey){this.body.selectionBox.show=true;const pointer=this.getPointer(event.center);this.body.selectionBox.position.start={x:this.canvas._XconvertDOMtoCanvas(pointer.x),y:this.canvas._YconvertDOMtoCanvas(pointer.y)};this.body.selectionBox.position.end={x:this.canvas._XconvertDOMtoCanvas(pointer.x),y:this.canvas._YconvertDOMtoCanvas(pointer.y)};}else if(node!==undefined&&this.options.dragNodes===true){this.drag.nodeId=node.id;// select the clicked node if not yet selected
if(node.isSelected()===false){this.selectionHandler.setSelection({nodes:[node.id]});}// after select to contain the node
this.selectionHandler.generateClickEvent("dragStart",event,this.drag.pointer);// create an array with the selected nodes and their original location and status
for(const node of this.selectionHandler.getSelectedNodes()){const s={id:node.id,node:node,// store original x, y, xFixed and yFixed, make the node temporarily Fixed
x:node.x,y:node.y,xFixed:node.options.fixed.x,yFixed:node.options.fixed.y};node.options.fixed.x=true;node.options.fixed.y=true;this.drag.selection.push(s);}}else {// fallback if no node is selected and thus the view is dragged.
this.selectionHandler.generateClickEvent("dragStart",event,this.drag.pointer,undefined,true);}}/**
   * handle drag event
   * @param {Event} event
   * @private
   */onDrag(event){if(this.drag.pinched===true){return;}// remove the focus on node if it is focussed on by the focusOnNode
this.body.emitter.emit("unlockNode");const pointer=this.getPointer(event.center);const selection=this.drag.selection;if(selection&&selection.length&&this.options.dragNodes===true){this.selectionHandler.generateClickEvent("dragging",event,pointer);// calculate delta's and new location
const deltaX=pointer.x-this.drag.pointer.x;const deltaY=pointer.y-this.drag.pointer.y;// update position of all selected nodes
_forEachInstanceProperty(selection).call(selection,selection=>{const node=selection.node;// only move the node if it was not fixed initially
if(selection.xFixed===false){node.x=this.canvas._XconvertDOMtoCanvas(this.canvas._XconvertCanvasToDOM(selection.x)+deltaX);}// only move the node if it was not fixed initially
if(selection.yFixed===false){node.y=this.canvas._YconvertDOMtoCanvas(this.canvas._YconvertCanvasToDOM(selection.y)+deltaY);}});// start the simulation of the physics
this.body.emitter.emit("startSimulation");}else {// create selection box
if(event.srcEvent.shiftKey){this.selectionHandler.generateClickEvent("dragging",event,pointer,undefined,true);// if the drag was not started properly because the click started outside the network div, start it now.
if(this.drag.pointer===undefined){this.onDragStart(event);return;}this.body.selectionBox.position.end={x:this.canvas._XconvertDOMtoCanvas(pointer.x),y:this.canvas._YconvertDOMtoCanvas(pointer.y)};this.body.emitter.emit("_requestRedraw");}// move the network
if(this.options.dragView===true&&!event.srcEvent.shiftKey){this.selectionHandler.generateClickEvent("dragging",event,pointer,undefined,true);// if the drag was not started properly because the click started outside the network div, start it now.
if(this.drag.pointer===undefined){this.onDragStart(event);return;}const diffX=pointer.x-this.drag.pointer.x;const diffY=pointer.y-this.drag.pointer.y;this.body.view.translation={x:this.drag.translation.x+diffX,y:this.drag.translation.y+diffY};this.body.emitter.emit("_requestRedraw");}}}/**
   * handle drag start event
   * @param {Event} event
   * @private
   */onDragEnd(event){this.drag.dragging=false;if(this.body.selectionBox.show){var _context12;this.body.selectionBox.show=false;const selectionBoxPosition=this.body.selectionBox.position;const selectionBoxPositionMinMax={minX:Math.min(selectionBoxPosition.start.x,selectionBoxPosition.end.x),minY:Math.min(selectionBoxPosition.start.y,selectionBoxPosition.end.y),maxX:Math.max(selectionBoxPosition.start.x,selectionBoxPosition.end.x),maxY:Math.max(selectionBoxPosition.start.y,selectionBoxPosition.end.y)};const toBeSelectedNodes=_filterInstanceProperty(_context12=this.body.nodeIndices).call(_context12,nodeId=>{const node=this.body.nodes[nodeId];return node.x>=selectionBoxPositionMinMax.minX&&node.x<=selectionBoxPositionMinMax.maxX&&node.y>=selectionBoxPositionMinMax.minY&&node.y<=selectionBoxPositionMinMax.maxY;});_forEachInstanceProperty(toBeSelectedNodes).call(toBeSelectedNodes,nodeId=>this.selectionHandler.selectObject(this.body.nodes[nodeId]));const pointer=this.getPointer(event.center);this.selectionHandler.commitAndEmit(pointer,event);this.selectionHandler.generateClickEvent("dragEnd",event,this.getPointer(event.center),undefined,true);this.body.emitter.emit("_requestRedraw");}else {const selection=this.drag.selection;if(selection&&selection.length){_forEachInstanceProperty(selection).call(selection,function(s){// restore original xFixed and yFixed
s.node.options.fixed.x=s.xFixed;s.node.options.fixed.y=s.yFixed;});this.selectionHandler.generateClickEvent("dragEnd",event,this.getPointer(event.center));this.body.emitter.emit("startSimulation");}else {this.selectionHandler.generateClickEvent("dragEnd",event,this.getPointer(event.center),undefined,true);this.body.emitter.emit("_requestRedraw");}}}/**
   * Handle pinch event
   * @param {Event}  event   The event
   * @private
   */onPinch(event){const pointer=this.getPointer(event.center);this.drag.pinched=true;if(this.pinch["scale"]===undefined){this.pinch.scale=1;}// TODO: enabled moving while pinching?
const scale=this.pinch.scale*event.scale;this.zoom(scale,pointer);}/**
   * Zoom the network in or out
   * @param {number} scale a number around 1, and between 0.01 and 10
   * @param {{x: number, y: number}} pointer    Position on screen
   * @private
   */zoom(scale,pointer){if(this.options.zoomView===true){const scaleOld=this.body.view.scale;if(scale<0.00001){scale=0.00001;}if(scale>10){scale=10;}let preScaleDragPointer=undefined;if(this.drag!==undefined){if(this.drag.dragging===true){preScaleDragPointer=this.canvas.DOMtoCanvas(this.drag.pointer);}}// + this.canvas.frame.canvas.clientHeight / 2
const translation=this.body.view.translation;const scaleFrac=scale/scaleOld;const tx=(1-scaleFrac)*pointer.x+translation.x*scaleFrac;const ty=(1-scaleFrac)*pointer.y+translation.y*scaleFrac;this.body.view.scale=scale;this.body.view.translation={x:tx,y:ty};if(preScaleDragPointer!=undefined){const postScaleDragPointer=this.canvas.canvasToDOM(preScaleDragPointer);this.drag.pointer.x=postScaleDragPointer.x;this.drag.pointer.y=postScaleDragPointer.y;}this.body.emitter.emit("_requestRedraw");if(scaleOld<scale){this.body.emitter.emit("zoom",{direction:"+",scale:this.body.view.scale,pointer:pointer});}else {this.body.emitter.emit("zoom",{direction:"-",scale:this.body.view.scale,pointer:pointer});}}}/**
   * Event handler for mouse wheel event, used to zoom the timeline
   * See http://adomas.org/javascript-mouse-wheel/
   * https://github.com/EightMedia/hammer.js/issues/256
   * @param {MouseEvent}  event
   * @private
   */onMouseWheel(event){if(this.options.zoomView===true){// If delta is nonzero, handle it.
// Basically, delta is now positive if wheel was scrolled up,
// and negative, if wheel was scrolled down.
if(event.deltaY!==0){// calculate the new scale
let scale=this.body.view.scale;scale*=1+(event.deltaY<0?1:-1)*(this.options.zoomSpeed*0.1);// calculate the pointer location
const pointer=this.getPointer({x:event.clientX,y:event.clientY});// apply the new scale
this.zoom(scale,pointer);}// Prevent default actions caused by mouse wheel.
event.preventDefault();}}/**
   * Mouse move handler for checking whether the title moves over a node with a title.
   * @param  {Event} event
   * @private
   */onMouseMove(event){const pointer=this.getPointer({x:event.clientX,y:event.clientY});let popupVisible=false;// check if the previously selected node is still selected
if(this.popup!==undefined){if(this.popup.hidden===false){this._checkHidePopup(pointer);}// if the popup was not hidden above
if(this.popup.hidden===false){popupVisible=true;this.popup.setPosition(pointer.x+3,pointer.y-5);this.popup.show();}}// if we bind the keyboard to the div, we have to highlight it to use it. This highlights it on mouse over.
if(this.options.keyboard.autoFocus&&this.options.keyboard.bindToWindow===false&&this.options.keyboard.enabled===true){this.canvas.frame.focus();}// start a timeout that will check if the mouse is positioned above an element
if(popupVisible===false){if(this.popupTimer!==undefined){clearInterval(this.popupTimer);// stop any running calculationTimer
this.popupTimer=undefined;}if(!this.drag.dragging){this.popupTimer=_setTimeout(()=>this._checkShowPopup(pointer),this.options.tooltipDelay);}}// adding hover highlights
if(this.options.hover===true){this.selectionHandler.hoverObject(event,pointer);}}/**
   * Check if there is an element on the given position in the network
   * (a node or edge). If so, and if this element has a title,
   * show a popup window with its title.
   * @param {{x:number, y:number}} pointer
   * @private
   */_checkShowPopup(pointer){const x=this.canvas._XconvertDOMtoCanvas(pointer.x);const y=this.canvas._YconvertDOMtoCanvas(pointer.y);const pointerObj={left:x,top:y,right:x,bottom:y};const previousPopupObjId=this.popupObj===undefined?undefined:this.popupObj.id;let nodeUnderCursor=false;let popupType="node";// check if a node is under the cursor.
if(this.popupObj===undefined){// search the nodes for overlap, select the top one in case of multiple nodes
const nodeIndices=this.body.nodeIndices;const nodes=this.body.nodes;let node;const overlappingNodes=[];for(let i=0;i<nodeIndices.length;i++){node=nodes[nodeIndices[i]];if(node.isOverlappingWith(pointerObj)===true){nodeUnderCursor=true;if(node.getTitle()!==undefined){overlappingNodes.push(nodeIndices[i]);}}}if(overlappingNodes.length>0){// if there are overlapping nodes, select the last one, this is the one which is drawn on top of the others
this.popupObj=nodes[overlappingNodes[overlappingNodes.length-1]];// if you hover over a node, the title of the edge is not supposed to be shown.
nodeUnderCursor=true;}}if(this.popupObj===undefined&&nodeUnderCursor===false){// search the edges for overlap
const edgeIndices=this.body.edgeIndices;const edges=this.body.edges;let edge;const overlappingEdges=[];for(let i=0;i<edgeIndices.length;i++){edge=edges[edgeIndices[i]];if(edge.isOverlappingWith(pointerObj)===true){if(edge.connected===true&&edge.getTitle()!==undefined){overlappingEdges.push(edgeIndices[i]);}}}if(overlappingEdges.length>0){this.popupObj=edges[overlappingEdges[overlappingEdges.length-1]];popupType="edge";}}if(this.popupObj!==undefined){// show popup message window
if(this.popupObj.id!==previousPopupObjId){if(this.popup===undefined){this.popup=new Popup(this.canvas.frame);}this.popup.popupTargetType=popupType;this.popup.popupTargetId=this.popupObj.id;// adjust a small offset such that the mouse cursor is located in the
// bottom left location of the popup, and you can easily move over the
// popup area
this.popup.setPosition(pointer.x+3,pointer.y-5);this.popup.setText(this.popupObj.getTitle());this.popup.show();this.body.emitter.emit("showPopup",this.popupObj.id);}}else {if(this.popup!==undefined){this.popup.hide();this.body.emitter.emit("hidePopup");}}}/**
   * Check if the popup must be hidden, which is the case when the mouse is no
   * longer hovering on the object
   * @param {{x:number, y:number}} pointer
   * @private
   */_checkHidePopup(pointer){const pointerObj=this.selectionHandler._pointerToPositionObject(pointer);let stillOnObj=false;if(this.popup.popupTargetType==="node"){if(this.body.nodes[this.popup.popupTargetId]!==undefined){stillOnObj=this.body.nodes[this.popup.popupTargetId].isOverlappingWith(pointerObj);// if the mouse is still one the node, we have to check if it is not also on one that is drawn on top of it.
// we initially only check stillOnObj because this is much faster.
if(stillOnObj===true){const overNode=this.selectionHandler.getNodeAt(pointer);stillOnObj=overNode===undefined?false:overNode.id===this.popup.popupTargetId;}}}else {if(this.selectionHandler.getNodeAt(pointer)===undefined){if(this.body.edges[this.popup.popupTargetId]!==undefined){stillOnObj=this.body.edges[this.popup.popupTargetId].isOverlappingWith(pointerObj);}}}if(stillOnObj===false){this.popupObj=undefined;this.popup.hide();this.body.emitter.emit("hidePopup");}}}var es_weakMap={};var es_weakMap_constructor={};var collectionWeak;var hasRequiredCollectionWeak;function requireCollectionWeak(){if(hasRequiredCollectionWeak)return collectionWeak;hasRequiredCollectionWeak=1;var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var defineBuiltIns=/*@__PURE__*/requireDefineBuiltIns();var getWeakData=/*@__PURE__*/requireInternalMetadata().getWeakData;var anInstance=/*@__PURE__*/requireAnInstance();var anObject=/*@__PURE__*/requireAnObject();var isNullOrUndefined=/*@__PURE__*/requireIsNullOrUndefined();var isObject=/*@__PURE__*/requireIsObject();var iterate=/*@__PURE__*/requireIterate();var ArrayIterationModule=/*@__PURE__*/requireArrayIteration();var hasOwn=/*@__PURE__*/requireHasOwnProperty();var InternalStateModule=/*@__PURE__*/requireInternalState();var setInternalState=InternalStateModule.set;var internalStateGetterFor=InternalStateModule.getterFor;var find=ArrayIterationModule.find;var findIndex=ArrayIterationModule.findIndex;var splice=uncurryThis([].splice);var id=0;// fallback for uncaught frozen keys
var uncaughtFrozenStore=function(state){return state.frozen||(state.frozen=new UncaughtFrozenStore());};var UncaughtFrozenStore=function(){this.entries=[];};var findUncaughtFrozen=function(store,key){return find(store.entries,function(it){return it[0]===key;});};UncaughtFrozenStore.prototype={get:function(key){var entry=findUncaughtFrozen(this,key);if(entry)return entry[1];},has:function(key){return !!findUncaughtFrozen(this,key);},set:function(key,value){var entry=findUncaughtFrozen(this,key);if(entry)entry[1]=value;else this.entries.push([key,value]);},'delete':function(key){var index=findIndex(this.entries,function(it){return it[0]===key;});if(~index)splice(this.entries,index,1);return !!~index;}};collectionWeak={getConstructor:function(wrapper,CONSTRUCTOR_NAME,IS_MAP,ADDER){var Constructor=wrapper(function(that,iterable){anInstance(that,Prototype);setInternalState(that,{type:CONSTRUCTOR_NAME,id:id++,frozen:null});if(!isNullOrUndefined(iterable))iterate(iterable,that[ADDER],{that:that,AS_ENTRIES:IS_MAP});});var Prototype=Constructor.prototype;var getInternalState=internalStateGetterFor(CONSTRUCTOR_NAME);var define=function(that,key,value){var state=getInternalState(that);var data=getWeakData(anObject(key),true);if(data===true)uncaughtFrozenStore(state).set(key,value);else data[state.id]=value;return that;};defineBuiltIns(Prototype,{// `{ WeakMap, WeakSet }.prototype.delete(key)` methods
// https://tc39.es/ecma262/#sec-weakmap.prototype.delete
// https://tc39.es/ecma262/#sec-weakset.prototype.delete
'delete':function(key){var state=getInternalState(this);if(!isObject(key))return false;var data=getWeakData(key);if(data===true)return uncaughtFrozenStore(state)['delete'](key);return data&&hasOwn(data,state.id)&&delete data[state.id];},// `{ WeakMap, WeakSet }.prototype.has(key)` methods
// https://tc39.es/ecma262/#sec-weakmap.prototype.has
// https://tc39.es/ecma262/#sec-weakset.prototype.has
has:function has(key){var state=getInternalState(this);if(!isObject(key))return false;var data=getWeakData(key);if(data===true)return uncaughtFrozenStore(state).has(key);return data&&hasOwn(data,state.id);}});defineBuiltIns(Prototype,IS_MAP?{// `WeakMap.prototype.get(key)` method
// https://tc39.es/ecma262/#sec-weakmap.prototype.get
get:function get(key){var state=getInternalState(this);if(isObject(key)){var data=getWeakData(key);if(data===true)return uncaughtFrozenStore(state).get(key);if(data)return data[state.id];}},// `WeakMap.prototype.set(key, value)` method
// https://tc39.es/ecma262/#sec-weakmap.prototype.set
set:function set(key,value){return define(this,key,value);}}:{// `WeakSet.prototype.add(value)` method
// https://tc39.es/ecma262/#sec-weakset.prototype.add
add:function add(value){return define(this,value,true);}});return Constructor;}};return collectionWeak;}var hasRequiredEs_weakMap_constructor;function requireEs_weakMap_constructor(){if(hasRequiredEs_weakMap_constructor)return es_weakMap_constructor;hasRequiredEs_weakMap_constructor=1;var FREEZING=/*@__PURE__*/requireFreezing();var globalThis=/*@__PURE__*/requireGlobalThis();var uncurryThis=/*@__PURE__*/requireFunctionUncurryThis();var defineBuiltIns=/*@__PURE__*/requireDefineBuiltIns();var InternalMetadataModule=/*@__PURE__*/requireInternalMetadata();var collection=/*@__PURE__*/requireCollection();var collectionWeak=/*@__PURE__*/requireCollectionWeak();var isObject=/*@__PURE__*/requireIsObject();var enforceInternalState=/*@__PURE__*/requireInternalState().enforce;var fails=/*@__PURE__*/requireFails();var NATIVE_WEAK_MAP=/*@__PURE__*/requireWeakMapBasicDetection();var $Object=Object;// eslint-disable-next-line es/no-array-isarray -- safe
var isArray=Array.isArray;// eslint-disable-next-line es/no-object-isextensible -- safe
var isExtensible=$Object.isExtensible;// eslint-disable-next-line es/no-object-isfrozen -- safe
var isFrozen=$Object.isFrozen;// eslint-disable-next-line es/no-object-issealed -- safe
var isSealed=$Object.isSealed;// eslint-disable-next-line es/no-object-freeze -- safe
var freeze=$Object.freeze;// eslint-disable-next-line es/no-object-seal -- safe
var seal=$Object.seal;var IS_IE11=!globalThis.ActiveXObject&&'ActiveXObject'in globalThis;var InternalWeakMap;var wrapper=function(init){return function WeakMap(){return init(this,arguments.length?arguments[0]:undefined);};};// `WeakMap` constructor
// https://tc39.es/ecma262/#sec-weakmap-constructor
var $WeakMap=collection('WeakMap',wrapper,collectionWeak);var WeakMapPrototype=$WeakMap.prototype;var nativeSet=uncurryThis(WeakMapPrototype.set);// Chakra Edge bug: adding frozen arrays to WeakMap unfreeze them
var hasMSEdgeFreezingBug=function(){return FREEZING&&fails(function(){var frozenArray=freeze([]);nativeSet(new $WeakMap(),frozenArray,1);return !isFrozen(frozenArray);});};// IE11 WeakMap frozen keys fix
// We can't use feature detection because it crash some old IE builds
// https://github.com/zloirock/core-js/issues/485
if(NATIVE_WEAK_MAP)if(IS_IE11){InternalWeakMap=collectionWeak.getConstructor(wrapper,'WeakMap',true);InternalMetadataModule.enable();var nativeDelete=uncurryThis(WeakMapPrototype['delete']);var nativeHas=uncurryThis(WeakMapPrototype.has);var nativeGet=uncurryThis(WeakMapPrototype.get);defineBuiltIns(WeakMapPrototype,{'delete':function(key){if(isObject(key)&&!isExtensible(key)){var state=enforceInternalState(this);if(!state.frozen)state.frozen=new InternalWeakMap();return nativeDelete(this,key)||state.frozen['delete'](key);}return nativeDelete(this,key);},has:function has(key){if(isObject(key)&&!isExtensible(key)){var state=enforceInternalState(this);if(!state.frozen)state.frozen=new InternalWeakMap();return nativeHas(this,key)||state.frozen.has(key);}return nativeHas(this,key);},get:function get(key){if(isObject(key)&&!isExtensible(key)){var state=enforceInternalState(this);if(!state.frozen)state.frozen=new InternalWeakMap();return nativeHas(this,key)?nativeGet(this,key):state.frozen.get(key);}return nativeGet(this,key);},set:function set(key,value){if(isObject(key)&&!isExtensible(key)){var state=enforceInternalState(this);if(!state.frozen)state.frozen=new InternalWeakMap();nativeHas(this,key)?nativeSet(this,key,value):state.frozen.set(key,value);}else nativeSet(this,key,value);return this;}});// Chakra Edge frozen keys fix
}else if(hasMSEdgeFreezingBug()){defineBuiltIns(WeakMapPrototype,{set:function set(key,value){var arrayIntegrityLevel;if(isArray(key)){if(isFrozen(key))arrayIntegrityLevel=freeze;else if(isSealed(key))arrayIntegrityLevel=seal;}nativeSet(this,key,value);if(arrayIntegrityLevel)arrayIntegrityLevel(key);return this;}});}return es_weakMap_constructor;}var hasRequiredEs_weakMap;function requireEs_weakMap(){if(hasRequiredEs_weakMap)return es_weakMap;hasRequiredEs_weakMap=1;// TODO: Remove this module from `core-js@4` since it's replaced to module below
requireEs_weakMap_constructor();return es_weakMap;}var weakMap$2;var hasRequiredWeakMap$2;function requireWeakMap$2(){if(hasRequiredWeakMap$2)return weakMap$2;hasRequiredWeakMap$2=1;requireEs_array_iterator();requireEs_weakMap();var path=/*@__PURE__*/requirePath();weakMap$2=path.WeakMap;return weakMap$2;}var weakMap$1;var hasRequiredWeakMap$1;function requireWeakMap$1(){if(hasRequiredWeakMap$1)return weakMap$1;hasRequiredWeakMap$1=1;var parent=/*@__PURE__*/requireWeakMap$2();requireWeb_domCollections_iterator();weakMap$1=parent;return weakMap$1;}var weakMap;var hasRequiredWeakMap;function requireWeakMap(){if(hasRequiredWeakMap)return weakMap;hasRequiredWeakMap=1;weakMap=/*@__PURE__*/requireWeakMap$1();return weakMap;}var weakMapExports=requireWeakMap();var _WeakMap=/*@__PURE__*/getDefaultExportFromCjs(weakMapExports);function _classPrivateFieldInitSpec(e,t,a){_checkPrivateRedeclaration(e,t),t.set(e,a);}function _checkPrivateRedeclaration(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object");}function _classPrivateFieldSet(s,a,r){return s.set(_assertClassBrand(s,a),r),r;}function _classPrivateFieldGet(s,a){return s.get(_assertClassBrand(s,a));}function _assertClassBrand(e,t,n){if("function"==typeof e?e===t:e.has(t))return arguments.length<3?t:n;throw new TypeError("Private element is not present on this object");}/**
 * @param prev
 * @param next
 */function diffSets(prev,next){const diff=new _Set();for(const item of next){if(!prev.has(item)){diff.add(item);}}return diff;}var _previousSelection=/*#__PURE__*/new _WeakMap();var _selection=/*#__PURE__*/new _WeakMap();class SingleTypeSelectionAccumulator{constructor(){_classPrivateFieldInitSpec(this,_previousSelection,new _Set());_classPrivateFieldInitSpec(this,_selection,new _Set());}get size(){return _classPrivateFieldGet(_selection,this).size;}add(){for(var _len=arguments.length,items=new Array(_len),_key=0;_key<_len;_key++){items[_key]=arguments[_key];}for(const item of items){_classPrivateFieldGet(_selection,this).add(item);}}delete(){for(var _len2=arguments.length,items=new Array(_len2),_key2=0;_key2<_len2;_key2++){items[_key2]=arguments[_key2];}for(const item of items){_classPrivateFieldGet(_selection,this).delete(item);}}clear(){_classPrivateFieldGet(_selection,this).clear();}getSelection(){return [..._classPrivateFieldGet(_selection,this)];}getChanges(){return {added:[...diffSets(_classPrivateFieldGet(_previousSelection,this),_classPrivateFieldGet(_selection,this))],deleted:[...diffSets(_classPrivateFieldGet(_selection,this),_classPrivateFieldGet(_previousSelection,this))],previous:[...new _Set(_classPrivateFieldGet(_previousSelection,this))],current:[...new _Set(_classPrivateFieldGet(_selection,this))]};}commit(){const changes=this.getChanges();_classPrivateFieldSet(_previousSelection,this,_classPrivateFieldGet(_selection,this));_classPrivateFieldSet(_selection,this,new _Set(_classPrivateFieldGet(_previousSelection,this)));for(const item of changes.added){item.select();}for(const item of changes.deleted){item.unselect();}return changes;}}var _nodes=/*#__PURE__*/new _WeakMap();var _edges=/*#__PURE__*/new _WeakMap();var _commitHandler=/*#__PURE__*/new _WeakMap();class SelectionAccumulator{constructor(){let commitHandler=arguments.length>0&&arguments[0]!==undefined?arguments[0]:()=>{};_classPrivateFieldInitSpec(this,_nodes,new SingleTypeSelectionAccumulator());_classPrivateFieldInitSpec(this,_edges,new SingleTypeSelectionAccumulator());_classPrivateFieldInitSpec(this,_commitHandler,void 0);_classPrivateFieldSet(_commitHandler,this,commitHandler);}get sizeNodes(){return _classPrivateFieldGet(_nodes,this).size;}get sizeEdges(){return _classPrivateFieldGet(_edges,this).size;}getNodes(){return _classPrivateFieldGet(_nodes,this).getSelection();}getEdges(){return _classPrivateFieldGet(_edges,this).getSelection();}addNodes(){_classPrivateFieldGet(_nodes,this).add(...arguments);}addEdges(){_classPrivateFieldGet(_edges,this).add(...arguments);}deleteNodes(node){_classPrivateFieldGet(_nodes,this).delete(node);}deleteEdges(edge){_classPrivateFieldGet(_edges,this).delete(edge);}clear(){_classPrivateFieldGet(_nodes,this).clear();_classPrivateFieldGet(_edges,this).clear();}commit(){const summary={nodes:_classPrivateFieldGet(_nodes,this).commit(),edges:_classPrivateFieldGet(_edges,this).commit()};for(var _len3=arguments.length,rest=new Array(_len3),_key3=0;_key3<_len3;_key3++){rest[_key3]=arguments[_key3];}_classPrivateFieldGet(_commitHandler,this).call(this,summary,...rest);return summary;}}/**
 * The handler for selections
 */class SelectionHandler{/**
   * @param {object} body
   * @param {Canvas} canvas
   */constructor(body,canvas){this.body=body;this.canvas=canvas;// TODO: Consider firing an event on any change to the selection, not
// only those caused by clicks and taps. It would be easy to implement
// now and (at least to me) it seems like something that could be
// quite useful.
this._selectionAccumulator=new SelectionAccumulator();this.hoverObj={nodes:{},edges:{}};this.options={};this.defaultOptions={multiselect:false,selectable:true,selectConnectedEdges:true,hoverConnectedEdges:true};_Object$assign(this.options,this.defaultOptions);this.body.emitter.on("_dataChanged",()=>{this.updateSelection();});}/**
   *
   * @param {object} [options]
   */setOptions(options){if(options!==undefined){const fields=["multiselect","hoverConnectedEdges","selectable","selectConnectedEdges"];selectiveDeepExtend(fields,this.options,options);}}/**
   * handles the selection part of the tap;
   * @param {{x: number, y: number}} pointer
   * @returns {boolean}
   */selectOnPoint(pointer){let selected=false;if(this.options.selectable===true){const obj=this.getNodeAt(pointer)||this.getEdgeAt(pointer);// unselect after getting the objects in order to restore width and height.
this.unselectAll();if(obj!==undefined){selected=this.selectObject(obj);}this.body.emitter.emit("_requestRedraw");}return selected;}/**
   *
   * @param {{x: number, y: number}} pointer
   * @returns {boolean}
   */selectAdditionalOnPoint(pointer){let selectionChanged=false;if(this.options.selectable===true){const obj=this.getNodeAt(pointer)||this.getEdgeAt(pointer);if(obj!==undefined){selectionChanged=true;if(obj.isSelected()===true){this.deselectObject(obj);}else {this.selectObject(obj);}this.body.emitter.emit("_requestRedraw");}}return selectionChanged;}/**
   * Create an object containing the standard fields for an event.
   * @param {Event} event
   * @param {{x: number, y: number}} pointer Object with the x and y screen coordinates of the mouse
   * @returns {{}}
   * @private
   */_initBaseEvent(event,pointer){const properties={};properties["pointer"]={DOM:{x:pointer.x,y:pointer.y},canvas:this.canvas.DOMtoCanvas(pointer)};properties["event"]=event;return properties;}/**
   * Generate an event which the user can catch.
   *
   * This adds some extra data to the event with respect to cursor position and
   * selected nodes and edges.
   * @param {string} eventType                          Name of event to send
   * @param {Event}  event
   * @param {{x: number, y: number}} pointer            Object with the x and y screen coordinates of the mouse
   * @param {object | undefined} oldSelection             If present, selection state before event occured
   * @param {boolean|undefined} [emptySelection]  Indicate if selection data should be passed
   */generateClickEvent(eventType,event,pointer,oldSelection){let emptySelection=arguments.length>4&&arguments[4]!==undefined?arguments[4]:false;const properties=this._initBaseEvent(event,pointer);if(emptySelection===true){properties.nodes=[];properties.edges=[];}else {const tmp=this.getSelection();properties.nodes=tmp.nodes;properties.edges=tmp.edges;}if(oldSelection!==undefined){properties["previousSelection"]=oldSelection;}if(eventType=="click"){// For the time being, restrict this functionality to
// just the click event.
properties.items=this.getClickedItems(pointer);}if(event.controlEdge!==undefined){properties.controlEdge=event.controlEdge;}this.body.emitter.emit(eventType,properties);}/**
   *
   * @param {object} obj
   * @param {boolean} [highlightEdges]
   * @returns {boolean}
   */selectObject(obj){let highlightEdges=arguments.length>1&&arguments[1]!==undefined?arguments[1]:this.options.selectConnectedEdges;if(obj!==undefined){if(obj instanceof Node$1){if(highlightEdges===true){this._selectionAccumulator.addEdges(...obj.edges);}this._selectionAccumulator.addNodes(obj);}else {this._selectionAccumulator.addEdges(obj);}return true;}return false;}/**
   *
   * @param {object} obj
   */deselectObject(obj){if(obj.isSelected()===true){obj.selected=false;this._removeFromSelection(obj);}}/**
   * retrieve all nodes overlapping with given object
   * @param {object} object  An object with parameters left, top, right, bottom
   * @returns {number[]}   An array with id's of the overlapping nodes
   * @private
   */_getAllNodesOverlappingWith(object){const overlappingNodes=[];const nodes=this.body.nodes;for(let i=0;i<this.body.nodeIndices.length;i++){const nodeId=this.body.nodeIndices[i];if(nodes[nodeId].isOverlappingWith(object)){overlappingNodes.push(nodeId);}}return overlappingNodes;}/**
   * Return a position object in canvasspace from a single point in screenspace
   * @param {{x: number, y: number}} pointer
   * @returns {{left: number, top: number, right: number, bottom: number}}
   * @private
   */_pointerToPositionObject(pointer){const canvasPos=this.canvas.DOMtoCanvas(pointer);return {left:canvasPos.x-1,top:canvasPos.y+1,right:canvasPos.x+1,bottom:canvasPos.y-1};}/**
   * Get the top node at the passed point (like a click)
   * @param {{x: number, y: number}} pointer
   * @param {boolean} [returnNode]
   * @returns {Node | undefined} node
   */getNodeAt(pointer){let returnNode=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;// we first check if this is an navigation controls element
const positionObject=this._pointerToPositionObject(pointer);const overlappingNodes=this._getAllNodesOverlappingWith(positionObject);// if there are overlapping nodes, select the last one, this is the
// one which is drawn on top of the others
if(overlappingNodes.length>0){if(returnNode===true){return this.body.nodes[overlappingNodes[overlappingNodes.length-1]];}else {return overlappingNodes[overlappingNodes.length-1];}}else {return undefined;}}/**
   * retrieve all edges overlapping with given object, selector is around center
   * @param {object} object  An object with parameters left, top, right, bottom
   * @param {number[]} overlappingEdges An array with id's of the overlapping nodes
   * @private
   */_getEdgesOverlappingWith(object,overlappingEdges){const edges=this.body.edges;for(let i=0;i<this.body.edgeIndices.length;i++){const edgeId=this.body.edgeIndices[i];if(edges[edgeId].isOverlappingWith(object)){overlappingEdges.push(edgeId);}}}/**
   * retrieve all nodes overlapping with given object
   * @param {object} object  An object with parameters left, top, right, bottom
   * @returns {number[]}   An array with id's of the overlapping nodes
   * @private
   */_getAllEdgesOverlappingWith(object){const overlappingEdges=[];this._getEdgesOverlappingWith(object,overlappingEdges);return overlappingEdges;}/**
   * Get the edges nearest to the passed point (like a click)
   * @param {{x: number, y: number}} pointer
   * @param {boolean} [returnEdge]
   * @returns {Edge | undefined} node
   */getEdgeAt(pointer){let returnEdge=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;// Iterate over edges, pick closest within 10
const canvasPos=this.canvas.DOMtoCanvas(pointer);let mindist=10;let overlappingEdge=null;const edges=this.body.edges;for(let i=0;i<this.body.edgeIndices.length;i++){const edgeId=this.body.edgeIndices[i];const edge=edges[edgeId];if(edge.connected){const xFrom=edge.from.x;const yFrom=edge.from.y;const xTo=edge.to.x;const yTo=edge.to.y;const dist=edge.edgeType.getDistanceToEdge(xFrom,yFrom,xTo,yTo,canvasPos.x,canvasPos.y);if(dist<mindist){overlappingEdge=edgeId;mindist=dist;}}}if(overlappingEdge!==null){if(returnEdge===true){return this.body.edges[overlappingEdge];}else {return overlappingEdge;}}else {return undefined;}}/**
   * Add object to the selection array.
   * @param {object} obj
   * @private
   */_addToHover(obj){if(obj instanceof Node$1){this.hoverObj.nodes[obj.id]=obj;}else {this.hoverObj.edges[obj.id]=obj;}}/**
   * Remove a single option from selection.
   * @param {object} obj
   * @private
   */_removeFromSelection(obj){if(obj instanceof Node$1){this._selectionAccumulator.deleteNodes(obj);this._selectionAccumulator.deleteEdges(...obj.edges);}else {this._selectionAccumulator.deleteEdges(obj);}}/**
   * Unselect all nodes and edges.
   */unselectAll(){this._selectionAccumulator.clear();}/**
   * return the number of selected nodes
   * @returns {number}
   */getSelectedNodeCount(){return this._selectionAccumulator.sizeNodes;}/**
   * return the number of selected edges
   * @returns {number}
   */getSelectedEdgeCount(){return this._selectionAccumulator.sizeEdges;}/**
   * select the edges connected to the node that is being selected
   * @param {Node} node
   * @private
   */_hoverConnectedEdges(node){for(let i=0;i<node.edges.length;i++){const edge=node.edges[i];edge.hover=true;this._addToHover(edge);}}/**
   * Remove the highlight from a node or edge, in response to mouse movement
   * @param {Event}  event
   * @param {{x: number, y: number}} pointer object with the x and y screen coordinates of the mouse
   * @param {Node|vis.Edge} object
   * @private
   */emitBlurEvent(event,pointer,object){const properties=this._initBaseEvent(event,pointer);if(object.hover===true){object.hover=false;if(object instanceof Node$1){properties.node=object.id;this.body.emitter.emit("blurNode",properties);}else {properties.edge=object.id;this.body.emitter.emit("blurEdge",properties);}}}/**
   * Create the highlight for a node or edge, in response to mouse movement
   * @param {Event}  event
   * @param {{x: number, y: number}} pointer object with the x and y screen coordinates of the mouse
   * @param {Node|vis.Edge} object
   * @returns {boolean} hoverChanged
   * @private
   */emitHoverEvent(event,pointer,object){const properties=this._initBaseEvent(event,pointer);let hoverChanged=false;if(object.hover===false){object.hover=true;this._addToHover(object);hoverChanged=true;if(object instanceof Node$1){properties.node=object.id;this.body.emitter.emit("hoverNode",properties);}else {properties.edge=object.id;this.body.emitter.emit("hoverEdge",properties);}}return hoverChanged;}/**
   * Perform actions in response to a mouse movement.
   * @param {Event}  event
   * @param {{x: number, y: number}} pointer | object with the x and y screen coordinates of the mouse
   */hoverObject(event,pointer){let object=this.getNodeAt(pointer);if(object===undefined){object=this.getEdgeAt(pointer);}let hoverChanged=false;// remove all node hover highlights
for(const nodeId in this.hoverObj.nodes){if(Object.prototype.hasOwnProperty.call(this.hoverObj.nodes,nodeId)){if(object===undefined||object instanceof Node$1&&object.id!=nodeId||object instanceof Edge){this.emitBlurEvent(event,pointer,this.hoverObj.nodes[nodeId]);delete this.hoverObj.nodes[nodeId];hoverChanged=true;}}}// removing all edge hover highlights
for(const edgeId in this.hoverObj.edges){if(Object.prototype.hasOwnProperty.call(this.hoverObj.edges,edgeId)){// if the hover has been changed here it means that the node has been hovered over or off
// we then do not use the emitBlurEvent method here.
if(hoverChanged===true){this.hoverObj.edges[edgeId].hover=false;delete this.hoverObj.edges[edgeId];}// if the blur remains the same and the object is undefined (mouse off) or another
// edge has been hovered, or another node has been hovered we blur the edge.
else if(object===undefined||object instanceof Edge&&object.id!=edgeId||object instanceof Node$1&&!object.hover){this.emitBlurEvent(event,pointer,this.hoverObj.edges[edgeId]);delete this.hoverObj.edges[edgeId];hoverChanged=true;}}}if(object!==undefined){const hoveredEdgesCount=_Object$keys(this.hoverObj.edges).length;const hoveredNodesCount=_Object$keys(this.hoverObj.nodes).length;const newOnlyHoveredEdge=object instanceof Edge&&hoveredEdgesCount===0&&hoveredNodesCount===0;const newOnlyHoveredNode=object instanceof Node$1&&hoveredEdgesCount===0&&hoveredNodesCount===0;if(hoverChanged||newOnlyHoveredEdge||newOnlyHoveredNode){hoverChanged=this.emitHoverEvent(event,pointer,object);}if(object instanceof Node$1&&this.options.hoverConnectedEdges===true){this._hoverConnectedEdges(object);}}if(hoverChanged===true){this.body.emitter.emit("_requestRedraw");}}/**
   * Commit the selection changes but don't emit any events.
   */commitWithoutEmitting(){this._selectionAccumulator.commit();}/**
   * Select and deselect nodes depending current selection change.
   *
   * For changing nodes, select/deselect events are fired.
   *
   * NOTE: For a given edge, if one connecting node is deselected and with the
   * same click the other node is selected, no events for the edge will fire. It
   * was selected and it will remain selected.
   * @param {{x: number, y: number}} pointer - The x and y coordinates of the
   * click, tap, dragend… that triggered this.
   * @param {UIEvent} event - The event that triggered this.
   */commitAndEmit(pointer,event){let selected=false;const selectionChanges=this._selectionAccumulator.commit();const previousSelection={nodes:selectionChanges.nodes.previous,edges:selectionChanges.edges.previous};if(selectionChanges.edges.deleted.length>0){this.generateClickEvent("deselectEdge",event,pointer,previousSelection);selected=true;}if(selectionChanges.nodes.deleted.length>0){this.generateClickEvent("deselectNode",event,pointer,previousSelection);selected=true;}if(selectionChanges.nodes.added.length>0){this.generateClickEvent("selectNode",event,pointer);selected=true;}if(selectionChanges.edges.added.length>0){this.generateClickEvent("selectEdge",event,pointer);selected=true;}// fire the select event if anything has been selected or deselected
if(selected===true){// select or unselect
this.generateClickEvent("select",event,pointer);}}/**
   * Retrieve the currently selected node and edge ids.
   * @returns {{nodes: Array.<string>, edges: Array.<string>}} Arrays with the
   * ids of the selected nodes and edges.
   */getSelection(){return {nodes:this.getSelectedNodeIds(),edges:this.getSelectedEdgeIds()};}/**
   * Retrieve the currently selected nodes.
   * @returns {Array} An array with selected nodes.
   */getSelectedNodes(){return this._selectionAccumulator.getNodes();}/**
   * Retrieve the currently selected edges.
   * @returns {Array} An array with selected edges.
   */getSelectedEdges(){return this._selectionAccumulator.getEdges();}/**
   * Retrieve the currently selected node ids.
   * @returns {Array} An array with the ids of the selected nodes.
   */getSelectedNodeIds(){var _context;return _mapInstanceProperty(_context=this._selectionAccumulator.getNodes()).call(_context,node=>node.id);}/**
   * Retrieve the currently selected edge ids.
   * @returns {Array} An array with the ids of the selected edges.
   */getSelectedEdgeIds(){var _context2;return _mapInstanceProperty(_context2=this._selectionAccumulator.getEdges()).call(_context2,edge=>edge.id);}/**
   * Updates the current selection
   * @param {{nodes: Array.<string>, edges: Array.<string>}} selection
   * @param {object} options                                 Options
   */setSelection(selection){let options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};if(!selection||!selection.nodes&&!selection.edges){throw new TypeError("Selection must be an object with nodes and/or edges properties");}// first unselect any selected node, if option is true or undefined
if(options.unselectAll||options.unselectAll===undefined){this.unselectAll();}if(selection.nodes){for(const id of selection.nodes){const node=this.body.nodes[id];if(!node){throw new RangeError('Node with id "'+id+'" not found');}// don't select edges with it
this.selectObject(node,options.highlightEdges);}}if(selection.edges){for(const id of selection.edges){const edge=this.body.edges[id];if(!edge){throw new RangeError('Edge with id "'+id+'" not found');}this.selectObject(edge);}}this.body.emitter.emit("_requestRedraw");this._selectionAccumulator.commit();}/**
   * select zero or more nodes with the option to highlight edges
   * @param {number[] | string[]} selection     An array with the ids of the
   *                                            selected nodes.
   * @param {boolean} [highlightEdges]
   */selectNodes(selection){let highlightEdges=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;if(!selection||selection.length===undefined)throw "Selection must be an array with ids";this.setSelection({nodes:selection},{highlightEdges:highlightEdges});}/**
   * select zero or more edges
   * @param {number[] | string[]} selection     An array with the ids of the
   *                                            selected nodes.
   */selectEdges(selection){if(!selection||selection.length===undefined)throw "Selection must be an array with ids";this.setSelection({edges:selection});}/**
   * Validate the selection: remove ids of nodes which no longer exist
   * @private
   */updateSelection(){for(const node in this._selectionAccumulator.getNodes()){if(!Object.prototype.hasOwnProperty.call(this.body.nodes,node.id)){this._selectionAccumulator.deleteNodes(node);}}for(const edge in this._selectionAccumulator.getEdges()){if(!Object.prototype.hasOwnProperty.call(this.body.edges,edge.id)){this._selectionAccumulator.deleteEdges(edge);}}}/**
   * Determine all the visual elements clicked which are on the given point.
   *
   * All elements are returned; this includes nodes, edges and their labels.
   * The order returned is from highest to lowest, i.e. element 0 of the return
   * value is the topmost item clicked on.
   *
   * The return value consists of an array of the following possible elements:
   *
   * - `{nodeId:number}`             - node with given id clicked on
   * - `{nodeId:number, labelId:0}`  - label of node with given id clicked on
   * - `{edgeId:number}`             - edge with given id clicked on
   * - `{edge:number, labelId:0}`    - label of edge with given id clicked on
   *
   * ## NOTES
   *
   * - Currently, there is only one label associated with a node or an edge,
   * but this is expected to change somewhere in the future.
   * - Since there is no z-indexing yet, it is not really possible to set the nodes and
   * edges in the correct order. For the time being, nodes come first.
   * @param {point} pointer  mouse position in screen coordinates
   * @returns {Array.<nodeClickItem|nodeLabelClickItem|edgeClickItem|edgeLabelClickItem>}
   * @private
   */getClickedItems(pointer){const point=this.canvas.DOMtoCanvas(pointer);const items=[];// Note reverse order; we want the topmost clicked items to be first in the array
// Also note that selected nodes are disregarded here; these normally display on top
const nodeIndices=this.body.nodeIndices;const nodes=this.body.nodes;for(let i=nodeIndices.length-1;i>=0;i--){const node=nodes[nodeIndices[i]];const ret=node.getItemsOnPoint(point);items.push.apply(items,ret);// Append the return value to the running list.
}const edgeIndices=this.body.edgeIndices;const edges=this.body.edges;for(let i=edgeIndices.length-1;i>=0;i--){const edge=edges[edgeIndices[i]];const ret=edge.getItemsOnPoint(point);items.push.apply(items,ret);// Append the return value to the running list.
}return items;}}/**
 * Helper classes for LayoutEngine.
 *
 * Strategy pattern for usage of direction methods for hierarchical layouts.
 *//**
 * Interface definition for direction strategy classes.
 *
 * This class describes the interface for the Strategy
 * pattern classes used to differentiate horizontal and vertical
 * direction of hierarchical results.
 *
 * For a given direction, one coordinate will be 'fixed', meaning that it is
 * determined by level.
 * The other coordinate is 'unfixed', meaning that the nodes on a given level
 * can still move along that coordinate. So:
 *
 * - `vertical` layout: `x` unfixed, `y` fixed per level
 * - `horizontal` layout: `x` fixed per level, `y` unfixed
 *
 * The local methods are stubs and should be regarded as abstract.
 * Derived classes **must** implement all the methods themselves.
 * @private
 */class DirectionInterface{/**
   * @ignore
   */abstract(){throw new Error("Can't instantiate abstract class!");}/**
   * This is a dummy call which is used to suppress the jsdoc errors of type:
   *
   * "'param' is assigned a value but never used"
   * @ignore
   */fake_use(){// Do nothing special
}/**
   * Type to use to translate dynamic curves to, in the case of hierarchical layout.
   * Dynamic curves do not work for these.
   *
   * The value should be perpendicular to the actual direction of the layout.
   * @returns {string} Direction, either 'vertical' or 'horizontal'
   */curveType(){return this.abstract();}/**
   * Return the value of the coordinate that is not fixed for this direction.
   * @param {Node} node The node to read
   * @returns {number} Value of the unfixed coordinate
   */getPosition(node){this.fake_use(node);return this.abstract();}/**
   * Set the value of the coordinate that is not fixed for this direction.
   * @param {Node} node The node to adjust
   * @param {number} position
   * @param {number} [level] if specified, the hierarchy level that this node should be fixed to
   */setPosition(node,position){let level=arguments.length>2&&arguments[2]!==undefined?arguments[2]:undefined;this.fake_use(node,position,level);this.abstract();}/**
   * Get the width of a tree.
   *
   * A `tree` here is a subset of nodes within the network which are not connected to other nodes,
   * only among themselves. In essence, it is a sub-network.
   * @param {number} index The index number of a tree
   * @returns {number} the width of a tree in the view coordinates
   */getTreeSize(index){this.fake_use(index);return this.abstract();}/**
   * Sort array of nodes on the unfixed coordinates.
   *
   * Note:** chrome has non-stable sorting implementation, which
   * has a tendency to change the order of the array items,
   * even if the custom sort function returns 0.
   *
   * For this reason, an external sort implementation is used,
   * which has the added benefit of being faster than the standard
   * platforms implementation. This has been verified on `node.js`,
   * `firefox` and `chrome` (all linux).
   * @param {Array.<Node>} nodeArray array of nodes to sort
   */sort(nodeArray){this.fake_use(nodeArray);this.abstract();}/**
   * Assign the fixed coordinate of the node to the given level
   * @param {Node} node The node to adjust
   * @param {number} level The level to fix to
   */fix(node,level){this.fake_use(node,level);this.abstract();}/**
   * Add an offset to the unfixed coordinate of the given node.
   * @param {NodeId} nodeId Id of the node to adjust
   * @param {number} diff Offset to add to the unfixed coordinate
   */shift(nodeId,diff){this.fake_use(nodeId,diff);this.abstract();}}/**
 * Vertical Strategy
 *
 * Coordinate `y` is fixed on levels, coordinate `x` is unfixed.
 * @augments DirectionInterface
 * @private
 */class VerticalStrategy extends DirectionInterface{/**
   * Constructor
   * @param {object} layout reference to the parent LayoutEngine instance.
   */constructor(layout){super();this.layout=layout;}/** @inheritDoc */curveType(){return "horizontal";}/** @inheritDoc */getPosition(node){return node.x;}/** @inheritDoc */setPosition(node,position){let level=arguments.length>2&&arguments[2]!==undefined?arguments[2]:undefined;if(level!==undefined){this.layout.hierarchical.addToOrdering(node,level);}node.x=position;}/** @inheritDoc */getTreeSize(index){const res=this.layout.hierarchical.getTreeSize(this.layout.body.nodes,index);return {min:res.min_x,max:res.max_x};}/** @inheritDoc */sort(nodeArray){_sortInstanceProperty(nodeArray).call(nodeArray,function(a,b){return a.x-b.x;});}/** @inheritDoc */fix(node,level){node.y=this.layout.options.hierarchical.levelSeparation*level;node.options.fixed.y=true;}/** @inheritDoc */shift(nodeId,diff){this.layout.body.nodes[nodeId].x+=diff;}}/**
 * Horizontal Strategy
 *
 * Coordinate `x` is fixed on levels, coordinate `y` is unfixed.
 * @augments DirectionInterface
 * @private
 */class HorizontalStrategy extends DirectionInterface{/**
   * Constructor
   * @param {object} layout reference to the parent LayoutEngine instance.
   */constructor(layout){super();this.layout=layout;}/** @inheritDoc */curveType(){return "vertical";}/** @inheritDoc */getPosition(node){return node.y;}/** @inheritDoc */setPosition(node,position){let level=arguments.length>2&&arguments[2]!==undefined?arguments[2]:undefined;if(level!==undefined){this.layout.hierarchical.addToOrdering(node,level);}node.y=position;}/** @inheritDoc */getTreeSize(index){const res=this.layout.hierarchical.getTreeSize(this.layout.body.nodes,index);return {min:res.min_y,max:res.max_y};}/** @inheritDoc */sort(nodeArray){_sortInstanceProperty(nodeArray).call(nodeArray,function(a,b){return a.y-b.y;});}/** @inheritDoc */fix(node,level){node.x=this.layout.options.hierarchical.levelSeparation*level;node.options.fixed.x=true;}/** @inheritDoc */shift(nodeId,diff){this.layout.body.nodes[nodeId].y+=diff;}}var es_array_every={};var hasRequiredEs_array_every;function requireEs_array_every(){if(hasRequiredEs_array_every)return es_array_every;hasRequiredEs_array_every=1;var $=/*@__PURE__*/require_export();var $every=/*@__PURE__*/requireArrayIteration().every;var arrayMethodIsStrict=/*@__PURE__*/requireArrayMethodIsStrict();var STRICT_METHOD=arrayMethodIsStrict('every');// `Array.prototype.every` method
// https://tc39.es/ecma262/#sec-array.prototype.every
$({target:'Array',proto:true,forced:!STRICT_METHOD},{every:function every(callbackfn/* , thisArg */){return $every(this,callbackfn,arguments.length>1?arguments[1]:undefined);}});return es_array_every;}var every$3;var hasRequiredEvery$3;function requireEvery$3(){if(hasRequiredEvery$3)return every$3;hasRequiredEvery$3=1;requireEs_array_every();var getBuiltInPrototypeMethod=/*@__PURE__*/requireGetBuiltInPrototypeMethod();every$3=getBuiltInPrototypeMethod('Array','every');return every$3;}var every$2;var hasRequiredEvery$2;function requireEvery$2(){if(hasRequiredEvery$2)return every$2;hasRequiredEvery$2=1;var isPrototypeOf=/*@__PURE__*/requireObjectIsPrototypeOf();var method=/*@__PURE__*/requireEvery$3();var ArrayPrototype=Array.prototype;every$2=function(it){var own=it.every;return it===ArrayPrototype||isPrototypeOf(ArrayPrototype,it)&&own===ArrayPrototype.every?method:own;};return every$2;}var every$1;var hasRequiredEvery$1;function requireEvery$1(){if(hasRequiredEvery$1)return every$1;hasRequiredEvery$1=1;var parent=/*@__PURE__*/requireEvery$2();every$1=parent;return every$1;}var every;var hasRequiredEvery;function requireEvery(){if(hasRequiredEvery)return every;hasRequiredEvery=1;every=/*@__PURE__*/requireEvery$1();return every;}var everyExports=requireEvery();var _everyInstanceProperty=/*@__PURE__*/getDefaultExportFromCjs(everyExports);/**
 * Try to assign levels to nodes according to their positions in the cyclic “hierarchy”.
 * @param nodes - Visible nodes of the graph.
 * @param levels - If present levels will be added to it, if not a new object will be created.
 * @returns Populated node levels.
 */function fillLevelsByDirectionCyclic(nodes,levels){const edges=new _Set();_forEachInstanceProperty(nodes).call(nodes,node=>{var _context;_forEachInstanceProperty(_context=node.edges).call(_context,edge=>{if(edge.connected){edges.add(edge);}});});_forEachInstanceProperty(edges).call(edges,edge=>{const fromId=edge.from.id;const toId=edge.to.id;if(levels[fromId]==null){levels[fromId]=0;}if(levels[toId]==null||levels[fromId]>=levels[toId]){levels[toId]=levels[fromId]+1;}});return levels;}/**
 * Assign levels to nodes according to their positions in the hierarchy. Leaves will be lined up at the bottom and all other nodes as close to their children as possible.
 * @param nodes - Visible nodes of the graph.
 * @returns Populated node levels.
 */function fillLevelsByDirectionLeaves(nodes){return fillLevelsByDirection(// Pick only leaves (nodes without children).
node=>{var _context2,_context3;return _everyInstanceProperty(_context2=_filterInstanceProperty(_context3=node.edges// Take only visible nodes into account.
).call(_context3,edge=>nodes.has(edge.toId))// Check that all edges lead to this node (leaf).
).call(_context2,edge=>edge.to===node);},// Use the lowest level.
(newLevel,oldLevel)=>oldLevel>newLevel,// Go against the direction of the edges.
"from",nodes);}/**
 * Assign levels to nodes according to their positions in the hierarchy. Roots will be lined up at the top and all nodes as close to their parents as possible.
 * @param nodes - Visible nodes of the graph.
 * @returns Populated node levels.
 */function fillLevelsByDirectionRoots(nodes){return fillLevelsByDirection(// Pick only roots (nodes without parents).
node=>{var _context4,_context5;return _everyInstanceProperty(_context4=_filterInstanceProperty(_context5=node.edges// Take only visible nodes into account.
).call(_context5,edge=>nodes.has(edge.toId))// Check that all edges lead from this node (root).
).call(_context4,edge=>edge.from===node);},// Use the highest level.
(newLevel,oldLevel)=>oldLevel<newLevel,// Go in the direction of the edges.
"to",nodes);}/**
 * Assign levels to nodes according to their positions in the hierarchy.
 * @param isEntryNode - Checks and return true if the graph should be traversed from this node.
 * @param shouldLevelBeReplaced - Checks and returns true if the level of given node should be updated to the new value.
 * @param direction - Wheter the graph should be traversed in the direction of the edges `"to"` or in the other way `"from"`.
 * @param nodes - Visible nodes of the graph.
 * @returns Populated node levels.
 */function fillLevelsByDirection(isEntryNode,shouldLevelBeReplaced,direction,nodes){var _context6;const levels=_Object$create(null);// If acyclic, the graph can be walked through with (most likely way) fewer
// steps than the number bellow. The exact value isn't too important as long
// as it's quick to compute (doesn't impact acyclic graphs too much), is
// higher than the number of steps actually needed (doesn't cut off before
// acyclic graph is walked through) and prevents infinite loops (cuts off for
// cyclic graphs).
const limit=_reduceInstanceProperty(_context6=[..._valuesInstanceProperty(nodes).call(nodes)]).call(_context6,(acc,node)=>acc+1+node.edges.length,0);const edgeIdProp=direction+"Id";const newLevelDiff=direction==="to"?1:-1;for(const[entryNodeId,entryNode]of nodes){if(// Skip if the node is not visible.
!nodes.has(entryNodeId)||// Skip if the node is not an entry node.
!isEntryNode(entryNode)){continue;}// Line up all the entry nodes on level 0.
levels[entryNodeId]=0;const stack=[entryNode];let done=0;let node;while(node=stack.pop()){var _context7,_context8;if(!nodes.has(entryNodeId)){// Skip if the node is not visible.
continue;}const newLevel=levels[node.id]+newLevelDiff;_forEachInstanceProperty(_context7=_filterInstanceProperty(_context8=node.edges).call(_context8,edge=>// Ignore disconnected edges.
edge.connected&&// Ignore circular edges.
edge.to!==edge.from&&// Ignore edges leading to the node that's currently being processed.
edge[direction]!==node&&// Ignore edges connecting to an invisible node.
nodes.has(edge.toId)&&// Ignore edges connecting from an invisible node.
nodes.has(edge.fromId))).call(_context7,edge=>{const targetNodeId=edge[edgeIdProp];const oldLevel=levels[targetNodeId];if(oldLevel==null||shouldLevelBeReplaced(newLevel,oldLevel)){levels[targetNodeId]=newLevel;stack.push(edge[direction]);}});if(done>limit){// This would run forever on a cyclic graph.
return fillLevelsByDirectionCyclic(nodes,levels);}else {++done;}}}return levels;}/**
 * There's a mix-up with terms in the code. Following are the formal definitions:
 *
 *   tree   - a strict hierarchical network, i.e. every node has at most one parent
 *   forest - a collection of trees. These distinct trees are thus not connected.
 *
 * So:
 * - in a network that is not a tree, there exist nodes with multiple parents.
 * - a network consisting of unconnected sub-networks, of which at least one
 *   is not a tree, is not a forest.
 *
 * In the code, the definitions are:
 *
 *   tree   - any disconnected sub-network, strict hierarchical or not.
 *   forest - a bunch of these sub-networks
 *
 * The difference between tree and not-tree is important in the code, notably within
 * to the block-shifting algorithm. The algorithm assumes formal trees and fails
 * for not-trees, often in a spectacular manner (search for 'exploding network' in the issues).
 *
 * In order to distinguish the definitions in the following code, the adjective 'formal' is
 * used. If 'formal' is absent, you must assume the non-formal definition.
 *
 * ----------------------------------------------------------------------------------
 * NOTES
 * =====
 *
 * A hierarchical layout is a different thing from a hierarchical network.
 * The layout is a way to arrange the nodes in the view; this can be done
 * on non-hierarchical networks as well. The converse is also possible.
 *//**
 * Container for derived data on current network, relating to hierarchy.
 * @private
 */class HierarchicalStatus{/**
   * @ignore
   */constructor(){this.childrenReference={};// child id's per node id
this.parentReference={};// parent id's per node id
this.trees={};// tree id per node id; i.e. to which tree does given node id belong
this.distributionOrdering={};// The nodes per level, in the display order
this.levels={};// hierarchy level per node id
this.distributionIndex={};// The position of the node in the level sorting order, per node id.
this.isTree=false;// True if current network is a formal tree
this.treeIndex=-1;// Highest tree id in current network.
}/**
   * Add the relation between given nodes to the current state.
   * @param {Node.id} parentNodeId
   * @param {Node.id} childNodeId
   */addRelation(parentNodeId,childNodeId){if(this.childrenReference[parentNodeId]===undefined){this.childrenReference[parentNodeId]=[];}this.childrenReference[parentNodeId].push(childNodeId);if(this.parentReference[childNodeId]===undefined){this.parentReference[childNodeId]=[];}this.parentReference[childNodeId].push(parentNodeId);}/**
   * Check if the current state is for a formal tree or formal forest.
   *
   * This is the case if every node has at most one parent.
   *
   * Pre: parentReference init'ed properly for current network
   */checkIfTree(){for(const i in this.parentReference){if(this.parentReference[i].length>1){this.isTree=false;return;}}this.isTree=true;}/**
   * Return the number of separate trees in the current network.
   * @returns {number}
   */numTrees(){return this.treeIndex+1;// This assumes the indexes are assigned consecitively
}/**
   * Assign a tree id to a node
   * @param {Node} node
   * @param {string|number} treeId
   */setTreeIndex(node,treeId){if(treeId===undefined)return;// Don't bother
if(this.trees[node.id]===undefined){this.trees[node.id]=treeId;this.treeIndex=Math.max(treeId,this.treeIndex);}}/**
   * Ensure level for given id is defined.
   *
   * Sets level to zero for given node id if not already present
   * @param {Node.id} nodeId
   */ensureLevel(nodeId){if(this.levels[nodeId]===undefined){this.levels[nodeId]=0;}}/**
   * get the maximum level of a branch.
   *
   * TODO: Never entered; find a test case to test this!
   * @param {Node.id} nodeId
   * @returns {number}
   */getMaxLevel(nodeId){const accumulator={};const _getMaxLevel=nodeId=>{if(accumulator[nodeId]!==undefined){return accumulator[nodeId];}let level=this.levels[nodeId];if(this.childrenReference[nodeId]){const children=this.childrenReference[nodeId];if(children.length>0){for(let i=0;i<children.length;i++){level=Math.max(level,_getMaxLevel(children[i]));}}}accumulator[nodeId]=level;return level;};return _getMaxLevel(nodeId);}/**
   *
   * @param {Node} nodeA
   * @param {Node} nodeB
   */levelDownstream(nodeA,nodeB){if(this.levels[nodeB.id]===undefined){// set initial level
if(this.levels[nodeA.id]===undefined){this.levels[nodeA.id]=0;}// set level
this.levels[nodeB.id]=this.levels[nodeA.id]+1;}}/**
   * Small util method to set the minimum levels of the nodes to zero and
   * eliminate gaps (for cyclic).
   */setMinLevelToZero(){var _context;const remap=new _Map();let newLevel=0;const uniqueSortedLevels=_sortInstanceProperty(_context=[...new _Set(_Object$values(this.levels))]).call(_context,(a,b)=>a-b);for(const level of uniqueSortedLevels){remap.set(level,newLevel++);}for(const nodeId in this.levels){if(Object.prototype.hasOwnProperty.call(this.levels,nodeId)){this.levels[nodeId]=remap.get(this.levels[nodeId]);}}}/**
   * Get the min and max xy-coordinates of a given tree
   * @param {Array.<Node>} nodes
   * @param {number} index
   * @returns {{min_x: number, max_x: number, min_y: number, max_y: number}}
   */getTreeSize(nodes,index){let min_x=1e9;let max_x=-1e9;let min_y=1e9;let max_y=-1e9;for(const nodeId in this.trees){if(Object.prototype.hasOwnProperty.call(this.trees,nodeId)){if(this.trees[nodeId]===index){const node=nodes[nodeId];min_x=Math.min(node.x,min_x);max_x=Math.max(node.x,max_x);min_y=Math.min(node.y,min_y);max_y=Math.max(node.y,max_y);}}}return {min_x:min_x,max_x:max_x,min_y:min_y,max_y:max_y};}/**
   * Check if two nodes have the same parent(s)
   * @param {Node} node1
   * @param {Node} node2
   * @returns {boolean} true if the two nodes have a same ancestor node, false otherwise
   */hasSameParent(node1,node2){const parents1=this.parentReference[node1.id];const parents2=this.parentReference[node2.id];if(parents1===undefined||parents2===undefined){return false;}for(let i=0;i<parents1.length;i++){for(let j=0;j<parents2.length;j++){if(parents1[i]==parents2[j]){return true;}}}return false;}/**
   * Check if two nodes are in the same tree.
   * @param {Node} node1
   * @param {Node} node2
   * @returns {boolean} true if this is so, false otherwise
   */inSameSubNetwork(node1,node2){return this.trees[node1.id]===this.trees[node2.id];}/**
   * Get a list of the distinct levels in the current network
   * @returns {Array}
   */getLevels(){return _Object$keys(this.distributionOrdering);}/**
   * Add a node to the ordering per level
   * @param {Node} node
   * @param {number} level
   */addToOrdering(node,level){if(this.distributionOrdering[level]===undefined){this.distributionOrdering[level]=[];}let isPresent=false;const curLevel=this.distributionOrdering[level];for(const n in curLevel){//if (curLevel[n].id === node.id) {
if(curLevel[n]===node){isPresent=true;break;}}if(!isPresent){this.distributionOrdering[level].push(node);this.distributionIndex[node.id]=this.distributionOrdering[level].length-1;}}}/**
 * The Layout Engine
 */class LayoutEngine{/**
   * @param {object} body
   */constructor(body){this.body=body;// Make sure there always is some RNG because the setOptions method won't
// set it unless there's a seed for it.
this._resetRNG(Math.random()+":"+_Date$now());this.setPhysics=false;this.options={};this.optionsBackup={physics:{}};this.defaultOptions={randomSeed:undefined,improvedLayout:true,clusterThreshold:150,hierarchical:{enabled:false,levelSeparation:150,nodeSpacing:100,treeSpacing:200,blockShifting:true,edgeMinimization:true,parentCentralization:true,direction:"UD",// UD, DU, LR, RL
sortMethod:"hubsize"// hubsize, directed
}};_Object$assign(this.options,this.defaultOptions);this.bindEventListeners();}/**
   * Binds event listeners
   */bindEventListeners(){this.body.emitter.on("_dataChanged",()=>{this.setupHierarchicalLayout();});this.body.emitter.on("_dataLoaded",()=>{this.layoutNetwork();});this.body.emitter.on("_resetHierarchicalLayout",()=>{this.setupHierarchicalLayout();});this.body.emitter.on("_adjustEdgesForHierarchicalLayout",()=>{if(this.options.hierarchical.enabled!==true){return;}// get the type of static smooth curve in case it is required
const type=this.direction.curveType();// force all edges into static smooth curves.
this.body.emitter.emit("_forceDisableDynamicCurves",type,false);});}/**
   *
   * @param {object} options
   * @param {object} allOptions
   * @returns {object}
   */setOptions(options,allOptions){if(options!==undefined){const hierarchical=this.options.hierarchical;const prevHierarchicalState=hierarchical.enabled;selectiveDeepExtend(["randomSeed","improvedLayout","clusterThreshold"],this.options,options);mergeOptions(this.options,options,"hierarchical");if(options.randomSeed!==undefined){this._resetRNG(options.randomSeed);}if(hierarchical.enabled===true){if(prevHierarchicalState===true){// refresh the overridden options for nodes and edges.
this.body.emitter.emit("refresh",true);}// make sure the level separation is the right way up
if(hierarchical.direction==="RL"||hierarchical.direction==="DU"){if(hierarchical.levelSeparation>0){hierarchical.levelSeparation*=-1;}}else {if(hierarchical.levelSeparation<0){hierarchical.levelSeparation*=-1;}}this.setDirectionStrategy();this.body.emitter.emit("_resetHierarchicalLayout");// because the hierarchical system needs it's own physics and smooth curve settings,
// we adapt the other options if needed.
return this.adaptAllOptionsForHierarchicalLayout(allOptions);}else {if(prevHierarchicalState===true){// refresh the overridden options for nodes and edges.
this.body.emitter.emit("refresh");return deepExtend(allOptions,this.optionsBackup);}}}return allOptions;}/**
   * Reset the random number generator with given seed.
   * @param {any} seed - The seed that will be forwarded the the RNG.
   */_resetRNG(seed){this.initialRandomSeed=seed;this._rng=Alea(this.initialRandomSeed);}/**
   *
   * @param {object} allOptions
   * @returns {object}
   */adaptAllOptionsForHierarchicalLayout(allOptions){if(this.options.hierarchical.enabled===true){const backupPhysics=this.optionsBackup.physics;// set the physics
if(allOptions.physics===undefined||allOptions.physics===true){allOptions.physics={enabled:backupPhysics.enabled===undefined?true:backupPhysics.enabled,solver:"hierarchicalRepulsion"};backupPhysics.enabled=backupPhysics.enabled===undefined?true:backupPhysics.enabled;backupPhysics.solver=backupPhysics.solver||"barnesHut";}else if(typeof allOptions.physics==="object"){backupPhysics.enabled=allOptions.physics.enabled===undefined?true:allOptions.physics.enabled;backupPhysics.solver=allOptions.physics.solver||"barnesHut";allOptions.physics.solver="hierarchicalRepulsion";}else if(allOptions.physics!==false){backupPhysics.solver="barnesHut";allOptions.physics={solver:"hierarchicalRepulsion"};}// get the type of static smooth curve in case it is required
let type=this.direction.curveType();// disable smooth curves if nothing is defined. If smooth curves have been turned on,
// turn them into static smooth curves.
if(allOptions.edges===undefined){this.optionsBackup.edges={smooth:{enabled:true,type:"dynamic"}};allOptions.edges={smooth:false};}else if(allOptions.edges.smooth===undefined){this.optionsBackup.edges={smooth:{enabled:true,type:"dynamic"}};allOptions.edges.smooth=false;}else {if(typeof allOptions.edges.smooth==="boolean"){this.optionsBackup.edges={smooth:allOptions.edges.smooth};allOptions.edges.smooth={enabled:allOptions.edges.smooth,type:type};}else {const smooth=allOptions.edges.smooth;// allow custom types except for dynamic
if(smooth.type!==undefined&&smooth.type!=="dynamic"){type=smooth.type;}// TODO: this is options merging; see if the standard routines can be used here.
this.optionsBackup.edges={smooth:{enabled:smooth.enabled===undefined?true:smooth.enabled,type:smooth.type===undefined?"dynamic":smooth.type,roundness:smooth.roundness===undefined?0.5:smooth.roundness,forceDirection:smooth.forceDirection===undefined?false:smooth.forceDirection}};// NOTE: Copying an object to self; this is basically setting defaults for undefined variables
allOptions.edges.smooth={enabled:smooth.enabled===undefined?true:smooth.enabled,type:type,roundness:smooth.roundness===undefined?0.5:smooth.roundness,forceDirection:smooth.forceDirection===undefined?false:smooth.forceDirection};}}// Force all edges into static smooth curves.
// Only applies to edges that do not use the global options for smooth.
this.body.emitter.emit("_forceDisableDynamicCurves",type);}return allOptions;}/**
   *
   * @param {Array.<Node>} nodesArray
   */positionInitially(nodesArray){if(this.options.hierarchical.enabled!==true){this._resetRNG(this.initialRandomSeed);const radius=nodesArray.length+50;for(let i=0;i<nodesArray.length;i++){const node=nodesArray[i];const angle=2*Math.PI*this._rng();if(node.x===undefined){node.x=radius*Math.cos(angle);}if(node.y===undefined){node.y=radius*Math.sin(angle);}}}}/**
   * Use Kamada Kawai to position nodes. This is quite a heavy algorithm so if there are a lot of nodes we
   * cluster them first to reduce the amount.
   */layoutNetwork(){if(this.options.hierarchical.enabled!==true&&this.options.improvedLayout===true){const indices=this.body.nodeIndices;// first check if we should Kamada Kawai to layout. The threshold is if less than half of the visible
// nodes have predefined positions we use this.
let positionDefined=0;for(let i=0;i<indices.length;i++){const node=this.body.nodes[indices[i]];if(node.predefinedPosition===true){positionDefined+=1;}}// if less than half of the nodes have a predefined position we continue
if(positionDefined<0.5*indices.length){const MAX_LEVELS=10;let level=0;const clusterThreshold=this.options.clusterThreshold;//
// Define the options for the hidden cluster nodes
// These options don't propagate outside the clustering phase.
//
// Some options are explicitly disabled, because they may be set in group or default node options.
// The clusters are never displayed, so most explicit settings here serve as performance optimizations.
//
// The explicit setting of 'shape' is to avoid `shape: 'image'`; images are not passed to the hidden
// cluster nodes, leading to an exception on creation.
//
// All settings here are performance related, except when noted otherwise.
//
const clusterOptions={clusterNodeProperties:{shape:"ellipse",// Bugfix: avoid type 'image', no images supplied
label:"",// avoid label handling
group:"",// avoid group handling
font:{multi:false}// avoid font propagation
},clusterEdgeProperties:{label:"",// avoid label handling
font:{multi:false},// avoid font propagation
smooth:{enabled:false// avoid drawing penalty for complex edges
}}};// if there are a lot of nodes, we cluster before we run the algorithm.
// NOTE: this part fails to find clusters for large scale-free networks, which should
//       be easily clusterable.
// TODO: examine why this is so
if(indices.length>clusterThreshold){const startLength=indices.length;while(indices.length>clusterThreshold&&level<=MAX_LEVELS){//console.time("clustering")
level+=1;const before=indices.length;// if there are many nodes we do a hubsize cluster
if(level%3===0){this.body.modules.clustering.clusterBridges(clusterOptions);}else {this.body.modules.clustering.clusterOutliers(clusterOptions);}const after=indices.length;if(before==after&&level%3!==0){this._declusterAll();this.body.emitter.emit("_layoutFailed");console.info("This network could not be positioned by this version of the improved layout algorithm."+" Please disable improvedLayout for better performance.");return;}//console.timeEnd("clustering")
//console.log(before,level,after);
}// increase the size of the edges
this.body.modules.kamadaKawai.setOptions({springLength:Math.max(150,2*startLength)});}if(level>MAX_LEVELS){console.info("The clustering didn't succeed within the amount of interations allowed,"+" progressing with partial result.");}// position the system for these nodes and edges
this.body.modules.kamadaKawai.solve(indices,this.body.edgeIndices,true);// shift to center point
this._shiftToCenter();// perturb the nodes a little bit to force the physics to kick in
const offset=70;for(let i=0;i<indices.length;i++){// Only perturb the nodes that aren't fixed
const node=this.body.nodes[indices[i]];if(node.predefinedPosition===false){node.x+=(0.5-this._rng())*offset;node.y+=(0.5-this._rng())*offset;}}// uncluster all clusters
this._declusterAll();// reposition all bezier nodes.
this.body.emitter.emit("_repositionBezierNodes");}}}/**
   * Move all the nodes towards to the center so gravitational pull wil not move the nodes away from view
   * @private
   */_shiftToCenter(){const range=NetworkUtil.getRangeCore(this.body.nodes,this.body.nodeIndices);const center=NetworkUtil.findCenter(range);for(let i=0;i<this.body.nodeIndices.length;i++){const node=this.body.nodes[this.body.nodeIndices[i]];node.x-=center.x;node.y-=center.y;}}/**
   * Expands all clusters
   * @private
   */_declusterAll(){let clustersPresent=true;while(clustersPresent===true){clustersPresent=false;for(let i=0;i<this.body.nodeIndices.length;i++){if(this.body.nodes[this.body.nodeIndices[i]].isCluster===true){clustersPresent=true;this.body.modules.clustering.openCluster(this.body.nodeIndices[i],{},false);}}if(clustersPresent===true){this.body.emitter.emit("_dataChanged");}}}/**
   *
   * @returns {number|*}
   */getSeed(){return this.initialRandomSeed;}/**
   * This is the main function to layout the nodes in a hierarchical way.
   * It checks if the node details are supplied correctly
   * @private
   */setupHierarchicalLayout(){if(this.options.hierarchical.enabled===true&&this.body.nodeIndices.length>0){// get the size of the largest hubs and check if the user has defined a level for a node.
let node,nodeId;let definedLevel=false;let undefinedLevel=false;this.lastNodeOnLevel={};this.hierarchical=new HierarchicalStatus();for(nodeId in this.body.nodes){if(Object.prototype.hasOwnProperty.call(this.body.nodes,nodeId)){node=this.body.nodes[nodeId];if(node.options.level!==undefined){definedLevel=true;this.hierarchical.levels[nodeId]=node.options.level;}else {undefinedLevel=true;}}}// if the user defined some levels but not all, alert and run without hierarchical layout
if(undefinedLevel===true&&definedLevel===true){throw new Error("To use the hierarchical layout, nodes require either no predefined levels"+" or levels have to be defined for all nodes.");}else {// define levels if undefined by the users. Based on hubsize.
if(undefinedLevel===true){const sortMethod=this.options.hierarchical.sortMethod;if(sortMethod==="hubsize"){this._determineLevelsByHubsize();}else if(sortMethod==="directed"){this._determineLevelsDirected();}else if(sortMethod==="custom"){this._determineLevelsCustomCallback();}}// fallback for cases where there are nodes but no edges
for(const nodeId in this.body.nodes){if(Object.prototype.hasOwnProperty.call(this.body.nodes,nodeId)){this.hierarchical.ensureLevel(nodeId);}}// check the distribution of the nodes per level.
const distribution=this._getDistribution();// get the parent children relations.
this._generateMap();// place the nodes on the canvas.
this._placeNodesByHierarchy(distribution);// condense the whitespace.
this._condenseHierarchy();// shift to center so gravity does not have to do much
this._shiftToCenter();}}}/**
   * @private
   */_condenseHierarchy(){var _this=this;// Global var in this scope to define when the movement has stopped.
let stillShifting=false;const branches={};// first we have some methods to help shifting trees around.
// the main method to shift the trees
const shiftTrees=()=>{const treeSizes=getTreeSizes();let shiftBy=0;for(let i=0;i<treeSizes.length-1;i++){const diff=treeSizes[i].max-treeSizes[i+1].min;shiftBy+=diff+this.options.hierarchical.treeSpacing;shiftTree(i+1,shiftBy);}};// shift a single tree by an offset
const shiftTree=(index,offset)=>{const trees=this.hierarchical.trees;for(const nodeId in trees){if(Object.prototype.hasOwnProperty.call(trees,nodeId)){if(trees[nodeId]===index){this.direction.shift(nodeId,offset);}}}};// get the width of all trees
const getTreeSizes=()=>{const treeWidths=[];for(let i=0;i<this.hierarchical.numTrees();i++){treeWidths.push(this.direction.getTreeSize(i));}return treeWidths;};// get a map of all nodes in this branch
const getBranchNodes=(source,map)=>{if(map[source.id]){return;}map[source.id]=true;if(this.hierarchical.childrenReference[source.id]){const children=this.hierarchical.childrenReference[source.id];if(children.length>0){for(let i=0;i<children.length;i++){getBranchNodes(this.body.nodes[children[i]],map);}}}};// get a min max width as well as the maximum movement space it has on either sides
// we use min max terminology because width and height can interchange depending on the direction of the layout
const getBranchBoundary=function(branchMap){let maxLevel=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1e9;let minSpace=1e9;let maxSpace=1e9;let min=1e9;let max=-1e9;for(const branchNode in branchMap){if(Object.prototype.hasOwnProperty.call(branchMap,branchNode)){const node=_this.body.nodes[branchNode];const level=_this.hierarchical.levels[node.id];const position=_this.direction.getPosition(node);// get the space around the node.
const[minSpaceNode,maxSpaceNode]=_this._getSpaceAroundNode(node,branchMap);minSpace=Math.min(minSpaceNode,minSpace);maxSpace=Math.min(maxSpaceNode,maxSpace);// the width is only relevant for the levels two nodes have in common. This is why we filter on this.
if(level<=maxLevel){min=Math.min(position,min);max=Math.max(position,max);}}}return [min,max,minSpace,maxSpace];};// check what the maximum level is these nodes have in common.
const getCollisionLevel=(node1,node2)=>{const maxLevel1=this.hierarchical.getMaxLevel(node1.id);const maxLevel2=this.hierarchical.getMaxLevel(node2.id);return Math.min(maxLevel1,maxLevel2);};/**
     * Condense elements. These can be nodes or branches depending on the callback.
     * @param {Function} callback
     * @param {Array.<number>} levels
     * @param {*} centerParents
     */const shiftElementsCloser=(callback,levels,centerParents)=>{const hier=this.hierarchical;for(let i=0;i<levels.length;i++){const level=levels[i];const levelNodes=hier.distributionOrdering[level];if(levelNodes.length>1){for(let j=0;j<levelNodes.length-1;j++){const node1=levelNodes[j];const node2=levelNodes[j+1];// NOTE: logic maintained as it was; if nodes have same ancestor,
//       then of course they are in the same sub-network.
if(hier.hasSameParent(node1,node2)&&hier.inSameSubNetwork(node1,node2)){callback(node1,node2,centerParents);}}}}};// callback for shifting branches
const branchShiftCallback=function(node1,node2){let centerParent=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;//window.CALLBACKS.push(() => {
const pos1=_this.direction.getPosition(node1);const pos2=_this.direction.getPosition(node2);const diffAbs=Math.abs(pos2-pos1);const nodeSpacing=_this.options.hierarchical.nodeSpacing;//console.log("NOW CHECKING:", node1.id, node2.id, diffAbs);
if(diffAbs>nodeSpacing){const branchNodes1={};const branchNodes2={};getBranchNodes(node1,branchNodes1);getBranchNodes(node2,branchNodes2);// check the largest distance between the branches
const maxLevel=getCollisionLevel(node1,node2);const branchNodeBoundary1=getBranchBoundary(branchNodes1,maxLevel);const branchNodeBoundary2=getBranchBoundary(branchNodes2,maxLevel);const max1=branchNodeBoundary1[1];const min2=branchNodeBoundary2[0];const minSpace2=branchNodeBoundary2[2];//console.log(node1.id, getBranchBoundary(branchNodes1, maxLevel), node2.id,
//            getBranchBoundary(branchNodes2, maxLevel), maxLevel);
const diffBranch=Math.abs(max1-min2);if(diffBranch>nodeSpacing){let offset=max1-min2+nodeSpacing;if(offset<-minSpace2+nodeSpacing){offset=-minSpace2+nodeSpacing;//console.log("RESETTING OFFSET", max1 - min2 + this.options.hierarchical.nodeSpacing, -minSpace2, offset);
}if(offset<0){//console.log("SHIFTING", node2.id, offset);
_this._shiftBlock(node2.id,offset);stillShifting=true;if(centerParent===true)_this._centerParent(node2);}}}//this.body.emitter.emit("_redraw");})
};const minimizeEdgeLength=(iterations,node)=>{//window.CALLBACKS.push(() => {
//  console.log("ts",node.id);
const nodeId=node.id;const allEdges=node.edges;const nodeLevel=this.hierarchical.levels[node.id];// gather constants
const C2=this.options.hierarchical.levelSeparation*this.options.hierarchical.levelSeparation;const referenceNodes={};const aboveEdges=[];for(let i=0;i<allEdges.length;i++){const edge=allEdges[i];if(edge.toId!=edge.fromId){const otherNode=edge.toId==nodeId?edge.from:edge.to;referenceNodes[allEdges[i].id]=otherNode;if(this.hierarchical.levels[otherNode.id]<nodeLevel){aboveEdges.push(edge);}}}// differentiated sum of lengths based on only moving one node over one axis
const getFx=(point,edges)=>{let sum=0;for(let i=0;i<edges.length;i++){if(referenceNodes[edges[i].id]!==undefined){const a=this.direction.getPosition(referenceNodes[edges[i].id])-point;sum+=a/Math.sqrt(a*a+C2);}}return sum;};// doubly differentiated sum of lengths based on only moving one node over one axis
const getDFx=(point,edges)=>{let sum=0;for(let i=0;i<edges.length;i++){if(referenceNodes[edges[i].id]!==undefined){const a=this.direction.getPosition(referenceNodes[edges[i].id])-point;sum-=C2*Math.pow(a*a+C2,-1.5);}}return sum;};const getGuess=(iterations,edges)=>{let guess=this.direction.getPosition(node);// Newton's method for optimization
const guessMap={};for(let i=0;i<iterations;i++){const fx=getFx(guess,edges);const dfx=getDFx(guess,edges);// we limit the movement to avoid instability.
const limit=40;const ratio=Math.max(-limit,Math.min(limit,Math.round(fx/dfx)));guess=guess-ratio;// reduce duplicates
if(guessMap[guess]!==undefined){break;}guessMap[guess]=i;}return guess;};const moveBranch=guess=>{// position node if there is space
const nodePosition=this.direction.getPosition(node);// check movable area of the branch
if(branches[node.id]===undefined){const branchNodes={};getBranchNodes(node,branchNodes);branches[node.id]=branchNodes;}const branchBoundary=getBranchBoundary(branches[node.id]);const minSpaceBranch=branchBoundary[2];const maxSpaceBranch=branchBoundary[3];const diff=guess-nodePosition;// check if we are allowed to move the node:
let branchOffset=0;if(diff>0){branchOffset=Math.min(diff,maxSpaceBranch-this.options.hierarchical.nodeSpacing);}else if(diff<0){branchOffset=-Math.min(-diff,minSpaceBranch-this.options.hierarchical.nodeSpacing);}if(branchOffset!=0){//console.log("moving branch:",branchOffset, maxSpaceBranch, minSpaceBranch)
this._shiftBlock(node.id,branchOffset);//this.body.emitter.emit("_redraw");
stillShifting=true;}};const moveNode=guess=>{const nodePosition=this.direction.getPosition(node);// position node if there is space
const[minSpace,maxSpace]=this._getSpaceAroundNode(node);const diff=guess-nodePosition;// check if we are allowed to move the node:
let newPosition=nodePosition;if(diff>0){newPosition=Math.min(nodePosition+(maxSpace-this.options.hierarchical.nodeSpacing),guess);}else if(diff<0){newPosition=Math.max(nodePosition-(minSpace-this.options.hierarchical.nodeSpacing),guess);}if(newPosition!==nodePosition){//console.log("moving Node:",diff, minSpace, maxSpace);
this.direction.setPosition(node,newPosition);//this.body.emitter.emit("_redraw");
stillShifting=true;}};let guess=getGuess(iterations,aboveEdges);moveBranch(guess);guess=getGuess(iterations,allEdges);moveNode(guess);//})
};// method to remove whitespace between branches. Because we do bottom up, we can center the parents.
const minimizeEdgeLengthBottomUp=iterations=>{let levels=this.hierarchical.getLevels();levels=_reverseInstanceProperty(levels).call(levels);for(let i=0;i<iterations;i++){stillShifting=false;for(let j=0;j<levels.length;j++){const level=levels[j];const levelNodes=this.hierarchical.distributionOrdering[level];for(let k=0;k<levelNodes.length;k++){minimizeEdgeLength(1000,levelNodes[k]);}}if(stillShifting!==true){//console.log("FINISHED minimizeEdgeLengthBottomUp IN " + i);
break;}}};// method to remove whitespace between branches. Because we do bottom up, we can center the parents.
const shiftBranchesCloserBottomUp=iterations=>{let levels=this.hierarchical.getLevels();levels=_reverseInstanceProperty(levels).call(levels);for(let i=0;i<iterations;i++){stillShifting=false;shiftElementsCloser(branchShiftCallback,levels,true);if(stillShifting!==true){//console.log("FINISHED shiftBranchesCloserBottomUp IN " + (i+1));
break;}}};// center all parents
const centerAllParents=()=>{for(const nodeId in this.body.nodes){if(Object.prototype.hasOwnProperty.call(this.body.nodes,nodeId))this._centerParent(this.body.nodes[nodeId]);}};// center all parents
const centerAllParentsBottomUp=()=>{let levels=this.hierarchical.getLevels();levels=_reverseInstanceProperty(levels).call(levels);for(let i=0;i<levels.length;i++){const level=levels[i];const levelNodes=this.hierarchical.distributionOrdering[level];for(let j=0;j<levelNodes.length;j++){this._centerParent(levelNodes[j]);}}};// the actual work is done here.
if(this.options.hierarchical.blockShifting===true){shiftBranchesCloserBottomUp(5);centerAllParents();}// minimize edge length
if(this.options.hierarchical.edgeMinimization===true){minimizeEdgeLengthBottomUp(20);}if(this.options.hierarchical.parentCentralization===true){centerAllParentsBottomUp();}shiftTrees();}/**
   * This gives the space around the node. IF a map is supplied, it will only check against nodes NOT in the map.
   * This is used to only get the distances to nodes outside of a branch.
   * @param {Node} node
   * @param {{Node.id: vis.Node}} map
   * @returns {number[]}
   * @private
   */_getSpaceAroundNode(node,map){let useMap=true;if(map===undefined){useMap=false;}const level=this.hierarchical.levels[node.id];if(level!==undefined){const index=this.hierarchical.distributionIndex[node.id];const position=this.direction.getPosition(node);const ordering=this.hierarchical.distributionOrdering[level];let minSpace=1e9;let maxSpace=1e9;if(index!==0){const prevNode=ordering[index-1];if(useMap===true&&map[prevNode.id]===undefined||useMap===false){const prevPos=this.direction.getPosition(prevNode);minSpace=position-prevPos;}}if(index!=ordering.length-1){const nextNode=ordering[index+1];if(useMap===true&&map[nextNode.id]===undefined||useMap===false){const nextPos=this.direction.getPosition(nextNode);maxSpace=Math.min(maxSpace,nextPos-position);}}return [minSpace,maxSpace];}else {return [0,0];}}/**
   * We use this method to center a parent node and check if it does not cross other nodes when it does.
   * @param {Node} node
   * @private
   */_centerParent(node){if(this.hierarchical.parentReference[node.id]){const parents=this.hierarchical.parentReference[node.id];for(let i=0;i<parents.length;i++){const parentId=parents[i];const parentNode=this.body.nodes[parentId];const children=this.hierarchical.childrenReference[parentId];if(children!==undefined){// get the range of the children
const newPosition=this._getCenterPosition(children);const position=this.direction.getPosition(parentNode);const[minSpace,maxSpace]=this._getSpaceAroundNode(parentNode);const diff=position-newPosition;if(diff<0&&Math.abs(diff)<maxSpace-this.options.hierarchical.nodeSpacing||diff>0&&Math.abs(diff)<minSpace-this.options.hierarchical.nodeSpacing){this.direction.setPosition(parentNode,newPosition);}}}}}/**
   * This function places the nodes on the canvas based on the hierarchial distribution.
   * @param {object} distribution | obtained by the function this._getDistribution()
   * @private
   */_placeNodesByHierarchy(distribution){this.positionedNodes={};// start placing all the level 0 nodes first. Then recursively position their branches.
for(const level in distribution){if(Object.prototype.hasOwnProperty.call(distribution,level)){var _context2;// sort nodes in level by position:
let nodeArray=_Object$keys(distribution[level]);nodeArray=this._indexArrayToNodes(nodeArray);_sortInstanceProperty(_context2=this.direction).call(_context2,nodeArray);let handledNodeCount=0;for(let i=0;i<nodeArray.length;i++){const node=nodeArray[i];if(this.positionedNodes[node.id]===undefined){const spacing=this.options.hierarchical.nodeSpacing;let pos=spacing*handledNodeCount;// We get the X or Y values we need and store them in pos and previousPos.
// The get and set make sure we get X or Y
if(handledNodeCount>0){pos=this.direction.getPosition(nodeArray[i-1])+spacing;}this.direction.setPosition(node,pos,level);this._validatePositionAndContinue(node,level,pos);handledNodeCount++;}}}}}/**
   * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
   * on a X position that ensures there will be no overlap.
   * @param {Node.id} parentId
   * @param {number} parentLevel
   * @private
   */_placeBranchNodes(parentId,parentLevel){var _context3;const childRef=this.hierarchical.childrenReference[parentId];// if this is not a parent, cancel the placing. This can happen with multiple parents to one child.
if(childRef===undefined){return;}// get a list of childNodes
const childNodes=[];for(let i=0;i<childRef.length;i++){childNodes.push(this.body.nodes[childRef[i]]);}// use the positions to order the nodes.
_sortInstanceProperty(_context3=this.direction).call(_context3,childNodes);// position the childNodes
for(let i=0;i<childNodes.length;i++){const childNode=childNodes[i];const childNodeLevel=this.hierarchical.levels[childNode.id];// check if the child node is below the parent node and if it has already been positioned.
if(childNodeLevel>parentLevel&&this.positionedNodes[childNode.id]===undefined){// get the amount of space required for this node. If parent the width is based on the amount of children.
const spacing=this.options.hierarchical.nodeSpacing;let pos;// we get the X or Y values we need and store them in pos and previousPos.
// The get and set make sure we get X or Y
if(i===0){pos=this.direction.getPosition(this.body.nodes[parentId]);}else {pos=this.direction.getPosition(childNodes[i-1])+spacing;}this.direction.setPosition(childNode,pos,childNodeLevel);this._validatePositionAndContinue(childNode,childNodeLevel,pos);}else {return;}}// center the parent nodes.
const center=this._getCenterPosition(childNodes);this.direction.setPosition(this.body.nodes[parentId],center,parentLevel);}/**
   * This method checks for overlap and if required shifts the branch. It also keeps records of positioned nodes.
   * Finally it will call _placeBranchNodes to place the branch nodes.
   * @param {Node} node
   * @param {number} level
   * @param {number} pos
   * @private
   */_validatePositionAndContinue(node,level,pos){// This method only works for formal trees and formal forests
// Early exit if this is not the case
if(!this.hierarchical.isTree)return;// if overlap has been detected, we shift the branch
if(this.lastNodeOnLevel[level]!==undefined){const previousPos=this.direction.getPosition(this.body.nodes[this.lastNodeOnLevel[level]]);if(pos-previousPos<this.options.hierarchical.nodeSpacing){const diff=previousPos+this.options.hierarchical.nodeSpacing-pos;const sharedParent=this._findCommonParent(this.lastNodeOnLevel[level],node.id);this._shiftBlock(sharedParent.withChild,diff);}}this.lastNodeOnLevel[level]=node.id;// store change in position.
this.positionedNodes[node.id]=true;this._placeBranchNodes(node.id,level);}/**
   * Receives an array with node indices and returns an array with the actual node references.
   * Used for sorting based on node properties.
   * @param {Array.<Node.id>} idArray
   * @returns {Array.<Node>}
   */_indexArrayToNodes(idArray){const array=[];for(let i=0;i<idArray.length;i++){array.push(this.body.nodes[idArray[i]]);}return array;}/**
   * This function get the distribution of levels based on hubsize
   * @returns {object}
   * @private
   */_getDistribution(){const distribution={};let nodeId,node;// we fix Y because the hierarchy is vertical,
// we fix X so we do not give a node an x position for a second time.
// the fix of X is removed after the x value has been set.
for(nodeId in this.body.nodes){if(Object.prototype.hasOwnProperty.call(this.body.nodes,nodeId)){node=this.body.nodes[nodeId];const level=this.hierarchical.levels[nodeId]===undefined?0:this.hierarchical.levels[nodeId];this.direction.fix(node,level);if(distribution[level]===undefined){distribution[level]={};}distribution[level][nodeId]=node;}}return distribution;}/**
   * Return the active (i.e. visible) edges for this node
   * @param {Node} node
   * @returns {Array.<vis.Edge>} Array of edge instances
   * @private
   */_getActiveEdges(node){const result=[];forEach(node.edges,edge=>{var _context4;if(_indexOfInstanceProperty(_context4=this.body.edgeIndices).call(_context4,edge.id)!==-1){result.push(edge);}});return result;}/**
   * Get the hubsizes for all active nodes.
   * @returns {number}
   * @private
   */_getHubSizes(){const hubSizes={};const nodeIds=this.body.nodeIndices;forEach(nodeIds,nodeId=>{const node=this.body.nodes[nodeId];const hubSize=this._getActiveEdges(node).length;hubSizes[hubSize]=true;});// Make an array of the size sorted descending
const result=[];forEach(hubSizes,size=>{result.push(Number(size));});_sortInstanceProperty(result).call(result,function(a,b){return b-a;});return result;}/**
   * this function allocates nodes in levels based on the recursive branching from the largest hubs.
   * @private
   */_determineLevelsByHubsize(){const levelDownstream=(nodeA,nodeB)=>{this.hierarchical.levelDownstream(nodeA,nodeB);};const hubSizes=this._getHubSizes();for(let i=0;i<hubSizes.length;++i){const hubSize=hubSizes[i];if(hubSize===0)break;forEach(this.body.nodeIndices,nodeId=>{const node=this.body.nodes[nodeId];if(hubSize===this._getActiveEdges(node).length){this._crawlNetwork(levelDownstream,nodeId);}});}}/**
   * TODO: release feature
   * TODO: Determine if this feature is needed at all
   * @private
   */_determineLevelsCustomCallback(){const minLevel=100000;// TODO: this should come from options.
// eslint-disable-next-line no-unused-vars -- This should eventually be implemented with these parameters used.
const customCallback=function(nodeA,nodeB,edge){};// TODO: perhaps move to HierarchicalStatus.
//       But I currently don't see the point, this method is not used.
const levelByDirection=(nodeA,nodeB,edge)=>{let levelA=this.hierarchical.levels[nodeA.id];// set initial level
if(levelA===undefined){levelA=this.hierarchical.levels[nodeA.id]=minLevel;}const diff=customCallback(NetworkUtil.cloneOptions(nodeA,"node"),NetworkUtil.cloneOptions(nodeB,"node"),NetworkUtil.cloneOptions(edge,"edge"));this.hierarchical.levels[nodeB.id]=levelA+diff;};this._crawlNetwork(levelByDirection);this.hierarchical.setMinLevelToZero();}/**
   * Allocate nodes in levels based on the direction of the edges.
   * @private
   */_determineLevelsDirected(){var _context5;const nodes=_reduceInstanceProperty(_context5=this.body.nodeIndices).call(_context5,(acc,id)=>{acc.set(id,this.body.nodes[id]);return acc;},new _Map());if(this.options.hierarchical.shakeTowards==="roots"){this.hierarchical.levels=fillLevelsByDirectionRoots(nodes);}else {this.hierarchical.levels=fillLevelsByDirectionLeaves(nodes);}this.hierarchical.setMinLevelToZero();}/**
   * Update the bookkeeping of parent and child.
   * @private
   */_generateMap(){const fillInRelations=(parentNode,childNode)=>{if(this.hierarchical.levels[childNode.id]>this.hierarchical.levels[parentNode.id]){this.hierarchical.addRelation(parentNode.id,childNode.id);}};this._crawlNetwork(fillInRelations);this.hierarchical.checkIfTree();}/**
   * Crawl over the entire network and use a callback on each node couple that is connected to each other.
   * @param {Function} [callback]          | will receive nodeA, nodeB and the connecting edge. A and B are distinct.
   * @param {Node.id} startingNodeId
   * @private
   */_crawlNetwork(){let callback=arguments.length>0&&arguments[0]!==undefined?arguments[0]:function(){};let startingNodeId=arguments.length>1?arguments[1]:undefined;const progress={};const crawler=(node,tree)=>{if(progress[node.id]===undefined){this.hierarchical.setTreeIndex(node,tree);progress[node.id]=true;let childNode;const edges=this._getActiveEdges(node);for(let i=0;i<edges.length;i++){const edge=edges[i];if(edge.connected===true){if(edge.toId==node.id){// Not '===' because id's can be string and numeric
childNode=edge.from;}else {childNode=edge.to;}if(node.id!=childNode.id){// Not '!==' because id's can be string and numeric
callback(node,childNode,edge);crawler(childNode,tree);}}}}};if(startingNodeId===undefined){// Crawl over all nodes
let treeIndex=0;// Serves to pass a unique id for the current distinct tree
for(let i=0;i<this.body.nodeIndices.length;i++){const nodeId=this.body.nodeIndices[i];if(progress[nodeId]===undefined){const node=this.body.nodes[nodeId];crawler(node,treeIndex);treeIndex+=1;}}}else {// Crawl from the given starting node
const node=this.body.nodes[startingNodeId];if(node===undefined){console.error("Node not found:",startingNodeId);return;}crawler(node);}}/**
   * Shift a branch a certain distance
   * @param {Node.id} parentId
   * @param {number} diff
   * @private
   */_shiftBlock(parentId,diff){const progress={};const shifter=parentId=>{if(progress[parentId]){return;}progress[parentId]=true;this.direction.shift(parentId,diff);const childRef=this.hierarchical.childrenReference[parentId];if(childRef!==undefined){for(let i=0;i<childRef.length;i++){shifter(childRef[i]);}}};shifter(parentId);}/**
   * Find a common parent between branches.
   * @param {Node.id} childA
   * @param {Node.id} childB
   * @returns {{foundParent, withChild}}
   * @private
   */_findCommonParent(childA,childB){const parents={};const iterateParents=(parents,child)=>{const parentRef=this.hierarchical.parentReference[child];if(parentRef!==undefined){for(let i=0;i<parentRef.length;i++){const parent=parentRef[i];parents[parent]=true;iterateParents(parents,parent);}}};const findParent=(parents,child)=>{const parentRef=this.hierarchical.parentReference[child];if(parentRef!==undefined){for(let i=0;i<parentRef.length;i++){const parent=parentRef[i];if(parents[parent]!==undefined){return {foundParent:parent,withChild:child};}const branch=findParent(parents,parent);if(branch.foundParent!==null){return branch;}}}return {foundParent:null,withChild:child};};iterateParents(parents,childA);return findParent(parents,childB);}/**
   * Set the strategy pattern for handling the coordinates given the current direction.
   *
   * The individual instances contain all the operations and data specific to a layout direction.
   * @param {Node} node
   * @param {{x: number, y: number}} position
   * @param {number} level
   * @param {boolean} [doNotUpdate]
   * @private
   */setDirectionStrategy(){const isVertical=this.options.hierarchical.direction==="UD"||this.options.hierarchical.direction==="DU";if(isVertical){this.direction=new VerticalStrategy(this);}else {this.direction=new HorizontalStrategy(this);}}/**
   * Determine the center position of a branch from the passed list of child nodes
   *
   * This takes into account the positions of all the child nodes.
   * @param {Array.<Node|vis.Node.id>} childNodes  Array of either child nodes or node id's
   * @returns {number}
   * @private
   */_getCenterPosition(childNodes){let minPos=1e9;let maxPos=-1e9;for(let i=0;i<childNodes.length;i++){let childNode;if(childNodes[i].id!==undefined){childNode=childNodes[i];}else {const childNodeId=childNodes[i];childNode=this.body.nodes[childNodeId];}const position=this.direction.getPosition(childNode);minPos=Math.min(minPos,position);maxPos=Math.max(maxPos,position);}return 0.5*(minPos+maxPos);}}/**
 * Clears the toolbar div element of children
 * @private
 */class ManipulationSystem{/**
   * @param {object} body
   * @param {Canvas} canvas
   * @param {SelectionHandler} selectionHandler
   * @param {InteractionHandler} interactionHandler
   */constructor(body,canvas,selectionHandler,interactionHandler){var _context,_context2;this.body=body;this.canvas=canvas;this.selectionHandler=selectionHandler;this.interactionHandler=interactionHandler;this.editMode=false;this.manipulationDiv=undefined;this.editModeDiv=undefined;this.closeDiv=undefined;this._domEventListenerCleanupQueue=[];this.temporaryUIFunctions={};this.temporaryEventFunctions=[];this.touchTime=0;this.temporaryIds={nodes:[],edges:[]};this.guiEnabled=false;this.inMode=false;this.selectedControlNode=undefined;this.options={};this.defaultOptions={enabled:false,initiallyActive:false,addNode:true,addEdge:true,editNode:undefined,editEdge:true,deleteNode:true,deleteEdge:true,controlNodeStyle:{shape:"dot",size:6,color:{background:"#ff0000",border:"#3c3c3c",highlight:{background:"#07f968",border:"#3c3c3c"}},borderWidth:2,borderWidthSelected:2}};_Object$assign(this.options,this.defaultOptions);this.body.emitter.on("destroy",()=>{this._clean();});this.body.emitter.on("_dataChanged",_bindInstanceProperty(_context=this._restore).call(_context,this));this.body.emitter.on("_resetData",_bindInstanceProperty(_context2=this._restore).call(_context2,this));}/**
   * If something changes in the data during editing, switch back to the initial datamanipulation state and close all edit modes.
   * @private
   */_restore(){if(this.inMode!==false){if(this.options.initiallyActive===true){this.enableEditMode();}else {this.disableEditMode();}}}/**
   * Set the Options
   * @param {object} options
   * @param {object} allOptions
   * @param {object} globalOptions
   */setOptions(options,allOptions,globalOptions){if(allOptions!==undefined){if(allOptions.locale!==undefined){this.options.locale=allOptions.locale;}else {this.options.locale=globalOptions.locale;}if(allOptions.locales!==undefined){this.options.locales=allOptions.locales;}else {this.options.locales=globalOptions.locales;}}if(options!==undefined){if(typeof options==="boolean"){this.options.enabled=options;}else {this.options.enabled=true;deepExtend(this.options,options);}if(this.options.initiallyActive===true){this.editMode=true;}this._setup();}}/**
   * Enable or disable edit-mode. Draws the DOM required and cleans up after itself.
   * @private
   */toggleEditMode(){if(this.editMode===true){this.disableEditMode();}else {this.enableEditMode();}}/**
   * Enables Edit Mode
   */enableEditMode(){this.editMode=true;this._clean();if(this.guiEnabled===true){this.manipulationDiv.style.display="block";this.closeDiv.style.display="block";this.editModeDiv.style.display="none";this.showManipulatorToolbar();}}/**
   * Disables Edit Mode
   */disableEditMode(){this.editMode=false;this._clean();if(this.guiEnabled===true){this.manipulationDiv.style.display="none";this.closeDiv.style.display="none";this.editModeDiv.style.display="block";this._createEditButton();}}/**
   * Creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar.
   * @private
   */showManipulatorToolbar(){// restore the state of any bound functions or events, remove control nodes, restore physics
this._clean();// reset global variables
this.manipulationDOM={};// if the gui is enabled, draw all elements.
if(this.guiEnabled===true){var _context3,_context4;// a _restore will hide these menus
this.editMode=true;this.manipulationDiv.style.display="block";this.closeDiv.style.display="block";const selectedNodeCount=this.selectionHandler.getSelectedNodeCount();const selectedEdgeCount=this.selectionHandler.getSelectedEdgeCount();const selectedTotalCount=selectedNodeCount+selectedEdgeCount;const locale=this.options.locales[this.options.locale];let needSeperator=false;if(this.options.addNode!==false){this._createAddNodeButton(locale);needSeperator=true;}if(this.options.addEdge!==false){if(needSeperator===true){this._createSeperator(1);}else {needSeperator=true;}this._createAddEdgeButton(locale);}if(selectedNodeCount===1&&typeof this.options.editNode==="function"){if(needSeperator===true){this._createSeperator(2);}else {needSeperator=true;}this._createEditNodeButton(locale);}else if(selectedEdgeCount===1&&selectedNodeCount===0&&this.options.editEdge!==false){if(needSeperator===true){this._createSeperator(3);}else {needSeperator=true;}this._createEditEdgeButton(locale);}// remove buttons
if(selectedTotalCount!==0){if(selectedNodeCount>0&&this.options.deleteNode!==false){if(needSeperator===true){this._createSeperator(4);}this._createDeleteButton(locale);}else if(selectedNodeCount===0&&this.options.deleteEdge!==false){if(needSeperator===true){this._createSeperator(4);}this._createDeleteButton(locale);}}// bind the close button
this._bindElementEvents(this.closeDiv,_bindInstanceProperty(_context3=this.toggleEditMode).call(_context3,this));// refresh this bar based on what has been selected
this._temporaryBindEvent("select",_bindInstanceProperty(_context4=this.showManipulatorToolbar).call(_context4,this));}// redraw to show any possible changes
this.body.emitter.emit("_redraw");}/**
   * Create the toolbar for adding Nodes
   */addNodeMode(){var _context6;// when using the gui, enable edit mode if it wasnt already.
if(this.editMode!==true){this.enableEditMode();}// restore the state of any bound functions or events, remove control nodes, restore physics
this._clean();this.inMode="addNode";if(this.guiEnabled===true){var _context5;const locale=this.options.locales[this.options.locale];this.manipulationDOM={};this._createBackButton(locale);this._createSeperator();this._createDescription(locale["addDescription"]||this.options.locales["en"]["addDescription"]);// bind the close button
this._bindElementEvents(this.closeDiv,_bindInstanceProperty(_context5=this.toggleEditMode).call(_context5,this));}this._temporaryBindEvent("click",_bindInstanceProperty(_context6=this._performAddNode).call(_context6,this));}/**
   * call the bound function to handle the editing of the node. The node has to be selected.
   */editNode(){// when using the gui, enable edit mode if it wasnt already.
if(this.editMode!==true){this.enableEditMode();}// restore the state of any bound functions or events, remove control nodes, restore physics
this._clean();const node=this.selectionHandler.getSelectedNodes()[0];if(node!==undefined){this.inMode="editNode";if(typeof this.options.editNode==="function"){if(node.isCluster!==true){const data=deepExtend({},node.options,false);data.x=node.x;data.y=node.y;if(this.options.editNode.length===2){this.options.editNode(data,finalizedData=>{if(finalizedData!==null&&finalizedData!==undefined&&this.inMode==="editNode"){// if for whatever reason the mode has changes (due to dataset change) disregard the callback) {
this.body.data.nodes.getDataSet().update(finalizedData);}this.showManipulatorToolbar();});}else {throw new Error("The function for edit does not support two arguments (data, callback)");}}else {alert(this.options.locales[this.options.locale]["editClusterError"]||this.options.locales["en"]["editClusterError"]);}}else {throw new Error("No function has been configured to handle the editing of nodes.");}}else {this.showManipulatorToolbar();}}/**
   * create the toolbar to connect nodes
   */addEdgeMode(){var _context8,_context9,_context0,_context1,_context10;// when using the gui, enable edit mode if it wasnt already.
if(this.editMode!==true){this.enableEditMode();}// restore the state of any bound functions or events, remove control nodes, restore physics
this._clean();this.inMode="addEdge";if(this.guiEnabled===true){var _context7;const locale=this.options.locales[this.options.locale];this.manipulationDOM={};this._createBackButton(locale);this._createSeperator();this._createDescription(locale["edgeDescription"]||this.options.locales["en"]["edgeDescription"]);// bind the close button
this._bindElementEvents(this.closeDiv,_bindInstanceProperty(_context7=this.toggleEditMode).call(_context7,this));}// temporarily overload functions
this._temporaryBindUI("onTouch",_bindInstanceProperty(_context8=this._handleConnect).call(_context8,this));this._temporaryBindUI("onDragEnd",_bindInstanceProperty(_context9=this._finishConnect).call(_context9,this));this._temporaryBindUI("onDrag",_bindInstanceProperty(_context0=this._dragControlNode).call(_context0,this));this._temporaryBindUI("onRelease",_bindInstanceProperty(_context1=this._finishConnect).call(_context1,this));this._temporaryBindUI("onDragStart",_bindInstanceProperty(_context10=this._dragStartEdge).call(_context10,this));this._temporaryBindUI("onHold",()=>{});}/**
   * create the toolbar to edit edges
   */editEdgeMode(){// when using the gui, enable edit mode if it wasn't already.
if(this.editMode!==true){this.enableEditMode();}// restore the state of any bound functions or events, remove control nodes, restore physics
this._clean();this.inMode="editEdge";if(typeof this.options.editEdge==="object"&&typeof this.options.editEdge.editWithoutDrag==="function"){this.edgeBeingEditedId=this.selectionHandler.getSelectedEdgeIds()[0];if(this.edgeBeingEditedId!==undefined){const edge=this.body.edges[this.edgeBeingEditedId];this._performEditEdge(edge.from.id,edge.to.id);return;}}if(this.guiEnabled===true){var _context11;const locale=this.options.locales[this.options.locale];this.manipulationDOM={};this._createBackButton(locale);this._createSeperator();this._createDescription(locale["editEdgeDescription"]||this.options.locales["en"]["editEdgeDescription"]);// bind the close button
this._bindElementEvents(this.closeDiv,_bindInstanceProperty(_context11=this.toggleEditMode).call(_context11,this));}this.edgeBeingEditedId=this.selectionHandler.getSelectedEdgeIds()[0];if(this.edgeBeingEditedId!==undefined){var _context12,_context13,_context14,_context15;const edge=this.body.edges[this.edgeBeingEditedId];// create control nodes
const controlNodeFrom=this._getNewTargetNode(edge.from.x,edge.from.y);const controlNodeTo=this._getNewTargetNode(edge.to.x,edge.to.y);this.temporaryIds.nodes.push(controlNodeFrom.id);this.temporaryIds.nodes.push(controlNodeTo.id);this.body.nodes[controlNodeFrom.id]=controlNodeFrom;this.body.nodeIndices.push(controlNodeFrom.id);this.body.nodes[controlNodeTo.id]=controlNodeTo;this.body.nodeIndices.push(controlNodeTo.id);// temporarily overload UI functions, cleaned up automatically because of _temporaryBindUI
this._temporaryBindUI("onTouch",_bindInstanceProperty(_context12=this._controlNodeTouch).call(_context12,this));// used to get the position
this._temporaryBindUI("onTap",()=>{});// disabled
this._temporaryBindUI("onHold",()=>{});// disabled
this._temporaryBindUI("onDragStart",_bindInstanceProperty(_context13=this._controlNodeDragStart).call(_context13,this));// used to select control node
this._temporaryBindUI("onDrag",_bindInstanceProperty(_context14=this._controlNodeDrag).call(_context14,this));// used to drag control node
this._temporaryBindUI("onDragEnd",_bindInstanceProperty(_context15=this._controlNodeDragEnd).call(_context15,this));// used to connect or revert control nodes
this._temporaryBindUI("onMouseMove",()=>{});// disabled
// create function to position control nodes correctly on movement
// automatically cleaned up because we use the temporary bind
this._temporaryBindEvent("beforeDrawing",ctx=>{const positions=edge.edgeType.findBorderPositions(ctx);if(controlNodeFrom.selected===false){controlNodeFrom.x=positions.from.x;controlNodeFrom.y=positions.from.y;}if(controlNodeTo.selected===false){controlNodeTo.x=positions.to.x;controlNodeTo.y=positions.to.y;}});this.body.emitter.emit("_redraw");}else {this.showManipulatorToolbar();}}/**
   * delete everything in the selection
   */deleteSelected(){// when using the gui, enable edit mode if it wasnt already.
if(this.editMode!==true){this.enableEditMode();}// restore the state of any bound functions or events, remove control nodes, restore physics
this._clean();this.inMode="delete";const selectedNodes=this.selectionHandler.getSelectedNodeIds();const selectedEdges=this.selectionHandler.getSelectedEdgeIds();let deleteFunction=undefined;if(selectedNodes.length>0){for(let i=0;i<selectedNodes.length;i++){if(this.body.nodes[selectedNodes[i]].isCluster===true){alert(this.options.locales[this.options.locale]["deleteClusterError"]||this.options.locales["en"]["deleteClusterError"]);return;}}if(typeof this.options.deleteNode==="function"){deleteFunction=this.options.deleteNode;}}else if(selectedEdges.length>0){if(typeof this.options.deleteEdge==="function"){deleteFunction=this.options.deleteEdge;}}if(typeof deleteFunction==="function"){const data={nodes:selectedNodes,edges:selectedEdges};if(deleteFunction.length===2){deleteFunction(data,finalizedData=>{if(finalizedData!==null&&finalizedData!==undefined&&this.inMode==="delete"){// if for whatever reason the mode has changes (due to dataset change) disregard the callback) {
this.body.data.edges.getDataSet().remove(finalizedData.edges);this.body.data.nodes.getDataSet().remove(finalizedData.nodes);this.body.emitter.emit("startSimulation");this.showManipulatorToolbar();}else {this.body.emitter.emit("startSimulation");this.showManipulatorToolbar();}});}else {throw new Error("The function for delete does not support two arguments (data, callback)");}}else {this.body.data.edges.getDataSet().remove(selectedEdges);this.body.data.nodes.getDataSet().remove(selectedNodes);this.body.emitter.emit("startSimulation");this.showManipulatorToolbar();}}//********************************************** PRIVATE ***************************************//
/**
   * draw or remove the DOM
   * @private
   */_setup(){if(this.options.enabled===true){// Enable the GUI
this.guiEnabled=true;this._createWrappers();if(this.editMode===false){this._createEditButton();}else {this.showManipulatorToolbar();}}else {this._removeManipulationDOM();// disable the gui
this.guiEnabled=false;}}/**
   * create the div overlays that contain the DOM
   * @private
   */_createWrappers(){// load the manipulator HTML elements. All styling done in css.
if(this.manipulationDiv===undefined){this.manipulationDiv=document.createElement("div");this.manipulationDiv.className="vis-manipulation";if(this.editMode===true){this.manipulationDiv.style.display="block";}else {this.manipulationDiv.style.display="none";}this.canvas.frame.appendChild(this.manipulationDiv);}// container for the edit button.
if(this.editModeDiv===undefined){this.editModeDiv=document.createElement("div");this.editModeDiv.className="vis-edit-mode";if(this.editMode===true){this.editModeDiv.style.display="none";}else {this.editModeDiv.style.display="block";}this.canvas.frame.appendChild(this.editModeDiv);}// container for the close div button
if(this.closeDiv===undefined){var _this$options$locales,_this$options$locales2;this.closeDiv=document.createElement("button");this.closeDiv.className="vis-close";this.closeDiv.setAttribute("aria-label",(_this$options$locales=(_this$options$locales2=this.options.locales[this.options.locale])===null||_this$options$locales2===void 0?void 0:_this$options$locales2["close"])!==null&&_this$options$locales!==void 0?_this$options$locales:this.options.locales["en"]["close"]);this.closeDiv.style.display=this.manipulationDiv.style.display;this.canvas.frame.appendChild(this.closeDiv);}}/**
   * generate a new target node. Used for creating new edges and editing edges
   * @param {number} x
   * @param {number} y
   * @returns {Node}
   * @private
   */_getNewTargetNode(x,y){const controlNodeStyle=deepExtend({},this.options.controlNodeStyle);controlNodeStyle.id="targetNode"+v4();controlNodeStyle.hidden=false;controlNodeStyle.physics=false;controlNodeStyle.x=x;controlNodeStyle.y=y;// we have to define the bounding box in order for the nodes to be drawn immediately
const node=this.body.functions.createNode(controlNodeStyle);node.shape.boundingBox={left:x,right:x,top:y,bottom:y};return node;}/**
   * Create the edit button
   */_createEditButton(){var _context16;// restore everything to it's original state (if applicable)
this._clean();// reset the manipulationDOM
this.manipulationDOM={};// empty the editModeDiv
recursiveDOMDelete(this.editModeDiv);// create the contents for the editMode button
const locale=this.options.locales[this.options.locale];const button=this._createButton("editMode","vis-edit vis-edit-mode",locale["edit"]||this.options.locales["en"]["edit"]);this.editModeDiv.appendChild(button);// bind a hammer listener to the button, calling the function toggleEditMode.
this._bindElementEvents(button,_bindInstanceProperty(_context16=this.toggleEditMode).call(_context16,this));}/**
   * this function cleans up after everything this module does. Temporary elements, functions and events are removed, physics restored, hammers removed.
   * @private
   */_clean(){// not in mode
this.inMode=false;// _clean the divs
if(this.guiEnabled===true){recursiveDOMDelete(this.editModeDiv);recursiveDOMDelete(this.manipulationDiv);// removes all the bindings and overloads
this._cleanupDOMEventListeners();}// remove temporary nodes and edges
this._cleanupTemporaryNodesAndEdges();// restore overloaded UI functions
this._unbindTemporaryUIs();// remove the temporaryEventFunctions
this._unbindTemporaryEvents();// restore the physics if required
this.body.emitter.emit("restorePhysics");}/**
   * Each dom element has it's own hammer. They are stored in this.manipulationHammers. This cleans them up.
   * @private
   */_cleanupDOMEventListeners(){// _clean DOM event listener bindings
for(const callback of _spliceInstanceProperty(_context17=this._domEventListenerCleanupQueue).call(_context17,0)){var _context17;callback();}}/**
   * Remove all DOM elements created by this module.
   * @private
   */_removeManipulationDOM(){// removes all the bindings and overloads
this._clean();// empty the manipulation divs
recursiveDOMDelete(this.manipulationDiv);recursiveDOMDelete(this.editModeDiv);recursiveDOMDelete(this.closeDiv);// remove the manipulation divs
if(this.manipulationDiv){this.canvas.frame.removeChild(this.manipulationDiv);}if(this.editModeDiv){this.canvas.frame.removeChild(this.editModeDiv);}if(this.closeDiv){this.canvas.frame.removeChild(this.closeDiv);}// set the references to undefined
this.manipulationDiv=undefined;this.editModeDiv=undefined;this.closeDiv=undefined;}/**
   * create a seperator line. the index is to differentiate in the manipulation dom
   * @param {number} [index]
   * @private
   */_createSeperator(){let index=arguments.length>0&&arguments[0]!==undefined?arguments[0]:1;this.manipulationDOM["seperatorLineDiv"+index]=document.createElement("div");this.manipulationDOM["seperatorLineDiv"+index].className="vis-separator-line";this.manipulationDiv.appendChild(this.manipulationDOM["seperatorLineDiv"+index]);}// ----------------------    DOM functions for buttons    --------------------------//
/**
   *
   * @param {Locale} locale
   * @private
   */_createAddNodeButton(locale){var _context18;const button=this._createButton("addNode","vis-add",locale["addNode"]||this.options.locales["en"]["addNode"]);this.manipulationDiv.appendChild(button);this._bindElementEvents(button,_bindInstanceProperty(_context18=this.addNodeMode).call(_context18,this));}/**
   *
   * @param {Locale} locale
   * @private
   */_createAddEdgeButton(locale){var _context19;const button=this._createButton("addEdge","vis-connect",locale["addEdge"]||this.options.locales["en"]["addEdge"]);this.manipulationDiv.appendChild(button);this._bindElementEvents(button,_bindInstanceProperty(_context19=this.addEdgeMode).call(_context19,this));}/**
   *
   * @param {Locale} locale
   * @private
   */_createEditNodeButton(locale){var _context20;const button=this._createButton("editNode","vis-edit",locale["editNode"]||this.options.locales["en"]["editNode"]);this.manipulationDiv.appendChild(button);this._bindElementEvents(button,_bindInstanceProperty(_context20=this.editNode).call(_context20,this));}/**
   *
   * @param {Locale} locale
   * @private
   */_createEditEdgeButton(locale){var _context21;const button=this._createButton("editEdge","vis-edit",locale["editEdge"]||this.options.locales["en"]["editEdge"]);this.manipulationDiv.appendChild(button);this._bindElementEvents(button,_bindInstanceProperty(_context21=this.editEdgeMode).call(_context21,this));}/**
   *
   * @param {Locale} locale
   * @private
   */_createDeleteButton(locale){var _context22;let deleteBtnClass;if(this.options.rtl){deleteBtnClass="vis-delete-rtl";}else {deleteBtnClass="vis-delete";}const button=this._createButton("delete",deleteBtnClass,locale["del"]||this.options.locales["en"]["del"]);this.manipulationDiv.appendChild(button);this._bindElementEvents(button,_bindInstanceProperty(_context22=this.deleteSelected).call(_context22,this));}/**
   *
   * @param {Locale} locale
   * @private
   */_createBackButton(locale){var _context23;const button=this._createButton("back","vis-back",locale["back"]||this.options.locales["en"]["back"]);this.manipulationDiv.appendChild(button);this._bindElementEvents(button,_bindInstanceProperty(_context23=this.showManipulatorToolbar).call(_context23,this));}/**
   *
   * @param {number|string} id
   * @param {string} className
   * @param {label} label
   * @param {string} labelClassName
   * @returns {HTMLElement}
   * @private
   */_createButton(id,className,label){let labelClassName=arguments.length>3&&arguments[3]!==undefined?arguments[3]:"vis-label";this.manipulationDOM[id+"Div"]=document.createElement("button");this.manipulationDOM[id+"Div"].className="vis-button "+className;this.manipulationDOM[id+"Label"]=document.createElement("div");this.manipulationDOM[id+"Label"].className=labelClassName;this.manipulationDOM[id+"Label"].innerText=label;this.manipulationDOM[id+"Div"].appendChild(this.manipulationDOM[id+"Label"]);return this.manipulationDOM[id+"Div"];}/**
   *
   * @param {Label} label
   * @private
   */_createDescription(label){this.manipulationDOM["descriptionLabel"]=document.createElement("div");this.manipulationDOM["descriptionLabel"].className="vis-none";this.manipulationDOM["descriptionLabel"].innerText=label;this.manipulationDiv.appendChild(this.manipulationDOM["descriptionLabel"]);}// -------------------------- End of DOM functions for buttons ------------------------------//
/**
   * this binds an event until cleanup by the clean functions.
   * @param {Event}  event   The event
   * @param {Function} newFunction
   * @private
   */_temporaryBindEvent(event,newFunction){this.temporaryEventFunctions.push({event:event,boundFunction:newFunction});this.body.emitter.on(event,newFunction);}/**
   * this overrides an UI function until cleanup by the clean function
   * @param {string} UIfunctionName
   * @param {Function} newFunction
   * @private
   */_temporaryBindUI(UIfunctionName,newFunction){if(this.body.eventListeners[UIfunctionName]!==undefined){this.temporaryUIFunctions[UIfunctionName]=this.body.eventListeners[UIfunctionName];this.body.eventListeners[UIfunctionName]=newFunction;}else {throw new Error("This UI function does not exist. Typo? You tried: "+UIfunctionName+" possible are: "+_JSON$stringify(_Object$keys(this.body.eventListeners)));}}/**
   * Restore the overridden UI functions to their original state.
   * @private
   */_unbindTemporaryUIs(){for(const functionName in this.temporaryUIFunctions){if(Object.prototype.hasOwnProperty.call(this.temporaryUIFunctions,functionName)){this.body.eventListeners[functionName]=this.temporaryUIFunctions[functionName];delete this.temporaryUIFunctions[functionName];}}this.temporaryUIFunctions={};}/**
   * Unbind the events created by _temporaryBindEvent
   * @private
   */_unbindTemporaryEvents(){for(let i=0;i<this.temporaryEventFunctions.length;i++){const eventName=this.temporaryEventFunctions[i].event;const boundFunction=this.temporaryEventFunctions[i].boundFunction;this.body.emitter.off(eventName,boundFunction);}this.temporaryEventFunctions=[];}/**
   * Bind an hammer instance to a DOM element.
   * @param {Element} domElement
   * @param {Function} boundFunction
   */_bindElementEvents(domElement,boundFunction){// Bind touch events.
const hammer=new Hammer(domElement,{});onTouch(hammer,boundFunction);this._domEventListenerCleanupQueue.push(()=>{hammer.destroy();});// Bind keyboard events.
const keyupListener=_ref=>{let{keyCode,key}=_ref;if(key==="Enter"||key===" "||keyCode===13||keyCode===32){boundFunction();}};domElement.addEventListener("keyup",keyupListener,false);this._domEventListenerCleanupQueue.push(()=>{domElement.removeEventListener("keyup",keyupListener,false);});}/**
   * Neatly clean up temporary edges and nodes
   * @private
   */_cleanupTemporaryNodesAndEdges(){// _clean temporary edges
for(let i=0;i<this.temporaryIds.edges.length;i++){var _context24;this.body.edges[this.temporaryIds.edges[i]].disconnect();delete this.body.edges[this.temporaryIds.edges[i]];const indexTempEdge=_indexOfInstanceProperty(_context24=this.body.edgeIndices).call(_context24,this.temporaryIds.edges[i]);if(indexTempEdge!==-1){var _context25;_spliceInstanceProperty(_context25=this.body.edgeIndices).call(_context25,indexTempEdge,1);}}// _clean temporary nodes
for(let i=0;i<this.temporaryIds.nodes.length;i++){var _context26;delete this.body.nodes[this.temporaryIds.nodes[i]];const indexTempNode=_indexOfInstanceProperty(_context26=this.body.nodeIndices).call(_context26,this.temporaryIds.nodes[i]);if(indexTempNode!==-1){var _context27;_spliceInstanceProperty(_context27=this.body.nodeIndices).call(_context27,indexTempNode,1);}}this.temporaryIds={nodes:[],edges:[]};}// ------------------------------------------ EDIT EDGE FUNCTIONS -----------------------------------------//
/**
   * the touch is used to get the position of the initial click
   * @param {Event}  event   The event
   * @private
   */_controlNodeTouch(event){this.selectionHandler.unselectAll();this.lastTouch=this.body.functions.getPointer(event.center);this.lastTouch.translation=_Object$assign({},this.body.view.translation);// copy the object
}/**
   * the drag start is used to mark one of the control nodes as selected.
   * @private
   */_controlNodeDragStart(){const pointer=this.lastTouch;const pointerObj=this.selectionHandler._pointerToPositionObject(pointer);const from=this.body.nodes[this.temporaryIds.nodes[0]];const to=this.body.nodes[this.temporaryIds.nodes[1]];const edge=this.body.edges[this.edgeBeingEditedId];this.selectedControlNode=undefined;const fromSelect=from.isOverlappingWith(pointerObj);const toSelect=to.isOverlappingWith(pointerObj);if(fromSelect===true){this.selectedControlNode=from;edge.edgeType.from=from;}else if(toSelect===true){this.selectedControlNode=to;edge.edgeType.to=to;}// we use the selection to find the node that is being dragged. We explicitly select it here.
if(this.selectedControlNode!==undefined){this.selectionHandler.selectObject(this.selectedControlNode);}this.body.emitter.emit("_redraw");}/**
   * dragging the control nodes or the canvas
   * @param {Event}  event   The event
   * @private
   */_controlNodeDrag(event){this.body.emitter.emit("disablePhysics");const pointer=this.body.functions.getPointer(event.center);const pos=this.canvas.DOMtoCanvas(pointer);if(this.selectedControlNode!==undefined){this.selectedControlNode.x=pos.x;this.selectedControlNode.y=pos.y;}else {this.interactionHandler.onDrag(event);}this.body.emitter.emit("_redraw");}/**
   * connecting or restoring the control nodes.
   * @param {Event}  event   The event
   * @private
   */_controlNodeDragEnd(event){const pointer=this.body.functions.getPointer(event.center);const pointerObj=this.selectionHandler._pointerToPositionObject(pointer);const edge=this.body.edges[this.edgeBeingEditedId];// if the node that was dragged is not a control node, return
if(this.selectedControlNode===undefined){return;}// we use the selection to find the node that is being dragged. We explicitly DEselect the control node here.
this.selectionHandler.unselectAll();const overlappingNodeIds=this.selectionHandler._getAllNodesOverlappingWith(pointerObj);let node=undefined;for(let i=overlappingNodeIds.length-1;i>=0;i--){if(overlappingNodeIds[i]!==this.selectedControlNode.id){node=this.body.nodes[overlappingNodeIds[i]];break;}}// perform the connection
if(node!==undefined&&this.selectedControlNode!==undefined){if(node.isCluster===true){alert(this.options.locales[this.options.locale]["createEdgeError"]||this.options.locales["en"]["createEdgeError"]);}else {const from=this.body.nodes[this.temporaryIds.nodes[0]];if(this.selectedControlNode.id===from.id){this._performEditEdge(node.id,edge.to.id);}else {this._performEditEdge(edge.from.id,node.id);}}}else {edge.updateEdgeType();this.body.emitter.emit("restorePhysics");}this.body.emitter.emit("_redraw");}// ------------------------------------ END OF EDIT EDGE FUNCTIONS -----------------------------------------//
// ------------------------------------------- ADD EDGE FUNCTIONS -----------------------------------------//
/**
   * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
   * to walk the user through the process.
   * @param {Event} event
   * @private
   */_handleConnect(event){// check to avoid double fireing of this function.
if(new Date().valueOf()-this.touchTime>100){this.lastTouch=this.body.functions.getPointer(event.center);this.lastTouch.translation=_Object$assign({},this.body.view.translation);// copy the object
this.interactionHandler.drag.pointer=this.lastTouch;// Drag pointer is not updated when adding edges
this.interactionHandler.drag.translation=this.lastTouch.translation;const pointer=this.lastTouch;const node=this.selectionHandler.getNodeAt(pointer);if(node!==undefined){if(node.isCluster===true){alert(this.options.locales[this.options.locale]["createEdgeError"]||this.options.locales["en"]["createEdgeError"]);}else {// create a node the temporary line can look at
const targetNode=this._getNewTargetNode(node.x,node.y);this.body.nodes[targetNode.id]=targetNode;this.body.nodeIndices.push(targetNode.id);// create a temporary edge
const connectionEdge=this.body.functions.createEdge({id:"connectionEdge"+v4(),from:node.id,to:targetNode.id,physics:false,smooth:{enabled:true,type:"continuous",roundness:0.5}});this.body.edges[connectionEdge.id]=connectionEdge;this.body.edgeIndices.push(connectionEdge.id);this.temporaryIds.nodes.push(targetNode.id);this.temporaryIds.edges.push(connectionEdge.id);}}this.touchTime=new Date().valueOf();}}/**
   *
   * @param {Event} event
   * @private
   */_dragControlNode(event){const pointer=this.body.functions.getPointer(event.center);const pointerObj=this.selectionHandler._pointerToPositionObject(pointer);// remember the edge id
let connectFromId=undefined;if(this.temporaryIds.edges[0]!==undefined){connectFromId=this.body.edges[this.temporaryIds.edges[0]].fromId;}// get the overlapping node but NOT the temporary node;
const overlappingNodeIds=this.selectionHandler._getAllNodesOverlappingWith(pointerObj);let node=undefined;for(let i=overlappingNodeIds.length-1;i>=0;i--){var _context28;// if the node id is NOT a temporary node, accept the node.
if(_indexOfInstanceProperty(_context28=this.temporaryIds.nodes).call(_context28,overlappingNodeIds[i])===-1){node=this.body.nodes[overlappingNodeIds[i]];break;}}event.controlEdge={from:connectFromId,to:node?node.id:undefined};this.selectionHandler.generateClickEvent("controlNodeDragging",event,pointer);if(this.temporaryIds.nodes[0]!==undefined){const targetNode=this.body.nodes[this.temporaryIds.nodes[0]];// there is only one temp node in the add edge mode.
targetNode.x=this.canvas._XconvertDOMtoCanvas(pointer.x);targetNode.y=this.canvas._YconvertDOMtoCanvas(pointer.y);this.body.emitter.emit("_redraw");}else {this.interactionHandler.onDrag(event);}}/**
   * Connect the new edge to the target if one exists, otherwise remove temp line
   * @param {Event}  event   The event
   * @private
   */_finishConnect(event){const pointer=this.body.functions.getPointer(event.center);const pointerObj=this.selectionHandler._pointerToPositionObject(pointer);// remember the edge id
let connectFromId=undefined;if(this.temporaryIds.edges[0]!==undefined){connectFromId=this.body.edges[this.temporaryIds.edges[0]].fromId;}// get the overlapping node but NOT the temporary node;
const overlappingNodeIds=this.selectionHandler._getAllNodesOverlappingWith(pointerObj);let node=undefined;for(let i=overlappingNodeIds.length-1;i>=0;i--){var _context29;// if the node id is NOT a temporary node, accept the node.
if(_indexOfInstanceProperty(_context29=this.temporaryIds.nodes).call(_context29,overlappingNodeIds[i])===-1){node=this.body.nodes[overlappingNodeIds[i]];break;}}// clean temporary nodes and edges.
this._cleanupTemporaryNodesAndEdges();// perform the connection
if(node!==undefined){if(node.isCluster===true){alert(this.options.locales[this.options.locale]["createEdgeError"]||this.options.locales["en"]["createEdgeError"]);}else {if(this.body.nodes[connectFromId]!==undefined&&this.body.nodes[node.id]!==undefined){this._performAddEdge(connectFromId,node.id);}}}event.controlEdge={from:connectFromId,to:node?node.id:undefined};this.selectionHandler.generateClickEvent("controlNodeDragEnd",event,pointer);// No need to do _generateclickevent('dragEnd') here, the regular dragEnd event fires.
this.body.emitter.emit("_redraw");}/**
   *
   * @param {Event} event
   * @private
   */_dragStartEdge(event){const pointer=this.lastTouch;this.selectionHandler.generateClickEvent("dragStart",event,pointer,undefined,true);}// --------------------------------------- END OF ADD EDGE FUNCTIONS -------------------------------------//
// ------------------------------ Performing all the actual data manipulation ------------------------//
/**
   * Adds a node on the specified location
   * @param {object} clickData
   * @private
   */_performAddNode(clickData){const defaultData={id:v4(),x:clickData.pointer.canvas.x,y:clickData.pointer.canvas.y,label:"new"};if(typeof this.options.addNode==="function"){if(this.options.addNode.length===2){this.options.addNode(defaultData,finalizedData=>{if(finalizedData!==null&&finalizedData!==undefined&&this.inMode==="addNode"){// if for whatever reason the mode has changes (due to dataset change) disregard the callback
this.body.data.nodes.getDataSet().add(finalizedData);}this.showManipulatorToolbar();});}else {this.showManipulatorToolbar();throw new Error("The function for add does not support two arguments (data,callback)");}}else {this.body.data.nodes.getDataSet().add(defaultData);this.showManipulatorToolbar();}}/**
   * connect two nodes with a new edge.
   * @param {Node.id} sourceNodeId
   * @param {Node.id} targetNodeId
   * @private
   */_performAddEdge(sourceNodeId,targetNodeId){const defaultData={from:sourceNodeId,to:targetNodeId};if(typeof this.options.addEdge==="function"){if(this.options.addEdge.length===2){this.options.addEdge(defaultData,finalizedData=>{if(finalizedData!==null&&finalizedData!==undefined&&this.inMode==="addEdge"){// if for whatever reason the mode has changes (due to dataset change) disregard the callback
this.body.data.edges.getDataSet().add(finalizedData);this.selectionHandler.unselectAll();this.showManipulatorToolbar();}});}else {throw new Error("The function for connect does not support two arguments (data,callback)");}}else {this.body.data.edges.getDataSet().add(defaultData);this.selectionHandler.unselectAll();this.showManipulatorToolbar();}}/**
   * connect two nodes with a new edge.
   * @param {Node.id} sourceNodeId
   * @param {Node.id} targetNodeId
   * @private
   */_performEditEdge(sourceNodeId,targetNodeId){const defaultData={id:this.edgeBeingEditedId,from:sourceNodeId,to:targetNodeId,label:this.body.data.edges.get(this.edgeBeingEditedId).label};let eeFunct=this.options.editEdge;if(typeof eeFunct==="object"){eeFunct=eeFunct.editWithoutDrag;}if(typeof eeFunct==="function"){if(eeFunct.length===2){eeFunct(defaultData,finalizedData=>{if(finalizedData===null||finalizedData===undefined||this.inMode!=="editEdge"){// if for whatever reason the mode has changes (due to dataset change) disregard the callback) {
this.body.edges[defaultData.id].updateEdgeType();this.body.emitter.emit("_redraw");this.showManipulatorToolbar();}else {this.body.data.edges.getDataSet().update(finalizedData);this.selectionHandler.unselectAll();this.showManipulatorToolbar();}});}else {throw new Error("The function for edit does not support two arguments (data, callback)");}}else {this.body.data.edges.getDataSet().update(defaultData);this.selectionHandler.unselectAll();this.showManipulatorToolbar();}}}/**
 * This object contains all possible options. It will check if the types are correct, if required if the option is one
 * of the allowed values.
 *
 * __any__ means that the name of the property does not matter.
 * __type__ is a required field for all objects and contains the allowed types of all objects
 */const string="string";const bool="boolean";const number="number";const array="array";const object="object";// should only be in a __type__ property
const dom="dom";const any="any";// List of endpoints
const endPoints=["arrow","bar","box","circle","crow","curve","diamond","image","inv_curve","inv_triangle","triangle","vee"];/* eslint-disable @typescript-eslint/naming-convention -- The __*__ format is used to prevent collisions with actual option names. */const nodeOptions={borderWidth:{number},borderWidthSelected:{number,undefined:"undefined"},brokenImage:{string,undefined:"undefined"},chosen:{label:{boolean:bool,function:"function"},node:{boolean:bool,function:"function"},__type__:{object,boolean:bool}},color:{border:{string},background:{string},highlight:{border:{string},background:{string},__type__:{object,string}},hover:{border:{string},background:{string},__type__:{object,string}},__type__:{object,string}},opacity:{number,undefined:"undefined"},fixed:{x:{boolean:bool},y:{boolean:bool},__type__:{object,boolean:bool}},font:{align:{string},color:{string},size:{number},// px
face:{string},background:{string},strokeWidth:{number},// px
strokeColor:{string},vadjust:{number},multi:{boolean:bool,string},bold:{color:{string},size:{number},// px
face:{string},mod:{string},vadjust:{number},__type__:{object,string}},boldital:{color:{string},size:{number},// px
face:{string},mod:{string},vadjust:{number},__type__:{object,string}},ital:{color:{string},size:{number},// px
face:{string},mod:{string},vadjust:{number},__type__:{object,string}},mono:{color:{string},size:{number},// px
face:{string},mod:{string},vadjust:{number},__type__:{object,string}},__type__:{object,string}},group:{string,number,undefined:"undefined"},heightConstraint:{minimum:{number},valign:{string},__type__:{object,boolean:bool,number}},hidden:{boolean:bool},icon:{face:{string},code:{string},//'\uf007',
size:{number},//50,
color:{string},weight:{string,number},__type__:{object}},id:{string,number},image:{selected:{string,undefined:"undefined"},// --> URL
unselected:{string,undefined:"undefined"},// --> URL
__type__:{object,string}},imagePadding:{top:{number},right:{number},bottom:{number},left:{number},__type__:{object,number}},label:{string,undefined:"undefined"},labelHighlightBold:{boolean:bool},level:{number,undefined:"undefined"},margin:{top:{number},right:{number},bottom:{number},left:{number},__type__:{object,number}},mass:{number},physics:{boolean:bool},scaling:{min:{number},max:{number},label:{enabled:{boolean:bool},min:{number},max:{number},maxVisible:{number},drawThreshold:{number},__type__:{object,boolean:bool}},customScalingFunction:{function:"function"},__type__:{object}},shadow:{enabled:{boolean:bool},color:{string},size:{number},x:{number},y:{number},__type__:{object,boolean:bool}},shape:{string:["custom","ellipse","circle","database","box","text","image","circularImage","diamond","dot","star","triangle","triangleDown","square","icon","hexagon"]},ctxRenderer:{function:"function"},shapeProperties:{borderDashes:{boolean:bool,array},borderRadius:{number},interpolation:{boolean:bool},useImageSize:{boolean:bool},useBorderWithImage:{boolean:bool},coordinateOrigin:{string:["center","top-left"]},__type__:{object}},size:{number},title:{string,dom,undefined:"undefined"},value:{number,undefined:"undefined"},widthConstraint:{minimum:{number},maximum:{number},__type__:{object,boolean:bool,number}},x:{number},y:{number},__type__:{object}};const allOptions={configure:{enabled:{boolean:bool},filter:{boolean:bool,string,array,function:"function"},container:{dom},showButton:{boolean:bool},__type__:{object,boolean:bool,string,array,function:"function"}},edges:{arrows:{to:{enabled:{boolean:bool},scaleFactor:{number},type:{string:endPoints},imageHeight:{number},imageWidth:{number},src:{string},__type__:{object,boolean:bool}},middle:{enabled:{boolean:bool},scaleFactor:{number},type:{string:endPoints},imageWidth:{number},imageHeight:{number},src:{string},__type__:{object,boolean:bool}},from:{enabled:{boolean:bool},scaleFactor:{number},type:{string:endPoints},imageWidth:{number},imageHeight:{number},src:{string},__type__:{object,boolean:bool}},__type__:{string:["from","to","middle"],object}},endPointOffset:{from:{number:number},to:{number:number},__type__:{object:object,number:number}},arrowStrikethrough:{boolean:bool},background:{enabled:{boolean:bool},color:{string},size:{number},dashes:{boolean:bool,array},__type__:{object,boolean:bool}},chosen:{label:{boolean:bool,function:"function"},edge:{boolean:bool,function:"function"},__type__:{object,boolean:bool}},color:{color:{string},highlight:{string},hover:{string},inherit:{string:["from","to","both"],boolean:bool},opacity:{number},__type__:{object,string}},dashes:{boolean:bool,array},font:{color:{string},size:{number},// px
face:{string},background:{string},strokeWidth:{number},// px
strokeColor:{string},align:{string:["horizontal","top","middle","bottom"]},vadjust:{number},multi:{boolean:bool,string},bold:{color:{string},size:{number},// px
face:{string},mod:{string},vadjust:{number},__type__:{object,string}},boldital:{color:{string},size:{number},// px
face:{string},mod:{string},vadjust:{number},__type__:{object,string}},ital:{color:{string},size:{number},// px
face:{string},mod:{string},vadjust:{number},__type__:{object,string}},mono:{color:{string},size:{number},// px
face:{string},mod:{string},vadjust:{number},__type__:{object,string}},__type__:{object,string}},hidden:{boolean:bool},hoverWidth:{function:"function",number},label:{string,undefined:"undefined"},labelHighlightBold:{boolean:bool},length:{number,undefined:"undefined"},physics:{boolean:bool},scaling:{min:{number},max:{number},label:{enabled:{boolean:bool},min:{number},max:{number},maxVisible:{number},drawThreshold:{number},__type__:{object,boolean:bool}},customScalingFunction:{function:"function"},__type__:{object}},selectionWidth:{function:"function",number},selfReferenceSize:{number},selfReference:{size:{number},angle:{number},renderBehindTheNode:{boolean:bool},__type__:{object}},shadow:{enabled:{boolean:bool},color:{string},size:{number},x:{number},y:{number},__type__:{object,boolean:bool}},smooth:{enabled:{boolean:bool},type:{string:["dynamic","continuous","discrete","diagonalCross","straightCross","horizontal","vertical","curvedCW","curvedCCW","cubicBezier"]},roundness:{number},forceDirection:{string:["horizontal","vertical","none"],boolean:bool},__type__:{object,boolean:bool}},title:{string,undefined:"undefined"},width:{number},widthConstraint:{maximum:{number},__type__:{object,boolean:bool,number}},value:{number,undefined:"undefined"},__type__:{object}},groups:{useDefaultGroups:{boolean:bool},__any__:nodeOptions,__type__:{object}},interaction:{dragNodes:{boolean:bool},dragView:{boolean:bool},hideEdgesOnDrag:{boolean:bool},hideEdgesOnZoom:{boolean:bool},hideNodesOnDrag:{boolean:bool},hover:{boolean:bool},keyboard:{enabled:{boolean:bool},speed:{x:{number},y:{number},zoom:{number},__type__:{object}},bindToWindow:{boolean:bool},autoFocus:{boolean:bool},__type__:{object,boolean:bool}},multiselect:{boolean:bool},navigationButtons:{boolean:bool},selectable:{boolean:bool},selectConnectedEdges:{boolean:bool},hoverConnectedEdges:{boolean:bool},tooltipDelay:{number},zoomView:{boolean:bool},zoomSpeed:{number},__type__:{object}},layout:{randomSeed:{undefined:"undefined",number,string},improvedLayout:{boolean:bool},clusterThreshold:{number},hierarchical:{enabled:{boolean:bool},levelSeparation:{number},nodeSpacing:{number},treeSpacing:{number},blockShifting:{boolean:bool},edgeMinimization:{boolean:bool},parentCentralization:{boolean:bool},direction:{string:["UD","DU","LR","RL"]},// UD, DU, LR, RL
sortMethod:{string:["hubsize","directed"]},// hubsize, directed
shakeTowards:{string:["leaves","roots"]},// leaves, roots
__type__:{object,boolean:bool}},__type__:{object}},manipulation:{enabled:{boolean:bool},initiallyActive:{boolean:bool},addNode:{boolean:bool,function:"function"},addEdge:{boolean:bool,function:"function"},editNode:{function:"function"},editEdge:{editWithoutDrag:{function:"function"},__type__:{object,boolean:bool,function:"function"}},deleteNode:{boolean:bool,function:"function"},deleteEdge:{boolean:bool,function:"function"},controlNodeStyle:nodeOptions,__type__:{object,boolean:bool}},nodes:nodeOptions,physics:{enabled:{boolean:bool},barnesHut:{theta:{number},gravitationalConstant:{number},centralGravity:{number},springLength:{number},springConstant:{number},damping:{number},avoidOverlap:{number},__type__:{object}},forceAtlas2Based:{theta:{number},gravitationalConstant:{number},centralGravity:{number},springLength:{number},springConstant:{number},damping:{number},avoidOverlap:{number},__type__:{object}},repulsion:{centralGravity:{number},springLength:{number},springConstant:{number},nodeDistance:{number},damping:{number},__type__:{object}},hierarchicalRepulsion:{centralGravity:{number},springLength:{number},springConstant:{number},nodeDistance:{number},damping:{number},avoidOverlap:{number},__type__:{object}},maxVelocity:{number},minVelocity:{number},// px/s
solver:{string:["barnesHut","repulsion","hierarchicalRepulsion","forceAtlas2Based"]},stabilization:{enabled:{boolean:bool},iterations:{number},// maximum number of iteration to stabilize
updateInterval:{number},onlyDynamicEdges:{boolean:bool},fit:{boolean:bool},__type__:{object,boolean:bool}},timestep:{number},adaptiveTimestep:{boolean:bool},wind:{x:{number},y:{number},__type__:{object,function:"function"}},__type__:{object,boolean:bool}},//globals :
autoResize:{boolean:bool},clickToUse:{boolean:bool},locale:{string},locales:{__any__:{any},__type__:{object}},height:{string},width:{string},__type__:{object}};/* eslint-enable @typescript-eslint/naming-convention *//**
 * This provides ranges, initial values, steps and dropdown menu choices for the
 * configuration.
 * @remarks
 * Checkbox: `boolean`
 *   The value supllied will be used as the initial value.
 *
 * Text field: `string`
 *   The passed text will be used as the initial value. Any text will be
 *   accepted afterwards.
 *
 * Number range: `[number, number, number, number]`
 *   The meanings are `[initial value, min, max, step]`.
 *
 * Dropdown: `[Exclude<string, "color">, ...(string | number | boolean)[]]`
 *   Translations for people with poor understanding of TypeScript: the first
 *   value always has to be a string but never `"color"`, the rest can be any
 *   combination of strings, numbers and booleans.
 *
 * Color picker: `["color", string]`
 *   The first value says this will be a color picker not a dropdown menu. The
 *   next value is the initial color.
 */const configureOptions={nodes:{borderWidth:[1,0,10,1],borderWidthSelected:[2,0,10,1],color:{border:["color","#2B7CE9"],background:["color","#97C2FC"],highlight:{border:["color","#2B7CE9"],background:["color","#D2E5FF"]},hover:{border:["color","#2B7CE9"],background:["color","#D2E5FF"]}},opacity:[0,0,1,0.1],fixed:{x:false,y:false},font:{color:["color","#343434"],size:[14,0,100,1],// px
face:["arial","verdana","tahoma"],background:["color","none"],strokeWidth:[0,0,50,1],// px
strokeColor:["color","#ffffff"]},//group: 'string',
hidden:false,labelHighlightBold:true,//icon: {
//  face: 'string',  //'FontAwesome',
//  code: 'string',  //'\uf007',
//  size: [50, 0, 200, 1],  //50,
//  color: ['color','#2B7CE9']   //'#aa00ff'
//},
//image: 'string', // --> URL
physics:true,scaling:{min:[10,0,200,1],max:[30,0,200,1],label:{enabled:false,min:[14,0,200,1],max:[30,0,200,1],maxVisible:[30,0,200,1],drawThreshold:[5,0,20,1]}},shadow:{enabled:false,color:"rgba(0,0,0,0.5)",size:[10,0,20,1],x:[5,-30,30,1],y:[5,-30,30,1]},shape:["ellipse","box","circle","database","diamond","dot","square","star","text","triangle","triangleDown","hexagon"],shapeProperties:{borderDashes:false,borderRadius:[6,0,20,1],interpolation:true,useImageSize:false},size:[25,0,200,1]},edges:{arrows:{to:{enabled:false,scaleFactor:[1,0,3,0.05],type:"arrow"},middle:{enabled:false,scaleFactor:[1,0,3,0.05],type:"arrow"},from:{enabled:false,scaleFactor:[1,0,3,0.05],type:"arrow"}},endPointOffset:{from:[0,-10,10,1],to:[0,-10,10,1]},arrowStrikethrough:true,color:{color:["color","#848484"],highlight:["color","#848484"],hover:["color","#848484"],inherit:["from","to","both",true,false],opacity:[1,0,1,0.05]},dashes:false,font:{color:["color","#343434"],size:[14,0,100,1],// px
face:["arial","verdana","tahoma"],background:["color","none"],strokeWidth:[2,0,50,1],// px
strokeColor:["color","#ffffff"],align:["horizontal","top","middle","bottom"]},hidden:false,hoverWidth:[1.5,0,5,0.1],labelHighlightBold:true,physics:true,scaling:{min:[1,0,100,1],max:[15,0,100,1],label:{enabled:true,min:[14,0,200,1],max:[30,0,200,1],maxVisible:[30,0,200,1],drawThreshold:[5,0,20,1]}},selectionWidth:[1.5,0,5,0.1],selfReferenceSize:[20,0,200,1],selfReference:{size:[20,0,200,1],angle:[Math.PI/2,-6*Math.PI,6*Math.PI,Math.PI/8],renderBehindTheNode:true},shadow:{enabled:false,color:"rgba(0,0,0,0.5)",size:[10,0,20,1],x:[5,-30,30,1],y:[5,-30,30,1]},smooth:{enabled:true,type:["dynamic","continuous","discrete","diagonalCross","straightCross","horizontal","vertical","curvedCW","curvedCCW","cubicBezier"],forceDirection:["horizontal","vertical","none"],roundness:[0.5,0,1,0.05]},width:[1,0,30,1]},layout:{//randomSeed: [0, 0, 500, 1],
//improvedLayout: true,
hierarchical:{enabled:false,levelSeparation:[150,20,500,5],nodeSpacing:[100,20,500,5],treeSpacing:[200,20,500,5],blockShifting:true,edgeMinimization:true,parentCentralization:true,direction:["UD","DU","LR","RL"],// UD, DU, LR, RL
sortMethod:["hubsize","directed"],// hubsize, directed
shakeTowards:["leaves","roots"]// leaves, roots
}},interaction:{dragNodes:true,dragView:true,hideEdgesOnDrag:false,hideEdgesOnZoom:false,hideNodesOnDrag:false,hover:false,keyboard:{enabled:false,speed:{x:[10,0,40,1],y:[10,0,40,1],zoom:[0.02,0,0.1,0.005]},bindToWindow:true,autoFocus:true},multiselect:false,navigationButtons:false,selectable:true,selectConnectedEdges:true,hoverConnectedEdges:true,tooltipDelay:[300,0,1000,25],zoomView:true,zoomSpeed:[1,0.1,2,0.1]},manipulation:{enabled:false,initiallyActive:false},physics:{enabled:true,barnesHut:{theta:[0.5,0.1,1,0.05],gravitationalConstant:[-2e3,-3e4,0,50],centralGravity:[0.3,0,10,0.05],springLength:[95,0,500,5],springConstant:[0.04,0,1.2,0.005],damping:[0.09,0,1,0.01],avoidOverlap:[0,0,1,0.01]},forceAtlas2Based:{theta:[0.5,0.1,1,0.05],gravitationalConstant:[-50,-500,0,1],centralGravity:[0.01,0,1,0.005],springLength:[95,0,500,5],springConstant:[0.08,0,1.2,0.005],damping:[0.4,0,1,0.01],avoidOverlap:[0,0,1,0.01]},repulsion:{centralGravity:[0.2,0,10,0.05],springLength:[200,0,500,5],springConstant:[0.05,0,1.2,0.005],nodeDistance:[100,0,500,5],damping:[0.09,0,1,0.01]},hierarchicalRepulsion:{centralGravity:[0.2,0,10,0.05],springLength:[100,0,500,5],springConstant:[0.01,0,1.2,0.005],nodeDistance:[120,0,500,5],damping:[0.09,0,1,0.01],avoidOverlap:[0,0,1,0.01]},maxVelocity:[50,0,150,1],minVelocity:[0.1,0.01,0.5,0.01],solver:["barnesHut","forceAtlas2Based","repulsion","hierarchicalRepulsion"],timestep:[0.5,0.01,1,0.01],wind:{x:[0,-10,10,0.1],y:[0,-10,10,0.1]}//adaptiveTimestep: true
}};const configuratorHideOption=(parentPath,optionName,options)=>{var _context,_options$physics;if(_includesInstanceProperty(parentPath).call(parentPath,"physics")&&_includesInstanceProperty(_context=configureOptions.physics.solver).call(_context,optionName)&&options.physics.solver!==optionName&&optionName!=="wind"){return true;}if(_includesInstanceProperty(parentPath).call(parentPath,"physics")&&_includesInstanceProperty(parentPath).call(parentPath,"wind")&&(optionName==="x"||optionName==="y")&&typeof(options===null||options===void 0||(_options$physics=options.physics)===null||_options$physics===void 0?void 0:_options$physics.wind)==="function"){return true;}return false;};/**
 *  The Floyd–Warshall algorithm is an algorithm for finding shortest paths in
 *  a weighted graph with positive or negative edge weights (but with no negative
 *  cycles). - https://en.wikipedia.org/wiki/Floyd–Warshall_algorithm
 */class FloydWarshall{/**
   *
   * @param {object} body
   * @param {Array.<Node>} nodesArray
   * @param {Array.<Edge>} edgesArray
   * @returns {{}}
   */getDistances(body,nodesArray,edgesArray){const D_matrix={};const edges=body.edges;// prepare matrix with large numbers
for(let i=0;i<nodesArray.length;i++){const node=nodesArray[i];const cell={};D_matrix[node]=cell;for(let j=0;j<nodesArray.length;j++){cell[nodesArray[j]]=i==j?0:1e9;}}// put the weights for the edges in. This assumes unidirectionality.
for(let i=0;i<edgesArray.length;i++){const edge=edges[edgesArray[i]];// edge has to be connected if it counts to the distances. If it is connected to inner clusters it will crash so we also check if it is in the D_matrix
if(edge.connected===true&&D_matrix[edge.fromId]!==undefined&&D_matrix[edge.toId]!==undefined){D_matrix[edge.fromId][edge.toId]=1;D_matrix[edge.toId][edge.fromId]=1;}}const nodeCount=nodesArray.length;// Adapted FloydWarshall based on unidirectionality to greatly reduce complexity.
for(let k=0;k<nodeCount;k++){const knode=nodesArray[k];const kcolm=D_matrix[knode];for(let i=0;i<nodeCount-1;i++){const inode=nodesArray[i];const icolm=D_matrix[inode];for(let j=i+1;j<nodeCount;j++){const jnode=nodesArray[j];const jcolm=D_matrix[jnode];const val=Math.min(icolm[jnode],icolm[knode]+kcolm[jnode]);icolm[jnode]=val;jcolm[inode]=val;}}}return D_matrix;}}// distance finding algorithm
/**
 * KamadaKawai positions the nodes initially based on
 *
 * "AN ALGORITHM FOR DRAWING GENERAL UNDIRECTED GRAPHS"
 * -- Tomihisa KAMADA and Satoru KAWAI in 1989
 *
 * Possible optimizations in the distance calculation can be implemented.
 */class KamadaKawai{/**
   * @param {object} body
   * @param {number} edgeLength
   * @param {number} edgeStrength
   */constructor(body,edgeLength,edgeStrength){this.body=body;this.springLength=edgeLength;this.springConstant=edgeStrength;this.distanceSolver=new FloydWarshall();}/**
   * Not sure if needed but can be used to update the spring length and spring constant
   * @param {object} options
   */setOptions(options){if(options){if(options.springLength){this.springLength=options.springLength;}if(options.springConstant){this.springConstant=options.springConstant;}}}/**
   * Position the system
   * @param {Array.<Node>} nodesArray
   * @param {Array.<vis.Edge>} edgesArray
   * @param {boolean} [ignoreClusters]
   */solve(nodesArray,edgesArray){let ignoreClusters=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;// get distance matrix
const D_matrix=this.distanceSolver.getDistances(this.body,nodesArray,edgesArray);// distance matrix
// get the L Matrix
this._createL_matrix(D_matrix);// get the K Matrix
this._createK_matrix(D_matrix);// initial E Matrix
this._createE_matrix();// calculate positions
const threshold=0.01;const innerThreshold=1;let iterations=0;const maxIterations=Math.max(1000,Math.min(10*this.body.nodeIndices.length,6000));const maxInnerIterations=5;let maxEnergy=1e9;let highE_nodeId=0,dE_dx=0,dE_dy=0,delta_m=0,subIterations=0;while(maxEnergy>threshold&&iterations<maxIterations){iterations+=1;[highE_nodeId,maxEnergy,dE_dx,dE_dy]=this._getHighestEnergyNode(ignoreClusters);delta_m=maxEnergy;subIterations=0;while(delta_m>innerThreshold&&subIterations<maxInnerIterations){subIterations+=1;this._moveNode(highE_nodeId,dE_dx,dE_dy);[delta_m,dE_dx,dE_dy]=this._getEnergy(highE_nodeId);}}}/**
   * get the node with the highest energy
   * @param {boolean} ignoreClusters
   * @returns {number[]}
   * @private
   */_getHighestEnergyNode(ignoreClusters){const nodesArray=this.body.nodeIndices;const nodes=this.body.nodes;let maxEnergy=0;let maxEnergyNodeId=nodesArray[0];let dE_dx_max=0,dE_dy_max=0;for(let nodeIdx=0;nodeIdx<nodesArray.length;nodeIdx++){const m=nodesArray[nodeIdx];// by not evaluating nodes with predefined positions we should only move nodes that have no positions.
if(nodes[m].predefinedPosition!==true||nodes[m].isCluster===true&&ignoreClusters===true||nodes[m].options.fixed.x!==true||nodes[m].options.fixed.y!==true){const[delta_m,dE_dx,dE_dy]=this._getEnergy(m);if(maxEnergy<delta_m){maxEnergy=delta_m;maxEnergyNodeId=m;dE_dx_max=dE_dx;dE_dy_max=dE_dy;}}}return [maxEnergyNodeId,maxEnergy,dE_dx_max,dE_dy_max];}/**
   * calculate the energy of a single node
   * @param {Node.id} m
   * @returns {number[]}
   * @private
   */_getEnergy(m){const[dE_dx,dE_dy]=this.E_sums[m];const delta_m=Math.sqrt(dE_dx**2+dE_dy**2);return [delta_m,dE_dx,dE_dy];}/**
   * move the node based on it's energy
   * the dx and dy are calculated from the linear system proposed by Kamada and Kawai
   * @param {number} m
   * @param {number} dE_dx
   * @param {number} dE_dy
   * @private
   */_moveNode(m,dE_dx,dE_dy){const nodesArray=this.body.nodeIndices;const nodes=this.body.nodes;let d2E_dx2=0;let d2E_dxdy=0;let d2E_dy2=0;const x_m=nodes[m].x;const y_m=nodes[m].y;const km=this.K_matrix[m];const lm=this.L_matrix[m];for(let iIdx=0;iIdx<nodesArray.length;iIdx++){const i=nodesArray[iIdx];if(i!==m){const x_i=nodes[i].x;const y_i=nodes[i].y;const kmat=km[i];const lmat=lm[i];const denominator=1.0/((x_m-x_i)**2+(y_m-y_i)**2)**1.5;d2E_dx2+=kmat*(1-lmat*(y_m-y_i)**2*denominator);d2E_dxdy+=kmat*(lmat*(x_m-x_i)*(y_m-y_i)*denominator);d2E_dy2+=kmat*(1-lmat*(x_m-x_i)**2*denominator);}}// make the variable names easier to make the solving of the linear system easier to read
const A=d2E_dx2,B=d2E_dxdy,C=dE_dx,D=d2E_dy2,E=dE_dy;// solve the linear system for dx and dy
const dy=(C/A+E/B)/(B/A-D/B);const dx=-(B*dy+C)/A;// move the node
nodes[m].x+=dx;nodes[m].y+=dy;// Recalculate E_matrix (should be incremental)
this._updateE_matrix(m);}/**
   * Create the L matrix: edge length times shortest path
   * @param {object} D_matrix
   * @private
   */_createL_matrix(D_matrix){const nodesArray=this.body.nodeIndices;const edgeLength=this.springLength;this.L_matrix=[];for(let i=0;i<nodesArray.length;i++){this.L_matrix[nodesArray[i]]={};for(let j=0;j<nodesArray.length;j++){this.L_matrix[nodesArray[i]][nodesArray[j]]=edgeLength*D_matrix[nodesArray[i]][nodesArray[j]];}}}/**
   * Create the K matrix: spring constants times shortest path
   * @param {object} D_matrix
   * @private
   */_createK_matrix(D_matrix){const nodesArray=this.body.nodeIndices;const edgeStrength=this.springConstant;this.K_matrix=[];for(let i=0;i<nodesArray.length;i++){this.K_matrix[nodesArray[i]]={};for(let j=0;j<nodesArray.length;j++){this.K_matrix[nodesArray[i]][nodesArray[j]]=edgeStrength*D_matrix[nodesArray[i]][nodesArray[j]]**-2;}}}/**
   *  Create matrix with all energies between nodes
   *  @private
   */_createE_matrix(){const nodesArray=this.body.nodeIndices;const nodes=this.body.nodes;this.E_matrix={};this.E_sums={};for(let mIdx=0;mIdx<nodesArray.length;mIdx++){this.E_matrix[nodesArray[mIdx]]=[];}for(let mIdx=0;mIdx<nodesArray.length;mIdx++){const m=nodesArray[mIdx];const x_m=nodes[m].x;const y_m=nodes[m].y;let dE_dx=0;let dE_dy=0;for(let iIdx=mIdx;iIdx<nodesArray.length;iIdx++){const i=nodesArray[iIdx];if(i!==m){const x_i=nodes[i].x;const y_i=nodes[i].y;const denominator=1.0/Math.sqrt((x_m-x_i)**2+(y_m-y_i)**2);this.E_matrix[m][iIdx]=[this.K_matrix[m][i]*(x_m-x_i-this.L_matrix[m][i]*(x_m-x_i)*denominator),this.K_matrix[m][i]*(y_m-y_i-this.L_matrix[m][i]*(y_m-y_i)*denominator)];this.E_matrix[i][mIdx]=this.E_matrix[m][iIdx];dE_dx+=this.E_matrix[m][iIdx][0];dE_dy+=this.E_matrix[m][iIdx][1];}}//Store sum
this.E_sums[m]=[dE_dx,dE_dy];}}/**
   * Update method, just doing single column (rows are auto-updated) (update all sums)
   * @param {number} m
   * @private
   */_updateE_matrix(m){const nodesArray=this.body.nodeIndices;const nodes=this.body.nodes;const colm=this.E_matrix[m];const kcolm=this.K_matrix[m];const lcolm=this.L_matrix[m];const x_m=nodes[m].x;const y_m=nodes[m].y;let dE_dx=0;let dE_dy=0;for(let iIdx=0;iIdx<nodesArray.length;iIdx++){const i=nodesArray[iIdx];if(i!==m){//Keep old energy value for sum modification below
const cell=colm[iIdx];const oldDx=cell[0];const oldDy=cell[1];//Calc new energy:
const x_i=nodes[i].x;const y_i=nodes[i].y;const denominator=1.0/Math.sqrt((x_m-x_i)**2+(y_m-y_i)**2);const dx=kcolm[i]*(x_m-x_i-lcolm[i]*(x_m-x_i)*denominator);const dy=kcolm[i]*(y_m-y_i-lcolm[i]*(y_m-y_i)*denominator);colm[iIdx]=[dx,dy];dE_dx+=dx;dE_dy+=dy;//add new energy to sum of each column
const sum=this.E_sums[i];sum[0]+=dx-oldDx;sum[1]+=dy-oldDy;}}//Store sum at -1 index
this.E_sums[m]=[dE_dx,dE_dy];}}/**
 * Create a network visualization, displaying nodes and edges.
 * @param {Element} container   The DOM element in which the Network will
 *                                  be created. Normally a div element.
 * @param {object} data         An object containing parameters
 *                              {Array} nodes
 *                              {Array} edges
 * @param {object} options      Options
 * @class Network
 */function Network(container,data,options){var _context,_context2,_context3,_context4;if(!(this instanceof Network)){throw new SyntaxError("Constructor must be called with the new operator");}// set constant values
this.options={};this.defaultOptions={locale:"en",locales:locales,clickToUse:false};_Object$assign(this.options,this.defaultOptions);/**
   * Containers for nodes and edges.
   *
   * 'edges' and 'nodes' contain the full definitions of all the network elements.
   * 'nodeIndices' and 'edgeIndices' contain the id's of the active elements.
   *
   * The distinction is important, because a defined node need not be active, i.e.
   * visible on the canvas. This happens in particular when clusters are defined, in
   * that case there will be nodes and edges not displayed.
   * The bottom line is that all code with actions related to visibility, *must* use
   * 'nodeIndices' and 'edgeIndices', not 'nodes' and 'edges' directly.
   */this.body={container:container,// See comment above for following fields
nodes:{},nodeIndices:[],edges:{},edgeIndices:[],emitter:{on:_bindInstanceProperty(_context=this.on).call(_context,this),off:_bindInstanceProperty(_context2=this.off).call(_context2,this),emit:_bindInstanceProperty(_context3=this.emit).call(_context3,this),once:_bindInstanceProperty(_context4=this.once).call(_context4,this)},eventListeners:{onTap:function(){},onTouch:function(){},onDoubleTap:function(){},onHold:function(){},onDragStart:function(){},onDrag:function(){},onDragEnd:function(){},onMouseWheel:function(){},onPinch:function(){},onMouseMove:function(){},onRelease:function(){},onContext:function(){}},data:{nodes:null,// A DataSet or DataView
edges:null// A DataSet or DataView
},functions:{createNode:function(){},createEdge:function(){},getPointer:function(){}},modules:{},view:{scale:1,translation:{x:0,y:0}},selectionBox:{show:false,position:{start:{x:0,y:0},end:{x:0,y:0}}}};// bind the event listeners
this.bindEventListeners();// setting up all modules
this.images=new Images(()=>this.body.emitter.emit("_requestRedraw"));// object with images
this.groups=new Groups();// object with groups
this.canvas=new Canvas(this.body);// DOM handler
this.selectionHandler=new SelectionHandler(this.body,this.canvas);// Selection handler
this.interactionHandler=new InteractionHandler(this.body,this.canvas,this.selectionHandler);// Interaction handler handles all the hammer bindings (that are bound by canvas), key
this.view=new View(this.body,this.canvas);// camera handler, does animations and zooms
this.renderer=new CanvasRenderer(this.body,this.canvas);// renderer, starts renderloop, has events that modules can hook into
this.physics=new PhysicsEngine(this.body);// physics engine, does all the simulations
this.layoutEngine=new LayoutEngine(this.body);// layout engine for inital layout and hierarchical layout
this.clustering=new ClusterEngine(this.body);// clustering api
this.manipulation=new ManipulationSystem(this.body,this.canvas,this.selectionHandler,this.interactionHandler);// data manipulation system
this.nodesHandler=new NodesHandler(this.body,this.images,this.groups,this.layoutEngine);// Handle adding, deleting and updating of nodes as well as global options
this.edgesHandler=new EdgesHandler(this.body,this.images,this.groups);// Handle adding, deleting and updating of edges as well as global options
this.body.modules["kamadaKawai"]=new KamadaKawai(this.body,150,0.05);// Layouting algorithm.
this.body.modules["clustering"]=this.clustering;// create the DOM elements
this.canvas._create();// apply options
this.setOptions(options);// load data (the disable start variable will be the same as the enabled clustering)
this.setData(data);}// Extend Network with an Emitter mixin
Emitter(Network.prototype);/**
 * Set options
 * @param {object} options
 */Network.prototype.setOptions=function(options){if(options===null){options=undefined;// This ensures that options handling doesn't crash in the handling
}if(options!==undefined){const errorFound=Validator.validate(options,allOptions);if(errorFound===true){console.error("%cErrors have been found in the supplied options object.",VALIDATOR_PRINT_STYLE);}// copy the global fields over
const fields=["locale","locales","clickToUse"];selectiveDeepExtend(fields,this.options,options);// normalize the locale or use English
if(options.locale!==undefined){options.locale=normalizeLanguageCode(options.locales||this.options.locales,options.locale);}// the hierarchical system can adapt the edges and the physics to it's own options because not all combinations work with the hierarichical system.
options=this.layoutEngine.setOptions(options.layout,options);this.canvas.setOptions(options);// options for canvas are in globals
// pass the options to the modules
this.groups.setOptions(options.groups);this.nodesHandler.setOptions(options.nodes);this.edgesHandler.setOptions(options.edges);this.physics.setOptions(options.physics);this.manipulation.setOptions(options.manipulation,options,this.options);// manipulation uses the locales in the globals
this.interactionHandler.setOptions(options.interaction);this.renderer.setOptions(options.interaction);// options for rendering are in interaction
this.selectionHandler.setOptions(options.interaction);// options for selection are in interaction
// reload the settings of the nodes to apply changes in groups that are not referenced by pointer.
if(options.groups!==undefined){this.body.emitter.emit("refreshNodes");}// these two do not have options at the moment, here for completeness
//this.view.setOptions(options.view);
//this.clustering.setOptions(options.clustering);
if("configure"in options){if(!this.configurator){this.configurator=new Configurator(this,this.body.container,configureOptions,this.canvas.pixelRatio,configuratorHideOption);}this.configurator.setOptions(options.configure);}// if the configuration system is enabled, copy all options and put them into the config system
if(this.configurator&&this.configurator.options.enabled===true){const networkOptions={nodes:{},edges:{},layout:{},interaction:{},manipulation:{},physics:{},global:{}};deepExtend(networkOptions.nodes,this.nodesHandler.options);deepExtend(networkOptions.edges,this.edgesHandler.options);deepExtend(networkOptions.layout,this.layoutEngine.options);// load the selectionHandler and render default options in to the interaction group
deepExtend(networkOptions.interaction,this.selectionHandler.options);deepExtend(networkOptions.interaction,this.renderer.options);deepExtend(networkOptions.interaction,this.interactionHandler.options);deepExtend(networkOptions.manipulation,this.manipulation.options);deepExtend(networkOptions.physics,this.physics.options);// load globals into the global object
deepExtend(networkOptions.global,this.canvas.options);deepExtend(networkOptions.global,this.options);this.configurator.setModuleOptions(networkOptions);}// handle network global options
if(options.clickToUse!==undefined){if(options.clickToUse===true){if(this.activator===undefined){this.activator=new Activator(this.canvas.frame);this.activator.on("change",()=>{this.body.emitter.emit("activate");});}}else {if(this.activator!==undefined){this.activator.destroy();delete this.activator;}this.body.emitter.emit("activate");}}else {this.body.emitter.emit("activate");}this.canvas.setSize();// start the physics simulation. Can be safely called multiple times.
this.body.emitter.emit("startSimulation");}};/**
 * Update the visible nodes and edges list with the most recent node state.
 *
 * Visible nodes are stored in this.body.nodeIndices.
 * Visible edges are stored in this.body.edgeIndices.
 * A node or edges is visible if it is not hidden or clustered.
 * @private
 */Network.prototype._updateVisibleIndices=function(){const nodes=this.body.nodes;const edges=this.body.edges;this.body.nodeIndices=[];this.body.edgeIndices=[];for(const nodeId in nodes){if(Object.prototype.hasOwnProperty.call(nodes,nodeId)){if(!this.clustering._isClusteredNode(nodeId)&&nodes[nodeId].options.hidden===false){this.body.nodeIndices.push(nodes[nodeId].id);}}}for(const edgeId in edges){if(Object.prototype.hasOwnProperty.call(edges,edgeId)){const edge=edges[edgeId];// It can happen that this is executed *after* a node edge has been removed,
// but *before* the edge itself has been removed. Taking this into account.
const fromNode=nodes[edge.fromId];const toNode=nodes[edge.toId];const edgeNodesPresent=fromNode!==undefined&&toNode!==undefined;const isVisible=!this.clustering._isClusteredEdge(edgeId)&&edge.options.hidden===false&&edgeNodesPresent&&fromNode.options.hidden===false&&// Also hidden if any of its connecting nodes are hidden
toNode.options.hidden===false;// idem
if(isVisible){this.body.edgeIndices.push(edge.id);}}}};/**
 * Bind all events
 */Network.prototype.bindEventListeners=function(){// This event will trigger a rebuilding of the cache everything.
// Used when nodes or edges have been added or removed.
this.body.emitter.on("_dataChanged",()=>{this.edgesHandler._updateState();this.body.emitter.emit("_dataUpdated");});// this is called when options of EXISTING nodes or edges have changed.
this.body.emitter.on("_dataUpdated",()=>{// Order important in following block
this.clustering._updateState();this._updateVisibleIndices();this._updateValueRange(this.body.nodes);this._updateValueRange(this.body.edges);// start simulation (can be called safely, even if already running)
this.body.emitter.emit("startSimulation");this.body.emitter.emit("_requestRedraw");});};/**
 * Set nodes and edges, and optionally options as well.
 * @param {object} data              Object containing parameters:
 *                                   {Array | DataSet | DataView} [nodes] Array with nodes
 *                                   {Array | DataSet | DataView} [edges] Array with edges
 *                                   {String} [dot] String containing data in DOT format
 *                                   {String} [gephi] String containing data in gephi JSON format
 *                                   {Options} [options] Object with options
 */Network.prototype.setData=function(data){// reset the physics engine.
this.body.emitter.emit("resetPhysics");this.body.emitter.emit("_resetData");// unselect all to ensure no selections from old data are carried over.
this.selectionHandler.unselectAll();if(data&&data.dot&&(data.nodes||data.edges)){throw new SyntaxError('Data must contain either parameter "dot" or '+' parameter pair "nodes" and "edges", but not both.');}// set options
this.setOptions(data&&data.options);// set all data
if(data&&data.dot){console.warn("The dot property has been deprecated. Please use the static convertDot method to convert DOT into vis.network format and use the normal data format with nodes and edges. This converter is used like this: var data = vis.network.convertDot(dotString);");// parse DOT file
const dotData=DOTToGraph(data.dot);this.setData(dotData);return;}else if(data&&data.gephi){// parse DOT file
console.warn("The gephi property has been deprecated. Please use the static convertGephi method to convert gephi into vis.network format and use the normal data format with nodes and edges. This converter is used like this: var data = vis.network.convertGephi(gephiJson);");const gephiData=parseGephi(data.gephi);this.setData(gephiData);return;}else {this.nodesHandler.setData(data&&data.nodes,true);this.edgesHandler.setData(data&&data.edges,true);}// emit change in data
this.body.emitter.emit("_dataChanged");// emit data loaded
this.body.emitter.emit("_dataLoaded");// find a stable position or start animating to a stable position
this.body.emitter.emit("initPhysics");};/**
 * Cleans up all bindings of the network, removing it fully from the memory IF the variable is set to null after calling this function.
 * var network = new vis.Network(..);
 * network.destroy();
 * network = null;
 */Network.prototype.destroy=function(){this.body.emitter.emit("destroy");// clear events
this.body.emitter.off();this.off();// delete modules
delete this.groups;delete this.canvas;delete this.selectionHandler;delete this.interactionHandler;delete this.view;delete this.renderer;delete this.physics;delete this.layoutEngine;delete this.clustering;delete this.manipulation;delete this.nodesHandler;delete this.edgesHandler;delete this.configurator;delete this.images;for(const nodeId in this.body.nodes){if(!Object.prototype.hasOwnProperty.call(this.body.nodes,nodeId))continue;delete this.body.nodes[nodeId];}for(const edgeId in this.body.edges){if(!Object.prototype.hasOwnProperty.call(this.body.edges,edgeId))continue;delete this.body.edges[edgeId];}// remove the container and everything inside it recursively
recursiveDOMDelete(this.body.container);};/**
 * Update the values of all object in the given array according to the current
 * value range of the objects in the array.
 * @param {object} obj    An object containing a set of Edges or Nodes
 *                        The objects must have a method getValue() and
 *                        setValueRange(min, max).
 * @private
 */Network.prototype._updateValueRange=function(obj){let id;// determine the range of the objects
let valueMin=undefined;let valueMax=undefined;let valueTotal=0;for(id in obj){if(Object.prototype.hasOwnProperty.call(obj,id)){const value=obj[id].getValue();if(value!==undefined){valueMin=valueMin===undefined?value:Math.min(value,valueMin);valueMax=valueMax===undefined?value:Math.max(value,valueMax);valueTotal+=value;}}}// adjust the range of all objects
if(valueMin!==undefined&&valueMax!==undefined){for(id in obj){if(Object.prototype.hasOwnProperty.call(obj,id)){obj[id].setValueRange(valueMin,valueMax,valueTotal);}}}};/**
 * Returns true when the Network is active.
 * @returns {boolean}
 */Network.prototype.isActive=function(){return !this.activator||this.activator.active;};Network.prototype.setSize=function(){return this.canvas.setSize.apply(this.canvas,arguments);};Network.prototype.canvasToDOM=function(){return this.canvas.canvasToDOM.apply(this.canvas,arguments);};Network.prototype.DOMtoCanvas=function(){return this.canvas.DOMtoCanvas.apply(this.canvas,arguments);};/**
 * Nodes can be in clusters. Clusters can also be in clusters. This function returns and array of
 * nodeIds showing where the node is.
 *
 * If any nodeId in the chain, especially the first passed in as a parameter, is not present in
 * the current nodes list, an empty array is returned.
 *
 * Example:
 * cluster 'A' contains cluster 'B',
 * cluster 'B' contains cluster 'C',
 * cluster 'C' contains node 'fred'.
 * `jsnetwork.clustering.findNode('fred')` will return `['A','B','C','fred']`.
 * @param {string|number} nodeId
 * @returns {Array}
 */Network.prototype.findNode=function(){return this.clustering.findNode.apply(this.clustering,arguments);};Network.prototype.isCluster=function(){return this.clustering.isCluster.apply(this.clustering,arguments);};Network.prototype.openCluster=function(){return this.clustering.openCluster.apply(this.clustering,arguments);};Network.prototype.cluster=function(){return this.clustering.cluster.apply(this.clustering,arguments);};Network.prototype.getNodesInCluster=function(){return this.clustering.getNodesInCluster.apply(this.clustering,arguments);};Network.prototype.clusterByConnection=function(){return this.clustering.clusterByConnection.apply(this.clustering,arguments);};Network.prototype.clusterByHubsize=function(){return this.clustering.clusterByHubsize.apply(this.clustering,arguments);};Network.prototype.updateClusteredNode=function(){return this.clustering.updateClusteredNode.apply(this.clustering,arguments);};Network.prototype.getClusteredEdges=function(){return this.clustering.getClusteredEdges.apply(this.clustering,arguments);};Network.prototype.getBaseEdge=function(){return this.clustering.getBaseEdge.apply(this.clustering,arguments);};Network.prototype.getBaseEdges=function(){return this.clustering.getBaseEdges.apply(this.clustering,arguments);};Network.prototype.updateEdge=function(){return this.clustering.updateEdge.apply(this.clustering,arguments);};/**
 * This method will cluster all nodes with 1 edge with their respective connected node.
 * The options object is explained in full <a data-scroll="" data-options="{ &quot;easing&quot;: &quot;easeInCubic&quot; }" href="#optionsObject">below</a>.
 * @param {object} [options]
 * @returns {undefined}
 */Network.prototype.clusterOutliers=function(){return this.clustering.clusterOutliers.apply(this.clustering,arguments);};Network.prototype.getSeed=function(){return this.layoutEngine.getSeed.apply(this.layoutEngine,arguments);};Network.prototype.enableEditMode=function(){return this.manipulation.enableEditMode.apply(this.manipulation,arguments);};Network.prototype.disableEditMode=function(){return this.manipulation.disableEditMode.apply(this.manipulation,arguments);};Network.prototype.addNodeMode=function(){return this.manipulation.addNodeMode.apply(this.manipulation,arguments);};Network.prototype.editNode=function(){return this.manipulation.editNode.apply(this.manipulation,arguments);};Network.prototype.editNodeMode=function(){console.warn("Deprecated: Please use editNode instead of editNodeMode.");return this.manipulation.editNode.apply(this.manipulation,arguments);};Network.prototype.addEdgeMode=function(){return this.manipulation.addEdgeMode.apply(this.manipulation,arguments);};Network.prototype.editEdgeMode=function(){return this.manipulation.editEdgeMode.apply(this.manipulation,arguments);};Network.prototype.deleteSelected=function(){return this.manipulation.deleteSelected.apply(this.manipulation,arguments);};Network.prototype.getPositions=function(){return this.nodesHandler.getPositions.apply(this.nodesHandler,arguments);};Network.prototype.getPosition=function(){return this.nodesHandler.getPosition.apply(this.nodesHandler,arguments);};Network.prototype.storePositions=function(){return this.nodesHandler.storePositions.apply(this.nodesHandler,arguments);};Network.prototype.moveNode=function(){return this.nodesHandler.moveNode.apply(this.nodesHandler,arguments);};Network.prototype.getBoundingBox=function(){return this.nodesHandler.getBoundingBox.apply(this.nodesHandler,arguments);};Network.prototype.getConnectedNodes=function(objectId){if(this.body.nodes[objectId]!==undefined){return this.nodesHandler.getConnectedNodes.apply(this.nodesHandler,arguments);}else {return this.edgesHandler.getConnectedNodes.apply(this.edgesHandler,arguments);}};Network.prototype.getConnectedEdges=function(){return this.nodesHandler.getConnectedEdges.apply(this.nodesHandler,arguments);};Network.prototype.startSimulation=function(){return this.physics.startSimulation.apply(this.physics,arguments);};Network.prototype.stopSimulation=function(){return this.physics.stopSimulation.apply(this.physics,arguments);};Network.prototype.stabilize=function(){return this.physics.stabilize.apply(this.physics,arguments);};Network.prototype.getSelection=function(){return this.selectionHandler.getSelection.apply(this.selectionHandler,arguments);};Network.prototype.setSelection=function(){return this.selectionHandler.setSelection.apply(this.selectionHandler,arguments);};Network.prototype.getSelectedNodes=function(){return this.selectionHandler.getSelectedNodeIds.apply(this.selectionHandler,arguments);};Network.prototype.getSelectedEdges=function(){return this.selectionHandler.getSelectedEdgeIds.apply(this.selectionHandler,arguments);};Network.prototype.getNodeAt=function(){const node=this.selectionHandler.getNodeAt.apply(this.selectionHandler,arguments);if(node!==undefined&&node.id!==undefined){return node.id;}return node;};Network.prototype.getEdgeAt=function(){const edge=this.selectionHandler.getEdgeAt.apply(this.selectionHandler,arguments);if(edge!==undefined&&edge.id!==undefined){return edge.id;}return edge;};Network.prototype.selectNodes=function(){return this.selectionHandler.selectNodes.apply(this.selectionHandler,arguments);};Network.prototype.selectEdges=function(){return this.selectionHandler.selectEdges.apply(this.selectionHandler,arguments);};Network.prototype.unselectAll=function(){this.selectionHandler.unselectAll.apply(this.selectionHandler,arguments);this.selectionHandler.commitWithoutEmitting.apply(this.selectionHandler);this.redraw();};Network.prototype.redraw=function(){return this.renderer.redraw.apply(this.renderer,arguments);};Network.prototype.getScale=function(){return this.view.getScale.apply(this.view,arguments);};Network.prototype.getViewPosition=function(){return this.view.getViewPosition.apply(this.view,arguments);};Network.prototype.fit=function(){return this.view.fit.apply(this.view,arguments);};Network.prototype.moveTo=function(){return this.view.moveTo.apply(this.view,arguments);};Network.prototype.focus=function(){return this.view.focus.apply(this.view,arguments);};Network.prototype.releaseNode=function(){return this.view.releaseNode.apply(this.view,arguments);};Network.prototype.getOptionsFromConfigurator=function(){let options={};if(this.configurator){options=this.configurator.getOptions.apply(this.configurator);}return options;};

var _staticBlock;
var __defProp$6 = Object.defineProperty;
var __decorateClass$7 = (decorators, target, key, kind) => {
  var result = void 0 ;
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (decorator(target, key, result) ) || result;
  if (result) __defProp$6(target, key, result);
  return result;
};
class BaseNetworkGraph extends i$4 {
  constructor() {
    super(...arguments);
    this.nodes = {};
    this._selectedNodeId = null;
    this._physicsEnabled = true;
    /** Whether auto-freeze has already been applied (to avoid re-freezing after user unfreezes) */
    this._autoFreezeApplied = false;
    /** Whether initial fit has been done (to preserve user's zoom/pan after first load) */
    this._initialFitDone = false;
    /** Store original edge colors for restoration after highlighting */
    this._originalEdgeColors = /* @__PURE__ */new Map();
  }
  _getFontColor() {
    return getCssVar("--graph-font-color", ThemeService.effectiveTheme === "dark" ? "#e0e0e0" : "#333333");
  }
  _getDimmedEdgeColor() {
    return getCssVar("--graph-edge-dimmed", ThemeService.effectiveTheme === "dark" ? "#555555" : "#cccccc");
  }
  /**
   * Returns physics options for the network. Override in subclasses for different behavior.
   */
  _getPhysicsOptions() {
    return {
      enabled: true,
      solver: "forceAtlas2Based",
      forceAtlas2Based: {
        gravitationalConstant: -70,
        centralGravity: 5e-3,
        springLength: 130,
        springConstant: 0.08,
        damping: 0.4,
        avoidOverlap: 0.6
      },
      stabilization: {
        enabled: true,
        iterations: 250,
        updateInterval: 25
      }
    };
  }
  updated(changedProperties) {
    super.updated(changedProperties);
    if (!this._container && !this._resizeObserver) {
      this._tryAttachContainer();
    }
    if (changedProperties.has("nodes")) {
      this._debouncedUpdateGraph();
    }
  }
  /**
   * Try to find and attach the graph container if it wasn't available before.
   * This handles the case where empty state was rendered initially.
   */
  _tryAttachContainer() {
    const container = this.shadowRoot?.querySelector(".graph-container");
    if (container) {
      this._container = container;
      this._resizeObserver = new ResizeObserver(entries => {
        const entry = entries[0];
        if (entry && entry.contentRect.width > 0 && entry.contentRect.height > 0) {
          if (!this._network) {
            this._initializeNetwork();
          } else {
            this._network.setSize(`${entry.contentRect.width}px`, `${entry.contentRect.height}px`);
            this._network.redraw();
          }
        }
      });
      this._resizeObserver.observe(this._container);
    }
  }
  /** Debounced graph update to avoid excessive redraws */
  _debouncedUpdateGraph() {
    if (this._updateDebounceTimer) {
      clearTimeout(this._updateDebounceTimer);
    }
    this._updateDebounceTimer = setTimeout(() => {
      this._updateGraph();
    }, 100);
  }
  firstUpdated() {
    this._container = this.shadowRoot?.querySelector(".graph-container");
    if (this._container) {
      this._resizeObserver = new ResizeObserver(entries => {
        const entry = entries[0];
        if (entry && entry.contentRect.width > 0 && entry.contentRect.height > 0) {
          if (!this._network) {
            this._initializeNetwork();
          } else {
            this._network.setSize(`${entry.contentRect.width}px`, `${entry.contentRect.height}px`);
            this._network.redraw();
          }
        }
      });
      this._resizeObserver.observe(this._container);
    }
    this._themeUnsubscribe = ThemeService.subscribe(() => {
      if (this._network && this._nodesDataSet) {
        const fontColor = this._getFontColor();
        this._network.setOptions({
          nodes: {
            font: {
              color: fontColor
            }
          }
        });
        this._updateGraph();
        const allNodes = this._nodesDataSet.get();
        const nodeUpdates = allNodes.map(node => ({
          id: node.id,
          font: {
            color: fontColor
          }
        }));
        this._nodesDataSet.update(nodeUpdates);
        this._network.redraw();
      }
    });
  }
  disconnectedCallback() {
    super.disconnectedCallback();
    this._resizeObserver?.disconnect();
    this._themeUnsubscribe?.();
    this._cancelAutoFreezeTimer();
    if (this._updateDebounceTimer) {
      clearTimeout(this._updateDebounceTimer);
    }
    this._nodesDataSet?.clear();
    this._edgesDataSet?.clear();
    this._network?.destroy();
    this._network = void 0;
    this._nodesDataSet = void 0;
    this._edgesDataSet = void 0;
    this._originalEdgeColors.clear();
  }
  _initializeNetwork() {
    if (!this._container) return;
    const rect = this._container.getBoundingClientRect();
    if (rect.width === 0 || rect.height === 0) {
      return;
    }
    this._nodesDataSet = new DataSet();
    this._edgesDataSet = new DataSet();
    const options = {
      width: `${rect.width}px`,
      height: `${rect.height}px`,
      autoResize: false,
      // We handle resize manually
      nodes: {
        shape: "image",
        size: 30,
        font: {
          size: 12,
          color: this._getFontColor()
        },
        borderWidth: 2,
        borderWidthSelected: 3
      },
      edges: {
        width: 2,
        smooth: {
          enabled: true,
          type: "continuous",
          roundness: 0.5
        }
      },
      physics: this._getPhysicsOptions(),
      interaction: {
        hover: true,
        tooltipDelay: 200,
        hideEdgesOnDrag: true
      }
    };
    this._network = new Network(this._container, {
      nodes: this._nodesDataSet,
      edges: this._edgesDataSet
    }, options);
    this._network.on("selectNode", params => {
      if (params.nodes.length > 0) {
        this._selectedNodeId = params.nodes[0];
        this._highlightConnections(this._selectedNodeId);
        this._dispatchNodeSelected(this._selectedNodeId);
      }
    });
    this._network.on("deselectNode", () => {
      this._selectedNodeId = null;
      this._clearHighlights();
      this._dispatchNodeSelected(null);
    });
    this._network.on("stabilizationIterationsDone", () => {
      if (!this._initialFitDone) {
        this._network?.fit({
          animation: {
            duration: 500,
            easingFunction: "easeInOutQuad"
          }
        });
        this._initialFitDone = true;
        this._startAutoFreezeTimer();
      }
    });
    this._updateGraph();
  }
  /**
   * Returns true if the graph is initialized and ready for interaction.
   */
  isReady() {
    return this._network !== void 0 && this._nodesDataSet !== void 0;
  }
  /**
   * Fits all nodes into view.
   */
  fit() {
    this._network?.fit({
      animation: {
        duration: 300,
        easingFunction: "easeInOutQuad"
      }
    });
  }
  /**
   * Zooms in by 20%.
   */
  zoomIn() {
    if (!this._network) return;
    const scale = this._network.getScale();
    this._network.moveTo({
      scale: scale * 1.2,
      animation: {
        duration: 200,
        easingFunction: "easeInOutQuad"
      }
    });
  }
  /**
   * Zooms out by 20%.
   */
  zoomOut() {
    if (!this._network) return;
    const scale = this._network.getScale();
    this._network.moveTo({
      scale: scale / 1.2,
      animation: {
        duration: 200,
        easingFunction: "easeInOutQuad"
      }
    });
  }
  /**
   * Returns whether physics simulation is currently enabled.
   */
  get physicsEnabled() {
    return this._physicsEnabled;
  }
  /**
   * Enables or disables physics simulation (node movement/settling).
   * When disabled, nodes freeze in place; when enabled, they resume settling.
   * @param enabled Whether to enable physics
   * @param isManual If true, cancels any pending auto-freeze (user manually toggled)
   */
  setPhysicsEnabled(enabled, isManual = true) {
    if (isManual) {
      this._cancelAutoFreezeTimer();
      this._autoFreezeApplied = true;
    }
    this._physicsEnabled = enabled;
    this._network?.setOptions({
      physics: {
        enabled
      }
    });
  }
  /**
   * Starts the auto-freeze timer. Physics will be disabled after 5 seconds
   * unless the user manually toggles physics or the timer is cancelled.
   */
  _startAutoFreezeTimer() {
    if (this._autoFreezeApplied) {
      return;
    }
    this._cancelAutoFreezeTimer();
    this._autoFreezeTimer = setTimeout(() => {
      if (!this._autoFreezeApplied && this._physicsEnabled) {
        this.setPhysicsEnabled(false, false);
        this._autoFreezeApplied = true;
        this.dispatchEvent(new CustomEvent("physics-changed", {
          detail: {
            enabled: false
          },
          bubbles: true,
          composed: true
        }));
      }
    }, 5e3);
  }
  /**
   * Cancels any pending auto-freeze timer.
   */
  _cancelAutoFreezeTimer() {
    if (this._autoFreezeTimer) {
      clearTimeout(this._autoFreezeTimer);
      this._autoFreezeTimer = void 0;
    }
  }
  /**
   * Selects a node by ID and focuses on it.
   */
  selectNode(nodeId) {
    if (!this._network) return;
    this._selectedNodeId = nodeId;
    this._network.selectNodes([nodeId]);
    this._highlightConnections(nodeId);
    this._dispatchNodeSelected(nodeId);
    this._network.focus(nodeId, {
      scale: 1.2,
      animation: {
        duration: 500,
        easingFunction: "easeInOutQuad"
      }
    });
  }
  /**
   * Deselects all nodes, clears highlights, and restores default styling.
   */
  deselectAll() {
    if (!this._network) return;
    this._selectedNodeId = null;
    this._network.unselectAll();
    this._clearHighlights();
  }
  _dispatchNodeSelected(nodeId) {
    this.dispatchEvent(new CustomEvent("node-selected", {
      detail: {
        nodeId
      },
      bubbles: true,
      composed: true
    }));
  }
  /**
   * Highlights edges connected to the selected node and makes neighbor nodes more prominent.
   */
  _highlightConnections(nodeId) {
    if (!this._edgesDataSet || !this._nodesDataSet) return;
    const allEdges = this._edgesDataSet.get();
    for (const edge of allEdges) {
      const edgeId = String(edge.id);
      if (!this._originalEdgeColors.has(edgeId)) {
        const colorObj = edge.color;
        const color = colorObj?.color ?? getCssVar("--graph-node-fallback", "#999999");
        const highlight = colorObj?.highlight ?? color;
        this._originalEdgeColors.set(edgeId, {
          color,
          highlight
        });
      }
    }
    const connectedEdges = this._edgesDataSet.get({
      filter: edge => edge.from === nodeId || edge.to === nodeId
    });
    const neighborIds = /* @__PURE__ */new Set();
    for (const edge of connectedEdges) {
      if (edge.from === nodeId) {
        neighborIds.add(edge.to);
      } else {
        neighborIds.add(edge.from);
      }
    }
    const dimmedColor = this._getDimmedEdgeColor();
    const edgeUpdates = allEdges.map(edge => {
      const isConnected = edge.from === nodeId || edge.to === nodeId;
      const originalColor = this._originalEdgeColors.get(String(edge.id));
      const connectedColor = originalColor ?? {
        color: getCssVar("--graph-node-fallback", "#999999"),
        highlight: getCssVar("--graph-node-fallback", "#999999")
      };
      return {
        id: edge.id,
        width: isConnected ? 3 : 1,
        color: isConnected ? {
          color: connectedColor.color,
          highlight: connectedColor.highlight
        } : {
          color: dimmedColor,
          highlight: dimmedColor
        }
      };
    });
    this._edgesDataSet.update(edgeUpdates);
    const allNodes = this._nodesDataSet.get();
    const nodeUpdates = allNodes.map(node => {
      const isNeighbor = neighborIds.has(node.id);
      const isSelected = node.id === nodeId;
      return {
        id: node.id,
        size: isSelected ? 40 : isNeighbor ? 35 : 25,
        font: {
          size: isSelected ? 14 : isNeighbor ? 13 : 11,
          color: this._getFontColor(),
          bold: isSelected || isNeighbor ? {
            color: this._getFontColor()
          } : void 0
        },
        opacity: isSelected || isNeighbor ? 1 : 0.5
      };
    });
    this._nodesDataSet.update(nodeUpdates);
  }
  /**
   * Clears all highlights and restores default styling.
   */
  _clearHighlights() {
    if (!this._edgesDataSet || !this._nodesDataSet) return;
    const allEdges = this._edgesDataSet.get();
    const edgeUpdates = allEdges.map(edge => {
      const originalColor = this._originalEdgeColors.get(String(edge.id));
      return {
        id: edge.id,
        width: 2,
        color: originalColor ?? {
          color: getCssVar("--graph-node-fallback", "#999999"),
          highlight: getCssVar("--graph-node-fallback", "#999999")
        }
      };
    });
    this._edgesDataSet.update(edgeUpdates);
    const allNodes = this._nodesDataSet.get();
    const nodeUpdates = allNodes.map(node => ({
      id: node.id,
      size: 30,
      font: {
        size: 12,
        color: this._getFontColor(),
        bold: void 0
      },
      opacity: 1
    }));
    this._nodesDataSet.update(nodeUpdates);
  }
  /**
   * Clear stored edge colors when graph is updated (edges are recreated).
   */
  _clearOriginalEdgeColors() {
    this._originalEdgeColors.clear();
  }
  static #_ = _staticBlock = () => this.styles = i$7`
        :host {
            display: block;
            width: 100%;
            height: 100%;
            min-height: 0;
        }

        .graph-container {
            width: 100%;
            height: 100%;
            background-color: var(--md-sys-color-surface, #fff);
            border-radius: 8px;
            border: 1px solid var(--md-sys-color-outline-variant, #ccc);
        }

        .empty-state {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
            color: var(--md-sys-color-on-surface-variant, #666);
            text-align: center;
            padding: 24px;
            box-sizing: border-box;
            background-color: var(--md-sys-color-surface, #fff);
            border-radius: 8px;
            border: 1px solid var(--md-sys-color-outline-variant, #ccc);
        }

        .empty-state p {
            margin: 8px 0;
        }

        .empty-state .hint {
            font-size: 0.875rem;
            opacity: 0.7;
        }
    `;
}
_staticBlock();
__decorateClass$7([n$5({
  type: Object
})], BaseNetworkGraph.prototype, "nodes");
__decorateClass$7([r$3()], BaseNetworkGraph.prototype, "_selectedNodeId");
__decorateClass$7([r$3()], BaseNetworkGraph.prototype, "_physicsEnabled");

var __defProp$5 = Object.defineProperty;
var __getOwnPropDesc$6 = Object.getOwnPropertyDescriptor;
var __decorateClass$6 = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$6(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp$5(target, key, result);
  return result;
};
let ThreadGraph = class extends BaseNetworkGraph {
  constructor() {
    super(...arguments);
    this.borderRouters = /* @__PURE__ */new Map();
    this.hideOfflineNodes = false;
    this.hideWeakSignalEdges = false;
    this.hideMediumSignalEdges = false;
    this.hideStrongSignalEdges = false;
    /** Cache of external Thread devices (Border Routers and unknown) for the current render */
    this._unknownDevices = [];
    /** Cached map of external Thread devices (rebuilt in _updateGraph) */
    this._unknownDevicesMapCache = /* @__PURE__ */new Map();
    /** All computed edge pairs (rebuilt in _updateGraph) */
    this._edgePairs = /* @__PURE__ */new Map();
    /** Base state of each edge after filter+dedup, before highlight */
    this._edgeBaseState = /* @__PURE__ */new Map();
    /** Whether highlight is currently active */
    this._isHighlighted = false;
    /** Node ID currently highlighted (for icon restoration on clear) */
    this._highlightedNodeId = null;
  }
  /** Get external Thread devices as a map for use by details panel */
  get unknownDevicesMap() {
    return this._unknownDevicesMapCache;
  }
  /** Get computed edge pairs (for potential use by other components) */
  get edgePairs() {
    return this._edgePairs;
  }
  updated(changedProperties) {
    super.updated(changedProperties);
    if (changedProperties.has("hideOfflineNodes") || changedProperties.has("hideWeakSignalEdges") || changedProperties.has("hideMediumSignalEdges") || changedProperties.has("hideStrongSignalEdges") || changedProperties.has("borderRouters")) {
      this._debouncedUpdateGraph();
    }
  }
  /**
   * Searches for a Thread node (known or unknown) and selects it. Matches, in priority order:
   * 1. Extended address (EUI-64), accepting `AABBCCDDEEFF0011`, `AA:BB:...`, or `0x...` forms.
   * 2. Node id (exact).
   * 3. Visible device label (case-insensitive substring).
   * Returns true when a match is found.
   */
  selectBySearch(query) {
    const trimmed = query.trim();
    if (!trimmed) {
      return false;
    }
    const threadNodes = Object.values(this.nodes).filter(node => getNetworkType(node) === "thread" && !(this.hideOfflineNodes && node.available === false));
    const normalized = normalizeExtendedAddressInput(trimmed);
    if (normalized) {
      for (const node of threadNodes) {
        const extAddressHex = getThreadExtendedAddressHex(node);
        if (extAddressHex && extAddressHex === normalized) {
          this.selectNode(String(node.node_id));
          return true;
        }
      }
      for (const [unknownId, unknown] of this._unknownDevicesMapCache) {
        if (normalizeExtendedAddressInput(unknown.extAddressHex) === normalized) {
          this.selectNode(unknownId);
          return true;
        }
      }
    }
    for (const node of threadNodes) {
      if (String(node.node_id) === trimmed) {
        this.selectNode(String(node.node_id));
        return true;
      }
    }
    const needle = trimmed.toLowerCase();
    for (const node of threadNodes) {
      if (getDeviceName(node).toLowerCase().includes(needle)) {
        this.selectNode(String(node.node_id));
        return true;
      }
    }
    return false;
  }
  _updateGraph() {
    if (!this._nodesDataSet || !this._edgesDataSet) return;
    this._clearOriginalEdgeColors();
    this._edgeBaseState.clear();
    this._isHighlighted = false;
    const threadNodes = Object.values(this.nodes).filter(node => getNetworkType(node) === "thread");
    if (threadNodes.length === 0) {
      this._nodesDataSet.clear();
      this._edgesDataSet.clear();
      this._unknownDevices = [];
      this._unknownDevicesMapCache.clear();
      this._edgePairs.clear();
      return;
    }
    const extAddrMap = buildExtAddrMap(this.nodes);
    const rloc16Map = buildRloc16Map(this.nodes);
    this._unknownDevices = findUnknownDevices(this.nodes, extAddrMap, rloc16Map, this.borderRouters);
    this._unknownDevicesMapCache.clear();
    for (const device of this._unknownDevices) {
      this._unknownDevicesMapCache.set(device.id, device);
    }
    this._edgePairs = buildThreadEdgePairs(this.nodes, extAddrMap, rloc16Map, this._unknownDevices);
    const hiddenNodeIds = /* @__PURE__ */new Set();
    const graphNodes = threadNodes.map(node => {
      const nodeId = String(node.node_id);
      const threadRole = getThreadRole(node);
      const isOffline = node.available === false;
      const shouldHide = this.hideOfflineNodes && isOffline;
      if (shouldHide) {
        hiddenNodeIds.add(nodeId);
      }
      return {
        id: nodeId,
        label: getDeviceName(node),
        image: createNodeIconDataUrl(node, threadRole, false, isOffline),
        shape: "image",
        networkType: "thread",
        threadRole,
        offline: isOffline,
        hidden: shouldHide
      };
    });
    for (const device of this._unknownDevices) {
      const isSelected = device.id === this._selectedNodeId;
      const hasOnlineObserver = device.seenBy.some(nodeId => {
        const node = this.nodes[nodeId];
        return node !== void 0 && node.available !== false;
      });
      let shouldHide;
      if (device.kind === "unknown") {
        shouldHide = !hasOnlineObserver;
        if (!shouldHide && device.seenBy.length === 1) {
          const observer = this.nodes[device.seenBy[0]];
          if (observer !== void 0 && getNeighborTableLength(observer) > 1) {
            shouldHide = true;
          }
        }
      } else {
        shouldHide = this.hideOfflineNodes && !hasOnlineObserver;
      }
      if (shouldHide) {
        hiddenNodeIds.add(device.id);
      }
      if (device.kind === "br") {
        const hostname = device.hostname !== void 0 ? stripMdnsHostname(device.hostname) : void 0;
        const top = (hostname ?? device.networkName ?? "Border Router").slice(0, 24);
        const suffix = hostname !== void 0 && device.networkName !== void 0 && device.networkName !== top ? `
${device.networkName}` : "";
        const label = `${top}${suffix}`;
        const decodedState = decodeMeshcopStateBitmap(device.stateBitmapHex);
        const isLeader = decodedState?.threadRoleValue === 3;
        const isPrimaryBbr = decodedState?.bbr === true && decodedState.bbrFunction === "primary";
        graphNodes.push({
          id: device.id,
          label,
          image: createBorderRouterIconDataUrl(isSelected, isLeader, isPrimaryBbr),
          shape: "image",
          networkType: "thread",
          isUnknown: false,
          hidden: shouldHide
        });
      } else {
        const typeLabel = device.isRouter ? "External Router" : "External Device";
        const suffix = device.networkName !== void 0 ? `
${device.networkName}` : "";
        graphNodes.push({
          id: device.id,
          label: `${typeLabel} (${device.extAddressHex.slice(-8)})${suffix}`,
          image: createUnknownDeviceIconDataUrl(device.isRouter, isSelected),
          shape: "image",
          networkType: "thread",
          isUnknown: true,
          hidden: shouldHide
        });
      }
    }
    const graphEdges = [];
    for (const pair of this._edgePairs.values()) {
      const edgesInPair = [];
      let hadZeroEdge = false;
      let hadLiveEdge = false;
      for (const conn of [pair.edgeAB, pair.edgeBA]) {
        if (!conn) continue;
        const fromId = String(conn.fromNodeId);
        const toId = String(conn.toNodeId);
        const isToUnknown = toId.startsWith("unknown_") || toId.startsWith("br_");
        const fromNode = this.nodes[fromId];
        const toNode = this.nodes[toId];
        const hasOfflineEndpoint = fromNode?.available === false || toNode?.available === false;
        let filterHidden = false;
        if (hiddenNodeIds.has(fromId) || hiddenNodeIds.has(toId)) {
          filterHidden = true;
        }
        if (conn.signalLevel === "none") {
          filterHidden = true;
          hadZeroEdge = true;
        } else {
          hadLiveEdge = true;
        }
        if (!filterHidden && this.hideWeakSignalEdges && conn.signalLevel === "weak") {
          filterHidden = true;
        }
        if (!filterHidden && this.hideMediumSignalEdges && conn.signalLevel === "medium") {
          filterHidden = true;
        }
        if (!filterHidden && this.hideStrongSignalEdges && conn.signalLevel === "strong") {
          filterHidden = true;
        }
        const edgeId = `edge_${fromId}_${toId}`;
        const visEdge = {
          id: edgeId,
          from: fromId,
          to: toId,
          color: {
            color: conn.signalColor,
            highlight: conn.signalColor
          },
          width: 2,
          title: conn.rssi !== null ? `RSSI: ${conn.rssi} dBm, LQI: ${conn.lqi}` : `LQI: ${conn.lqi}`,
          dashes: isToUnknown || hasOfflineEndpoint,
          hidden: filterHidden,
          pairKey: pair.pairKey,
          reportingNodeId: fromId
        };
        edgesInPair.push({
          conn,
          visEdge,
          filterHidden
        });
      }
      const visibleInPair = edgesInPair.filter(e => !e.visEdge.hidden);
      if (visibleInPair.length > 1) {
        visibleInPair.sort((a, b) => getEdgeSignalScore(a.conn) - getEdgeSignalScore(b.conn));
        for (let i = 1; i < visibleInPair.length; i++) {
          visibleInPair[i].visEdge.hidden = true;
        }
      }
      if (hadZeroEdge && hadLiveEdge) {
        for (const e of edgesInPair) {
          if (!e.visEdge.hidden) {
            e.visEdge.dashes = true;
            e.visEdge.title = `${e.visEdge.title ?? ""} (asymmetric: peer reports no link)`;
          }
        }
      }
      for (const e of edgesInPair) {
        const isHidden = e.visEdge.hidden ?? false;
        let hiddenReason = "visible";
        if (isHidden) {
          hiddenReason = e.filterHidden ? "filter" : "dedup";
        }
        this._edgeBaseState.set(e.visEdge.id, {
          hiddenReason,
          width: e.visEdge.width,
          color: {
            color: e.visEdge.color.color,
            highlight: e.visEdge.color.highlight
          },
          dashes: e.visEdge.dashes ?? false
        });
        graphEdges.push(e.visEdge);
      }
    }
    const existingNodeIds = this._nodesDataSet.getIds();
    const newNodeIds = new Set(graphNodes.map(n => n.id));
    const nodesToRemove = existingNodeIds.filter(id => !newNodeIds.has(id));
    if (nodesToRemove.length > 0) {
      this._nodesDataSet.remove(nodesToRemove);
    }
    this._nodesDataSet.update(graphNodes);
    this._edgesDataSet.clear();
    this._edgesDataSet.add(graphEdges);
    if (this._selectedNodeId !== null) {
      this._highlightConnections(this._selectedNodeId);
    }
  }
  /**
   * Highlights edges connected to the selected node with swap/arrow logic.
   *
   * For each visible edge connected to the highlighted node:
   * - If the visible edge comes from the remote node AND there is a
   *   dedup-hidden edge from the highlighted node → SWAP: show the
   *   highlighted node's edge instead (its signal is better or equal,
   *   but we prefer the highlighted node's perspective).
   * - Otherwise → thicken the edge. If the pair is truly one-way (only
   *   one of edgeAB/edgeBA exists), also draw an arrow in the data
   *   direction so asymmetric visibility is visible at a glance.
   */
  _highlightConnections(nodeId) {
    if (!this._edgesDataSet || !this._nodesDataSet) return;
    const nodeIdStr = String(nodeId);
    if (this._isHighlighted && this._highlightedNodeId === nodeIdStr) return;
    if (this._isHighlighted) {
      this._restoreEdgeBaseState();
    }
    const allEdges = this._edgesDataSet.get();
    const dimmedColor = this._getDimmedEdgeColor();
    const edgesByPair = /* @__PURE__ */new Map();
    for (const edge of allEdges) {
      if (edge.pairKey) {
        const list = edgesByPair.get(edge.pairKey) ?? [];
        list.push(edge);
        edgesByPair.set(edge.pairKey, list);
      }
    }
    const connectedNodeIds = /* @__PURE__ */new Set();
    const edgeUpdates = {};
    for (const edge of allEdges) {
      const fromStr = String(edge.from);
      const toStr = String(edge.to);
      const isConnected = fromStr === nodeIdStr || toStr === nodeIdStr;
      if (!isConnected) {
        const baseState2 = this._edgeBaseState.get(edge.id);
        if (baseState2 && baseState2.hiddenReason === "visible") {
          edgeUpdates[String(edge.id)] = {
            id: edge.id,
            width: 1,
            color: {
              color: dimmedColor,
              highlight: dimmedColor
            }
          };
        }
        continue;
      }
      const baseState = this._edgeBaseState.get(edge.id);
      if (!baseState || baseState.hiddenReason !== "visible") {
        continue;
      }
      const remoteId = fromStr === nodeIdStr ? toStr : fromStr;
      const reportingId = String(edge.reportingNodeId ?? edge.from);
      connectedNodeIds.add(remoteId);
      if (reportingId !== nodeIdStr) {
        const pairEdges = edge.pairKey ? edgesByPair.get(edge.pairKey) : void 0;
        const swapCandidate = pairEdges?.find(e => {
          const rid = String(e.reportingNodeId ?? e.from);
          if (rid !== nodeIdStr) return false;
          const bs = this._edgeBaseState.get(e.id);
          return bs?.hiddenReason === "dedup";
        });
        if (swapCandidate) {
          const swapBaseState = this._edgeBaseState.get(swapCandidate.id);
          edgeUpdates[String(edge.id)] = {
            id: edge.id,
            hidden: true
          };
          edgeUpdates[String(swapCandidate.id)] = {
            id: swapCandidate.id,
            hidden: false,
            width: 3,
            color: swapBaseState ? {
              color: swapBaseState.color.color,
              highlight: swapBaseState.color.highlight
            } : {
              color: "#999999",
              highlight: "#999999"
            }
          };
        } else {
          edgeUpdates[String(edge.id)] = this._reverseEdgeUpdate(edge);
        }
      } else {
        edgeUpdates[String(edge.id)] = this._asymmetricEdgeUpdate(edge);
      }
    }
    this._edgesDataSet.update(Object.values(edgeUpdates));
    const allNodes = this._nodesDataSet.get();
    const nodeUpdates = allNodes.map(node => {
      const isNeighbor = connectedNodeIds.has(node.id);
      const isSelected = node.id === nodeId;
      return {
        id: node.id,
        size: isSelected ? 40 : isNeighbor ? 35 : 25,
        font: {
          size: isSelected ? 14 : isNeighbor ? 13 : 11,
          color: this._getFontColor(),
          bold: isSelected || isNeighbor ? {
            color: this._getFontColor()
          } : void 0
        },
        opacity: isSelected || isNeighbor ? 1 : 0.5
      };
    });
    this._nodesDataSet.update(nodeUpdates);
    if (this._highlightedNodeId && this._highlightedNodeId !== nodeIdStr) {
      this._setNodeIconHighlight(this._highlightedNodeId, false);
    }
    this._highlightedNodeId = nodeIdStr;
    this._setNodeIconHighlight(nodeIdStr, true);
    this._isHighlighted = true;
  }
  /**
   * Thicken a connected edge and add a directional arrow when the pair is
   * truly one-way in data (only one of edgeAB/edgeBA exists). Used for the
   * highlighted-reports-peer branch where filter-hidden peer directions
   * should not draw an arrow on the user's own perspective.
   *
   * Explicit arrow object (vs the shorthand "to") keeps the head visible
   * on dashed offline edges where some vis.js builds skip the shorthand.
   */
  _asymmetricEdgeUpdate(edge) {
    const pair = edge.pairKey ? this._edgePairs.get(edge.pairKey) : void 0;
    const isAsymmetric = pair ? !pair.edgeAB || !pair.edgeBA : false;
    const update = {
      id: edge.id,
      width: 3
    };
    if (isAsymmetric) {
      update.arrows = {
        to: {
          enabled: true,
          scaleFactor: 1
        }
      };
    }
    return update;
  }
  /**
   * Thicken a connected edge and always add a directional arrow. Used for
   * the remote-reports-highlighted branch where the displayed edge is the
   * peer's direction (no swap target available); the user sees the same
   * single line whether the outgoing direction is filter-hidden or absent.
   */
  _reverseEdgeUpdate(edge) {
    return {
      id: edge.id,
      width: 3,
      arrows: {
        to: {
          enabled: true,
          scaleFactor: 1
        }
      }
    };
  }
  /**
   * Swap a node's icon between the default and highlighted variants.
   * Kept separate so both `_highlightConnections` (switching target) and
   * `_clearHighlights` (fully unselecting) reach the same end state.
   */
  _setNodeIconHighlight(nodeId, isHighlighted) {
    if (!this._nodesDataSet) return;
    const nodeData = this.nodes[nodeId];
    if (nodeData) {
      const threadRole = getThreadRole(nodeData);
      const isOffline = nodeData.available === false;
      this._nodesDataSet.update({
        id: nodeId,
        image: createNodeIconDataUrl(nodeData, threadRole, isHighlighted, isOffline)
      });
      return;
    }
    const external = this._unknownDevicesMapCache.get(nodeId);
    if (external?.kind === "br") {
      const decodedState = decodeMeshcopStateBitmap(external.stateBitmapHex);
      const isLeader = decodedState?.threadRoleValue === 3;
      const isPrimaryBbr = decodedState?.bbr === true && decodedState.bbrFunction === "primary";
      this._nodesDataSet.update({
        id: nodeId,
        image: createBorderRouterIconDataUrl(isHighlighted, isLeader, isPrimaryBbr)
      });
    } else if (nodeId.startsWith("unknown_") || nodeId.startsWith("br_")) {
      this._nodesDataSet.update({
        id: nodeId,
        image: createUnknownDeviceIconDataUrl(external?.isRouter ?? false, isHighlighted)
      });
    }
  }
  /**
   * Clears all highlights and restores the graph to its base state
   * (after filter+dedup, before highlight modifications).
   */
  _clearHighlights() {
    if (!this._edgesDataSet || !this._nodesDataSet) return;
    this._restoreEdgeBaseState();
    if (this._highlightedNodeId) {
      this._setNodeIconHighlight(this._highlightedNodeId, false);
      this._highlightedNodeId = null;
    }
    const allNodes = this._nodesDataSet.get();
    const nodeUpdates = allNodes.map(node => ({
      id: node.id,
      size: 30,
      font: {
        size: 12,
        color: this._getFontColor(),
        bold: void 0
      },
      opacity: 1
    }));
    this._nodesDataSet.update(nodeUpdates);
    this._isHighlighted = false;
  }
  /**
   * Restores all edges to their base state (undoes highlight modifications).
   * This resets hidden/visible state, width, color, and dashes.
   */
  _restoreEdgeBaseState() {
    if (!this._edgesDataSet) return;
    const edgeUpdates = [];
    for (const [id, baseState] of this._edgeBaseState) {
      edgeUpdates.push({
        id,
        hidden: baseState.hiddenReason !== "visible",
        width: baseState.width,
        color: {
          color: baseState.color.color,
          highlight: baseState.color.highlight
        },
        dashes: baseState.dashes,
        arrows: ""
      });
    }
    this._edgesDataSet.update(edgeUpdates);
  }
  render() {
    const threadNodes = Object.values(this.nodes).filter(node => getNetworkType(node) === "thread");
    const visibleThreadNodes = this.hideOfflineNodes ? threadNodes.filter(node => node.available !== false) : threadNodes;
    if (visibleThreadNodes.length === 0) {
      const allOfflineFiltered = threadNodes.length > 0 && this.hideOfflineNodes;
      return b`
                <div class="empty-state">
                    <p>${allOfflineFiltered ? "No online Thread devices" : "No Thread devices found"}</p>
                    <p class="hint">
                        ${allOfflineFiltered ? 'Disable the "Offline nodes" filter to show offline devices' : "Thread devices will appear here once commissioned"}
                    </p>
                </div>
            `;
    }
    return b` <div class="graph-container"></div> `;
  }
};
__decorateClass$6([n$5({
  attribute: false
})], ThreadGraph.prototype, "borderRouters", 2);
__decorateClass$6([n$5({
  type: Boolean
})], ThreadGraph.prototype, "hideOfflineNodes", 2);
__decorateClass$6([n$5({
  type: Boolean
})], ThreadGraph.prototype, "hideWeakSignalEdges", 2);
__decorateClass$6([n$5({
  type: Boolean
})], ThreadGraph.prototype, "hideMediumSignalEdges", 2);
__decorateClass$6([n$5({
  type: Boolean
})], ThreadGraph.prototype, "hideStrongSignalEdges", 2);
ThreadGraph = __decorateClass$6([t$1("thread-graph")], ThreadGraph);
function normalizeExtendedAddressInput(address) {
  const trimmed = address.trim();
  if (!trimmed) {
    return null;
  }
  const noPrefix = trimmed.startsWith("0x") || trimmed.startsWith("0X") ? trimmed.slice(2) : trimmed;
  const hexOnly = noPrefix.replace(/[^a-fA-F0-9]/g, "");
  if (hexOnly.length !== 16 || !/^[a-fA-F0-9]{16}$/.test(hexOnly)) {
    return null;
  }
  return hexOnly.toUpperCase();
}

var __getOwnPropDesc$5 = Object.getOwnPropertyDescriptor;
var __decorateClass$5 = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$5(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (decorator(result)) || result;
  return result;
};
let WiFiGraph = class extends BaseNetworkGraph {
  constructor() {
    super(...arguments);
    /** Cache of access points for the current render */
    this._accessPoints = /* @__PURE__ */new Map();
  }
  /** Get access points map for use by details panel */
  get wifiAccessPointsMap() {
    return this._accessPoints;
  }
  /**
   * Override physics for WiFi star topology - needs stronger cluster separation.
   */
  _getPhysicsOptions() {
    return {
      enabled: true,
      solver: "forceAtlas2Based",
      forceAtlas2Based: {
        gravitationalConstant: -120,
        // Stronger repulsion for star topology
        centralGravity: 3e-3,
        // Weaker central pull
        springLength: 100,
        // Shorter springs keep devices close to their AP
        springConstant: 0.12,
        // Stronger springs
        damping: 0.4,
        avoidOverlap: 0.8
      },
      stabilization: {
        enabled: true,
        iterations: 300,
        updateInterval: 25
      }
    };
  }
  _updateGraph() {
    if (!this._nodesDataSet || !this._edgesDataSet) return;
    this._clearOriginalEdgeColors();
    const categorized = categorizeDevices(this.nodes);
    const wifiNodeIds = categorized.wifi;
    if (wifiNodeIds.length === 0) {
      this._nodesDataSet.clear();
      this._edgesDataSet.clear();
      this._accessPoints.clear();
      return;
    }
    this._accessPoints.clear();
    for (const nodeId of wifiNodeIds) {
      const node = this.nodes[nodeId];
      if (!node) continue;
      const wifiDiag = getWiFiDiagnostics(node);
      if (wifiDiag.bssid) {
        const apId = `ap_${wifiDiag.bssid.replace(/:/g, "")}`;
        if (!this._accessPoints.has(apId)) {
          this._accessPoints.set(apId, {
            bssid: wifiDiag.bssid,
            connectedNodes: []
          });
        }
        this._accessPoints.get(apId).connectedNodes.push(nodeId);
      }
    }
    const graphNodes = [];
    const graphEdges = [];
    for (const [apId, ap] of this._accessPoints) {
      const bssid = ap.bssid;
      const isSelected = String(apId) === String(this._selectedNodeId);
      graphNodes.push({
        id: apId,
        label: `AP ${bssid}`,
        image: createWiFiRouterIconDataUrl(isSelected),
        shape: "image",
        networkType: "wifi",
        isUnknown: true
        // Mark as infrastructure
      });
    }
    let edgeIndex = 0;
    for (const nodeId of wifiNodeIds) {
      const node = this.nodes[nodeId];
      if (!node) continue;
      const isSelected = nodeId === String(this._selectedNodeId);
      const isOffline = node.available === false;
      const networkType = getNetworkType(node);
      const wifiDiag = getWiFiDiagnostics(node);
      graphNodes.push({
        id: nodeId,
        label: getDeviceName(node),
        image: createNodeIconDataUrl(node, void 0, isSelected, isOffline),
        shape: "image",
        networkType,
        offline: isOffline
      });
      if (wifiDiag.bssid) {
        const apId = `ap_${wifiDiag.bssid.replace(/:/g, "")}`;
        const signalColor = getSignalColorFromRssi(wifiDiag.rssi);
        graphEdges.push({
          id: `edge_${edgeIndex++}`,
          from: nodeId,
          to: apId,
          color: {
            color: signalColor,
            highlight: signalColor
          },
          width: 2,
          title: wifiDiag.rssi !== null ? `RSSI: ${wifiDiag.rssi} dBm` : "RSSI: Unknown",
          dashes: isOffline
          // Dashed lines for offline devices
        });
      }
    }
    const existingNodeIds = this._nodesDataSet.getIds();
    const newNodeIds = new Set(graphNodes.map(n => n.id));
    const nodesToRemove = existingNodeIds.filter(id => !newNodeIds.has(id));
    if (nodesToRemove.length > 0) {
      this._nodesDataSet.remove(nodesToRemove);
    }
    this._nodesDataSet.update(graphNodes);
    this._edgesDataSet.clear();
    this._edgesDataSet.add(graphEdges);
  }
  render() {
    const categorized = categorizeDevices(this.nodes);
    const wifiCount = categorized.wifi.length;
    if (wifiCount === 0) {
      return b`
                <div class="empty-state">
                    <p>No WiFi devices found</p>
                    <p class="hint">WiFi devices will appear here once commissioned</p>
                </div>
            `;
    }
    return b` <div class="graph-container"></div> `;
  }
};
WiFiGraph = __decorateClass$5([t$1("wifi-graph")], WiFiGraph);

var __defProp$4 = Object.defineProperty;
var __getOwnPropDesc$4 = Object.getOwnPropertyDescriptor;
var __decorateClass$4 = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$4(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp$4(target, key, result);
  return result;
};
const HIDE_OPTIONS = [{
  key: "_hideOfflineNodes",
  label: "Offline nodes"
}, {
  key: "_hideWeakSignalEdges",
  label: "Weak signal edges"
}, {
  key: "_hideMediumSignalEdges",
  label: "Medium signal edges"
}, {
  key: "_hideStrongSignalEdges",
  label: "Strong signal edges"
}];
let MatterNetworkView = class extends i$4 {
  constructor() {
    super(...arguments);
    this.nodes = {};
    this.networkType = "thread";
    this.initialSelectedNodeId = null;
    this._selectedNodeId = null;
    this._physicsEnabled = true;
    this._threadAddressSearch = "";
    this._threadAddressSearchStatus = "idle";
    this._borderRouterStore = new BorderRouterStore();
    this._showHideMenu = false;
    this._hideOfflineNodes = false;
    this._hideWeakSignalEdges = false;
    this._hideMediumSignalEdges = false;
    this._hideStrongSignalEdges = false;
    this._initialSelectionApplied = false;
    this._documentClickHandler = event => {
      const path = event.composedPath();
      if (!path.some(el => el instanceof HTMLElement && el.classList.contains("hide-menu-container"))) {
        this._showHideMenu = false;
      }
    };
    this._documentKeyHandler = event => {
      if (event.key === "Escape" && this._showHideMenu) {
        this._showHideMenu = false;
      }
    };
  }
  willUpdate(changedProperties) {
    if (changedProperties.has("initialSelectedNodeId") && this.initialSelectedNodeId !== null) {
      this._selectedNodeId = this.initialSelectedNodeId;
      this._initialSelectionApplied = false;
    }
  }
  async _refreshBorderRouters() {
    try {
      await this._borderRouterStore.refresh(this.client);
      this.requestUpdate();
    } catch (err) {
      console.warn("Failed to refresh border router store:", err);
    }
  }
  _handleConnectionsUpdated() {
    if (this.networkType !== "thread") return;
    void this._refreshBorderRouters();
  }
  updated(changedProperties) {
    super.updated(changedProperties);
    if (changedProperties.has("networkType") && this.networkType === "thread") {
      void this._refreshBorderRouters();
    }
    if (!this._initialSelectionApplied && this.initialSelectedNodeId !== null) {
      this._initialSelectionApplied = true;
      this._selectNodeWhenReady(this.initialSelectedNodeId);
    }
  }
  connectedCallback() {
    super.connectedCallback();
    document.addEventListener("click", this._documentClickHandler);
    document.addEventListener("keydown", this._documentKeyHandler);
  }
  disconnectedCallback() {
    super.disconnectedCallback();
    document.removeEventListener("click", this._documentClickHandler);
    document.removeEventListener("keydown", this._documentKeyHandler);
    if (this._selectRetryTimer) {
      clearTimeout(this._selectRetryTimer);
    }
  }
  /**
   * Tries to select a node in the graph, retrying until the graph is ready.
   */
  _selectNodeWhenReady(nodeId, retries = 10) {
    const graph = this.networkType === "thread" ? this._threadGraph : this._wifiGraph;
    if (graph?.isReady()) {
      graph.selectNode(nodeId);
    } else if (retries > 0) {
      this._selectRetryTimer = setTimeout(() => this._selectNodeWhenReady(nodeId, retries - 1), 100);
    }
  }
  _handleNodeSelected(event) {
    this._selectedNodeId = event.detail.nodeId;
  }
  _handleDetailsClose() {
    this._selectedNodeId = null;
    if (this.networkType === "thread") {
      this._threadGraph?.deselectAll();
    } else {
      this._wifiGraph?.deselectAll();
    }
  }
  _handleSelectNode(event) {
    const nodeId = event.detail.nodeId;
    this._selectedNodeId = nodeId;
    if (this.networkType === "thread") {
      this._threadGraph?.selectNode(nodeId);
    } else {
      this._wifiGraph?.selectNode(nodeId);
    }
  }
  _handleFitToScreen() {
    if (this.networkType === "thread") {
      this._threadGraph?.fit();
    } else {
      this._wifiGraph?.fit();
    }
  }
  _handleZoomIn() {
    if (this.networkType === "thread") {
      this._threadGraph?.zoomIn();
    } else {
      this._wifiGraph?.zoomIn();
    }
  }
  _handleZoomOut() {
    if (this.networkType === "thread") {
      this._threadGraph?.zoomOut();
    } else {
      this._wifiGraph?.zoomOut();
    }
  }
  _handleToggleHideMenu() {
    this._showHideMenu = !this._showHideMenu;
  }
  _handleToggleHideOption(option) {
    this[option] = !this[option];
  }
  _isAnyHideOptionActive() {
    return HIDE_OPTIONS.some(option => this[option.key]);
  }
  _handleTogglePhysics() {
    const newState = !this._physicsEnabled;
    this._physicsEnabled = newState;
    this._threadGraph?.setPhysicsEnabled(newState);
    this._wifiGraph?.setPhysicsEnabled(newState);
  }
  _handlePhysicsChanged(event) {
    this._physicsEnabled = event.detail.enabled;
    this._threadGraph?.setPhysicsEnabled(event.detail.enabled);
    this._wifiGraph?.setPhysicsEnabled(event.detail.enabled);
  }
  _handleThreadAddressSearchInput(event) {
    this._threadAddressSearch = event.target.value;
    this._threadAddressSearchStatus = "idle";
  }
  _handleThreadAddressSearchSubmit(event) {
    event.preventDefault();
    const searchValue = this._threadAddressSearch.trim();
    if (!searchValue) {
      this._threadAddressSearchStatus = "idle";
      return;
    }
    this._searchThreadAddressWhenReady(searchValue);
  }
  _searchThreadAddressWhenReady(searchValue, retries = 10) {
    const graph = this._threadGraph;
    if (!graph?.isReady()) {
      if (retries > 0) {
        this._selectRetryTimer = setTimeout(() => this._searchThreadAddressWhenReady(searchValue, retries - 1), 100);
      } else {
        this._threadAddressSearchStatus = "not-found";
      }
      return;
    }
    const found = graph.selectBySearch(searchValue);
    this._threadAddressSearchStatus = found ? "found" : "not-found";
  }
  _renderThreadView() {
    return b`
            <div class="graph-section">
                <div class="graph-header">
                    <h2>Thread Network Mesh</h2>
                    <div class="graph-actions">
                        <form class="thread-search" @submit=${this._handleThreadAddressSearchSubmit}>
                            <input
                                type="text"
                                .value=${this._threadAddressSearch}
                                @input=${this._handleThreadAddressSearchInput}
                                placeholder="Search label, node id, or address"
                                title="Find a Thread device by node label, node id, or extended address (EUI-64)"
                            />
                            <button type="submit" class="search-button">Find</button>
                        </form>
                        <div class="graph-controls">
                            <button class="control-button" @click=${this._handleZoomIn} title="Zoom in">
                                <ha-svg-icon .path=${mdiMagnifyPlus}></ha-svg-icon>
                            </button>
                            <button class="control-button" @click=${this._handleZoomOut} title="Zoom out">
                                <ha-svg-icon .path=${mdiMagnifyMinus}></ha-svg-icon>
                            </button>
                            <button class="control-button" @click=${this._handleFitToScreen} title="Fit to screen">
                                <ha-svg-icon .path=${mdiFitToScreen}></ha-svg-icon>
                            </button>
                            <div class="hide-menu-container">
                                <button
                                    class="control-button ${this._isAnyHideOptionActive() ? "active" : ""}"
                                    @click=${this._handleToggleHideMenu}
                                    title="Hide options"
                                    aria-haspopup="true"
                                    aria-expanded=${this._showHideMenu}
                                    aria-controls="hide-options-menu"
                                >
                                    <ha-svg-icon .path=${mdiEyeOff}></ha-svg-icon>
                                </button>
                                ${this._showHideMenu ? b`
                                          <div
                                              id="hide-options-menu"
                                              class="hide-dropdown"
                                              role="group"
                                              aria-label="Hide options"
                                          >
                                              ${HIDE_OPTIONS.map(option => b`
                                                      <label class="hide-option">
                                                          <input
                                                              type="checkbox"
                                                              .checked=${this[option.key]}
                                                              @change=${() => this._handleToggleHideOption(option.key)}
                                                          />
                                                          <span>${option.label}</span>
                                                      </label>
                                                  `)}
                                          </div>
                                      ` : ""}
                            </div>
                            <button
                                class="control-button ${this._physicsEnabled ? "" : "active"}"
                                @click=${this._handleTogglePhysics}
                                title="${this._physicsEnabled ? "Freeze layout" : "Unfreeze layout"}"
                            >
                                <ha-svg-icon .path=${this._physicsEnabled ? mdiPause : mdiPlay}></ha-svg-icon>
                            </button>
                        </div>
                    </div>
                </div>
                ${this._threadAddressSearchStatus === "idle" ? "" : b`<div class="thread-search-status ${this._threadAddressSearchStatus}">
                          ${this._threadAddressSearchStatus === "found" ? "Node highlighted." : "No matching device found."}
                      </div>`}
                <thread-graph
                    .nodes=${this.nodes}
                    .borderRouters=${this._borderRouterStore.entries}
                    .hideOfflineNodes=${this._hideOfflineNodes}
                    .hideWeakSignalEdges=${this._hideWeakSignalEdges}
                    .hideMediumSignalEdges=${this._hideMediumSignalEdges}
                    .hideStrongSignalEdges=${this._hideStrongSignalEdges}
                    @node-selected=${this._handleNodeSelected}
                    @physics-changed=${this._handlePhysicsChanged}
                ></thread-graph>
            </div>
        `;
  }
  _renderWifiView() {
    return b`
            <div class="graph-section">
                <div class="graph-header">
                    <h2>WiFi Network</h2>
                    <div class="graph-controls">
                        <button class="control-button" @click=${this._handleZoomIn} title="Zoom in">
                            <ha-svg-icon .path=${mdiMagnifyPlus}></ha-svg-icon>
                        </button>
                        <button class="control-button" @click=${this._handleZoomOut} title="Zoom out">
                            <ha-svg-icon .path=${mdiMagnifyMinus}></ha-svg-icon>
                        </button>
                        <button class="control-button" @click=${this._handleFitToScreen} title="Fit to screen">
                            <ha-svg-icon .path=${mdiFitToScreen}></ha-svg-icon>
                        </button>
                        <button
                            class="control-button ${this._physicsEnabled ? "" : "active"}"
                            @click=${this._handleTogglePhysics}
                            title="${this._physicsEnabled ? "Freeze layout" : "Unfreeze layout"}"
                        >
                            <ha-svg-icon .path=${this._physicsEnabled ? mdiPause : mdiPlay}></ha-svg-icon>
                        </button>
                    </div>
                </div>
                <wifi-graph
                    .nodes=${this.nodes}
                    @node-selected=${this._handleNodeSelected}
                    @physics-changed=${this._handlePhysicsChanged}
                ></wifi-graph>
            </div>
        `;
  }
  render() {
    const showSidebar = this._selectedNodeId !== null;
    const unknownDevices = this._threadGraph?.unknownDevicesMap ?? /* @__PURE__ */new Map();
    const wifiAccessPoints = this._wifiGraph?.wifiAccessPointsMap ?? /* @__PURE__ */new Map();
    const threadEdgePairs = this._threadGraph?.edgePairs ?? /* @__PURE__ */new Map();
    return b`
            <dashboard-header
                title="Open Home Foundation Matter Server"
                .activeView=${this.activeView}
                .hasThreadDevices=${this.hasThreadDevices}
                .hasWifiDevices=${this.hasWifiDevices}
            ></dashboard-header>

            <div class="content">
                <div class="main-area">
                    ${this.networkType === "thread" ? this._renderThreadView() : this._renderWifiView()}
                </div>

                <aside class="details-sidebar ${showSidebar ? "visible" : ""}">
                    <network-details
                        .selectedNodeId=${this._selectedNodeId}
                        .nodes=${this.nodes}
                        .unknownDevices=${unknownDevices}
                        .borderRouters=${this._borderRouterStore.entries}
                        .wifiAccessPoints=${wifiAccessPoints}
                        .threadEdgePairs=${threadEdgePairs}
                        .hideOfflineNodes=${this._hideOfflineNodes}
                        .hideWeakSignalEdges=${this._hideWeakSignalEdges}
                        .hideMediumSignalEdges=${this._hideMediumSignalEdges}
                        .hideStrongSignalEdges=${this._hideStrongSignalEdges}
                        @close=${this._handleDetailsClose}
                        @select-node=${this._handleSelectNode}
                        @connections-updated=${this._handleConnectionsUpdated}
                    ></network-details>
                </aside>
            </div>

            <dashboard-footer></dashboard-footer>
        `;
  }
};
MatterNetworkView.styles = [reducedMotionStyles, i$7`
            :host {
                display: flex;
                flex-direction: column;
                height: 100vh;
                height: 100dvh; /* dynamic viewport height - fallback above for older browsers */
                overflow: hidden;
                background-color: var(--md-sys-color-background, #fafafa);
            }

            .content {
                display: flex;
                flex: 1 1 0;
                padding: 8px 16px;
                gap: 8px;
                width: 100%;
                box-sizing: border-box;
                min-height: 0;
                overflow: hidden;
            }

            .main-area {
                flex: 1 1 0;
                display: flex;
                flex-direction: column;
                min-width: 0;
                min-height: 0;
                overflow: hidden;
            }

            .graph-section {
                flex: 1 1 0;
                min-height: 0;
                display: flex;
                flex-direction: column;
                overflow: hidden;
            }

            .graph-header {
                display: flex;
                align-items: center;
                justify-content: space-between;
                margin-bottom: 4px;
                flex-shrink: 0;
            }

            .graph-header h2 {
                margin: 0;
                font-size: 1.1rem;
                font-weight: 500;
                color: var(--md-sys-color-on-background, #333);
            }

            .graph-controls {
                display: flex;
                gap: 4px;
            }

            .graph-actions {
                display: flex;
                align-items: center;
                gap: 8px;
                min-width: 0;
            }

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

            .thread-search input {
                width: 260px;
                max-width: 45vw;
                padding: 6px 8px;
                border: 1px solid var(--md-sys-color-outline-variant, #ccc);
                border-radius: 4px;
                background-color: var(--md-sys-color-surface, #fff);
                color: var(--md-sys-color-on-surface, #1c1b1f);
                font: inherit;
            }

            .thread-search input:focus {
                outline: 2px solid var(--md-sys-color-primary, #6750a4);
                outline-offset: 1px;
            }

            .search-button {
                padding: 6px 10px;
                border: 1px solid var(--md-sys-color-outline-variant, #ccc);
                border-radius: 4px;
                background-color: var(--md-sys-color-surface, #fff);
                color: var(--md-sys-color-on-surface, #1c1b1f);
                cursor: pointer;
                font: inherit;
            }

            .search-button:hover {
                background-color: var(--md-sys-color-surface-container-high, #e8e8e8);
            }

            .search-button:focus-visible {
                outline: 2px solid var(--md-sys-color-primary);
                outline-offset: 1px;
            }

            .thread-search-status {
                margin: 0 0 6px;
                font-size: 0.85rem;
                color: var(--md-sys-color-on-surface-variant, #666);
            }

            .thread-search-status.found {
                color: var(--signal-color-strong);
            }

            .thread-search-status.not-found {
                color: var(--md-sys-color-error);
            }

            .control-button {
                background: none;
                border: 1px solid var(--md-sys-color-outline-variant, #ccc);
                border-radius: 4px;
                padding: 6px;
                cursor: pointer;
                display: flex;
                align-items: center;
                justify-content: center;
                transition:
                    background-color 0.2s,
                    border-color 0.2s;
            }

            .control-button:hover {
                background-color: var(--md-sys-color-surface-container-high, #e8e8e8);
            }

            .control-button.active {
                background-color: var(--md-sys-color-primary-container, #e8def8);
                border-color: var(--md-sys-color-primary, #6750a4);
            }

            .control-button ha-svg-icon {
                --icon-primary-color: var(--md-sys-color-on-surface-variant, #666);
            }

            .control-button.active ha-svg-icon {
                --icon-primary-color: var(--md-sys-color-on-primary-container, #21005d);
            }

            .hide-menu-container {
                position: relative;
            }

            .hide-dropdown {
                position: absolute;
                top: calc(100% + 4px);
                right: 0;
                background: var(--md-sys-color-surface-container, #fff);
                border: 1px solid var(--md-sys-color-outline-variant, #ccc);
                border-radius: 4px;
                box-shadow: var(--md-sys-elevation-level2, 0 2px 6px var(--md-sys-color-shadow, rgba(0, 0, 0, 0.15)));
                min-width: 150px;
                z-index: 100;
                padding: 4px 0;
            }

            .hide-option {
                display: flex;
                align-items: center;
                gap: 8px;
                padding: 8px 12px;
                cursor: pointer;
                color: var(--md-sys-color-on-surface, #1c1b1f);
                font-size: 0.9rem;
                user-select: none;
            }

            .hide-option:hover {
                background-color: var(--md-sys-color-surface-container-high, #e8e8e8);
            }

            .hide-option input[type="checkbox"] {
                cursor: pointer;
                margin: 0;
            }

            .hide-option span {
                flex: 1;
            }

            .graph-section thread-graph,
            .graph-section wifi-graph {
                flex: 1 1 0;
                min-height: 0;
            }

            .wifi-section {
                display: flex;
                flex-direction: column;
                gap: 16px;
                overflow-y: auto;
            }

            .wifi-section h2 {
                margin: 0;
                font-size: 1.25rem;
                font-weight: 500;
                color: var(--md-sys-color-on-background, #333);
            }

            .wifi-section device-panel {
                flex-shrink: 0;
            }

            .details-sidebar {
                width: clamp(320px, 22vw, 480px);
                flex-shrink: 0;
                display: none;
                min-height: 0;
                overflow-y: auto;
            }

            .details-sidebar.visible {
                display: block;
            }

            @media (max-width: 1024px) {
                .content {
                    flex-direction: column;
                }

                .details-sidebar {
                    width: 100%;
                    max-height: 300px;
                }

                .details-sidebar.visible {
                    display: block;
                }
            }

            @media (max-width: 600px) {
                .content {
                    padding: 8px;
                }

                .graph-header {
                    align-items: flex-start;
                    gap: 6px;
                }

                .graph-actions {
                    flex-direction: column;
                    align-items: stretch;
                    width: 100%;
                }

                .thread-search {
                    width: 100%;
                }

                .thread-search input {
                    flex: 1 1 auto;
                    width: auto;
                    max-width: none;
                }

                .graph-controls {
                    justify-content: flex-end;
                }
            }
        `];
__decorateClass$4([c$5({
  context: clientContext
})], MatterNetworkView.prototype, "client", 2);
__decorateClass$4([n$5({
  type: Object
})], MatterNetworkView.prototype, "nodes", 2);
__decorateClass$4([n$5()], MatterNetworkView.prototype, "activeView", 2);
__decorateClass$4([n$5()], MatterNetworkView.prototype, "networkType", 2);
__decorateClass$4([n$5()], MatterNetworkView.prototype, "initialSelectedNodeId", 2);
__decorateClass$4([n$5({
  type: Boolean
})], MatterNetworkView.prototype, "hasThreadDevices", 2);
__decorateClass$4([n$5({
  type: Boolean
})], MatterNetworkView.prototype, "hasWifiDevices", 2);
__decorateClass$4([r$3()], MatterNetworkView.prototype, "_selectedNodeId", 2);
__decorateClass$4([r$3()], MatterNetworkView.prototype, "_physicsEnabled", 2);
__decorateClass$4([r$3()], MatterNetworkView.prototype, "_threadAddressSearch", 2);
__decorateClass$4([r$3()], MatterNetworkView.prototype, "_threadAddressSearchStatus", 2);
__decorateClass$4([r$3()], MatterNetworkView.prototype, "_borderRouterStore", 2);
__decorateClass$4([r$3()], MatterNetworkView.prototype, "_showHideMenu", 2);
__decorateClass$4([r$3()], MatterNetworkView.prototype, "_hideOfflineNodes", 2);
__decorateClass$4([r$3()], MatterNetworkView.prototype, "_hideWeakSignalEdges", 2);
__decorateClass$4([r$3()], MatterNetworkView.prototype, "_hideMediumSignalEdges", 2);
__decorateClass$4([r$3()], MatterNetworkView.prototype, "_hideStrongSignalEdges", 2);
__decorateClass$4([e$6("thread-graph")], MatterNetworkView.prototype, "_threadGraph", 2);
__decorateClass$4([e$6("wifi-graph")], MatterNetworkView.prototype, "_wifiGraph", 2);
MatterNetworkView = __decorateClass$4([t$1("matter-network-view")], MatterNetworkView);

var __defProp$3 = Object.defineProperty;
var __getOwnPropDesc$3 = Object.getOwnPropertyDescriptor;
var __decorateClass$3 = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$3(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp$3(target, key, result);
  return result;
};
function getUniqueEndpoints(node) {
  return Array.from(new Set(Object.keys(node.attributes).map(key => Number(key.split("/")[0])))).sort((a, b) => {
    return a - b;
  });
}
let MatterNodeView = class extends i$4 {
  constructor() {
    super(...arguments);
    this._tick = 0;
  }
  render() {
    if (!this.node) {
      return b`
                <dashboard-header title="Node not found" backButton="#"></dashboard-header>
                <div class="not-found">
                    <ha-svg-icon .path=${mdiAlertCircleOutline}></ha-svg-icon>
                    <p>Node not found</p>
                    <md-outlined-button @click=${this._goBack}>Back</md-outlined-button>
                </div>
            `;
    }
    const networkType = getNetworkType(this.node);
    const showGraphButton = networkType === "thread" || networkType === "wifi" || networkType === "ethernet";
    const graphViewType = networkType === "ethernet" ? "wifi" : networkType;
    const graphUrl = showGraphButton ? `#${graphViewType}/${this.node.node_id}` : null;
    const fabricIndex = getEffectiveFabricIndex(this.client.serverInfo.fabric_index, isTestNodeId(this.node.node_id));
    const nodeHex = formatNodeAddress(fabricIndex, this.node.node_id);
    return b`
            <dashboard-header .title=${`Node ${this.node.node_id} ${nodeHex}`} backButton="#"></dashboard-header>

            <!-- node details section -->
            <div class="container">
                <div class="node-title-bar">
                    <ha-svg-icon class="node-icon" .path=${getDeviceIcon(this.node)}></ha-svg-icon>
                    <h2>Node ${this.node.node_id} <span class="node-id-hex">${nodeHex}</span></h2>
                    ${showGraphButton ? b`
                              <a href=${graphUrl} class="show-in-graph-button" title="Show in ${graphViewType} graph">
                                  <ha-svg-icon .path=${mdiGraphOutline}></ha-svg-icon>
                                  <span class="button-text">Show in graph</span>
                              </a>
                          ` : ""}
                </div>
                <node-details .node=${this.node}></node-details>
            </div>

            <!-- Node Endpoints listing -->
            <div class="container">
                <md-list>
                    <md-list-item>
                        <div slot="headline">
                            <b>Endpoints</b>
                        </div>
                    </md-list-item>
                    ${i([this.node, this.node?.attributes], () => getUniqueEndpoints(this.node).map(endPointId => {
      return b`
                                <md-list-item type="link" href=${`#node/${this.node.node_id}/${endPointId}`}>
                                    <ha-svg-icon
                                        slot="start"
                                        class="endpoint-icon"
                                        .path=${getEndpointIcon(this.node, endPointId)}
                                    ></ha-svg-icon>
                                    <div slot="headline">Endpoint ${endPointId}</div>
                                    <div slot="supporting-text">
                                        Device Type(s):
                                        ${getEndpointDeviceTypes(this.node, endPointId).map(deviceType => {
        return deviceType.label;
      }).join(" / ")}
                                    </div>
                                    <ha-svg-icon slot="end" .path=${mdiChevronRight}></ha-svg-icon>
                                </md-list-item>
                            `;
    }))}
                </md-list>
            </div>

            <dashboard-footer />
        `;
  }
  _goBack() {
    history.back();
  }
};
MatterNodeView.styles = [notFoundStyles, reducedMotionStyles, i$7`
            :host {
                display: flex;
                background-color: var(--md-sys-color-background);
                box-sizing: border-box;
                flex-direction: column;
                min-height: 100vh;
            }

            .container {
                padding: 16px;
                max-width: 95%;
                margin: 0 auto;
                width: 100%;
            }

            @media (max-width: 600px) {
                .container {
                    padding: 16px 0;
                }
            }

            .status {
                color: var(--danger-color);
                font-weight: bold;
                font-size: 0.8em;
            }

            .node-title-bar {
                display: flex;
                align-items: center;
                gap: 16px;
                margin-bottom: 16px;
            }

            .node-icon {
                --icon-primary-color: var(--md-sys-color-on-surface-variant, #666);
                --mdc-icon-size: 28px;
            }

            .endpoint-icon {
                --icon-primary-color: var(--md-sys-color-on-surface-variant, #666);
            }

            .node-title-bar h2 {
                margin: 0;
                font-size: 1.25rem;
                font-weight: 500;
                color: var(--md-sys-color-on-background, #333);
            }

            .node-id-hex {
                font-size: 0.75em;
                font-weight: 400;
                color: var(--md-sys-color-on-surface-variant, #666);
                font-family: var(--monospace-font, monospace);
            }

            .show-in-graph-button {
                display: inline-flex;
                align-items: center;
                gap: 6px;
                padding: 6px 12px;
                background-color: var(--md-sys-color-primary);
                color: var(--md-sys-color-on-primary);
                text-decoration: none;
                border-radius: 4px;
                font-size: 0.8rem;
                font-weight: 500;
                transition: opacity 0.2s;
                white-space: nowrap;
            }

            .show-in-graph-button:hover {
                opacity: 0.9;
            }

            .show-in-graph-button ha-svg-icon {
                --icon-primary-color: var(--md-sys-color-on-primary);
                width: 16px;
                height: 16px;
            }

            @media (max-width: 768px) {
                .show-in-graph-button {
                    display: none;
                }
            }

            @media (max-width: 480px) {
                .show-in-graph-button .button-text {
                    display: none;
                }

                .show-in-graph-button {
                    padding: 6px;
                }
            }
        `];
__decorateClass$3([c$5({
  context: clientContext
})], MatterNodeView.prototype, "client", 2);
__decorateClass$3([c$5({
  context: tickContext,
  subscribe: true
})], MatterNodeView.prototype, "_tick", 2);
__decorateClass$3([n$5()], MatterNodeView.prototype, "node", 2);
MatterNodeView = __decorateClass$3([t$1("matter-node-view")], MatterNodeView);

/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
const showCommissionNodeDialog = async () => {
  await import('./commission-node-dialog-cRMHM9mB.js');
  const dialog = document.createElement("commission-node-dialog");
  document.querySelector("matter-dashboard-app")?.renderRoot.appendChild(dialog);
};

var __defProp$2 = Object.defineProperty;
var __getOwnPropDesc$2 = Object.getOwnPropertyDescriptor;
var __decorateClass$2 = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$2(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp$2(target, key, result);
  return result;
};
let ServerDetails = class extends i$4 {
  constructor() {
    super(...arguments);
    this._tick = 0;
    this._onFileInput = event => {
      const fileElem = event.target;
      if (fileElem.files.length > 0) {
        const selectedFile = fileElem.files[0];
        const reader = new FileReader();
        reader.readAsText(selectedFile, "UTF-8");
        reader.onload = async () => {
          try {
            await this.client?.importTestNode(reader.result?.toString() ?? "");
          } catch (err) {
            showAlertDialog({
              title: "Failed to import test node",
              text: err.message
            });
          } finally {
            fileElem.value = "";
          }
        };
      }
      event.preventDefault();
    };
  }
  render() {
    if (!this.client) return b``;
    return b`
      <md-list>
        <md-list-item>
            <div slot="headline">
                <b>Open Home Foundation Matter Server ${this.client.isProduction ? "" : `(${this.client.serverBaseAddress})`}</b>
                ${this.client.connection.connected ? A : b` <span class="status">OFFLINE</span> `}
      </div>
        </md-list-item>
        <md-list-item>
          <div slot="supporting-text">
            <div class="left">Matter Server Version: </div>${this.client.serverInfo.sdk_version}
          </div>
          <div slot="supporting-text">
            <div class="left">FabricId: </div>${this.client.serverInfo.fabric_id}
          </div>
          <div slot="supporting-text">
            <div class="left">Compressed FabricId: </div>${this.client.serverInfo.compressed_fabric_id}
          </div>
          <div slot="supporting-text">
            <div class="left">Schema Version: </div>${this.client.serverInfo.schema_version}
          </div>
          <div slot="supporting-text">
            <div class="left">Node count: </div>${Object.keys(this.client.nodes).length}
          </div>
        </md-list-item>
        <md-list-item>
          <div class="btn-row">
            <md-outlined-button @click=${this._commissionNode}>Commission node<ha-svg-icon slot="icon" .path=${mdiPlus}></ha-svg-icon></md-outlined-button>
            <md-outlined-button @click=${handleAsync(() => this._uploadDiagnosticsDumpFile())}>Import node<ha-svg-icon slot="icon" .path=${mdiFile}></ha-svg-icon></md-outlined-button>
          </div>
        </md-list-item>
      </md-list>
      <!-- hidden file element for the upload diagnostics -->
      <input
        @change=${this._onFileInput}
        type="file"
        id="fileElem"
        accept=".json"
        style="display:none" />
      </div>
  `;
  }
  _commissionNode() {
    showCommissionNodeDialog();
  }
  async _uploadDiagnosticsDumpFile() {
    if (!(await showPromptDialog({
      title: "Add test node",
      text: "Do you want to add a test node from a diagnostics dump ?",
      confirmText: "Select file"
    }))) {
      return;
    }
    const fileElem = this.shadowRoot.getElementById("fileElem");
    fileElem.click();
  }
};
ServerDetails.styles = i$7`
        .btn-row {
            --md-outlined-button-container-shape: 0px;
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
        }

        .btn-row md-outlined-button {
            max-width: 100%;
        }

        .left {
            min-width: 120px;
            display: inline-block;
        }

        @media (min-width: 600px) {
            .left {
                min-width: 160px;
            }
        }

        .whitespace {
            height: 15px;
        }

        .status {
            color: var(--danger-color);
            font-weight: bold;
            font-size: 0.8em;
        }
    `;
__decorateClass$2([c$5({
  context: clientContext
})], ServerDetails.prototype, "client", 2);
__decorateClass$2([c$5({
  context: tickContext,
  subscribe: true
})], ServerDetails.prototype, "_tick", 2);
ServerDetails = __decorateClass$2([t$1("server-details")], ServerDetails);

var __defProp$1 = Object.defineProperty;
var __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor;
var __decorateClass$1 = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$1(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp$1(target, key, result);
  return result;
};
let MatterServerView = class extends i$4 {
  constructor() {
    super(...arguments);
    this._tick = 0;
  }
  getNodeEntries(nodes) {
    if (nodes !== this._cachedNodes) {
      this._cachedNodes = nodes;
      this._cachedNodeEntries = Object.entries(nodes);
    }
    return this._cachedNodeEntries;
  }
  render() {
    const nodes = this.getNodeEntries(this.nodes);
    return b`
            <dashboard-header
                title="Open Home Foundation Matter Server"
                .activeView=${this.activeView}
                .hasThreadDevices=${this.hasThreadDevices}
                .hasWifiDevices=${this.hasWifiDevices}
            ></dashboard-header>

            <!-- server details section -->
            <div class="container">
                <server-details></server-details>
            </div>

            <!-- Nodes listing -->
            <div class="container">
                <md-list>
                    <md-list-item>
                        <div slot="headline">
                            <b>Nodes</b>
                        </div>
                    </md-list-item>
                    ${nodes.map(([_id, node]) => {
      return b`
                            <md-list-item type="link" href=${`#node/${node.node_id}`}>
                                <ha-svg-icon
                                    slot="start"
                                    class="device-icon"
                                    .path=${getDeviceIcon(node)}
                                ></ha-svg-icon>
                                <div slot="headline">
                                    Node ${node.node_id}
                                    <span class="hex-id"
                                        >(${formatNodeAddress(isTestNodeId(node.node_id) || this.client.serverInfo.fabric_index === void 0 ? void 0 : this.client.serverInfo.fabric_index, node.node_id)})</span
                                    >
                                    ${node.available ? "" : b` <span class="status">OFFLINE</span> `}
                                </div>
                                <div slot="supporting-text">
                                    ${node.nodeLabel ? `${node.nodeLabel} | ` : A} ${node.vendorName} |
                                    ${node.productName}
                                </div>
                                <ha-svg-icon slot="end" .path=${mdiChevronRight}></ha-svg-icon>
                            </md-list-item>
                        `;
    })}
                </md-list>
            </div>
            <dashboard-footer />
        `;
  }
};
MatterServerView.styles = i$7`
        :host {
            display: flex;
            background-color: var(--md-sys-color-background);
            box-sizing: border-box;
            flex-direction: column;
        }

        .container {
            padding: 16px;
            max-width: 95%;
            margin: 0 auto;
            flex: 1;
            width: 100%;
        }

        @media (max-width: 600px) {
            .container {
                padding: 16px 0;
            }
        }

        .device-icon {
            --icon-primary-color: var(--md-sys-color-on-surface-variant, #666);
        }

        span[slot="start"] {
            width: 40px;
            text-align: center;
        }

        .status {
            color: var(--danger-color);
            font-weight: bold;
            font-size: 0.8em;
            margin-left: 8px;
        }

        .hex-id {
            color: var(--text-color, rgba(0, 0, 0, 0.6));
            font-size: 0.85em;
            word-break: break-all;
        }

        @media (max-width: 400px) {
            .hex-id {
                display: block;
                margin-top: 2px;
            }
        }
    `;
__decorateClass$1([c$5({
  context: clientContext
})], MatterServerView.prototype, "client", 2);
__decorateClass$1([c$5({
  context: tickContext,
  subscribe: true
})], MatterServerView.prototype, "_tick", 2);
__decorateClass$1([n$5()], MatterServerView.prototype, "nodes", 2);
__decorateClass$1([n$5()], MatterServerView.prototype, "activeView", 2);
__decorateClass$1([n$5({
  type: Boolean
})], MatterServerView.prototype, "hasThreadDevices", 2);
__decorateClass$1([n$5({
  type: Boolean
})], MatterServerView.prototype, "hasWifiDevices", 2);
MatterServerView = __decorateClass$1([t$1("matter-server-view")], MatterServerView);

var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __decorateClass = (decorators, target, key, kind) => {
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
  if (kind && result) __defProp(target, key, result);
  return result;
};
let MatterDashboardApp = class extends i$4 {
  constructor() {
    super(...arguments);
    this._route = {
      prefix: "",
      path: []
    };
    this._activeView = "nodes";
    this._initialSelectedNodeId = null;
    this._state = "connecting";
    this._tick = 0;
    /** Track whether nodes have been loaded at least once (to avoid redirecting before data arrives) */
    this._nodesLoaded = false;
    this.clientProvider = new i$8(this, {
      context: clientContext
    });
    this.tickProvider = new i$8(this, {
      context: tickContext,
      initialValue: 0
    });
    this._reconnect = () => {
      this._state = "connecting";
      this._connect();
    };
  }
  firstUpdated(_changedProperties) {
    super.firstUpdated(_changedProperties);
    this._connect();
    this._updateRoute = () => {
      const hash = location.hash.substring(1);
      const pathParts = hash.split("/");
      this._initialSelectedNodeId = null;
      const {
        hasThreadDevices,
        hasWifiDevices
      } = this._getDeviceCounts();
      if (pathParts[0] === "thread") {
        if (this._nodesLoaded && !hasThreadDevices) {
          location.hash = "#nodes";
          return;
        }
        this._activeView = "thread";
        if (pathParts.length > 1 && pathParts[1]) {
          this._initialSelectedNodeId = pathParts[1];
        }
      } else if (pathParts[0] === "wifi") {
        if (this._nodesLoaded && !hasWifiDevices) {
          location.hash = "#nodes";
          return;
        }
        this._activeView = "wifi";
        if (pathParts.length > 1 && pathParts[1]) {
          this._initialSelectedNodeId = pathParts[1];
        }
      } else if (hash === "nodes" || hash === "" || pathParts[0] === "node") {
        this._activeView = "nodes";
      }
      this._route = {
        prefix: pathParts.length == 1 ? "" : pathParts[0],
        path: pathParts.length == 1 ? pathParts : pathParts.slice(1)
      };
    };
    window.addEventListener("hashchange", this._updateRoute);
    this._updateRoute();
  }
  _connect() {
    this.client.startListening().then(() => {
      this.clientProvider.setValue(this.client);
      this.tickProvider.setValue(++this._tick);
      this._state = "connected";
      this._setupEventListeners();
    }, _err => {
      this._state = "error";
    });
  }
  _setupEventListeners() {
    this.client.addEventListener("nodes_changed", () => {
      const wasFirstLoad = !this._nodesLoaded;
      this._nodesLoaded = true;
      if (wasFirstLoad && this._updateRoute) {
        this._updateRoute();
      }
      this.requestUpdate();
      this.tickProvider.setValue(++this._tick);
    });
    this.client.addEventListener("server_info_updated", () => {
      this.tickProvider.setValue(++this._tick);
    });
    this.client.addEventListener("connection_lost", () => {
      this._state = "disconnected";
    });
  }
  /**
   * Get device counts for Thread and WiFi networks.
   */
  _getDeviceCounts() {
    if (!this.client?.nodes) {
      return {
        hasThreadDevices: false,
        hasWifiDevices: false
      };
    }
    const categorized = categorizeDevices(this.client.nodes);
    return {
      hasThreadDevices: categorized.thread.length > 0,
      hasWifiDevices: categorized.wifi.length > 0 || categorized.ethernet.length > 0
    };
  }
  render() {
    if (this._state === "connecting") {
      return b`
                <dashboard-header title="Matter Server"></dashboard-header>
                <div class="status-page">
                    <p class="status-message">Connecting...</p>
                </div>
            `;
    }
    if (this._state === "disconnected") {
      return b`
                <dashboard-header title="Matter Server"></dashboard-header>
                <div class="status-page">
                    <p class="status-message error">Connection lost</p>
                    <p class="status-hint">
                        The connection to the Matter Server was lost. Please check if the server is running.
                    </p>
                    <button class="retry-button" @click=${this._reconnect}>
                        <ha-svg-icon .path=${mdiRefresh}></ha-svg-icon>
                        Reconnect
                    </button>
                </div>
            `;
    }
    if (this._state === "error") {
      return b`
                <dashboard-header title="Matter Server"></dashboard-header>
                <div class="status-page">
                    <p class="status-message error">No connection</p>
                    <p class="status-hint">
                        Unable to connect to the Matter Server. Please check if the server is running.
                    </p>
                    <button class="retry-button" @click=${this._reconnect}>
                        <ha-svg-icon .path=${mdiRefresh}></ha-svg-icon>
                        Reconnect
                    </button>
                </div>
            `;
    }
    if (this._route.prefix === "node" && this._route.path.length == 3) {
      return b`
                <matter-cluster-view
                    .node=${this.client.nodes[this._route.path[0]]}
                    .endpoint=${parseInt(this._route.path[1], 10)}
                    .cluster=${parseInt(this._route.path[2], 10)}
                ></matter-cluster-view>
            `;
    }
    if (this._route.prefix === "node" && this._route.path.length == 2) {
      return b`
                <matter-endpoint-view
                    .node=${this.client.nodes[this._route.path[0]]}
                    .endpoint=${parseInt(this._route.path[1], 10)}
                ></matter-endpoint-view>
            `;
    }
    if (this._route.prefix === "node") {
      return b` <matter-node-view .node=${this.client.nodes[this._route.path[0]]}></matter-node-view> `;
    }
    const {
      hasThreadDevices,
      hasWifiDevices
    } = this._getDeviceCounts();
    if (this._route.prefix === "thread" || this._route.path[0] === "thread") {
      return b`<matter-network-view
                .nodes=${this.client.nodes}
                .activeView=${this._activeView}
                .initialSelectedNodeId=${this._initialSelectedNodeId}
                .hasThreadDevices=${hasThreadDevices}
                .hasWifiDevices=${hasWifiDevices}
                networkType="thread"
            ></matter-network-view>`;
    }
    if (this._route.prefix === "wifi" || this._route.path[0] === "wifi") {
      return b`<matter-network-view
                .nodes=${this.client.nodes}
                .activeView=${this._activeView}
                .initialSelectedNodeId=${this._initialSelectedNodeId}
                .hasThreadDevices=${hasThreadDevices}
                .hasWifiDevices=${hasWifiDevices}
                networkType="wifi"
            ></matter-network-view>`;
    }
    return b`<matter-server-view
            .nodes=${this.client.nodes}
            .route=${this._route}
            .activeView=${this._activeView}
            .hasThreadDevices=${hasThreadDevices}
            .hasWifiDevices=${hasWifiDevices}
        ></matter-server-view>`;
  }
};
MatterDashboardApp.styles = i$7`
        :host {
            display: block;
            min-height: 100vh;
            background-color: var(--md-sys-color-background);
        }

        .status-page {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 48px 24px;
            text-align: center;
        }

        .status-message {
            font-size: 1.5rem;
            color: var(--md-sys-color-on-background);
            margin: 0 0 16px 0;
        }

        .status-message.error {
            color: var(--danger-color);
        }

        .status-hint {
            font-size: 1rem;
            color: var(--md-sys-color-on-surface-variant);
            margin: 0;
            max-width: 400px;
        }

        .retry-button {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            margin-top: 24px;
            padding: 12px 24px;
            font-size: 1rem;
            background-color: var(--md-sys-color-primary);
            color: var(--md-sys-color-on-primary);
            --icon-primary-color: var(--md-sys-color-on-primary);
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .retry-button:hover {
            opacity: 0.9;
        }

        .retry-button ha-svg-icon {
            width: 20px;
            height: 20px;
        }
    `;
__decorateClass([r$3()], MatterDashboardApp.prototype, "_route", 2);
__decorateClass([r$3()], MatterDashboardApp.prototype, "_activeView", 2);
__decorateClass([r$3()], MatterDashboardApp.prototype, "_initialSelectedNodeId", 2);
__decorateClass([r$3()], MatterDashboardApp.prototype, "_state", 2);
__decorateClass([r$3()], MatterDashboardApp.prototype, "_tick", 2);
MatterDashboardApp = __decorateClass([t$1("matter-dashboard-app")], MatterDashboardApp);

var matterDashboardApp = /*#__PURE__*/Object.freeze({
  __proto__: null
});

export { A, mdiClose as B, getDeviceName as C, DevModeService as D, targetAclCapacityForBinding as E, addBinding as F, bindableClusters as G, getEndpointDeviceTypes as H, mixinDelegatesAria as I, e$3 as J, showSettingsDialog$1 as K, matterDashboardApp as L, MAX_NODE_LABEL_LENGTH as M, Privilege as P, __decorate as _, clientContext as a, i$4 as b, c$5 as c, b as d, e$6 as e, fireAndForget as f, t$1 as g, handleAsync as h, i$7 as i, mdiAccessPoint as j, mdiEyeOff as k, mdiEye as l, mdiWifi as m, n$5 as n, formatHex as o, nodeIdKey as p, aclCapacity as q, r$3 as r, showAlertDialog as s, tickContext as t, targetServerClusters as u, clusters as v, writeNodeLabel as w, AuthMode as x, addAclEntry as y, PRIVILEGE_NAMES as z };
