const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./lib-CBtriEt5.js","./chunk-DfAF0w94.js","./wgxpath.install-node-Csk64Aj9.js","./liteDOM-Cp0aN3bP.js","./_commonjsHelpers.js","./xypic-DrMJn58R.js","./tex-svg-full-BI3fonbT.js"])))=>i.map(i=>d[i]);
import { g as getDefaultExportFromCjs, c as commonjsGlobal } from "./_commonjsHelpers.js";
import { l } from "./chunk-DfAF0w94.js";
(function polyfill() {
  const relList = document.createElement("link").relList;
  if (relList && relList.supports && relList.supports("modulepreload")) return;
  for (const link2 of document.querySelectorAll('link[rel="modulepreload"]')) processPreload(link2);
  new MutationObserver((mutations) => {
    for (const mutation of mutations) {
      if (mutation.type !== "childList") continue;
      for (const node2 of mutation.addedNodes) if (node2.tagName === "LINK" && node2.rel === "modulepreload") processPreload(node2);
    }
  }).observe(document, {
    childList: true,
    subtree: true
  });
  function getFetchOpts(link2) {
    const fetchOpts = {};
    if (link2.integrity) fetchOpts.integrity = link2.integrity;
    if (link2.referrerPolicy) fetchOpts.referrerPolicy = link2.referrerPolicy;
    if (link2.crossOrigin === "use-credentials") fetchOpts.credentials = "include";
    else if (link2.crossOrigin === "anonymous") fetchOpts.credentials = "omit";
    else fetchOpts.credentials = "same-origin";
    return fetchOpts;
  }
  function processPreload(link2) {
    if (link2.ep) return;
    link2.ep = true;
    const fetchOpts = getFetchOpts(link2);
    fetch(link2.href, fetchOpts);
  }
})();
var jsxDevRuntime = { exports: {} };
var reactJsxDevRuntime_development = {};
var react = { exports: {} };
var react_development = { exports: {} };
react_development.exports;
var hasRequiredReact_development;
function requireReact_development() {
  if (hasRequiredReact_development) return react_development.exports;
  hasRequiredReact_development = 1;
  (function(module, exports2) {
    /**
     * @license React
     * react.development.js
     *
     * Copyright (c) Meta Platforms, Inc. and affiliates.
     *
     * This source code is licensed under the MIT license found in the
     * LICENSE file in the root directory of this source tree.
     */
    (function() {
      function defineDeprecationWarning(methodName, info) {
        Object.defineProperty(Component2.prototype, methodName, {
          get: function() {
            console.warn(
              "%s(...) is deprecated in plain JavaScript React classes. %s",
              info[0],
              info[1]
            );
          }
        });
      }
      function getIteratorFn(maybeIterable) {
        if (null === maybeIterable || "object" !== typeof maybeIterable)
          return null;
        maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"];
        return "function" === typeof maybeIterable ? maybeIterable : null;
      }
      function warnNoop(publicInstance, callerName) {
        publicInstance = (publicInstance = publicInstance.constructor) && (publicInstance.displayName || publicInstance.name) || "ReactClass";
        var warningKey = publicInstance + "." + callerName;
        didWarnStateUpdateForUnmountedComponent[warningKey] || (console.error(
          "Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",
          callerName,
          publicInstance
        ), didWarnStateUpdateForUnmountedComponent[warningKey] = true);
      }
      function Component2(props, context, updater) {
        this.props = props;
        this.context = context;
        this.refs = emptyObject;
        this.updater = updater || ReactNoopUpdateQueue;
      }
      function ComponentDummy() {
      }
      function PureComponent(props, context, updater) {
        this.props = props;
        this.context = context;
        this.refs = emptyObject;
        this.updater = updater || ReactNoopUpdateQueue;
      }
      function noop2() {
      }
      function testStringCoercion(value2) {
        return "" + value2;
      }
      function checkKeyStringCoercion(value2) {
        try {
          testStringCoercion(value2);
          var JSCompiler_inline_result = false;
        } catch (e) {
          JSCompiler_inline_result = true;
        }
        if (JSCompiler_inline_result) {
          JSCompiler_inline_result = console;
          var JSCompiler_temp_const = JSCompiler_inline_result.error;
          var JSCompiler_inline_result$jscomp$0 = "function" === typeof Symbol && Symbol.toStringTag && value2[Symbol.toStringTag] || value2.constructor.name || "Object";
          JSCompiler_temp_const.call(
            JSCompiler_inline_result,
            "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",
            JSCompiler_inline_result$jscomp$0
          );
          return testStringCoercion(value2);
        }
      }
      function getComponentNameFromType(type) {
        if (null == type) return null;
        if ("function" === typeof type)
          return type.$$typeof === REACT_CLIENT_REFERENCE ? null : type.displayName || type.name || null;
        if ("string" === typeof type) return type;
        switch (type) {
          case REACT_FRAGMENT_TYPE:
            return "Fragment";
          case REACT_PROFILER_TYPE:
            return "Profiler";
          case REACT_STRICT_MODE_TYPE:
            return "StrictMode";
          case REACT_SUSPENSE_TYPE:
            return "Suspense";
          case REACT_SUSPENSE_LIST_TYPE:
            return "SuspenseList";
          case REACT_ACTIVITY_TYPE:
            return "Activity";
        }
        if ("object" === typeof type)
          switch ("number" === typeof type.tag && console.error(
            "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."
          ), type.$$typeof) {
            case REACT_PORTAL_TYPE:
              return "Portal";
            case REACT_CONTEXT_TYPE:
              return type.displayName || "Context";
            case REACT_CONSUMER_TYPE:
              return (type._context.displayName || "Context") + ".Consumer";
            case REACT_FORWARD_REF_TYPE:
              var innerType = type.render;
              type = type.displayName;
              type || (type = innerType.displayName || innerType.name || "", type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef");
              return type;
            case REACT_MEMO_TYPE:
              return innerType = type.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type.type) || "Memo";
            case REACT_LAZY_TYPE:
              innerType = type._payload;
              type = type._init;
              try {
                return getComponentNameFromType(type(innerType));
              } catch (x) {
              }
          }
        return null;
      }
      function getTaskName(type) {
        if (type === REACT_FRAGMENT_TYPE) return "<>";
        if ("object" === typeof type && null !== type && type.$$typeof === REACT_LAZY_TYPE)
          return "<...>";
        try {
          var name2 = getComponentNameFromType(type);
          return name2 ? "<" + name2 + ">" : "<...>";
        } catch (x) {
          return "<...>";
        }
      }
      function getOwner() {
        var dispatcher = ReactSharedInternals.A;
        return null === dispatcher ? null : dispatcher.getOwner();
      }
      function UnknownOwner() {
        return Error("react-stack-top-frame");
      }
      function hasValidKey(config2) {
        if (hasOwnProperty2.call(config2, "key")) {
          var getter = Object.getOwnPropertyDescriptor(config2, "key").get;
          if (getter && getter.isReactWarning) return false;
        }
        return void 0 !== config2.key;
      }
      function defineKeyPropWarningGetter(props, displayName) {
        function warnAboutAccessingKey() {
          specialPropKeyWarningShown || (specialPropKeyWarningShown = true, console.error(
            "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",
            displayName
          ));
        }
        warnAboutAccessingKey.isReactWarning = true;
        Object.defineProperty(props, "key", {
          get: warnAboutAccessingKey,
          configurable: true
        });
      }
      function elementRefGetterWithDeprecationWarning() {
        var componentName = getComponentNameFromType(this.type);
        didWarnAboutElementRef[componentName] || (didWarnAboutElementRef[componentName] = true, console.error(
          "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."
        ));
        componentName = this.props.ref;
        return void 0 !== componentName ? componentName : null;
      }
      function ReactElement(type, key2, props, owner, debugStack, debugTask) {
        var refProp = props.ref;
        type = {
          $$typeof: REACT_ELEMENT_TYPE,
          type,
          key: key2,
          props,
          _owner: owner
        };
        null !== (void 0 !== refProp ? refProp : null) ? Object.defineProperty(type, "ref", {
          enumerable: false,
          get: elementRefGetterWithDeprecationWarning
        }) : Object.defineProperty(type, "ref", { enumerable: false, value: null });
        type._store = {};
        Object.defineProperty(type._store, "validated", {
          configurable: false,
          enumerable: false,
          writable: true,
          value: 0
        });
        Object.defineProperty(type, "_debugInfo", {
          configurable: false,
          enumerable: false,
          writable: true,
          value: null
        });
        Object.defineProperty(type, "_debugStack", {
          configurable: false,
          enumerable: false,
          writable: true,
          value: debugStack
        });
        Object.defineProperty(type, "_debugTask", {
          configurable: false,
          enumerable: false,
          writable: true,
          value: debugTask
        });
        Object.freeze && (Object.freeze(type.props), Object.freeze(type));
        return type;
      }
      function cloneAndReplaceKey(oldElement, newKey) {
        newKey = ReactElement(
          oldElement.type,
          newKey,
          oldElement.props,
          oldElement._owner,
          oldElement._debugStack,
          oldElement._debugTask
        );
        oldElement._store && (newKey._store.validated = oldElement._store.validated);
        return newKey;
      }
      function validateChildKeys(node2) {
        isValidElement(node2) ? node2._store && (node2._store.validated = 1) : "object" === typeof node2 && null !== node2 && node2.$$typeof === REACT_LAZY_TYPE && ("fulfilled" === node2._payload.status ? isValidElement(node2._payload.value) && node2._payload.value._store && (node2._payload.value._store.validated = 1) : node2._store && (node2._store.validated = 1));
      }
      function isValidElement(object2) {
        return "object" === typeof object2 && null !== object2 && object2.$$typeof === REACT_ELEMENT_TYPE;
      }
      function escape2(key2) {
        var escaperLookup = { "=": "=0", ":": "=2" };
        return "$" + key2.replace(/[=:]/g, function(match3) {
          return escaperLookup[match3];
        });
      }
      function getElementKey(element, index) {
        return "object" === typeof element && null !== element && null != element.key ? (checkKeyStringCoercion(element.key), escape2("" + element.key)) : index.toString(36);
      }
      function resolveThenable(thenable) {
        switch (thenable.status) {
          case "fulfilled":
            return thenable.value;
          case "rejected":
            throw thenable.reason;
          default:
            switch ("string" === typeof thenable.status ? thenable.then(noop2, noop2) : (thenable.status = "pending", thenable.then(
              function(fulfilledValue) {
                "pending" === thenable.status && (thenable.status = "fulfilled", thenable.value = fulfilledValue);
              },
              function(error2) {
                "pending" === thenable.status && (thenable.status = "rejected", thenable.reason = error2);
              }
            )), thenable.status) {
              case "fulfilled":
                return thenable.value;
              case "rejected":
                throw thenable.reason;
            }
        }
        throw thenable;
      }
      function mapIntoArray(children2, array2, escapedPrefix, nameSoFar, callback) {
        var type = typeof children2;
        if ("undefined" === type || "boolean" === type) children2 = null;
        var invokeCallback = false;
        if (null === children2) invokeCallback = true;
        else
          switch (type) {
            case "bigint":
            case "string":
            case "number":
              invokeCallback = true;
              break;
            case "object":
              switch (children2.$$typeof) {
                case REACT_ELEMENT_TYPE:
                case REACT_PORTAL_TYPE:
                  invokeCallback = true;
                  break;
                case REACT_LAZY_TYPE:
                  return invokeCallback = children2._init, mapIntoArray(
                    invokeCallback(children2._payload),
                    array2,
                    escapedPrefix,
                    nameSoFar,
                    callback
                  );
              }
          }
        if (invokeCallback) {
          invokeCallback = children2;
          callback = callback(invokeCallback);
          var childKey = "" === nameSoFar ? "." + getElementKey(invokeCallback, 0) : nameSoFar;
          isArrayImpl(callback) ? (escapedPrefix = "", null != childKey && (escapedPrefix = childKey.replace(userProvidedKeyEscapeRegex, "$&/") + "/"), mapIntoArray(callback, array2, escapedPrefix, "", function(c2) {
            return c2;
          })) : null != callback && (isValidElement(callback) && (null != callback.key && (invokeCallback && invokeCallback.key === callback.key || checkKeyStringCoercion(callback.key)), escapedPrefix = cloneAndReplaceKey(
            callback,
            escapedPrefix + (null == callback.key || invokeCallback && invokeCallback.key === callback.key ? "" : ("" + callback.key).replace(
              userProvidedKeyEscapeRegex,
              "$&/"
            ) + "/") + childKey
          ), "" !== nameSoFar && null != invokeCallback && isValidElement(invokeCallback) && null == invokeCallback.key && invokeCallback._store && !invokeCallback._store.validated && (escapedPrefix._store.validated = 2), callback = escapedPrefix), array2.push(callback));
          return 1;
        }
        invokeCallback = 0;
        childKey = "" === nameSoFar ? "." : nameSoFar + ":";
        if (isArrayImpl(children2))
          for (var i2 = 0; i2 < children2.length; i2++)
            nameSoFar = children2[i2], type = childKey + getElementKey(nameSoFar, i2), invokeCallback += mapIntoArray(
              nameSoFar,
              array2,
              escapedPrefix,
              type,
              callback
            );
        else if (i2 = getIteratorFn(children2), "function" === typeof i2)
          for (i2 === children2.entries && (didWarnAboutMaps || console.warn(
            "Using Maps as children is not supported. Use an array of keyed ReactElements instead."
          ), didWarnAboutMaps = true), children2 = i2.call(children2), i2 = 0; !(nameSoFar = children2.next()).done; )
            nameSoFar = nameSoFar.value, type = childKey + getElementKey(nameSoFar, i2++), invokeCallback += mapIntoArray(
              nameSoFar,
              array2,
              escapedPrefix,
              type,
              callback
            );
        else if ("object" === type) {
          if ("function" === typeof children2.then)
            return mapIntoArray(
              resolveThenable(children2),
              array2,
              escapedPrefix,
              nameSoFar,
              callback
            );
          array2 = String(children2);
          throw Error(
            "Objects are not valid as a React child (found: " + ("[object Object]" === array2 ? "object with keys {" + Object.keys(children2).join(", ") + "}" : array2) + "). If you meant to render a collection of children, use an array instead."
          );
        }
        return invokeCallback;
      }
      function mapChildren(children2, func2, context) {
        if (null == children2) return children2;
        var result2 = [], count2 = 0;
        mapIntoArray(children2, result2, "", "", function(child) {
          return func2.call(context, child, count2++);
        });
        return result2;
      }
      function lazyInitializer(payload) {
        if (-1 === payload._status) {
          var ioInfo = payload._ioInfo;
          null != ioInfo && (ioInfo.start = ioInfo.end = performance.now());
          ioInfo = payload._result;
          var thenable = ioInfo();
          thenable.then(
            function(moduleObject) {
              if (0 === payload._status || -1 === payload._status) {
                payload._status = 1;
                payload._result = moduleObject;
                var _ioInfo = payload._ioInfo;
                null != _ioInfo && (_ioInfo.end = performance.now());
                void 0 === thenable.status && (thenable.status = "fulfilled", thenable.value = moduleObject);
              }
            },
            function(error2) {
              if (0 === payload._status || -1 === payload._status) {
                payload._status = 2;
                payload._result = error2;
                var _ioInfo2 = payload._ioInfo;
                null != _ioInfo2 && (_ioInfo2.end = performance.now());
                void 0 === thenable.status && (thenable.status = "rejected", thenable.reason = error2);
              }
            }
          );
          ioInfo = payload._ioInfo;
          if (null != ioInfo) {
            ioInfo.value = thenable;
            var displayName = thenable.displayName;
            "string" === typeof displayName && (ioInfo.name = displayName);
          }
          -1 === payload._status && (payload._status = 0, payload._result = thenable);
        }
        if (1 === payload._status)
          return ioInfo = payload._result, void 0 === ioInfo && console.error(
            "lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n  const MyComponent = lazy(() => import('./MyComponent'))\n\nDid you accidentally put curly braces around the import?",
            ioInfo
          ), "default" in ioInfo || console.error(
            "lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n  const MyComponent = lazy(() => import('./MyComponent'))",
            ioInfo
          ), ioInfo.default;
        throw payload._result;
      }
      function resolveDispatcher() {
        var dispatcher = ReactSharedInternals.H;
        null === dispatcher && console.error(
          "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem."
        );
        return dispatcher;
      }
      function releaseAsyncTransition() {
        ReactSharedInternals.asyncTransitions--;
      }
      function enqueueTask(task) {
        if (null === enqueueTaskImpl)
          try {
            var requireString = ("require" + Math.random()).slice(0, 7);
            enqueueTaskImpl = (module && module[requireString]).call(
              module,
              "timers"
            ).setImmediate;
          } catch (_err) {
            enqueueTaskImpl = function(callback) {
              false === didWarnAboutMessageChannel && (didWarnAboutMessageChannel = true, "undefined" === typeof MessageChannel && console.error(
                "This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."
              ));
              var channel = new MessageChannel();
              channel.port1.onmessage = callback;
              channel.port2.postMessage(void 0);
            };
          }
        return enqueueTaskImpl(task);
      }
      function aggregateErrors(errors2) {
        return 1 < errors2.length && "function" === typeof AggregateError ? new AggregateError(errors2) : errors2[0];
      }
      function popActScope(prevActQueue, prevActScopeDepth) {
        prevActScopeDepth !== actScopeDepth - 1 && console.error(
          "You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "
        );
        actScopeDepth = prevActScopeDepth;
      }
      function recursivelyFlushAsyncActWork(returnValue, resolve2, reject) {
        var queue = ReactSharedInternals.actQueue;
        if (null !== queue)
          if (0 !== queue.length)
            try {
              flushActQueue(queue);
              enqueueTask(function() {
                return recursivelyFlushAsyncActWork(returnValue, resolve2, reject);
              });
              return;
            } catch (error2) {
              ReactSharedInternals.thrownErrors.push(error2);
            }
          else ReactSharedInternals.actQueue = null;
        0 < ReactSharedInternals.thrownErrors.length ? (queue = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, reject(queue)) : resolve2(returnValue);
      }
      function flushActQueue(queue) {
        if (!isFlushing) {
          isFlushing = true;
          var i2 = 0;
          try {
            for (; i2 < queue.length; i2++) {
              var callback = queue[i2];
              do {
                ReactSharedInternals.didUsePromise = false;
                var continuation = callback(false);
                if (null !== continuation) {
                  if (ReactSharedInternals.didUsePromise) {
                    queue[i2] = callback;
                    queue.splice(0, i2);
                    return;
                  }
                  callback = continuation;
                } else break;
              } while (1);
            }
            queue.length = 0;
          } catch (error2) {
            queue.splice(0, i2 + 1), ReactSharedInternals.thrownErrors.push(error2);
          } finally {
            isFlushing = false;
          }
        }
      }
      "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
      var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = Symbol.for("react.memo"), REACT_LAZY_TYPE = Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = Symbol.for("react.activity"), MAYBE_ITERATOR_SYMBOL = Symbol.iterator, didWarnStateUpdateForUnmountedComponent = {}, ReactNoopUpdateQueue = {
        isMounted: function() {
          return false;
        },
        enqueueForceUpdate: function(publicInstance) {
          warnNoop(publicInstance, "forceUpdate");
        },
        enqueueReplaceState: function(publicInstance) {
          warnNoop(publicInstance, "replaceState");
        },
        enqueueSetState: function(publicInstance) {
          warnNoop(publicInstance, "setState");
        }
      }, assign2 = Object.assign, emptyObject = {};
      Object.freeze(emptyObject);
      Component2.prototype.isReactComponent = {};
      Component2.prototype.setState = function(partialState, callback) {
        if ("object" !== typeof partialState && "function" !== typeof partialState && null != partialState)
          throw Error(
            "takes an object of state variables to update or a function which returns an object of state variables."
          );
        this.updater.enqueueSetState(this, partialState, callback, "setState");
      };
      Component2.prototype.forceUpdate = function(callback) {
        this.updater.enqueueForceUpdate(this, callback, "forceUpdate");
      };
      var deprecatedAPIs = {
        isMounted: [
          "isMounted",
          "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."
        ],
        replaceState: [
          "replaceState",
          "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."
        ]
      };
      for (fnName in deprecatedAPIs)
        deprecatedAPIs.hasOwnProperty(fnName) && defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
      ComponentDummy.prototype = Component2.prototype;
      deprecatedAPIs = PureComponent.prototype = new ComponentDummy();
      deprecatedAPIs.constructor = PureComponent;
      assign2(deprecatedAPIs, Component2.prototype);
      deprecatedAPIs.isPureReactComponent = true;
      var isArrayImpl = Array.isArray, REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"), ReactSharedInternals = {
        H: null,
        A: null,
        T: null,
        S: null,
        actQueue: null,
        asyncTransitions: 0,
        isBatchingLegacy: false,
        didScheduleLegacyUpdate: false,
        didUsePromise: false,
        thrownErrors: [],
        getCurrentStack: null,
        recentlyCreatedOwnerStacks: 0
      }, hasOwnProperty2 = Object.prototype.hasOwnProperty, createTask = console.createTask ? console.createTask : function() {
        return null;
      };
      deprecatedAPIs = {
        react_stack_bottom_frame: function(callStackForError) {
          return callStackForError();
        }
      };
      var specialPropKeyWarningShown, didWarnAboutOldJSXRuntime;
      var didWarnAboutElementRef = {};
      var unknownOwnerDebugStack = deprecatedAPIs.react_stack_bottom_frame.bind(
        deprecatedAPIs,
        UnknownOwner
      )();
      var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));
      var didWarnAboutMaps = false, userProvidedKeyEscapeRegex = /\/+/g, reportGlobalError = "function" === typeof reportError ? reportError : function(error2) {
        if ("object" === typeof window && "function" === typeof window.ErrorEvent) {
          var event = new window.ErrorEvent("error", {
            bubbles: true,
            cancelable: true,
            message: "object" === typeof error2 && null !== error2 && "string" === typeof error2.message ? String(error2.message) : String(error2),
            error: error2
          });
          if (!window.dispatchEvent(event)) return;
        } else if ("object" === typeof process && "function" === typeof process.emit) {
          process.emit("uncaughtException", error2);
          return;
        }
        console.error(error2);
      }, didWarnAboutMessageChannel = false, enqueueTaskImpl = null, actScopeDepth = 0, didWarnNoAwaitAct = false, isFlushing = false, queueSeveralMicrotasks = "function" === typeof queueMicrotask ? function(callback) {
        queueMicrotask(function() {
          return queueMicrotask(callback);
        });
      } : enqueueTask;
      deprecatedAPIs = Object.freeze({
        __proto__: null,
        c: function(size) {
          return resolveDispatcher().useMemoCache(size);
        }
      });
      var fnName = {
        map: mapChildren,
        forEach: function(children2, forEachFunc, forEachContext) {
          mapChildren(
            children2,
            function() {
              forEachFunc.apply(this, arguments);
            },
            forEachContext
          );
        },
        count: function(children2) {
          var n2 = 0;
          mapChildren(children2, function() {
            n2++;
          });
          return n2;
        },
        toArray: function(children2) {
          return mapChildren(children2, function(child) {
            return child;
          }) || [];
        },
        only: function(children2) {
          if (!isValidElement(children2))
            throw Error(
              "React.Children.only expected to receive a single React element child."
            );
          return children2;
        }
      };
      exports2.Activity = REACT_ACTIVITY_TYPE;
      exports2.Children = fnName;
      exports2.Component = Component2;
      exports2.Fragment = REACT_FRAGMENT_TYPE;
      exports2.Profiler = REACT_PROFILER_TYPE;
      exports2.PureComponent = PureComponent;
      exports2.StrictMode = REACT_STRICT_MODE_TYPE;
      exports2.Suspense = REACT_SUSPENSE_TYPE;
      exports2.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = ReactSharedInternals;
      exports2.__COMPILER_RUNTIME = deprecatedAPIs;
      exports2.act = function(callback) {
        var prevActQueue = ReactSharedInternals.actQueue, prevActScopeDepth = actScopeDepth;
        actScopeDepth++;
        var queue = ReactSharedInternals.actQueue = null !== prevActQueue ? prevActQueue : [], didAwaitActCall = false;
        try {
          var result2 = callback();
        } catch (error2) {
          ReactSharedInternals.thrownErrors.push(error2);
        }
        if (0 < ReactSharedInternals.thrownErrors.length)
          throw popActScope(prevActQueue, prevActScopeDepth), callback = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, callback;
        if (null !== result2 && "object" === typeof result2 && "function" === typeof result2.then) {
          var thenable = result2;
          queueSeveralMicrotasks(function() {
            didAwaitActCall || didWarnNoAwaitAct || (didWarnNoAwaitAct = true, console.error(
              "You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"
            ));
          });
          return {
            then: function(resolve2, reject) {
              didAwaitActCall = true;
              thenable.then(
                function(returnValue) {
                  popActScope(prevActQueue, prevActScopeDepth);
                  if (0 === prevActScopeDepth) {
                    try {
                      flushActQueue(queue), enqueueTask(function() {
                        return recursivelyFlushAsyncActWork(
                          returnValue,
                          resolve2,
                          reject
                        );
                      });
                    } catch (error$0) {
                      ReactSharedInternals.thrownErrors.push(error$0);
                    }
                    if (0 < ReactSharedInternals.thrownErrors.length) {
                      var _thrownError = aggregateErrors(
                        ReactSharedInternals.thrownErrors
                      );
                      ReactSharedInternals.thrownErrors.length = 0;
                      reject(_thrownError);
                    }
                  } else resolve2(returnValue);
                },
                function(error2) {
                  popActScope(prevActQueue, prevActScopeDepth);
                  0 < ReactSharedInternals.thrownErrors.length ? (error2 = aggregateErrors(
                    ReactSharedInternals.thrownErrors
                  ), ReactSharedInternals.thrownErrors.length = 0, reject(error2)) : reject(error2);
                }
              );
            }
          };
        }
        var returnValue$jscomp$0 = result2;
        popActScope(prevActQueue, prevActScopeDepth);
        0 === prevActScopeDepth && (flushActQueue(queue), 0 !== queue.length && queueSeveralMicrotasks(function() {
          didAwaitActCall || didWarnNoAwaitAct || (didWarnNoAwaitAct = true, console.error(
            "A component suspended inside an `act` scope, but the `act` call was not awaited. When testing React components that depend on asynchronous data, you must await the result:\n\nawait act(() => ...)"
          ));
        }), ReactSharedInternals.actQueue = null);
        if (0 < ReactSharedInternals.thrownErrors.length)
          throw callback = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, callback;
        return {
          then: function(resolve2, reject) {
            didAwaitActCall = true;
            0 === prevActScopeDepth ? (ReactSharedInternals.actQueue = queue, enqueueTask(function() {
              return recursivelyFlushAsyncActWork(
                returnValue$jscomp$0,
                resolve2,
                reject
              );
            })) : resolve2(returnValue$jscomp$0);
          }
        };
      };
      exports2.cache = function(fn3) {
        return function() {
          return fn3.apply(null, arguments);
        };
      };
      exports2.cacheSignal = function() {
        return null;
      };
      exports2.captureOwnerStack = function() {
        var getCurrentStack = ReactSharedInternals.getCurrentStack;
        return null === getCurrentStack ? null : getCurrentStack();
      };
      exports2.cloneElement = function(element, config2, children2) {
        if (null === element || void 0 === element)
          throw Error(
            "The argument must be a React element, but you passed " + element + "."
          );
        var props = assign2({}, element.props), key2 = element.key, owner = element._owner;
        if (null != config2) {
          var JSCompiler_inline_result;
          a: {
            if (hasOwnProperty2.call(config2, "ref") && (JSCompiler_inline_result = Object.getOwnPropertyDescriptor(
              config2,
              "ref"
            ).get) && JSCompiler_inline_result.isReactWarning) {
              JSCompiler_inline_result = false;
              break a;
            }
            JSCompiler_inline_result = void 0 !== config2.ref;
          }
          JSCompiler_inline_result && (owner = getOwner());
          hasValidKey(config2) && (checkKeyStringCoercion(config2.key), key2 = "" + config2.key);
          for (propName in config2)
            !hasOwnProperty2.call(config2, propName) || "key" === propName || "__self" === propName || "__source" === propName || "ref" === propName && void 0 === config2.ref || (props[propName] = config2[propName]);
        }
        var propName = arguments.length - 2;
        if (1 === propName) props.children = children2;
        else if (1 < propName) {
          JSCompiler_inline_result = Array(propName);
          for (var i2 = 0; i2 < propName; i2++)
            JSCompiler_inline_result[i2] = arguments[i2 + 2];
          props.children = JSCompiler_inline_result;
        }
        props = ReactElement(
          element.type,
          key2,
          props,
          owner,
          element._debugStack,
          element._debugTask
        );
        for (key2 = 2; key2 < arguments.length; key2++)
          validateChildKeys(arguments[key2]);
        return props;
      };
      exports2.createContext = function(defaultValue) {
        defaultValue = {
          $$typeof: REACT_CONTEXT_TYPE,
          _currentValue: defaultValue,
          _currentValue2: defaultValue,
          _threadCount: 0,
          Provider: null,
          Consumer: null
        };
        defaultValue.Provider = defaultValue;
        defaultValue.Consumer = {
          $$typeof: REACT_CONSUMER_TYPE,
          _context: defaultValue
        };
        defaultValue._currentRenderer = null;
        defaultValue._currentRenderer2 = null;
        return defaultValue;
      };
      exports2.createElement = function(type, config2, children2) {
        for (var i2 = 2; i2 < arguments.length; i2++)
          validateChildKeys(arguments[i2]);
        i2 = {};
        var key2 = null;
        if (null != config2)
          for (propName in didWarnAboutOldJSXRuntime || !("__self" in config2) || "key" in config2 || (didWarnAboutOldJSXRuntime = true, console.warn(
            "Your app (or one of its dependencies) is using an outdated JSX transform. Update to the modern JSX transform for faster performance: https://react.dev/link/new-jsx-transform"
          )), hasValidKey(config2) && (checkKeyStringCoercion(config2.key), key2 = "" + config2.key), config2)
            hasOwnProperty2.call(config2, propName) && "key" !== propName && "__self" !== propName && "__source" !== propName && (i2[propName] = config2[propName]);
        var childrenLength = arguments.length - 2;
        if (1 === childrenLength) i2.children = children2;
        else if (1 < childrenLength) {
          for (var childArray = Array(childrenLength), _i = 0; _i < childrenLength; _i++)
            childArray[_i] = arguments[_i + 2];
          Object.freeze && Object.freeze(childArray);
          i2.children = childArray;
        }
        if (type && type.defaultProps)
          for (propName in childrenLength = type.defaultProps, childrenLength)
            void 0 === i2[propName] && (i2[propName] = childrenLength[propName]);
        key2 && defineKeyPropWarningGetter(
          i2,
          "function" === typeof type ? type.displayName || type.name || "Unknown" : type
        );
        var propName = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
        return ReactElement(
          type,
          key2,
          i2,
          getOwner(),
          propName ? Error("react-stack-top-frame") : unknownOwnerDebugStack,
          propName ? createTask(getTaskName(type)) : unknownOwnerDebugTask
        );
      };
      exports2.createRef = function() {
        var refObject = { current: null };
        Object.seal(refObject);
        return refObject;
      };
      exports2.forwardRef = function(render2) {
        null != render2 && render2.$$typeof === REACT_MEMO_TYPE ? console.error(
          "forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."
        ) : "function" !== typeof render2 ? console.error(
          "forwardRef requires a render function but was given %s.",
          null === render2 ? "null" : typeof render2
        ) : 0 !== render2.length && 2 !== render2.length && console.error(
          "forwardRef render functions accept exactly two parameters: props and ref. %s",
          1 === render2.length ? "Did you forget to use the ref parameter?" : "Any additional parameter will be undefined."
        );
        null != render2 && null != render2.defaultProps && console.error(
          "forwardRef render functions do not support defaultProps. Did you accidentally pass a React component?"
        );
        var elementType = { $$typeof: REACT_FORWARD_REF_TYPE, render: render2 }, ownName;
        Object.defineProperty(elementType, "displayName", {
          enumerable: false,
          configurable: true,
          get: function() {
            return ownName;
          },
          set: function(name2) {
            ownName = name2;
            render2.name || render2.displayName || (Object.defineProperty(render2, "name", { value: name2 }), render2.displayName = name2);
          }
        });
        return elementType;
      };
      exports2.isValidElement = isValidElement;
      exports2.lazy = function(ctor) {
        ctor = { _status: -1, _result: ctor };
        var lazyType = {
          $$typeof: REACT_LAZY_TYPE,
          _payload: ctor,
          _init: lazyInitializer
        }, ioInfo = {
          name: "lazy",
          start: -1,
          end: -1,
          value: null,
          owner: null,
          debugStack: Error("react-stack-top-frame"),
          debugTask: console.createTask ? console.createTask("lazy()") : null
        };
        ctor._ioInfo = ioInfo;
        lazyType._debugInfo = [{ awaited: ioInfo }];
        return lazyType;
      };
      exports2.memo = function(type, compare2) {
        null == type && console.error(
          "memo: The first argument must be a component. Instead received: %s",
          null === type ? "null" : typeof type
        );
        compare2 = {
          $$typeof: REACT_MEMO_TYPE,
          type,
          compare: void 0 === compare2 ? null : compare2
        };
        var ownName;
        Object.defineProperty(compare2, "displayName", {
          enumerable: false,
          configurable: true,
          get: function() {
            return ownName;
          },
          set: function(name2) {
            ownName = name2;
            type.name || type.displayName || (Object.defineProperty(type, "name", { value: name2 }), type.displayName = name2);
          }
        });
        return compare2;
      };
      exports2.startTransition = function(scope) {
        var prevTransition = ReactSharedInternals.T, currentTransition = {};
        currentTransition._updatedFibers = /* @__PURE__ */ new Set();
        ReactSharedInternals.T = currentTransition;
        try {
          var returnValue = scope(), onStartTransitionFinish = ReactSharedInternals.S;
          null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue);
          "object" === typeof returnValue && null !== returnValue && "function" === typeof returnValue.then && (ReactSharedInternals.asyncTransitions++, returnValue.then(releaseAsyncTransition, releaseAsyncTransition), returnValue.then(noop2, reportGlobalError));
        } catch (error2) {
          reportGlobalError(error2);
        } finally {
          null === prevTransition && currentTransition._updatedFibers && (scope = currentTransition._updatedFibers.size, currentTransition._updatedFibers.clear(), 10 < scope && console.warn(
            "Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."
          )), null !== prevTransition && null !== currentTransition.types && (null !== prevTransition.types && prevTransition.types !== currentTransition.types && console.error(
            "We expected inner Transitions to have transferred the outer types set and that you cannot add to the outer Transition while inside the inner.This is a bug in React."
          ), prevTransition.types = currentTransition.types), ReactSharedInternals.T = prevTransition;
        }
      };
      exports2.unstable_useCacheRefresh = function() {
        return resolveDispatcher().useCacheRefresh();
      };
      exports2.use = function(usable) {
        return resolveDispatcher().use(usable);
      };
      exports2.useActionState = function(action, initialState, permalink) {
        return resolveDispatcher().useActionState(
          action,
          initialState,
          permalink
        );
      };
      exports2.useCallback = function(callback, deps) {
        return resolveDispatcher().useCallback(callback, deps);
      };
      exports2.useContext = function(Context2) {
        var dispatcher = resolveDispatcher();
        Context2.$$typeof === REACT_CONSUMER_TYPE && console.error(
          "Calling useContext(Context.Consumer) is not supported and will cause bugs. Did you mean to call useContext(Context) instead?"
        );
        return dispatcher.useContext(Context2);
      };
      exports2.useDebugValue = function(value2, formatterFn) {
        return resolveDispatcher().useDebugValue(value2, formatterFn);
      };
      exports2.useDeferredValue = function(value2, initialValue) {
        return resolveDispatcher().useDeferredValue(value2, initialValue);
      };
      exports2.useEffect = function(create2, deps) {
        null == create2 && console.warn(
          "React Hook useEffect requires an effect callback. Did you forget to pass a callback to the hook?"
        );
        return resolveDispatcher().useEffect(create2, deps);
      };
      exports2.useEffectEvent = function(callback) {
        return resolveDispatcher().useEffectEvent(callback);
      };
      exports2.useId = function() {
        return resolveDispatcher().useId();
      };
      exports2.useImperativeHandle = function(ref2, create2, deps) {
        return resolveDispatcher().useImperativeHandle(ref2, create2, deps);
      };
      exports2.useInsertionEffect = function(create2, deps) {
        null == create2 && console.warn(
          "React Hook useInsertionEffect requires an effect callback. Did you forget to pass a callback to the hook?"
        );
        return resolveDispatcher().useInsertionEffect(create2, deps);
      };
      exports2.useLayoutEffect = function(create2, deps) {
        null == create2 && console.warn(
          "React Hook useLayoutEffect requires an effect callback. Did you forget to pass a callback to the hook?"
        );
        return resolveDispatcher().useLayoutEffect(create2, deps);
      };
      exports2.useMemo = function(create2, deps) {
        return resolveDispatcher().useMemo(create2, deps);
      };
      exports2.useOptimistic = function(passthrough, reducer) {
        return resolveDispatcher().useOptimistic(passthrough, reducer);
      };
      exports2.useReducer = function(reducer, initialArg, init) {
        return resolveDispatcher().useReducer(reducer, initialArg, init);
      };
      exports2.useRef = function(initialValue) {
        return resolveDispatcher().useRef(initialValue);
      };
      exports2.useState = function(initialState) {
        return resolveDispatcher().useState(initialState);
      };
      exports2.useSyncExternalStore = function(subscribe, getSnapshot, getServerSnapshot) {
        return resolveDispatcher().useSyncExternalStore(
          subscribe,
          getSnapshot,
          getServerSnapshot
        );
      };
      exports2.useTransition = function() {
        return resolveDispatcher().useTransition();
      };
      exports2.version = "19.2.0";
      "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
    })();
  })(react_development, react_development.exports);
  return react_development.exports;
}
var hasRequiredReact;
function requireReact() {
  if (hasRequiredReact) return react.exports;
  hasRequiredReact = 1;
  {
    react.exports = requireReact_development();
  }
  return react.exports;
}
var hasRequiredReactJsxDevRuntime_development;
function requireReactJsxDevRuntime_development() {
  if (hasRequiredReactJsxDevRuntime_development) return reactJsxDevRuntime_development;
  hasRequiredReactJsxDevRuntime_development = 1;
  /**
   * @license React
   * react-jsx-dev-runtime.development.js
   *
   * Copyright (c) Meta Platforms, Inc. and affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   */
  (function() {
    function getComponentNameFromType(type) {
      if (null == type) return null;
      if ("function" === typeof type)
        return type.$$typeof === REACT_CLIENT_REFERENCE ? null : type.displayName || type.name || null;
      if ("string" === typeof type) return type;
      switch (type) {
        case REACT_FRAGMENT_TYPE:
          return "Fragment";
        case REACT_PROFILER_TYPE:
          return "Profiler";
        case REACT_STRICT_MODE_TYPE:
          return "StrictMode";
        case REACT_SUSPENSE_TYPE:
          return "Suspense";
        case REACT_SUSPENSE_LIST_TYPE:
          return "SuspenseList";
        case REACT_ACTIVITY_TYPE:
          return "Activity";
      }
      if ("object" === typeof type)
        switch ("number" === typeof type.tag && console.error(
          "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."
        ), type.$$typeof) {
          case REACT_PORTAL_TYPE:
            return "Portal";
          case REACT_CONTEXT_TYPE:
            return type.displayName || "Context";
          case REACT_CONSUMER_TYPE:
            return (type._context.displayName || "Context") + ".Consumer";
          case REACT_FORWARD_REF_TYPE:
            var innerType = type.render;
            type = type.displayName;
            type || (type = innerType.displayName || innerType.name || "", type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef");
            return type;
          case REACT_MEMO_TYPE:
            return innerType = type.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type.type) || "Memo";
          case REACT_LAZY_TYPE:
            innerType = type._payload;
            type = type._init;
            try {
              return getComponentNameFromType(type(innerType));
            } catch (x) {
            }
        }
      return null;
    }
    function testStringCoercion(value2) {
      return "" + value2;
    }
    function checkKeyStringCoercion(value2) {
      try {
        testStringCoercion(value2);
        var JSCompiler_inline_result = false;
      } catch (e) {
        JSCompiler_inline_result = true;
      }
      if (JSCompiler_inline_result) {
        JSCompiler_inline_result = console;
        var JSCompiler_temp_const = JSCompiler_inline_result.error;
        var JSCompiler_inline_result$jscomp$0 = "function" === typeof Symbol && Symbol.toStringTag && value2[Symbol.toStringTag] || value2.constructor.name || "Object";
        JSCompiler_temp_const.call(
          JSCompiler_inline_result,
          "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",
          JSCompiler_inline_result$jscomp$0
        );
        return testStringCoercion(value2);
      }
    }
    function getTaskName(type) {
      if (type === REACT_FRAGMENT_TYPE) return "<>";
      if ("object" === typeof type && null !== type && type.$$typeof === REACT_LAZY_TYPE)
        return "<...>";
      try {
        var name2 = getComponentNameFromType(type);
        return name2 ? "<" + name2 + ">" : "<...>";
      } catch (x) {
        return "<...>";
      }
    }
    function getOwner() {
      var dispatcher = ReactSharedInternals.A;
      return null === dispatcher ? null : dispatcher.getOwner();
    }
    function UnknownOwner() {
      return Error("react-stack-top-frame");
    }
    function hasValidKey(config2) {
      if (hasOwnProperty2.call(config2, "key")) {
        var getter = Object.getOwnPropertyDescriptor(config2, "key").get;
        if (getter && getter.isReactWarning) return false;
      }
      return void 0 !== config2.key;
    }
    function defineKeyPropWarningGetter(props, displayName) {
      function warnAboutAccessingKey() {
        specialPropKeyWarningShown || (specialPropKeyWarningShown = true, console.error(
          "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",
          displayName
        ));
      }
      warnAboutAccessingKey.isReactWarning = true;
      Object.defineProperty(props, "key", {
        get: warnAboutAccessingKey,
        configurable: true
      });
    }
    function elementRefGetterWithDeprecationWarning() {
      var componentName = getComponentNameFromType(this.type);
      didWarnAboutElementRef[componentName] || (didWarnAboutElementRef[componentName] = true, console.error(
        "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."
      ));
      componentName = this.props.ref;
      return void 0 !== componentName ? componentName : null;
    }
    function ReactElement(type, key2, props, owner, debugStack, debugTask) {
      var refProp = props.ref;
      type = {
        $$typeof: REACT_ELEMENT_TYPE,
        type,
        key: key2,
        props,
        _owner: owner
      };
      null !== (void 0 !== refProp ? refProp : null) ? Object.defineProperty(type, "ref", {
        enumerable: false,
        get: elementRefGetterWithDeprecationWarning
      }) : Object.defineProperty(type, "ref", { enumerable: false, value: null });
      type._store = {};
      Object.defineProperty(type._store, "validated", {
        configurable: false,
        enumerable: false,
        writable: true,
        value: 0
      });
      Object.defineProperty(type, "_debugInfo", {
        configurable: false,
        enumerable: false,
        writable: true,
        value: null
      });
      Object.defineProperty(type, "_debugStack", {
        configurable: false,
        enumerable: false,
        writable: true,
        value: debugStack
      });
      Object.defineProperty(type, "_debugTask", {
        configurable: false,
        enumerable: false,
        writable: true,
        value: debugTask
      });
      Object.freeze && (Object.freeze(type.props), Object.freeze(type));
      return type;
    }
    function jsxDEVImpl(type, config2, maybeKey, isStaticChildren, debugStack, debugTask) {
      var children2 = config2.children;
      if (void 0 !== children2)
        if (isStaticChildren)
          if (isArrayImpl(children2)) {
            for (isStaticChildren = 0; isStaticChildren < children2.length; isStaticChildren++)
              validateChildKeys(children2[isStaticChildren]);
            Object.freeze && Object.freeze(children2);
          } else
            console.error(
              "React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead."
            );
        else validateChildKeys(children2);
      if (hasOwnProperty2.call(config2, "key")) {
        children2 = getComponentNameFromType(type);
        var keys2 = Object.keys(config2).filter(function(k) {
          return "key" !== k;
        });
        isStaticChildren = 0 < keys2.length ? "{key: someKey, " + keys2.join(": ..., ") + ": ...}" : "{key: someKey}";
        didWarnAboutKeySpread[children2 + isStaticChildren] || (keys2 = 0 < keys2.length ? "{" + keys2.join(": ..., ") + ": ...}" : "{}", console.error(
          'A props object containing a "key" prop is being spread into JSX:\n  let props = %s;\n  <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n  let props = %s;\n  <%s key={someKey} {...props} />',
          isStaticChildren,
          children2,
          keys2,
          children2
        ), didWarnAboutKeySpread[children2 + isStaticChildren] = true);
      }
      children2 = null;
      void 0 !== maybeKey && (checkKeyStringCoercion(maybeKey), children2 = "" + maybeKey);
      hasValidKey(config2) && (checkKeyStringCoercion(config2.key), children2 = "" + config2.key);
      if ("key" in config2) {
        maybeKey = {};
        for (var propName in config2)
          "key" !== propName && (maybeKey[propName] = config2[propName]);
      } else maybeKey = config2;
      children2 && defineKeyPropWarningGetter(
        maybeKey,
        "function" === typeof type ? type.displayName || type.name || "Unknown" : type
      );
      return ReactElement(
        type,
        children2,
        maybeKey,
        getOwner(),
        debugStack,
        debugTask
      );
    }
    function validateChildKeys(node2) {
      isValidElement(node2) ? node2._store && (node2._store.validated = 1) : "object" === typeof node2 && null !== node2 && node2.$$typeof === REACT_LAZY_TYPE && ("fulfilled" === node2._payload.status ? isValidElement(node2._payload.value) && node2._payload.value._store && (node2._payload.value._store.validated = 1) : node2._store && (node2._store.validated = 1));
    }
    function isValidElement(object2) {
      return "object" === typeof object2 && null !== object2 && object2.$$typeof === REACT_ELEMENT_TYPE;
    }
    var React = requireReact(), REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = Symbol.for("react.memo"), REACT_LAZY_TYPE = Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = Symbol.for("react.activity"), REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"), ReactSharedInternals = React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, hasOwnProperty2 = Object.prototype.hasOwnProperty, isArrayImpl = Array.isArray, createTask = console.createTask ? console.createTask : function() {
      return null;
    };
    React = {
      react_stack_bottom_frame: function(callStackForError) {
        return callStackForError();
      }
    };
    var specialPropKeyWarningShown;
    var didWarnAboutElementRef = {};
    var unknownOwnerDebugStack = React.react_stack_bottom_frame.bind(
      React,
      UnknownOwner
    )();
    var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));
    var didWarnAboutKeySpread = {};
    reactJsxDevRuntime_development.Fragment = REACT_FRAGMENT_TYPE;
    reactJsxDevRuntime_development.jsxDEV = function(type, config2, maybeKey, isStaticChildren) {
      var trackActualOwner = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
      return jsxDEVImpl(
        type,
        config2,
        maybeKey,
        isStaticChildren,
        trackActualOwner ? Error("react-stack-top-frame") : unknownOwnerDebugStack,
        trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask
      );
    };
  })();
  return reactJsxDevRuntime_development;
}
var hasRequiredJsxDevRuntime;
function requireJsxDevRuntime() {
  if (hasRequiredJsxDevRuntime) return jsxDevRuntime.exports;
  hasRequiredJsxDevRuntime = 1;
  {
    jsxDevRuntime.exports = requireReactJsxDevRuntime_development();
  }
  return jsxDevRuntime.exports;
}
var jsxDevRuntimeExports = requireJsxDevRuntime();
var client = { exports: {} };
var reactDomClient_development = {};
var scheduler = { exports: {} };
var scheduler_development = {};
var hasRequiredScheduler_development;
function requireScheduler_development() {
  if (hasRequiredScheduler_development) return scheduler_development;
  hasRequiredScheduler_development = 1;
  (function(exports2) {
    /**
     * @license React
     * scheduler.development.js
     *
     * Copyright (c) Meta Platforms, Inc. and affiliates.
     *
     * This source code is licensed under the MIT license found in the
     * LICENSE file in the root directory of this source tree.
     */
    (function() {
      function performWorkUntilDeadline() {
        needsPaint = false;
        if (isMessageLoopRunning) {
          var currentTime = exports2.unstable_now();
          startTime = currentTime;
          var hasMoreWork = true;
          try {
            a: {
              isHostCallbackScheduled = false;
              isHostTimeoutScheduled && (isHostTimeoutScheduled = false, localClearTimeout(taskTimeoutID), taskTimeoutID = -1);
              isPerformingWork = true;
              var previousPriorityLevel = currentPriorityLevel;
              try {
                b: {
                  advanceTimers(currentTime);
                  for (currentTask = peek2(taskQueue); null !== currentTask && !(currentTask.expirationTime > currentTime && shouldYieldToHost()); ) {
                    var callback = currentTask.callback;
                    if ("function" === typeof callback) {
                      currentTask.callback = null;
                      currentPriorityLevel = currentTask.priorityLevel;
                      var continuationCallback = callback(
                        currentTask.expirationTime <= currentTime
                      );
                      currentTime = exports2.unstable_now();
                      if ("function" === typeof continuationCallback) {
                        currentTask.callback = continuationCallback;
                        advanceTimers(currentTime);
                        hasMoreWork = true;
                        break b;
                      }
                      currentTask === peek2(taskQueue) && pop2(taskQueue);
                      advanceTimers(currentTime);
                    } else pop2(taskQueue);
                    currentTask = peek2(taskQueue);
                  }
                  if (null !== currentTask) hasMoreWork = true;
                  else {
                    var firstTimer = peek2(timerQueue);
                    null !== firstTimer && requestHostTimeout(
                      handleTimeout,
                      firstTimer.startTime - currentTime
                    );
                    hasMoreWork = false;
                  }
                }
                break a;
              } finally {
                currentTask = null, currentPriorityLevel = previousPriorityLevel, isPerformingWork = false;
              }
              hasMoreWork = void 0;
            }
          } finally {
            hasMoreWork ? schedulePerformWorkUntilDeadline() : isMessageLoopRunning = false;
          }
        }
      }
      function push2(heap2, node2) {
        var index = heap2.length;
        heap2.push(node2);
        a: for (; 0 < index; ) {
          var parentIndex = index - 1 >>> 1, parent = heap2[parentIndex];
          if (0 < compare2(parent, node2))
            heap2[parentIndex] = node2, heap2[index] = parent, index = parentIndex;
          else break a;
        }
      }
      function peek2(heap2) {
        return 0 === heap2.length ? null : heap2[0];
      }
      function pop2(heap2) {
        if (0 === heap2.length) return null;
        var first2 = heap2[0], last2 = heap2.pop();
        if (last2 !== first2) {
          heap2[0] = last2;
          a: for (var index = 0, length2 = heap2.length, halfLength = length2 >>> 1; index < halfLength; ) {
            var leftIndex = 2 * (index + 1) - 1, left2 = heap2[leftIndex], rightIndex = leftIndex + 1, right2 = heap2[rightIndex];
            if (0 > compare2(left2, last2))
              rightIndex < length2 && 0 > compare2(right2, left2) ? (heap2[index] = right2, heap2[rightIndex] = last2, index = rightIndex) : (heap2[index] = left2, heap2[leftIndex] = last2, index = leftIndex);
            else if (rightIndex < length2 && 0 > compare2(right2, last2))
              heap2[index] = right2, heap2[rightIndex] = last2, index = rightIndex;
            else break a;
          }
        }
        return first2;
      }
      function compare2(a2, b) {
        var diff2 = a2.sortIndex - b.sortIndex;
        return 0 !== diff2 ? diff2 : a2.id - b.id;
      }
      function advanceTimers(currentTime) {
        for (var timer = peek2(timerQueue); null !== timer; ) {
          if (null === timer.callback) pop2(timerQueue);
          else if (timer.startTime <= currentTime)
            pop2(timerQueue), timer.sortIndex = timer.expirationTime, push2(taskQueue, timer);
          else break;
          timer = peek2(timerQueue);
        }
      }
      function handleTimeout(currentTime) {
        isHostTimeoutScheduled = false;
        advanceTimers(currentTime);
        if (!isHostCallbackScheduled)
          if (null !== peek2(taskQueue))
            isHostCallbackScheduled = true, isMessageLoopRunning || (isMessageLoopRunning = true, schedulePerformWorkUntilDeadline());
          else {
            var firstTimer = peek2(timerQueue);
            null !== firstTimer && requestHostTimeout(
              handleTimeout,
              firstTimer.startTime - currentTime
            );
          }
      }
      function shouldYieldToHost() {
        return needsPaint ? true : exports2.unstable_now() - startTime < frameInterval ? false : true;
      }
      function requestHostTimeout(callback, ms) {
        taskTimeoutID = localSetTimeout(function() {
          callback(exports2.unstable_now());
        }, ms);
      }
      "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
      exports2.unstable_now = void 0;
      if ("object" === typeof performance && "function" === typeof performance.now) {
        var localPerformance = performance;
        exports2.unstable_now = function() {
          return localPerformance.now();
        };
      } else {
        var localDate = Date, initialTime = localDate.now();
        exports2.unstable_now = function() {
          return localDate.now() - initialTime;
        };
      }
      var taskQueue = [], timerQueue = [], taskIdCounter = 1, currentTask = null, currentPriorityLevel = 3, isPerformingWork = false, isHostCallbackScheduled = false, isHostTimeoutScheduled = false, needsPaint = false, localSetTimeout = "function" === typeof setTimeout ? setTimeout : null, localClearTimeout = "function" === typeof clearTimeout ? clearTimeout : null, localSetImmediate = "undefined" !== typeof setImmediate ? setImmediate : null, isMessageLoopRunning = false, taskTimeoutID = -1, frameInterval = 5, startTime = -1;
      if ("function" === typeof localSetImmediate)
        var schedulePerformWorkUntilDeadline = function() {
          localSetImmediate(performWorkUntilDeadline);
        };
      else if ("undefined" !== typeof MessageChannel) {
        var channel = new MessageChannel(), port = channel.port2;
        channel.port1.onmessage = performWorkUntilDeadline;
        schedulePerformWorkUntilDeadline = function() {
          port.postMessage(null);
        };
      } else
        schedulePerformWorkUntilDeadline = function() {
          localSetTimeout(performWorkUntilDeadline, 0);
        };
      exports2.unstable_IdlePriority = 5;
      exports2.unstable_ImmediatePriority = 1;
      exports2.unstable_LowPriority = 4;
      exports2.unstable_NormalPriority = 3;
      exports2.unstable_Profiling = null;
      exports2.unstable_UserBlockingPriority = 2;
      exports2.unstable_cancelCallback = function(task) {
        task.callback = null;
      };
      exports2.unstable_forceFrameRate = function(fps) {
        0 > fps || 125 < fps ? console.error(
          "forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"
        ) : frameInterval = 0 < fps ? Math.floor(1e3 / fps) : 5;
      };
      exports2.unstable_getCurrentPriorityLevel = function() {
        return currentPriorityLevel;
      };
      exports2.unstable_next = function(eventHandler2) {
        switch (currentPriorityLevel) {
          case 1:
          case 2:
          case 3:
            var priorityLevel = 3;
            break;
          default:
            priorityLevel = currentPriorityLevel;
        }
        var previousPriorityLevel = currentPriorityLevel;
        currentPriorityLevel = priorityLevel;
        try {
          return eventHandler2();
        } finally {
          currentPriorityLevel = previousPriorityLevel;
        }
      };
      exports2.unstable_requestPaint = function() {
        needsPaint = true;
      };
      exports2.unstable_runWithPriority = function(priorityLevel, eventHandler2) {
        switch (priorityLevel) {
          case 1:
          case 2:
          case 3:
          case 4:
          case 5:
            break;
          default:
            priorityLevel = 3;
        }
        var previousPriorityLevel = currentPriorityLevel;
        currentPriorityLevel = priorityLevel;
        try {
          return eventHandler2();
        } finally {
          currentPriorityLevel = previousPriorityLevel;
        }
      };
      exports2.unstable_scheduleCallback = function(priorityLevel, callback, options) {
        var currentTime = exports2.unstable_now();
        "object" === typeof options && null !== options ? (options = options.delay, options = "number" === typeof options && 0 < options ? currentTime + options : currentTime) : options = currentTime;
        switch (priorityLevel) {
          case 1:
            var timeout = -1;
            break;
          case 2:
            timeout = 250;
            break;
          case 5:
            timeout = 1073741823;
            break;
          case 4:
            timeout = 1e4;
            break;
          default:
            timeout = 5e3;
        }
        timeout = options + timeout;
        priorityLevel = {
          id: taskIdCounter++,
          callback,
          priorityLevel,
          startTime: options,
          expirationTime: timeout,
          sortIndex: -1
        };
        options > currentTime ? (priorityLevel.sortIndex = options, push2(timerQueue, priorityLevel), null === peek2(taskQueue) && priorityLevel === peek2(timerQueue) && (isHostTimeoutScheduled ? (localClearTimeout(taskTimeoutID), taskTimeoutID = -1) : isHostTimeoutScheduled = true, requestHostTimeout(handleTimeout, options - currentTime))) : (priorityLevel.sortIndex = timeout, push2(taskQueue, priorityLevel), isHostCallbackScheduled || isPerformingWork || (isHostCallbackScheduled = true, isMessageLoopRunning || (isMessageLoopRunning = true, schedulePerformWorkUntilDeadline())));
        return priorityLevel;
      };
      exports2.unstable_shouldYield = shouldYieldToHost;
      exports2.unstable_wrapCallback = function(callback) {
        var parentPriorityLevel = currentPriorityLevel;
        return function() {
          var previousPriorityLevel = currentPriorityLevel;
          currentPriorityLevel = parentPriorityLevel;
          try {
            return callback.apply(this, arguments);
          } finally {
            currentPriorityLevel = previousPriorityLevel;
          }
        };
      };
      "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
    })();
  })(scheduler_development);
  return scheduler_development;
}
var hasRequiredScheduler;
function requireScheduler() {
  if (hasRequiredScheduler) return scheduler.exports;
  hasRequiredScheduler = 1;
  {
    scheduler.exports = requireScheduler_development();
  }
  return scheduler.exports;
}
var reactDom = { exports: {} };
var reactDom_development = {};
var hasRequiredReactDom_development;
function requireReactDom_development() {
  if (hasRequiredReactDom_development) return reactDom_development;
  hasRequiredReactDom_development = 1;
  /**
   * @license React
   * react-dom.development.js
   *
   * Copyright (c) Meta Platforms, Inc. and affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   */
  (function() {
    function noop2() {
    }
    function testStringCoercion(value2) {
      return "" + value2;
    }
    function createPortal$1(children2, containerInfo, implementation) {
      var key2 = 3 < arguments.length && void 0 !== arguments[3] ? arguments[3] : null;
      try {
        testStringCoercion(key2);
        var JSCompiler_inline_result = false;
      } catch (e) {
        JSCompiler_inline_result = true;
      }
      JSCompiler_inline_result && (console.error(
        "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",
        "function" === typeof Symbol && Symbol.toStringTag && key2[Symbol.toStringTag] || key2.constructor.name || "Object"
      ), testStringCoercion(key2));
      return {
        $$typeof: REACT_PORTAL_TYPE,
        key: null == key2 ? null : "" + key2,
        children: children2,
        containerInfo,
        implementation
      };
    }
    function getCrossOriginStringAs(as, input2) {
      if ("font" === as) return "";
      if ("string" === typeof input2)
        return "use-credentials" === input2 ? input2 : "";
    }
    function getValueDescriptorExpectingObjectForWarning(thing) {
      return null === thing ? "`null`" : void 0 === thing ? "`undefined`" : "" === thing ? "an empty string" : 'something with type "' + typeof thing + '"';
    }
    function getValueDescriptorExpectingEnumForWarning(thing) {
      return null === thing ? "`null`" : void 0 === thing ? "`undefined`" : "" === thing ? "an empty string" : "string" === typeof thing ? JSON.stringify(thing) : "number" === typeof thing ? "`" + thing + "`" : 'something with type "' + typeof thing + '"';
    }
    function resolveDispatcher() {
      var dispatcher = ReactSharedInternals.H;
      null === dispatcher && console.error(
        "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem."
      );
      return dispatcher;
    }
    "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
    var React = requireReact(), Internals = {
      d: {
        f: noop2,
        r: function() {
          throw Error(
            "Invalid form element. requestFormReset must be passed a form that was rendered by React."
          );
        },
        D: noop2,
        C: noop2,
        L: noop2,
        m: noop2,
        X: noop2,
        S: noop2,
        M: noop2
      },
      p: 0,
      findDOMNode: null
    }, REACT_PORTAL_TYPE = Symbol.for("react.portal"), ReactSharedInternals = React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
    "function" === typeof Map && null != Map.prototype && "function" === typeof Map.prototype.forEach && "function" === typeof Set && null != Set.prototype && "function" === typeof Set.prototype.clear && "function" === typeof Set.prototype.forEach || console.error(
      "React depends on Map and Set built-in types. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills"
    );
    reactDom_development.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = Internals;
    reactDom_development.createPortal = function(children2, container2) {
      var key2 = 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : null;
      if (!container2 || 1 !== container2.nodeType && 9 !== container2.nodeType && 11 !== container2.nodeType)
        throw Error("Target container is not a DOM element.");
      return createPortal$1(children2, container2, null, key2);
    };
    reactDom_development.flushSync = function(fn3) {
      var previousTransition = ReactSharedInternals.T, previousUpdatePriority = Internals.p;
      try {
        if (ReactSharedInternals.T = null, Internals.p = 2, fn3)
          return fn3();
      } finally {
        ReactSharedInternals.T = previousTransition, Internals.p = previousUpdatePriority, Internals.d.f() && console.error(
          "flushSync was called from inside a lifecycle method. React cannot flush when React is already rendering. Consider moving this call to a scheduler task or micro task."
        );
      }
    };
    reactDom_development.preconnect = function(href, options) {
      "string" === typeof href && href ? null != options && "object" !== typeof options ? console.error(
        "ReactDOM.preconnect(): Expected the `options` argument (second) to be an object but encountered %s instead. The only supported option at this time is `crossOrigin` which accepts a string.",
        getValueDescriptorExpectingEnumForWarning(options)
      ) : null != options && "string" !== typeof options.crossOrigin && console.error(
        "ReactDOM.preconnect(): Expected the `crossOrigin` option (second argument) to be a string but encountered %s instead. Try removing this option or passing a string value instead.",
        getValueDescriptorExpectingObjectForWarning(options.crossOrigin)
      ) : console.error(
        "ReactDOM.preconnect(): Expected the `href` argument (first) to be a non-empty string but encountered %s instead.",
        getValueDescriptorExpectingObjectForWarning(href)
      );
      "string" === typeof href && (options ? (options = options.crossOrigin, options = "string" === typeof options ? "use-credentials" === options ? options : "" : void 0) : options = null, Internals.d.C(href, options));
    };
    reactDom_development.prefetchDNS = function(href) {
      if ("string" !== typeof href || !href)
        console.error(
          "ReactDOM.prefetchDNS(): Expected the `href` argument (first) to be a non-empty string but encountered %s instead.",
          getValueDescriptorExpectingObjectForWarning(href)
        );
      else if (1 < arguments.length) {
        var options = arguments[1];
        "object" === typeof options && options.hasOwnProperty("crossOrigin") ? console.error(
          "ReactDOM.prefetchDNS(): Expected only one argument, `href`, but encountered %s as a second argument instead. This argument is reserved for future options and is currently disallowed. It looks like the you are attempting to set a crossOrigin property for this DNS lookup hint. Browsers do not perform DNS queries using CORS and setting this attribute on the resource hint has no effect. Try calling ReactDOM.prefetchDNS() with just a single string argument, `href`.",
          getValueDescriptorExpectingEnumForWarning(options)
        ) : console.error(
          "ReactDOM.prefetchDNS(): Expected only one argument, `href`, but encountered %s as a second argument instead. This argument is reserved for future options and is currently disallowed. Try calling ReactDOM.prefetchDNS() with just a single string argument, `href`.",
          getValueDescriptorExpectingEnumForWarning(options)
        );
      }
      "string" === typeof href && Internals.d.D(href);
    };
    reactDom_development.preinit = function(href, options) {
      "string" === typeof href && href ? null == options || "object" !== typeof options ? console.error(
        "ReactDOM.preinit(): Expected the `options` argument (second) to be an object with an `as` property describing the type of resource to be preinitialized but encountered %s instead.",
        getValueDescriptorExpectingEnumForWarning(options)
      ) : "style" !== options.as && "script" !== options.as && console.error(
        'ReactDOM.preinit(): Expected the `as` property in the `options` argument (second) to contain a valid value describing the type of resource to be preinitialized but encountered %s instead. Valid values for `as` are "style" and "script".',
        getValueDescriptorExpectingEnumForWarning(options.as)
      ) : console.error(
        "ReactDOM.preinit(): Expected the `href` argument (first) to be a non-empty string but encountered %s instead.",
        getValueDescriptorExpectingObjectForWarning(href)
      );
      if ("string" === typeof href && options && "string" === typeof options.as) {
        var as = options.as, crossOrigin = getCrossOriginStringAs(as, options.crossOrigin), integrity = "string" === typeof options.integrity ? options.integrity : void 0, fetchPriority = "string" === typeof options.fetchPriority ? options.fetchPriority : void 0;
        "style" === as ? Internals.d.S(
          href,
          "string" === typeof options.precedence ? options.precedence : void 0,
          {
            crossOrigin,
            integrity,
            fetchPriority
          }
        ) : "script" === as && Internals.d.X(href, {
          crossOrigin,
          integrity,
          fetchPriority,
          nonce: "string" === typeof options.nonce ? options.nonce : void 0
        });
      }
    };
    reactDom_development.preinitModule = function(href, options) {
      var encountered = "";
      "string" === typeof href && href || (encountered += " The `href` argument encountered was " + getValueDescriptorExpectingObjectForWarning(href) + ".");
      void 0 !== options && "object" !== typeof options ? encountered += " The `options` argument encountered was " + getValueDescriptorExpectingObjectForWarning(options) + "." : options && "as" in options && "script" !== options.as && (encountered += " The `as` option encountered was " + getValueDescriptorExpectingEnumForWarning(options.as) + ".");
      if (encountered)
        console.error(
          "ReactDOM.preinitModule(): Expected up to two arguments, a non-empty `href` string and, optionally, an `options` object with a valid `as` property.%s",
          encountered
        );
      else
        switch (encountered = options && "string" === typeof options.as ? options.as : "script", encountered) {
          case "script":
            break;
          default:
            encountered = getValueDescriptorExpectingEnumForWarning(encountered), console.error(
              'ReactDOM.preinitModule(): Currently the only supported "as" type for this function is "script" but received "%s" instead. This warning was generated for `href` "%s". In the future other module types will be supported, aligning with the import-attributes proposal. Learn more here: (https://github.com/tc39/proposal-import-attributes)',
              encountered,
              href
            );
        }
      if ("string" === typeof href)
        if ("object" === typeof options && null !== options) {
          if (null == options.as || "script" === options.as)
            encountered = getCrossOriginStringAs(
              options.as,
              options.crossOrigin
            ), Internals.d.M(href, {
              crossOrigin: encountered,
              integrity: "string" === typeof options.integrity ? options.integrity : void 0,
              nonce: "string" === typeof options.nonce ? options.nonce : void 0
            });
        } else null == options && Internals.d.M(href);
    };
    reactDom_development.preload = function(href, options) {
      var encountered = "";
      "string" === typeof href && href || (encountered += " The `href` argument encountered was " + getValueDescriptorExpectingObjectForWarning(href) + ".");
      null == options || "object" !== typeof options ? encountered += " The `options` argument encountered was " + getValueDescriptorExpectingObjectForWarning(options) + "." : "string" === typeof options.as && options.as || (encountered += " The `as` option encountered was " + getValueDescriptorExpectingObjectForWarning(options.as) + ".");
      encountered && console.error(
        'ReactDOM.preload(): Expected two arguments, a non-empty `href` string and an `options` object with an `as` property valid for a `<link rel="preload" as="..." />` tag.%s',
        encountered
      );
      if ("string" === typeof href && "object" === typeof options && null !== options && "string" === typeof options.as) {
        encountered = options.as;
        var crossOrigin = getCrossOriginStringAs(
          encountered,
          options.crossOrigin
        );
        Internals.d.L(href, encountered, {
          crossOrigin,
          integrity: "string" === typeof options.integrity ? options.integrity : void 0,
          nonce: "string" === typeof options.nonce ? options.nonce : void 0,
          type: "string" === typeof options.type ? options.type : void 0,
          fetchPriority: "string" === typeof options.fetchPriority ? options.fetchPriority : void 0,
          referrerPolicy: "string" === typeof options.referrerPolicy ? options.referrerPolicy : void 0,
          imageSrcSet: "string" === typeof options.imageSrcSet ? options.imageSrcSet : void 0,
          imageSizes: "string" === typeof options.imageSizes ? options.imageSizes : void 0,
          media: "string" === typeof options.media ? options.media : void 0
        });
      }
    };
    reactDom_development.preloadModule = function(href, options) {
      var encountered = "";
      "string" === typeof href && href || (encountered += " The `href` argument encountered was " + getValueDescriptorExpectingObjectForWarning(href) + ".");
      void 0 !== options && "object" !== typeof options ? encountered += " The `options` argument encountered was " + getValueDescriptorExpectingObjectForWarning(options) + "." : options && "as" in options && "string" !== typeof options.as && (encountered += " The `as` option encountered was " + getValueDescriptorExpectingObjectForWarning(options.as) + ".");
      encountered && console.error(
        'ReactDOM.preloadModule(): Expected two arguments, a non-empty `href` string and, optionally, an `options` object with an `as` property valid for a `<link rel="modulepreload" as="..." />` tag.%s',
        encountered
      );
      "string" === typeof href && (options ? (encountered = getCrossOriginStringAs(
        options.as,
        options.crossOrigin
      ), Internals.d.m(href, {
        as: "string" === typeof options.as && "script" !== options.as ? options.as : void 0,
        crossOrigin: encountered,
        integrity: "string" === typeof options.integrity ? options.integrity : void 0
      })) : Internals.d.m(href));
    };
    reactDom_development.requestFormReset = function(form) {
      Internals.d.r(form);
    };
    reactDom_development.unstable_batchedUpdates = function(fn3, a2) {
      return fn3(a2);
    };
    reactDom_development.useFormState = function(action, initialState, permalink) {
      return resolveDispatcher().useFormState(action, initialState, permalink);
    };
    reactDom_development.useFormStatus = function() {
      return resolveDispatcher().useHostTransitionStatus();
    };
    reactDom_development.version = "19.2.0";
    "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
  })();
  return reactDom_development;
}
var hasRequiredReactDom;
function requireReactDom() {
  if (hasRequiredReactDom) return reactDom.exports;
  hasRequiredReactDom = 1;
  {
    reactDom.exports = requireReactDom_development();
  }
  return reactDom.exports;
}
var hasRequiredReactDomClient_development;
function requireReactDomClient_development() {
  if (hasRequiredReactDomClient_development) return reactDomClient_development;
  hasRequiredReactDomClient_development = 1;
  /**
   * @license React
   * react-dom-client.development.js
   *
   * Copyright (c) Meta Platforms, Inc. and affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   */
  (function() {
    function findHook(fiber, id2) {
      for (fiber = fiber.memoizedState; null !== fiber && 0 < id2; )
        fiber = fiber.next, id2--;
      return fiber;
    }
    function copyWithSetImpl(obj, path, index, value2) {
      if (index >= path.length) return value2;
      var key2 = path[index], updated = isArrayImpl(obj) ? obj.slice() : assign2({}, obj);
      updated[key2] = copyWithSetImpl(obj[key2], path, index + 1, value2);
      return updated;
    }
    function copyWithRename(obj, oldPath, newPath) {
      if (oldPath.length !== newPath.length)
        console.warn("copyWithRename() expects paths of the same length");
      else {
        for (var i2 = 0; i2 < newPath.length - 1; i2++)
          if (oldPath[i2] !== newPath[i2]) {
            console.warn(
              "copyWithRename() expects paths to be the same except for the deepest key"
            );
            return;
          }
        return copyWithRenameImpl(obj, oldPath, newPath, 0);
      }
    }
    function copyWithRenameImpl(obj, oldPath, newPath, index) {
      var oldKey = oldPath[index], updated = isArrayImpl(obj) ? obj.slice() : assign2({}, obj);
      index + 1 === oldPath.length ? (updated[newPath[index]] = updated[oldKey], isArrayImpl(updated) ? updated.splice(oldKey, 1) : delete updated[oldKey]) : updated[oldKey] = copyWithRenameImpl(
        obj[oldKey],
        oldPath,
        newPath,
        index + 1
      );
      return updated;
    }
    function copyWithDeleteImpl(obj, path, index) {
      var key2 = path[index], updated = isArrayImpl(obj) ? obj.slice() : assign2({}, obj);
      if (index + 1 === path.length)
        return isArrayImpl(updated) ? updated.splice(key2, 1) : delete updated[key2], updated;
      updated[key2] = copyWithDeleteImpl(obj[key2], path, index + 1);
      return updated;
    }
    function shouldSuspendImpl() {
      return false;
    }
    function shouldErrorImpl() {
      return null;
    }
    function warnInvalidHookAccess() {
      console.error(
        "Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. You can only call Hooks at the top level of your React function. For more information, see https://react.dev/link/rules-of-hooks"
      );
    }
    function warnInvalidContextAccess() {
      console.error(
        "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()."
      );
    }
    function noop2() {
    }
    function warnForMissingKey() {
    }
    function setToSortedString(set3) {
      var array2 = [];
      set3.forEach(function(value2) {
        array2.push(value2);
      });
      return array2.sort().join(", ");
    }
    function createFiber(tag, pendingProps, key2, mode) {
      return new FiberNode(tag, pendingProps, key2, mode);
    }
    function scheduleRoot(root22, element) {
      root22.context === emptyContextObject && (updateContainerImpl(root22.current, 2, element, root22, null, null), flushSyncWork$1());
    }
    function scheduleRefresh(root22, update2) {
      if (null !== resolveFamily) {
        var staleFamilies = update2.staleFamilies;
        update2 = update2.updatedFamilies;
        flushPendingEffects();
        scheduleFibersWithFamiliesRecursively(
          root22.current,
          update2,
          staleFamilies
        );
        flushSyncWork$1();
      }
    }
    function setRefreshHandler(handler) {
      resolveFamily = handler;
    }
    function isValidContainer(node2) {
      return !(!node2 || 1 !== node2.nodeType && 9 !== node2.nodeType && 11 !== node2.nodeType);
    }
    function getNearestMountedFiber(fiber) {
      var node2 = fiber, nearestMounted = fiber;
      if (fiber.alternate) for (; node2.return; ) node2 = node2.return;
      else {
        fiber = node2;
        do
          node2 = fiber, 0 !== (node2.flags & 4098) && (nearestMounted = node2.return), fiber = node2.return;
        while (fiber);
      }
      return 3 === node2.tag ? nearestMounted : null;
    }
    function getSuspenseInstanceFromFiber(fiber) {
      if (13 === fiber.tag) {
        var suspenseState = fiber.memoizedState;
        null === suspenseState && (fiber = fiber.alternate, null !== fiber && (suspenseState = fiber.memoizedState));
        if (null !== suspenseState) return suspenseState.dehydrated;
      }
      return null;
    }
    function getActivityInstanceFromFiber(fiber) {
      if (31 === fiber.tag) {
        var activityState = fiber.memoizedState;
        null === activityState && (fiber = fiber.alternate, null !== fiber && (activityState = fiber.memoizedState));
        if (null !== activityState) return activityState.dehydrated;
      }
      return null;
    }
    function assertIsMounted(fiber) {
      if (getNearestMountedFiber(fiber) !== fiber)
        throw Error("Unable to find node on an unmounted component.");
    }
    function findCurrentFiberUsingSlowPath(fiber) {
      var alternate = fiber.alternate;
      if (!alternate) {
        alternate = getNearestMountedFiber(fiber);
        if (null === alternate)
          throw Error("Unable to find node on an unmounted component.");
        return alternate !== fiber ? null : fiber;
      }
      for (var a2 = fiber, b = alternate; ; ) {
        var parentA = a2.return;
        if (null === parentA) break;
        var parentB = parentA.alternate;
        if (null === parentB) {
          b = parentA.return;
          if (null !== b) {
            a2 = b;
            continue;
          }
          break;
        }
        if (parentA.child === parentB.child) {
          for (parentB = parentA.child; parentB; ) {
            if (parentB === a2) return assertIsMounted(parentA), fiber;
            if (parentB === b) return assertIsMounted(parentA), alternate;
            parentB = parentB.sibling;
          }
          throw Error("Unable to find node on an unmounted component.");
        }
        if (a2.return !== b.return) a2 = parentA, b = parentB;
        else {
          for (var didFindChild = false, _child = parentA.child; _child; ) {
            if (_child === a2) {
              didFindChild = true;
              a2 = parentA;
              b = parentB;
              break;
            }
            if (_child === b) {
              didFindChild = true;
              b = parentA;
              a2 = parentB;
              break;
            }
            _child = _child.sibling;
          }
          if (!didFindChild) {
            for (_child = parentB.child; _child; ) {
              if (_child === a2) {
                didFindChild = true;
                a2 = parentB;
                b = parentA;
                break;
              }
              if (_child === b) {
                didFindChild = true;
                b = parentB;
                a2 = parentA;
                break;
              }
              _child = _child.sibling;
            }
            if (!didFindChild)
              throw Error(
                "Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue."
              );
          }
        }
        if (a2.alternate !== b)
          throw Error(
            "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue."
          );
      }
      if (3 !== a2.tag)
        throw Error("Unable to find node on an unmounted component.");
      return a2.stateNode.current === a2 ? fiber : alternate;
    }
    function findCurrentHostFiberImpl(node2) {
      var tag = node2.tag;
      if (5 === tag || 26 === tag || 27 === tag || 6 === tag) return node2;
      for (node2 = node2.child; null !== node2; ) {
        tag = findCurrentHostFiberImpl(node2);
        if (null !== tag) return tag;
        node2 = node2.sibling;
      }
      return null;
    }
    function getIteratorFn(maybeIterable) {
      if (null === maybeIterable || "object" !== typeof maybeIterable)
        return null;
      maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"];
      return "function" === typeof maybeIterable ? maybeIterable : null;
    }
    function getComponentNameFromType(type) {
      if (null == type) return null;
      if ("function" === typeof type)
        return type.$$typeof === REACT_CLIENT_REFERENCE ? null : type.displayName || type.name || null;
      if ("string" === typeof type) return type;
      switch (type) {
        case REACT_FRAGMENT_TYPE:
          return "Fragment";
        case REACT_PROFILER_TYPE:
          return "Profiler";
        case REACT_STRICT_MODE_TYPE:
          return "StrictMode";
        case REACT_SUSPENSE_TYPE:
          return "Suspense";
        case REACT_SUSPENSE_LIST_TYPE:
          return "SuspenseList";
        case REACT_ACTIVITY_TYPE:
          return "Activity";
      }
      if ("object" === typeof type)
        switch ("number" === typeof type.tag && console.error(
          "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."
        ), type.$$typeof) {
          case REACT_PORTAL_TYPE:
            return "Portal";
          case REACT_CONTEXT_TYPE:
            return type.displayName || "Context";
          case REACT_CONSUMER_TYPE:
            return (type._context.displayName || "Context") + ".Consumer";
          case REACT_FORWARD_REF_TYPE:
            var innerType = type.render;
            type = type.displayName;
            type || (type = innerType.displayName || innerType.name || "", type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef");
            return type;
          case REACT_MEMO_TYPE:
            return innerType = type.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type.type) || "Memo";
          case REACT_LAZY_TYPE:
            innerType = type._payload;
            type = type._init;
            try {
              return getComponentNameFromType(type(innerType));
            } catch (x) {
            }
        }
      return null;
    }
    function getComponentNameFromOwner(owner) {
      return "number" === typeof owner.tag ? getComponentNameFromFiber(owner) : "string" === typeof owner.name ? owner.name : null;
    }
    function getComponentNameFromFiber(fiber) {
      var type = fiber.type;
      switch (fiber.tag) {
        case 31:
          return "Activity";
        case 24:
          return "Cache";
        case 9:
          return (type._context.displayName || "Context") + ".Consumer";
        case 10:
          return type.displayName || "Context";
        case 18:
          return "DehydratedFragment";
        case 11:
          return fiber = type.render, fiber = fiber.displayName || fiber.name || "", type.displayName || ("" !== fiber ? "ForwardRef(" + fiber + ")" : "ForwardRef");
        case 7:
          return "Fragment";
        case 26:
        case 27:
        case 5:
          return type;
        case 4:
          return "Portal";
        case 3:
          return "Root";
        case 6:
          return "Text";
        case 16:
          return getComponentNameFromType(type);
        case 8:
          return type === REACT_STRICT_MODE_TYPE ? "StrictMode" : "Mode";
        case 22:
          return "Offscreen";
        case 12:
          return "Profiler";
        case 21:
          return "Scope";
        case 13:
          return "Suspense";
        case 19:
          return "SuspenseList";
        case 25:
          return "TracingMarker";
        case 1:
        case 0:
        case 14:
        case 15:
          if ("function" === typeof type)
            return type.displayName || type.name || null;
          if ("string" === typeof type) return type;
          break;
        case 29:
          type = fiber._debugInfo;
          if (null != type) {
            for (var i2 = type.length - 1; 0 <= i2; i2--)
              if ("string" === typeof type[i2].name) return type[i2].name;
          }
          if (null !== fiber.return)
            return getComponentNameFromFiber(fiber.return);
      }
      return null;
    }
    function createCursor(defaultValue) {
      return { current: defaultValue };
    }
    function pop2(cursor, fiber) {
      0 > index$jscomp$0 ? console.error("Unexpected pop.") : (fiber !== fiberStack[index$jscomp$0] && console.error("Unexpected Fiber popped."), cursor.current = valueStack[index$jscomp$0], valueStack[index$jscomp$0] = null, fiberStack[index$jscomp$0] = null, index$jscomp$0--);
    }
    function push2(cursor, value2, fiber) {
      index$jscomp$0++;
      valueStack[index$jscomp$0] = cursor.current;
      fiberStack[index$jscomp$0] = fiber;
      cursor.current = value2;
    }
    function requiredContext(c2) {
      null === c2 && console.error(
        "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue."
      );
      return c2;
    }
    function pushHostContainer(fiber, nextRootInstance) {
      push2(rootInstanceStackCursor, nextRootInstance, fiber);
      push2(contextFiberStackCursor, fiber, fiber);
      push2(contextStackCursor, null, fiber);
      var nextRootContext = nextRootInstance.nodeType;
      switch (nextRootContext) {
        case 9:
        case 11:
          nextRootContext = 9 === nextRootContext ? "#document" : "#fragment";
          nextRootInstance = (nextRootInstance = nextRootInstance.documentElement) ? (nextRootInstance = nextRootInstance.namespaceURI) ? getOwnHostContext(nextRootInstance) : HostContextNamespaceNone : HostContextNamespaceNone;
          break;
        default:
          if (nextRootContext = nextRootInstance.tagName, nextRootInstance = nextRootInstance.namespaceURI)
            nextRootInstance = getOwnHostContext(nextRootInstance), nextRootInstance = getChildHostContextProd(
              nextRootInstance,
              nextRootContext
            );
          else
            switch (nextRootContext) {
              case "svg":
                nextRootInstance = HostContextNamespaceSvg;
                break;
              case "math":
                nextRootInstance = HostContextNamespaceMath;
                break;
              default:
                nextRootInstance = HostContextNamespaceNone;
            }
      }
      nextRootContext = nextRootContext.toLowerCase();
      nextRootContext = updatedAncestorInfoDev(null, nextRootContext);
      nextRootContext = {
        context: nextRootInstance,
        ancestorInfo: nextRootContext
      };
      pop2(contextStackCursor, fiber);
      push2(contextStackCursor, nextRootContext, fiber);
    }
    function popHostContainer(fiber) {
      pop2(contextStackCursor, fiber);
      pop2(contextFiberStackCursor, fiber);
      pop2(rootInstanceStackCursor, fiber);
    }
    function getHostContext() {
      return requiredContext(contextStackCursor.current);
    }
    function pushHostContext(fiber) {
      null !== fiber.memoizedState && push2(hostTransitionProviderCursor, fiber, fiber);
      var context = requiredContext(contextStackCursor.current);
      var type = fiber.type;
      var nextContext = getChildHostContextProd(context.context, type);
      type = updatedAncestorInfoDev(context.ancestorInfo, type);
      nextContext = { context: nextContext, ancestorInfo: type };
      context !== nextContext && (push2(contextFiberStackCursor, fiber, fiber), push2(contextStackCursor, nextContext, fiber));
    }
    function popHostContext(fiber) {
      contextFiberStackCursor.current === fiber && (pop2(contextStackCursor, fiber), pop2(contextFiberStackCursor, fiber));
      hostTransitionProviderCursor.current === fiber && (pop2(hostTransitionProviderCursor, fiber), HostTransitionContext._currentValue = NotPendingTransition);
    }
    function disabledLog() {
    }
    function disableLogs() {
      if (0 === disabledDepth) {
        prevLog = console.log;
        prevInfo = console.info;
        prevWarn = console.warn;
        prevError = console.error;
        prevGroup = console.group;
        prevGroupCollapsed = console.groupCollapsed;
        prevGroupEnd = console.groupEnd;
        var props = {
          configurable: true,
          enumerable: true,
          value: disabledLog,
          writable: true
        };
        Object.defineProperties(console, {
          info: props,
          log: props,
          warn: props,
          error: props,
          group: props,
          groupCollapsed: props,
          groupEnd: props
        });
      }
      disabledDepth++;
    }
    function reenableLogs() {
      disabledDepth--;
      if (0 === disabledDepth) {
        var props = { configurable: true, enumerable: true, writable: true };
        Object.defineProperties(console, {
          log: assign2({}, props, { value: prevLog }),
          info: assign2({}, props, { value: prevInfo }),
          warn: assign2({}, props, { value: prevWarn }),
          error: assign2({}, props, { value: prevError }),
          group: assign2({}, props, { value: prevGroup }),
          groupCollapsed: assign2({}, props, { value: prevGroupCollapsed }),
          groupEnd: assign2({}, props, { value: prevGroupEnd })
        });
      }
      0 > disabledDepth && console.error(
        "disabledDepth fell below zero. This is a bug in React. Please file an issue."
      );
    }
    function formatOwnerStack(error2) {
      var prevPrepareStackTrace = Error.prepareStackTrace;
      Error.prepareStackTrace = void 0;
      error2 = error2.stack;
      Error.prepareStackTrace = prevPrepareStackTrace;
      error2.startsWith("Error: react-stack-top-frame\n") && (error2 = error2.slice(29));
      prevPrepareStackTrace = error2.indexOf("\n");
      -1 !== prevPrepareStackTrace && (error2 = error2.slice(prevPrepareStackTrace + 1));
      prevPrepareStackTrace = error2.indexOf("react_stack_bottom_frame");
      -1 !== prevPrepareStackTrace && (prevPrepareStackTrace = error2.lastIndexOf(
        "\n",
        prevPrepareStackTrace
      ));
      if (-1 !== prevPrepareStackTrace)
        error2 = error2.slice(0, prevPrepareStackTrace);
      else return "";
      return error2;
    }
    function describeBuiltInComponentFrame(name2) {
      if (void 0 === prefix)
        try {
          throw Error();
        } catch (x) {
          var match3 = x.stack.trim().match(/\n( *(at )?)/);
          prefix = match3 && match3[1] || "";
          suffix = -1 < x.stack.indexOf("\n    at") ? " (<anonymous>)" : -1 < x.stack.indexOf("@") ? "@unknown:0:0" : "";
        }
      return "\n" + prefix + name2 + suffix;
    }
    function describeNativeComponentFrame(fn3, construct) {
      if (!fn3 || reentry) return "";
      var frame = componentFrameCache.get(fn3);
      if (void 0 !== frame) return frame;
      reentry = true;
      frame = Error.prepareStackTrace;
      Error.prepareStackTrace = void 0;
      var previousDispatcher2 = null;
      previousDispatcher2 = ReactSharedInternals.H;
      ReactSharedInternals.H = null;
      disableLogs();
      try {
        var RunInRootFrame = {
          DetermineComponentFrameRoot: function() {
            try {
              if (construct) {
                var Fake = function() {
                  throw Error();
                };
                Object.defineProperty(Fake.prototype, "props", {
                  set: function() {
                    throw Error();
                  }
                });
                if ("object" === typeof Reflect && Reflect.construct) {
                  try {
                    Reflect.construct(Fake, []);
                  } catch (x) {
                    var control = x;
                  }
                  Reflect.construct(fn3, [], Fake);
                } else {
                  try {
                    Fake.call();
                  } catch (x$0) {
                    control = x$0;
                  }
                  fn3.call(Fake.prototype);
                }
              } else {
                try {
                  throw Error();
                } catch (x$1) {
                  control = x$1;
                }
                (Fake = fn3()) && "function" === typeof Fake.catch && Fake.catch(function() {
                });
              }
            } catch (sample2) {
              if (sample2 && control && "string" === typeof sample2.stack)
                return [sample2.stack, control.stack];
            }
            return [null, null];
          }
        };
        RunInRootFrame.DetermineComponentFrameRoot.displayName = "DetermineComponentFrameRoot";
        var namePropDescriptor = Object.getOwnPropertyDescriptor(
          RunInRootFrame.DetermineComponentFrameRoot,
          "name"
        );
        namePropDescriptor && namePropDescriptor.configurable && Object.defineProperty(
          RunInRootFrame.DetermineComponentFrameRoot,
          "name",
          { value: "DetermineComponentFrameRoot" }
        );
        var _RunInRootFrame$Deter = RunInRootFrame.DetermineComponentFrameRoot(), sampleStack = _RunInRootFrame$Deter[0], controlStack = _RunInRootFrame$Deter[1];
        if (sampleStack && controlStack) {
          var sampleLines = sampleStack.split("\n"), controlLines = controlStack.split("\n");
          for (_RunInRootFrame$Deter = namePropDescriptor = 0; namePropDescriptor < sampleLines.length && !sampleLines[namePropDescriptor].includes(
            "DetermineComponentFrameRoot"
          ); )
            namePropDescriptor++;
          for (; _RunInRootFrame$Deter < controlLines.length && !controlLines[_RunInRootFrame$Deter].includes(
            "DetermineComponentFrameRoot"
          ); )
            _RunInRootFrame$Deter++;
          if (namePropDescriptor === sampleLines.length || _RunInRootFrame$Deter === controlLines.length)
            for (namePropDescriptor = sampleLines.length - 1, _RunInRootFrame$Deter = controlLines.length - 1; 1 <= namePropDescriptor && 0 <= _RunInRootFrame$Deter && sampleLines[namePropDescriptor] !== controlLines[_RunInRootFrame$Deter]; )
              _RunInRootFrame$Deter--;
          for (; 1 <= namePropDescriptor && 0 <= _RunInRootFrame$Deter; namePropDescriptor--, _RunInRootFrame$Deter--)
            if (sampleLines[namePropDescriptor] !== controlLines[_RunInRootFrame$Deter]) {
              if (1 !== namePropDescriptor || 1 !== _RunInRootFrame$Deter) {
                do
                  if (namePropDescriptor--, _RunInRootFrame$Deter--, 0 > _RunInRootFrame$Deter || sampleLines[namePropDescriptor] !== controlLines[_RunInRootFrame$Deter]) {
                    var _frame = "\n" + sampleLines[namePropDescriptor].replace(
                      " at new ",
                      " at "
                    );
                    fn3.displayName && _frame.includes("<anonymous>") && (_frame = _frame.replace("<anonymous>", fn3.displayName));
                    "function" === typeof fn3 && componentFrameCache.set(fn3, _frame);
                    return _frame;
                  }
                while (1 <= namePropDescriptor && 0 <= _RunInRootFrame$Deter);
              }
              break;
            }
        }
      } finally {
        reentry = false, ReactSharedInternals.H = previousDispatcher2, reenableLogs(), Error.prepareStackTrace = frame;
      }
      sampleLines = (sampleLines = fn3 ? fn3.displayName || fn3.name : "") ? describeBuiltInComponentFrame(sampleLines) : "";
      "function" === typeof fn3 && componentFrameCache.set(fn3, sampleLines);
      return sampleLines;
    }
    function describeFiber(fiber, childFiber) {
      switch (fiber.tag) {
        case 26:
        case 27:
        case 5:
          return describeBuiltInComponentFrame(fiber.type);
        case 16:
          return describeBuiltInComponentFrame("Lazy");
        case 13:
          return fiber.child !== childFiber && null !== childFiber ? describeBuiltInComponentFrame("Suspense Fallback") : describeBuiltInComponentFrame("Suspense");
        case 19:
          return describeBuiltInComponentFrame("SuspenseList");
        case 0:
        case 15:
          return describeNativeComponentFrame(fiber.type, false);
        case 11:
          return describeNativeComponentFrame(fiber.type.render, false);
        case 1:
          return describeNativeComponentFrame(fiber.type, true);
        case 31:
          return describeBuiltInComponentFrame("Activity");
        default:
          return "";
      }
    }
    function getStackByFiberInDevAndProd(workInProgress2) {
      try {
        var info = "", previous = null;
        do {
          info += describeFiber(workInProgress2, previous);
          var debugInfo = workInProgress2._debugInfo;
          if (debugInfo)
            for (var i2 = debugInfo.length - 1; 0 <= i2; i2--) {
              var entry2 = debugInfo[i2];
              if ("string" === typeof entry2.name) {
                var JSCompiler_temp_const = info;
                a: {
                  var name2 = entry2.name, env = entry2.env, location = entry2.debugLocation;
                  if (null != location) {
                    var childStack = formatOwnerStack(location), idx = childStack.lastIndexOf("\n"), lastLine = -1 === idx ? childStack : childStack.slice(idx + 1);
                    if (-1 !== lastLine.indexOf(name2)) {
                      var JSCompiler_inline_result = "\n" + lastLine;
                      break a;
                    }
                  }
                  JSCompiler_inline_result = describeBuiltInComponentFrame(
                    name2 + (env ? " [" + env + "]" : "")
                  );
                }
                info = JSCompiler_temp_const + JSCompiler_inline_result;
              }
            }
          previous = workInProgress2;
          workInProgress2 = workInProgress2.return;
        } while (workInProgress2);
        return info;
      } catch (x) {
        return "\nError generating stack: " + x.message + "\n" + x.stack;
      }
    }
    function describeFunctionComponentFrameWithoutLineNumber(fn3) {
      return (fn3 = fn3 ? fn3.displayName || fn3.name : "") ? describeBuiltInComponentFrame(fn3) : "";
    }
    function getCurrentFiberOwnerNameInDevOrNull() {
      if (null === current3) return null;
      var owner = current3._debugOwner;
      return null != owner ? getComponentNameFromOwner(owner) : null;
    }
    function getCurrentFiberStackInDev() {
      if (null === current3) return "";
      var workInProgress2 = current3;
      try {
        var info = "";
        6 === workInProgress2.tag && (workInProgress2 = workInProgress2.return);
        switch (workInProgress2.tag) {
          case 26:
          case 27:
          case 5:
            info += describeBuiltInComponentFrame(workInProgress2.type);
            break;
          case 13:
            info += describeBuiltInComponentFrame("Suspense");
            break;
          case 19:
            info += describeBuiltInComponentFrame("SuspenseList");
            break;
          case 31:
            info += describeBuiltInComponentFrame("Activity");
            break;
          case 30:
          case 0:
          case 15:
          case 1:
            workInProgress2._debugOwner || "" !== info || (info += describeFunctionComponentFrameWithoutLineNumber(
              workInProgress2.type
            ));
            break;
          case 11:
            workInProgress2._debugOwner || "" !== info || (info += describeFunctionComponentFrameWithoutLineNumber(
              workInProgress2.type.render
            ));
        }
        for (; workInProgress2; )
          if ("number" === typeof workInProgress2.tag) {
            var fiber = workInProgress2;
            workInProgress2 = fiber._debugOwner;
            var debugStack = fiber._debugStack;
            if (workInProgress2 && debugStack) {
              var formattedStack = formatOwnerStack(debugStack);
              "" !== formattedStack && (info += "\n" + formattedStack);
            }
          } else if (null != workInProgress2.debugStack) {
            var ownerStack = workInProgress2.debugStack;
            (workInProgress2 = workInProgress2.owner) && ownerStack && (info += "\n" + formatOwnerStack(ownerStack));
          } else break;
        var JSCompiler_inline_result = info;
      } catch (x) {
        JSCompiler_inline_result = "\nError generating stack: " + x.message + "\n" + x.stack;
      }
      return JSCompiler_inline_result;
    }
    function runWithFiberInDEV(fiber, callback, arg0, arg1, arg2, arg3, arg4) {
      var previousFiber = current3;
      setCurrentFiber(fiber);
      try {
        return null !== fiber && fiber._debugTask ? fiber._debugTask.run(
          callback.bind(null, arg0, arg1, arg2, arg3, arg4)
        ) : callback(arg0, arg1, arg2, arg3, arg4);
      } finally {
        setCurrentFiber(previousFiber);
      }
      throw Error(
        "runWithFiberInDEV should never be called in production. This is a bug in React."
      );
    }
    function setCurrentFiber(fiber) {
      ReactSharedInternals.getCurrentStack = null === fiber ? null : getCurrentFiberStackInDev;
      isRendering = false;
      current3 = fiber;
    }
    function typeName(value2) {
      return "function" === typeof Symbol && Symbol.toStringTag && value2[Symbol.toStringTag] || value2.constructor.name || "Object";
    }
    function willCoercionThrow(value2) {
      try {
        return testStringCoercion(value2), false;
      } catch (e) {
        return true;
      }
    }
    function testStringCoercion(value2) {
      return "" + value2;
    }
    function checkAttributeStringCoercion(value2, attributeName) {
      if (willCoercionThrow(value2))
        return console.error(
          "The provided `%s` attribute is an unsupported type %s. This value must be coerced to a string before using it here.",
          attributeName,
          typeName(value2)
        ), testStringCoercion(value2);
    }
    function checkCSSPropertyStringCoercion(value2, propName) {
      if (willCoercionThrow(value2))
        return console.error(
          "The provided `%s` CSS property is an unsupported type %s. This value must be coerced to a string before using it here.",
          propName,
          typeName(value2)
        ), testStringCoercion(value2);
    }
    function checkFormFieldValueStringCoercion(value2) {
      if (willCoercionThrow(value2))
        return console.error(
          "Form field values (value, checked, defaultValue, or defaultChecked props) must be strings, not %s. This value must be coerced to a string before using it here.",
          typeName(value2)
        ), testStringCoercion(value2);
    }
    function injectInternals(internals) {
      if ("undefined" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__) return false;
      var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
      if (hook.isDisabled) return true;
      if (!hook.supportsFiber)
        return console.error(
          "The installed version of React DevTools is too old and will not work with the current version of React. Please update React DevTools. https://react.dev/link/react-devtools"
        ), true;
      try {
        rendererID = hook.inject(internals), injectedHook = hook;
      } catch (err) {
        console.error("React instrumentation encountered an error: %o.", err);
      }
      return hook.checkDCE ? true : false;
    }
    function setIsStrictModeForDevtools(newIsStrictMode) {
      "function" === typeof log$12 && unstable_setDisableYieldValue(newIsStrictMode);
      if (injectedHook && "function" === typeof injectedHook.setStrictMode)
        try {
          injectedHook.setStrictMode(rendererID, newIsStrictMode);
        } catch (err) {
          hasLoggedError || (hasLoggedError = true, console.error(
            "React instrumentation encountered an error: %o",
            err
          ));
        }
    }
    function clz32Fallback(x) {
      x >>>= 0;
      return 0 === x ? 32 : 31 - (log3(x) / LN2 | 0) | 0;
    }
    function getHighestPriorityLanes(lanes) {
      var pendingSyncLanes = lanes & 42;
      if (0 !== pendingSyncLanes) return pendingSyncLanes;
      switch (lanes & -lanes) {
        case 1:
          return 1;
        case 2:
          return 2;
        case 4:
          return 4;
        case 8:
          return 8;
        case 16:
          return 16;
        case 32:
          return 32;
        case 64:
          return 64;
        case 128:
          return 128;
        case 256:
        case 512:
        case 1024:
        case 2048:
        case 4096:
        case 8192:
        case 16384:
        case 32768:
        case 65536:
        case 131072:
          return lanes & 261888;
        case 262144:
        case 524288:
        case 1048576:
        case 2097152:
          return lanes & 3932160;
        case 4194304:
        case 8388608:
        case 16777216:
        case 33554432:
          return lanes & 62914560;
        case 67108864:
          return 67108864;
        case 134217728:
          return 134217728;
        case 268435456:
          return 268435456;
        case 536870912:
          return 536870912;
        case 1073741824:
          return 0;
        default:
          return console.error(
            "Should have found matching lanes. This is a bug in React."
          ), lanes;
      }
    }
    function getNextLanes(root22, wipLanes, rootHasPendingCommit) {
      var pendingLanes = root22.pendingLanes;
      if (0 === pendingLanes) return 0;
      var nextLanes = 0, suspendedLanes = root22.suspendedLanes, pingedLanes = root22.pingedLanes;
      root22 = root22.warmLanes;
      var nonIdlePendingLanes = pendingLanes & 134217727;
      0 !== nonIdlePendingLanes ? (pendingLanes = nonIdlePendingLanes & ~suspendedLanes, 0 !== pendingLanes ? nextLanes = getHighestPriorityLanes(pendingLanes) : (pingedLanes &= nonIdlePendingLanes, 0 !== pingedLanes ? nextLanes = getHighestPriorityLanes(pingedLanes) : rootHasPendingCommit || (rootHasPendingCommit = nonIdlePendingLanes & ~root22, 0 !== rootHasPendingCommit && (nextLanes = getHighestPriorityLanes(rootHasPendingCommit))))) : (nonIdlePendingLanes = pendingLanes & ~suspendedLanes, 0 !== nonIdlePendingLanes ? nextLanes = getHighestPriorityLanes(nonIdlePendingLanes) : 0 !== pingedLanes ? nextLanes = getHighestPriorityLanes(pingedLanes) : rootHasPendingCommit || (rootHasPendingCommit = pendingLanes & ~root22, 0 !== rootHasPendingCommit && (nextLanes = getHighestPriorityLanes(rootHasPendingCommit))));
      return 0 === nextLanes ? 0 : 0 !== wipLanes && wipLanes !== nextLanes && 0 === (wipLanes & suspendedLanes) && (suspendedLanes = nextLanes & -nextLanes, rootHasPendingCommit = wipLanes & -wipLanes, suspendedLanes >= rootHasPendingCommit || 32 === suspendedLanes && 0 !== (rootHasPendingCommit & 4194048)) ? wipLanes : nextLanes;
    }
    function checkIfRootIsPrerendering(root22, renderLanes2) {
      return 0 === (root22.pendingLanes & ~(root22.suspendedLanes & ~root22.pingedLanes) & renderLanes2);
    }
    function computeExpirationTime(lane, currentTime) {
      switch (lane) {
        case 1:
        case 2:
        case 4:
        case 8:
        case 64:
          return currentTime + 250;
        case 16:
        case 32:
        case 128:
        case 256:
        case 512:
        case 1024:
        case 2048:
        case 4096:
        case 8192:
        case 16384:
        case 32768:
        case 65536:
        case 131072:
        case 262144:
        case 524288:
        case 1048576:
        case 2097152:
          return currentTime + 5e3;
        case 4194304:
        case 8388608:
        case 16777216:
        case 33554432:
          return -1;
        case 67108864:
        case 134217728:
        case 268435456:
        case 536870912:
        case 1073741824:
          return -1;
        default:
          return console.error(
            "Should have found matching lanes. This is a bug in React."
          ), -1;
      }
    }
    function claimNextRetryLane() {
      var lane = nextRetryLane;
      nextRetryLane <<= 1;
      0 === (nextRetryLane & 62914560) && (nextRetryLane = 4194304);
      return lane;
    }
    function createLaneMap(initial) {
      for (var laneMap = [], i2 = 0; 31 > i2; i2++) laneMap.push(initial);
      return laneMap;
    }
    function markRootUpdated$1(root22, updateLane) {
      root22.pendingLanes |= updateLane;
      268435456 !== updateLane && (root22.suspendedLanes = 0, root22.pingedLanes = 0, root22.warmLanes = 0);
    }
    function markRootFinished(root22, finishedLanes, remainingLanes, spawnedLane, updatedLanes, suspendedRetryLanes) {
      var previouslyPendingLanes = root22.pendingLanes;
      root22.pendingLanes = remainingLanes;
      root22.suspendedLanes = 0;
      root22.pingedLanes = 0;
      root22.warmLanes = 0;
      root22.expiredLanes &= remainingLanes;
      root22.entangledLanes &= remainingLanes;
      root22.errorRecoveryDisabledLanes &= remainingLanes;
      root22.shellSuspendCounter = 0;
      var entanglements = root22.entanglements, expirationTimes = root22.expirationTimes, hiddenUpdates = root22.hiddenUpdates;
      for (remainingLanes = previouslyPendingLanes & ~remainingLanes; 0 < remainingLanes; ) {
        var index = 31 - clz322(remainingLanes), lane = 1 << index;
        entanglements[index] = 0;
        expirationTimes[index] = -1;
        var hiddenUpdatesForLane = hiddenUpdates[index];
        if (null !== hiddenUpdatesForLane)
          for (hiddenUpdates[index] = null, index = 0; index < hiddenUpdatesForLane.length; index++) {
            var update2 = hiddenUpdatesForLane[index];
            null !== update2 && (update2.lane &= -536870913);
          }
        remainingLanes &= ~lane;
      }
      0 !== spawnedLane && markSpawnedDeferredLane(root22, spawnedLane, 0);
      0 !== suspendedRetryLanes && 0 === updatedLanes && 0 !== root22.tag && (root22.suspendedLanes |= suspendedRetryLanes & ~(previouslyPendingLanes & ~finishedLanes));
    }
    function markSpawnedDeferredLane(root22, spawnedLane, entangledLanes) {
      root22.pendingLanes |= spawnedLane;
      root22.suspendedLanes &= ~spawnedLane;
      var spawnedLaneIndex = 31 - clz322(spawnedLane);
      root22.entangledLanes |= spawnedLane;
      root22.entanglements[spawnedLaneIndex] = root22.entanglements[spawnedLaneIndex] | 1073741824 | entangledLanes & 261930;
    }
    function markRootEntangled(root22, entangledLanes) {
      var rootEntangledLanes = root22.entangledLanes |= entangledLanes;
      for (root22 = root22.entanglements; rootEntangledLanes; ) {
        var index = 31 - clz322(rootEntangledLanes), lane = 1 << index;
        lane & entangledLanes | root22[index] & entangledLanes && (root22[index] |= entangledLanes);
        rootEntangledLanes &= ~lane;
      }
    }
    function getBumpedLaneForHydration(root22, renderLanes2) {
      var renderLane = renderLanes2 & -renderLanes2;
      renderLane = 0 !== (renderLane & 42) ? 1 : getBumpedLaneForHydrationByLane(renderLane);
      return 0 !== (renderLane & (root22.suspendedLanes | renderLanes2)) ? 0 : renderLane;
    }
    function getBumpedLaneForHydrationByLane(lane) {
      switch (lane) {
        case 2:
          lane = 1;
          break;
        case 8:
          lane = 4;
          break;
        case 32:
          lane = 16;
          break;
        case 256:
        case 512:
        case 1024:
        case 2048:
        case 4096:
        case 8192:
        case 16384:
        case 32768:
        case 65536:
        case 131072:
        case 262144:
        case 524288:
        case 1048576:
        case 2097152:
        case 4194304:
        case 8388608:
        case 16777216:
        case 33554432:
          lane = 128;
          break;
        case 268435456:
          lane = 134217728;
          break;
        default:
          lane = 0;
      }
      return lane;
    }
    function addFiberToLanesMap(root22, fiber, lanes) {
      if (isDevToolsPresent)
        for (root22 = root22.pendingUpdatersLaneMap; 0 < lanes; ) {
          var index = 31 - clz322(lanes), lane = 1 << index;
          root22[index].add(fiber);
          lanes &= ~lane;
        }
    }
    function movePendingFibersToMemoized(root22, lanes) {
      if (isDevToolsPresent)
        for (var pendingUpdatersLaneMap = root22.pendingUpdatersLaneMap, memoizedUpdaters = root22.memoizedUpdaters; 0 < lanes; ) {
          var index = 31 - clz322(lanes);
          root22 = 1 << index;
          index = pendingUpdatersLaneMap[index];
          0 < index.size && (index.forEach(function(fiber) {
            var alternate = fiber.alternate;
            null !== alternate && memoizedUpdaters.has(alternate) || memoizedUpdaters.add(fiber);
          }), index.clear());
          lanes &= ~root22;
        }
    }
    function lanesToEventPriority(lanes) {
      lanes &= -lanes;
      return DiscreteEventPriority < lanes ? ContinuousEventPriority < lanes ? 0 !== (lanes & 134217727) ? DefaultEventPriority : IdleEventPriority : ContinuousEventPriority : DiscreteEventPriority;
    }
    function resolveUpdatePriority() {
      var updatePriority = ReactDOMSharedInternals.p;
      if (0 !== updatePriority) return updatePriority;
      updatePriority = window.event;
      return void 0 === updatePriority ? DefaultEventPriority : getEventPriority(updatePriority.type);
    }
    function runWithPriority(priority, fn3) {
      var previousPriority = ReactDOMSharedInternals.p;
      try {
        return ReactDOMSharedInternals.p = priority, fn3();
      } finally {
        ReactDOMSharedInternals.p = previousPriority;
      }
    }
    function detachDeletedInstance(node2) {
      delete node2[internalInstanceKey];
      delete node2[internalPropsKey];
      delete node2[internalEventHandlersKey];
      delete node2[internalEventHandlerListenersKey];
      delete node2[internalEventHandlesSetKey];
    }
    function getClosestInstanceFromNode(targetNode) {
      var targetInst = targetNode[internalInstanceKey];
      if (targetInst) return targetInst;
      for (var parentNode = targetNode.parentNode; parentNode; ) {
        if (targetInst = parentNode[internalContainerInstanceKey] || parentNode[internalInstanceKey]) {
          parentNode = targetInst.alternate;
          if (null !== targetInst.child || null !== parentNode && null !== parentNode.child)
            for (targetNode = getParentHydrationBoundary(targetNode); null !== targetNode; ) {
              if (parentNode = targetNode[internalInstanceKey])
                return parentNode;
              targetNode = getParentHydrationBoundary(targetNode);
            }
          return targetInst;
        }
        targetNode = parentNode;
        parentNode = targetNode.parentNode;
      }
      return null;
    }
    function getInstanceFromNode(node2) {
      if (node2 = node2[internalInstanceKey] || node2[internalContainerInstanceKey]) {
        var tag = node2.tag;
        if (5 === tag || 6 === tag || 13 === tag || 31 === tag || 26 === tag || 27 === tag || 3 === tag)
          return node2;
      }
      return null;
    }
    function getNodeFromInstance(inst) {
      var tag = inst.tag;
      if (5 === tag || 26 === tag || 27 === tag || 6 === tag)
        return inst.stateNode;
      throw Error("getNodeFromInstance: Invalid argument.");
    }
    function getResourcesFromRoot(root22) {
      var resources = root22[internalRootNodeResourcesKey];
      resources || (resources = root22[internalRootNodeResourcesKey] = { hoistableStyles: /* @__PURE__ */ new Map(), hoistableScripts: /* @__PURE__ */ new Map() });
      return resources;
    }
    function markNodeAsHoistable(node2) {
      node2[internalHoistableMarker] = true;
    }
    function registerTwoPhaseEvent(registrationName, dependencies) {
      registerDirectEvent(registrationName, dependencies);
      registerDirectEvent(registrationName + "Capture", dependencies);
    }
    function registerDirectEvent(registrationName, dependencies) {
      registrationNameDependencies[registrationName] && console.error(
        "EventRegistry: More than one plugin attempted to publish the same registration name, `%s`.",
        registrationName
      );
      registrationNameDependencies[registrationName] = dependencies;
      var lowerCasedName = registrationName.toLowerCase();
      possibleRegistrationNames[lowerCasedName] = registrationName;
      "onDoubleClick" === registrationName && (possibleRegistrationNames.ondblclick = registrationName);
      for (registrationName = 0; registrationName < dependencies.length; registrationName++)
        allNativeEvents.add(dependencies[registrationName]);
    }
    function checkControlledValueProps(tagName, props) {
      hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || null == props.value || ("select" === tagName ? console.error(
        "You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set `onChange`."
      ) : console.error(
        "You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`."
      ));
      props.onChange || props.readOnly || props.disabled || null == props.checked || console.error(
        "You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`."
      );
    }
    function isAttributeNameSafe(attributeName) {
      if (hasOwnProperty2.call(validatedAttributeNameCache, attributeName))
        return true;
      if (hasOwnProperty2.call(illegalAttributeNameCache, attributeName))
        return false;
      if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName))
        return validatedAttributeNameCache[attributeName] = true;
      illegalAttributeNameCache[attributeName] = true;
      console.error("Invalid attribute name: `%s`", attributeName);
      return false;
    }
    function getValueForAttributeOnCustomComponent(node2, name2, expected) {
      if (isAttributeNameSafe(name2)) {
        if (!node2.hasAttribute(name2)) {
          switch (typeof expected) {
            case "symbol":
            case "object":
              return expected;
            case "function":
              return expected;
            case "boolean":
              if (false === expected) return expected;
          }
          return void 0 === expected ? void 0 : null;
        }
        node2 = node2.getAttribute(name2);
        if ("" === node2 && true === expected) return true;
        checkAttributeStringCoercion(expected, name2);
        return node2 === "" + expected ? expected : node2;
      }
    }
    function setValueForAttribute(node2, name2, value2) {
      if (isAttributeNameSafe(name2))
        if (null === value2) node2.removeAttribute(name2);
        else {
          switch (typeof value2) {
            case "undefined":
            case "function":
            case "symbol":
              node2.removeAttribute(name2);
              return;
            case "boolean":
              var prefix2 = name2.toLowerCase().slice(0, 5);
              if ("data-" !== prefix2 && "aria-" !== prefix2) {
                node2.removeAttribute(name2);
                return;
              }
          }
          checkAttributeStringCoercion(value2, name2);
          node2.setAttribute(name2, "" + value2);
        }
    }
    function setValueForKnownAttribute(node2, name2, value2) {
      if (null === value2) node2.removeAttribute(name2);
      else {
        switch (typeof value2) {
          case "undefined":
          case "function":
          case "symbol":
          case "boolean":
            node2.removeAttribute(name2);
            return;
        }
        checkAttributeStringCoercion(value2, name2);
        node2.setAttribute(name2, "" + value2);
      }
    }
    function setValueForNamespacedAttribute(node2, namespace, name2, value2) {
      if (null === value2) node2.removeAttribute(name2);
      else {
        switch (typeof value2) {
          case "undefined":
          case "function":
          case "symbol":
          case "boolean":
            node2.removeAttribute(name2);
            return;
        }
        checkAttributeStringCoercion(value2, name2);
        node2.setAttributeNS(namespace, name2, "" + value2);
      }
    }
    function getToStringValue(value2) {
      switch (typeof value2) {
        case "bigint":
        case "boolean":
        case "number":
        case "string":
        case "undefined":
          return value2;
        case "object":
          return checkFormFieldValueStringCoercion(value2), value2;
        default:
          return "";
      }
    }
    function isCheckable(elem) {
      var type = elem.type;
      return (elem = elem.nodeName) && "input" === elem.toLowerCase() && ("checkbox" === type || "radio" === type);
    }
    function trackValueOnNode(node2, valueField, currentValue) {
      var descriptor = Object.getOwnPropertyDescriptor(
        node2.constructor.prototype,
        valueField
      );
      if (!node2.hasOwnProperty(valueField) && "undefined" !== typeof descriptor && "function" === typeof descriptor.get && "function" === typeof descriptor.set) {
        var get2 = descriptor.get, set3 = descriptor.set;
        Object.defineProperty(node2, valueField, {
          configurable: true,
          get: function() {
            return get2.call(this);
          },
          set: function(value2) {
            checkFormFieldValueStringCoercion(value2);
            currentValue = "" + value2;
            set3.call(this, value2);
          }
        });
        Object.defineProperty(node2, valueField, {
          enumerable: descriptor.enumerable
        });
        return {
          getValue: function() {
            return currentValue;
          },
          setValue: function(value2) {
            checkFormFieldValueStringCoercion(value2);
            currentValue = "" + value2;
          },
          stopTracking: function() {
            node2._valueTracker = null;
            delete node2[valueField];
          }
        };
      }
    }
    function track(node2) {
      if (!node2._valueTracker) {
        var valueField = isCheckable(node2) ? "checked" : "value";
        node2._valueTracker = trackValueOnNode(
          node2,
          valueField,
          "" + node2[valueField]
        );
      }
    }
    function updateValueIfChanged(node2) {
      if (!node2) return false;
      var tracker = node2._valueTracker;
      if (!tracker) return true;
      var lastValue = tracker.getValue();
      var value2 = "";
      node2 && (value2 = isCheckable(node2) ? node2.checked ? "true" : "false" : node2.value);
      node2 = value2;
      return node2 !== lastValue ? (tracker.setValue(node2), true) : false;
    }
    function getActiveElement(doc) {
      doc = doc || ("undefined" !== typeof document ? document : void 0);
      if ("undefined" === typeof doc) return null;
      try {
        return doc.activeElement || doc.body;
      } catch (e) {
        return doc.body;
      }
    }
    function escapeSelectorAttributeValueInsideDoubleQuotes(value2) {
      return value2.replace(
        escapeSelectorAttributeValueInsideDoubleQuotesRegex,
        function(ch) {
          return "\\" + ch.charCodeAt(0).toString(16) + " ";
        }
      );
    }
    function validateInputProps(element, props) {
      void 0 === props.checked || void 0 === props.defaultChecked || didWarnCheckedDefaultChecked || (console.error(
        "%s contains an input of type %s with both checked and defaultChecked props. Input elements must be either controlled or uncontrolled (specify either the checked prop, or the defaultChecked prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://react.dev/link/controlled-components",
        getCurrentFiberOwnerNameInDevOrNull() || "A component",
        props.type
      ), didWarnCheckedDefaultChecked = true);
      void 0 === props.value || void 0 === props.defaultValue || didWarnValueDefaultValue$1 || (console.error(
        "%s contains an input of type %s with both value and defaultValue props. Input elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://react.dev/link/controlled-components",
        getCurrentFiberOwnerNameInDevOrNull() || "A component",
        props.type
      ), didWarnValueDefaultValue$1 = true);
    }
    function updateInput(element, value2, defaultValue, lastDefaultValue, checked, defaultChecked, type, name2) {
      element.name = "";
      null != type && "function" !== typeof type && "symbol" !== typeof type && "boolean" !== typeof type ? (checkAttributeStringCoercion(type, "type"), element.type = type) : element.removeAttribute("type");
      if (null != value2)
        if ("number" === type) {
          if (0 === value2 && "" === element.value || element.value != value2)
            element.value = "" + getToStringValue(value2);
        } else
          element.value !== "" + getToStringValue(value2) && (element.value = "" + getToStringValue(value2));
      else
        "submit" !== type && "reset" !== type || element.removeAttribute("value");
      null != value2 ? setDefaultValue(element, type, getToStringValue(value2)) : null != defaultValue ? setDefaultValue(element, type, getToStringValue(defaultValue)) : null != lastDefaultValue && element.removeAttribute("value");
      null == checked && null != defaultChecked && (element.defaultChecked = !!defaultChecked);
      null != checked && (element.checked = checked && "function" !== typeof checked && "symbol" !== typeof checked);
      null != name2 && "function" !== typeof name2 && "symbol" !== typeof name2 && "boolean" !== typeof name2 ? (checkAttributeStringCoercion(name2, "name"), element.name = "" + getToStringValue(name2)) : element.removeAttribute("name");
    }
    function initInput(element, value2, defaultValue, checked, defaultChecked, type, name2, isHydrating2) {
      null != type && "function" !== typeof type && "symbol" !== typeof type && "boolean" !== typeof type && (checkAttributeStringCoercion(type, "type"), element.type = type);
      if (null != value2 || null != defaultValue) {
        if (!("submit" !== type && "reset" !== type || void 0 !== value2 && null !== value2)) {
          track(element);
          return;
        }
        defaultValue = null != defaultValue ? "" + getToStringValue(defaultValue) : "";
        value2 = null != value2 ? "" + getToStringValue(value2) : defaultValue;
        isHydrating2 || value2 === element.value || (element.value = value2);
        element.defaultValue = value2;
      }
      checked = null != checked ? checked : defaultChecked;
      checked = "function" !== typeof checked && "symbol" !== typeof checked && !!checked;
      element.checked = isHydrating2 ? element.checked : !!checked;
      element.defaultChecked = !!checked;
      null != name2 && "function" !== typeof name2 && "symbol" !== typeof name2 && "boolean" !== typeof name2 && (checkAttributeStringCoercion(name2, "name"), element.name = name2);
      track(element);
    }
    function setDefaultValue(node2, type, value2) {
      "number" === type && getActiveElement(node2.ownerDocument) === node2 || node2.defaultValue === "" + value2 || (node2.defaultValue = "" + value2);
    }
    function validateOptionProps(element, props) {
      null == props.value && ("object" === typeof props.children && null !== props.children ? React.Children.forEach(props.children, function(child) {
        null == child || "string" === typeof child || "number" === typeof child || "bigint" === typeof child || didWarnInvalidChild || (didWarnInvalidChild = true, console.error(
          "Cannot infer the option value of complex children. Pass a `value` prop or use a plain string as children to <option>."
        ));
      }) : null == props.dangerouslySetInnerHTML || didWarnInvalidInnerHTML || (didWarnInvalidInnerHTML = true, console.error(
        "Pass a `value` prop if you set dangerouslyInnerHTML so React knows which value should be selected."
      )));
      null == props.selected || didWarnSelectedSetOnOption || (console.error(
        "Use the `defaultValue` or `value` props on <select> instead of setting `selected` on <option>."
      ), didWarnSelectedSetOnOption = true);
    }
    function getDeclarationErrorAddendum() {
      var ownerName = getCurrentFiberOwnerNameInDevOrNull();
      return ownerName ? "\n\nCheck the render method of `" + ownerName + "`." : "";
    }
    function updateOptions(node2, multiple, propValue, setDefaultSelected) {
      node2 = node2.options;
      if (multiple) {
        multiple = {};
        for (var i2 = 0; i2 < propValue.length; i2++)
          multiple["$" + propValue[i2]] = true;
        for (propValue = 0; propValue < node2.length; propValue++)
          i2 = multiple.hasOwnProperty("$" + node2[propValue].value), node2[propValue].selected !== i2 && (node2[propValue].selected = i2), i2 && setDefaultSelected && (node2[propValue].defaultSelected = true);
      } else {
        propValue = "" + getToStringValue(propValue);
        multiple = null;
        for (i2 = 0; i2 < node2.length; i2++) {
          if (node2[i2].value === propValue) {
            node2[i2].selected = true;
            setDefaultSelected && (node2[i2].defaultSelected = true);
            return;
          }
          null !== multiple || node2[i2].disabled || (multiple = node2[i2]);
        }
        null !== multiple && (multiple.selected = true);
      }
    }
    function validateSelectProps(element, props) {
      for (element = 0; element < valuePropNames.length; element++) {
        var propName = valuePropNames[element];
        if (null != props[propName]) {
          var propNameIsArray = isArrayImpl(props[propName]);
          props.multiple && !propNameIsArray ? console.error(
            "The `%s` prop supplied to <select> must be an array if `multiple` is true.%s",
            propName,
            getDeclarationErrorAddendum()
          ) : !props.multiple && propNameIsArray && console.error(
            "The `%s` prop supplied to <select> must be a scalar value if `multiple` is false.%s",
            propName,
            getDeclarationErrorAddendum()
          );
        }
      }
      void 0 === props.value || void 0 === props.defaultValue || didWarnValueDefaultValue || (console.error(
        "Select elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled select element and remove one of these props. More info: https://react.dev/link/controlled-components"
      ), didWarnValueDefaultValue = true);
    }
    function validateTextareaProps(element, props) {
      void 0 === props.value || void 0 === props.defaultValue || didWarnValDefaultVal || (console.error(
        "%s contains a textarea with both value and defaultValue props. Textarea elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled textarea and remove one of these props. More info: https://react.dev/link/controlled-components",
        getCurrentFiberOwnerNameInDevOrNull() || "A component"
      ), didWarnValDefaultVal = true);
      null != props.children && null == props.value && console.error(
        "Use the `defaultValue` or `value` props instead of setting children on <textarea>."
      );
    }
    function updateTextarea(element, value2, defaultValue) {
      if (null != value2 && (value2 = "" + getToStringValue(value2), value2 !== element.value && (element.value = value2), null == defaultValue)) {
        element.defaultValue !== value2 && (element.defaultValue = value2);
        return;
      }
      element.defaultValue = null != defaultValue ? "" + getToStringValue(defaultValue) : "";
    }
    function initTextarea(element, value2, defaultValue, children2) {
      if (null == value2) {
        if (null != children2) {
          if (null != defaultValue)
            throw Error(
              "If you supply `defaultValue` on a <textarea>, do not pass children."
            );
          if (isArrayImpl(children2)) {
            if (1 < children2.length)
              throw Error("<textarea> can only have at most one child.");
            children2 = children2[0];
          }
          defaultValue = children2;
        }
        null == defaultValue && (defaultValue = "");
        value2 = defaultValue;
      }
      defaultValue = getToStringValue(value2);
      element.defaultValue = defaultValue;
      children2 = element.textContent;
      children2 === defaultValue && "" !== children2 && null !== children2 && (element.value = children2);
      track(element);
    }
    function findNotableNode(node2, indent) {
      return void 0 === node2.serverProps && 0 === node2.serverTail.length && 1 === node2.children.length && 3 < node2.distanceFromLeaf && node2.distanceFromLeaf > 15 - indent ? findNotableNode(node2.children[0], indent) : node2;
    }
    function indentation(indent) {
      return "  " + "  ".repeat(indent);
    }
    function added(indent) {
      return "+ " + "  ".repeat(indent);
    }
    function removed(indent) {
      return "- " + "  ".repeat(indent);
    }
    function describeFiberType(fiber) {
      switch (fiber.tag) {
        case 26:
        case 27:
        case 5:
          return fiber.type;
        case 16:
          return "Lazy";
        case 31:
          return "Activity";
        case 13:
          return "Suspense";
        case 19:
          return "SuspenseList";
        case 0:
        case 15:
          return fiber = fiber.type, fiber.displayName || fiber.name || null;
        case 11:
          return fiber = fiber.type.render, fiber.displayName || fiber.name || null;
        case 1:
          return fiber = fiber.type, fiber.displayName || fiber.name || null;
        default:
          return null;
      }
    }
    function describeTextNode(content2, maxLength) {
      return needsEscaping.test(content2) ? (content2 = JSON.stringify(content2), content2.length > maxLength - 2 ? 8 > maxLength ? '{"..."}' : "{" + content2.slice(0, maxLength - 7) + '..."}' : "{" + content2 + "}") : content2.length > maxLength ? 5 > maxLength ? '{"..."}' : content2.slice(0, maxLength - 3) + "..." : content2;
    }
    function describeTextDiff(clientText, serverProps, indent) {
      var maxLength = 120 - 2 * indent;
      if (null === serverProps)
        return added(indent) + describeTextNode(clientText, maxLength) + "\n";
      if ("string" === typeof serverProps) {
        for (var firstDiff = 0; firstDiff < serverProps.length && firstDiff < clientText.length && serverProps.charCodeAt(firstDiff) === clientText.charCodeAt(firstDiff); firstDiff++) ;
        firstDiff > maxLength - 8 && 10 < firstDiff && (clientText = "..." + clientText.slice(firstDiff - 8), serverProps = "..." + serverProps.slice(firstDiff - 8));
        return added(indent) + describeTextNode(clientText, maxLength) + "\n" + removed(indent) + describeTextNode(serverProps, maxLength) + "\n";
      }
      return indentation(indent) + describeTextNode(clientText, maxLength) + "\n";
    }
    function objectName(object2) {
      return Object.prototype.toString.call(object2).replace(/^\[object (.*)\]$/, function(m, p0) {
        return p0;
      });
    }
    function describeValue(value2, maxLength) {
      switch (typeof value2) {
        case "string":
          return value2 = JSON.stringify(value2), value2.length > maxLength ? 5 > maxLength ? '"..."' : value2.slice(0, maxLength - 4) + '..."' : value2;
        case "object":
          if (null === value2) return "null";
          if (isArrayImpl(value2)) return "[...]";
          if (value2.$$typeof === REACT_ELEMENT_TYPE)
            return (maxLength = getComponentNameFromType(value2.type)) ? "<" + maxLength + ">" : "<...>";
          var name2 = objectName(value2);
          if ("Object" === name2) {
            name2 = "";
            maxLength -= 2;
            for (var propName in value2)
              if (value2.hasOwnProperty(propName)) {
                var jsonPropName = JSON.stringify(propName);
                jsonPropName !== '"' + propName + '"' && (propName = jsonPropName);
                maxLength -= propName.length - 2;
                jsonPropName = describeValue(
                  value2[propName],
                  15 > maxLength ? maxLength : 15
                );
                maxLength -= jsonPropName.length;
                if (0 > maxLength) {
                  name2 += "" === name2 ? "..." : ", ...";
                  break;
                }
                name2 += ("" === name2 ? "" : ",") + propName + ":" + jsonPropName;
              }
            return "{" + name2 + "}";
          }
          return name2;
        case "function":
          return (maxLength = value2.displayName || value2.name) ? "function " + maxLength : "function";
        default:
          return String(value2);
      }
    }
    function describePropValue(value2, maxLength) {
      return "string" !== typeof value2 || needsEscaping.test(value2) ? "{" + describeValue(value2, maxLength - 2) + "}" : value2.length > maxLength - 2 ? 5 > maxLength ? '"..."' : '"' + value2.slice(0, maxLength - 5) + '..."' : '"' + value2 + '"';
    }
    function describeExpandedElement(type, props, rowPrefix) {
      var remainingRowLength = 120 - rowPrefix.length - type.length, properties = [], propName;
      for (propName in props)
        if (props.hasOwnProperty(propName) && "children" !== propName) {
          var propValue = describePropValue(
            props[propName],
            120 - rowPrefix.length - propName.length - 1
          );
          remainingRowLength -= propName.length + propValue.length + 2;
          properties.push(propName + "=" + propValue);
        }
      return 0 === properties.length ? rowPrefix + "<" + type + ">\n" : 0 < remainingRowLength ? rowPrefix + "<" + type + " " + properties.join(" ") + ">\n" : rowPrefix + "<" + type + "\n" + rowPrefix + "  " + properties.join("\n" + rowPrefix + "  ") + "\n" + rowPrefix + ">\n";
    }
    function describePropertiesDiff(clientObject, serverObject, indent) {
      var properties = "", remainingServerProperties = assign2({}, serverObject), propName;
      for (propName in clientObject)
        if (clientObject.hasOwnProperty(propName)) {
          delete remainingServerProperties[propName];
          var maxLength = 120 - 2 * indent - propName.length - 2, clientPropValue = describeValue(clientObject[propName], maxLength);
          serverObject.hasOwnProperty(propName) ? (maxLength = describeValue(serverObject[propName], maxLength), properties += added(indent) + propName + ": " + clientPropValue + "\n", properties += removed(indent) + propName + ": " + maxLength + "\n") : properties += added(indent) + propName + ": " + clientPropValue + "\n";
        }
      for (var _propName in remainingServerProperties)
        remainingServerProperties.hasOwnProperty(_propName) && (clientObject = describeValue(
          remainingServerProperties[_propName],
          120 - 2 * indent - _propName.length - 2
        ), properties += removed(indent) + _propName + ": " + clientObject + "\n");
      return properties;
    }
    function describeElementDiff(type, clientProps, serverProps, indent) {
      var content2 = "", serverPropNames = /* @__PURE__ */ new Map();
      for (propName$jscomp$0 in serverProps)
        serverProps.hasOwnProperty(propName$jscomp$0) && serverPropNames.set(
          propName$jscomp$0.toLowerCase(),
          propName$jscomp$0
        );
      if (1 === serverPropNames.size && serverPropNames.has("children"))
        content2 += describeExpandedElement(
          type,
          clientProps,
          indentation(indent)
        );
      else {
        for (var _propName2 in clientProps)
          if (clientProps.hasOwnProperty(_propName2) && "children" !== _propName2) {
            var maxLength$jscomp$0 = 120 - 2 * (indent + 1) - _propName2.length - 1, serverPropName = serverPropNames.get(_propName2.toLowerCase());
            if (void 0 !== serverPropName) {
              serverPropNames.delete(_propName2.toLowerCase());
              var propName$jscomp$0 = clientProps[_propName2];
              serverPropName = serverProps[serverPropName];
              var clientPropValue = describePropValue(
                propName$jscomp$0,
                maxLength$jscomp$0
              );
              maxLength$jscomp$0 = describePropValue(
                serverPropName,
                maxLength$jscomp$0
              );
              "object" === typeof propName$jscomp$0 && null !== propName$jscomp$0 && "object" === typeof serverPropName && null !== serverPropName && "Object" === objectName(propName$jscomp$0) && "Object" === objectName(serverPropName) && (2 < Object.keys(propName$jscomp$0).length || 2 < Object.keys(serverPropName).length || -1 < clientPropValue.indexOf("...") || -1 < maxLength$jscomp$0.indexOf("...")) ? content2 += indentation(indent + 1) + _propName2 + "={{\n" + describePropertiesDiff(
                propName$jscomp$0,
                serverPropName,
                indent + 2
              ) + indentation(indent + 1) + "}}\n" : (content2 += added(indent + 1) + _propName2 + "=" + clientPropValue + "\n", content2 += removed(indent + 1) + _propName2 + "=" + maxLength$jscomp$0 + "\n");
            } else
              content2 += indentation(indent + 1) + _propName2 + "=" + describePropValue(clientProps[_propName2], maxLength$jscomp$0) + "\n";
          }
        serverPropNames.forEach(function(propName) {
          if ("children" !== propName) {
            var maxLength = 120 - 2 * (indent + 1) - propName.length - 1;
            content2 += removed(indent + 1) + propName + "=" + describePropValue(serverProps[propName], maxLength) + "\n";
          }
        });
        content2 = "" === content2 ? indentation(indent) + "<" + type + ">\n" : indentation(indent) + "<" + type + "\n" + content2 + indentation(indent) + ">\n";
      }
      type = serverProps.children;
      clientProps = clientProps.children;
      if ("string" === typeof type || "number" === typeof type || "bigint" === typeof type) {
        serverPropNames = "";
        if ("string" === typeof clientProps || "number" === typeof clientProps || "bigint" === typeof clientProps)
          serverPropNames = "" + clientProps;
        content2 += describeTextDiff(serverPropNames, "" + type, indent + 1);
      } else if ("string" === typeof clientProps || "number" === typeof clientProps || "bigint" === typeof clientProps)
        content2 = null == type ? content2 + describeTextDiff("" + clientProps, null, indent + 1) : content2 + describeTextDiff("" + clientProps, void 0, indent + 1);
      return content2;
    }
    function describeSiblingFiber(fiber, indent) {
      var type = describeFiberType(fiber);
      if (null === type) {
        type = "";
        for (fiber = fiber.child; fiber; )
          type += describeSiblingFiber(fiber, indent), fiber = fiber.sibling;
        return type;
      }
      return indentation(indent) + "<" + type + ">\n";
    }
    function describeNode(node2, indent) {
      var skipToNode = findNotableNode(node2, indent);
      if (skipToNode !== node2 && (1 !== node2.children.length || node2.children[0] !== skipToNode))
        return indentation(indent) + "...\n" + describeNode(skipToNode, indent + 1);
      skipToNode = "";
      var debugInfo = node2.fiber._debugInfo;
      if (debugInfo)
        for (var i2 = 0; i2 < debugInfo.length; i2++) {
          var serverComponentName = debugInfo[i2].name;
          "string" === typeof serverComponentName && (skipToNode += indentation(indent) + "<" + serverComponentName + ">\n", indent++);
        }
      debugInfo = "";
      i2 = node2.fiber.pendingProps;
      if (6 === node2.fiber.tag)
        debugInfo = describeTextDiff(i2, node2.serverProps, indent), indent++;
      else if (serverComponentName = describeFiberType(node2.fiber), null !== serverComponentName)
        if (void 0 === node2.serverProps) {
          debugInfo = indent;
          var maxLength = 120 - 2 * debugInfo - serverComponentName.length - 2, content2 = "";
          for (propName in i2)
            if (i2.hasOwnProperty(propName) && "children" !== propName) {
              var propValue = describePropValue(i2[propName], 15);
              maxLength -= propName.length + propValue.length + 2;
              if (0 > maxLength) {
                content2 += " ...";
                break;
              }
              content2 += " " + propName + "=" + propValue;
            }
          debugInfo = indentation(debugInfo) + "<" + serverComponentName + content2 + ">\n";
          indent++;
        } else
          null === node2.serverProps ? (debugInfo = describeExpandedElement(
            serverComponentName,
            i2,
            added(indent)
          ), indent++) : "string" === typeof node2.serverProps ? console.error(
            "Should not have matched a non HostText fiber to a Text node. This is a bug in React."
          ) : (debugInfo = describeElementDiff(
            serverComponentName,
            i2,
            node2.serverProps,
            indent
          ), indent++);
      var propName = "";
      i2 = node2.fiber.child;
      for (serverComponentName = 0; i2 && serverComponentName < node2.children.length; )
        maxLength = node2.children[serverComponentName], maxLength.fiber === i2 ? (propName += describeNode(maxLength, indent), serverComponentName++) : propName += describeSiblingFiber(i2, indent), i2 = i2.sibling;
      i2 && 0 < node2.children.length && (propName += indentation(indent) + "...\n");
      i2 = node2.serverTail;
      null === node2.serverProps && indent--;
      for (node2 = 0; node2 < i2.length; node2++)
        serverComponentName = i2[node2], propName = "string" === typeof serverComponentName ? propName + (removed(indent) + describeTextNode(serverComponentName, 120 - 2 * indent) + "\n") : propName + describeExpandedElement(
          serverComponentName.type,
          serverComponentName.props,
          removed(indent)
        );
      return skipToNode + debugInfo + propName;
    }
    function describeDiff(rootNode) {
      try {
        return "\n\n" + describeNode(rootNode, 0);
      } catch (x) {
        return "";
      }
    }
    function describeAncestors(ancestor, child, props) {
      for (var fiber = child, node2 = null, distanceFromLeaf = 0; fiber; )
        fiber === ancestor && (distanceFromLeaf = 0), node2 = {
          fiber,
          children: null !== node2 ? [node2] : [],
          serverProps: fiber === child ? props : fiber === ancestor ? null : void 0,
          serverTail: [],
          distanceFromLeaf
        }, distanceFromLeaf++, fiber = fiber.return;
      return null !== node2 ? describeDiff(node2).replaceAll(/^[+-]/gm, ">") : "";
    }
    function updatedAncestorInfoDev(oldInfo, tag) {
      var ancestorInfo = assign2({}, oldInfo || emptyAncestorInfoDev), info = { tag };
      -1 !== inScopeTags.indexOf(tag) && (ancestorInfo.aTagInScope = null, ancestorInfo.buttonTagInScope = null, ancestorInfo.nobrTagInScope = null);
      -1 !== buttonScopeTags.indexOf(tag) && (ancestorInfo.pTagInButtonScope = null);
      -1 !== specialTags.indexOf(tag) && "address" !== tag && "div" !== tag && "p" !== tag && (ancestorInfo.listItemTagAutoclosing = null, ancestorInfo.dlItemTagAutoclosing = null);
      ancestorInfo.current = info;
      "form" === tag && (ancestorInfo.formTag = info);
      "a" === tag && (ancestorInfo.aTagInScope = info);
      "button" === tag && (ancestorInfo.buttonTagInScope = info);
      "nobr" === tag && (ancestorInfo.nobrTagInScope = info);
      "p" === tag && (ancestorInfo.pTagInButtonScope = info);
      "li" === tag && (ancestorInfo.listItemTagAutoclosing = info);
      if ("dd" === tag || "dt" === tag)
        ancestorInfo.dlItemTagAutoclosing = info;
      "#document" === tag || "html" === tag ? ancestorInfo.containerTagInScope = null : ancestorInfo.containerTagInScope || (ancestorInfo.containerTagInScope = info);
      null !== oldInfo || "#document" !== tag && "html" !== tag && "body" !== tag ? true === ancestorInfo.implicitRootScope && (ancestorInfo.implicitRootScope = false) : ancestorInfo.implicitRootScope = true;
      return ancestorInfo;
    }
    function isTagValidWithParent(tag, parentTag, implicitRootScope) {
      switch (parentTag) {
        case "select":
          return "hr" === tag || "option" === tag || "optgroup" === tag || "script" === tag || "template" === tag || "#text" === tag;
        case "optgroup":
          return "option" === tag || "#text" === tag;
        case "option":
          return "#text" === tag;
        case "tr":
          return "th" === tag || "td" === tag || "style" === tag || "script" === tag || "template" === tag;
        case "tbody":
        case "thead":
        case "tfoot":
          return "tr" === tag || "style" === tag || "script" === tag || "template" === tag;
        case "colgroup":
          return "col" === tag || "template" === tag;
        case "table":
          return "caption" === tag || "colgroup" === tag || "tbody" === tag || "tfoot" === tag || "thead" === tag || "style" === tag || "script" === tag || "template" === tag;
        case "head":
          return "base" === tag || "basefont" === tag || "bgsound" === tag || "link" === tag || "meta" === tag || "title" === tag || "noscript" === tag || "noframes" === tag || "style" === tag || "script" === tag || "template" === tag;
        case "html":
          if (implicitRootScope) break;
          return "head" === tag || "body" === tag || "frameset" === tag;
        case "frameset":
          return "frame" === tag;
        case "#document":
          if (!implicitRootScope) return "html" === tag;
      }
      switch (tag) {
        case "h1":
        case "h2":
        case "h3":
        case "h4":
        case "h5":
        case "h6":
          return "h1" !== parentTag && "h2" !== parentTag && "h3" !== parentTag && "h4" !== parentTag && "h5" !== parentTag && "h6" !== parentTag;
        case "rp":
        case "rt":
          return -1 === impliedEndTags.indexOf(parentTag);
        case "caption":
        case "col":
        case "colgroup":
        case "frameset":
        case "frame":
        case "tbody":
        case "td":
        case "tfoot":
        case "th":
        case "thead":
        case "tr":
          return null == parentTag;
        case "head":
          return implicitRootScope || null === parentTag;
        case "html":
          return implicitRootScope && "#document" === parentTag || null === parentTag;
        case "body":
          return implicitRootScope && ("#document" === parentTag || "html" === parentTag) || null === parentTag;
      }
      return true;
    }
    function findInvalidAncestorForTag(tag, ancestorInfo) {
      switch (tag) {
        case "address":
        case "article":
        case "aside":
        case "blockquote":
        case "center":
        case "details":
        case "dialog":
        case "dir":
        case "div":
        case "dl":
        case "fieldset":
        case "figcaption":
        case "figure":
        case "footer":
        case "header":
        case "hgroup":
        case "main":
        case "menu":
        case "nav":
        case "ol":
        case "p":
        case "section":
        case "summary":
        case "ul":
        case "pre":
        case "listing":
        case "table":
        case "hr":
        case "xmp":
        case "h1":
        case "h2":
        case "h3":
        case "h4":
        case "h5":
        case "h6":
          return ancestorInfo.pTagInButtonScope;
        case "form":
          return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;
        case "li":
          return ancestorInfo.listItemTagAutoclosing;
        case "dd":
        case "dt":
          return ancestorInfo.dlItemTagAutoclosing;
        case "button":
          return ancestorInfo.buttonTagInScope;
        case "a":
          return ancestorInfo.aTagInScope;
        case "nobr":
          return ancestorInfo.nobrTagInScope;
      }
      return null;
    }
    function findAncestor(parent, tagName) {
      for (; parent; ) {
        switch (parent.tag) {
          case 5:
          case 26:
          case 27:
            if (parent.type === tagName) return parent;
        }
        parent = parent.return;
      }
      return null;
    }
    function validateDOMNesting(childTag, ancestorInfo) {
      ancestorInfo = ancestorInfo || emptyAncestorInfoDev;
      var parentInfo = ancestorInfo.current;
      ancestorInfo = (parentInfo = isTagValidWithParent(
        childTag,
        parentInfo && parentInfo.tag,
        ancestorInfo.implicitRootScope
      ) ? null : parentInfo) ? null : findInvalidAncestorForTag(childTag, ancestorInfo);
      ancestorInfo = parentInfo || ancestorInfo;
      if (!ancestorInfo) return true;
      var ancestorTag = ancestorInfo.tag;
      ancestorInfo = String(!!parentInfo) + "|" + childTag + "|" + ancestorTag;
      if (didWarn[ancestorInfo]) return false;
      didWarn[ancestorInfo] = true;
      var ancestor = (ancestorInfo = current3) ? findAncestor(ancestorInfo.return, ancestorTag) : null, ancestorDescription = null !== ancestorInfo && null !== ancestor ? describeAncestors(ancestor, ancestorInfo, null) : "", tagDisplayName = "<" + childTag + ">";
      parentInfo ? (parentInfo = "", "table" === ancestorTag && "tr" === childTag && (parentInfo += " Add a <tbody>, <thead> or <tfoot> to your code to match the DOM tree generated by the browser."), console.error(
        "In HTML, %s cannot be a child of <%s>.%s\nThis will cause a hydration error.%s",
        tagDisplayName,
        ancestorTag,
        parentInfo,
        ancestorDescription
      )) : console.error(
        "In HTML, %s cannot be a descendant of <%s>.\nThis will cause a hydration error.%s",
        tagDisplayName,
        ancestorTag,
        ancestorDescription
      );
      ancestorInfo && (childTag = ancestorInfo.return, null === ancestor || null === childTag || ancestor === childTag && childTag._debugOwner === ancestorInfo._debugOwner || runWithFiberInDEV(ancestor, function() {
        console.error(
          "<%s> cannot contain a nested %s.\nSee this log for the ancestor stack trace.",
          ancestorTag,
          tagDisplayName
        );
      }));
      return false;
    }
    function validateTextNesting(childText, parentTag, implicitRootScope) {
      if (implicitRootScope || isTagValidWithParent("#text", parentTag, false))
        return true;
      implicitRootScope = "#text|" + parentTag;
      if (didWarn[implicitRootScope]) return false;
      didWarn[implicitRootScope] = true;
      var ancestor = (implicitRootScope = current3) ? findAncestor(implicitRootScope, parentTag) : null;
      implicitRootScope = null !== implicitRootScope && null !== ancestor ? describeAncestors(
        ancestor,
        implicitRootScope,
        6 !== implicitRootScope.tag ? { children: null } : null
      ) : "";
      /\S/.test(childText) ? console.error(
        "In HTML, text nodes cannot be a child of <%s>.\nThis will cause a hydration error.%s",
        parentTag,
        implicitRootScope
      ) : console.error(
        "In HTML, whitespace text nodes cannot be a child of <%s>. Make sure you don't have any extra whitespace between tags on each line of your source code.\nThis will cause a hydration error.%s",
        parentTag,
        implicitRootScope
      );
      return false;
    }
    function setTextContent(node2, text2) {
      if (text2) {
        var firstChild = node2.firstChild;
        if (firstChild && firstChild === node2.lastChild && 3 === firstChild.nodeType) {
          firstChild.nodeValue = text2;
          return;
        }
      }
      node2.textContent = text2;
    }
    function camelize(string2) {
      return string2.replace(hyphenPattern, function(_, character) {
        return character.toUpperCase();
      });
    }
    function setValueForStyle(style22, styleName, value2) {
      var isCustomProperty = 0 === styleName.indexOf("--");
      isCustomProperty || (-1 < styleName.indexOf("-") ? warnedStyleNames.hasOwnProperty(styleName) && warnedStyleNames[styleName] || (warnedStyleNames[styleName] = true, console.error(
        "Unsupported style property %s. Did you mean %s?",
        styleName,
        camelize(styleName.replace(msPattern, "ms-"))
      )) : badVendoredStyleNamePattern.test(styleName) ? warnedStyleNames.hasOwnProperty(styleName) && warnedStyleNames[styleName] || (warnedStyleNames[styleName] = true, console.error(
        "Unsupported vendor-prefixed style property %s. Did you mean %s?",
        styleName,
        styleName.charAt(0).toUpperCase() + styleName.slice(1)
      )) : !badStyleValueWithSemicolonPattern.test(value2) || warnedStyleValues.hasOwnProperty(value2) && warnedStyleValues[value2] || (warnedStyleValues[value2] = true, console.error(
        `Style property values shouldn't contain a semicolon. Try "%s: %s" instead.`,
        styleName,
        value2.replace(badStyleValueWithSemicolonPattern, "")
      )), "number" === typeof value2 && (isNaN(value2) ? warnedForNaNValue || (warnedForNaNValue = true, console.error(
        "`NaN` is an invalid value for the `%s` css style property.",
        styleName
      )) : isFinite(value2) || warnedForInfinityValue || (warnedForInfinityValue = true, console.error(
        "`Infinity` is an invalid value for the `%s` css style property.",
        styleName
      ))));
      null == value2 || "boolean" === typeof value2 || "" === value2 ? isCustomProperty ? style22.setProperty(styleName, "") : "float" === styleName ? style22.cssFloat = "" : style22[styleName] = "" : isCustomProperty ? style22.setProperty(styleName, value2) : "number" !== typeof value2 || 0 === value2 || unitlessNumbers.has(styleName) ? "float" === styleName ? style22.cssFloat = value2 : (checkCSSPropertyStringCoercion(value2, styleName), style22[styleName] = ("" + value2).trim()) : style22[styleName] = value2 + "px";
    }
    function setValueForStyles(node2, styles2, prevStyles) {
      if (null != styles2 && "object" !== typeof styles2)
        throw Error(
          "The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX."
        );
      styles2 && Object.freeze(styles2);
      node2 = node2.style;
      if (null != prevStyles) {
        if (styles2) {
          var expandedUpdates = {};
          if (prevStyles) {
            for (var key2 in prevStyles)
              if (prevStyles.hasOwnProperty(key2) && !styles2.hasOwnProperty(key2))
                for (var longhands = shorthandToLonghand[key2] || [key2], i2 = 0; i2 < longhands.length; i2++)
                  expandedUpdates[longhands[i2]] = key2;
          }
          for (var _key in styles2)
            if (styles2.hasOwnProperty(_key) && (!prevStyles || prevStyles[_key] !== styles2[_key]))
              for (key2 = shorthandToLonghand[_key] || [_key], longhands = 0; longhands < key2.length; longhands++)
                expandedUpdates[key2[longhands]] = _key;
          _key = {};
          for (var key$jscomp$0 in styles2)
            for (key2 = shorthandToLonghand[key$jscomp$0] || [key$jscomp$0], longhands = 0; longhands < key2.length; longhands++)
              _key[key2[longhands]] = key$jscomp$0;
          key$jscomp$0 = {};
          for (var _key2 in expandedUpdates)
            if (key2 = expandedUpdates[_key2], (longhands = _key[_key2]) && key2 !== longhands && (i2 = key2 + "," + longhands, !key$jscomp$0[i2])) {
              key$jscomp$0[i2] = true;
              i2 = console;
              var value2 = styles2[key2];
              i2.error.call(
                i2,
                "%s a style property during rerender (%s) when a conflicting property is set (%s) can lead to styling bugs. To avoid this, don't mix shorthand and non-shorthand properties for the same value; instead, replace the shorthand with separate values.",
                null == value2 || "boolean" === typeof value2 || "" === value2 ? "Removing" : "Updating",
                key2,
                longhands
              );
            }
        }
        for (var styleName in prevStyles)
          !prevStyles.hasOwnProperty(styleName) || null != styles2 && styles2.hasOwnProperty(styleName) || (0 === styleName.indexOf("--") ? node2.setProperty(styleName, "") : "float" === styleName ? node2.cssFloat = "" : node2[styleName] = "");
        for (var _styleName in styles2)
          _key2 = styles2[_styleName], styles2.hasOwnProperty(_styleName) && prevStyles[_styleName] !== _key2 && setValueForStyle(node2, _styleName, _key2);
      } else
        for (expandedUpdates in styles2)
          styles2.hasOwnProperty(expandedUpdates) && setValueForStyle(node2, expandedUpdates, styles2[expandedUpdates]);
    }
    function isCustomElement(tagName) {
      if (-1 === tagName.indexOf("-")) return false;
      switch (tagName) {
        case "annotation-xml":
        case "color-profile":
        case "font-face":
        case "font-face-src":
        case "font-face-uri":
        case "font-face-format":
        case "font-face-name":
        case "missing-glyph":
          return false;
        default:
          return true;
      }
    }
    function getAttributeAlias(name2) {
      return aliases.get(name2) || name2;
    }
    function validateProperty$1(tagName, name2) {
      if (hasOwnProperty2.call(warnedProperties$1, name2) && warnedProperties$1[name2])
        return true;
      if (rARIACamel$1.test(name2)) {
        tagName = "aria-" + name2.slice(4).toLowerCase();
        tagName = ariaProperties.hasOwnProperty(tagName) ? tagName : null;
        if (null == tagName)
          return console.error(
            "Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.",
            name2
          ), warnedProperties$1[name2] = true;
        if (name2 !== tagName)
          return console.error(
            "Invalid ARIA attribute `%s`. Did you mean `%s`?",
            name2,
            tagName
          ), warnedProperties$1[name2] = true;
      }
      if (rARIA$1.test(name2)) {
        tagName = name2.toLowerCase();
        tagName = ariaProperties.hasOwnProperty(tagName) ? tagName : null;
        if (null == tagName) return warnedProperties$1[name2] = true, false;
        name2 !== tagName && (console.error(
          "Unknown ARIA attribute `%s`. Did you mean `%s`?",
          name2,
          tagName
        ), warnedProperties$1[name2] = true);
      }
      return true;
    }
    function validateProperties$2(type, props) {
      var invalidProps = [], key2;
      for (key2 in props)
        validateProperty$1(type, key2) || invalidProps.push(key2);
      props = invalidProps.map(function(prop) {
        return "`" + prop + "`";
      }).join(", ");
      1 === invalidProps.length ? console.error(
        "Invalid aria prop %s on <%s> tag. For details, see https://react.dev/link/invalid-aria-props",
        props,
        type
      ) : 1 < invalidProps.length && console.error(
        "Invalid aria props %s on <%s> tag. For details, see https://react.dev/link/invalid-aria-props",
        props,
        type
      );
    }
    function validateProperty(tagName, name2, value2, eventRegistry) {
      if (hasOwnProperty2.call(warnedProperties, name2) && warnedProperties[name2])
        return true;
      var lowerCasedName = name2.toLowerCase();
      if ("onfocusin" === lowerCasedName || "onfocusout" === lowerCasedName)
        return console.error(
          "React uses onFocus and onBlur instead of onFocusIn and onFocusOut. All React events are normalized to bubble, so onFocusIn and onFocusOut are not needed/supported by React."
        ), warnedProperties[name2] = true;
      if ("function" === typeof value2 && ("form" === tagName && "action" === name2 || "input" === tagName && "formAction" === name2 || "button" === tagName && "formAction" === name2))
        return true;
      if (null != eventRegistry) {
        tagName = eventRegistry.possibleRegistrationNames;
        if (eventRegistry.registrationNameDependencies.hasOwnProperty(name2))
          return true;
        eventRegistry = tagName.hasOwnProperty(lowerCasedName) ? tagName[lowerCasedName] : null;
        if (null != eventRegistry)
          return console.error(
            "Invalid event handler property `%s`. Did you mean `%s`?",
            name2,
            eventRegistry
          ), warnedProperties[name2] = true;
        if (EVENT_NAME_REGEX.test(name2))
          return console.error(
            "Unknown event handler property `%s`. It will be ignored.",
            name2
          ), warnedProperties[name2] = true;
      } else if (EVENT_NAME_REGEX.test(name2))
        return INVALID_EVENT_NAME_REGEX.test(name2) && console.error(
          "Invalid event handler property `%s`. React events use the camelCase naming convention, for example `onClick`.",
          name2
        ), warnedProperties[name2] = true;
      if (rARIA.test(name2) || rARIACamel.test(name2)) return true;
      if ("innerhtml" === lowerCasedName)
        return console.error(
          "Directly setting property `innerHTML` is not permitted. For more information, lookup documentation on `dangerouslySetInnerHTML`."
        ), warnedProperties[name2] = true;
      if ("aria" === lowerCasedName)
        return console.error(
          "The `aria` attribute is reserved for future use in React. Pass individual `aria-` attributes instead."
        ), warnedProperties[name2] = true;
      if ("is" === lowerCasedName && null !== value2 && void 0 !== value2 && "string" !== typeof value2)
        return console.error(
          "Received a `%s` for a string attribute `is`. If this is expected, cast the value to a string.",
          typeof value2
        ), warnedProperties[name2] = true;
      if ("number" === typeof value2 && isNaN(value2))
        return console.error(
          "Received NaN for the `%s` attribute. If this is expected, cast the value to a string.",
          name2
        ), warnedProperties[name2] = true;
      if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
        if (lowerCasedName = possibleStandardNames[lowerCasedName], lowerCasedName !== name2)
          return console.error(
            "Invalid DOM property `%s`. Did you mean `%s`?",
            name2,
            lowerCasedName
          ), warnedProperties[name2] = true;
      } else if (name2 !== lowerCasedName)
        return console.error(
          "React does not recognize the `%s` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `%s` instead. If you accidentally passed it from a parent component, remove it from the DOM element.",
          name2,
          lowerCasedName
        ), warnedProperties[name2] = true;
      switch (name2) {
        case "dangerouslySetInnerHTML":
        case "children":
        case "style":
        case "suppressContentEditableWarning":
        case "suppressHydrationWarning":
        case "defaultValue":
        case "defaultChecked":
        case "innerHTML":
        case "ref":
          return true;
        case "innerText":
        case "textContent":
          return true;
      }
      switch (typeof value2) {
        case "boolean":
          switch (name2) {
            case "autoFocus":
            case "checked":
            case "multiple":
            case "muted":
            case "selected":
            case "contentEditable":
            case "spellCheck":
            case "draggable":
            case "value":
            case "autoReverse":
            case "externalResourcesRequired":
            case "focusable":
            case "preserveAlpha":
            case "allowFullScreen":
            case "async":
            case "autoPlay":
            case "controls":
            case "default":
            case "defer":
            case "disabled":
            case "disablePictureInPicture":
            case "disableRemotePlayback":
            case "formNoValidate":
            case "hidden":
            case "loop":
            case "noModule":
            case "noValidate":
            case "open":
            case "playsInline":
            case "readOnly":
            case "required":
            case "reversed":
            case "scoped":
            case "seamless":
            case "itemScope":
            case "capture":
            case "download":
            case "inert":
              return true;
            default:
              lowerCasedName = name2.toLowerCase().slice(0, 5);
              if ("data-" === lowerCasedName || "aria-" === lowerCasedName)
                return true;
              value2 ? console.error(
                'Received `%s` for a non-boolean attribute `%s`.\n\nIf you want to write it to the DOM, pass a string instead: %s="%s" or %s={value.toString()}.',
                value2,
                name2,
                name2,
                value2,
                name2
              ) : console.error(
                'Received `%s` for a non-boolean attribute `%s`.\n\nIf you want to write it to the DOM, pass a string instead: %s="%s" or %s={value.toString()}.\n\nIf you used to conditionally omit it with %s={condition && value}, pass %s={condition ? value : undefined} instead.',
                value2,
                name2,
                name2,
                value2,
                name2,
                name2,
                name2
              );
              return warnedProperties[name2] = true;
          }
        case "function":
        case "symbol":
          return warnedProperties[name2] = true, false;
        case "string":
          if ("false" === value2 || "true" === value2) {
            switch (name2) {
              case "checked":
              case "selected":
              case "multiple":
              case "muted":
              case "allowFullScreen":
              case "async":
              case "autoPlay":
              case "controls":
              case "default":
              case "defer":
              case "disabled":
              case "disablePictureInPicture":
              case "disableRemotePlayback":
              case "formNoValidate":
              case "hidden":
              case "loop":
              case "noModule":
              case "noValidate":
              case "open":
              case "playsInline":
              case "readOnly":
              case "required":
              case "reversed":
              case "scoped":
              case "seamless":
              case "itemScope":
              case "inert":
                break;
              default:
                return true;
            }
            console.error(
              "Received the string `%s` for the boolean attribute `%s`. %s Did you mean %s={%s}?",
              value2,
              name2,
              "false" === value2 ? "The browser will interpret it as a truthy value." : 'Although this works, it will not work as expected if you pass the string "false".',
              name2,
              value2
            );
            warnedProperties[name2] = true;
          }
      }
      return true;
    }
    function warnUnknownProperties(type, props, eventRegistry) {
      var unknownProps = [], key2;
      for (key2 in props)
        validateProperty(type, key2, props[key2], eventRegistry) || unknownProps.push(key2);
      props = unknownProps.map(function(prop) {
        return "`" + prop + "`";
      }).join(", ");
      1 === unknownProps.length ? console.error(
        "Invalid value for prop %s on <%s> tag. Either remove it from the element, or pass a string or number value to keep it in the DOM. For details, see https://react.dev/link/attribute-behavior ",
        props,
        type
      ) : 1 < unknownProps.length && console.error(
        "Invalid values for props %s on <%s> tag. Either remove them from the element, or pass a string or number value to keep them in the DOM. For details, see https://react.dev/link/attribute-behavior ",
        props,
        type
      );
    }
    function sanitizeURL(url) {
      return isJavaScriptProtocol.test("" + url) ? "javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')" : url;
    }
    function noop$12() {
    }
    function getEventTarget(nativeEvent) {
      nativeEvent = nativeEvent.target || nativeEvent.srcElement || window;
      nativeEvent.correspondingUseElement && (nativeEvent = nativeEvent.correspondingUseElement);
      return 3 === nativeEvent.nodeType ? nativeEvent.parentNode : nativeEvent;
    }
    function restoreStateOfTarget(target) {
      var internalInstance = getInstanceFromNode(target);
      if (internalInstance && (target = internalInstance.stateNode)) {
        var props = target[internalPropsKey] || null;
        a: switch (target = internalInstance.stateNode, internalInstance.type) {
          case "input":
            updateInput(
              target,
              props.value,
              props.defaultValue,
              props.defaultValue,
              props.checked,
              props.defaultChecked,
              props.type,
              props.name
            );
            internalInstance = props.name;
            if ("radio" === props.type && null != internalInstance) {
              for (props = target; props.parentNode; ) props = props.parentNode;
              checkAttributeStringCoercion(internalInstance, "name");
              props = props.querySelectorAll(
                'input[name="' + escapeSelectorAttributeValueInsideDoubleQuotes(
                  "" + internalInstance
                ) + '"][type="radio"]'
              );
              for (internalInstance = 0; internalInstance < props.length; internalInstance++) {
                var otherNode = props[internalInstance];
                if (otherNode !== target && otherNode.form === target.form) {
                  var otherProps = otherNode[internalPropsKey] || null;
                  if (!otherProps)
                    throw Error(
                      "ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported."
                    );
                  updateInput(
                    otherNode,
                    otherProps.value,
                    otherProps.defaultValue,
                    otherProps.defaultValue,
                    otherProps.checked,
                    otherProps.defaultChecked,
                    otherProps.type,
                    otherProps.name
                  );
                }
              }
              for (internalInstance = 0; internalInstance < props.length; internalInstance++)
                otherNode = props[internalInstance], otherNode.form === target.form && updateValueIfChanged(otherNode);
            }
            break a;
          case "textarea":
            updateTextarea(target, props.value, props.defaultValue);
            break a;
          case "select":
            internalInstance = props.value, null != internalInstance && updateOptions(target, !!props.multiple, internalInstance, false);
        }
      }
    }
    function batchedUpdates$1(fn3, a2, b) {
      if (isInsideEventHandler) return fn3(a2, b);
      isInsideEventHandler = true;
      try {
        var JSCompiler_inline_result = fn3(a2);
        return JSCompiler_inline_result;
      } finally {
        if (isInsideEventHandler = false, null !== restoreTarget || null !== restoreQueue) {
          if (flushSyncWork$1(), restoreTarget && (a2 = restoreTarget, fn3 = restoreQueue, restoreQueue = restoreTarget = null, restoreStateOfTarget(a2), fn3))
            for (a2 = 0; a2 < fn3.length; a2++) restoreStateOfTarget(fn3[a2]);
        }
      }
    }
    function getListener2(inst, registrationName) {
      var stateNode = inst.stateNode;
      if (null === stateNode) return null;
      var props = stateNode[internalPropsKey] || null;
      if (null === props) return null;
      stateNode = props[registrationName];
      a: switch (registrationName) {
        case "onClick":
        case "onClickCapture":
        case "onDoubleClick":
        case "onDoubleClickCapture":
        case "onMouseDown":
        case "onMouseDownCapture":
        case "onMouseMove":
        case "onMouseMoveCapture":
        case "onMouseUp":
        case "onMouseUpCapture":
        case "onMouseEnter":
          (props = !props.disabled) || (inst = inst.type, props = !("button" === inst || "input" === inst || "select" === inst || "textarea" === inst));
          inst = !props;
          break a;
        default:
          inst = false;
      }
      if (inst) return null;
      if (stateNode && "function" !== typeof stateNode)
        throw Error(
          "Expected `" + registrationName + "` listener to be a function, instead got a value of `" + typeof stateNode + "` type."
        );
      return stateNode;
    }
    function getData() {
      if (fallbackText) return fallbackText;
      var start2, startValue = startText, startLength = startValue.length, end2, endValue = "value" in root2 ? root2.value : root2.textContent, endLength = endValue.length;
      for (start2 = 0; start2 < startLength && startValue[start2] === endValue[start2]; start2++) ;
      var minEnd = startLength - start2;
      for (end2 = 1; end2 <= minEnd && startValue[startLength - end2] === endValue[endLength - end2]; end2++) ;
      return fallbackText = endValue.slice(start2, 1 < end2 ? 1 - end2 : void 0);
    }
    function getEventCharCode(nativeEvent) {
      var keyCode = nativeEvent.keyCode;
      "charCode" in nativeEvent ? (nativeEvent = nativeEvent.charCode, 0 === nativeEvent && 13 === keyCode && (nativeEvent = 13)) : nativeEvent = keyCode;
      10 === nativeEvent && (nativeEvent = 13);
      return 32 <= nativeEvent || 13 === nativeEvent ? nativeEvent : 0;
    }
    function functionThatReturnsTrue() {
      return true;
    }
    function functionThatReturnsFalse() {
      return false;
    }
    function createSyntheticEvent(Interface) {
      function SyntheticBaseEvent(reactName, reactEventType, targetInst, nativeEvent, nativeEventTarget) {
        this._reactName = reactName;
        this._targetInst = targetInst;
        this.type = reactEventType;
        this.nativeEvent = nativeEvent;
        this.target = nativeEventTarget;
        this.currentTarget = null;
        for (var propName in Interface)
          Interface.hasOwnProperty(propName) && (reactName = Interface[propName], this[propName] = reactName ? reactName(nativeEvent) : nativeEvent[propName]);
        this.isDefaultPrevented = (null != nativeEvent.defaultPrevented ? nativeEvent.defaultPrevented : false === nativeEvent.returnValue) ? functionThatReturnsTrue : functionThatReturnsFalse;
        this.isPropagationStopped = functionThatReturnsFalse;
        return this;
      }
      assign2(SyntheticBaseEvent.prototype, {
        preventDefault: function() {
          this.defaultPrevented = true;
          var event = this.nativeEvent;
          event && (event.preventDefault ? event.preventDefault() : "unknown" !== typeof event.returnValue && (event.returnValue = false), this.isDefaultPrevented = functionThatReturnsTrue);
        },
        stopPropagation: function() {
          var event = this.nativeEvent;
          event && (event.stopPropagation ? event.stopPropagation() : "unknown" !== typeof event.cancelBubble && (event.cancelBubble = true), this.isPropagationStopped = functionThatReturnsTrue);
        },
        persist: function() {
        },
        isPersistent: functionThatReturnsTrue
      });
      return SyntheticBaseEvent;
    }
    function modifierStateGetter(keyArg) {
      var nativeEvent = this.nativeEvent;
      return nativeEvent.getModifierState ? nativeEvent.getModifierState(keyArg) : (keyArg = modifierKeyToProp[keyArg]) ? !!nativeEvent[keyArg] : false;
    }
    function getEventModifierState() {
      return modifierStateGetter;
    }
    function isFallbackCompositionEnd(domEventName, nativeEvent) {
      switch (domEventName) {
        case "keyup":
          return -1 !== END_KEYCODES.indexOf(nativeEvent.keyCode);
        case "keydown":
          return nativeEvent.keyCode !== START_KEYCODE;
        case "keypress":
        case "mousedown":
        case "focusout":
          return true;
        default:
          return false;
      }
    }
    function getDataFromCustomEvent(nativeEvent) {
      nativeEvent = nativeEvent.detail;
      return "object" === typeof nativeEvent && "data" in nativeEvent ? nativeEvent.data : null;
    }
    function getNativeBeforeInputChars(domEventName, nativeEvent) {
      switch (domEventName) {
        case "compositionend":
          return getDataFromCustomEvent(nativeEvent);
        case "keypress":
          if (nativeEvent.which !== SPACEBAR_CODE) return null;
          hasSpaceKeypress = true;
          return SPACEBAR_CHAR;
        case "textInput":
          return domEventName = nativeEvent.data, domEventName === SPACEBAR_CHAR && hasSpaceKeypress ? null : domEventName;
        default:
          return null;
      }
    }
    function getFallbackBeforeInputChars(domEventName, nativeEvent) {
      if (isComposing)
        return "compositionend" === domEventName || !canUseCompositionEvent && isFallbackCompositionEnd(domEventName, nativeEvent) ? (domEventName = getData(), fallbackText = startText = root2 = null, isComposing = false, domEventName) : null;
      switch (domEventName) {
        case "paste":
          return null;
        case "keypress":
          if (!(nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) || nativeEvent.ctrlKey && nativeEvent.altKey) {
            if (nativeEvent.char && 1 < nativeEvent.char.length)
              return nativeEvent.char;
            if (nativeEvent.which)
              return String.fromCharCode(nativeEvent.which);
          }
          return null;
        case "compositionend":
          return useFallbackCompositionData && "ko" !== nativeEvent.locale ? null : nativeEvent.data;
        default:
          return null;
      }
    }
    function isTextInputElement(elem) {
      var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
      return "input" === nodeName ? !!supportedInputTypes[elem.type] : "textarea" === nodeName ? true : false;
    }
    function isEventSupported(eventNameSuffix) {
      if (!canUseDOM) return false;
      eventNameSuffix = "on" + eventNameSuffix;
      var isSupported = eventNameSuffix in document;
      isSupported || (isSupported = document.createElement("div"), isSupported.setAttribute(eventNameSuffix, "return;"), isSupported = "function" === typeof isSupported[eventNameSuffix]);
      return isSupported;
    }
    function createAndAccumulateChangeEvent(dispatchQueue, inst, nativeEvent, target) {
      restoreTarget ? restoreQueue ? restoreQueue.push(target) : restoreQueue = [target] : restoreTarget = target;
      inst = accumulateTwoPhaseListeners(inst, "onChange");
      0 < inst.length && (nativeEvent = new SyntheticEvent(
        "onChange",
        "change",
        null,
        nativeEvent,
        target
      ), dispatchQueue.push({ event: nativeEvent, listeners: inst }));
    }
    function runEventInBatch(dispatchQueue) {
      processDispatchQueue(dispatchQueue, 0);
    }
    function getInstIfValueChanged(targetInst) {
      var targetNode = getNodeFromInstance(targetInst);
      if (updateValueIfChanged(targetNode)) return targetInst;
    }
    function getTargetInstForChangeEvent(domEventName, targetInst) {
      if ("change" === domEventName) return targetInst;
    }
    function stopWatchingForValueChange() {
      activeElement$1 && (activeElement$1.detachEvent("onpropertychange", handlePropertyChange), activeElementInst$1 = activeElement$1 = null);
    }
    function handlePropertyChange(nativeEvent) {
      if ("value" === nativeEvent.propertyName && getInstIfValueChanged(activeElementInst$1)) {
        var dispatchQueue = [];
        createAndAccumulateChangeEvent(
          dispatchQueue,
          activeElementInst$1,
          nativeEvent,
          getEventTarget(nativeEvent)
        );
        batchedUpdates$1(runEventInBatch, dispatchQueue);
      }
    }
    function handleEventsForInputEventPolyfill(domEventName, target, targetInst) {
      "focusin" === domEventName ? (stopWatchingForValueChange(), activeElement$1 = target, activeElementInst$1 = targetInst, activeElement$1.attachEvent("onpropertychange", handlePropertyChange)) : "focusout" === domEventName && stopWatchingForValueChange();
    }
    function getTargetInstForInputEventPolyfill(domEventName) {
      if ("selectionchange" === domEventName || "keyup" === domEventName || "keydown" === domEventName)
        return getInstIfValueChanged(activeElementInst$1);
    }
    function getTargetInstForClickEvent(domEventName, targetInst) {
      if ("click" === domEventName) return getInstIfValueChanged(targetInst);
    }
    function getTargetInstForInputOrChangeEvent(domEventName, targetInst) {
      if ("input" === domEventName || "change" === domEventName)
        return getInstIfValueChanged(targetInst);
    }
    function is2(x, y) {
      return x === y && (0 !== x || 1 / x === 1 / y) || x !== x && y !== y;
    }
    function shallowEqual(objA, objB) {
      if (objectIs(objA, objB)) return true;
      if ("object" !== typeof objA || null === objA || "object" !== typeof objB || null === objB)
        return false;
      var keysA = Object.keys(objA), keysB = Object.keys(objB);
      if (keysA.length !== keysB.length) return false;
      for (keysB = 0; keysB < keysA.length; keysB++) {
        var currentKey = keysA[keysB];
        if (!hasOwnProperty2.call(objB, currentKey) || !objectIs(objA[currentKey], objB[currentKey]))
          return false;
      }
      return true;
    }
    function getLeafNode(node2) {
      for (; node2 && node2.firstChild; ) node2 = node2.firstChild;
      return node2;
    }
    function getNodeForCharacterOffset(root22, offset3) {
      var node2 = getLeafNode(root22);
      root22 = 0;
      for (var nodeEnd; node2; ) {
        if (3 === node2.nodeType) {
          nodeEnd = root22 + node2.textContent.length;
          if (root22 <= offset3 && nodeEnd >= offset3)
            return { node: node2, offset: offset3 - root22 };
          root22 = nodeEnd;
        }
        a: {
          for (; node2; ) {
            if (node2.nextSibling) {
              node2 = node2.nextSibling;
              break a;
            }
            node2 = node2.parentNode;
          }
          node2 = void 0;
        }
        node2 = getLeafNode(node2);
      }
    }
    function containsNode(outerNode, innerNode) {
      return outerNode && innerNode ? outerNode === innerNode ? true : outerNode && 3 === outerNode.nodeType ? false : innerNode && 3 === innerNode.nodeType ? containsNode(outerNode, innerNode.parentNode) : "contains" in outerNode ? outerNode.contains(innerNode) : outerNode.compareDocumentPosition ? !!(outerNode.compareDocumentPosition(innerNode) & 16) : false : false;
    }
    function getActiveElementDeep(containerInfo) {
      containerInfo = null != containerInfo && null != containerInfo.ownerDocument && null != containerInfo.ownerDocument.defaultView ? containerInfo.ownerDocument.defaultView : window;
      for (var element = getActiveElement(containerInfo.document); element instanceof containerInfo.HTMLIFrameElement; ) {
        try {
          var JSCompiler_inline_result = "string" === typeof element.contentWindow.location.href;
        } catch (err) {
          JSCompiler_inline_result = false;
        }
        if (JSCompiler_inline_result) containerInfo = element.contentWindow;
        else break;
        element = getActiveElement(containerInfo.document);
      }
      return element;
    }
    function hasSelectionCapabilities(elem) {
      var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
      return nodeName && ("input" === nodeName && ("text" === elem.type || "search" === elem.type || "tel" === elem.type || "url" === elem.type || "password" === elem.type) || "textarea" === nodeName || "true" === elem.contentEditable);
    }
    function constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget) {
      var doc = nativeEventTarget.window === nativeEventTarget ? nativeEventTarget.document : 9 === nativeEventTarget.nodeType ? nativeEventTarget : nativeEventTarget.ownerDocument;
      mouseDown || null == activeElement || activeElement !== getActiveElement(doc) || (doc = activeElement, "selectionStart" in doc && hasSelectionCapabilities(doc) ? doc = { start: doc.selectionStart, end: doc.selectionEnd } : (doc = (doc.ownerDocument && doc.ownerDocument.defaultView || window).getSelection(), doc = {
        anchorNode: doc.anchorNode,
        anchorOffset: doc.anchorOffset,
        focusNode: doc.focusNode,
        focusOffset: doc.focusOffset
      }), lastSelection && shallowEqual(lastSelection, doc) || (lastSelection = doc, doc = accumulateTwoPhaseListeners(activeElementInst, "onSelect"), 0 < doc.length && (nativeEvent = new SyntheticEvent(
        "onSelect",
        "select",
        null,
        nativeEvent,
        nativeEventTarget
      ), dispatchQueue.push({ event: nativeEvent, listeners: doc }), nativeEvent.target = activeElement)));
    }
    function makePrefixMap(styleProp, eventName) {
      var prefixes = {};
      prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
      prefixes["Webkit" + styleProp] = "webkit" + eventName;
      prefixes["Moz" + styleProp] = "moz" + eventName;
      return prefixes;
    }
    function getVendorPrefixedEventName(eventName) {
      if (prefixedEventNames[eventName]) return prefixedEventNames[eventName];
      if (!vendorPrefixes[eventName]) return eventName;
      var prefixMap = vendorPrefixes[eventName], styleProp;
      for (styleProp in prefixMap)
        if (prefixMap.hasOwnProperty(styleProp) && styleProp in style2)
          return prefixedEventNames[eventName] = prefixMap[styleProp];
      return eventName;
    }
    function registerSimpleEvent(domEventName, reactName) {
      topLevelEventsToReactNames.set(domEventName, reactName);
      registerTwoPhaseEvent(reactName, [domEventName]);
    }
    function getArrayKind(array2) {
      for (var kind = EMPTY_ARRAY, i2 = 0; i2 < array2.length; i2++) {
        var value2 = array2[i2];
        if ("object" === typeof value2 && null !== value2)
          if (isArrayImpl(value2) && 2 === value2.length && "string" === typeof value2[0]) {
            if (kind !== EMPTY_ARRAY && kind !== ENTRIES_ARRAY)
              return COMPLEX_ARRAY;
            kind = ENTRIES_ARRAY;
          } else return COMPLEX_ARRAY;
        else {
          if ("function" === typeof value2 || "string" === typeof value2 && 50 < value2.length || kind !== EMPTY_ARRAY && kind !== PRIMITIVE_ARRAY)
            return COMPLEX_ARRAY;
          kind = PRIMITIVE_ARRAY;
        }
      }
      return kind;
    }
    function addObjectToProperties(object2, properties, indent, prefix2) {
      for (var key2 in object2)
        hasOwnProperty2.call(object2, key2) && "_" !== key2[0] && addValueToProperties(key2, object2[key2], properties, indent, prefix2);
    }
    function addValueToProperties(propertyName, value2, properties, indent, prefix2) {
      switch (typeof value2) {
        case "object":
          if (null === value2) {
            value2 = "null";
            break;
          } else {
            if (value2.$$typeof === REACT_ELEMENT_TYPE) {
              var typeName2 = getComponentNameFromType(value2.type) || "…", key2 = value2.key;
              value2 = value2.props;
              var propsKeys = Object.keys(value2), propsLength = propsKeys.length;
              if (null == key2 && 0 === propsLength) {
                value2 = "<" + typeName2 + " />";
                break;
              }
              if (3 > indent || 1 === propsLength && "children" === propsKeys[0] && null == key2) {
                value2 = "<" + typeName2 + " … />";
                break;
              }
              properties.push([
                prefix2 + "  ".repeat(indent) + propertyName,
                "<" + typeName2
              ]);
              null !== key2 && addValueToProperties(
                "key",
                key2,
                properties,
                indent + 1,
                prefix2
              );
              propertyName = false;
              for (var propKey in value2)
                "children" === propKey ? null != value2.children && (!isArrayImpl(value2.children) || 0 < value2.children.length) && (propertyName = true) : hasOwnProperty2.call(value2, propKey) && "_" !== propKey[0] && addValueToProperties(
                  propKey,
                  value2[propKey],
                  properties,
                  indent + 1,
                  prefix2
                );
              properties.push([
                "",
                propertyName ? ">…</" + typeName2 + ">" : "/>"
              ]);
              return;
            }
            typeName2 = Object.prototype.toString.call(value2);
            typeName2 = typeName2.slice(8, typeName2.length - 1);
            if ("Array" === typeName2) {
              if (propKey = getArrayKind(value2), propKey === PRIMITIVE_ARRAY || propKey === EMPTY_ARRAY) {
                value2 = JSON.stringify(value2);
                break;
              } else if (propKey === ENTRIES_ARRAY) {
                properties.push([
                  prefix2 + "  ".repeat(indent) + propertyName,
                  ""
                ]);
                for (propertyName = 0; propertyName < value2.length; propertyName++)
                  typeName2 = value2[propertyName], addValueToProperties(
                    typeName2[0],
                    typeName2[1],
                    properties,
                    indent + 1,
                    prefix2
                  );
                return;
              }
            }
            if ("Promise" === typeName2) {
              if ("fulfilled" === value2.status) {
                if (typeName2 = properties.length, addValueToProperties(
                  propertyName,
                  value2.value,
                  properties,
                  indent,
                  prefix2
                ), properties.length > typeName2) {
                  properties = properties[typeName2];
                  properties[1] = "Promise<" + (properties[1] || "Object") + ">";
                  return;
                }
              } else if ("rejected" === value2.status && (typeName2 = properties.length, addValueToProperties(
                propertyName,
                value2.reason,
                properties,
                indent,
                prefix2
              ), properties.length > typeName2)) {
                properties = properties[typeName2];
                properties[1] = "Rejected Promise<" + properties[1] + ">";
                return;
              }
              properties.push([
                "  ".repeat(indent) + propertyName,
                "Promise"
              ]);
              return;
            }
            "Object" === typeName2 && (propKey = Object.getPrototypeOf(value2)) && "function" === typeof propKey.constructor && (typeName2 = propKey.constructor.name);
            properties.push([
              prefix2 + "  ".repeat(indent) + propertyName,
              "Object" === typeName2 ? 3 > indent ? "" : "…" : typeName2
            ]);
            3 > indent && addObjectToProperties(value2, properties, indent + 1, prefix2);
            return;
          }
        case "function":
          value2 = "" === value2.name ? "() => {}" : value2.name + "() {}";
          break;
        case "string":
          value2 = value2 === OMITTED_PROP_ERROR ? "…" : JSON.stringify(value2);
          break;
        case "undefined":
          value2 = "undefined";
          break;
        case "boolean":
          value2 = value2 ? "true" : "false";
          break;
        default:
          value2 = String(value2);
      }
      properties.push([
        prefix2 + "  ".repeat(indent) + propertyName,
        value2
      ]);
    }
    function addObjectDiffToProperties(prev, next, properties, indent) {
      var isDeeplyEqual = true;
      for (key2 in prev)
        key2 in next || (properties.push([
          REMOVED + "  ".repeat(indent) + key2,
          "…"
        ]), isDeeplyEqual = false);
      for (var _key in next)
        if (_key in prev) {
          var key2 = prev[_key];
          var nextValue = next[_key];
          if (key2 !== nextValue) {
            if (0 === indent && "children" === _key)
              isDeeplyEqual = "  ".repeat(indent) + _key, properties.push(
                [REMOVED + isDeeplyEqual, "…"],
                [ADDED + isDeeplyEqual, "…"]
              );
            else {
              if (!(3 <= indent)) {
                if ("object" === typeof key2 && "object" === typeof nextValue && null !== key2 && null !== nextValue && key2.$$typeof === nextValue.$$typeof)
                  if (nextValue.$$typeof === REACT_ELEMENT_TYPE) {
                    if (key2.type === nextValue.type && key2.key === nextValue.key) {
                      key2 = getComponentNameFromType(nextValue.type) || "…";
                      isDeeplyEqual = "  ".repeat(indent) + _key;
                      key2 = "<" + key2 + " … />";
                      properties.push(
                        [REMOVED + isDeeplyEqual, key2],
                        [ADDED + isDeeplyEqual, key2]
                      );
                      isDeeplyEqual = false;
                      continue;
                    }
                  } else {
                    var prevKind = Object.prototype.toString.call(key2), nextKind = Object.prototype.toString.call(nextValue);
                    if (prevKind === nextKind && ("[object Object]" === nextKind || "[object Array]" === nextKind)) {
                      prevKind = [
                        UNCHANGED + "  ".repeat(indent) + _key,
                        "[object Array]" === nextKind ? "Array" : ""
                      ];
                      properties.push(prevKind);
                      nextKind = properties.length;
                      addObjectDiffToProperties(
                        key2,
                        nextValue,
                        properties,
                        indent + 1
                      ) ? nextKind === properties.length && (prevKind[1] = "Referentially unequal but deeply equal objects. Consider memoization.") : isDeeplyEqual = false;
                      continue;
                    }
                  }
                else if ("function" === typeof key2 && "function" === typeof nextValue && key2.name === nextValue.name && key2.length === nextValue.length && (prevKind = Function.prototype.toString.call(key2), nextKind = Function.prototype.toString.call(nextValue), prevKind === nextKind)) {
                  key2 = "" === nextValue.name ? "() => {}" : nextValue.name + "() {}";
                  properties.push([
                    UNCHANGED + "  ".repeat(indent) + _key,
                    key2 + " Referentially unequal function closure. Consider memoization."
                  ]);
                  continue;
                }
              }
              addValueToProperties(_key, key2, properties, indent, REMOVED);
              addValueToProperties(_key, nextValue, properties, indent, ADDED);
            }
            isDeeplyEqual = false;
          }
        } else
          properties.push([
            ADDED + "  ".repeat(indent) + _key,
            "…"
          ]), isDeeplyEqual = false;
      return isDeeplyEqual;
    }
    function setCurrentTrackFromLanes(lanes) {
      currentTrack = lanes & 63 ? "Blocking" : lanes & 64 ? "Gesture" : lanes & 4194176 ? "Transition" : lanes & 62914560 ? "Suspense" : lanes & 2080374784 ? "Idle" : "Other";
    }
    function logComponentTrigger(fiber, startTime, endTime, trigger) {
      supportsUserTiming && (reusableComponentOptions.start = startTime, reusableComponentOptions.end = endTime, reusableComponentDevToolDetails.color = "warning", reusableComponentDevToolDetails.tooltipText = trigger, reusableComponentDevToolDetails.properties = null, (fiber = fiber._debugTask) ? fiber.run(
        performance.measure.bind(
          performance,
          trigger,
          reusableComponentOptions
        )
      ) : performance.measure(trigger, reusableComponentOptions));
    }
    function logComponentReappeared(fiber, startTime, endTime) {
      logComponentTrigger(fiber, startTime, endTime, "Reconnect");
    }
    function logComponentRender(fiber, startTime, endTime, wasHydrated, committedLanes) {
      var name2 = getComponentNameFromFiber(fiber);
      if (null !== name2 && supportsUserTiming) {
        var alternate = fiber.alternate, selfTime = fiber.actualDuration;
        if (null === alternate || alternate.child !== fiber.child)
          for (var child = fiber.child; null !== child; child = child.sibling)
            selfTime -= child.actualDuration;
        wasHydrated = 0.5 > selfTime ? wasHydrated ? "tertiary-light" : "primary-light" : 10 > selfTime ? wasHydrated ? "tertiary" : "primary" : 100 > selfTime ? wasHydrated ? "tertiary-dark" : "primary-dark" : "error";
        var props = fiber.memoizedProps;
        selfTime = fiber._debugTask;
        null !== props && null !== alternate && alternate.memoizedProps !== props ? (child = [resuableChangedPropsEntry], props = addObjectDiffToProperties(
          alternate.memoizedProps,
          props,
          child,
          0
        ), 1 < child.length && (props && !alreadyWarnedForDeepEquality && 0 === (alternate.lanes & committedLanes) && 100 < fiber.actualDuration ? (alreadyWarnedForDeepEquality = true, child[0] = reusableDeeplyEqualPropsEntry, reusableComponentDevToolDetails.color = "warning", reusableComponentDevToolDetails.tooltipText = DEEP_EQUALITY_WARNING) : (reusableComponentDevToolDetails.color = wasHydrated, reusableComponentDevToolDetails.tooltipText = name2), reusableComponentDevToolDetails.properties = child, reusableComponentOptions.start = startTime, reusableComponentOptions.end = endTime, null != selfTime ? selfTime.run(
          performance.measure.bind(
            performance,
            "​" + name2,
            reusableComponentOptions
          )
        ) : performance.measure(
          "​" + name2,
          reusableComponentOptions
        ))) : null != selfTime ? selfTime.run(
          console.timeStamp.bind(
            console,
            name2,
            startTime,
            endTime,
            COMPONENTS_TRACK,
            void 0,
            wasHydrated
          )
        ) : console.timeStamp(
          name2,
          startTime,
          endTime,
          COMPONENTS_TRACK,
          void 0,
          wasHydrated
        );
      }
    }
    function logComponentErrored(fiber, startTime, endTime, errors2) {
      if (supportsUserTiming) {
        var name2 = getComponentNameFromFiber(fiber);
        if (null !== name2) {
          for (var debugTask = null, properties = [], i2 = 0; i2 < errors2.length; i2++) {
            var capturedValue = errors2[i2];
            null == debugTask && null !== capturedValue.source && (debugTask = capturedValue.source._debugTask);
            capturedValue = capturedValue.value;
            properties.push([
              "Error",
              "object" === typeof capturedValue && null !== capturedValue && "string" === typeof capturedValue.message ? String(capturedValue.message) : String(capturedValue)
            ]);
          }
          null !== fiber.key && addValueToProperties("key", fiber.key, properties, 0, "");
          null !== fiber.memoizedProps && addObjectToProperties(fiber.memoizedProps, properties, 0, "");
          null == debugTask && (debugTask = fiber._debugTask);
          fiber = {
            start: startTime,
            end: endTime,
            detail: {
              devtools: {
                color: "error",
                track: COMPONENTS_TRACK,
                tooltipText: 13 === fiber.tag ? "Hydration failed" : "Error boundary caught an error",
                properties
              }
            }
          };
          debugTask ? debugTask.run(
            performance.measure.bind(performance, "​" + name2, fiber)
          ) : performance.measure("​" + name2, fiber);
        }
      }
    }
    function logComponentEffect(fiber, startTime, endTime, selfTime, errors2) {
      if (null !== errors2) {
        if (supportsUserTiming) {
          var name2 = getComponentNameFromFiber(fiber);
          if (null !== name2) {
            selfTime = [];
            for (var i2 = 0; i2 < errors2.length; i2++) {
              var error2 = errors2[i2].value;
              selfTime.push([
                "Error",
                "object" === typeof error2 && null !== error2 && "string" === typeof error2.message ? String(error2.message) : String(error2)
              ]);
            }
            null !== fiber.key && addValueToProperties("key", fiber.key, selfTime, 0, "");
            null !== fiber.memoizedProps && addObjectToProperties(fiber.memoizedProps, selfTime, 0, "");
            startTime = {
              start: startTime,
              end: endTime,
              detail: {
                devtools: {
                  color: "error",
                  track: COMPONENTS_TRACK,
                  tooltipText: "A lifecycle or effect errored",
                  properties: selfTime
                }
              }
            };
            (fiber = fiber._debugTask) ? fiber.run(
              performance.measure.bind(
                performance,
                "​" + name2,
                startTime
              )
            ) : performance.measure("​" + name2, startTime);
          }
        }
      } else
        name2 = getComponentNameFromFiber(fiber), null !== name2 && supportsUserTiming && (errors2 = 1 > selfTime ? "secondary-light" : 100 > selfTime ? "secondary" : 500 > selfTime ? "secondary-dark" : "error", (fiber = fiber._debugTask) ? fiber.run(
          console.timeStamp.bind(
            console,
            name2,
            startTime,
            endTime,
            COMPONENTS_TRACK,
            void 0,
            errors2
          )
        ) : console.timeStamp(
          name2,
          startTime,
          endTime,
          COMPONENTS_TRACK,
          void 0,
          errors2
        ));
    }
    function logRenderPhase(startTime, endTime, lanes, debugTask) {
      if (supportsUserTiming && !(endTime <= startTime)) {
        var color = (lanes & 738197653) === lanes ? "tertiary-dark" : "primary-dark";
        lanes = (lanes & 536870912) === lanes ? "Prepared" : (lanes & 201326741) === lanes ? "Hydrated" : "Render";
        debugTask ? debugTask.run(
          console.timeStamp.bind(
            console,
            lanes,
            startTime,
            endTime,
            currentTrack,
            LANES_TRACK_GROUP,
            color
          )
        ) : console.timeStamp(
          lanes,
          startTime,
          endTime,
          currentTrack,
          LANES_TRACK_GROUP,
          color
        );
      }
    }
    function logSuspendedRenderPhase(startTime, endTime, lanes, debugTask) {
      !supportsUserTiming || endTime <= startTime || (lanes = (lanes & 738197653) === lanes ? "tertiary-dark" : "primary-dark", debugTask ? debugTask.run(
        console.timeStamp.bind(
          console,
          "Prewarm",
          startTime,
          endTime,
          currentTrack,
          LANES_TRACK_GROUP,
          lanes
        )
      ) : console.timeStamp(
        "Prewarm",
        startTime,
        endTime,
        currentTrack,
        LANES_TRACK_GROUP,
        lanes
      ));
    }
    function logSuspendedWithDelayPhase(startTime, endTime, lanes, debugTask) {
      !supportsUserTiming || endTime <= startTime || (lanes = (lanes & 738197653) === lanes ? "tertiary-dark" : "primary-dark", debugTask ? debugTask.run(
        console.timeStamp.bind(
          console,
          "Suspended",
          startTime,
          endTime,
          currentTrack,
          LANES_TRACK_GROUP,
          lanes
        )
      ) : console.timeStamp(
        "Suspended",
        startTime,
        endTime,
        currentTrack,
        LANES_TRACK_GROUP,
        lanes
      ));
    }
    function logRecoveredRenderPhase(startTime, endTime, lanes, recoverableErrors, hydrationFailed, debugTask) {
      if (supportsUserTiming && !(endTime <= startTime)) {
        lanes = [];
        for (var i2 = 0; i2 < recoverableErrors.length; i2++) {
          var error2 = recoverableErrors[i2].value;
          lanes.push([
            "Recoverable Error",
            "object" === typeof error2 && null !== error2 && "string" === typeof error2.message ? String(error2.message) : String(error2)
          ]);
        }
        startTime = {
          start: startTime,
          end: endTime,
          detail: {
            devtools: {
              color: "primary-dark",
              track: currentTrack,
              trackGroup: LANES_TRACK_GROUP,
              tooltipText: hydrationFailed ? "Hydration Failed" : "Recovered after Error",
              properties: lanes
            }
          }
        };
        debugTask ? debugTask.run(
          performance.measure.bind(performance, "Recovered", startTime)
        ) : performance.measure("Recovered", startTime);
      }
    }
    function logErroredRenderPhase(startTime, endTime, lanes, debugTask) {
      !supportsUserTiming || endTime <= startTime || (debugTask ? debugTask.run(
        console.timeStamp.bind(
          console,
          "Errored",
          startTime,
          endTime,
          currentTrack,
          LANES_TRACK_GROUP,
          "error"
        )
      ) : console.timeStamp(
        "Errored",
        startTime,
        endTime,
        currentTrack,
        LANES_TRACK_GROUP,
        "error"
      ));
    }
    function logSuspendedCommitPhase(startTime, endTime, reason, debugTask) {
      !supportsUserTiming || endTime <= startTime || (debugTask ? debugTask.run(
        console.timeStamp.bind(
          console,
          reason,
          startTime,
          endTime,
          currentTrack,
          LANES_TRACK_GROUP,
          "secondary-light"
        )
      ) : console.timeStamp(
        reason,
        startTime,
        endTime,
        currentTrack,
        LANES_TRACK_GROUP,
        "secondary-light"
      ));
    }
    function logCommitErrored(startTime, endTime, errors2, passive2, debugTask) {
      if (supportsUserTiming && !(endTime <= startTime)) {
        for (var properties = [], i2 = 0; i2 < errors2.length; i2++) {
          var error2 = errors2[i2].value;
          properties.push([
            "Error",
            "object" === typeof error2 && null !== error2 && "string" === typeof error2.message ? String(error2.message) : String(error2)
          ]);
        }
        startTime = {
          start: startTime,
          end: endTime,
          detail: {
            devtools: {
              color: "error",
              track: currentTrack,
              trackGroup: LANES_TRACK_GROUP,
              tooltipText: passive2 ? "Remaining Effects Errored" : "Commit Errored",
              properties
            }
          }
        };
        debugTask ? debugTask.run(
          performance.measure.bind(performance, "Errored", startTime)
        ) : performance.measure("Errored", startTime);
      }
    }
    function logAnimatingPhase(startTime, endTime, debugTask) {
      !supportsUserTiming || endTime <= startTime || console.timeStamp(
        "Animating",
        startTime,
        endTime,
        currentTrack,
        LANES_TRACK_GROUP,
        "secondary-dark"
      );
    }
    function finishQueueingConcurrentUpdates() {
      for (var endIndex = concurrentQueuesIndex, i2 = concurrentlyUpdatedLanes = concurrentQueuesIndex = 0; i2 < endIndex; ) {
        var fiber = concurrentQueues[i2];
        concurrentQueues[i2++] = null;
        var queue = concurrentQueues[i2];
        concurrentQueues[i2++] = null;
        var update2 = concurrentQueues[i2];
        concurrentQueues[i2++] = null;
        var lane = concurrentQueues[i2];
        concurrentQueues[i2++] = null;
        if (null !== queue && null !== update2) {
          var pending = queue.pending;
          null === pending ? update2.next = update2 : (update2.next = pending.next, pending.next = update2);
          queue.pending = update2;
        }
        0 !== lane && markUpdateLaneFromFiberToRoot(fiber, update2, lane);
      }
    }
    function enqueueUpdate$1(fiber, queue, update2, lane) {
      concurrentQueues[concurrentQueuesIndex++] = fiber;
      concurrentQueues[concurrentQueuesIndex++] = queue;
      concurrentQueues[concurrentQueuesIndex++] = update2;
      concurrentQueues[concurrentQueuesIndex++] = lane;
      concurrentlyUpdatedLanes |= lane;
      fiber.lanes |= lane;
      fiber = fiber.alternate;
      null !== fiber && (fiber.lanes |= lane);
    }
    function enqueueConcurrentHookUpdate(fiber, queue, update2, lane) {
      enqueueUpdate$1(fiber, queue, update2, lane);
      return getRootForUpdatedFiber(fiber);
    }
    function enqueueConcurrentRenderForLane(fiber, lane) {
      enqueueUpdate$1(fiber, null, null, lane);
      return getRootForUpdatedFiber(fiber);
    }
    function markUpdateLaneFromFiberToRoot(sourceFiber, update2, lane) {
      sourceFiber.lanes |= lane;
      var alternate = sourceFiber.alternate;
      null !== alternate && (alternate.lanes |= lane);
      for (var isHidden = false, parent = sourceFiber.return; null !== parent; )
        parent.childLanes |= lane, alternate = parent.alternate, null !== alternate && (alternate.childLanes |= lane), 22 === parent.tag && (sourceFiber = parent.stateNode, null === sourceFiber || sourceFiber._visibility & OffscreenVisible || (isHidden = true)), sourceFiber = parent, parent = parent.return;
      return 3 === sourceFiber.tag ? (parent = sourceFiber.stateNode, isHidden && null !== update2 && (isHidden = 31 - clz322(lane), sourceFiber = parent.hiddenUpdates, alternate = sourceFiber[isHidden], null === alternate ? sourceFiber[isHidden] = [update2] : alternate.push(update2), update2.lane = lane | 536870912), parent) : null;
    }
    function getRootForUpdatedFiber(sourceFiber) {
      if (nestedUpdateCount > NESTED_UPDATE_LIMIT)
        throw nestedPassiveUpdateCount = nestedUpdateCount = 0, rootWithPassiveNestedUpdates = rootWithNestedUpdates = null, Error(
          "Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops."
        );
      nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT && (nestedPassiveUpdateCount = 0, rootWithPassiveNestedUpdates = null, console.error(
        "Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render."
      ));
      null === sourceFiber.alternate && 0 !== (sourceFiber.flags & 4098) && warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber);
      for (var node2 = sourceFiber, parent = node2.return; null !== parent; )
        null === node2.alternate && 0 !== (node2.flags & 4098) && warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber), node2 = parent, parent = node2.return;
      return 3 === node2.tag ? node2.stateNode : null;
    }
    function resolveFunctionForHotReloading(type) {
      if (null === resolveFamily) return type;
      var family = resolveFamily(type);
      return void 0 === family ? type : family.current;
    }
    function resolveForwardRefForHotReloading(type) {
      if (null === resolveFamily) return type;
      var family = resolveFamily(type);
      return void 0 === family ? null !== type && void 0 !== type && "function" === typeof type.render && (family = resolveFunctionForHotReloading(type.render), type.render !== family) ? (family = { $$typeof: REACT_FORWARD_REF_TYPE, render: family }, void 0 !== type.displayName && (family.displayName = type.displayName), family) : type : family.current;
    }
    function isCompatibleFamilyForHotReloading(fiber, element) {
      if (null === resolveFamily) return false;
      var prevType = fiber.elementType;
      element = element.type;
      var needsCompareFamilies = false, $$typeofNextType = "object" === typeof element && null !== element ? element.$$typeof : null;
      switch (fiber.tag) {
        case 1:
          "function" === typeof element && (needsCompareFamilies = true);
          break;
        case 0:
          "function" === typeof element ? needsCompareFamilies = true : $$typeofNextType === REACT_LAZY_TYPE && (needsCompareFamilies = true);
          break;
        case 11:
          $$typeofNextType === REACT_FORWARD_REF_TYPE ? needsCompareFamilies = true : $$typeofNextType === REACT_LAZY_TYPE && (needsCompareFamilies = true);
          break;
        case 14:
        case 15:
          $$typeofNextType === REACT_MEMO_TYPE ? needsCompareFamilies = true : $$typeofNextType === REACT_LAZY_TYPE && (needsCompareFamilies = true);
          break;
        default:
          return false;
      }
      return needsCompareFamilies && (fiber = resolveFamily(prevType), void 0 !== fiber && fiber === resolveFamily(element)) ? true : false;
    }
    function markFailedErrorBoundaryForHotReloading(fiber) {
      null !== resolveFamily && "function" === typeof WeakSet && (null === failedBoundaries && (failedBoundaries = /* @__PURE__ */ new WeakSet()), failedBoundaries.add(fiber));
    }
    function scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) {
      do {
        var _fiber = fiber, alternate = _fiber.alternate, child = _fiber.child, sibling2 = _fiber.sibling, tag = _fiber.tag;
        _fiber = _fiber.type;
        var candidateType = null;
        switch (tag) {
          case 0:
          case 15:
          case 1:
            candidateType = _fiber;
            break;
          case 11:
            candidateType = _fiber.render;
        }
        if (null === resolveFamily)
          throw Error("Expected resolveFamily to be set during hot reload.");
        var needsRender = false;
        _fiber = false;
        null !== candidateType && (candidateType = resolveFamily(candidateType), void 0 !== candidateType && (staleFamilies.has(candidateType) ? _fiber = true : updatedFamilies.has(candidateType) && (1 === tag ? _fiber = true : needsRender = true)));
        null !== failedBoundaries && (failedBoundaries.has(fiber) || null !== alternate && failedBoundaries.has(alternate)) && (_fiber = true);
        _fiber && (fiber._debugNeedsRemount = true);
        if (_fiber || needsRender)
          alternate = enqueueConcurrentRenderForLane(fiber, 2), null !== alternate && scheduleUpdateOnFiber(alternate, fiber, 2);
        null === child || _fiber || scheduleFibersWithFamiliesRecursively(
          child,
          updatedFamilies,
          staleFamilies
        );
        if (null === sibling2) break;
        fiber = sibling2;
      } while (1);
    }
    function FiberNode(tag, pendingProps, key2, mode) {
      this.tag = tag;
      this.key = key2;
      this.sibling = this.child = this.return = this.stateNode = this.type = this.elementType = null;
      this.index = 0;
      this.refCleanup = this.ref = null;
      this.pendingProps = pendingProps;
      this.dependencies = this.memoizedState = this.updateQueue = this.memoizedProps = null;
      this.mode = mode;
      this.subtreeFlags = this.flags = 0;
      this.deletions = null;
      this.childLanes = this.lanes = 0;
      this.alternate = null;
      this.actualDuration = -0;
      this.actualStartTime = -1.1;
      this.treeBaseDuration = this.selfBaseDuration = -0;
      this._debugTask = this._debugStack = this._debugOwner = this._debugInfo = null;
      this._debugNeedsRemount = false;
      this._debugHookTypes = null;
      hasBadMapPolyfill || "function" !== typeof Object.preventExtensions || Object.preventExtensions(this);
    }
    function shouldConstruct(Component2) {
      Component2 = Component2.prototype;
      return !(!Component2 || !Component2.isReactComponent);
    }
    function createWorkInProgress(current22, pendingProps) {
      var workInProgress2 = current22.alternate;
      null === workInProgress2 ? (workInProgress2 = createFiber(
        current22.tag,
        pendingProps,
        current22.key,
        current22.mode
      ), workInProgress2.elementType = current22.elementType, workInProgress2.type = current22.type, workInProgress2.stateNode = current22.stateNode, workInProgress2._debugOwner = current22._debugOwner, workInProgress2._debugStack = current22._debugStack, workInProgress2._debugTask = current22._debugTask, workInProgress2._debugHookTypes = current22._debugHookTypes, workInProgress2.alternate = current22, current22.alternate = workInProgress2) : (workInProgress2.pendingProps = pendingProps, workInProgress2.type = current22.type, workInProgress2.flags = 0, workInProgress2.subtreeFlags = 0, workInProgress2.deletions = null, workInProgress2.actualDuration = -0, workInProgress2.actualStartTime = -1.1);
      workInProgress2.flags = current22.flags & 65011712;
      workInProgress2.childLanes = current22.childLanes;
      workInProgress2.lanes = current22.lanes;
      workInProgress2.child = current22.child;
      workInProgress2.memoizedProps = current22.memoizedProps;
      workInProgress2.memoizedState = current22.memoizedState;
      workInProgress2.updateQueue = current22.updateQueue;
      pendingProps = current22.dependencies;
      workInProgress2.dependencies = null === pendingProps ? null : {
        lanes: pendingProps.lanes,
        firstContext: pendingProps.firstContext,
        _debugThenableState: pendingProps._debugThenableState
      };
      workInProgress2.sibling = current22.sibling;
      workInProgress2.index = current22.index;
      workInProgress2.ref = current22.ref;
      workInProgress2.refCleanup = current22.refCleanup;
      workInProgress2.selfBaseDuration = current22.selfBaseDuration;
      workInProgress2.treeBaseDuration = current22.treeBaseDuration;
      workInProgress2._debugInfo = current22._debugInfo;
      workInProgress2._debugNeedsRemount = current22._debugNeedsRemount;
      switch (workInProgress2.tag) {
        case 0:
        case 15:
          workInProgress2.type = resolveFunctionForHotReloading(current22.type);
          break;
        case 1:
          workInProgress2.type = resolveFunctionForHotReloading(current22.type);
          break;
        case 11:
          workInProgress2.type = resolveForwardRefForHotReloading(current22.type);
      }
      return workInProgress2;
    }
    function resetWorkInProgress(workInProgress2, renderLanes2) {
      workInProgress2.flags &= 65011714;
      var current22 = workInProgress2.alternate;
      null === current22 ? (workInProgress2.childLanes = 0, workInProgress2.lanes = renderLanes2, workInProgress2.child = null, workInProgress2.subtreeFlags = 0, workInProgress2.memoizedProps = null, workInProgress2.memoizedState = null, workInProgress2.updateQueue = null, workInProgress2.dependencies = null, workInProgress2.stateNode = null, workInProgress2.selfBaseDuration = 0, workInProgress2.treeBaseDuration = 0) : (workInProgress2.childLanes = current22.childLanes, workInProgress2.lanes = current22.lanes, workInProgress2.child = current22.child, workInProgress2.subtreeFlags = 0, workInProgress2.deletions = null, workInProgress2.memoizedProps = current22.memoizedProps, workInProgress2.memoizedState = current22.memoizedState, workInProgress2.updateQueue = current22.updateQueue, workInProgress2.type = current22.type, renderLanes2 = current22.dependencies, workInProgress2.dependencies = null === renderLanes2 ? null : {
        lanes: renderLanes2.lanes,
        firstContext: renderLanes2.firstContext,
        _debugThenableState: renderLanes2._debugThenableState
      }, workInProgress2.selfBaseDuration = current22.selfBaseDuration, workInProgress2.treeBaseDuration = current22.treeBaseDuration);
      return workInProgress2;
    }
    function createFiberFromTypeAndProps(type, key2, pendingProps, owner, mode, lanes) {
      var fiberTag = 0, resolvedType = type;
      if ("function" === typeof type)
        shouldConstruct(type) && (fiberTag = 1), resolvedType = resolveFunctionForHotReloading(resolvedType);
      else if ("string" === typeof type)
        fiberTag = getHostContext(), fiberTag = isHostHoistableType(type, pendingProps, fiberTag) ? 26 : "html" === type || "head" === type || "body" === type ? 27 : 5;
      else
        a: switch (type) {
          case REACT_ACTIVITY_TYPE:
            return key2 = createFiber(31, pendingProps, key2, mode), key2.elementType = REACT_ACTIVITY_TYPE, key2.lanes = lanes, key2;
          case REACT_FRAGMENT_TYPE:
            return createFiberFromFragment(
              pendingProps.children,
              mode,
              lanes,
              key2
            );
          case REACT_STRICT_MODE_TYPE:
            fiberTag = 8;
            mode |= StrictLegacyMode;
            mode |= StrictEffectsMode;
            break;
          case REACT_PROFILER_TYPE:
            return type = pendingProps, owner = mode, "string" !== typeof type.id && console.error(
              'Profiler must specify an "id" of type `string` as a prop. Received the type `%s` instead.',
              typeof type.id
            ), key2 = createFiber(12, type, key2, owner | ProfileMode), key2.elementType = REACT_PROFILER_TYPE, key2.lanes = lanes, key2.stateNode = { effectDuration: 0, passiveEffectDuration: 0 }, key2;
          case REACT_SUSPENSE_TYPE:
            return key2 = createFiber(13, pendingProps, key2, mode), key2.elementType = REACT_SUSPENSE_TYPE, key2.lanes = lanes, key2;
          case REACT_SUSPENSE_LIST_TYPE:
            return key2 = createFiber(19, pendingProps, key2, mode), key2.elementType = REACT_SUSPENSE_LIST_TYPE, key2.lanes = lanes, key2;
          default:
            if ("object" === typeof type && null !== type)
              switch (type.$$typeof) {
                case REACT_CONTEXT_TYPE:
                  fiberTag = 10;
                  break a;
                case REACT_CONSUMER_TYPE:
                  fiberTag = 9;
                  break a;
                case REACT_FORWARD_REF_TYPE:
                  fiberTag = 11;
                  resolvedType = resolveForwardRefForHotReloading(resolvedType);
                  break a;
                case REACT_MEMO_TYPE:
                  fiberTag = 14;
                  break a;
                case REACT_LAZY_TYPE:
                  fiberTag = 16;
                  resolvedType = null;
                  break a;
              }
            resolvedType = "";
            if (void 0 === type || "object" === typeof type && null !== type && 0 === Object.keys(type).length)
              resolvedType += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.";
            null === type ? pendingProps = "null" : isArrayImpl(type) ? pendingProps = "array" : void 0 !== type && type.$$typeof === REACT_ELEMENT_TYPE ? (pendingProps = "<" + (getComponentNameFromType(type.type) || "Unknown") + " />", resolvedType = " Did you accidentally export a JSX literal instead of a component?") : pendingProps = typeof type;
            (fiberTag = owner ? getComponentNameFromOwner(owner) : null) && (resolvedType += "\n\nCheck the render method of `" + fiberTag + "`.");
            fiberTag = 29;
            pendingProps = Error(
              "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + (pendingProps + "." + resolvedType)
            );
            resolvedType = null;
        }
      key2 = createFiber(fiberTag, pendingProps, key2, mode);
      key2.elementType = type;
      key2.type = resolvedType;
      key2.lanes = lanes;
      key2._debugOwner = owner;
      return key2;
    }
    function createFiberFromElement(element, mode, lanes) {
      mode = createFiberFromTypeAndProps(
        element.type,
        element.key,
        element.props,
        element._owner,
        mode,
        lanes
      );
      mode._debugOwner = element._owner;
      mode._debugStack = element._debugStack;
      mode._debugTask = element._debugTask;
      return mode;
    }
    function createFiberFromFragment(elements, mode, lanes, key2) {
      elements = createFiber(7, elements, key2, mode);
      elements.lanes = lanes;
      return elements;
    }
    function createFiberFromText(content2, mode, lanes) {
      content2 = createFiber(6, content2, null, mode);
      content2.lanes = lanes;
      return content2;
    }
    function createFiberFromDehydratedFragment(dehydratedNode) {
      var fiber = createFiber(18, null, null, NoMode);
      fiber.stateNode = dehydratedNode;
      return fiber;
    }
    function createFiberFromPortal(portal, mode, lanes) {
      mode = createFiber(
        4,
        null !== portal.children ? portal.children : [],
        portal.key,
        mode
      );
      mode.lanes = lanes;
      mode.stateNode = {
        containerInfo: portal.containerInfo,
        pendingChildren: null,
        implementation: portal.implementation
      };
      return mode;
    }
    function createCapturedValueAtFiber(value2, source2) {
      if ("object" === typeof value2 && null !== value2) {
        var existing = CapturedStacks.get(value2);
        if (void 0 !== existing) return existing;
        source2 = {
          value: value2,
          source: source2,
          stack: getStackByFiberInDevAndProd(source2)
        };
        CapturedStacks.set(value2, source2);
        return source2;
      }
      return {
        value: value2,
        source: source2,
        stack: getStackByFiberInDevAndProd(source2)
      };
    }
    function pushTreeFork(workInProgress2, totalChildren) {
      warnIfNotHydrating();
      forkStack[forkStackIndex++] = treeForkCount;
      forkStack[forkStackIndex++] = treeForkProvider;
      treeForkProvider = workInProgress2;
      treeForkCount = totalChildren;
    }
    function pushTreeId(workInProgress2, totalChildren, index) {
      warnIfNotHydrating();
      idStack[idStackIndex++] = treeContextId;
      idStack[idStackIndex++] = treeContextOverflow;
      idStack[idStackIndex++] = treeContextProvider;
      treeContextProvider = workInProgress2;
      var baseIdWithLeadingBit = treeContextId;
      workInProgress2 = treeContextOverflow;
      var baseLength = 32 - clz322(baseIdWithLeadingBit) - 1;
      baseIdWithLeadingBit &= ~(1 << baseLength);
      index += 1;
      var length2 = 32 - clz322(totalChildren) + baseLength;
      if (30 < length2) {
        var numberOfOverflowBits = baseLength - baseLength % 5;
        length2 = (baseIdWithLeadingBit & (1 << numberOfOverflowBits) - 1).toString(32);
        baseIdWithLeadingBit >>= numberOfOverflowBits;
        baseLength -= numberOfOverflowBits;
        treeContextId = 1 << 32 - clz322(totalChildren) + baseLength | index << baseLength | baseIdWithLeadingBit;
        treeContextOverflow = length2 + workInProgress2;
      } else
        treeContextId = 1 << length2 | index << baseLength | baseIdWithLeadingBit, treeContextOverflow = workInProgress2;
    }
    function pushMaterializedTreeId(workInProgress2) {
      warnIfNotHydrating();
      null !== workInProgress2.return && (pushTreeFork(workInProgress2, 1), pushTreeId(workInProgress2, 1, 0));
    }
    function popTreeContext(workInProgress2) {
      for (; workInProgress2 === treeForkProvider; )
        treeForkProvider = forkStack[--forkStackIndex], forkStack[forkStackIndex] = null, treeForkCount = forkStack[--forkStackIndex], forkStack[forkStackIndex] = null;
      for (; workInProgress2 === treeContextProvider; )
        treeContextProvider = idStack[--idStackIndex], idStack[idStackIndex] = null, treeContextOverflow = idStack[--idStackIndex], idStack[idStackIndex] = null, treeContextId = idStack[--idStackIndex], idStack[idStackIndex] = null;
    }
    function getSuspendedTreeContext() {
      warnIfNotHydrating();
      return null !== treeContextProvider ? { id: treeContextId, overflow: treeContextOverflow } : null;
    }
    function restoreSuspendedTreeContext(workInProgress2, suspendedContext) {
      warnIfNotHydrating();
      idStack[idStackIndex++] = treeContextId;
      idStack[idStackIndex++] = treeContextOverflow;
      idStack[idStackIndex++] = treeContextProvider;
      treeContextId = suspendedContext.id;
      treeContextOverflow = suspendedContext.overflow;
      treeContextProvider = workInProgress2;
    }
    function warnIfNotHydrating() {
      isHydrating || console.error(
        "Expected to be hydrating. This is a bug in React. Please file an issue."
      );
    }
    function buildHydrationDiffNode(fiber, distanceFromLeaf) {
      if (null === fiber.return) {
        if (null === hydrationDiffRootDEV)
          hydrationDiffRootDEV = {
            fiber,
            children: [],
            serverProps: void 0,
            serverTail: [],
            distanceFromLeaf
          };
        else {
          if (hydrationDiffRootDEV.fiber !== fiber)
            throw Error(
              "Saw multiple hydration diff roots in a pass. This is a bug in React."
            );
          hydrationDiffRootDEV.distanceFromLeaf > distanceFromLeaf && (hydrationDiffRootDEV.distanceFromLeaf = distanceFromLeaf);
        }
        return hydrationDiffRootDEV;
      }
      var siblings = buildHydrationDiffNode(
        fiber.return,
        distanceFromLeaf + 1
      ).children;
      if (0 < siblings.length && siblings[siblings.length - 1].fiber === fiber)
        return siblings = siblings[siblings.length - 1], siblings.distanceFromLeaf > distanceFromLeaf && (siblings.distanceFromLeaf = distanceFromLeaf), siblings;
      distanceFromLeaf = {
        fiber,
        children: [],
        serverProps: void 0,
        serverTail: [],
        distanceFromLeaf
      };
      siblings.push(distanceFromLeaf);
      return distanceFromLeaf;
    }
    function warnIfHydrating() {
      isHydrating && console.error(
        "We should not be hydrating here. This is a bug in React. Please file a bug."
      );
    }
    function warnNonHydratedInstance(fiber, rejectedCandidate) {
      didSuspendOrErrorDEV || (fiber = buildHydrationDiffNode(fiber, 0), fiber.serverProps = null, null !== rejectedCandidate && (rejectedCandidate = describeHydratableInstanceForDevWarnings(rejectedCandidate), fiber.serverTail.push(rejectedCandidate)));
    }
    function throwOnHydrationMismatch(fiber) {
      var fromText = 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : false, diff2 = "", diffRoot = hydrationDiffRootDEV;
      null !== diffRoot && (hydrationDiffRootDEV = null, diff2 = describeDiff(diffRoot));
      queueHydrationError(
        createCapturedValueAtFiber(
          Error(
            "Hydration failed because the server rendered " + (fromText ? "text" : "HTML") + " didn't match the client. As a result this tree will be regenerated on the client. This can happen if a SSR-ed Client Component used:\n\n- A server/client branch `if (typeof window !== 'undefined')`.\n- Variable input such as `Date.now()` or `Math.random()` which changes each time it's called.\n- Date formatting in a user's locale which doesn't match the server.\n- External changing data without sending a snapshot of it along with the HTML.\n- Invalid HTML tag nesting.\n\nIt can also happen if the client has a browser extension installed which messes with the HTML before React loaded.\n\nhttps://react.dev/link/hydration-mismatch" + diff2
          ),
          fiber
        )
      );
      throw HydrationMismatchException;
    }
    function prepareToHydrateHostInstance(fiber) {
      var didHydrate = fiber.stateNode;
      var type = fiber.type, props = fiber.memoizedProps;
      didHydrate[internalInstanceKey] = fiber;
      didHydrate[internalPropsKey] = props;
      validatePropertiesInDevelopment(type, props);
      switch (type) {
        case "dialog":
          listenToNonDelegatedEvent("cancel", didHydrate);
          listenToNonDelegatedEvent("close", didHydrate);
          break;
        case "iframe":
        case "object":
        case "embed":
          listenToNonDelegatedEvent("load", didHydrate);
          break;
        case "video":
        case "audio":
          for (type = 0; type < mediaEventTypes.length; type++)
            listenToNonDelegatedEvent(mediaEventTypes[type], didHydrate);
          break;
        case "source":
          listenToNonDelegatedEvent("error", didHydrate);
          break;
        case "img":
        case "image":
        case "link":
          listenToNonDelegatedEvent("error", didHydrate);
          listenToNonDelegatedEvent("load", didHydrate);
          break;
        case "details":
          listenToNonDelegatedEvent("toggle", didHydrate);
          break;
        case "input":
          checkControlledValueProps("input", props);
          listenToNonDelegatedEvent("invalid", didHydrate);
          validateInputProps(didHydrate, props);
          initInput(
            didHydrate,
            props.value,
            props.defaultValue,
            props.checked,
            props.defaultChecked,
            props.type,
            props.name,
            true
          );
          break;
        case "option":
          validateOptionProps(didHydrate, props);
          break;
        case "select":
          checkControlledValueProps("select", props);
          listenToNonDelegatedEvent("invalid", didHydrate);
          validateSelectProps(didHydrate, props);
          break;
        case "textarea":
          checkControlledValueProps("textarea", props), listenToNonDelegatedEvent("invalid", didHydrate), validateTextareaProps(didHydrate, props), initTextarea(
            didHydrate,
            props.value,
            props.defaultValue,
            props.children
          );
      }
      type = props.children;
      "string" !== typeof type && "number" !== typeof type && "bigint" !== typeof type || didHydrate.textContent === "" + type || true === props.suppressHydrationWarning || checkForUnmatchedText(didHydrate.textContent, type) ? (null != props.popover && (listenToNonDelegatedEvent("beforetoggle", didHydrate), listenToNonDelegatedEvent("toggle", didHydrate)), null != props.onScroll && listenToNonDelegatedEvent("scroll", didHydrate), null != props.onScrollEnd && listenToNonDelegatedEvent("scrollend", didHydrate), null != props.onClick && (didHydrate.onclick = noop$12), didHydrate = true) : didHydrate = false;
      didHydrate || throwOnHydrationMismatch(fiber, true);
    }
    function popToNextHostParent(fiber) {
      for (hydrationParentFiber = fiber.return; hydrationParentFiber; )
        switch (hydrationParentFiber.tag) {
          case 5:
          case 31:
          case 13:
            rootOrSingletonContext = false;
            return;
          case 27:
          case 3:
            rootOrSingletonContext = true;
            return;
          default:
            hydrationParentFiber = hydrationParentFiber.return;
        }
    }
    function popHydrationState(fiber) {
      if (fiber !== hydrationParentFiber) return false;
      if (!isHydrating)
        return popToNextHostParent(fiber), isHydrating = true, false;
      var tag = fiber.tag, JSCompiler_temp;
      if (JSCompiler_temp = 3 !== tag && 27 !== tag) {
        if (JSCompiler_temp = 5 === tag)
          JSCompiler_temp = fiber.type, JSCompiler_temp = !("form" !== JSCompiler_temp && "button" !== JSCompiler_temp) || shouldSetTextContent(fiber.type, fiber.memoizedProps);
        JSCompiler_temp = !JSCompiler_temp;
      }
      if (JSCompiler_temp && nextHydratableInstance) {
        for (JSCompiler_temp = nextHydratableInstance; JSCompiler_temp; ) {
          var diffNode = buildHydrationDiffNode(fiber, 0), description2 = describeHydratableInstanceForDevWarnings(JSCompiler_temp);
          diffNode.serverTail.push(description2);
          JSCompiler_temp = "Suspense" === description2.type ? getNextHydratableInstanceAfterHydrationBoundary(JSCompiler_temp) : getNextHydratable(JSCompiler_temp.nextSibling);
        }
        throwOnHydrationMismatch(fiber);
      }
      popToNextHostParent(fiber);
      if (13 === tag) {
        fiber = fiber.memoizedState;
        fiber = null !== fiber ? fiber.dehydrated : null;
        if (!fiber)
          throw Error(
            "Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue."
          );
        nextHydratableInstance = getNextHydratableInstanceAfterHydrationBoundary(fiber);
      } else if (31 === tag) {
        fiber = fiber.memoizedState;
        fiber = null !== fiber ? fiber.dehydrated : null;
        if (!fiber)
          throw Error(
            "Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue."
          );
        nextHydratableInstance = getNextHydratableInstanceAfterHydrationBoundary(fiber);
      } else
        27 === tag ? (tag = nextHydratableInstance, isSingletonScope(fiber.type) ? (fiber = previousHydratableOnEnteringScopedSingleton, previousHydratableOnEnteringScopedSingleton = null, nextHydratableInstance = fiber) : nextHydratableInstance = tag) : nextHydratableInstance = hydrationParentFiber ? getNextHydratable(fiber.stateNode.nextSibling) : null;
      return true;
    }
    function resetHydrationState() {
      nextHydratableInstance = hydrationParentFiber = null;
      didSuspendOrErrorDEV = isHydrating = false;
    }
    function upgradeHydrationErrorsToRecoverable() {
      var queuedErrors = hydrationErrors;
      null !== queuedErrors && (null === workInProgressRootRecoverableErrors ? workInProgressRootRecoverableErrors = queuedErrors : workInProgressRootRecoverableErrors.push.apply(
        workInProgressRootRecoverableErrors,
        queuedErrors
      ), hydrationErrors = null);
      return queuedErrors;
    }
    function queueHydrationError(error2) {
      null === hydrationErrors ? hydrationErrors = [error2] : hydrationErrors.push(error2);
    }
    function emitPendingHydrationWarnings() {
      var diffRoot = hydrationDiffRootDEV;
      if (null !== diffRoot) {
        hydrationDiffRootDEV = null;
        for (var diff2 = describeDiff(diffRoot); 0 < diffRoot.children.length; )
          diffRoot = diffRoot.children[0];
        runWithFiberInDEV(diffRoot.fiber, function() {
          console.error(
            "A tree hydrated but some attributes of the server rendered HTML didn't match the client properties. This won't be patched up. This can happen if a SSR-ed Client Component used:\n\n- A server/client branch `if (typeof window !== 'undefined')`.\n- Variable input such as `Date.now()` or `Math.random()` which changes each time it's called.\n- Date formatting in a user's locale which doesn't match the server.\n- External changing data without sending a snapshot of it along with the HTML.\n- Invalid HTML tag nesting.\n\nIt can also happen if the client has a browser extension installed which messes with the HTML before React loaded.\n\n%s%s",
            "https://react.dev/link/hydration-mismatch",
            diff2
          );
        });
      }
    }
    function resetContextDependencies() {
      lastContextDependency = currentlyRenderingFiber$1 = null;
      isDisallowedContextReadInDEV = false;
    }
    function pushProvider(providerFiber, context, nextValue) {
      push2(valueCursor, context._currentValue, providerFiber);
      context._currentValue = nextValue;
      push2(rendererCursorDEV, context._currentRenderer, providerFiber);
      void 0 !== context._currentRenderer && null !== context._currentRenderer && context._currentRenderer !== rendererSigil && console.error(
        "Detected multiple renderers concurrently rendering the same context provider. This is currently unsupported."
      );
      context._currentRenderer = rendererSigil;
    }
    function popProvider(context, providerFiber) {
      context._currentValue = valueCursor.current;
      var currentRenderer = rendererCursorDEV.current;
      pop2(rendererCursorDEV, providerFiber);
      context._currentRenderer = currentRenderer;
      pop2(valueCursor, providerFiber);
    }
    function scheduleContextWorkOnParentPath(parent, renderLanes2, propagationRoot) {
      for (; null !== parent; ) {
        var alternate = parent.alternate;
        (parent.childLanes & renderLanes2) !== renderLanes2 ? (parent.childLanes |= renderLanes2, null !== alternate && (alternate.childLanes |= renderLanes2)) : null !== alternate && (alternate.childLanes & renderLanes2) !== renderLanes2 && (alternate.childLanes |= renderLanes2);
        if (parent === propagationRoot) break;
        parent = parent.return;
      }
      parent !== propagationRoot && console.error(
        "Expected to find the propagation root when scheduling context work. This error is likely caused by a bug in React. Please file an issue."
      );
    }
    function propagateContextChanges(workInProgress2, contexts, renderLanes2, forcePropagateEntireTree) {
      var fiber = workInProgress2.child;
      null !== fiber && (fiber.return = workInProgress2);
      for (; null !== fiber; ) {
        var list2 = fiber.dependencies;
        if (null !== list2) {
          var nextFiber = fiber.child;
          list2 = list2.firstContext;
          a: for (; null !== list2; ) {
            var dependency = list2;
            list2 = fiber;
            for (var i2 = 0; i2 < contexts.length; i2++)
              if (dependency.context === contexts[i2]) {
                list2.lanes |= renderLanes2;
                dependency = list2.alternate;
                null !== dependency && (dependency.lanes |= renderLanes2);
                scheduleContextWorkOnParentPath(
                  list2.return,
                  renderLanes2,
                  workInProgress2
                );
                forcePropagateEntireTree || (nextFiber = null);
                break a;
              }
            list2 = dependency.next;
          }
        } else if (18 === fiber.tag) {
          nextFiber = fiber.return;
          if (null === nextFiber)
            throw Error(
              "We just came from a parent so we must have had a parent. This is a bug in React."
            );
          nextFiber.lanes |= renderLanes2;
          list2 = nextFiber.alternate;
          null !== list2 && (list2.lanes |= renderLanes2);
          scheduleContextWorkOnParentPath(
            nextFiber,
            renderLanes2,
            workInProgress2
          );
          nextFiber = null;
        } else nextFiber = fiber.child;
        if (null !== nextFiber) nextFiber.return = fiber;
        else
          for (nextFiber = fiber; null !== nextFiber; ) {
            if (nextFiber === workInProgress2) {
              nextFiber = null;
              break;
            }
            fiber = nextFiber.sibling;
            if (null !== fiber) {
              fiber.return = nextFiber.return;
              nextFiber = fiber;
              break;
            }
            nextFiber = nextFiber.return;
          }
        fiber = nextFiber;
      }
    }
    function propagateParentContextChanges(current22, workInProgress2, renderLanes2, forcePropagateEntireTree) {
      current22 = null;
      for (var parent = workInProgress2, isInsidePropagationBailout = false; null !== parent; ) {
        if (!isInsidePropagationBailout) {
          if (0 !== (parent.flags & 524288)) isInsidePropagationBailout = true;
          else if (0 !== (parent.flags & 262144)) break;
        }
        if (10 === parent.tag) {
          var currentParent = parent.alternate;
          if (null === currentParent)
            throw Error("Should have a current fiber. This is a bug in React.");
          currentParent = currentParent.memoizedProps;
          if (null !== currentParent) {
            var context = parent.type;
            objectIs(parent.pendingProps.value, currentParent.value) || (null !== current22 ? current22.push(context) : current22 = [context]);
          }
        } else if (parent === hostTransitionProviderCursor.current) {
          currentParent = parent.alternate;
          if (null === currentParent)
            throw Error("Should have a current fiber. This is a bug in React.");
          currentParent.memoizedState.memoizedState !== parent.memoizedState.memoizedState && (null !== current22 ? current22.push(HostTransitionContext) : current22 = [HostTransitionContext]);
        }
        parent = parent.return;
      }
      null !== current22 && propagateContextChanges(
        workInProgress2,
        current22,
        renderLanes2,
        forcePropagateEntireTree
      );
      workInProgress2.flags |= 262144;
    }
    function checkIfContextChanged(currentDependencies) {
      for (currentDependencies = currentDependencies.firstContext; null !== currentDependencies; ) {
        if (!objectIs(
          currentDependencies.context._currentValue,
          currentDependencies.memoizedValue
        ))
          return true;
        currentDependencies = currentDependencies.next;
      }
      return false;
    }
    function prepareToReadContext(workInProgress2) {
      currentlyRenderingFiber$1 = workInProgress2;
      lastContextDependency = null;
      workInProgress2 = workInProgress2.dependencies;
      null !== workInProgress2 && (workInProgress2.firstContext = null);
    }
    function readContext(context) {
      isDisallowedContextReadInDEV && console.error(
        "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()."
      );
      return readContextForConsumer(currentlyRenderingFiber$1, context);
    }
    function readContextDuringReconciliation(consumer, context) {
      null === currentlyRenderingFiber$1 && prepareToReadContext(consumer);
      return readContextForConsumer(consumer, context);
    }
    function readContextForConsumer(consumer, context) {
      var value2 = context._currentValue;
      context = { context, memoizedValue: value2, next: null };
      if (null === lastContextDependency) {
        if (null === consumer)
          throw Error(
            "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()."
          );
        lastContextDependency = context;
        consumer.dependencies = {
          lanes: 0,
          firstContext: context,
          _debugThenableState: null
        };
        consumer.flags |= 524288;
      } else lastContextDependency = lastContextDependency.next = context;
      return value2;
    }
    function createCache() {
      return {
        controller: new AbortControllerLocal(),
        data: /* @__PURE__ */ new Map(),
        refCount: 0
      };
    }
    function retainCache(cache) {
      cache.controller.signal.aborted && console.warn(
        "A cache instance was retained after it was already freed. This likely indicates a bug in React."
      );
      cache.refCount++;
    }
    function releaseCache(cache) {
      cache.refCount--;
      0 > cache.refCount && console.warn(
        "A cache instance was released after it was already freed. This likely indicates a bug in React."
      );
      0 === cache.refCount && scheduleCallback$2(NormalPriority, function() {
        cache.controller.abort();
      });
    }
    function startUpdateTimerByLane(lane, method, fiber) {
      if (0 !== (lane & 127))
        0 > blockingUpdateTime && (blockingUpdateTime = now2(), blockingUpdateTask = createTask(method), blockingUpdateMethodName = method, null != fiber && (blockingUpdateComponentName = getComponentNameFromFiber(fiber)), (executionContext & (RenderContext | CommitContext)) !== NoContext && (componentEffectSpawnedUpdate = true, blockingUpdateType = SPAWNED_UPDATE), lane = resolveEventTimeStamp(), method = resolveEventType(), lane !== blockingEventRepeatTime || method !== blockingEventType ? blockingEventRepeatTime = -1.1 : null !== method && (blockingUpdateType = SPAWNED_UPDATE), blockingEventTime = lane, blockingEventType = method);
      else if (0 !== (lane & 4194048) && 0 > transitionUpdateTime && (transitionUpdateTime = now2(), transitionUpdateTask = createTask(method), transitionUpdateMethodName = method, null != fiber && (transitionUpdateComponentName = getComponentNameFromFiber(fiber)), 0 > transitionStartTime)) {
        lane = resolveEventTimeStamp();
        method = resolveEventType();
        if (lane !== transitionEventRepeatTime || method !== transitionEventType)
          transitionEventRepeatTime = -1.1;
        transitionEventTime = lane;
        transitionEventType = method;
      }
    }
    function startHostActionTimer(fiber) {
      if (0 > blockingUpdateTime) {
        blockingUpdateTime = now2();
        blockingUpdateTask = null != fiber._debugTask ? fiber._debugTask : null;
        (executionContext & (RenderContext | CommitContext)) !== NoContext && (blockingUpdateType = SPAWNED_UPDATE);
        var newEventTime = resolveEventTimeStamp(), newEventType = resolveEventType();
        newEventTime !== blockingEventRepeatTime || newEventType !== blockingEventType ? blockingEventRepeatTime = -1.1 : null !== newEventType && (blockingUpdateType = SPAWNED_UPDATE);
        blockingEventTime = newEventTime;
        blockingEventType = newEventType;
      }
      if (0 > transitionUpdateTime && (transitionUpdateTime = now2(), transitionUpdateTask = null != fiber._debugTask ? fiber._debugTask : null, 0 > transitionStartTime)) {
        fiber = resolveEventTimeStamp();
        newEventTime = resolveEventType();
        if (fiber !== transitionEventRepeatTime || newEventTime !== transitionEventType)
          transitionEventRepeatTime = -1.1;
        transitionEventTime = fiber;
        transitionEventType = newEventTime;
      }
    }
    function pushNestedEffectDurations() {
      var prevEffectDuration = profilerEffectDuration;
      profilerEffectDuration = 0;
      return prevEffectDuration;
    }
    function popNestedEffectDurations(prevEffectDuration) {
      var elapsedTime = profilerEffectDuration;
      profilerEffectDuration = prevEffectDuration;
      return elapsedTime;
    }
    function bubbleNestedEffectDurations(prevEffectDuration) {
      var elapsedTime = profilerEffectDuration;
      profilerEffectDuration += prevEffectDuration;
      return elapsedTime;
    }
    function resetComponentEffectTimers() {
      componentEffectEndTime = componentEffectStartTime = -1.1;
    }
    function pushComponentEffectStart() {
      var prevEffectStart = componentEffectStartTime;
      componentEffectStartTime = -1.1;
      return prevEffectStart;
    }
    function popComponentEffectStart(prevEffectStart) {
      0 <= prevEffectStart && (componentEffectStartTime = prevEffectStart);
    }
    function pushComponentEffectDuration() {
      var prevEffectDuration = componentEffectDuration;
      componentEffectDuration = -0;
      return prevEffectDuration;
    }
    function popComponentEffectDuration(prevEffectDuration) {
      0 <= prevEffectDuration && (componentEffectDuration = prevEffectDuration);
    }
    function pushComponentEffectErrors() {
      var prevErrors = componentEffectErrors;
      componentEffectErrors = null;
      return prevErrors;
    }
    function pushComponentEffectDidSpawnUpdate() {
      var prev = componentEffectSpawnedUpdate;
      componentEffectSpawnedUpdate = false;
      return prev;
    }
    function startProfilerTimer(fiber) {
      profilerStartTime = now2();
      0 > fiber.actualStartTime && (fiber.actualStartTime = profilerStartTime);
    }
    function stopProfilerTimerIfRunningAndRecordDuration(fiber) {
      if (0 <= profilerStartTime) {
        var elapsedTime = now2() - profilerStartTime;
        fiber.actualDuration += elapsedTime;
        fiber.selfBaseDuration = elapsedTime;
        profilerStartTime = -1;
      }
    }
    function stopProfilerTimerIfRunningAndRecordIncompleteDuration(fiber) {
      if (0 <= profilerStartTime) {
        var elapsedTime = now2() - profilerStartTime;
        fiber.actualDuration += elapsedTime;
        profilerStartTime = -1;
      }
    }
    function recordEffectDuration() {
      if (0 <= profilerStartTime) {
        var endTime = now2(), elapsedTime = endTime - profilerStartTime;
        profilerStartTime = -1;
        profilerEffectDuration += elapsedTime;
        componentEffectDuration += elapsedTime;
        componentEffectEndTime = endTime;
      }
    }
    function recordEffectError(errorInfo) {
      null === componentEffectErrors && (componentEffectErrors = []);
      componentEffectErrors.push(errorInfo);
      null === commitErrors && (commitErrors = []);
      commitErrors.push(errorInfo);
    }
    function startEffectTimer() {
      profilerStartTime = now2();
      0 > componentEffectStartTime && (componentEffectStartTime = profilerStartTime);
    }
    function transferActualDuration(fiber) {
      for (var child = fiber.child; child; )
        fiber.actualDuration += child.actualDuration, child = child.sibling;
    }
    function entangleAsyncAction(transition, thenable) {
      if (null === currentEntangledListeners) {
        var entangledListeners = currentEntangledListeners = [];
        currentEntangledPendingCount = 0;
        currentEntangledLane = requestTransitionLane();
        currentEntangledActionThenable = {
          status: "pending",
          value: void 0,
          then: function(resolve2) {
            entangledListeners.push(resolve2);
          }
        };
      }
      currentEntangledPendingCount++;
      thenable.then(pingEngtangledActionScope, pingEngtangledActionScope);
      return thenable;
    }
    function pingEngtangledActionScope() {
      if (0 === --currentEntangledPendingCount && (-1 < transitionUpdateTime || (transitionStartTime = -1.1), null !== currentEntangledListeners)) {
        null !== currentEntangledActionThenable && (currentEntangledActionThenable.status = "fulfilled");
        var listeners = currentEntangledListeners;
        currentEntangledListeners = null;
        currentEntangledLane = 0;
        currentEntangledActionThenable = null;
        for (var i2 = 0; i2 < listeners.length; i2++) (0, listeners[i2])();
      }
    }
    function chainThenableValue(thenable, result2) {
      var listeners = [], thenableWithOverride = {
        status: "pending",
        value: null,
        reason: null,
        then: function(resolve2) {
          listeners.push(resolve2);
        }
      };
      thenable.then(
        function() {
          thenableWithOverride.status = "fulfilled";
          thenableWithOverride.value = result2;
          for (var i2 = 0; i2 < listeners.length; i2++) (0, listeners[i2])(result2);
        },
        function(error2) {
          thenableWithOverride.status = "rejected";
          thenableWithOverride.reason = error2;
          for (error2 = 0; error2 < listeners.length; error2++)
            (0, listeners[error2])(void 0);
        }
      );
      return thenableWithOverride;
    }
    function peekCacheFromPool() {
      var cacheResumedFromPreviousRender = resumedCache.current;
      return null !== cacheResumedFromPreviousRender ? cacheResumedFromPreviousRender : workInProgressRoot.pooledCache;
    }
    function pushTransition(offscreenWorkInProgress, prevCachePool) {
      null === prevCachePool ? push2(resumedCache, resumedCache.current, offscreenWorkInProgress) : push2(resumedCache, prevCachePool.pool, offscreenWorkInProgress);
    }
    function getSuspendedCache() {
      var cacheFromPool = peekCacheFromPool();
      return null === cacheFromPool ? null : { parent: CacheContext._currentValue, pool: cacheFromPool };
    }
    function createThenableState() {
      return { didWarnAboutUncachedPromise: false, thenables: [] };
    }
    function isThenableResolved(thenable) {
      thenable = thenable.status;
      return "fulfilled" === thenable || "rejected" === thenable;
    }
    function trackUsedThenable(thenableState2, thenable, index) {
      null !== ReactSharedInternals.actQueue && (ReactSharedInternals.didUsePromise = true);
      var trackedThenables = thenableState2.thenables;
      index = trackedThenables[index];
      void 0 === index ? trackedThenables.push(thenable) : index !== thenable && (thenableState2.didWarnAboutUncachedPromise || (thenableState2.didWarnAboutUncachedPromise = true, console.error(
        "A component was suspended by an uncached promise. Creating promises inside a Client Component or hook is not yet supported, except via a Suspense-compatible library or framework."
      )), thenable.then(noop$12, noop$12), thenable = index);
      if (void 0 === thenable._debugInfo) {
        thenableState2 = performance.now();
        trackedThenables = thenable.displayName;
        var ioInfo = {
          name: "string" === typeof trackedThenables ? trackedThenables : "Promise",
          start: thenableState2,
          end: thenableState2,
          value: thenable
        };
        thenable._debugInfo = [{ awaited: ioInfo }];
        "fulfilled" !== thenable.status && "rejected" !== thenable.status && (thenableState2 = function() {
          ioInfo.end = performance.now();
        }, thenable.then(thenableState2, thenableState2));
      }
      switch (thenable.status) {
        case "fulfilled":
          return thenable.value;
        case "rejected":
          throw thenableState2 = thenable.reason, checkIfUseWrappedInAsyncCatch(thenableState2), thenableState2;
        default:
          if ("string" === typeof thenable.status)
            thenable.then(noop$12, noop$12);
          else {
            thenableState2 = workInProgressRoot;
            if (null !== thenableState2 && 100 < thenableState2.shellSuspendCounter)
              throw Error(
                "An unknown Component is an async Client Component. Only Server Components can be async at the moment. This error is often caused by accidentally adding `'use client'` to a module that was originally written for the server."
              );
            thenableState2 = thenable;
            thenableState2.status = "pending";
            thenableState2.then(
              function(fulfilledValue) {
                if ("pending" === thenable.status) {
                  var fulfilledThenable = thenable;
                  fulfilledThenable.status = "fulfilled";
                  fulfilledThenable.value = fulfilledValue;
                }
              },
              function(error2) {
                if ("pending" === thenable.status) {
                  var rejectedThenable = thenable;
                  rejectedThenable.status = "rejected";
                  rejectedThenable.reason = error2;
                }
              }
            );
          }
          switch (thenable.status) {
            case "fulfilled":
              return thenable.value;
            case "rejected":
              throw thenableState2 = thenable.reason, checkIfUseWrappedInAsyncCatch(thenableState2), thenableState2;
          }
          suspendedThenable = thenable;
          needsToResetSuspendedThenableDEV = true;
          throw SuspenseException;
      }
    }
    function resolveLazy(lazyType) {
      try {
        return callLazyInitInDEV(lazyType);
      } catch (x) {
        if (null !== x && "object" === typeof x && "function" === typeof x.then)
          throw suspendedThenable = x, needsToResetSuspendedThenableDEV = true, SuspenseException;
        throw x;
      }
    }
    function getSuspendedThenable() {
      if (null === suspendedThenable)
        throw Error(
          "Expected a suspended thenable. This is a bug in React. Please file an issue."
        );
      var thenable = suspendedThenable;
      suspendedThenable = null;
      needsToResetSuspendedThenableDEV = false;
      return thenable;
    }
    function checkIfUseWrappedInAsyncCatch(rejectedReason) {
      if (rejectedReason === SuspenseException || rejectedReason === SuspenseActionException)
        throw Error(
          "Hooks are not supported inside an async component. This error is often caused by accidentally adding `'use client'` to a module that was originally written for the server."
        );
    }
    function pushDebugInfo(debugInfo) {
      var previousDebugInfo = currentDebugInfo;
      null != debugInfo && (currentDebugInfo = null === previousDebugInfo ? debugInfo : previousDebugInfo.concat(debugInfo));
      return previousDebugInfo;
    }
    function getCurrentDebugTask() {
      var debugInfo = currentDebugInfo;
      if (null != debugInfo) {
        for (var i2 = debugInfo.length - 1; 0 <= i2; i2--)
          if (null != debugInfo[i2].name) {
            var debugTask = debugInfo[i2].debugTask;
            if (null != debugTask) return debugTask;
          }
      }
      return null;
    }
    function validateFragmentProps(element, fiber, returnFiber) {
      for (var keys2 = Object.keys(element.props), i2 = 0; i2 < keys2.length; i2++) {
        var key2 = keys2[i2];
        if ("children" !== key2 && "key" !== key2) {
          null === fiber && (fiber = createFiberFromElement(element, returnFiber.mode, 0), fiber._debugInfo = currentDebugInfo, fiber.return = returnFiber);
          runWithFiberInDEV(
            fiber,
            function(erroredKey) {
              console.error(
                "Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",
                erroredKey
              );
            },
            key2
          );
          break;
        }
      }
    }
    function unwrapThenable(thenable) {
      var index = thenableIndexCounter$1;
      thenableIndexCounter$1 += 1;
      null === thenableState$1 && (thenableState$1 = createThenableState());
      return trackUsedThenable(thenableState$1, thenable, index);
    }
    function coerceRef(workInProgress2, element) {
      element = element.props.ref;
      workInProgress2.ref = void 0 !== element ? element : null;
    }
    function throwOnInvalidObjectTypeImpl(returnFiber, newChild) {
      if (newChild.$$typeof === REACT_LEGACY_ELEMENT_TYPE)
        throw Error(
          'A React Element from an older version of React was rendered. This is not supported. It can happen if:\n- Multiple copies of the "react" package is used.\n- A library pre-bundled an old copy of "react" or "react/jsx-runtime".\n- A compiler tries to "inline" JSX instead of using the runtime.'
        );
      returnFiber = Object.prototype.toString.call(newChild);
      throw Error(
        "Objects are not valid as a React child (found: " + ("[object Object]" === returnFiber ? "object with keys {" + Object.keys(newChild).join(", ") + "}" : returnFiber) + "). If you meant to render a collection of children, use an array instead."
      );
    }
    function throwOnInvalidObjectType(returnFiber, newChild) {
      var debugTask = getCurrentDebugTask();
      null !== debugTask ? debugTask.run(
        throwOnInvalidObjectTypeImpl.bind(null, returnFiber, newChild)
      ) : throwOnInvalidObjectTypeImpl(returnFiber, newChild);
    }
    function warnOnFunctionTypeImpl(returnFiber, invalidChild) {
      var parentName = getComponentNameFromFiber(returnFiber) || "Component";
      ownerHasFunctionTypeWarning[parentName] || (ownerHasFunctionTypeWarning[parentName] = true, invalidChild = invalidChild.displayName || invalidChild.name || "Component", 3 === returnFiber.tag ? console.error(
        "Functions are not valid as a React child. This may happen if you return %s instead of <%s /> from render. Or maybe you meant to call this function rather than return it.\n  root.render(%s)",
        invalidChild,
        invalidChild,
        invalidChild
      ) : console.error(
        "Functions are not valid as a React child. This may happen if you return %s instead of <%s /> from render. Or maybe you meant to call this function rather than return it.\n  <%s>{%s}</%s>",
        invalidChild,
        invalidChild,
        parentName,
        invalidChild,
        parentName
      ));
    }
    function warnOnFunctionType(returnFiber, invalidChild) {
      var debugTask = getCurrentDebugTask();
      null !== debugTask ? debugTask.run(
        warnOnFunctionTypeImpl.bind(null, returnFiber, invalidChild)
      ) : warnOnFunctionTypeImpl(returnFiber, invalidChild);
    }
    function warnOnSymbolTypeImpl(returnFiber, invalidChild) {
      var parentName = getComponentNameFromFiber(returnFiber) || "Component";
      ownerHasSymbolTypeWarning[parentName] || (ownerHasSymbolTypeWarning[parentName] = true, invalidChild = String(invalidChild), 3 === returnFiber.tag ? console.error(
        "Symbols are not valid as a React child.\n  root.render(%s)",
        invalidChild
      ) : console.error(
        "Symbols are not valid as a React child.\n  <%s>%s</%s>",
        parentName,
        invalidChild,
        parentName
      ));
    }
    function warnOnSymbolType(returnFiber, invalidChild) {
      var debugTask = getCurrentDebugTask();
      null !== debugTask ? debugTask.run(
        warnOnSymbolTypeImpl.bind(null, returnFiber, invalidChild)
      ) : warnOnSymbolTypeImpl(returnFiber, invalidChild);
    }
    function createChildReconciler(shouldTrackSideEffects) {
      function deleteChild(returnFiber, childToDelete) {
        if (shouldTrackSideEffects) {
          var deletions = returnFiber.deletions;
          null === deletions ? (returnFiber.deletions = [childToDelete], returnFiber.flags |= 16) : deletions.push(childToDelete);
        }
      }
      function deleteRemainingChildren(returnFiber, currentFirstChild) {
        if (!shouldTrackSideEffects) return null;
        for (; null !== currentFirstChild; )
          deleteChild(returnFiber, currentFirstChild), currentFirstChild = currentFirstChild.sibling;
        return null;
      }
      function mapRemainingChildren(currentFirstChild) {
        for (var existingChildren = /* @__PURE__ */ new Map(); null !== currentFirstChild; )
          null !== currentFirstChild.key ? existingChildren.set(currentFirstChild.key, currentFirstChild) : existingChildren.set(currentFirstChild.index, currentFirstChild), currentFirstChild = currentFirstChild.sibling;
        return existingChildren;
      }
      function useFiber(fiber, pendingProps) {
        fiber = createWorkInProgress(fiber, pendingProps);
        fiber.index = 0;
        fiber.sibling = null;
        return fiber;
      }
      function placeChild(newFiber, lastPlacedIndex, newIndex) {
        newFiber.index = newIndex;
        if (!shouldTrackSideEffects)
          return newFiber.flags |= 1048576, lastPlacedIndex;
        newIndex = newFiber.alternate;
        if (null !== newIndex)
          return newIndex = newIndex.index, newIndex < lastPlacedIndex ? (newFiber.flags |= 67108866, lastPlacedIndex) : newIndex;
        newFiber.flags |= 67108866;
        return lastPlacedIndex;
      }
      function placeSingleChild(newFiber) {
        shouldTrackSideEffects && null === newFiber.alternate && (newFiber.flags |= 67108866);
        return newFiber;
      }
      function updateTextNode(returnFiber, current22, textContent, lanes) {
        if (null === current22 || 6 !== current22.tag)
          return current22 = createFiberFromText(
            textContent,
            returnFiber.mode,
            lanes
          ), current22.return = returnFiber, current22._debugOwner = returnFiber, current22._debugTask = returnFiber._debugTask, current22._debugInfo = currentDebugInfo, current22;
        current22 = useFiber(current22, textContent);
        current22.return = returnFiber;
        current22._debugInfo = currentDebugInfo;
        return current22;
      }
      function updateElement(returnFiber, current22, element, lanes) {
        var elementType = element.type;
        if (elementType === REACT_FRAGMENT_TYPE)
          return current22 = updateFragment(
            returnFiber,
            current22,
            element.props.children,
            lanes,
            element.key
          ), validateFragmentProps(element, current22, returnFiber), current22;
        if (null !== current22 && (current22.elementType === elementType || isCompatibleFamilyForHotReloading(current22, element) || "object" === typeof elementType && null !== elementType && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === current22.type))
          return current22 = useFiber(current22, element.props), coerceRef(current22, element), current22.return = returnFiber, current22._debugOwner = element._owner, current22._debugInfo = currentDebugInfo, current22;
        current22 = createFiberFromElement(element, returnFiber.mode, lanes);
        coerceRef(current22, element);
        current22.return = returnFiber;
        current22._debugInfo = currentDebugInfo;
        return current22;
      }
      function updatePortal(returnFiber, current22, portal, lanes) {
        if (null === current22 || 4 !== current22.tag || current22.stateNode.containerInfo !== portal.containerInfo || current22.stateNode.implementation !== portal.implementation)
          return current22 = createFiberFromPortal(portal, returnFiber.mode, lanes), current22.return = returnFiber, current22._debugInfo = currentDebugInfo, current22;
        current22 = useFiber(current22, portal.children || []);
        current22.return = returnFiber;
        current22._debugInfo = currentDebugInfo;
        return current22;
      }
      function updateFragment(returnFiber, current22, fragment, lanes, key2) {
        if (null === current22 || 7 !== current22.tag)
          return current22 = createFiberFromFragment(
            fragment,
            returnFiber.mode,
            lanes,
            key2
          ), current22.return = returnFiber, current22._debugOwner = returnFiber, current22._debugTask = returnFiber._debugTask, current22._debugInfo = currentDebugInfo, current22;
        current22 = useFiber(current22, fragment);
        current22.return = returnFiber;
        current22._debugInfo = currentDebugInfo;
        return current22;
      }
      function createChild(returnFiber, newChild, lanes) {
        if ("string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild)
          return newChild = createFiberFromText(
            "" + newChild,
            returnFiber.mode,
            lanes
          ), newChild.return = returnFiber, newChild._debugOwner = returnFiber, newChild._debugTask = returnFiber._debugTask, newChild._debugInfo = currentDebugInfo, newChild;
        if ("object" === typeof newChild && null !== newChild) {
          switch (newChild.$$typeof) {
            case REACT_ELEMENT_TYPE:
              return lanes = createFiberFromElement(
                newChild,
                returnFiber.mode,
                lanes
              ), coerceRef(lanes, newChild), lanes.return = returnFiber, returnFiber = pushDebugInfo(newChild._debugInfo), lanes._debugInfo = currentDebugInfo, currentDebugInfo = returnFiber, lanes;
            case REACT_PORTAL_TYPE:
              return newChild = createFiberFromPortal(
                newChild,
                returnFiber.mode,
                lanes
              ), newChild.return = returnFiber, newChild._debugInfo = currentDebugInfo, newChild;
            case REACT_LAZY_TYPE:
              var _prevDebugInfo = pushDebugInfo(newChild._debugInfo);
              newChild = resolveLazy(newChild);
              returnFiber = createChild(returnFiber, newChild, lanes);
              currentDebugInfo = _prevDebugInfo;
              return returnFiber;
          }
          if (isArrayImpl(newChild) || getIteratorFn(newChild))
            return lanes = createFiberFromFragment(
              newChild,
              returnFiber.mode,
              lanes,
              null
            ), lanes.return = returnFiber, lanes._debugOwner = returnFiber, lanes._debugTask = returnFiber._debugTask, returnFiber = pushDebugInfo(newChild._debugInfo), lanes._debugInfo = currentDebugInfo, currentDebugInfo = returnFiber, lanes;
          if ("function" === typeof newChild.then)
            return _prevDebugInfo = pushDebugInfo(newChild._debugInfo), returnFiber = createChild(
              returnFiber,
              unwrapThenable(newChild),
              lanes
            ), currentDebugInfo = _prevDebugInfo, returnFiber;
          if (newChild.$$typeof === REACT_CONTEXT_TYPE)
            return createChild(
              returnFiber,
              readContextDuringReconciliation(returnFiber, newChild),
              lanes
            );
          throwOnInvalidObjectType(returnFiber, newChild);
        }
        "function" === typeof newChild && warnOnFunctionType(returnFiber, newChild);
        "symbol" === typeof newChild && warnOnSymbolType(returnFiber, newChild);
        return null;
      }
      function updateSlot(returnFiber, oldFiber, newChild, lanes) {
        var key2 = null !== oldFiber ? oldFiber.key : null;
        if ("string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild)
          return null !== key2 ? null : updateTextNode(returnFiber, oldFiber, "" + newChild, lanes);
        if ("object" === typeof newChild && null !== newChild) {
          switch (newChild.$$typeof) {
            case REACT_ELEMENT_TYPE:
              return newChild.key === key2 ? (key2 = pushDebugInfo(newChild._debugInfo), returnFiber = updateElement(
                returnFiber,
                oldFiber,
                newChild,
                lanes
              ), currentDebugInfo = key2, returnFiber) : null;
            case REACT_PORTAL_TYPE:
              return newChild.key === key2 ? updatePortal(returnFiber, oldFiber, newChild, lanes) : null;
            case REACT_LAZY_TYPE:
              return key2 = pushDebugInfo(newChild._debugInfo), newChild = resolveLazy(newChild), returnFiber = updateSlot(
                returnFiber,
                oldFiber,
                newChild,
                lanes
              ), currentDebugInfo = key2, returnFiber;
          }
          if (isArrayImpl(newChild) || getIteratorFn(newChild)) {
            if (null !== key2) return null;
            key2 = pushDebugInfo(newChild._debugInfo);
            returnFiber = updateFragment(
              returnFiber,
              oldFiber,
              newChild,
              lanes,
              null
            );
            currentDebugInfo = key2;
            return returnFiber;
          }
          if ("function" === typeof newChild.then)
            return key2 = pushDebugInfo(newChild._debugInfo), returnFiber = updateSlot(
              returnFiber,
              oldFiber,
              unwrapThenable(newChild),
              lanes
            ), currentDebugInfo = key2, returnFiber;
          if (newChild.$$typeof === REACT_CONTEXT_TYPE)
            return updateSlot(
              returnFiber,
              oldFiber,
              readContextDuringReconciliation(returnFiber, newChild),
              lanes
            );
          throwOnInvalidObjectType(returnFiber, newChild);
        }
        "function" === typeof newChild && warnOnFunctionType(returnFiber, newChild);
        "symbol" === typeof newChild && warnOnSymbolType(returnFiber, newChild);
        return null;
      }
      function updateFromMap(existingChildren, returnFiber, newIdx, newChild, lanes) {
        if ("string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild)
          return existingChildren = existingChildren.get(newIdx) || null, updateTextNode(returnFiber, existingChildren, "" + newChild, lanes);
        if ("object" === typeof newChild && null !== newChild) {
          switch (newChild.$$typeof) {
            case REACT_ELEMENT_TYPE:
              return newIdx = existingChildren.get(
                null === newChild.key ? newIdx : newChild.key
              ) || null, existingChildren = pushDebugInfo(newChild._debugInfo), returnFiber = updateElement(
                returnFiber,
                newIdx,
                newChild,
                lanes
              ), currentDebugInfo = existingChildren, returnFiber;
            case REACT_PORTAL_TYPE:
              return existingChildren = existingChildren.get(
                null === newChild.key ? newIdx : newChild.key
              ) || null, updatePortal(returnFiber, existingChildren, newChild, lanes);
            case REACT_LAZY_TYPE:
              var _prevDebugInfo7 = pushDebugInfo(newChild._debugInfo);
              newChild = resolveLazy(newChild);
              returnFiber = updateFromMap(
                existingChildren,
                returnFiber,
                newIdx,
                newChild,
                lanes
              );
              currentDebugInfo = _prevDebugInfo7;
              return returnFiber;
          }
          if (isArrayImpl(newChild) || getIteratorFn(newChild))
            return newIdx = existingChildren.get(newIdx) || null, existingChildren = pushDebugInfo(newChild._debugInfo), returnFiber = updateFragment(
              returnFiber,
              newIdx,
              newChild,
              lanes,
              null
            ), currentDebugInfo = existingChildren, returnFiber;
          if ("function" === typeof newChild.then)
            return _prevDebugInfo7 = pushDebugInfo(newChild._debugInfo), returnFiber = updateFromMap(
              existingChildren,
              returnFiber,
              newIdx,
              unwrapThenable(newChild),
              lanes
            ), currentDebugInfo = _prevDebugInfo7, returnFiber;
          if (newChild.$$typeof === REACT_CONTEXT_TYPE)
            return updateFromMap(
              existingChildren,
              returnFiber,
              newIdx,
              readContextDuringReconciliation(returnFiber, newChild),
              lanes
            );
          throwOnInvalidObjectType(returnFiber, newChild);
        }
        "function" === typeof newChild && warnOnFunctionType(returnFiber, newChild);
        "symbol" === typeof newChild && warnOnSymbolType(returnFiber, newChild);
        return null;
      }
      function warnOnInvalidKey(returnFiber, workInProgress2, child, knownKeys) {
        if ("object" !== typeof child || null === child) return knownKeys;
        switch (child.$$typeof) {
          case REACT_ELEMENT_TYPE:
          case REACT_PORTAL_TYPE:
            warnForMissingKey(returnFiber, workInProgress2, child);
            var key2 = child.key;
            if ("string" !== typeof key2) break;
            if (null === knownKeys) {
              knownKeys = /* @__PURE__ */ new Set();
              knownKeys.add(key2);
              break;
            }
            if (!knownKeys.has(key2)) {
              knownKeys.add(key2);
              break;
            }
            runWithFiberInDEV(workInProgress2, function() {
              console.error(
                "Encountered two children with the same key, `%s`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.",
                key2
              );
            });
            break;
          case REACT_LAZY_TYPE:
            child = resolveLazy(child), warnOnInvalidKey(returnFiber, workInProgress2, child, knownKeys);
        }
        return knownKeys;
      }
      function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, lanes) {
        for (var knownKeys = null, resultingFirstChild = null, previousNewFiber = null, oldFiber = currentFirstChild, newIdx = currentFirstChild = 0, nextOldFiber = null; null !== oldFiber && newIdx < newChildren.length; newIdx++) {
          oldFiber.index > newIdx ? (nextOldFiber = oldFiber, oldFiber = null) : nextOldFiber = oldFiber.sibling;
          var newFiber = updateSlot(
            returnFiber,
            oldFiber,
            newChildren[newIdx],
            lanes
          );
          if (null === newFiber) {
            null === oldFiber && (oldFiber = nextOldFiber);
            break;
          }
          knownKeys = warnOnInvalidKey(
            returnFiber,
            newFiber,
            newChildren[newIdx],
            knownKeys
          );
          shouldTrackSideEffects && oldFiber && null === newFiber.alternate && deleteChild(returnFiber, oldFiber);
          currentFirstChild = placeChild(newFiber, currentFirstChild, newIdx);
          null === previousNewFiber ? resultingFirstChild = newFiber : previousNewFiber.sibling = newFiber;
          previousNewFiber = newFiber;
          oldFiber = nextOldFiber;
        }
        if (newIdx === newChildren.length)
          return deleteRemainingChildren(returnFiber, oldFiber), isHydrating && pushTreeFork(returnFiber, newIdx), resultingFirstChild;
        if (null === oldFiber) {
          for (; newIdx < newChildren.length; newIdx++)
            oldFiber = createChild(returnFiber, newChildren[newIdx], lanes), null !== oldFiber && (knownKeys = warnOnInvalidKey(
              returnFiber,
              oldFiber,
              newChildren[newIdx],
              knownKeys
            ), currentFirstChild = placeChild(
              oldFiber,
              currentFirstChild,
              newIdx
            ), null === previousNewFiber ? resultingFirstChild = oldFiber : previousNewFiber.sibling = oldFiber, previousNewFiber = oldFiber);
          isHydrating && pushTreeFork(returnFiber, newIdx);
          return resultingFirstChild;
        }
        for (oldFiber = mapRemainingChildren(oldFiber); newIdx < newChildren.length; newIdx++)
          nextOldFiber = updateFromMap(
            oldFiber,
            returnFiber,
            newIdx,
            newChildren[newIdx],
            lanes
          ), null !== nextOldFiber && (knownKeys = warnOnInvalidKey(
            returnFiber,
            nextOldFiber,
            newChildren[newIdx],
            knownKeys
          ), shouldTrackSideEffects && null !== nextOldFiber.alternate && oldFiber.delete(
            null === nextOldFiber.key ? newIdx : nextOldFiber.key
          ), currentFirstChild = placeChild(
            nextOldFiber,
            currentFirstChild,
            newIdx
          ), null === previousNewFiber ? resultingFirstChild = nextOldFiber : previousNewFiber.sibling = nextOldFiber, previousNewFiber = nextOldFiber);
        shouldTrackSideEffects && oldFiber.forEach(function(child) {
          return deleteChild(returnFiber, child);
        });
        isHydrating && pushTreeFork(returnFiber, newIdx);
        return resultingFirstChild;
      }
      function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildren, lanes) {
        if (null == newChildren)
          throw Error("An iterable object provided no iterator.");
        for (var resultingFirstChild = null, previousNewFiber = null, oldFiber = currentFirstChild, newIdx = currentFirstChild = 0, nextOldFiber = null, knownKeys = null, step = newChildren.next(); null !== oldFiber && !step.done; newIdx++, step = newChildren.next()) {
          oldFiber.index > newIdx ? (nextOldFiber = oldFiber, oldFiber = null) : nextOldFiber = oldFiber.sibling;
          var newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes);
          if (null === newFiber) {
            null === oldFiber && (oldFiber = nextOldFiber);
            break;
          }
          knownKeys = warnOnInvalidKey(
            returnFiber,
            newFiber,
            step.value,
            knownKeys
          );
          shouldTrackSideEffects && oldFiber && null === newFiber.alternate && deleteChild(returnFiber, oldFiber);
          currentFirstChild = placeChild(newFiber, currentFirstChild, newIdx);
          null === previousNewFiber ? resultingFirstChild = newFiber : previousNewFiber.sibling = newFiber;
          previousNewFiber = newFiber;
          oldFiber = nextOldFiber;
        }
        if (step.done)
          return deleteRemainingChildren(returnFiber, oldFiber), isHydrating && pushTreeFork(returnFiber, newIdx), resultingFirstChild;
        if (null === oldFiber) {
          for (; !step.done; newIdx++, step = newChildren.next())
            oldFiber = createChild(returnFiber, step.value, lanes), null !== oldFiber && (knownKeys = warnOnInvalidKey(
              returnFiber,
              oldFiber,
              step.value,
              knownKeys
            ), currentFirstChild = placeChild(
              oldFiber,
              currentFirstChild,
              newIdx
            ), null === previousNewFiber ? resultingFirstChild = oldFiber : previousNewFiber.sibling = oldFiber, previousNewFiber = oldFiber);
          isHydrating && pushTreeFork(returnFiber, newIdx);
          return resultingFirstChild;
        }
        for (oldFiber = mapRemainingChildren(oldFiber); !step.done; newIdx++, step = newChildren.next())
          nextOldFiber = updateFromMap(
            oldFiber,
            returnFiber,
            newIdx,
            step.value,
            lanes
          ), null !== nextOldFiber && (knownKeys = warnOnInvalidKey(
            returnFiber,
            nextOldFiber,
            step.value,
            knownKeys
          ), shouldTrackSideEffects && null !== nextOldFiber.alternate && oldFiber.delete(
            null === nextOldFiber.key ? newIdx : nextOldFiber.key
          ), currentFirstChild = placeChild(
            nextOldFiber,
            currentFirstChild,
            newIdx
          ), null === previousNewFiber ? resultingFirstChild = nextOldFiber : previousNewFiber.sibling = nextOldFiber, previousNewFiber = nextOldFiber);
        shouldTrackSideEffects && oldFiber.forEach(function(child) {
          return deleteChild(returnFiber, child);
        });
        isHydrating && pushTreeFork(returnFiber, newIdx);
        return resultingFirstChild;
      }
      function reconcileChildFibersImpl(returnFiber, currentFirstChild, newChild, lanes) {
        "object" === typeof newChild && null !== newChild && newChild.type === REACT_FRAGMENT_TYPE && null === newChild.key && (validateFragmentProps(newChild, null, returnFiber), newChild = newChild.props.children);
        if ("object" === typeof newChild && null !== newChild) {
          switch (newChild.$$typeof) {
            case REACT_ELEMENT_TYPE:
              var prevDebugInfo = pushDebugInfo(newChild._debugInfo);
              a: {
                for (var key2 = newChild.key; null !== currentFirstChild; ) {
                  if (currentFirstChild.key === key2) {
                    key2 = newChild.type;
                    if (key2 === REACT_FRAGMENT_TYPE) {
                      if (7 === currentFirstChild.tag) {
                        deleteRemainingChildren(
                          returnFiber,
                          currentFirstChild.sibling
                        );
                        lanes = useFiber(
                          currentFirstChild,
                          newChild.props.children
                        );
                        lanes.return = returnFiber;
                        lanes._debugOwner = newChild._owner;
                        lanes._debugInfo = currentDebugInfo;
                        validateFragmentProps(newChild, lanes, returnFiber);
                        returnFiber = lanes;
                        break a;
                      }
                    } else if (currentFirstChild.elementType === key2 || isCompatibleFamilyForHotReloading(
                      currentFirstChild,
                      newChild
                    ) || "object" === typeof key2 && null !== key2 && key2.$$typeof === REACT_LAZY_TYPE && resolveLazy(key2) === currentFirstChild.type) {
                      deleteRemainingChildren(
                        returnFiber,
                        currentFirstChild.sibling
                      );
                      lanes = useFiber(currentFirstChild, newChild.props);
                      coerceRef(lanes, newChild);
                      lanes.return = returnFiber;
                      lanes._debugOwner = newChild._owner;
                      lanes._debugInfo = currentDebugInfo;
                      returnFiber = lanes;
                      break a;
                    }
                    deleteRemainingChildren(returnFiber, currentFirstChild);
                    break;
                  } else deleteChild(returnFiber, currentFirstChild);
                  currentFirstChild = currentFirstChild.sibling;
                }
                newChild.type === REACT_FRAGMENT_TYPE ? (lanes = createFiberFromFragment(
                  newChild.props.children,
                  returnFiber.mode,
                  lanes,
                  newChild.key
                ), lanes.return = returnFiber, lanes._debugOwner = returnFiber, lanes._debugTask = returnFiber._debugTask, lanes._debugInfo = currentDebugInfo, validateFragmentProps(newChild, lanes, returnFiber), returnFiber = lanes) : (lanes = createFiberFromElement(
                  newChild,
                  returnFiber.mode,
                  lanes
                ), coerceRef(lanes, newChild), lanes.return = returnFiber, lanes._debugInfo = currentDebugInfo, returnFiber = lanes);
              }
              returnFiber = placeSingleChild(returnFiber);
              currentDebugInfo = prevDebugInfo;
              return returnFiber;
            case REACT_PORTAL_TYPE:
              a: {
                prevDebugInfo = newChild;
                for (newChild = prevDebugInfo.key; null !== currentFirstChild; ) {
                  if (currentFirstChild.key === newChild)
                    if (4 === currentFirstChild.tag && currentFirstChild.stateNode.containerInfo === prevDebugInfo.containerInfo && currentFirstChild.stateNode.implementation === prevDebugInfo.implementation) {
                      deleteRemainingChildren(
                        returnFiber,
                        currentFirstChild.sibling
                      );
                      lanes = useFiber(
                        currentFirstChild,
                        prevDebugInfo.children || []
                      );
                      lanes.return = returnFiber;
                      returnFiber = lanes;
                      break a;
                    } else {
                      deleteRemainingChildren(returnFiber, currentFirstChild);
                      break;
                    }
                  else deleteChild(returnFiber, currentFirstChild);
                  currentFirstChild = currentFirstChild.sibling;
                }
                lanes = createFiberFromPortal(
                  prevDebugInfo,
                  returnFiber.mode,
                  lanes
                );
                lanes.return = returnFiber;
                returnFiber = lanes;
              }
              return placeSingleChild(returnFiber);
            case REACT_LAZY_TYPE:
              return prevDebugInfo = pushDebugInfo(newChild._debugInfo), newChild = resolveLazy(newChild), returnFiber = reconcileChildFibersImpl(
                returnFiber,
                currentFirstChild,
                newChild,
                lanes
              ), currentDebugInfo = prevDebugInfo, returnFiber;
          }
          if (isArrayImpl(newChild))
            return prevDebugInfo = pushDebugInfo(newChild._debugInfo), returnFiber = reconcileChildrenArray(
              returnFiber,
              currentFirstChild,
              newChild,
              lanes
            ), currentDebugInfo = prevDebugInfo, returnFiber;
          if (getIteratorFn(newChild)) {
            prevDebugInfo = pushDebugInfo(newChild._debugInfo);
            key2 = getIteratorFn(newChild);
            if ("function" !== typeof key2)
              throw Error(
                "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue."
              );
            var newChildren = key2.call(newChild);
            if (newChildren === newChild) {
              if (0 !== returnFiber.tag || "[object GeneratorFunction]" !== Object.prototype.toString.call(returnFiber.type) || "[object Generator]" !== Object.prototype.toString.call(newChildren))
                didWarnAboutGenerators || console.error(
                  "Using Iterators as children is unsupported and will likely yield unexpected results because enumerating a generator mutates it. You may convert it to an array with `Array.from()` or the `[...spread]` operator before rendering. You can also use an Iterable that can iterate multiple times over the same items."
                ), didWarnAboutGenerators = true;
            } else
              newChild.entries !== key2 || didWarnAboutMaps || (console.error(
                "Using Maps as children is not supported. Use an array of keyed ReactElements instead."
              ), didWarnAboutMaps = true);
            returnFiber = reconcileChildrenIterator(
              returnFiber,
              currentFirstChild,
              newChildren,
              lanes
            );
            currentDebugInfo = prevDebugInfo;
            return returnFiber;
          }
          if ("function" === typeof newChild.then)
            return prevDebugInfo = pushDebugInfo(newChild._debugInfo), returnFiber = reconcileChildFibersImpl(
              returnFiber,
              currentFirstChild,
              unwrapThenable(newChild),
              lanes
            ), currentDebugInfo = prevDebugInfo, returnFiber;
          if (newChild.$$typeof === REACT_CONTEXT_TYPE)
            return reconcileChildFibersImpl(
              returnFiber,
              currentFirstChild,
              readContextDuringReconciliation(returnFiber, newChild),
              lanes
            );
          throwOnInvalidObjectType(returnFiber, newChild);
        }
        if ("string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild)
          return prevDebugInfo = "" + newChild, null !== currentFirstChild && 6 === currentFirstChild.tag ? (deleteRemainingChildren(
            returnFiber,
            currentFirstChild.sibling
          ), lanes = useFiber(currentFirstChild, prevDebugInfo), lanes.return = returnFiber, returnFiber = lanes) : (deleteRemainingChildren(returnFiber, currentFirstChild), lanes = createFiberFromText(
            prevDebugInfo,
            returnFiber.mode,
            lanes
          ), lanes.return = returnFiber, lanes._debugOwner = returnFiber, lanes._debugTask = returnFiber._debugTask, lanes._debugInfo = currentDebugInfo, returnFiber = lanes), placeSingleChild(returnFiber);
        "function" === typeof newChild && warnOnFunctionType(returnFiber, newChild);
        "symbol" === typeof newChild && warnOnSymbolType(returnFiber, newChild);
        return deleteRemainingChildren(returnFiber, currentFirstChild);
      }
      return function(returnFiber, currentFirstChild, newChild, lanes) {
        var prevDebugInfo = currentDebugInfo;
        currentDebugInfo = null;
        try {
          thenableIndexCounter$1 = 0;
          var firstChildFiber = reconcileChildFibersImpl(
            returnFiber,
            currentFirstChild,
            newChild,
            lanes
          );
          thenableState$1 = null;
          return firstChildFiber;
        } catch (x) {
          if (x === SuspenseException || x === SuspenseActionException) throw x;
          var fiber = createFiber(29, x, null, returnFiber.mode);
          fiber.lanes = lanes;
          fiber.return = returnFiber;
          var debugInfo = fiber._debugInfo = currentDebugInfo;
          fiber._debugOwner = returnFiber._debugOwner;
          fiber._debugTask = returnFiber._debugTask;
          if (null != debugInfo) {
            for (var i2 = debugInfo.length - 1; 0 <= i2; i2--)
              if ("string" === typeof debugInfo[i2].stack) {
                fiber._debugOwner = debugInfo[i2];
                fiber._debugTask = debugInfo[i2].debugTask;
                break;
              }
          }
          return fiber;
        } finally {
          currentDebugInfo = prevDebugInfo;
        }
      };
    }
    function validateSuspenseListNestedChild(childSlot, index) {
      var isAnArray = isArrayImpl(childSlot);
      childSlot = !isAnArray && "function" === typeof getIteratorFn(childSlot);
      return isAnArray || childSlot ? (isAnArray = isAnArray ? "array" : "iterable", console.error(
        "A nested %s was passed to row #%s in <SuspenseList />. Wrap it in an additional SuspenseList to configure its revealOrder: <SuspenseList revealOrder=...> ... <SuspenseList revealOrder=...>{%s}</SuspenseList> ... </SuspenseList>",
        isAnArray,
        index,
        isAnArray
      ), false) : true;
    }
    function initializeUpdateQueue(fiber) {
      fiber.updateQueue = {
        baseState: fiber.memoizedState,
        firstBaseUpdate: null,
        lastBaseUpdate: null,
        shared: { pending: null, lanes: 0, hiddenCallbacks: null },
        callbacks: null
      };
    }
    function cloneUpdateQueue(current22, workInProgress2) {
      current22 = current22.updateQueue;
      workInProgress2.updateQueue === current22 && (workInProgress2.updateQueue = {
        baseState: current22.baseState,
        firstBaseUpdate: current22.firstBaseUpdate,
        lastBaseUpdate: current22.lastBaseUpdate,
        shared: current22.shared,
        callbacks: null
      });
    }
    function createUpdate(lane) {
      return {
        lane,
        tag: UpdateState,
        payload: null,
        callback: null,
        next: null
      };
    }
    function enqueueUpdate(fiber, update2, lane) {
      var updateQueue = fiber.updateQueue;
      if (null === updateQueue) return null;
      updateQueue = updateQueue.shared;
      if (currentlyProcessingQueue === updateQueue && !didWarnUpdateInsideUpdate) {
        var componentName2 = getComponentNameFromFiber(fiber);
        console.error(
          "An update (setState, replaceState, or forceUpdate) was scheduled from inside an update function. Update functions should be pure, with zero side-effects. Consider using componentDidUpdate or a callback.\n\nPlease update the following component: %s",
          componentName2
        );
        didWarnUpdateInsideUpdate = true;
      }
      if ((executionContext & RenderContext) !== NoContext)
        return componentName2 = updateQueue.pending, null === componentName2 ? update2.next = update2 : (update2.next = componentName2.next, componentName2.next = update2), updateQueue.pending = update2, update2 = getRootForUpdatedFiber(fiber), markUpdateLaneFromFiberToRoot(fiber, null, lane), update2;
      enqueueUpdate$1(fiber, updateQueue, update2, lane);
      return getRootForUpdatedFiber(fiber);
    }
    function entangleTransitions(root22, fiber, lane) {
      fiber = fiber.updateQueue;
      if (null !== fiber && (fiber = fiber.shared, 0 !== (lane & 4194048))) {
        var queueLanes = fiber.lanes;
        queueLanes &= root22.pendingLanes;
        lane |= queueLanes;
        fiber.lanes = lane;
        markRootEntangled(root22, lane);
      }
    }
    function enqueueCapturedUpdate(workInProgress2, capturedUpdate) {
      var queue = workInProgress2.updateQueue, current22 = workInProgress2.alternate;
      if (null !== current22 && (current22 = current22.updateQueue, queue === current22)) {
        var newFirst = null, newLast = null;
        queue = queue.firstBaseUpdate;
        if (null !== queue) {
          do {
            var clone2 = {
              lane: queue.lane,
              tag: queue.tag,
              payload: queue.payload,
              callback: null,
              next: null
            };
            null === newLast ? newFirst = newLast = clone2 : newLast = newLast.next = clone2;
            queue = queue.next;
          } while (null !== queue);
          null === newLast ? newFirst = newLast = capturedUpdate : newLast = newLast.next = capturedUpdate;
        } else newFirst = newLast = capturedUpdate;
        queue = {
          baseState: current22.baseState,
          firstBaseUpdate: newFirst,
          lastBaseUpdate: newLast,
          shared: current22.shared,
          callbacks: current22.callbacks
        };
        workInProgress2.updateQueue = queue;
        return;
      }
      workInProgress2 = queue.lastBaseUpdate;
      null === workInProgress2 ? queue.firstBaseUpdate = capturedUpdate : workInProgress2.next = capturedUpdate;
      queue.lastBaseUpdate = capturedUpdate;
    }
    function suspendIfUpdateReadFromEntangledAsyncAction() {
      if (didReadFromEntangledAsyncAction) {
        var entangledActionThenable = currentEntangledActionThenable;
        if (null !== entangledActionThenable) throw entangledActionThenable;
      }
    }
    function processUpdateQueue(workInProgress2, props, instance$jscomp$0, renderLanes2) {
      didReadFromEntangledAsyncAction = false;
      var queue = workInProgress2.updateQueue;
      hasForceUpdate = false;
      currentlyProcessingQueue = queue.shared;
      var firstBaseUpdate = queue.firstBaseUpdate, lastBaseUpdate = queue.lastBaseUpdate, pendingQueue = queue.shared.pending;
      if (null !== pendingQueue) {
        queue.shared.pending = null;
        var lastPendingUpdate = pendingQueue, firstPendingUpdate = lastPendingUpdate.next;
        lastPendingUpdate.next = null;
        null === lastBaseUpdate ? firstBaseUpdate = firstPendingUpdate : lastBaseUpdate.next = firstPendingUpdate;
        lastBaseUpdate = lastPendingUpdate;
        var current22 = workInProgress2.alternate;
        null !== current22 && (current22 = current22.updateQueue, pendingQueue = current22.lastBaseUpdate, pendingQueue !== lastBaseUpdate && (null === pendingQueue ? current22.firstBaseUpdate = firstPendingUpdate : pendingQueue.next = firstPendingUpdate, current22.lastBaseUpdate = lastPendingUpdate));
      }
      if (null !== firstBaseUpdate) {
        var newState = queue.baseState;
        lastBaseUpdate = 0;
        current22 = firstPendingUpdate = lastPendingUpdate = null;
        pendingQueue = firstBaseUpdate;
        do {
          var updateLane = pendingQueue.lane & -536870913, isHiddenUpdate = updateLane !== pendingQueue.lane;
          if (isHiddenUpdate ? (workInProgressRootRenderLanes & updateLane) === updateLane : (renderLanes2 & updateLane) === updateLane) {
            0 !== updateLane && updateLane === currentEntangledLane && (didReadFromEntangledAsyncAction = true);
            null !== current22 && (current22 = current22.next = {
              lane: 0,
              tag: pendingQueue.tag,
              payload: pendingQueue.payload,
              callback: null,
              next: null
            });
            a: {
              updateLane = workInProgress2;
              var partialState = pendingQueue;
              var nextProps = props, instance2 = instance$jscomp$0;
              switch (partialState.tag) {
                case ReplaceState:
                  partialState = partialState.payload;
                  if ("function" === typeof partialState) {
                    isDisallowedContextReadInDEV = true;
                    var nextState = partialState.call(
                      instance2,
                      newState,
                      nextProps
                    );
                    if (updateLane.mode & StrictLegacyMode) {
                      setIsStrictModeForDevtools(true);
                      try {
                        partialState.call(instance2, newState, nextProps);
                      } finally {
                        setIsStrictModeForDevtools(false);
                      }
                    }
                    isDisallowedContextReadInDEV = false;
                    newState = nextState;
                    break a;
                  }
                  newState = partialState;
                  break a;
                case CaptureUpdate:
                  updateLane.flags = updateLane.flags & -65537 | 128;
                case UpdateState:
                  nextState = partialState.payload;
                  if ("function" === typeof nextState) {
                    isDisallowedContextReadInDEV = true;
                    partialState = nextState.call(
                      instance2,
                      newState,
                      nextProps
                    );
                    if (updateLane.mode & StrictLegacyMode) {
                      setIsStrictModeForDevtools(true);
                      try {
                        nextState.call(instance2, newState, nextProps);
                      } finally {
                        setIsStrictModeForDevtools(false);
                      }
                    }
                    isDisallowedContextReadInDEV = false;
                  } else partialState = nextState;
                  if (null === partialState || void 0 === partialState) break a;
                  newState = assign2({}, newState, partialState);
                  break a;
                case ForceUpdate:
                  hasForceUpdate = true;
              }
            }
            updateLane = pendingQueue.callback;
            null !== updateLane && (workInProgress2.flags |= 64, isHiddenUpdate && (workInProgress2.flags |= 8192), isHiddenUpdate = queue.callbacks, null === isHiddenUpdate ? queue.callbacks = [updateLane] : isHiddenUpdate.push(updateLane));
          } else
            isHiddenUpdate = {
              lane: updateLane,
              tag: pendingQueue.tag,
              payload: pendingQueue.payload,
              callback: pendingQueue.callback,
              next: null
            }, null === current22 ? (firstPendingUpdate = current22 = isHiddenUpdate, lastPendingUpdate = newState) : current22 = current22.next = isHiddenUpdate, lastBaseUpdate |= updateLane;
          pendingQueue = pendingQueue.next;
          if (null === pendingQueue)
            if (pendingQueue = queue.shared.pending, null === pendingQueue)
              break;
            else
              isHiddenUpdate = pendingQueue, pendingQueue = isHiddenUpdate.next, isHiddenUpdate.next = null, queue.lastBaseUpdate = isHiddenUpdate, queue.shared.pending = null;
        } while (1);
        null === current22 && (lastPendingUpdate = newState);
        queue.baseState = lastPendingUpdate;
        queue.firstBaseUpdate = firstPendingUpdate;
        queue.lastBaseUpdate = current22;
        null === firstBaseUpdate && (queue.shared.lanes = 0);
        workInProgressRootSkippedLanes |= lastBaseUpdate;
        workInProgress2.lanes = lastBaseUpdate;
        workInProgress2.memoizedState = newState;
      }
      currentlyProcessingQueue = null;
    }
    function callCallback(callback, context) {
      if ("function" !== typeof callback)
        throw Error(
          "Invalid argument passed as callback. Expected a function. Instead received: " + callback
        );
      callback.call(context);
    }
    function commitHiddenCallbacks(updateQueue, context) {
      var hiddenCallbacks = updateQueue.shared.hiddenCallbacks;
      if (null !== hiddenCallbacks)
        for (updateQueue.shared.hiddenCallbacks = null, updateQueue = 0; updateQueue < hiddenCallbacks.length; updateQueue++)
          callCallback(hiddenCallbacks[updateQueue], context);
    }
    function commitCallbacks(updateQueue, context) {
      var callbacks = updateQueue.callbacks;
      if (null !== callbacks)
        for (updateQueue.callbacks = null, updateQueue = 0; updateQueue < callbacks.length; updateQueue++)
          callCallback(callbacks[updateQueue], context);
    }
    function pushHiddenContext(fiber, context) {
      var prevEntangledRenderLanes = entangledRenderLanes;
      push2(prevEntangledRenderLanesCursor, prevEntangledRenderLanes, fiber);
      push2(currentTreeHiddenStackCursor, context, fiber);
      entangledRenderLanes = prevEntangledRenderLanes | context.baseLanes;
    }
    function reuseHiddenContextOnStack(fiber) {
      push2(prevEntangledRenderLanesCursor, entangledRenderLanes, fiber);
      push2(
        currentTreeHiddenStackCursor,
        currentTreeHiddenStackCursor.current,
        fiber
      );
    }
    function popHiddenContext(fiber) {
      entangledRenderLanes = prevEntangledRenderLanesCursor.current;
      pop2(currentTreeHiddenStackCursor, fiber);
      pop2(prevEntangledRenderLanesCursor, fiber);
    }
    function pushPrimaryTreeSuspenseHandler(handler) {
      var current22 = handler.alternate;
      push2(
        suspenseStackCursor,
        suspenseStackCursor.current & SubtreeSuspenseContextMask,
        handler
      );
      push2(suspenseHandlerStackCursor, handler, handler);
      null === shellBoundary && (null === current22 || null !== currentTreeHiddenStackCursor.current ? shellBoundary = handler : null !== current22.memoizedState && (shellBoundary = handler));
    }
    function pushDehydratedActivitySuspenseHandler(fiber) {
      push2(suspenseStackCursor, suspenseStackCursor.current, fiber);
      push2(suspenseHandlerStackCursor, fiber, fiber);
      null === shellBoundary && (shellBoundary = fiber);
    }
    function pushOffscreenSuspenseHandler(fiber) {
      22 === fiber.tag ? (push2(suspenseStackCursor, suspenseStackCursor.current, fiber), push2(suspenseHandlerStackCursor, fiber, fiber), null === shellBoundary && (shellBoundary = fiber)) : reuseSuspenseHandlerOnStack(fiber);
    }
    function reuseSuspenseHandlerOnStack(fiber) {
      push2(suspenseStackCursor, suspenseStackCursor.current, fiber);
      push2(
        suspenseHandlerStackCursor,
        suspenseHandlerStackCursor.current,
        fiber
      );
    }
    function popSuspenseHandler(fiber) {
      pop2(suspenseHandlerStackCursor, fiber);
      shellBoundary === fiber && (shellBoundary = null);
      pop2(suspenseStackCursor, fiber);
    }
    function findFirstSuspended(row2) {
      for (var node2 = row2; null !== node2; ) {
        if (13 === node2.tag) {
          var state = node2.memoizedState;
          if (null !== state && (state = state.dehydrated, null === state || isSuspenseInstancePending(state) || isSuspenseInstanceFallback(state)))
            return node2;
        } else if (19 === node2.tag && ("forwards" === node2.memoizedProps.revealOrder || "backwards" === node2.memoizedProps.revealOrder || "unstable_legacy-backwards" === node2.memoizedProps.revealOrder || "together" === node2.memoizedProps.revealOrder)) {
          if (0 !== (node2.flags & 128)) return node2;
        } else if (null !== node2.child) {
          node2.child.return = node2;
          node2 = node2.child;
          continue;
        }
        if (node2 === row2) break;
        for (; null === node2.sibling; ) {
          if (null === node2.return || node2.return === row2) return null;
          node2 = node2.return;
        }
        node2.sibling.return = node2.return;
        node2 = node2.sibling;
      }
      return null;
    }
    function mountHookTypesDev() {
      var hookName = currentHookNameInDev;
      null === hookTypesDev ? hookTypesDev = [hookName] : hookTypesDev.push(hookName);
    }
    function updateHookTypesDev() {
      var hookName = currentHookNameInDev;
      if (null !== hookTypesDev && (hookTypesUpdateIndexDev++, hookTypesDev[hookTypesUpdateIndexDev] !== hookName)) {
        var componentName2 = getComponentNameFromFiber(currentlyRenderingFiber);
        if (!didWarnAboutMismatchedHooksForComponent.has(componentName2) && (didWarnAboutMismatchedHooksForComponent.add(componentName2), null !== hookTypesDev)) {
          for (var table2 = "", i2 = 0; i2 <= hookTypesUpdateIndexDev; i2++) {
            var oldHookName = hookTypesDev[i2], newHookName = i2 === hookTypesUpdateIndexDev ? hookName : oldHookName;
            for (oldHookName = i2 + 1 + ". " + oldHookName; 30 > oldHookName.length; )
              oldHookName += " ";
            oldHookName += newHookName + "\n";
            table2 += oldHookName;
          }
          console.error(
            "React has detected a change in the order of Hooks called by %s. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://react.dev/link/rules-of-hooks\n\n   Previous render            Next render\n   ------------------------------------------------------\n%s   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
            componentName2,
            table2
          );
        }
      }
    }
    function checkDepsAreArrayDev(deps) {
      void 0 === deps || null === deps || isArrayImpl(deps) || console.error(
        "%s received a final argument that is not an array (instead, received `%s`). When specified, the final argument must be an array.",
        currentHookNameInDev,
        typeof deps
      );
    }
    function warnOnUseFormStateInDev() {
      var componentName2 = getComponentNameFromFiber(currentlyRenderingFiber);
      didWarnAboutUseFormState.has(componentName2) || (didWarnAboutUseFormState.add(componentName2), console.error(
        "ReactDOM.useFormState has been renamed to React.useActionState. Please update %s to use React.useActionState.",
        componentName2
      ));
    }
    function throwInvalidHookError() {
      throw Error(
        "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem."
      );
    }
    function areHookInputsEqual(nextDeps, prevDeps) {
      if (ignorePreviousDependencies) return false;
      if (null === prevDeps)
        return console.error(
          "%s received a final argument during this render, but not during the previous render. Even though the final argument is optional, its type cannot change between renders.",
          currentHookNameInDev
        ), false;
      nextDeps.length !== prevDeps.length && console.error(
        "The final argument passed to %s changed size between renders. The order and size of this array must remain constant.\n\nPrevious: %s\nIncoming: %s",
        currentHookNameInDev,
        "[" + prevDeps.join(", ") + "]",
        "[" + nextDeps.join(", ") + "]"
      );
      for (var i2 = 0; i2 < prevDeps.length && i2 < nextDeps.length; i2++)
        if (!objectIs(nextDeps[i2], prevDeps[i2])) return false;
      return true;
    }
    function renderWithHooks(current22, workInProgress2, Component2, props, secondArg, nextRenderLanes) {
      renderLanes = nextRenderLanes;
      currentlyRenderingFiber = workInProgress2;
      hookTypesDev = null !== current22 ? current22._debugHookTypes : null;
      hookTypesUpdateIndexDev = -1;
      ignorePreviousDependencies = null !== current22 && current22.type !== workInProgress2.type;
      if ("[object AsyncFunction]" === Object.prototype.toString.call(Component2) || "[object AsyncGeneratorFunction]" === Object.prototype.toString.call(Component2))
        nextRenderLanes = getComponentNameFromFiber(currentlyRenderingFiber), didWarnAboutAsyncClientComponent.has(nextRenderLanes) || (didWarnAboutAsyncClientComponent.add(nextRenderLanes), console.error(
          "%s is an async Client Component. Only Server Components can be async at the moment. This error is often caused by accidentally adding `'use client'` to a module that was originally written for the server.",
          null === nextRenderLanes ? "An unknown Component" : "<" + nextRenderLanes + ">"
        ));
      workInProgress2.memoizedState = null;
      workInProgress2.updateQueue = null;
      workInProgress2.lanes = 0;
      ReactSharedInternals.H = null !== current22 && null !== current22.memoizedState ? HooksDispatcherOnUpdateInDEV : null !== hookTypesDev ? HooksDispatcherOnMountWithHookTypesInDEV : HooksDispatcherOnMountInDEV;
      shouldDoubleInvokeUserFnsInHooksDEV = nextRenderLanes = (workInProgress2.mode & StrictLegacyMode) !== NoMode;
      var children2 = callComponentInDEV(Component2, props, secondArg);
      shouldDoubleInvokeUserFnsInHooksDEV = false;
      didScheduleRenderPhaseUpdateDuringThisPass && (children2 = renderWithHooksAgain(
        workInProgress2,
        Component2,
        props,
        secondArg
      ));
      if (nextRenderLanes) {
        setIsStrictModeForDevtools(true);
        try {
          children2 = renderWithHooksAgain(
            workInProgress2,
            Component2,
            props,
            secondArg
          );
        } finally {
          setIsStrictModeForDevtools(false);
        }
      }
      finishRenderingHooks(current22, workInProgress2);
      return children2;
    }
    function finishRenderingHooks(current22, workInProgress2) {
      workInProgress2._debugHookTypes = hookTypesDev;
      null === workInProgress2.dependencies ? null !== thenableState && (workInProgress2.dependencies = {
        lanes: 0,
        firstContext: null,
        _debugThenableState: thenableState
      }) : workInProgress2.dependencies._debugThenableState = thenableState;
      ReactSharedInternals.H = ContextOnlyDispatcher;
      var didRenderTooFewHooks = null !== currentHook && null !== currentHook.next;
      renderLanes = 0;
      hookTypesDev = currentHookNameInDev = workInProgressHook = currentHook = currentlyRenderingFiber = null;
      hookTypesUpdateIndexDev = -1;
      null !== current22 && (current22.flags & 65011712) !== (workInProgress2.flags & 65011712) && console.error(
        "Internal React error: Expected static flag was missing. Please notify the React team."
      );
      didScheduleRenderPhaseUpdate = false;
      thenableIndexCounter = 0;
      thenableState = null;
      if (didRenderTooFewHooks)
        throw Error(
          "Rendered fewer hooks than expected. This may be caused by an accidental early return statement."
        );
      null === current22 || didReceiveUpdate || (current22 = current22.dependencies, null !== current22 && checkIfContextChanged(current22) && (didReceiveUpdate = true));
      needsToResetSuspendedThenableDEV ? (needsToResetSuspendedThenableDEV = false, current22 = true) : current22 = false;
      current22 && (workInProgress2 = getComponentNameFromFiber(workInProgress2) || "Unknown", didWarnAboutUseWrappedInTryCatch.has(workInProgress2) || didWarnAboutAsyncClientComponent.has(workInProgress2) || (didWarnAboutUseWrappedInTryCatch.add(workInProgress2), console.error(
        "`use` was called from inside a try/catch block. This is not allowed and can lead to unexpected behavior. To handle errors triggered by `use`, wrap your component in a error boundary."
      )));
    }
    function renderWithHooksAgain(workInProgress2, Component2, props, secondArg) {
      currentlyRenderingFiber = workInProgress2;
      var numberOfReRenders = 0;
      do {
        didScheduleRenderPhaseUpdateDuringThisPass && (thenableState = null);
        thenableIndexCounter = 0;
        didScheduleRenderPhaseUpdateDuringThisPass = false;
        if (numberOfReRenders >= RE_RENDER_LIMIT)
          throw Error(
            "Too many re-renders. React limits the number of renders to prevent an infinite loop."
          );
        numberOfReRenders += 1;
        ignorePreviousDependencies = false;
        workInProgressHook = currentHook = null;
        if (null != workInProgress2.updateQueue) {
          var children2 = workInProgress2.updateQueue;
          children2.lastEffect = null;
          children2.events = null;
          children2.stores = null;
          null != children2.memoCache && (children2.memoCache.index = 0);
        }
        hookTypesUpdateIndexDev = -1;
        ReactSharedInternals.H = HooksDispatcherOnRerenderInDEV;
        children2 = callComponentInDEV(Component2, props, secondArg);
      } while (didScheduleRenderPhaseUpdateDuringThisPass);
      return children2;
    }
    function TransitionAwareHostComponent() {
      var dispatcher = ReactSharedInternals.H, maybeThenable = dispatcher.useState()[0];
      maybeThenable = "function" === typeof maybeThenable.then ? useThenable(maybeThenable) : maybeThenable;
      dispatcher = dispatcher.useState()[0];
      (null !== currentHook ? currentHook.memoizedState : null) !== dispatcher && (currentlyRenderingFiber.flags |= 1024);
      return maybeThenable;
    }
    function checkDidRenderIdHook() {
      var didRenderIdHook = 0 !== localIdCounter;
      localIdCounter = 0;
      return didRenderIdHook;
    }
    function bailoutHooks(current22, workInProgress2, lanes) {
      workInProgress2.updateQueue = current22.updateQueue;
      workInProgress2.flags = (workInProgress2.mode & StrictEffectsMode) !== NoMode ? workInProgress2.flags & -402655237 : workInProgress2.flags & -2053;
      current22.lanes &= ~lanes;
    }
    function resetHooksOnUnwind(workInProgress2) {
      if (didScheduleRenderPhaseUpdate) {
        for (workInProgress2 = workInProgress2.memoizedState; null !== workInProgress2; ) {
          var queue = workInProgress2.queue;
          null !== queue && (queue.pending = null);
          workInProgress2 = workInProgress2.next;
        }
        didScheduleRenderPhaseUpdate = false;
      }
      renderLanes = 0;
      hookTypesDev = workInProgressHook = currentHook = currentlyRenderingFiber = null;
      hookTypesUpdateIndexDev = -1;
      currentHookNameInDev = null;
      didScheduleRenderPhaseUpdateDuringThisPass = false;
      thenableIndexCounter = localIdCounter = 0;
      thenableState = null;
    }
    function mountWorkInProgressHook() {
      var hook = {
        memoizedState: null,
        baseState: null,
        baseQueue: null,
        queue: null,
        next: null
      };
      null === workInProgressHook ? currentlyRenderingFiber.memoizedState = workInProgressHook = hook : workInProgressHook = workInProgressHook.next = hook;
      return workInProgressHook;
    }
    function updateWorkInProgressHook() {
      if (null === currentHook) {
        var nextCurrentHook = currentlyRenderingFiber.alternate;
        nextCurrentHook = null !== nextCurrentHook ? nextCurrentHook.memoizedState : null;
      } else nextCurrentHook = currentHook.next;
      var nextWorkInProgressHook = null === workInProgressHook ? currentlyRenderingFiber.memoizedState : workInProgressHook.next;
      if (null !== nextWorkInProgressHook)
        workInProgressHook = nextWorkInProgressHook, currentHook = nextCurrentHook;
      else {
        if (null === nextCurrentHook) {
          if (null === currentlyRenderingFiber.alternate)
            throw Error(
              "Update hook called on initial render. This is likely a bug in React. Please file an issue."
            );
          throw Error("Rendered more hooks than during the previous render.");
        }
        currentHook = nextCurrentHook;
        nextCurrentHook = {
          memoizedState: currentHook.memoizedState,
          baseState: currentHook.baseState,
          baseQueue: currentHook.baseQueue,
          queue: currentHook.queue,
          next: null
        };
        null === workInProgressHook ? currentlyRenderingFiber.memoizedState = workInProgressHook = nextCurrentHook : workInProgressHook = workInProgressHook.next = nextCurrentHook;
      }
      return workInProgressHook;
    }
    function createFunctionComponentUpdateQueue() {
      return { lastEffect: null, events: null, stores: null, memoCache: null };
    }
    function useThenable(thenable) {
      var index = thenableIndexCounter;
      thenableIndexCounter += 1;
      null === thenableState && (thenableState = createThenableState());
      thenable = trackUsedThenable(thenableState, thenable, index);
      index = currentlyRenderingFiber;
      null === (null === workInProgressHook ? index.memoizedState : workInProgressHook.next) && (index = index.alternate, ReactSharedInternals.H = null !== index && null !== index.memoizedState ? HooksDispatcherOnUpdateInDEV : HooksDispatcherOnMountInDEV);
      return thenable;
    }
    function use2(usable) {
      if (null !== usable && "object" === typeof usable) {
        if ("function" === typeof usable.then) return useThenable(usable);
        if (usable.$$typeof === REACT_CONTEXT_TYPE) return readContext(usable);
      }
      throw Error("An unsupported type was passed to use(): " + String(usable));
    }
    function useMemoCache(size) {
      var memoCache = null, updateQueue = currentlyRenderingFiber.updateQueue;
      null !== updateQueue && (memoCache = updateQueue.memoCache);
      if (null == memoCache) {
        var current22 = currentlyRenderingFiber.alternate;
        null !== current22 && (current22 = current22.updateQueue, null !== current22 && (current22 = current22.memoCache, null != current22 && (memoCache = {
          data: current22.data.map(function(array2) {
            return array2.slice();
          }),
          index: 0
        })));
      }
      null == memoCache && (memoCache = { data: [], index: 0 });
      null === updateQueue && (updateQueue = createFunctionComponentUpdateQueue(), currentlyRenderingFiber.updateQueue = updateQueue);
      updateQueue.memoCache = memoCache;
      updateQueue = memoCache.data[memoCache.index];
      if (void 0 === updateQueue || ignorePreviousDependencies)
        for (updateQueue = memoCache.data[memoCache.index] = Array(size), current22 = 0; current22 < size; current22++)
          updateQueue[current22] = REACT_MEMO_CACHE_SENTINEL;
      else
        updateQueue.length !== size && console.error(
          "Expected a constant size argument for each invocation of useMemoCache. The previous cache was allocated with size %s but size %s was requested.",
          updateQueue.length,
          size
        );
      memoCache.index++;
      return updateQueue;
    }
    function basicStateReducer(state, action) {
      return "function" === typeof action ? action(state) : action;
    }
    function mountReducer(reducer, initialArg, init) {
      var hook = mountWorkInProgressHook();
      if (void 0 !== init) {
        var initialState = init(initialArg);
        if (shouldDoubleInvokeUserFnsInHooksDEV) {
          setIsStrictModeForDevtools(true);
          try {
            init(initialArg);
          } finally {
            setIsStrictModeForDevtools(false);
          }
        }
      } else initialState = initialArg;
      hook.memoizedState = hook.baseState = initialState;
      reducer = {
        pending: null,
        lanes: 0,
        dispatch: null,
        lastRenderedReducer: reducer,
        lastRenderedState: initialState
      };
      hook.queue = reducer;
      reducer = reducer.dispatch = dispatchReducerAction.bind(
        null,
        currentlyRenderingFiber,
        reducer
      );
      return [hook.memoizedState, reducer];
    }
    function updateReducer(reducer) {
      var hook = updateWorkInProgressHook();
      return updateReducerImpl(hook, currentHook, reducer);
    }
    function updateReducerImpl(hook, current22, reducer) {
      var queue = hook.queue;
      if (null === queue)
        throw Error(
          "Should have a queue. You are likely calling Hooks conditionally, which is not allowed. (https://react.dev/link/invalid-hook-call)"
        );
      queue.lastRenderedReducer = reducer;
      var baseQueue = hook.baseQueue, pendingQueue = queue.pending;
      if (null !== pendingQueue) {
        if (null !== baseQueue) {
          var baseFirst = baseQueue.next;
          baseQueue.next = pendingQueue.next;
          pendingQueue.next = baseFirst;
        }
        current22.baseQueue !== baseQueue && console.error(
          "Internal error: Expected work-in-progress queue to be a clone. This is a bug in React."
        );
        current22.baseQueue = baseQueue = pendingQueue;
        queue.pending = null;
      }
      pendingQueue = hook.baseState;
      if (null === baseQueue) hook.memoizedState = pendingQueue;
      else {
        current22 = baseQueue.next;
        var newBaseQueueFirst = baseFirst = null, newBaseQueueLast = null, update2 = current22, didReadFromEntangledAsyncAction2 = false;
        do {
          var updateLane = update2.lane & -536870913;
          if (updateLane !== update2.lane ? (workInProgressRootRenderLanes & updateLane) === updateLane : (renderLanes & updateLane) === updateLane) {
            var revertLane = update2.revertLane;
            if (0 === revertLane)
              null !== newBaseQueueLast && (newBaseQueueLast = newBaseQueueLast.next = {
                lane: 0,
                revertLane: 0,
                gesture: null,
                action: update2.action,
                hasEagerState: update2.hasEagerState,
                eagerState: update2.eagerState,
                next: null
              }), updateLane === currentEntangledLane && (didReadFromEntangledAsyncAction2 = true);
            else if ((renderLanes & revertLane) === revertLane) {
              update2 = update2.next;
              revertLane === currentEntangledLane && (didReadFromEntangledAsyncAction2 = true);
              continue;
            } else
              updateLane = {
                lane: 0,
                revertLane: update2.revertLane,
                gesture: null,
                action: update2.action,
                hasEagerState: update2.hasEagerState,
                eagerState: update2.eagerState,
                next: null
              }, null === newBaseQueueLast ? (newBaseQueueFirst = newBaseQueueLast = updateLane, baseFirst = pendingQueue) : newBaseQueueLast = newBaseQueueLast.next = updateLane, currentlyRenderingFiber.lanes |= revertLane, workInProgressRootSkippedLanes |= revertLane;
            updateLane = update2.action;
            shouldDoubleInvokeUserFnsInHooksDEV && reducer(pendingQueue, updateLane);
            pendingQueue = update2.hasEagerState ? update2.eagerState : reducer(pendingQueue, updateLane);
          } else
            revertLane = {
              lane: updateLane,
              revertLane: update2.revertLane,
              gesture: update2.gesture,
              action: update2.action,
              hasEagerState: update2.hasEagerState,
              eagerState: update2.eagerState,
              next: null
            }, null === newBaseQueueLast ? (newBaseQueueFirst = newBaseQueueLast = revertLane, baseFirst = pendingQueue) : newBaseQueueLast = newBaseQueueLast.next = revertLane, currentlyRenderingFiber.lanes |= updateLane, workInProgressRootSkippedLanes |= updateLane;
          update2 = update2.next;
        } while (null !== update2 && update2 !== current22);
        null === newBaseQueueLast ? baseFirst = pendingQueue : newBaseQueueLast.next = newBaseQueueFirst;
        if (!objectIs(pendingQueue, hook.memoizedState) && (didReceiveUpdate = true, didReadFromEntangledAsyncAction2 && (reducer = currentEntangledActionThenable, null !== reducer)))
          throw reducer;
        hook.memoizedState = pendingQueue;
        hook.baseState = baseFirst;
        hook.baseQueue = newBaseQueueLast;
        queue.lastRenderedState = pendingQueue;
      }
      null === baseQueue && (queue.lanes = 0);
      return [hook.memoizedState, queue.dispatch];
    }
    function rerenderReducer(reducer) {
      var hook = updateWorkInProgressHook(), queue = hook.queue;
      if (null === queue)
        throw Error(
          "Should have a queue. You are likely calling Hooks conditionally, which is not allowed. (https://react.dev/link/invalid-hook-call)"
        );
      queue.lastRenderedReducer = reducer;
      var dispatch = queue.dispatch, lastRenderPhaseUpdate = queue.pending, newState = hook.memoizedState;
      if (null !== lastRenderPhaseUpdate) {
        queue.pending = null;
        var update2 = lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
        do
          newState = reducer(newState, update2.action), update2 = update2.next;
        while (update2 !== lastRenderPhaseUpdate);
        objectIs(newState, hook.memoizedState) || (didReceiveUpdate = true);
        hook.memoizedState = newState;
        null === hook.baseQueue && (hook.baseState = newState);
        queue.lastRenderedState = newState;
      }
      return [newState, dispatch];
    }
    function mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
      var fiber = currentlyRenderingFiber, hook = mountWorkInProgressHook();
      if (isHydrating) {
        if (void 0 === getServerSnapshot)
          throw Error(
            "Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering."
          );
        var nextSnapshot = getServerSnapshot();
        didWarnUncachedGetSnapshot || nextSnapshot === getServerSnapshot() || (console.error(
          "The result of getServerSnapshot should be cached to avoid an infinite loop"
        ), didWarnUncachedGetSnapshot = true);
      } else {
        nextSnapshot = getSnapshot();
        didWarnUncachedGetSnapshot || (getServerSnapshot = getSnapshot(), objectIs(nextSnapshot, getServerSnapshot) || (console.error(
          "The result of getSnapshot should be cached to avoid an infinite loop"
        ), didWarnUncachedGetSnapshot = true));
        if (null === workInProgressRoot)
          throw Error(
            "Expected a work-in-progress root. This is a bug in React. Please file an issue."
          );
        0 !== (workInProgressRootRenderLanes & 127) || pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot);
      }
      hook.memoizedState = nextSnapshot;
      getServerSnapshot = { value: nextSnapshot, getSnapshot };
      hook.queue = getServerSnapshot;
      mountEffect(
        subscribeToStore.bind(null, fiber, getServerSnapshot, subscribe),
        [subscribe]
      );
      fiber.flags |= 2048;
      pushSimpleEffect(
        HasEffect | Passive,
        { destroy: void 0 },
        updateStoreInstance.bind(
          null,
          fiber,
          getServerSnapshot,
          nextSnapshot,
          getSnapshot
        ),
        null
      );
      return nextSnapshot;
    }
    function updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
      var fiber = currentlyRenderingFiber, hook = updateWorkInProgressHook(), isHydrating$jscomp$0 = isHydrating;
      if (isHydrating$jscomp$0) {
        if (void 0 === getServerSnapshot)
          throw Error(
            "Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering."
          );
        getServerSnapshot = getServerSnapshot();
      } else if (getServerSnapshot = getSnapshot(), !didWarnUncachedGetSnapshot) {
        var cachedSnapshot = getSnapshot();
        objectIs(getServerSnapshot, cachedSnapshot) || (console.error(
          "The result of getSnapshot should be cached to avoid an infinite loop"
        ), didWarnUncachedGetSnapshot = true);
      }
      if (cachedSnapshot = !objectIs(
        (currentHook || hook).memoizedState,
        getServerSnapshot
      ))
        hook.memoizedState = getServerSnapshot, didReceiveUpdate = true;
      hook = hook.queue;
      var create2 = subscribeToStore.bind(null, fiber, hook, subscribe);
      updateEffectImpl(2048, Passive, create2, [subscribe]);
      if (hook.getSnapshot !== getSnapshot || cachedSnapshot || null !== workInProgressHook && workInProgressHook.memoizedState.tag & HasEffect) {
        fiber.flags |= 2048;
        pushSimpleEffect(
          HasEffect | Passive,
          { destroy: void 0 },
          updateStoreInstance.bind(
            null,
            fiber,
            hook,
            getServerSnapshot,
            getSnapshot
          ),
          null
        );
        if (null === workInProgressRoot)
          throw Error(
            "Expected a work-in-progress root. This is a bug in React. Please file an issue."
          );
        isHydrating$jscomp$0 || 0 !== (renderLanes & 127) || pushStoreConsistencyCheck(fiber, getSnapshot, getServerSnapshot);
      }
      return getServerSnapshot;
    }
    function pushStoreConsistencyCheck(fiber, getSnapshot, renderedSnapshot) {
      fiber.flags |= 16384;
      fiber = { getSnapshot, value: renderedSnapshot };
      getSnapshot = currentlyRenderingFiber.updateQueue;
      null === getSnapshot ? (getSnapshot = createFunctionComponentUpdateQueue(), currentlyRenderingFiber.updateQueue = getSnapshot, getSnapshot.stores = [fiber]) : (renderedSnapshot = getSnapshot.stores, null === renderedSnapshot ? getSnapshot.stores = [fiber] : renderedSnapshot.push(fiber));
    }
    function updateStoreInstance(fiber, inst, nextSnapshot, getSnapshot) {
      inst.value = nextSnapshot;
      inst.getSnapshot = getSnapshot;
      checkIfSnapshotChanged(inst) && forceStoreRerender(fiber);
    }
    function subscribeToStore(fiber, inst, subscribe) {
      return subscribe(function() {
        checkIfSnapshotChanged(inst) && (startUpdateTimerByLane(2, "updateSyncExternalStore()", fiber), forceStoreRerender(fiber));
      });
    }
    function checkIfSnapshotChanged(inst) {
      var latestGetSnapshot = inst.getSnapshot;
      inst = inst.value;
      try {
        var nextValue = latestGetSnapshot();
        return !objectIs(inst, nextValue);
      } catch (error2) {
        return true;
      }
    }
    function forceStoreRerender(fiber) {
      var root22 = enqueueConcurrentRenderForLane(fiber, 2);
      null !== root22 && scheduleUpdateOnFiber(root22, fiber, 2);
    }
    function mountStateImpl(initialState) {
      var hook = mountWorkInProgressHook();
      if ("function" === typeof initialState) {
        var initialStateInitializer = initialState;
        initialState = initialStateInitializer();
        if (shouldDoubleInvokeUserFnsInHooksDEV) {
          setIsStrictModeForDevtools(true);
          try {
            initialStateInitializer();
          } finally {
            setIsStrictModeForDevtools(false);
          }
        }
      }
      hook.memoizedState = hook.baseState = initialState;
      hook.queue = {
        pending: null,
        lanes: 0,
        dispatch: null,
        lastRenderedReducer: basicStateReducer,
        lastRenderedState: initialState
      };
      return hook;
    }
    function mountState(initialState) {
      initialState = mountStateImpl(initialState);
      var queue = initialState.queue, dispatch = dispatchSetState.bind(null, currentlyRenderingFiber, queue);
      queue.dispatch = dispatch;
      return [initialState.memoizedState, dispatch];
    }
    function mountOptimistic(passthrough) {
      var hook = mountWorkInProgressHook();
      hook.memoizedState = hook.baseState = passthrough;
      var queue = {
        pending: null,
        lanes: 0,
        dispatch: null,
        lastRenderedReducer: null,
        lastRenderedState: null
      };
      hook.queue = queue;
      hook = dispatchOptimisticSetState.bind(
        null,
        currentlyRenderingFiber,
        true,
        queue
      );
      queue.dispatch = hook;
      return [passthrough, hook];
    }
    function updateOptimistic(passthrough, reducer) {
      var hook = updateWorkInProgressHook();
      return updateOptimisticImpl(hook, currentHook, passthrough, reducer);
    }
    function updateOptimisticImpl(hook, current22, passthrough, reducer) {
      hook.baseState = passthrough;
      return updateReducerImpl(
        hook,
        currentHook,
        "function" === typeof reducer ? reducer : basicStateReducer
      );
    }
    function rerenderOptimistic(passthrough, reducer) {
      var hook = updateWorkInProgressHook();
      if (null !== currentHook)
        return updateOptimisticImpl(hook, currentHook, passthrough, reducer);
      hook.baseState = passthrough;
      return [passthrough, hook.queue.dispatch];
    }
    function dispatchActionState(fiber, actionQueue, setPendingState, setState2, payload) {
      if (isRenderPhaseUpdate(fiber))
        throw Error("Cannot update form state while rendering.");
      fiber = actionQueue.action;
      if (null !== fiber) {
        var actionNode = {
          payload,
          action: fiber,
          next: null,
          isTransition: true,
          status: "pending",
          value: null,
          reason: null,
          listeners: [],
          then: function(listener) {
            actionNode.listeners.push(listener);
          }
        };
        null !== ReactSharedInternals.T ? setPendingState(true) : actionNode.isTransition = false;
        setState2(actionNode);
        setPendingState = actionQueue.pending;
        null === setPendingState ? (actionNode.next = actionQueue.pending = actionNode, runActionStateAction(actionQueue, actionNode)) : (actionNode.next = setPendingState.next, actionQueue.pending = setPendingState.next = actionNode);
      }
    }
    function runActionStateAction(actionQueue, node2) {
      var action = node2.action, payload = node2.payload, prevState = actionQueue.state;
      if (node2.isTransition) {
        var prevTransition = ReactSharedInternals.T, currentTransition = {};
        currentTransition._updatedFibers = /* @__PURE__ */ new Set();
        ReactSharedInternals.T = currentTransition;
        try {
          var returnValue = action(prevState, payload), onStartTransitionFinish = ReactSharedInternals.S;
          null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue);
          handleActionReturnValue(actionQueue, node2, returnValue);
        } catch (error2) {
          onActionError(actionQueue, node2, error2);
        } finally {
          null !== prevTransition && null !== currentTransition.types && (null !== prevTransition.types && prevTransition.types !== currentTransition.types && console.error(
            "We expected inner Transitions to have transferred the outer types set and that you cannot add to the outer Transition while inside the inner.This is a bug in React."
          ), prevTransition.types = currentTransition.types), ReactSharedInternals.T = prevTransition, null === prevTransition && currentTransition._updatedFibers && (actionQueue = currentTransition._updatedFibers.size, currentTransition._updatedFibers.clear(), 10 < actionQueue && console.warn(
            "Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."
          ));
        }
      } else
        try {
          currentTransition = action(prevState, payload), handleActionReturnValue(actionQueue, node2, currentTransition);
        } catch (error$42) {
          onActionError(actionQueue, node2, error$42);
        }
    }
    function handleActionReturnValue(actionQueue, node2, returnValue) {
      null !== returnValue && "object" === typeof returnValue && "function" === typeof returnValue.then ? (ReactSharedInternals.asyncTransitions++, returnValue.then(releaseAsyncTransition, releaseAsyncTransition), returnValue.then(
        function(nextState) {
          onActionSuccess(actionQueue, node2, nextState);
        },
        function(error2) {
          return onActionError(actionQueue, node2, error2);
        }
      ), node2.isTransition || console.error(
        "An async function with useActionState was called outside of a transition. This is likely not what you intended (for example, isPending will not update correctly). Either call the returned function inside startTransition, or pass it to an `action` or `formAction` prop."
      )) : onActionSuccess(actionQueue, node2, returnValue);
    }
    function onActionSuccess(actionQueue, actionNode, nextState) {
      actionNode.status = "fulfilled";
      actionNode.value = nextState;
      notifyActionListeners(actionNode);
      actionQueue.state = nextState;
      actionNode = actionQueue.pending;
      null !== actionNode && (nextState = actionNode.next, nextState === actionNode ? actionQueue.pending = null : (nextState = nextState.next, actionNode.next = nextState, runActionStateAction(actionQueue, nextState)));
    }
    function onActionError(actionQueue, actionNode, error2) {
      var last2 = actionQueue.pending;
      actionQueue.pending = null;
      if (null !== last2) {
        last2 = last2.next;
        do
          actionNode.status = "rejected", actionNode.reason = error2, notifyActionListeners(actionNode), actionNode = actionNode.next;
        while (actionNode !== last2);
      }
      actionQueue.action = null;
    }
    function notifyActionListeners(actionNode) {
      actionNode = actionNode.listeners;
      for (var i2 = 0; i2 < actionNode.length; i2++) (0, actionNode[i2])();
    }
    function actionStateReducer(oldState, newState) {
      return newState;
    }
    function mountActionState(action, initialStateProp) {
      if (isHydrating) {
        var ssrFormState = workInProgressRoot.formState;
        if (null !== ssrFormState) {
          a: {
            var isMatching = currentlyRenderingFiber;
            if (isHydrating) {
              if (nextHydratableInstance) {
                b: {
                  var markerInstance = nextHydratableInstance;
                  for (var inRootOrSingleton = rootOrSingletonContext; 8 !== markerInstance.nodeType; ) {
                    if (!inRootOrSingleton) {
                      markerInstance = null;
                      break b;
                    }
                    markerInstance = getNextHydratable(
                      markerInstance.nextSibling
                    );
                    if (null === markerInstance) {
                      markerInstance = null;
                      break b;
                    }
                  }
                  inRootOrSingleton = markerInstance.data;
                  markerInstance = inRootOrSingleton === FORM_STATE_IS_MATCHING || inRootOrSingleton === FORM_STATE_IS_NOT_MATCHING ? markerInstance : null;
                }
                if (markerInstance) {
                  nextHydratableInstance = getNextHydratable(
                    markerInstance.nextSibling
                  );
                  isMatching = markerInstance.data === FORM_STATE_IS_MATCHING;
                  break a;
                }
              }
              throwOnHydrationMismatch(isMatching);
            }
            isMatching = false;
          }
          isMatching && (initialStateProp = ssrFormState[0]);
        }
      }
      ssrFormState = mountWorkInProgressHook();
      ssrFormState.memoizedState = ssrFormState.baseState = initialStateProp;
      isMatching = {
        pending: null,
        lanes: 0,
        dispatch: null,
        lastRenderedReducer: actionStateReducer,
        lastRenderedState: initialStateProp
      };
      ssrFormState.queue = isMatching;
      ssrFormState = dispatchSetState.bind(
        null,
        currentlyRenderingFiber,
        isMatching
      );
      isMatching.dispatch = ssrFormState;
      isMatching = mountStateImpl(false);
      inRootOrSingleton = dispatchOptimisticSetState.bind(
        null,
        currentlyRenderingFiber,
        false,
        isMatching.queue
      );
      isMatching = mountWorkInProgressHook();
      markerInstance = {
        state: initialStateProp,
        dispatch: null,
        action,
        pending: null
      };
      isMatching.queue = markerInstance;
      ssrFormState = dispatchActionState.bind(
        null,
        currentlyRenderingFiber,
        markerInstance,
        inRootOrSingleton,
        ssrFormState
      );
      markerInstance.dispatch = ssrFormState;
      isMatching.memoizedState = action;
      return [initialStateProp, ssrFormState, false];
    }
    function updateActionState(action) {
      var stateHook = updateWorkInProgressHook();
      return updateActionStateImpl(stateHook, currentHook, action);
    }
    function updateActionStateImpl(stateHook, currentStateHook, action) {
      currentStateHook = updateReducerImpl(
        stateHook,
        currentStateHook,
        actionStateReducer
      )[0];
      stateHook = updateReducer(basicStateReducer)[0];
      if ("object" === typeof currentStateHook && null !== currentStateHook && "function" === typeof currentStateHook.then)
        try {
          var state = useThenable(currentStateHook);
        } catch (x) {
          if (x === SuspenseException) throw SuspenseActionException;
          throw x;
        }
      else state = currentStateHook;
      currentStateHook = updateWorkInProgressHook();
      var actionQueue = currentStateHook.queue, dispatch = actionQueue.dispatch;
      action !== currentStateHook.memoizedState && (currentlyRenderingFiber.flags |= 2048, pushSimpleEffect(
        HasEffect | Passive,
        { destroy: void 0 },
        actionStateActionEffect.bind(null, actionQueue, action),
        null
      ));
      return [state, dispatch, stateHook];
    }
    function actionStateActionEffect(actionQueue, action) {
      actionQueue.action = action;
    }
    function rerenderActionState(action) {
      var stateHook = updateWorkInProgressHook(), currentStateHook = currentHook;
      if (null !== currentStateHook)
        return updateActionStateImpl(stateHook, currentStateHook, action);
      updateWorkInProgressHook();
      stateHook = stateHook.memoizedState;
      currentStateHook = updateWorkInProgressHook();
      var dispatch = currentStateHook.queue.dispatch;
      currentStateHook.memoizedState = action;
      return [stateHook, dispatch, false];
    }
    function pushSimpleEffect(tag, inst, create2, deps) {
      tag = { tag, create: create2, deps, inst, next: null };
      inst = currentlyRenderingFiber.updateQueue;
      null === inst && (inst = createFunctionComponentUpdateQueue(), currentlyRenderingFiber.updateQueue = inst);
      create2 = inst.lastEffect;
      null === create2 ? inst.lastEffect = tag.next = tag : (deps = create2.next, create2.next = tag, tag.next = deps, inst.lastEffect = tag);
      return tag;
    }
    function mountRef(initialValue) {
      var hook = mountWorkInProgressHook();
      initialValue = { current: initialValue };
      return hook.memoizedState = initialValue;
    }
    function mountEffectImpl(fiberFlags, hookFlags, create2, deps) {
      var hook = mountWorkInProgressHook();
      currentlyRenderingFiber.flags |= fiberFlags;
      hook.memoizedState = pushSimpleEffect(
        HasEffect | hookFlags,
        { destroy: void 0 },
        create2,
        void 0 === deps ? null : deps
      );
    }
    function updateEffectImpl(fiberFlags, hookFlags, create2, deps) {
      var hook = updateWorkInProgressHook();
      deps = void 0 === deps ? null : deps;
      var inst = hook.memoizedState.inst;
      null !== currentHook && null !== deps && areHookInputsEqual(deps, currentHook.memoizedState.deps) ? hook.memoizedState = pushSimpleEffect(hookFlags, inst, create2, deps) : (currentlyRenderingFiber.flags |= fiberFlags, hook.memoizedState = pushSimpleEffect(
        HasEffect | hookFlags,
        inst,
        create2,
        deps
      ));
    }
    function mountEffect(create2, deps) {
      (currentlyRenderingFiber.mode & StrictEffectsMode) !== NoMode ? mountEffectImpl(276826112, Passive, create2, deps) : mountEffectImpl(8390656, Passive, create2, deps);
    }
    function useEffectEventImpl(payload) {
      currentlyRenderingFiber.flags |= 4;
      var componentUpdateQueue = currentlyRenderingFiber.updateQueue;
      if (null === componentUpdateQueue)
        componentUpdateQueue = createFunctionComponentUpdateQueue(), currentlyRenderingFiber.updateQueue = componentUpdateQueue, componentUpdateQueue.events = [payload];
      else {
        var events = componentUpdateQueue.events;
        null === events ? componentUpdateQueue.events = [payload] : events.push(payload);
      }
    }
    function mountEvent(callback) {
      var hook = mountWorkInProgressHook(), ref2 = { impl: callback };
      hook.memoizedState = ref2;
      return function() {
        if ((executionContext & RenderContext) !== NoContext)
          throw Error(
            "A function wrapped in useEffectEvent can't be called during rendering."
          );
        return ref2.impl.apply(void 0, arguments);
      };
    }
    function updateEvent(callback) {
      var ref2 = updateWorkInProgressHook().memoizedState;
      useEffectEventImpl({ ref: ref2, nextImpl: callback });
      return function() {
        if ((executionContext & RenderContext) !== NoContext)
          throw Error(
            "A function wrapped in useEffectEvent can't be called during rendering."
          );
        return ref2.impl.apply(void 0, arguments);
      };
    }
    function mountLayoutEffect(create2, deps) {
      var fiberFlags = 4194308;
      (currentlyRenderingFiber.mode & StrictEffectsMode) !== NoMode && (fiberFlags |= 134217728);
      return mountEffectImpl(fiberFlags, Layout, create2, deps);
    }
    function imperativeHandleEffect(create2, ref2) {
      if ("function" === typeof ref2) {
        create2 = create2();
        var refCleanup = ref2(create2);
        return function() {
          "function" === typeof refCleanup ? refCleanup() : ref2(null);
        };
      }
      if (null !== ref2 && void 0 !== ref2)
        return ref2.hasOwnProperty("current") || console.error(
          "Expected useImperativeHandle() first argument to either be a ref callback or React.createRef() object. Instead received: %s.",
          "an object with keys {" + Object.keys(ref2).join(", ") + "}"
        ), create2 = create2(), ref2.current = create2, function() {
          ref2.current = null;
        };
    }
    function mountImperativeHandle(ref2, create2, deps) {
      "function" !== typeof create2 && console.error(
        "Expected useImperativeHandle() second argument to be a function that creates a handle. Instead received: %s.",
        null !== create2 ? typeof create2 : "null"
      );
      deps = null !== deps && void 0 !== deps ? deps.concat([ref2]) : null;
      var fiberFlags = 4194308;
      (currentlyRenderingFiber.mode & StrictEffectsMode) !== NoMode && (fiberFlags |= 134217728);
      mountEffectImpl(
        fiberFlags,
        Layout,
        imperativeHandleEffect.bind(null, create2, ref2),
        deps
      );
    }
    function updateImperativeHandle(ref2, create2, deps) {
      "function" !== typeof create2 && console.error(
        "Expected useImperativeHandle() second argument to be a function that creates a handle. Instead received: %s.",
        null !== create2 ? typeof create2 : "null"
      );
      deps = null !== deps && void 0 !== deps ? deps.concat([ref2]) : null;
      updateEffectImpl(
        4,
        Layout,
        imperativeHandleEffect.bind(null, create2, ref2),
        deps
      );
    }
    function mountCallback(callback, deps) {
      mountWorkInProgressHook().memoizedState = [
        callback,
        void 0 === deps ? null : deps
      ];
      return callback;
    }
    function updateCallback(callback, deps) {
      var hook = updateWorkInProgressHook();
      deps = void 0 === deps ? null : deps;
      var prevState = hook.memoizedState;
      if (null !== deps && areHookInputsEqual(deps, prevState[1]))
        return prevState[0];
      hook.memoizedState = [callback, deps];
      return callback;
    }
    function mountMemo(nextCreate, deps) {
      var hook = mountWorkInProgressHook();
      deps = void 0 === deps ? null : deps;
      var nextValue = nextCreate();
      if (shouldDoubleInvokeUserFnsInHooksDEV) {
        setIsStrictModeForDevtools(true);
        try {
          nextCreate();
        } finally {
          setIsStrictModeForDevtools(false);
        }
      }
      hook.memoizedState = [nextValue, deps];
      return nextValue;
    }
    function updateMemo(nextCreate, deps) {
      var hook = updateWorkInProgressHook();
      deps = void 0 === deps ? null : deps;
      var prevState = hook.memoizedState;
      if (null !== deps && areHookInputsEqual(deps, prevState[1]))
        return prevState[0];
      prevState = nextCreate();
      if (shouldDoubleInvokeUserFnsInHooksDEV) {
        setIsStrictModeForDevtools(true);
        try {
          nextCreate();
        } finally {
          setIsStrictModeForDevtools(false);
        }
      }
      hook.memoizedState = [prevState, deps];
      return prevState;
    }
    function mountDeferredValue(value2, initialValue) {
      var hook = mountWorkInProgressHook();
      return mountDeferredValueImpl(hook, value2, initialValue);
    }
    function updateDeferredValue(value2, initialValue) {
      var hook = updateWorkInProgressHook();
      return updateDeferredValueImpl(
        hook,
        currentHook.memoizedState,
        value2,
        initialValue
      );
    }
    function rerenderDeferredValue(value2, initialValue) {
      var hook = updateWorkInProgressHook();
      return null === currentHook ? mountDeferredValueImpl(hook, value2, initialValue) : updateDeferredValueImpl(
        hook,
        currentHook.memoizedState,
        value2,
        initialValue
      );
    }
    function mountDeferredValueImpl(hook, value2, initialValue) {
      if (void 0 === initialValue || 0 !== (renderLanes & 1073741824) && 0 === (workInProgressRootRenderLanes & 261930))
        return hook.memoizedState = value2;
      hook.memoizedState = initialValue;
      hook = requestDeferredLane();
      currentlyRenderingFiber.lanes |= hook;
      workInProgressRootSkippedLanes |= hook;
      return initialValue;
    }
    function updateDeferredValueImpl(hook, prevValue, value2, initialValue) {
      if (objectIs(value2, prevValue)) return value2;
      if (null !== currentTreeHiddenStackCursor.current)
        return hook = mountDeferredValueImpl(hook, value2, initialValue), objectIs(hook, prevValue) || (didReceiveUpdate = true), hook;
      if (0 === (renderLanes & 42) || 0 !== (renderLanes & 1073741824) && 0 === (workInProgressRootRenderLanes & 261930))
        return didReceiveUpdate = true, hook.memoizedState = value2;
      hook = requestDeferredLane();
      currentlyRenderingFiber.lanes |= hook;
      workInProgressRootSkippedLanes |= hook;
      return prevValue;
    }
    function releaseAsyncTransition() {
      ReactSharedInternals.asyncTransitions--;
    }
    function startTransition2(fiber, queue, pendingState, finishedState, callback) {
      var previousPriority = ReactDOMSharedInternals.p;
      ReactDOMSharedInternals.p = 0 !== previousPriority && previousPriority < ContinuousEventPriority ? previousPriority : ContinuousEventPriority;
      var prevTransition = ReactSharedInternals.T, currentTransition = {};
      currentTransition._updatedFibers = /* @__PURE__ */ new Set();
      ReactSharedInternals.T = currentTransition;
      dispatchOptimisticSetState(fiber, false, queue, pendingState);
      try {
        var returnValue = callback(), onStartTransitionFinish = ReactSharedInternals.S;
        null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue);
        if (null !== returnValue && "object" === typeof returnValue && "function" === typeof returnValue.then) {
          ReactSharedInternals.asyncTransitions++;
          returnValue.then(releaseAsyncTransition, releaseAsyncTransition);
          var thenableForFinishedState = chainThenableValue(
            returnValue,
            finishedState
          );
          dispatchSetStateInternal(
            fiber,
            queue,
            thenableForFinishedState,
            requestUpdateLane(fiber)
          );
        } else
          dispatchSetStateInternal(
            fiber,
            queue,
            finishedState,
            requestUpdateLane(fiber)
          );
      } catch (error2) {
        dispatchSetStateInternal(
          fiber,
          queue,
          { then: function() {
          }, status: "rejected", reason: error2 },
          requestUpdateLane(fiber)
        );
      } finally {
        ReactDOMSharedInternals.p = previousPriority, null !== prevTransition && null !== currentTransition.types && (null !== prevTransition.types && prevTransition.types !== currentTransition.types && console.error(
          "We expected inner Transitions to have transferred the outer types set and that you cannot add to the outer Transition while inside the inner.This is a bug in React."
        ), prevTransition.types = currentTransition.types), ReactSharedInternals.T = prevTransition, null === prevTransition && currentTransition._updatedFibers && (fiber = currentTransition._updatedFibers.size, currentTransition._updatedFibers.clear(), 10 < fiber && console.warn(
          "Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."
        ));
      }
    }
    function startHostTransition(formFiber, pendingState, action, formData) {
      if (5 !== formFiber.tag)
        throw Error(
          "Expected the form instance to be a HostComponent. This is a bug in React."
        );
      var queue = ensureFormComponentIsStateful(formFiber).queue;
      startHostActionTimer(formFiber);
      startTransition2(
        formFiber,
        queue,
        pendingState,
        NotPendingTransition,
        null === action ? noop2 : function() {
          requestFormReset$1(formFiber);
          return action(formData);
        }
      );
    }
    function ensureFormComponentIsStateful(formFiber) {
      var existingStateHook = formFiber.memoizedState;
      if (null !== existingStateHook) return existingStateHook;
      existingStateHook = {
        memoizedState: NotPendingTransition,
        baseState: NotPendingTransition,
        baseQueue: null,
        queue: {
          pending: null,
          lanes: 0,
          dispatch: null,
          lastRenderedReducer: basicStateReducer,
          lastRenderedState: NotPendingTransition
        },
        next: null
      };
      var initialResetState = {};
      existingStateHook.next = {
        memoizedState: initialResetState,
        baseState: initialResetState,
        baseQueue: null,
        queue: {
          pending: null,
          lanes: 0,
          dispatch: null,
          lastRenderedReducer: basicStateReducer,
          lastRenderedState: initialResetState
        },
        next: null
      };
      formFiber.memoizedState = existingStateHook;
      formFiber = formFiber.alternate;
      null !== formFiber && (formFiber.memoizedState = existingStateHook);
      return existingStateHook;
    }
    function requestFormReset$1(formFiber) {
      null === ReactSharedInternals.T && console.error(
        "requestFormReset was called outside a transition or action. To fix, move to an action, or wrap with startTransition."
      );
      var stateHook = ensureFormComponentIsStateful(formFiber);
      null === stateHook.next && (stateHook = formFiber.alternate.memoizedState);
      dispatchSetStateInternal(
        formFiber,
        stateHook.next.queue,
        {},
        requestUpdateLane(formFiber)
      );
    }
    function mountTransition() {
      var stateHook = mountStateImpl(false);
      stateHook = startTransition2.bind(
        null,
        currentlyRenderingFiber,
        stateHook.queue,
        true,
        false
      );
      mountWorkInProgressHook().memoizedState = stateHook;
      return [false, stateHook];
    }
    function updateTransition() {
      var booleanOrThenable = updateReducer(basicStateReducer)[0], start2 = updateWorkInProgressHook().memoizedState;
      return [
        "boolean" === typeof booleanOrThenable ? booleanOrThenable : useThenable(booleanOrThenable),
        start2
      ];
    }
    function rerenderTransition() {
      var booleanOrThenable = rerenderReducer(basicStateReducer)[0], start2 = updateWorkInProgressHook().memoizedState;
      return [
        "boolean" === typeof booleanOrThenable ? booleanOrThenable : useThenable(booleanOrThenable),
        start2
      ];
    }
    function useHostTransitionStatus() {
      return readContext(HostTransitionContext);
    }
    function mountId() {
      var hook = mountWorkInProgressHook(), identifierPrefix = workInProgressRoot.identifierPrefix;
      if (isHydrating) {
        var treeId = treeContextOverflow;
        var idWithLeadingBit = treeContextId;
        treeId = (idWithLeadingBit & ~(1 << 32 - clz322(idWithLeadingBit) - 1)).toString(32) + treeId;
        identifierPrefix = "_" + identifierPrefix + "R_" + treeId;
        treeId = localIdCounter++;
        0 < treeId && (identifierPrefix += "H" + treeId.toString(32));
        identifierPrefix += "_";
      } else
        treeId = globalClientIdCounter++, identifierPrefix = "_" + identifierPrefix + "r_" + treeId.toString(32) + "_";
      return hook.memoizedState = identifierPrefix;
    }
    function mountRefresh() {
      return mountWorkInProgressHook().memoizedState = refreshCache.bind(
        null,
        currentlyRenderingFiber
      );
    }
    function refreshCache(fiber, seedKey) {
      for (var provider = fiber.return; null !== provider; ) {
        switch (provider.tag) {
          case 24:
          case 3:
            var lane = requestUpdateLane(provider), refreshUpdate = createUpdate(lane), root22 = enqueueUpdate(provider, refreshUpdate, lane);
            null !== root22 && (startUpdateTimerByLane(lane, "refresh()", fiber), scheduleUpdateOnFiber(root22, provider, lane), entangleTransitions(root22, provider, lane));
            fiber = createCache();
            null !== seedKey && void 0 !== seedKey && null !== root22 && console.error(
              "The seed argument is not enabled outside experimental channels."
            );
            refreshUpdate.payload = { cache: fiber };
            return;
        }
        provider = provider.return;
      }
    }
    function dispatchReducerAction(fiber, queue, action) {
      var args2 = arguments;
      "function" === typeof args2[3] && console.error(
        "State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect()."
      );
      args2 = requestUpdateLane(fiber);
      var update2 = {
        lane: args2,
        revertLane: 0,
        gesture: null,
        action,
        hasEagerState: false,
        eagerState: null,
        next: null
      };
      isRenderPhaseUpdate(fiber) ? enqueueRenderPhaseUpdate(queue, update2) : (update2 = enqueueConcurrentHookUpdate(fiber, queue, update2, args2), null !== update2 && (startUpdateTimerByLane(args2, "dispatch()", fiber), scheduleUpdateOnFiber(update2, fiber, args2), entangleTransitionUpdate(update2, queue, args2)));
    }
    function dispatchSetState(fiber, queue, action) {
      var args2 = arguments;
      "function" === typeof args2[3] && console.error(
        "State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect()."
      );
      args2 = requestUpdateLane(fiber);
      dispatchSetStateInternal(fiber, queue, action, args2) && startUpdateTimerByLane(args2, "setState()", fiber);
    }
    function dispatchSetStateInternal(fiber, queue, action, lane) {
      var update2 = {
        lane,
        revertLane: 0,
        gesture: null,
        action,
        hasEagerState: false,
        eagerState: null,
        next: null
      };
      if (isRenderPhaseUpdate(fiber)) enqueueRenderPhaseUpdate(queue, update2);
      else {
        var alternate = fiber.alternate;
        if (0 === fiber.lanes && (null === alternate || 0 === alternate.lanes) && (alternate = queue.lastRenderedReducer, null !== alternate)) {
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
          try {
            var currentState = queue.lastRenderedState, eagerState = alternate(currentState, action);
            update2.hasEagerState = true;
            update2.eagerState = eagerState;
            if (objectIs(eagerState, currentState))
              return enqueueUpdate$1(fiber, queue, update2, 0), null === workInProgressRoot && finishQueueingConcurrentUpdates(), false;
          } catch (error2) {
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        }
        action = enqueueConcurrentHookUpdate(fiber, queue, update2, lane);
        if (null !== action)
          return scheduleUpdateOnFiber(action, fiber, lane), entangleTransitionUpdate(action, queue, lane), true;
      }
      return false;
    }
    function dispatchOptimisticSetState(fiber, throwIfDuringRender, queue, action) {
      null === ReactSharedInternals.T && 0 === currentEntangledLane && console.error(
        "An optimistic state update occurred outside a transition or action. To fix, move the update to an action, or wrap with startTransition."
      );
      action = {
        lane: 2,
        revertLane: requestTransitionLane(),
        gesture: null,
        action,
        hasEagerState: false,
        eagerState: null,
        next: null
      };
      if (isRenderPhaseUpdate(fiber)) {
        if (throwIfDuringRender)
          throw Error("Cannot update optimistic state while rendering.");
        console.error("Cannot call startTransition while rendering.");
      } else
        throwIfDuringRender = enqueueConcurrentHookUpdate(
          fiber,
          queue,
          action,
          2
        ), null !== throwIfDuringRender && (startUpdateTimerByLane(2, "setOptimistic()", fiber), scheduleUpdateOnFiber(throwIfDuringRender, fiber, 2));
    }
    function isRenderPhaseUpdate(fiber) {
      var alternate = fiber.alternate;
      return fiber === currentlyRenderingFiber || null !== alternate && alternate === currentlyRenderingFiber;
    }
    function enqueueRenderPhaseUpdate(queue, update2) {
      didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate = true;
      var pending = queue.pending;
      null === pending ? update2.next = update2 : (update2.next = pending.next, pending.next = update2);
      queue.pending = update2;
    }
    function entangleTransitionUpdate(root22, queue, lane) {
      if (0 !== (lane & 4194048)) {
        var queueLanes = queue.lanes;
        queueLanes &= root22.pendingLanes;
        lane |= queueLanes;
        queue.lanes = lane;
        markRootEntangled(root22, lane);
      }
    }
    function warnOnInvalidCallback(callback) {
      if (null !== callback && "function" !== typeof callback) {
        var key2 = String(callback);
        didWarnOnInvalidCallback.has(key2) || (didWarnOnInvalidCallback.add(key2), console.error(
          "Expected the last optional `callback` argument to be a function. Instead received: %s.",
          callback
        ));
      }
    }
    function applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, nextProps) {
      var prevState = workInProgress2.memoizedState, partialState = getDerivedStateFromProps(nextProps, prevState);
      if (workInProgress2.mode & StrictLegacyMode) {
        setIsStrictModeForDevtools(true);
        try {
          partialState = getDerivedStateFromProps(nextProps, prevState);
        } finally {
          setIsStrictModeForDevtools(false);
        }
      }
      void 0 === partialState && (ctor = getComponentNameFromType(ctor) || "Component", didWarnAboutUndefinedDerivedState.has(ctor) || (didWarnAboutUndefinedDerivedState.add(ctor), console.error(
        "%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. You have returned undefined.",
        ctor
      )));
      prevState = null === partialState || void 0 === partialState ? prevState : assign2({}, prevState, partialState);
      workInProgress2.memoizedState = prevState;
      0 === workInProgress2.lanes && (workInProgress2.updateQueue.baseState = prevState);
    }
    function checkShouldComponentUpdate(workInProgress2, ctor, oldProps, newProps, oldState, newState, nextContext) {
      var instance2 = workInProgress2.stateNode;
      if ("function" === typeof instance2.shouldComponentUpdate) {
        oldProps = instance2.shouldComponentUpdate(
          newProps,
          newState,
          nextContext
        );
        if (workInProgress2.mode & StrictLegacyMode) {
          setIsStrictModeForDevtools(true);
          try {
            oldProps = instance2.shouldComponentUpdate(
              newProps,
              newState,
              nextContext
            );
          } finally {
            setIsStrictModeForDevtools(false);
          }
        }
        void 0 === oldProps && console.error(
          "%s.shouldComponentUpdate(): Returned undefined instead of a boolean value. Make sure to return true or false.",
          getComponentNameFromType(ctor) || "Component"
        );
        return oldProps;
      }
      return ctor.prototype && ctor.prototype.isPureReactComponent ? !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState) : true;
    }
    function callComponentWillReceiveProps(workInProgress2, instance2, newProps, nextContext) {
      var oldState = instance2.state;
      "function" === typeof instance2.componentWillReceiveProps && instance2.componentWillReceiveProps(newProps, nextContext);
      "function" === typeof instance2.UNSAFE_componentWillReceiveProps && instance2.UNSAFE_componentWillReceiveProps(newProps, nextContext);
      instance2.state !== oldState && (workInProgress2 = getComponentNameFromFiber(workInProgress2) || "Component", didWarnAboutStateAssignmentForComponent.has(workInProgress2) || (didWarnAboutStateAssignmentForComponent.add(workInProgress2), console.error(
        "%s.componentWillReceiveProps(): Assigning directly to this.state is deprecated (except inside a component's constructor). Use setState instead.",
        workInProgress2
      )), classComponentUpdater.enqueueReplaceState(
        instance2,
        instance2.state,
        null
      ));
    }
    function resolveClassComponentProps(Component2, baseProps) {
      var newProps = baseProps;
      if ("ref" in baseProps) {
        newProps = {};
        for (var propName in baseProps)
          "ref" !== propName && (newProps[propName] = baseProps[propName]);
      }
      if (Component2 = Component2.defaultProps) {
        newProps === baseProps && (newProps = assign2({}, newProps));
        for (var _propName in Component2)
          void 0 === newProps[_propName] && (newProps[_propName] = Component2[_propName]);
      }
      return newProps;
    }
    function defaultOnUncaughtError(error2) {
      reportGlobalError(error2);
      console.warn(
        "%s\n\n%s\n",
        componentName ? "An error occurred in the <" + componentName + "> component." : "An error occurred in one of your React components.",
        "Consider adding an error boundary to your tree to customize error handling behavior.\nVisit https://react.dev/link/error-boundaries to learn more about error boundaries."
      );
    }
    function defaultOnCaughtError(error2) {
      var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component." : "The above error occurred in one of your React components.", recreateMessage = "React will try to recreate this component tree from scratch using the error boundary you provided, " + ((errorBoundaryName || "Anonymous") + ".");
      if ("object" === typeof error2 && null !== error2 && "string" === typeof error2.environmentName) {
        var JSCompiler_inline_result = error2.environmentName;
        error2 = [
          "%o\n\n%s\n\n%s\n",
          error2,
          componentNameMessage,
          recreateMessage
        ].slice(0);
        "string" === typeof error2[0] ? error2.splice(
          0,
          1,
          badgeFormat + " " + error2[0],
          badgeStyle,
          pad3 + JSCompiler_inline_result + pad3,
          resetStyle
        ) : error2.splice(
          0,
          0,
          badgeFormat,
          badgeStyle,
          pad3 + JSCompiler_inline_result + pad3,
          resetStyle
        );
        error2.unshift(console);
        JSCompiler_inline_result = bind.apply(console.error, error2);
        JSCompiler_inline_result();
      } else
        console.error(
          "%o\n\n%s\n\n%s\n",
          error2,
          componentNameMessage,
          recreateMessage
        );
    }
    function defaultOnRecoverableError(error2) {
      reportGlobalError(error2);
    }
    function logUncaughtError(root22, errorInfo) {
      try {
        componentName = errorInfo.source ? getComponentNameFromFiber(errorInfo.source) : null;
        errorBoundaryName = null;
        var error2 = errorInfo.value;
        if (null !== ReactSharedInternals.actQueue)
          ReactSharedInternals.thrownErrors.push(error2);
        else {
          var onUncaughtError = root22.onUncaughtError;
          onUncaughtError(error2, { componentStack: errorInfo.stack });
        }
      } catch (e$5) {
        setTimeout(function() {
          throw e$5;
        });
      }
    }
    function logCaughtError(root22, boundary, errorInfo) {
      try {
        componentName = errorInfo.source ? getComponentNameFromFiber(errorInfo.source) : null;
        errorBoundaryName = getComponentNameFromFiber(boundary);
        var onCaughtError = root22.onCaughtError;
        onCaughtError(errorInfo.value, {
          componentStack: errorInfo.stack,
          errorBoundary: 1 === boundary.tag ? boundary.stateNode : null
        });
      } catch (e$6) {
        setTimeout(function() {
          throw e$6;
        });
      }
    }
    function createRootErrorUpdate(root22, errorInfo, lane) {
      lane = createUpdate(lane);
      lane.tag = CaptureUpdate;
      lane.payload = { element: null };
      lane.callback = function() {
        runWithFiberInDEV(errorInfo.source, logUncaughtError, root22, errorInfo);
      };
      return lane;
    }
    function createClassErrorUpdate(lane) {
      lane = createUpdate(lane);
      lane.tag = CaptureUpdate;
      return lane;
    }
    function initializeClassErrorUpdate(update2, root22, fiber, errorInfo) {
      var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
      if ("function" === typeof getDerivedStateFromError) {
        var error2 = errorInfo.value;
        update2.payload = function() {
          return getDerivedStateFromError(error2);
        };
        update2.callback = function() {
          markFailedErrorBoundaryForHotReloading(fiber);
          runWithFiberInDEV(
            errorInfo.source,
            logCaughtError,
            root22,
            fiber,
            errorInfo
          );
        };
      }
      var inst = fiber.stateNode;
      null !== inst && "function" === typeof inst.componentDidCatch && (update2.callback = function() {
        markFailedErrorBoundaryForHotReloading(fiber);
        runWithFiberInDEV(
          errorInfo.source,
          logCaughtError,
          root22,
          fiber,
          errorInfo
        );
        "function" !== typeof getDerivedStateFromError && (null === legacyErrorBoundariesThatAlreadyFailed ? legacyErrorBoundariesThatAlreadyFailed = /* @__PURE__ */ new Set([this]) : legacyErrorBoundariesThatAlreadyFailed.add(this));
        callComponentDidCatchInDEV(this, errorInfo);
        "function" === typeof getDerivedStateFromError || 0 === (fiber.lanes & 2) && console.error(
          "%s: Error boundaries should implement getDerivedStateFromError(). In that method, return a state update to display an error message or fallback UI.",
          getComponentNameFromFiber(fiber) || "Unknown"
        );
      });
    }
    function throwException(root22, returnFiber, sourceFiber, value2, rootRenderLanes) {
      sourceFiber.flags |= 32768;
      isDevToolsPresent && restorePendingUpdaters(root22, rootRenderLanes);
      if (null !== value2 && "object" === typeof value2 && "function" === typeof value2.then) {
        returnFiber = sourceFiber.alternate;
        null !== returnFiber && propagateParentContextChanges(
          returnFiber,
          sourceFiber,
          rootRenderLanes,
          true
        );
        isHydrating && (didSuspendOrErrorDEV = true);
        sourceFiber = suspenseHandlerStackCursor.current;
        if (null !== sourceFiber) {
          switch (sourceFiber.tag) {
            case 31:
            case 13:
              return null === shellBoundary ? renderDidSuspendDelayIfPossible() : null === sourceFiber.alternate && workInProgressRootExitStatus === RootInProgress && (workInProgressRootExitStatus = RootSuspended), sourceFiber.flags &= -257, sourceFiber.flags |= 65536, sourceFiber.lanes = rootRenderLanes, value2 === noopSuspenseyCommitThenable ? sourceFiber.flags |= 16384 : (returnFiber = sourceFiber.updateQueue, null === returnFiber ? sourceFiber.updateQueue = /* @__PURE__ */ new Set([value2]) : returnFiber.add(value2), attachPingListener(root22, value2, rootRenderLanes)), false;
            case 22:
              return sourceFiber.flags |= 65536, value2 === noopSuspenseyCommitThenable ? sourceFiber.flags |= 16384 : (returnFiber = sourceFiber.updateQueue, null === returnFiber ? (returnFiber = {
                transitions: null,
                markerInstances: null,
                retryQueue: /* @__PURE__ */ new Set([value2])
              }, sourceFiber.updateQueue = returnFiber) : (sourceFiber = returnFiber.retryQueue, null === sourceFiber ? returnFiber.retryQueue = /* @__PURE__ */ new Set([value2]) : sourceFiber.add(value2)), attachPingListener(root22, value2, rootRenderLanes)), false;
          }
          throw Error(
            "Unexpected Suspense handler tag (" + sourceFiber.tag + "). This is a bug in React."
          );
        }
        attachPingListener(root22, value2, rootRenderLanes);
        renderDidSuspendDelayIfPossible();
        return false;
      }
      if (isHydrating)
        return didSuspendOrErrorDEV = true, returnFiber = suspenseHandlerStackCursor.current, null !== returnFiber ? (0 === (returnFiber.flags & 65536) && (returnFiber.flags |= 256), returnFiber.flags |= 65536, returnFiber.lanes = rootRenderLanes, value2 !== HydrationMismatchException && queueHydrationError(
          createCapturedValueAtFiber(
            Error(
              "There was an error while hydrating but React was able to recover by instead client rendering from the nearest Suspense boundary.",
              { cause: value2 }
            ),
            sourceFiber
          )
        )) : (value2 !== HydrationMismatchException && queueHydrationError(
          createCapturedValueAtFiber(
            Error(
              "There was an error while hydrating but React was able to recover by instead client rendering the entire root.",
              { cause: value2 }
            ),
            sourceFiber
          )
        ), root22 = root22.current.alternate, root22.flags |= 65536, rootRenderLanes &= -rootRenderLanes, root22.lanes |= rootRenderLanes, value2 = createCapturedValueAtFiber(value2, sourceFiber), rootRenderLanes = createRootErrorUpdate(
          root22.stateNode,
          value2,
          rootRenderLanes
        ), enqueueCapturedUpdate(root22, rootRenderLanes), workInProgressRootExitStatus !== RootSuspendedWithDelay && (workInProgressRootExitStatus = RootErrored)), false;
      var error2 = createCapturedValueAtFiber(
        Error(
          "There was an error during concurrent rendering but React was able to recover by instead synchronously rendering the entire root.",
          { cause: value2 }
        ),
        sourceFiber
      );
      null === workInProgressRootConcurrentErrors ? workInProgressRootConcurrentErrors = [error2] : workInProgressRootConcurrentErrors.push(error2);
      workInProgressRootExitStatus !== RootSuspendedWithDelay && (workInProgressRootExitStatus = RootErrored);
      if (null === returnFiber) return true;
      value2 = createCapturedValueAtFiber(value2, sourceFiber);
      sourceFiber = returnFiber;
      do {
        switch (sourceFiber.tag) {
          case 3:
            return sourceFiber.flags |= 65536, root22 = rootRenderLanes & -rootRenderLanes, sourceFiber.lanes |= root22, root22 = createRootErrorUpdate(
              sourceFiber.stateNode,
              value2,
              root22
            ), enqueueCapturedUpdate(sourceFiber, root22), false;
          case 1:
            if (returnFiber = sourceFiber.type, error2 = sourceFiber.stateNode, 0 === (sourceFiber.flags & 128) && ("function" === typeof returnFiber.getDerivedStateFromError || null !== error2 && "function" === typeof error2.componentDidCatch && (null === legacyErrorBoundariesThatAlreadyFailed || !legacyErrorBoundariesThatAlreadyFailed.has(error2))))
              return sourceFiber.flags |= 65536, rootRenderLanes &= -rootRenderLanes, sourceFiber.lanes |= rootRenderLanes, rootRenderLanes = createClassErrorUpdate(rootRenderLanes), initializeClassErrorUpdate(
                rootRenderLanes,
                root22,
                sourceFiber,
                value2
              ), enqueueCapturedUpdate(sourceFiber, rootRenderLanes), false;
        }
        sourceFiber = sourceFiber.return;
      } while (null !== sourceFiber);
      return false;
    }
    function reconcileChildren(current22, workInProgress2, nextChildren, renderLanes2) {
      workInProgress2.child = null === current22 ? mountChildFibers(workInProgress2, null, nextChildren, renderLanes2) : reconcileChildFibers(
        workInProgress2,
        current22.child,
        nextChildren,
        renderLanes2
      );
    }
    function updateForwardRef(current22, workInProgress2, Component2, nextProps, renderLanes2) {
      Component2 = Component2.render;
      var ref2 = workInProgress2.ref;
      if ("ref" in nextProps) {
        var propsWithoutRef = {};
        for (var key2 in nextProps)
          "ref" !== key2 && (propsWithoutRef[key2] = nextProps[key2]);
      } else propsWithoutRef = nextProps;
      prepareToReadContext(workInProgress2);
      nextProps = renderWithHooks(
        current22,
        workInProgress2,
        Component2,
        propsWithoutRef,
        ref2,
        renderLanes2
      );
      key2 = checkDidRenderIdHook();
      if (null !== current22 && !didReceiveUpdate)
        return bailoutHooks(current22, workInProgress2, renderLanes2), bailoutOnAlreadyFinishedWork(current22, workInProgress2, renderLanes2);
      isHydrating && key2 && pushMaterializedTreeId(workInProgress2);
      workInProgress2.flags |= 1;
      reconcileChildren(current22, workInProgress2, nextProps, renderLanes2);
      return workInProgress2.child;
    }
    function updateMemoComponent(current22, workInProgress2, Component2, nextProps, renderLanes2) {
      if (null === current22) {
        var type = Component2.type;
        if ("function" === typeof type && !shouldConstruct(type) && void 0 === type.defaultProps && null === Component2.compare)
          return Component2 = resolveFunctionForHotReloading(type), workInProgress2.tag = 15, workInProgress2.type = Component2, validateFunctionComponentInDev(workInProgress2, type), updateSimpleMemoComponent(
            current22,
            workInProgress2,
            Component2,
            nextProps,
            renderLanes2
          );
        current22 = createFiberFromTypeAndProps(
          Component2.type,
          null,
          nextProps,
          workInProgress2,
          workInProgress2.mode,
          renderLanes2
        );
        current22.ref = workInProgress2.ref;
        current22.return = workInProgress2;
        return workInProgress2.child = current22;
      }
      type = current22.child;
      if (!checkScheduledUpdateOrContext(current22, renderLanes2)) {
        var prevProps = type.memoizedProps;
        Component2 = Component2.compare;
        Component2 = null !== Component2 ? Component2 : shallowEqual;
        if (Component2(prevProps, nextProps) && current22.ref === workInProgress2.ref)
          return bailoutOnAlreadyFinishedWork(
            current22,
            workInProgress2,
            renderLanes2
          );
      }
      workInProgress2.flags |= 1;
      current22 = createWorkInProgress(type, nextProps);
      current22.ref = workInProgress2.ref;
      current22.return = workInProgress2;
      return workInProgress2.child = current22;
    }
    function updateSimpleMemoComponent(current22, workInProgress2, Component2, nextProps, renderLanes2) {
      if (null !== current22) {
        var prevProps = current22.memoizedProps;
        if (shallowEqual(prevProps, nextProps) && current22.ref === workInProgress2.ref && workInProgress2.type === current22.type)
          if (didReceiveUpdate = false, workInProgress2.pendingProps = nextProps = prevProps, checkScheduledUpdateOrContext(current22, renderLanes2))
            0 !== (current22.flags & 131072) && (didReceiveUpdate = true);
          else
            return workInProgress2.lanes = current22.lanes, bailoutOnAlreadyFinishedWork(current22, workInProgress2, renderLanes2);
      }
      return updateFunctionComponent(
        current22,
        workInProgress2,
        Component2,
        nextProps,
        renderLanes2
      );
    }
    function updateOffscreenComponent(current22, workInProgress2, renderLanes2, nextProps) {
      var nextChildren = nextProps.children, prevState = null !== current22 ? current22.memoizedState : null;
      null === current22 && null === workInProgress2.stateNode && (workInProgress2.stateNode = {
        _visibility: OffscreenVisible,
        _pendingMarkers: null,
        _retryCache: null,
        _transitions: null
      });
      if ("hidden" === nextProps.mode) {
        if (0 !== (workInProgress2.flags & 128)) {
          prevState = null !== prevState ? prevState.baseLanes | renderLanes2 : renderLanes2;
          if (null !== current22) {
            nextProps = workInProgress2.child = current22.child;
            for (nextChildren = 0; null !== nextProps; )
              nextChildren = nextChildren | nextProps.lanes | nextProps.childLanes, nextProps = nextProps.sibling;
            nextProps = nextChildren & ~prevState;
          } else nextProps = 0, workInProgress2.child = null;
          return deferHiddenOffscreenComponent(
            current22,
            workInProgress2,
            prevState,
            renderLanes2,
            nextProps
          );
        }
        if (0 !== (renderLanes2 & 536870912))
          workInProgress2.memoizedState = { baseLanes: 0, cachePool: null }, null !== current22 && pushTransition(
            workInProgress2,
            null !== prevState ? prevState.cachePool : null
          ), null !== prevState ? pushHiddenContext(workInProgress2, prevState) : reuseHiddenContextOnStack(workInProgress2), pushOffscreenSuspenseHandler(workInProgress2);
        else
          return nextProps = workInProgress2.lanes = 536870912, deferHiddenOffscreenComponent(
            current22,
            workInProgress2,
            null !== prevState ? prevState.baseLanes | renderLanes2 : renderLanes2,
            renderLanes2,
            nextProps
          );
      } else
        null !== prevState ? (pushTransition(workInProgress2, prevState.cachePool), pushHiddenContext(workInProgress2, prevState), reuseSuspenseHandlerOnStack(workInProgress2), workInProgress2.memoizedState = null) : (null !== current22 && pushTransition(workInProgress2, null), reuseHiddenContextOnStack(workInProgress2), reuseSuspenseHandlerOnStack(workInProgress2));
      reconcileChildren(current22, workInProgress2, nextChildren, renderLanes2);
      return workInProgress2.child;
    }
    function bailoutOffscreenComponent(current22, workInProgress2) {
      null !== current22 && 22 === current22.tag || null !== workInProgress2.stateNode || (workInProgress2.stateNode = {
        _visibility: OffscreenVisible,
        _pendingMarkers: null,
        _retryCache: null,
        _transitions: null
      });
      return workInProgress2.sibling;
    }
    function deferHiddenOffscreenComponent(current22, workInProgress2, nextBaseLanes, renderLanes2, remainingChildLanes) {
      var JSCompiler_inline_result = peekCacheFromPool();
      JSCompiler_inline_result = null === JSCompiler_inline_result ? null : {
        parent: CacheContext._currentValue,
        pool: JSCompiler_inline_result
      };
      workInProgress2.memoizedState = {
        baseLanes: nextBaseLanes,
        cachePool: JSCompiler_inline_result
      };
      null !== current22 && pushTransition(workInProgress2, null);
      reuseHiddenContextOnStack(workInProgress2);
      pushOffscreenSuspenseHandler(workInProgress2);
      null !== current22 && propagateParentContextChanges(current22, workInProgress2, renderLanes2, true);
      workInProgress2.childLanes = remainingChildLanes;
      return null;
    }
    function mountActivityChildren(workInProgress2, nextProps) {
      var hiddenProp = nextProps.hidden;
      void 0 !== hiddenProp && console.error(
        `<Activity> doesn't accept a hidden prop. Use mode="hidden" instead.
- <Activity %s>
+ <Activity %s>`,
        true === hiddenProp ? "hidden" : false === hiddenProp ? "hidden={false}" : "hidden={...}",
        hiddenProp ? 'mode="hidden"' : 'mode="visible"'
      );
      nextProps = mountWorkInProgressOffscreenFiber(
        { mode: nextProps.mode, children: nextProps.children },
        workInProgress2.mode
      );
      nextProps.ref = workInProgress2.ref;
      workInProgress2.child = nextProps;
      nextProps.return = workInProgress2;
      return nextProps;
    }
    function retryActivityComponentWithoutHydrating(current22, workInProgress2, renderLanes2) {
      reconcileChildFibers(workInProgress2, current22.child, null, renderLanes2);
      current22 = mountActivityChildren(
        workInProgress2,
        workInProgress2.pendingProps
      );
      current22.flags |= 2;
      popSuspenseHandler(workInProgress2);
      workInProgress2.memoizedState = null;
      return current22;
    }
    function updateActivityComponent(current22, workInProgress2, renderLanes2) {
      var nextProps = workInProgress2.pendingProps, didSuspend = 0 !== (workInProgress2.flags & 128);
      workInProgress2.flags &= -129;
      if (null === current22) {
        if (isHydrating) {
          if ("hidden" === nextProps.mode)
            return current22 = mountActivityChildren(workInProgress2, nextProps), workInProgress2.lanes = 536870912, bailoutOffscreenComponent(null, current22);
          pushDehydratedActivitySuspenseHandler(workInProgress2);
          (current22 = nextHydratableInstance) ? (renderLanes2 = canHydrateHydrationBoundary(
            current22,
            rootOrSingletonContext
          ), renderLanes2 = null !== renderLanes2 && renderLanes2.data === ACTIVITY_START_DATA ? renderLanes2 : null, null !== renderLanes2 && (nextProps = {
            dehydrated: renderLanes2,
            treeContext: getSuspendedTreeContext(),
            retryLane: 536870912,
            hydrationErrors: null
          }, workInProgress2.memoizedState = nextProps, nextProps = createFiberFromDehydratedFragment(renderLanes2), nextProps.return = workInProgress2, workInProgress2.child = nextProps, hydrationParentFiber = workInProgress2, nextHydratableInstance = null)) : renderLanes2 = null;
          if (null === renderLanes2)
            throw warnNonHydratedInstance(workInProgress2, current22), throwOnHydrationMismatch(workInProgress2);
          workInProgress2.lanes = 536870912;
          return null;
        }
        return mountActivityChildren(workInProgress2, nextProps);
      }
      var prevState = current22.memoizedState;
      if (null !== prevState) {
        var activityInstance = prevState.dehydrated;
        pushDehydratedActivitySuspenseHandler(workInProgress2);
        if (didSuspend)
          if (workInProgress2.flags & 256)
            workInProgress2.flags &= -257, workInProgress2 = retryActivityComponentWithoutHydrating(
              current22,
              workInProgress2,
              renderLanes2
            );
          else if (null !== workInProgress2.memoizedState)
            workInProgress2.child = current22.child, workInProgress2.flags |= 128, workInProgress2 = null;
          else
            throw Error(
              "Client rendering an Activity suspended it again. This is a bug in React."
            );
        else if (warnIfHydrating(), 0 !== (renderLanes2 & 536870912) && markRenderDerivedCause(workInProgress2), didReceiveUpdate || propagateParentContextChanges(
          current22,
          workInProgress2,
          renderLanes2,
          false
        ), didSuspend = 0 !== (renderLanes2 & current22.childLanes), didReceiveUpdate || didSuspend) {
          nextProps = workInProgressRoot;
          if (null !== nextProps && (activityInstance = getBumpedLaneForHydration(
            nextProps,
            renderLanes2
          ), 0 !== activityInstance && activityInstance !== prevState.retryLane))
            throw prevState.retryLane = activityInstance, enqueueConcurrentRenderForLane(current22, activityInstance), scheduleUpdateOnFiber(nextProps, current22, activityInstance), SelectiveHydrationException;
          renderDidSuspendDelayIfPossible();
          workInProgress2 = retryActivityComponentWithoutHydrating(
            current22,
            workInProgress2,
            renderLanes2
          );
        } else
          current22 = prevState.treeContext, nextHydratableInstance = getNextHydratable(
            activityInstance.nextSibling
          ), hydrationParentFiber = workInProgress2, isHydrating = true, hydrationErrors = null, didSuspendOrErrorDEV = false, hydrationDiffRootDEV = null, rootOrSingletonContext = false, null !== current22 && restoreSuspendedTreeContext(workInProgress2, current22), workInProgress2 = mountActivityChildren(workInProgress2, nextProps), workInProgress2.flags |= 4096;
        return workInProgress2;
      }
      prevState = current22.child;
      nextProps = { mode: nextProps.mode, children: nextProps.children };
      0 !== (renderLanes2 & 536870912) && 0 !== (renderLanes2 & current22.lanes) && markRenderDerivedCause(workInProgress2);
      current22 = createWorkInProgress(prevState, nextProps);
      current22.ref = workInProgress2.ref;
      workInProgress2.child = current22;
      current22.return = workInProgress2;
      return current22;
    }
    function markRef(current22, workInProgress2) {
      var ref2 = workInProgress2.ref;
      if (null === ref2)
        null !== current22 && null !== current22.ref && (workInProgress2.flags |= 4194816);
      else {
        if ("function" !== typeof ref2 && "object" !== typeof ref2)
          throw Error(
            "Expected ref to be a function, an object returned by React.createRef(), or undefined/null."
          );
        if (null === current22 || current22.ref !== ref2)
          workInProgress2.flags |= 4194816;
      }
    }
    function updateFunctionComponent(current22, workInProgress2, Component2, nextProps, renderLanes2) {
      if (Component2.prototype && "function" === typeof Component2.prototype.render) {
        var componentName2 = getComponentNameFromType(Component2) || "Unknown";
        didWarnAboutBadClass[componentName2] || (console.error(
          "The <%s /> component appears to have a render method, but doesn't extend React.Component. This is likely to cause errors. Change %s to extend React.Component instead.",
          componentName2,
          componentName2
        ), didWarnAboutBadClass[componentName2] = true);
      }
      workInProgress2.mode & StrictLegacyMode && ReactStrictModeWarnings.recordLegacyContextWarning(
        workInProgress2,
        null
      );
      null === current22 && (validateFunctionComponentInDev(workInProgress2, workInProgress2.type), Component2.contextTypes && (componentName2 = getComponentNameFromType(Component2) || "Unknown", didWarnAboutContextTypes[componentName2] || (didWarnAboutContextTypes[componentName2] = true, console.error(
        "%s uses the legacy contextTypes API which was removed in React 19. Use React.createContext() with React.useContext() instead. (https://react.dev/link/legacy-context)",
        componentName2
      ))));
      prepareToReadContext(workInProgress2);
      Component2 = renderWithHooks(
        current22,
        workInProgress2,
        Component2,
        nextProps,
        void 0,
        renderLanes2
      );
      nextProps = checkDidRenderIdHook();
      if (null !== current22 && !didReceiveUpdate)
        return bailoutHooks(current22, workInProgress2, renderLanes2), bailoutOnAlreadyFinishedWork(current22, workInProgress2, renderLanes2);
      isHydrating && nextProps && pushMaterializedTreeId(workInProgress2);
      workInProgress2.flags |= 1;
      reconcileChildren(current22, workInProgress2, Component2, renderLanes2);
      return workInProgress2.child;
    }
    function replayFunctionComponent(current22, workInProgress2, nextProps, Component2, secondArg, renderLanes2) {
      prepareToReadContext(workInProgress2);
      hookTypesUpdateIndexDev = -1;
      ignorePreviousDependencies = null !== current22 && current22.type !== workInProgress2.type;
      workInProgress2.updateQueue = null;
      nextProps = renderWithHooksAgain(
        workInProgress2,
        Component2,
        nextProps,
        secondArg
      );
      finishRenderingHooks(current22, workInProgress2);
      Component2 = checkDidRenderIdHook();
      if (null !== current22 && !didReceiveUpdate)
        return bailoutHooks(current22, workInProgress2, renderLanes2), bailoutOnAlreadyFinishedWork(current22, workInProgress2, renderLanes2);
      isHydrating && Component2 && pushMaterializedTreeId(workInProgress2);
      workInProgress2.flags |= 1;
      reconcileChildren(current22, workInProgress2, nextProps, renderLanes2);
      return workInProgress2.child;
    }
    function updateClassComponent(current22, workInProgress2, Component2, nextProps, renderLanes2) {
      switch (shouldErrorImpl(workInProgress2)) {
        case false:
          var _instance = workInProgress2.stateNode, state = new workInProgress2.type(
            workInProgress2.memoizedProps,
            _instance.context
          ).state;
          _instance.updater.enqueueSetState(_instance, state, null);
          break;
        case true:
          workInProgress2.flags |= 128;
          workInProgress2.flags |= 65536;
          _instance = Error("Simulated error coming from DevTools");
          var lane = renderLanes2 & -renderLanes2;
          workInProgress2.lanes |= lane;
          state = workInProgressRoot;
          if (null === state)
            throw Error(
              "Expected a work-in-progress root. This is a bug in React. Please file an issue."
            );
          lane = createClassErrorUpdate(lane);
          initializeClassErrorUpdate(
            lane,
            state,
            workInProgress2,
            createCapturedValueAtFiber(_instance, workInProgress2)
          );
          enqueueCapturedUpdate(workInProgress2, lane);
      }
      prepareToReadContext(workInProgress2);
      if (null === workInProgress2.stateNode) {
        state = emptyContextObject;
        _instance = Component2.contextType;
        "contextType" in Component2 && null !== _instance && (void 0 === _instance || _instance.$$typeof !== REACT_CONTEXT_TYPE) && !didWarnAboutInvalidateContextType.has(Component2) && (didWarnAboutInvalidateContextType.add(Component2), lane = void 0 === _instance ? " However, it is set to undefined. This can be caused by a typo or by mixing up named and default imports. This can also happen due to a circular dependency, so try moving the createContext() call to a separate file." : "object" !== typeof _instance ? " However, it is set to a " + typeof _instance + "." : _instance.$$typeof === REACT_CONSUMER_TYPE ? " Did you accidentally pass the Context.Consumer instead?" : " However, it is set to an object with keys {" + Object.keys(_instance).join(", ") + "}.", console.error(
          "%s defines an invalid contextType. contextType should point to the Context object returned by React.createContext().%s",
          getComponentNameFromType(Component2) || "Component",
          lane
        ));
        "object" === typeof _instance && null !== _instance && (state = readContext(_instance));
        _instance = new Component2(nextProps, state);
        if (workInProgress2.mode & StrictLegacyMode) {
          setIsStrictModeForDevtools(true);
          try {
            _instance = new Component2(nextProps, state);
          } finally {
            setIsStrictModeForDevtools(false);
          }
        }
        state = workInProgress2.memoizedState = null !== _instance.state && void 0 !== _instance.state ? _instance.state : null;
        _instance.updater = classComponentUpdater;
        workInProgress2.stateNode = _instance;
        _instance._reactInternals = workInProgress2;
        _instance._reactInternalInstance = fakeInternalInstance;
        "function" === typeof Component2.getDerivedStateFromProps && null === state && (state = getComponentNameFromType(Component2) || "Component", didWarnAboutUninitializedState.has(state) || (didWarnAboutUninitializedState.add(state), console.error(
          "`%s` uses `getDerivedStateFromProps` but its initial state is %s. This is not recommended. Instead, define the initial state by assigning an object to `this.state` in the constructor of `%s`. This ensures that `getDerivedStateFromProps` arguments have a consistent shape.",
          state,
          null === _instance.state ? "null" : "undefined",
          state
        )));
        if ("function" === typeof Component2.getDerivedStateFromProps || "function" === typeof _instance.getSnapshotBeforeUpdate) {
          var foundWillUpdateName = lane = state = null;
          "function" === typeof _instance.componentWillMount && true !== _instance.componentWillMount.__suppressDeprecationWarning ? state = "componentWillMount" : "function" === typeof _instance.UNSAFE_componentWillMount && (state = "UNSAFE_componentWillMount");
          "function" === typeof _instance.componentWillReceiveProps && true !== _instance.componentWillReceiveProps.__suppressDeprecationWarning ? lane = "componentWillReceiveProps" : "function" === typeof _instance.UNSAFE_componentWillReceiveProps && (lane = "UNSAFE_componentWillReceiveProps");
          "function" === typeof _instance.componentWillUpdate && true !== _instance.componentWillUpdate.__suppressDeprecationWarning ? foundWillUpdateName = "componentWillUpdate" : "function" === typeof _instance.UNSAFE_componentWillUpdate && (foundWillUpdateName = "UNSAFE_componentWillUpdate");
          if (null !== state || null !== lane || null !== foundWillUpdateName) {
            _instance = getComponentNameFromType(Component2) || "Component";
            var newApiName = "function" === typeof Component2.getDerivedStateFromProps ? "getDerivedStateFromProps()" : "getSnapshotBeforeUpdate()";
            didWarnAboutLegacyLifecyclesAndDerivedState.has(_instance) || (didWarnAboutLegacyLifecyclesAndDerivedState.add(_instance), console.error(
              "Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\nThe above lifecycles should be removed. Learn more about this warning here:\nhttps://react.dev/link/unsafe-component-lifecycles",
              _instance,
              newApiName,
              null !== state ? "\n  " + state : "",
              null !== lane ? "\n  " + lane : "",
              null !== foundWillUpdateName ? "\n  " + foundWillUpdateName : ""
            ));
          }
        }
        _instance = workInProgress2.stateNode;
        state = getComponentNameFromType(Component2) || "Component";
        _instance.render || (Component2.prototype && "function" === typeof Component2.prototype.render ? console.error(
          "No `render` method found on the %s instance: did you accidentally return an object from the constructor?",
          state
        ) : console.error(
          "No `render` method found on the %s instance: you may have forgotten to define `render`.",
          state
        ));
        !_instance.getInitialState || _instance.getInitialState.isReactClassApproved || _instance.state || console.error(
          "getInitialState was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?",
          state
        );
        _instance.getDefaultProps && !_instance.getDefaultProps.isReactClassApproved && console.error(
          "getDefaultProps was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Use a static property to define defaultProps instead.",
          state
        );
        _instance.contextType && console.error(
          "contextType was defined as an instance property on %s. Use a static property to define contextType instead.",
          state
        );
        Component2.childContextTypes && !didWarnAboutChildContextTypes.has(Component2) && (didWarnAboutChildContextTypes.add(Component2), console.error(
          "%s uses the legacy childContextTypes API which was removed in React 19. Use React.createContext() instead. (https://react.dev/link/legacy-context)",
          state
        ));
        Component2.contextTypes && !didWarnAboutContextTypes$1.has(Component2) && (didWarnAboutContextTypes$1.add(Component2), console.error(
          "%s uses the legacy contextTypes API which was removed in React 19. Use React.createContext() with static contextType instead. (https://react.dev/link/legacy-context)",
          state
        ));
        "function" === typeof _instance.componentShouldUpdate && console.error(
          "%s has a method called componentShouldUpdate(). Did you mean shouldComponentUpdate()? The name is phrased as a question because the function is expected to return a value.",
          state
        );
        Component2.prototype && Component2.prototype.isPureReactComponent && "undefined" !== typeof _instance.shouldComponentUpdate && console.error(
          "%s has a method called shouldComponentUpdate(). shouldComponentUpdate should not be used when extending React.PureComponent. Please extend React.Component if shouldComponentUpdate is used.",
          getComponentNameFromType(Component2) || "A pure component"
        );
        "function" === typeof _instance.componentDidUnmount && console.error(
          "%s has a method called componentDidUnmount(). But there is no such lifecycle method. Did you mean componentWillUnmount()?",
          state
        );
        "function" === typeof _instance.componentDidReceiveProps && console.error(
          "%s has a method called componentDidReceiveProps(). But there is no such lifecycle method. If you meant to update the state in response to changing props, use componentWillReceiveProps(). If you meant to fetch data or run side-effects or mutations after React has updated the UI, use componentDidUpdate().",
          state
        );
        "function" === typeof _instance.componentWillRecieveProps && console.error(
          "%s has a method called componentWillRecieveProps(). Did you mean componentWillReceiveProps()?",
          state
        );
        "function" === typeof _instance.UNSAFE_componentWillRecieveProps && console.error(
          "%s has a method called UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?",
          state
        );
        lane = _instance.props !== nextProps;
        void 0 !== _instance.props && lane && console.error(
          "When calling super() in `%s`, make sure to pass up the same props that your component's constructor was passed.",
          state
        );
        _instance.defaultProps && console.error(
          "Setting defaultProps as an instance property on %s is not supported and will be ignored. Instead, define defaultProps as a static property on %s.",
          state,
          state
        );
        "function" !== typeof _instance.getSnapshotBeforeUpdate || "function" === typeof _instance.componentDidUpdate || didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(Component2) || (didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(Component2), console.error(
          "%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). This component defines getSnapshotBeforeUpdate() only.",
          getComponentNameFromType(Component2)
        ));
        "function" === typeof _instance.getDerivedStateFromProps && console.error(
          "%s: getDerivedStateFromProps() is defined as an instance method and will be ignored. Instead, declare it as a static method.",
          state
        );
        "function" === typeof _instance.getDerivedStateFromError && console.error(
          "%s: getDerivedStateFromError() is defined as an instance method and will be ignored. Instead, declare it as a static method.",
          state
        );
        "function" === typeof Component2.getSnapshotBeforeUpdate && console.error(
          "%s: getSnapshotBeforeUpdate() is defined as a static method and will be ignored. Instead, declare it as an instance method.",
          state
        );
        (lane = _instance.state) && ("object" !== typeof lane || isArrayImpl(lane)) && console.error("%s.state: must be set to an object or null", state);
        "function" === typeof _instance.getChildContext && "object" !== typeof Component2.childContextTypes && console.error(
          "%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().",
          state
        );
        _instance = workInProgress2.stateNode;
        _instance.props = nextProps;
        _instance.state = workInProgress2.memoizedState;
        _instance.refs = {};
        initializeUpdateQueue(workInProgress2);
        state = Component2.contextType;
        _instance.context = "object" === typeof state && null !== state ? readContext(state) : emptyContextObject;
        _instance.state === nextProps && (state = getComponentNameFromType(Component2) || "Component", didWarnAboutDirectlyAssigningPropsToState.has(state) || (didWarnAboutDirectlyAssigningPropsToState.add(state), console.error(
          "%s: It is not recommended to assign props directly to state because updates to props won't be reflected in state. In most cases, it is better to use props directly.",
          state
        )));
        workInProgress2.mode & StrictLegacyMode && ReactStrictModeWarnings.recordLegacyContextWarning(
          workInProgress2,
          _instance
        );
        ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(
          workInProgress2,
          _instance
        );
        _instance.state = workInProgress2.memoizedState;
        state = Component2.getDerivedStateFromProps;
        "function" === typeof state && (applyDerivedStateFromProps(
          workInProgress2,
          Component2,
          state,
          nextProps
        ), _instance.state = workInProgress2.memoizedState);
        "function" === typeof Component2.getDerivedStateFromProps || "function" === typeof _instance.getSnapshotBeforeUpdate || "function" !== typeof _instance.UNSAFE_componentWillMount && "function" !== typeof _instance.componentWillMount || (state = _instance.state, "function" === typeof _instance.componentWillMount && _instance.componentWillMount(), "function" === typeof _instance.UNSAFE_componentWillMount && _instance.UNSAFE_componentWillMount(), state !== _instance.state && (console.error(
          "%s.componentWillMount(): Assigning directly to this.state is deprecated (except inside a component's constructor). Use setState instead.",
          getComponentNameFromFiber(workInProgress2) || "Component"
        ), classComponentUpdater.enqueueReplaceState(
          _instance,
          _instance.state,
          null
        )), processUpdateQueue(workInProgress2, nextProps, _instance, renderLanes2), suspendIfUpdateReadFromEntangledAsyncAction(), _instance.state = workInProgress2.memoizedState);
        "function" === typeof _instance.componentDidMount && (workInProgress2.flags |= 4194308);
        (workInProgress2.mode & StrictEffectsMode) !== NoMode && (workInProgress2.flags |= 134217728);
        _instance = true;
      } else if (null === current22) {
        _instance = workInProgress2.stateNode;
        var unresolvedOldProps = workInProgress2.memoizedProps;
        lane = resolveClassComponentProps(Component2, unresolvedOldProps);
        _instance.props = lane;
        var oldContext = _instance.context;
        foundWillUpdateName = Component2.contextType;
        state = emptyContextObject;
        "object" === typeof foundWillUpdateName && null !== foundWillUpdateName && (state = readContext(foundWillUpdateName));
        newApiName = Component2.getDerivedStateFromProps;
        foundWillUpdateName = "function" === typeof newApiName || "function" === typeof _instance.getSnapshotBeforeUpdate;
        unresolvedOldProps = workInProgress2.pendingProps !== unresolvedOldProps;
        foundWillUpdateName || "function" !== typeof _instance.UNSAFE_componentWillReceiveProps && "function" !== typeof _instance.componentWillReceiveProps || (unresolvedOldProps || oldContext !== state) && callComponentWillReceiveProps(
          workInProgress2,
          _instance,
          nextProps,
          state
        );
        hasForceUpdate = false;
        var oldState = workInProgress2.memoizedState;
        _instance.state = oldState;
        processUpdateQueue(workInProgress2, nextProps, _instance, renderLanes2);
        suspendIfUpdateReadFromEntangledAsyncAction();
        oldContext = workInProgress2.memoizedState;
        unresolvedOldProps || oldState !== oldContext || hasForceUpdate ? ("function" === typeof newApiName && (applyDerivedStateFromProps(
          workInProgress2,
          Component2,
          newApiName,
          nextProps
        ), oldContext = workInProgress2.memoizedState), (lane = hasForceUpdate || checkShouldComponentUpdate(
          workInProgress2,
          Component2,
          lane,
          nextProps,
          oldState,
          oldContext,
          state
        )) ? (foundWillUpdateName || "function" !== typeof _instance.UNSAFE_componentWillMount && "function" !== typeof _instance.componentWillMount || ("function" === typeof _instance.componentWillMount && _instance.componentWillMount(), "function" === typeof _instance.UNSAFE_componentWillMount && _instance.UNSAFE_componentWillMount()), "function" === typeof _instance.componentDidMount && (workInProgress2.flags |= 4194308), (workInProgress2.mode & StrictEffectsMode) !== NoMode && (workInProgress2.flags |= 134217728)) : ("function" === typeof _instance.componentDidMount && (workInProgress2.flags |= 4194308), (workInProgress2.mode & StrictEffectsMode) !== NoMode && (workInProgress2.flags |= 134217728), workInProgress2.memoizedProps = nextProps, workInProgress2.memoizedState = oldContext), _instance.props = nextProps, _instance.state = oldContext, _instance.context = state, _instance = lane) : ("function" === typeof _instance.componentDidMount && (workInProgress2.flags |= 4194308), (workInProgress2.mode & StrictEffectsMode) !== NoMode && (workInProgress2.flags |= 134217728), _instance = false);
      } else {
        _instance = workInProgress2.stateNode;
        cloneUpdateQueue(current22, workInProgress2);
        state = workInProgress2.memoizedProps;
        foundWillUpdateName = resolveClassComponentProps(Component2, state);
        _instance.props = foundWillUpdateName;
        newApiName = workInProgress2.pendingProps;
        oldState = _instance.context;
        oldContext = Component2.contextType;
        lane = emptyContextObject;
        "object" === typeof oldContext && null !== oldContext && (lane = readContext(oldContext));
        unresolvedOldProps = Component2.getDerivedStateFromProps;
        (oldContext = "function" === typeof unresolvedOldProps || "function" === typeof _instance.getSnapshotBeforeUpdate) || "function" !== typeof _instance.UNSAFE_componentWillReceiveProps && "function" !== typeof _instance.componentWillReceiveProps || (state !== newApiName || oldState !== lane) && callComponentWillReceiveProps(
          workInProgress2,
          _instance,
          nextProps,
          lane
        );
        hasForceUpdate = false;
        oldState = workInProgress2.memoizedState;
        _instance.state = oldState;
        processUpdateQueue(workInProgress2, nextProps, _instance, renderLanes2);
        suspendIfUpdateReadFromEntangledAsyncAction();
        var newState = workInProgress2.memoizedState;
        state !== newApiName || oldState !== newState || hasForceUpdate || null !== current22 && null !== current22.dependencies && checkIfContextChanged(current22.dependencies) ? ("function" === typeof unresolvedOldProps && (applyDerivedStateFromProps(
          workInProgress2,
          Component2,
          unresolvedOldProps,
          nextProps
        ), newState = workInProgress2.memoizedState), (foundWillUpdateName = hasForceUpdate || checkShouldComponentUpdate(
          workInProgress2,
          Component2,
          foundWillUpdateName,
          nextProps,
          oldState,
          newState,
          lane
        ) || null !== current22 && null !== current22.dependencies && checkIfContextChanged(current22.dependencies)) ? (oldContext || "function" !== typeof _instance.UNSAFE_componentWillUpdate && "function" !== typeof _instance.componentWillUpdate || ("function" === typeof _instance.componentWillUpdate && _instance.componentWillUpdate(nextProps, newState, lane), "function" === typeof _instance.UNSAFE_componentWillUpdate && _instance.UNSAFE_componentWillUpdate(
          nextProps,
          newState,
          lane
        )), "function" === typeof _instance.componentDidUpdate && (workInProgress2.flags |= 4), "function" === typeof _instance.getSnapshotBeforeUpdate && (workInProgress2.flags |= 1024)) : ("function" !== typeof _instance.componentDidUpdate || state === current22.memoizedProps && oldState === current22.memoizedState || (workInProgress2.flags |= 4), "function" !== typeof _instance.getSnapshotBeforeUpdate || state === current22.memoizedProps && oldState === current22.memoizedState || (workInProgress2.flags |= 1024), workInProgress2.memoizedProps = nextProps, workInProgress2.memoizedState = newState), _instance.props = nextProps, _instance.state = newState, _instance.context = lane, _instance = foundWillUpdateName) : ("function" !== typeof _instance.componentDidUpdate || state === current22.memoizedProps && oldState === current22.memoizedState || (workInProgress2.flags |= 4), "function" !== typeof _instance.getSnapshotBeforeUpdate || state === current22.memoizedProps && oldState === current22.memoizedState || (workInProgress2.flags |= 1024), _instance = false);
      }
      lane = _instance;
      markRef(current22, workInProgress2);
      state = 0 !== (workInProgress2.flags & 128);
      if (lane || state) {
        lane = workInProgress2.stateNode;
        setCurrentFiber(workInProgress2);
        if (state && "function" !== typeof Component2.getDerivedStateFromError)
          Component2 = null, profilerStartTime = -1;
        else if (Component2 = callRenderInDEV(lane), workInProgress2.mode & StrictLegacyMode) {
          setIsStrictModeForDevtools(true);
          try {
            callRenderInDEV(lane);
          } finally {
            setIsStrictModeForDevtools(false);
          }
        }
        workInProgress2.flags |= 1;
        null !== current22 && state ? (workInProgress2.child = reconcileChildFibers(
          workInProgress2,
          current22.child,
          null,
          renderLanes2
        ), workInProgress2.child = reconcileChildFibers(
          workInProgress2,
          null,
          Component2,
          renderLanes2
        )) : reconcileChildren(current22, workInProgress2, Component2, renderLanes2);
        workInProgress2.memoizedState = lane.state;
        current22 = workInProgress2.child;
      } else
        current22 = bailoutOnAlreadyFinishedWork(
          current22,
          workInProgress2,
          renderLanes2
        );
      renderLanes2 = workInProgress2.stateNode;
      _instance && renderLanes2.props !== nextProps && (didWarnAboutReassigningProps || console.error(
        "It looks like %s is reassigning its own `this.props` while rendering. This is not supported and can lead to confusing bugs.",
        getComponentNameFromFiber(workInProgress2) || "a component"
      ), didWarnAboutReassigningProps = true);
      return current22;
    }
    function mountHostRootWithoutHydrating(current22, workInProgress2, nextChildren, renderLanes2) {
      resetHydrationState();
      workInProgress2.flags |= 256;
      reconcileChildren(current22, workInProgress2, nextChildren, renderLanes2);
      return workInProgress2.child;
    }
    function validateFunctionComponentInDev(workInProgress2, Component2) {
      Component2 && Component2.childContextTypes && console.error(
        "childContextTypes cannot be defined on a function component.\n  %s.childContextTypes = ...",
        Component2.displayName || Component2.name || "Component"
      );
      "function" === typeof Component2.getDerivedStateFromProps && (workInProgress2 = getComponentNameFromType(Component2) || "Unknown", didWarnAboutGetDerivedStateOnFunctionComponent[workInProgress2] || (console.error(
        "%s: Function components do not support getDerivedStateFromProps.",
        workInProgress2
      ), didWarnAboutGetDerivedStateOnFunctionComponent[workInProgress2] = true));
      "object" === typeof Component2.contextType && null !== Component2.contextType && (Component2 = getComponentNameFromType(Component2) || "Unknown", didWarnAboutContextTypeOnFunctionComponent[Component2] || (console.error(
        "%s: Function components do not support contextType.",
        Component2
      ), didWarnAboutContextTypeOnFunctionComponent[Component2] = true));
    }
    function mountSuspenseOffscreenState(renderLanes2) {
      return { baseLanes: renderLanes2, cachePool: getSuspendedCache() };
    }
    function getRemainingWorkInPrimaryTree(current22, primaryTreeDidDefer, renderLanes2) {
      current22 = null !== current22 ? current22.childLanes & ~renderLanes2 : 0;
      primaryTreeDidDefer && (current22 |= workInProgressDeferredLane);
      return current22;
    }
    function updateSuspenseComponent(current22, workInProgress2, renderLanes2) {
      var JSCompiler_object_inline_digest_2724;
      var JSCompiler_object_inline_stack_2725 = workInProgress2.pendingProps;
      shouldSuspendImpl(workInProgress2) && (workInProgress2.flags |= 128);
      var JSCompiler_object_inline_message_2723 = false;
      var didSuspend = 0 !== (workInProgress2.flags & 128);
      (JSCompiler_object_inline_digest_2724 = didSuspend) || (JSCompiler_object_inline_digest_2724 = null !== current22 && null === current22.memoizedState ? false : 0 !== (suspenseStackCursor.current & ForceSuspenseFallback));
      JSCompiler_object_inline_digest_2724 && (JSCompiler_object_inline_message_2723 = true, workInProgress2.flags &= -129);
      JSCompiler_object_inline_digest_2724 = 0 !== (workInProgress2.flags & 32);
      workInProgress2.flags &= -33;
      if (null === current22) {
        if (isHydrating) {
          JSCompiler_object_inline_message_2723 ? pushPrimaryTreeSuspenseHandler(workInProgress2) : reuseSuspenseHandlerOnStack(workInProgress2);
          (current22 = nextHydratableInstance) ? (renderLanes2 = canHydrateHydrationBoundary(
            current22,
            rootOrSingletonContext
          ), renderLanes2 = null !== renderLanes2 && renderLanes2.data !== ACTIVITY_START_DATA ? renderLanes2 : null, null !== renderLanes2 && (JSCompiler_object_inline_digest_2724 = {
            dehydrated: renderLanes2,
            treeContext: getSuspendedTreeContext(),
            retryLane: 536870912,
            hydrationErrors: null
          }, workInProgress2.memoizedState = JSCompiler_object_inline_digest_2724, JSCompiler_object_inline_digest_2724 = createFiberFromDehydratedFragment(renderLanes2), JSCompiler_object_inline_digest_2724.return = workInProgress2, workInProgress2.child = JSCompiler_object_inline_digest_2724, hydrationParentFiber = workInProgress2, nextHydratableInstance = null)) : renderLanes2 = null;
          if (null === renderLanes2)
            throw warnNonHydratedInstance(workInProgress2, current22), throwOnHydrationMismatch(workInProgress2);
          isSuspenseInstanceFallback(renderLanes2) ? workInProgress2.lanes = 32 : workInProgress2.lanes = 536870912;
          return null;
        }
        var nextPrimaryChildren = JSCompiler_object_inline_stack_2725.children;
        JSCompiler_object_inline_stack_2725 = JSCompiler_object_inline_stack_2725.fallback;
        if (JSCompiler_object_inline_message_2723) {
          reuseSuspenseHandlerOnStack(workInProgress2);
          var mode = workInProgress2.mode;
          nextPrimaryChildren = mountWorkInProgressOffscreenFiber(
            { mode: "hidden", children: nextPrimaryChildren },
            mode
          );
          JSCompiler_object_inline_stack_2725 = createFiberFromFragment(
            JSCompiler_object_inline_stack_2725,
            mode,
            renderLanes2,
            null
          );
          nextPrimaryChildren.return = workInProgress2;
          JSCompiler_object_inline_stack_2725.return = workInProgress2;
          nextPrimaryChildren.sibling = JSCompiler_object_inline_stack_2725;
          workInProgress2.child = nextPrimaryChildren;
          JSCompiler_object_inline_stack_2725 = workInProgress2.child;
          JSCompiler_object_inline_stack_2725.memoizedState = mountSuspenseOffscreenState(renderLanes2);
          JSCompiler_object_inline_stack_2725.childLanes = getRemainingWorkInPrimaryTree(
            current22,
            JSCompiler_object_inline_digest_2724,
            renderLanes2
          );
          workInProgress2.memoizedState = SUSPENDED_MARKER;
          return bailoutOffscreenComponent(
            null,
            JSCompiler_object_inline_stack_2725
          );
        }
        pushPrimaryTreeSuspenseHandler(workInProgress2);
        return mountSuspensePrimaryChildren(
          workInProgress2,
          nextPrimaryChildren
        );
      }
      var prevState = current22.memoizedState;
      if (null !== prevState) {
        var JSCompiler_object_inline_componentStack_2726 = prevState.dehydrated;
        if (null !== JSCompiler_object_inline_componentStack_2726) {
          if (didSuspend)
            workInProgress2.flags & 256 ? (pushPrimaryTreeSuspenseHandler(workInProgress2), workInProgress2.flags &= -257, workInProgress2 = retrySuspenseComponentWithoutHydrating(
              current22,
              workInProgress2,
              renderLanes2
            )) : null !== workInProgress2.memoizedState ? (reuseSuspenseHandlerOnStack(workInProgress2), workInProgress2.child = current22.child, workInProgress2.flags |= 128, workInProgress2 = null) : (reuseSuspenseHandlerOnStack(workInProgress2), nextPrimaryChildren = JSCompiler_object_inline_stack_2725.fallback, mode = workInProgress2.mode, JSCompiler_object_inline_stack_2725 = mountWorkInProgressOffscreenFiber(
              {
                mode: "visible",
                children: JSCompiler_object_inline_stack_2725.children
              },
              mode
            ), nextPrimaryChildren = createFiberFromFragment(
              nextPrimaryChildren,
              mode,
              renderLanes2,
              null
            ), nextPrimaryChildren.flags |= 2, JSCompiler_object_inline_stack_2725.return = workInProgress2, nextPrimaryChildren.return = workInProgress2, JSCompiler_object_inline_stack_2725.sibling = nextPrimaryChildren, workInProgress2.child = JSCompiler_object_inline_stack_2725, reconcileChildFibers(
              workInProgress2,
              current22.child,
              null,
              renderLanes2
            ), JSCompiler_object_inline_stack_2725 = workInProgress2.child, JSCompiler_object_inline_stack_2725.memoizedState = mountSuspenseOffscreenState(renderLanes2), JSCompiler_object_inline_stack_2725.childLanes = getRemainingWorkInPrimaryTree(
              current22,
              JSCompiler_object_inline_digest_2724,
              renderLanes2
            ), workInProgress2.memoizedState = SUSPENDED_MARKER, workInProgress2 = bailoutOffscreenComponent(
              null,
              JSCompiler_object_inline_stack_2725
            ));
          else if (pushPrimaryTreeSuspenseHandler(workInProgress2), warnIfHydrating(), 0 !== (renderLanes2 & 536870912) && markRenderDerivedCause(workInProgress2), isSuspenseInstanceFallback(
            JSCompiler_object_inline_componentStack_2726
          )) {
            JSCompiler_object_inline_digest_2724 = JSCompiler_object_inline_componentStack_2726.nextSibling && JSCompiler_object_inline_componentStack_2726.nextSibling.dataset;
            if (JSCompiler_object_inline_digest_2724) {
              nextPrimaryChildren = JSCompiler_object_inline_digest_2724.dgst;
              var message2 = JSCompiler_object_inline_digest_2724.msg;
              mode = JSCompiler_object_inline_digest_2724.stck;
              var componentStack = JSCompiler_object_inline_digest_2724.cstck;
            }
            JSCompiler_object_inline_message_2723 = message2;
            JSCompiler_object_inline_digest_2724 = nextPrimaryChildren;
            JSCompiler_object_inline_stack_2725 = mode;
            JSCompiler_object_inline_componentStack_2726 = componentStack;
            nextPrimaryChildren = JSCompiler_object_inline_message_2723;
            mode = JSCompiler_object_inline_componentStack_2726;
            nextPrimaryChildren = nextPrimaryChildren ? Error(nextPrimaryChildren) : Error(
              "The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering."
            );
            nextPrimaryChildren.stack = JSCompiler_object_inline_stack_2725 || "";
            nextPrimaryChildren.digest = JSCompiler_object_inline_digest_2724;
            JSCompiler_object_inline_digest_2724 = void 0 === mode ? null : mode;
            JSCompiler_object_inline_stack_2725 = {
              value: nextPrimaryChildren,
              source: null,
              stack: JSCompiler_object_inline_digest_2724
            };
            "string" === typeof JSCompiler_object_inline_digest_2724 && CapturedStacks.set(
              nextPrimaryChildren,
              JSCompiler_object_inline_stack_2725
            );
            queueHydrationError(JSCompiler_object_inline_stack_2725);
            workInProgress2 = retrySuspenseComponentWithoutHydrating(
              current22,
              workInProgress2,
              renderLanes2
            );
          } else if (didReceiveUpdate || propagateParentContextChanges(
            current22,
            workInProgress2,
            renderLanes2,
            false
          ), JSCompiler_object_inline_digest_2724 = 0 !== (renderLanes2 & current22.childLanes), didReceiveUpdate || JSCompiler_object_inline_digest_2724) {
            JSCompiler_object_inline_digest_2724 = workInProgressRoot;
            if (null !== JSCompiler_object_inline_digest_2724 && (JSCompiler_object_inline_stack_2725 = getBumpedLaneForHydration(
              JSCompiler_object_inline_digest_2724,
              renderLanes2
            ), 0 !== JSCompiler_object_inline_stack_2725 && JSCompiler_object_inline_stack_2725 !== prevState.retryLane))
              throw prevState.retryLane = JSCompiler_object_inline_stack_2725, enqueueConcurrentRenderForLane(
                current22,
                JSCompiler_object_inline_stack_2725
              ), scheduleUpdateOnFiber(
                JSCompiler_object_inline_digest_2724,
                current22,
                JSCompiler_object_inline_stack_2725
              ), SelectiveHydrationException;
            isSuspenseInstancePending(
              JSCompiler_object_inline_componentStack_2726
            ) || renderDidSuspendDelayIfPossible();
            workInProgress2 = retrySuspenseComponentWithoutHydrating(
              current22,
              workInProgress2,
              renderLanes2
            );
          } else
            isSuspenseInstancePending(
              JSCompiler_object_inline_componentStack_2726
            ) ? (workInProgress2.flags |= 192, workInProgress2.child = current22.child, workInProgress2 = null) : (current22 = prevState.treeContext, nextHydratableInstance = getNextHydratable(
              JSCompiler_object_inline_componentStack_2726.nextSibling
            ), hydrationParentFiber = workInProgress2, isHydrating = true, hydrationErrors = null, didSuspendOrErrorDEV = false, hydrationDiffRootDEV = null, rootOrSingletonContext = false, null !== current22 && restoreSuspendedTreeContext(workInProgress2, current22), workInProgress2 = mountSuspensePrimaryChildren(
              workInProgress2,
              JSCompiler_object_inline_stack_2725.children
            ), workInProgress2.flags |= 4096);
          return workInProgress2;
        }
      }
      if (JSCompiler_object_inline_message_2723)
        return reuseSuspenseHandlerOnStack(workInProgress2), nextPrimaryChildren = JSCompiler_object_inline_stack_2725.fallback, mode = workInProgress2.mode, componentStack = current22.child, JSCompiler_object_inline_componentStack_2726 = componentStack.sibling, JSCompiler_object_inline_stack_2725 = createWorkInProgress(
          componentStack,
          {
            mode: "hidden",
            children: JSCompiler_object_inline_stack_2725.children
          }
        ), JSCompiler_object_inline_stack_2725.subtreeFlags = componentStack.subtreeFlags & 65011712, null !== JSCompiler_object_inline_componentStack_2726 ? nextPrimaryChildren = createWorkInProgress(
          JSCompiler_object_inline_componentStack_2726,
          nextPrimaryChildren
        ) : (nextPrimaryChildren = createFiberFromFragment(
          nextPrimaryChildren,
          mode,
          renderLanes2,
          null
        ), nextPrimaryChildren.flags |= 2), nextPrimaryChildren.return = workInProgress2, JSCompiler_object_inline_stack_2725.return = workInProgress2, JSCompiler_object_inline_stack_2725.sibling = nextPrimaryChildren, workInProgress2.child = JSCompiler_object_inline_stack_2725, bailoutOffscreenComponent(null, JSCompiler_object_inline_stack_2725), JSCompiler_object_inline_stack_2725 = workInProgress2.child, nextPrimaryChildren = current22.child.memoizedState, null === nextPrimaryChildren ? nextPrimaryChildren = mountSuspenseOffscreenState(renderLanes2) : (mode = nextPrimaryChildren.cachePool, null !== mode ? (componentStack = CacheContext._currentValue, mode = mode.parent !== componentStack ? { parent: componentStack, pool: componentStack } : mode) : mode = getSuspendedCache(), nextPrimaryChildren = {
          baseLanes: nextPrimaryChildren.baseLanes | renderLanes2,
          cachePool: mode
        }), JSCompiler_object_inline_stack_2725.memoizedState = nextPrimaryChildren, JSCompiler_object_inline_stack_2725.childLanes = getRemainingWorkInPrimaryTree(
          current22,
          JSCompiler_object_inline_digest_2724,
          renderLanes2
        ), workInProgress2.memoizedState = SUSPENDED_MARKER, bailoutOffscreenComponent(
          current22.child,
          JSCompiler_object_inline_stack_2725
        );
      null !== prevState && (renderLanes2 & 62914560) === renderLanes2 && 0 !== (renderLanes2 & current22.lanes) && markRenderDerivedCause(workInProgress2);
      pushPrimaryTreeSuspenseHandler(workInProgress2);
      renderLanes2 = current22.child;
      current22 = renderLanes2.sibling;
      renderLanes2 = createWorkInProgress(renderLanes2, {
        mode: "visible",
        children: JSCompiler_object_inline_stack_2725.children
      });
      renderLanes2.return = workInProgress2;
      renderLanes2.sibling = null;
      null !== current22 && (JSCompiler_object_inline_digest_2724 = workInProgress2.deletions, null === JSCompiler_object_inline_digest_2724 ? (workInProgress2.deletions = [current22], workInProgress2.flags |= 16) : JSCompiler_object_inline_digest_2724.push(current22));
      workInProgress2.child = renderLanes2;
      workInProgress2.memoizedState = null;
      return renderLanes2;
    }
    function mountSuspensePrimaryChildren(workInProgress2, primaryChildren) {
      primaryChildren = mountWorkInProgressOffscreenFiber(
        { mode: "visible", children: primaryChildren },
        workInProgress2.mode
      );
      primaryChildren.return = workInProgress2;
      return workInProgress2.child = primaryChildren;
    }
    function mountWorkInProgressOffscreenFiber(offscreenProps, mode) {
      offscreenProps = createFiber(22, offscreenProps, null, mode);
      offscreenProps.lanes = 0;
      return offscreenProps;
    }
    function retrySuspenseComponentWithoutHydrating(current22, workInProgress2, renderLanes2) {
      reconcileChildFibers(workInProgress2, current22.child, null, renderLanes2);
      current22 = mountSuspensePrimaryChildren(
        workInProgress2,
        workInProgress2.pendingProps.children
      );
      current22.flags |= 2;
      workInProgress2.memoizedState = null;
      return current22;
    }
    function scheduleSuspenseWorkOnFiber(fiber, renderLanes2, propagationRoot) {
      fiber.lanes |= renderLanes2;
      var alternate = fiber.alternate;
      null !== alternate && (alternate.lanes |= renderLanes2);
      scheduleContextWorkOnParentPath(
        fiber.return,
        renderLanes2,
        propagationRoot
      );
    }
    function initSuspenseListRenderState(workInProgress2, isBackwards, tail, lastContentRow, tailMode, treeForkCount2) {
      var renderState = workInProgress2.memoizedState;
      null === renderState ? workInProgress2.memoizedState = {
        isBackwards,
        rendering: null,
        renderingStartTime: 0,
        last: lastContentRow,
        tail,
        tailMode,
        treeForkCount: treeForkCount2
      } : (renderState.isBackwards = isBackwards, renderState.rendering = null, renderState.renderingStartTime = 0, renderState.last = lastContentRow, renderState.tail = tail, renderState.tailMode = tailMode, renderState.treeForkCount = treeForkCount2);
    }
    function updateSuspenseListComponent(current22, workInProgress2, renderLanes2) {
      var nextProps = workInProgress2.pendingProps, revealOrder = nextProps.revealOrder, tailMode = nextProps.tail, newChildren = nextProps.children, suspenseContext = suspenseStackCursor.current;
      (nextProps = 0 !== (suspenseContext & ForceSuspenseFallback)) ? (suspenseContext = suspenseContext & SubtreeSuspenseContextMask | ForceSuspenseFallback, workInProgress2.flags |= 128) : suspenseContext &= SubtreeSuspenseContextMask;
      push2(suspenseStackCursor, suspenseContext, workInProgress2);
      suspenseContext = null == revealOrder ? "null" : revealOrder;
      if ("forwards" !== revealOrder && "unstable_legacy-backwards" !== revealOrder && "together" !== revealOrder && "independent" !== revealOrder && !didWarnAboutRevealOrder[suspenseContext])
        if (didWarnAboutRevealOrder[suspenseContext] = true, null == revealOrder)
          console.error(
            'The default for the <SuspenseList revealOrder="..."> prop is changing. To be future compatible you must explictly specify either "independent" (the current default), "together", "forwards" or "legacy_unstable-backwards".'
          );
        else if ("backwards" === revealOrder)
          console.error(
            'The rendering order of <SuspenseList revealOrder="backwards"> is changing. To be future compatible you must specify revealOrder="legacy_unstable-backwards" instead.'
          );
        else if ("string" === typeof revealOrder)
          switch (revealOrder.toLowerCase()) {
            case "together":
            case "forwards":
            case "backwards":
            case "independent":
              console.error(
                '"%s" is not a valid value for revealOrder on <SuspenseList />. Use lowercase "%s" instead.',
                revealOrder,
                revealOrder.toLowerCase()
              );
              break;
            case "forward":
            case "backward":
              console.error(
                '"%s" is not a valid value for revealOrder on <SuspenseList />. React uses the -s suffix in the spelling. Use "%ss" instead.',
                revealOrder,
                revealOrder.toLowerCase()
              );
              break;
            default:
              console.error(
                '"%s" is not a supported revealOrder on <SuspenseList />. Did you mean "independent", "together", "forwards" or "backwards"?',
                revealOrder
              );
          }
        else
          console.error(
            '%s is not a supported value for revealOrder on <SuspenseList />. Did you mean "independent", "together", "forwards" or "backwards"?',
            revealOrder
          );
      suspenseContext = null == tailMode ? "null" : tailMode;
      if (!didWarnAboutTailOptions[suspenseContext])
        if (null == tailMode) {
          if ("forwards" === revealOrder || "backwards" === revealOrder || "unstable_legacy-backwards" === revealOrder)
            didWarnAboutTailOptions[suspenseContext] = true, console.error(
              'The default for the <SuspenseList tail="..."> prop is changing. To be future compatible you must explictly specify either "visible" (the current default), "collapsed" or "hidden".'
            );
        } else
          "visible" !== tailMode && "collapsed" !== tailMode && "hidden" !== tailMode ? (didWarnAboutTailOptions[suspenseContext] = true, console.error(
            '"%s" is not a supported value for tail on <SuspenseList />. Did you mean "visible", "collapsed" or "hidden"?',
            tailMode
          )) : "forwards" !== revealOrder && "backwards" !== revealOrder && "unstable_legacy-backwards" !== revealOrder && (didWarnAboutTailOptions[suspenseContext] = true, console.error(
            '<SuspenseList tail="%s" /> is only valid if revealOrder is "forwards" or "backwards". Did you mean to specify revealOrder="forwards"?',
            tailMode
          ));
      a: if (("forwards" === revealOrder || "backwards" === revealOrder || "unstable_legacy-backwards" === revealOrder) && void 0 !== newChildren && null !== newChildren && false !== newChildren)
        if (isArrayImpl(newChildren))
          for (suspenseContext = 0; suspenseContext < newChildren.length; suspenseContext++) {
            if (!validateSuspenseListNestedChild(
              newChildren[suspenseContext],
              suspenseContext
            ))
              break a;
          }
        else if (suspenseContext = getIteratorFn(newChildren), "function" === typeof suspenseContext) {
          if (suspenseContext = suspenseContext.call(newChildren))
            for (var step = suspenseContext.next(), _i = 0; !step.done; step = suspenseContext.next()) {
              if (!validateSuspenseListNestedChild(step.value, _i)) break a;
              _i++;
            }
        } else
          console.error(
            'A single row was passed to a <SuspenseList revealOrder="%s" />. This is not useful since it needs multiple rows. Did you mean to pass multiple children or an array?',
            revealOrder
          );
      reconcileChildren(current22, workInProgress2, newChildren, renderLanes2);
      isHydrating ? (warnIfNotHydrating(), newChildren = treeForkCount) : newChildren = 0;
      if (!nextProps && null !== current22 && 0 !== (current22.flags & 128))
        a: for (current22 = workInProgress2.child; null !== current22; ) {
          if (13 === current22.tag)
            null !== current22.memoizedState && scheduleSuspenseWorkOnFiber(current22, renderLanes2, workInProgress2);
          else if (19 === current22.tag)
            scheduleSuspenseWorkOnFiber(current22, renderLanes2, workInProgress2);
          else if (null !== current22.child) {
            current22.child.return = current22;
            current22 = current22.child;
            continue;
          }
          if (current22 === workInProgress2) break a;
          for (; null === current22.sibling; ) {
            if (null === current22.return || current22.return === workInProgress2)
              break a;
            current22 = current22.return;
          }
          current22.sibling.return = current22.return;
          current22 = current22.sibling;
        }
      switch (revealOrder) {
        case "forwards":
          renderLanes2 = workInProgress2.child;
          for (revealOrder = null; null !== renderLanes2; )
            current22 = renderLanes2.alternate, null !== current22 && null === findFirstSuspended(current22) && (revealOrder = renderLanes2), renderLanes2 = renderLanes2.sibling;
          renderLanes2 = revealOrder;
          null === renderLanes2 ? (revealOrder = workInProgress2.child, workInProgress2.child = null) : (revealOrder = renderLanes2.sibling, renderLanes2.sibling = null);
          initSuspenseListRenderState(
            workInProgress2,
            false,
            revealOrder,
            renderLanes2,
            tailMode,
            newChildren
          );
          break;
        case "backwards":
        case "unstable_legacy-backwards":
          renderLanes2 = null;
          revealOrder = workInProgress2.child;
          for (workInProgress2.child = null; null !== revealOrder; ) {
            current22 = revealOrder.alternate;
            if (null !== current22 && null === findFirstSuspended(current22)) {
              workInProgress2.child = revealOrder;
              break;
            }
            current22 = revealOrder.sibling;
            revealOrder.sibling = renderLanes2;
            renderLanes2 = revealOrder;
            revealOrder = current22;
          }
          initSuspenseListRenderState(
            workInProgress2,
            true,
            renderLanes2,
            null,
            tailMode,
            newChildren
          );
          break;
        case "together":
          initSuspenseListRenderState(
            workInProgress2,
            false,
            null,
            null,
            void 0,
            newChildren
          );
          break;
        default:
          workInProgress2.memoizedState = null;
      }
      return workInProgress2.child;
    }
    function bailoutOnAlreadyFinishedWork(current22, workInProgress2, renderLanes2) {
      null !== current22 && (workInProgress2.dependencies = current22.dependencies);
      profilerStartTime = -1;
      workInProgressRootSkippedLanes |= workInProgress2.lanes;
      if (0 === (renderLanes2 & workInProgress2.childLanes))
        if (null !== current22) {
          if (propagateParentContextChanges(
            current22,
            workInProgress2,
            renderLanes2,
            false
          ), 0 === (renderLanes2 & workInProgress2.childLanes))
            return null;
        } else return null;
      if (null !== current22 && workInProgress2.child !== current22.child)
        throw Error("Resuming work not yet implemented.");
      if (null !== workInProgress2.child) {
        current22 = workInProgress2.child;
        renderLanes2 = createWorkInProgress(current22, current22.pendingProps);
        workInProgress2.child = renderLanes2;
        for (renderLanes2.return = workInProgress2; null !== current22.sibling; )
          current22 = current22.sibling, renderLanes2 = renderLanes2.sibling = createWorkInProgress(current22, current22.pendingProps), renderLanes2.return = workInProgress2;
        renderLanes2.sibling = null;
      }
      return workInProgress2.child;
    }
    function checkScheduledUpdateOrContext(current22, renderLanes2) {
      if (0 !== (current22.lanes & renderLanes2)) return true;
      current22 = current22.dependencies;
      return null !== current22 && checkIfContextChanged(current22) ? true : false;
    }
    function attemptEarlyBailoutIfNoScheduledUpdate(current22, workInProgress2, renderLanes2) {
      switch (workInProgress2.tag) {
        case 3:
          pushHostContainer(
            workInProgress2,
            workInProgress2.stateNode.containerInfo
          );
          pushProvider(
            workInProgress2,
            CacheContext,
            current22.memoizedState.cache
          );
          resetHydrationState();
          break;
        case 27:
        case 5:
          pushHostContext(workInProgress2);
          break;
        case 4:
          pushHostContainer(
            workInProgress2,
            workInProgress2.stateNode.containerInfo
          );
          break;
        case 10:
          pushProvider(
            workInProgress2,
            workInProgress2.type,
            workInProgress2.memoizedProps.value
          );
          break;
        case 12:
          0 !== (renderLanes2 & workInProgress2.childLanes) && (workInProgress2.flags |= 4);
          workInProgress2.flags |= 2048;
          var stateNode = workInProgress2.stateNode;
          stateNode.effectDuration = -0;
          stateNode.passiveEffectDuration = -0;
          break;
        case 31:
          if (null !== workInProgress2.memoizedState)
            return workInProgress2.flags |= 128, pushDehydratedActivitySuspenseHandler(workInProgress2), null;
          break;
        case 13:
          stateNode = workInProgress2.memoizedState;
          if (null !== stateNode) {
            if (null !== stateNode.dehydrated)
              return pushPrimaryTreeSuspenseHandler(workInProgress2), workInProgress2.flags |= 128, null;
            if (0 !== (renderLanes2 & workInProgress2.child.childLanes))
              return updateSuspenseComponent(
                current22,
                workInProgress2,
                renderLanes2
              );
            pushPrimaryTreeSuspenseHandler(workInProgress2);
            current22 = bailoutOnAlreadyFinishedWork(
              current22,
              workInProgress2,
              renderLanes2
            );
            return null !== current22 ? current22.sibling : null;
          }
          pushPrimaryTreeSuspenseHandler(workInProgress2);
          break;
        case 19:
          var didSuspendBefore = 0 !== (current22.flags & 128);
          stateNode = 0 !== (renderLanes2 & workInProgress2.childLanes);
          stateNode || (propagateParentContextChanges(
            current22,
            workInProgress2,
            renderLanes2,
            false
          ), stateNode = 0 !== (renderLanes2 & workInProgress2.childLanes));
          if (didSuspendBefore) {
            if (stateNode)
              return updateSuspenseListComponent(
                current22,
                workInProgress2,
                renderLanes2
              );
            workInProgress2.flags |= 128;
          }
          didSuspendBefore = workInProgress2.memoizedState;
          null !== didSuspendBefore && (didSuspendBefore.rendering = null, didSuspendBefore.tail = null, didSuspendBefore.lastEffect = null);
          push2(
            suspenseStackCursor,
            suspenseStackCursor.current,
            workInProgress2
          );
          if (stateNode) break;
          else return null;
        case 22:
          return workInProgress2.lanes = 0, updateOffscreenComponent(
            current22,
            workInProgress2,
            renderLanes2,
            workInProgress2.pendingProps
          );
        case 24:
          pushProvider(
            workInProgress2,
            CacheContext,
            current22.memoizedState.cache
          );
      }
      return bailoutOnAlreadyFinishedWork(current22, workInProgress2, renderLanes2);
    }
    function beginWork(current22, workInProgress2, renderLanes2) {
      if (workInProgress2._debugNeedsRemount && null !== current22) {
        renderLanes2 = createFiberFromTypeAndProps(
          workInProgress2.type,
          workInProgress2.key,
          workInProgress2.pendingProps,
          workInProgress2._debugOwner || null,
          workInProgress2.mode,
          workInProgress2.lanes
        );
        renderLanes2._debugStack = workInProgress2._debugStack;
        renderLanes2._debugTask = workInProgress2._debugTask;
        var returnFiber = workInProgress2.return;
        if (null === returnFiber) throw Error("Cannot swap the root fiber.");
        current22.alternate = null;
        workInProgress2.alternate = null;
        renderLanes2.index = workInProgress2.index;
        renderLanes2.sibling = workInProgress2.sibling;
        renderLanes2.return = workInProgress2.return;
        renderLanes2.ref = workInProgress2.ref;
        renderLanes2._debugInfo = workInProgress2._debugInfo;
        if (workInProgress2 === returnFiber.child)
          returnFiber.child = renderLanes2;
        else {
          var prevSibling = returnFiber.child;
          if (null === prevSibling)
            throw Error("Expected parent to have a child.");
          for (; prevSibling.sibling !== workInProgress2; )
            if (prevSibling = prevSibling.sibling, null === prevSibling)
              throw Error("Expected to find the previous sibling.");
          prevSibling.sibling = renderLanes2;
        }
        workInProgress2 = returnFiber.deletions;
        null === workInProgress2 ? (returnFiber.deletions = [current22], returnFiber.flags |= 16) : workInProgress2.push(current22);
        renderLanes2.flags |= 2;
        return renderLanes2;
      }
      if (null !== current22)
        if (current22.memoizedProps !== workInProgress2.pendingProps || workInProgress2.type !== current22.type)
          didReceiveUpdate = true;
        else {
          if (!checkScheduledUpdateOrContext(current22, renderLanes2) && 0 === (workInProgress2.flags & 128))
            return didReceiveUpdate = false, attemptEarlyBailoutIfNoScheduledUpdate(
              current22,
              workInProgress2,
              renderLanes2
            );
          didReceiveUpdate = 0 !== (current22.flags & 131072) ? true : false;
        }
      else {
        didReceiveUpdate = false;
        if (returnFiber = isHydrating)
          warnIfNotHydrating(), returnFiber = 0 !== (workInProgress2.flags & 1048576);
        returnFiber && (returnFiber = workInProgress2.index, warnIfNotHydrating(), pushTreeId(workInProgress2, treeForkCount, returnFiber));
      }
      workInProgress2.lanes = 0;
      switch (workInProgress2.tag) {
        case 16:
          a: if (returnFiber = workInProgress2.pendingProps, current22 = resolveLazy(workInProgress2.elementType), workInProgress2.type = current22, "function" === typeof current22)
            shouldConstruct(current22) ? (returnFiber = resolveClassComponentProps(
              current22,
              returnFiber
            ), workInProgress2.tag = 1, workInProgress2.type = current22 = resolveFunctionForHotReloading(current22), workInProgress2 = updateClassComponent(
              null,
              workInProgress2,
              current22,
              returnFiber,
              renderLanes2
            )) : (workInProgress2.tag = 0, validateFunctionComponentInDev(workInProgress2, current22), workInProgress2.type = current22 = resolveFunctionForHotReloading(current22), workInProgress2 = updateFunctionComponent(
              null,
              workInProgress2,
              current22,
              returnFiber,
              renderLanes2
            ));
          else {
            if (void 0 !== current22 && null !== current22) {
              if (prevSibling = current22.$$typeof, prevSibling === REACT_FORWARD_REF_TYPE) {
                workInProgress2.tag = 11;
                workInProgress2.type = current22 = resolveForwardRefForHotReloading(current22);
                workInProgress2 = updateForwardRef(
                  null,
                  workInProgress2,
                  current22,
                  returnFiber,
                  renderLanes2
                );
                break a;
              } else if (prevSibling === REACT_MEMO_TYPE) {
                workInProgress2.tag = 14;
                workInProgress2 = updateMemoComponent(
                  null,
                  workInProgress2,
                  current22,
                  returnFiber,
                  renderLanes2
                );
                break a;
              }
            }
            workInProgress2 = "";
            null !== current22 && "object" === typeof current22 && current22.$$typeof === REACT_LAZY_TYPE && (workInProgress2 = " Did you wrap a component in React.lazy() more than once?");
            renderLanes2 = getComponentNameFromType(current22) || current22;
            throw Error(
              "Element type is invalid. Received a promise that resolves to: " + renderLanes2 + ". Lazy element type must resolve to a class or function." + workInProgress2
            );
          }
          return workInProgress2;
        case 0:
          return updateFunctionComponent(
            current22,
            workInProgress2,
            workInProgress2.type,
            workInProgress2.pendingProps,
            renderLanes2
          );
        case 1:
          return returnFiber = workInProgress2.type, prevSibling = resolveClassComponentProps(
            returnFiber,
            workInProgress2.pendingProps
          ), updateClassComponent(
            current22,
            workInProgress2,
            returnFiber,
            prevSibling,
            renderLanes2
          );
        case 3:
          a: {
            pushHostContainer(
              workInProgress2,
              workInProgress2.stateNode.containerInfo
            );
            if (null === current22)
              throw Error(
                "Should have a current fiber. This is a bug in React."
              );
            returnFiber = workInProgress2.pendingProps;
            var prevState = workInProgress2.memoizedState;
            prevSibling = prevState.element;
            cloneUpdateQueue(current22, workInProgress2);
            processUpdateQueue(workInProgress2, returnFiber, null, renderLanes2);
            var nextState = workInProgress2.memoizedState;
            returnFiber = nextState.cache;
            pushProvider(workInProgress2, CacheContext, returnFiber);
            returnFiber !== prevState.cache && propagateContextChanges(
              workInProgress2,
              [CacheContext],
              renderLanes2,
              true
            );
            suspendIfUpdateReadFromEntangledAsyncAction();
            returnFiber = nextState.element;
            if (prevState.isDehydrated)
              if (prevState = {
                element: returnFiber,
                isDehydrated: false,
                cache: nextState.cache
              }, workInProgress2.updateQueue.baseState = prevState, workInProgress2.memoizedState = prevState, workInProgress2.flags & 256) {
                workInProgress2 = mountHostRootWithoutHydrating(
                  current22,
                  workInProgress2,
                  returnFiber,
                  renderLanes2
                );
                break a;
              } else if (returnFiber !== prevSibling) {
                prevSibling = createCapturedValueAtFiber(
                  Error(
                    "This root received an early update, before anything was able hydrate. Switched the entire root to client rendering."
                  ),
                  workInProgress2
                );
                queueHydrationError(prevSibling);
                workInProgress2 = mountHostRootWithoutHydrating(
                  current22,
                  workInProgress2,
                  returnFiber,
                  renderLanes2
                );
                break a;
              } else {
                current22 = workInProgress2.stateNode.containerInfo;
                switch (current22.nodeType) {
                  case 9:
                    current22 = current22.body;
                    break;
                  default:
                    current22 = "HTML" === current22.nodeName ? current22.ownerDocument.body : current22;
                }
                nextHydratableInstance = getNextHydratable(current22.firstChild);
                hydrationParentFiber = workInProgress2;
                isHydrating = true;
                hydrationErrors = null;
                didSuspendOrErrorDEV = false;
                hydrationDiffRootDEV = null;
                rootOrSingletonContext = true;
                renderLanes2 = mountChildFibers(
                  workInProgress2,
                  null,
                  returnFiber,
                  renderLanes2
                );
                for (workInProgress2.child = renderLanes2; renderLanes2; )
                  renderLanes2.flags = renderLanes2.flags & -3 | 4096, renderLanes2 = renderLanes2.sibling;
              }
            else {
              resetHydrationState();
              if (returnFiber === prevSibling) {
                workInProgress2 = bailoutOnAlreadyFinishedWork(
                  current22,
                  workInProgress2,
                  renderLanes2
                );
                break a;
              }
              reconcileChildren(
                current22,
                workInProgress2,
                returnFiber,
                renderLanes2
              );
            }
            workInProgress2 = workInProgress2.child;
          }
          return workInProgress2;
        case 26:
          return markRef(current22, workInProgress2), null === current22 ? (renderLanes2 = getResource(
            workInProgress2.type,
            null,
            workInProgress2.pendingProps,
            null
          )) ? workInProgress2.memoizedState = renderLanes2 : isHydrating || (renderLanes2 = workInProgress2.type, current22 = workInProgress2.pendingProps, returnFiber = requiredContext(
            rootInstanceStackCursor.current
          ), returnFiber = getOwnerDocumentFromRootContainer(
            returnFiber
          ).createElement(renderLanes2), returnFiber[internalInstanceKey] = workInProgress2, returnFiber[internalPropsKey] = current22, setInitialProperties(returnFiber, renderLanes2, current22), markNodeAsHoistable(returnFiber), workInProgress2.stateNode = returnFiber) : workInProgress2.memoizedState = getResource(
            workInProgress2.type,
            current22.memoizedProps,
            workInProgress2.pendingProps,
            current22.memoizedState
          ), null;
        case 27:
          return pushHostContext(workInProgress2), null === current22 && isHydrating && (returnFiber = requiredContext(rootInstanceStackCursor.current), prevSibling = getHostContext(), returnFiber = workInProgress2.stateNode = resolveSingletonInstance(
            workInProgress2.type,
            workInProgress2.pendingProps,
            returnFiber,
            prevSibling,
            false
          ), didSuspendOrErrorDEV || (prevSibling = diffHydratedProperties(
            returnFiber,
            workInProgress2.type,
            workInProgress2.pendingProps,
            prevSibling
          ), null !== prevSibling && (buildHydrationDiffNode(workInProgress2, 0).serverProps = prevSibling)), hydrationParentFiber = workInProgress2, rootOrSingletonContext = true, prevSibling = nextHydratableInstance, isSingletonScope(workInProgress2.type) ? (previousHydratableOnEnteringScopedSingleton = prevSibling, nextHydratableInstance = getNextHydratable(
            returnFiber.firstChild
          )) : nextHydratableInstance = prevSibling), reconcileChildren(
            current22,
            workInProgress2,
            workInProgress2.pendingProps.children,
            renderLanes2
          ), markRef(current22, workInProgress2), null === current22 && (workInProgress2.flags |= 4194304), workInProgress2.child;
        case 5:
          return null === current22 && isHydrating && (prevState = getHostContext(), returnFiber = validateDOMNesting(
            workInProgress2.type,
            prevState.ancestorInfo
          ), prevSibling = nextHydratableInstance, (nextState = !prevSibling) || (nextState = canHydrateInstance(
            prevSibling,
            workInProgress2.type,
            workInProgress2.pendingProps,
            rootOrSingletonContext
          ), null !== nextState ? (workInProgress2.stateNode = nextState, didSuspendOrErrorDEV || (prevState = diffHydratedProperties(
            nextState,
            workInProgress2.type,
            workInProgress2.pendingProps,
            prevState
          ), null !== prevState && (buildHydrationDiffNode(workInProgress2, 0).serverProps = prevState)), hydrationParentFiber = workInProgress2, nextHydratableInstance = getNextHydratable(
            nextState.firstChild
          ), rootOrSingletonContext = false, prevState = true) : prevState = false, nextState = !prevState), nextState && (returnFiber && warnNonHydratedInstance(workInProgress2, prevSibling), throwOnHydrationMismatch(workInProgress2))), pushHostContext(workInProgress2), prevSibling = workInProgress2.type, prevState = workInProgress2.pendingProps, nextState = null !== current22 ? current22.memoizedProps : null, returnFiber = prevState.children, shouldSetTextContent(prevSibling, prevState) ? returnFiber = null : null !== nextState && shouldSetTextContent(prevSibling, nextState) && (workInProgress2.flags |= 32), null !== workInProgress2.memoizedState && (prevSibling = renderWithHooks(
            current22,
            workInProgress2,
            TransitionAwareHostComponent,
            null,
            null,
            renderLanes2
          ), HostTransitionContext._currentValue = prevSibling), markRef(current22, workInProgress2), reconcileChildren(
            current22,
            workInProgress2,
            returnFiber,
            renderLanes2
          ), workInProgress2.child;
        case 6:
          return null === current22 && isHydrating && (renderLanes2 = workInProgress2.pendingProps, current22 = getHostContext(), returnFiber = current22.ancestorInfo.current, renderLanes2 = null != returnFiber ? validateTextNesting(
            renderLanes2,
            returnFiber.tag,
            current22.ancestorInfo.implicitRootScope
          ) : true, current22 = nextHydratableInstance, (returnFiber = !current22) || (returnFiber = canHydrateTextInstance(
            current22,
            workInProgress2.pendingProps,
            rootOrSingletonContext
          ), null !== returnFiber ? (workInProgress2.stateNode = returnFiber, hydrationParentFiber = workInProgress2, nextHydratableInstance = null, returnFiber = true) : returnFiber = false, returnFiber = !returnFiber), returnFiber && (renderLanes2 && warnNonHydratedInstance(workInProgress2, current22), throwOnHydrationMismatch(workInProgress2))), null;
        case 13:
          return updateSuspenseComponent(current22, workInProgress2, renderLanes2);
        case 4:
          return pushHostContainer(
            workInProgress2,
            workInProgress2.stateNode.containerInfo
          ), returnFiber = workInProgress2.pendingProps, null === current22 ? workInProgress2.child = reconcileChildFibers(
            workInProgress2,
            null,
            returnFiber,
            renderLanes2
          ) : reconcileChildren(
            current22,
            workInProgress2,
            returnFiber,
            renderLanes2
          ), workInProgress2.child;
        case 11:
          return updateForwardRef(
            current22,
            workInProgress2,
            workInProgress2.type,
            workInProgress2.pendingProps,
            renderLanes2
          );
        case 7:
          return reconcileChildren(
            current22,
            workInProgress2,
            workInProgress2.pendingProps,
            renderLanes2
          ), workInProgress2.child;
        case 8:
          return reconcileChildren(
            current22,
            workInProgress2,
            workInProgress2.pendingProps.children,
            renderLanes2
          ), workInProgress2.child;
        case 12:
          return workInProgress2.flags |= 4, workInProgress2.flags |= 2048, returnFiber = workInProgress2.stateNode, returnFiber.effectDuration = -0, returnFiber.passiveEffectDuration = -0, reconcileChildren(
            current22,
            workInProgress2,
            workInProgress2.pendingProps.children,
            renderLanes2
          ), workInProgress2.child;
        case 10:
          return returnFiber = workInProgress2.type, prevSibling = workInProgress2.pendingProps, prevState = prevSibling.value, "value" in prevSibling || hasWarnedAboutUsingNoValuePropOnContextProvider || (hasWarnedAboutUsingNoValuePropOnContextProvider = true, console.error(
            "The `value` prop is required for the `<Context.Provider>`. Did you misspell it or forget to pass it?"
          )), pushProvider(workInProgress2, returnFiber, prevState), reconcileChildren(
            current22,
            workInProgress2,
            prevSibling.children,
            renderLanes2
          ), workInProgress2.child;
        case 9:
          return prevSibling = workInProgress2.type._context, returnFiber = workInProgress2.pendingProps.children, "function" !== typeof returnFiber && console.error(
            "A context consumer was rendered with multiple children, or a child that isn't a function. A context consumer expects a single child that is a function. If you did pass a function, make sure there is no trailing or leading whitespace around it."
          ), prepareToReadContext(workInProgress2), prevSibling = readContext(prevSibling), returnFiber = callComponentInDEV(
            returnFiber,
            prevSibling,
            void 0
          ), workInProgress2.flags |= 1, reconcileChildren(
            current22,
            workInProgress2,
            returnFiber,
            renderLanes2
          ), workInProgress2.child;
        case 14:
          return updateMemoComponent(
            current22,
            workInProgress2,
            workInProgress2.type,
            workInProgress2.pendingProps,
            renderLanes2
          );
        case 15:
          return updateSimpleMemoComponent(
            current22,
            workInProgress2,
            workInProgress2.type,
            workInProgress2.pendingProps,
            renderLanes2
          );
        case 19:
          return updateSuspenseListComponent(
            current22,
            workInProgress2,
            renderLanes2
          );
        case 31:
          return updateActivityComponent(current22, workInProgress2, renderLanes2);
        case 22:
          return updateOffscreenComponent(
            current22,
            workInProgress2,
            renderLanes2,
            workInProgress2.pendingProps
          );
        case 24:
          return prepareToReadContext(workInProgress2), returnFiber = readContext(CacheContext), null === current22 ? (prevSibling = peekCacheFromPool(), null === prevSibling && (prevSibling = workInProgressRoot, prevState = createCache(), prevSibling.pooledCache = prevState, retainCache(prevState), null !== prevState && (prevSibling.pooledCacheLanes |= renderLanes2), prevSibling = prevState), workInProgress2.memoizedState = {
            parent: returnFiber,
            cache: prevSibling
          }, initializeUpdateQueue(workInProgress2), pushProvider(workInProgress2, CacheContext, prevSibling)) : (0 !== (current22.lanes & renderLanes2) && (cloneUpdateQueue(current22, workInProgress2), processUpdateQueue(workInProgress2, null, null, renderLanes2), suspendIfUpdateReadFromEntangledAsyncAction()), prevSibling = current22.memoizedState, prevState = workInProgress2.memoizedState, prevSibling.parent !== returnFiber ? (prevSibling = {
            parent: returnFiber,
            cache: returnFiber
          }, workInProgress2.memoizedState = prevSibling, 0 === workInProgress2.lanes && (workInProgress2.memoizedState = workInProgress2.updateQueue.baseState = prevSibling), pushProvider(workInProgress2, CacheContext, returnFiber)) : (returnFiber = prevState.cache, pushProvider(workInProgress2, CacheContext, returnFiber), returnFiber !== prevSibling.cache && propagateContextChanges(
            workInProgress2,
            [CacheContext],
            renderLanes2,
            true
          ))), reconcileChildren(
            current22,
            workInProgress2,
            workInProgress2.pendingProps.children,
            renderLanes2
          ), workInProgress2.child;
        case 29:
          throw workInProgress2.pendingProps;
      }
      throw Error(
        "Unknown unit of work tag (" + workInProgress2.tag + "). This error is likely caused by a bug in React. Please file an issue."
      );
    }
    function markUpdate(workInProgress2) {
      workInProgress2.flags |= 4;
    }
    function preloadInstanceAndSuspendIfNeeded(workInProgress2, type, oldProps, newProps, renderLanes2) {
      if (type = (workInProgress2.mode & SuspenseyImagesMode) !== NoMode)
        type = false;
      if (type) {
        if (workInProgress2.flags |= 16777216, (renderLanes2 & 335544128) === renderLanes2)
          if (workInProgress2.stateNode.complete) workInProgress2.flags |= 8192;
          else if (shouldRemainOnPreviousScreen()) workInProgress2.flags |= 8192;
          else
            throw suspendedThenable = noopSuspenseyCommitThenable, SuspenseyCommitException;
      } else workInProgress2.flags &= -16777217;
    }
    function preloadResourceAndSuspendIfNeeded(workInProgress2, resource) {
      if ("stylesheet" !== resource.type || (resource.state.loading & Inserted) !== NotLoaded)
        workInProgress2.flags &= -16777217;
      else if (workInProgress2.flags |= 16777216, !preloadResource(resource))
        if (shouldRemainOnPreviousScreen()) workInProgress2.flags |= 8192;
        else
          throw suspendedThenable = noopSuspenseyCommitThenable, SuspenseyCommitException;
    }
    function scheduleRetryEffect(workInProgress2, retryQueue) {
      null !== retryQueue && (workInProgress2.flags |= 4);
      workInProgress2.flags & 16384 && (retryQueue = 22 !== workInProgress2.tag ? claimNextRetryLane() : 536870912, workInProgress2.lanes |= retryQueue, workInProgressSuspendedRetryLanes |= retryQueue);
    }
    function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) {
      if (!isHydrating)
        switch (renderState.tailMode) {
          case "hidden":
            hasRenderedATailFallback = renderState.tail;
            for (var lastTailNode = null; null !== hasRenderedATailFallback; )
              null !== hasRenderedATailFallback.alternate && (lastTailNode = hasRenderedATailFallback), hasRenderedATailFallback = hasRenderedATailFallback.sibling;
            null === lastTailNode ? renderState.tail = null : lastTailNode.sibling = null;
            break;
          case "collapsed":
            lastTailNode = renderState.tail;
            for (var _lastTailNode = null; null !== lastTailNode; )
              null !== lastTailNode.alternate && (_lastTailNode = lastTailNode), lastTailNode = lastTailNode.sibling;
            null === _lastTailNode ? hasRenderedATailFallback || null === renderState.tail ? renderState.tail = null : renderState.tail.sibling = null : _lastTailNode.sibling = null;
        }
    }
    function bubbleProperties(completedWork) {
      var didBailout = null !== completedWork.alternate && completedWork.alternate.child === completedWork.child, newChildLanes = 0, subtreeFlags = 0;
      if (didBailout)
        if ((completedWork.mode & ProfileMode) !== NoMode) {
          for (var _treeBaseDuration = completedWork.selfBaseDuration, _child2 = completedWork.child; null !== _child2; )
            newChildLanes |= _child2.lanes | _child2.childLanes, subtreeFlags |= _child2.subtreeFlags & 65011712, subtreeFlags |= _child2.flags & 65011712, _treeBaseDuration += _child2.treeBaseDuration, _child2 = _child2.sibling;
          completedWork.treeBaseDuration = _treeBaseDuration;
        } else
          for (_treeBaseDuration = completedWork.child; null !== _treeBaseDuration; )
            newChildLanes |= _treeBaseDuration.lanes | _treeBaseDuration.childLanes, subtreeFlags |= _treeBaseDuration.subtreeFlags & 65011712, subtreeFlags |= _treeBaseDuration.flags & 65011712, _treeBaseDuration.return = completedWork, _treeBaseDuration = _treeBaseDuration.sibling;
      else if ((completedWork.mode & ProfileMode) !== NoMode) {
        _treeBaseDuration = completedWork.actualDuration;
        _child2 = completedWork.selfBaseDuration;
        for (var child = completedWork.child; null !== child; )
          newChildLanes |= child.lanes | child.childLanes, subtreeFlags |= child.subtreeFlags, subtreeFlags |= child.flags, _treeBaseDuration += child.actualDuration, _child2 += child.treeBaseDuration, child = child.sibling;
        completedWork.actualDuration = _treeBaseDuration;
        completedWork.treeBaseDuration = _child2;
      } else
        for (_treeBaseDuration = completedWork.child; null !== _treeBaseDuration; )
          newChildLanes |= _treeBaseDuration.lanes | _treeBaseDuration.childLanes, subtreeFlags |= _treeBaseDuration.subtreeFlags, subtreeFlags |= _treeBaseDuration.flags, _treeBaseDuration.return = completedWork, _treeBaseDuration = _treeBaseDuration.sibling;
      completedWork.subtreeFlags |= subtreeFlags;
      completedWork.childLanes = newChildLanes;
      return didBailout;
    }
    function completeWork(current22, workInProgress2, renderLanes2) {
      var newProps = workInProgress2.pendingProps;
      popTreeContext(workInProgress2);
      switch (workInProgress2.tag) {
        case 16:
        case 15:
        case 0:
        case 11:
        case 7:
        case 8:
        case 12:
        case 9:
        case 14:
          return bubbleProperties(workInProgress2), null;
        case 1:
          return bubbleProperties(workInProgress2), null;
        case 3:
          renderLanes2 = workInProgress2.stateNode;
          newProps = null;
          null !== current22 && (newProps = current22.memoizedState.cache);
          workInProgress2.memoizedState.cache !== newProps && (workInProgress2.flags |= 2048);
          popProvider(CacheContext, workInProgress2);
          popHostContainer(workInProgress2);
          renderLanes2.pendingContext && (renderLanes2.context = renderLanes2.pendingContext, renderLanes2.pendingContext = null);
          if (null === current22 || null === current22.child)
            popHydrationState(workInProgress2) ? (emitPendingHydrationWarnings(), markUpdate(workInProgress2)) : null === current22 || current22.memoizedState.isDehydrated && 0 === (workInProgress2.flags & 256) || (workInProgress2.flags |= 1024, upgradeHydrationErrorsToRecoverable());
          bubbleProperties(workInProgress2);
          return null;
        case 26:
          var type = workInProgress2.type, nextResource = workInProgress2.memoizedState;
          null === current22 ? (markUpdate(workInProgress2), null !== nextResource ? (bubbleProperties(workInProgress2), preloadResourceAndSuspendIfNeeded(
            workInProgress2,
            nextResource
          )) : (bubbleProperties(workInProgress2), preloadInstanceAndSuspendIfNeeded(
            workInProgress2,
            type,
            null,
            newProps,
            renderLanes2
          ))) : nextResource ? nextResource !== current22.memoizedState ? (markUpdate(workInProgress2), bubbleProperties(workInProgress2), preloadResourceAndSuspendIfNeeded(
            workInProgress2,
            nextResource
          )) : (bubbleProperties(workInProgress2), workInProgress2.flags &= -16777217) : (current22 = current22.memoizedProps, current22 !== newProps && markUpdate(workInProgress2), bubbleProperties(workInProgress2), preloadInstanceAndSuspendIfNeeded(
            workInProgress2,
            type,
            current22,
            newProps,
            renderLanes2
          ));
          return null;
        case 27:
          popHostContext(workInProgress2);
          renderLanes2 = requiredContext(rootInstanceStackCursor.current);
          type = workInProgress2.type;
          if (null !== current22 && null != workInProgress2.stateNode)
            current22.memoizedProps !== newProps && markUpdate(workInProgress2);
          else {
            if (!newProps) {
              if (null === workInProgress2.stateNode)
                throw Error(
                  "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue."
                );
              bubbleProperties(workInProgress2);
              return null;
            }
            current22 = getHostContext();
            popHydrationState(workInProgress2) ? prepareToHydrateHostInstance(workInProgress2) : (current22 = resolveSingletonInstance(
              type,
              newProps,
              renderLanes2,
              current22,
              true
            ), workInProgress2.stateNode = current22, markUpdate(workInProgress2));
          }
          bubbleProperties(workInProgress2);
          return null;
        case 5:
          popHostContext(workInProgress2);
          type = workInProgress2.type;
          if (null !== current22 && null != workInProgress2.stateNode)
            current22.memoizedProps !== newProps && markUpdate(workInProgress2);
          else {
            if (!newProps) {
              if (null === workInProgress2.stateNode)
                throw Error(
                  "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue."
                );
              bubbleProperties(workInProgress2);
              return null;
            }
            var _currentHostContext = getHostContext();
            if (popHydrationState(workInProgress2))
              prepareToHydrateHostInstance(workInProgress2);
            else {
              nextResource = requiredContext(rootInstanceStackCursor.current);
              validateDOMNesting(type, _currentHostContext.ancestorInfo);
              _currentHostContext = _currentHostContext.context;
              nextResource = getOwnerDocumentFromRootContainer(nextResource);
              switch (_currentHostContext) {
                case HostContextNamespaceSvg:
                  nextResource = nextResource.createElementNS(
                    SVG_NAMESPACE,
                    type
                  );
                  break;
                case HostContextNamespaceMath:
                  nextResource = nextResource.createElementNS(
                    MATH_NAMESPACE,
                    type
                  );
                  break;
                default:
                  switch (type) {
                    case "svg":
                      nextResource = nextResource.createElementNS(
                        SVG_NAMESPACE,
                        type
                      );
                      break;
                    case "math":
                      nextResource = nextResource.createElementNS(
                        MATH_NAMESPACE,
                        type
                      );
                      break;
                    case "script":
                      nextResource = nextResource.createElement("div");
                      nextResource.innerHTML = "<script><\/script>";
                      nextResource = nextResource.removeChild(
                        nextResource.firstChild
                      );
                      break;
                    case "select":
                      nextResource = "string" === typeof newProps.is ? nextResource.createElement("select", {
                        is: newProps.is
                      }) : nextResource.createElement("select");
                      newProps.multiple ? nextResource.multiple = true : newProps.size && (nextResource.size = newProps.size);
                      break;
                    default:
                      nextResource = "string" === typeof newProps.is ? nextResource.createElement(type, {
                        is: newProps.is
                      }) : nextResource.createElement(type), -1 === type.indexOf("-") && (type !== type.toLowerCase() && console.error(
                        "<%s /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.",
                        type
                      ), "[object HTMLUnknownElement]" !== Object.prototype.toString.call(nextResource) || hasOwnProperty2.call(warnedUnknownTags, type) || (warnedUnknownTags[type] = true, console.error(
                        "The tag <%s> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.",
                        type
                      )));
                  }
              }
              nextResource[internalInstanceKey] = workInProgress2;
              nextResource[internalPropsKey] = newProps;
              a: for (_currentHostContext = workInProgress2.child; null !== _currentHostContext; ) {
                if (5 === _currentHostContext.tag || 6 === _currentHostContext.tag)
                  nextResource.appendChild(_currentHostContext.stateNode);
                else if (4 !== _currentHostContext.tag && 27 !== _currentHostContext.tag && null !== _currentHostContext.child) {
                  _currentHostContext.child.return = _currentHostContext;
                  _currentHostContext = _currentHostContext.child;
                  continue;
                }
                if (_currentHostContext === workInProgress2) break a;
                for (; null === _currentHostContext.sibling; ) {
                  if (null === _currentHostContext.return || _currentHostContext.return === workInProgress2)
                    break a;
                  _currentHostContext = _currentHostContext.return;
                }
                _currentHostContext.sibling.return = _currentHostContext.return;
                _currentHostContext = _currentHostContext.sibling;
              }
              workInProgress2.stateNode = nextResource;
              a: switch (setInitialProperties(nextResource, type, newProps), type) {
                case "button":
                case "input":
                case "select":
                case "textarea":
                  newProps = !!newProps.autoFocus;
                  break a;
                case "img":
                  newProps = true;
                  break a;
                default:
                  newProps = false;
              }
              newProps && markUpdate(workInProgress2);
            }
          }
          bubbleProperties(workInProgress2);
          preloadInstanceAndSuspendIfNeeded(
            workInProgress2,
            workInProgress2.type,
            null === current22 ? null : current22.memoizedProps,
            workInProgress2.pendingProps,
            renderLanes2
          );
          return null;
        case 6:
          if (current22 && null != workInProgress2.stateNode)
            current22.memoizedProps !== newProps && markUpdate(workInProgress2);
          else {
            if ("string" !== typeof newProps && null === workInProgress2.stateNode)
              throw Error(
                "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue."
              );
            current22 = requiredContext(rootInstanceStackCursor.current);
            renderLanes2 = getHostContext();
            if (popHydrationState(workInProgress2)) {
              current22 = workInProgress2.stateNode;
              renderLanes2 = workInProgress2.memoizedProps;
              type = !didSuspendOrErrorDEV;
              newProps = null;
              nextResource = hydrationParentFiber;
              if (null !== nextResource)
                switch (nextResource.tag) {
                  case 3:
                    type && (type = diffHydratedTextForDevWarnings(
                      current22,
                      renderLanes2,
                      newProps
                    ), null !== type && (buildHydrationDiffNode(workInProgress2, 0).serverProps = type));
                    break;
                  case 27:
                  case 5:
                    newProps = nextResource.memoizedProps, type && (type = diffHydratedTextForDevWarnings(
                      current22,
                      renderLanes2,
                      newProps
                    ), null !== type && (buildHydrationDiffNode(
                      workInProgress2,
                      0
                    ).serverProps = type));
                }
              current22[internalInstanceKey] = workInProgress2;
              current22 = current22.nodeValue === renderLanes2 || null !== newProps && true === newProps.suppressHydrationWarning || checkForUnmatchedText(current22.nodeValue, renderLanes2) ? true : false;
              current22 || throwOnHydrationMismatch(workInProgress2, true);
            } else
              type = renderLanes2.ancestorInfo.current, null != type && validateTextNesting(
                newProps,
                type.tag,
                renderLanes2.ancestorInfo.implicitRootScope
              ), current22 = getOwnerDocumentFromRootContainer(current22).createTextNode(
                newProps
              ), current22[internalInstanceKey] = workInProgress2, workInProgress2.stateNode = current22;
          }
          bubbleProperties(workInProgress2);
          return null;
        case 31:
          renderLanes2 = workInProgress2.memoizedState;
          if (null === current22 || null !== current22.memoizedState) {
            newProps = popHydrationState(workInProgress2);
            if (null !== renderLanes2) {
              if (null === current22) {
                if (!newProps)
                  throw Error(
                    "A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React."
                  );
                current22 = workInProgress2.memoizedState;
                current22 = null !== current22 ? current22.dehydrated : null;
                if (!current22)
                  throw Error(
                    "Expected to have a hydrated activity instance. This error is likely caused by a bug in React. Please file an issue."
                  );
                current22[internalInstanceKey] = workInProgress2;
                bubbleProperties(workInProgress2);
                (workInProgress2.mode & ProfileMode) !== NoMode && null !== renderLanes2 && (current22 = workInProgress2.child, null !== current22 && (workInProgress2.treeBaseDuration -= current22.treeBaseDuration));
              } else
                emitPendingHydrationWarnings(), resetHydrationState(), 0 === (workInProgress2.flags & 128) && (renderLanes2 = workInProgress2.memoizedState = null), workInProgress2.flags |= 4, bubbleProperties(workInProgress2), (workInProgress2.mode & ProfileMode) !== NoMode && null !== renderLanes2 && (current22 = workInProgress2.child, null !== current22 && (workInProgress2.treeBaseDuration -= current22.treeBaseDuration));
              current22 = false;
            } else
              renderLanes2 = upgradeHydrationErrorsToRecoverable(), null !== current22 && null !== current22.memoizedState && (current22.memoizedState.hydrationErrors = renderLanes2), current22 = true;
            if (!current22) {
              if (workInProgress2.flags & 256)
                return popSuspenseHandler(workInProgress2), workInProgress2;
              popSuspenseHandler(workInProgress2);
              return null;
            }
            if (0 !== (workInProgress2.flags & 128))
              throw Error(
                "Client rendering an Activity suspended it again. This is a bug in React."
              );
          }
          bubbleProperties(workInProgress2);
          return null;
        case 13:
          newProps = workInProgress2.memoizedState;
          if (null === current22 || null !== current22.memoizedState && null !== current22.memoizedState.dehydrated) {
            type = newProps;
            nextResource = popHydrationState(workInProgress2);
            if (null !== type && null !== type.dehydrated) {
              if (null === current22) {
                if (!nextResource)
                  throw Error(
                    "A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React."
                  );
                nextResource = workInProgress2.memoizedState;
                nextResource = null !== nextResource ? nextResource.dehydrated : null;
                if (!nextResource)
                  throw Error(
                    "Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue."
                  );
                nextResource[internalInstanceKey] = workInProgress2;
                bubbleProperties(workInProgress2);
                (workInProgress2.mode & ProfileMode) !== NoMode && null !== type && (type = workInProgress2.child, null !== type && (workInProgress2.treeBaseDuration -= type.treeBaseDuration));
              } else
                emitPendingHydrationWarnings(), resetHydrationState(), 0 === (workInProgress2.flags & 128) && (type = workInProgress2.memoizedState = null), workInProgress2.flags |= 4, bubbleProperties(workInProgress2), (workInProgress2.mode & ProfileMode) !== NoMode && null !== type && (type = workInProgress2.child, null !== type && (workInProgress2.treeBaseDuration -= type.treeBaseDuration));
              type = false;
            } else
              type = upgradeHydrationErrorsToRecoverable(), null !== current22 && null !== current22.memoizedState && (current22.memoizedState.hydrationErrors = type), type = true;
            if (!type) {
              if (workInProgress2.flags & 256)
                return popSuspenseHandler(workInProgress2), workInProgress2;
              popSuspenseHandler(workInProgress2);
              return null;
            }
          }
          popSuspenseHandler(workInProgress2);
          if (0 !== (workInProgress2.flags & 128))
            return workInProgress2.lanes = renderLanes2, (workInProgress2.mode & ProfileMode) !== NoMode && transferActualDuration(workInProgress2), workInProgress2;
          renderLanes2 = null !== newProps;
          current22 = null !== current22 && null !== current22.memoizedState;
          renderLanes2 && (newProps = workInProgress2.child, type = null, null !== newProps.alternate && null !== newProps.alternate.memoizedState && null !== newProps.alternate.memoizedState.cachePool && (type = newProps.alternate.memoizedState.cachePool.pool), nextResource = null, null !== newProps.memoizedState && null !== newProps.memoizedState.cachePool && (nextResource = newProps.memoizedState.cachePool.pool), nextResource !== type && (newProps.flags |= 2048));
          renderLanes2 !== current22 && renderLanes2 && (workInProgress2.child.flags |= 8192);
          scheduleRetryEffect(workInProgress2, workInProgress2.updateQueue);
          bubbleProperties(workInProgress2);
          (workInProgress2.mode & ProfileMode) !== NoMode && renderLanes2 && (current22 = workInProgress2.child, null !== current22 && (workInProgress2.treeBaseDuration -= current22.treeBaseDuration));
          return null;
        case 4:
          return popHostContainer(workInProgress2), null === current22 && listenToAllSupportedEvents(
            workInProgress2.stateNode.containerInfo
          ), bubbleProperties(workInProgress2), null;
        case 10:
          return popProvider(workInProgress2.type, workInProgress2), bubbleProperties(workInProgress2), null;
        case 19:
          pop2(suspenseStackCursor, workInProgress2);
          newProps = workInProgress2.memoizedState;
          if (null === newProps) return bubbleProperties(workInProgress2), null;
          type = 0 !== (workInProgress2.flags & 128);
          nextResource = newProps.rendering;
          if (null === nextResource)
            if (type) cutOffTailIfNeeded(newProps, false);
            else {
              if (workInProgressRootExitStatus !== RootInProgress || null !== current22 && 0 !== (current22.flags & 128))
                for (current22 = workInProgress2.child; null !== current22; ) {
                  nextResource = findFirstSuspended(current22);
                  if (null !== nextResource) {
                    workInProgress2.flags |= 128;
                    cutOffTailIfNeeded(newProps, false);
                    current22 = nextResource.updateQueue;
                    workInProgress2.updateQueue = current22;
                    scheduleRetryEffect(workInProgress2, current22);
                    workInProgress2.subtreeFlags = 0;
                    current22 = renderLanes2;
                    for (renderLanes2 = workInProgress2.child; null !== renderLanes2; )
                      resetWorkInProgress(renderLanes2, current22), renderLanes2 = renderLanes2.sibling;
                    push2(
                      suspenseStackCursor,
                      suspenseStackCursor.current & SubtreeSuspenseContextMask | ForceSuspenseFallback,
                      workInProgress2
                    );
                    isHydrating && pushTreeFork(workInProgress2, newProps.treeForkCount);
                    return workInProgress2.child;
                  }
                  current22 = current22.sibling;
                }
              null !== newProps.tail && now$1() > workInProgressRootRenderTargetTime && (workInProgress2.flags |= 128, type = true, cutOffTailIfNeeded(newProps, false), workInProgress2.lanes = 4194304);
            }
          else {
            if (!type)
              if (current22 = findFirstSuspended(nextResource), null !== current22) {
                if (workInProgress2.flags |= 128, type = true, current22 = current22.updateQueue, workInProgress2.updateQueue = current22, scheduleRetryEffect(workInProgress2, current22), cutOffTailIfNeeded(newProps, true), null === newProps.tail && "hidden" === newProps.tailMode && !nextResource.alternate && !isHydrating)
                  return bubbleProperties(workInProgress2), null;
              } else
                2 * now$1() - newProps.renderingStartTime > workInProgressRootRenderTargetTime && 536870912 !== renderLanes2 && (workInProgress2.flags |= 128, type = true, cutOffTailIfNeeded(newProps, false), workInProgress2.lanes = 4194304);
            newProps.isBackwards ? (nextResource.sibling = workInProgress2.child, workInProgress2.child = nextResource) : (current22 = newProps.last, null !== current22 ? current22.sibling = nextResource : workInProgress2.child = nextResource, newProps.last = nextResource);
          }
          if (null !== newProps.tail)
            return current22 = newProps.tail, newProps.rendering = current22, newProps.tail = current22.sibling, newProps.renderingStartTime = now$1(), current22.sibling = null, renderLanes2 = suspenseStackCursor.current, renderLanes2 = type ? renderLanes2 & SubtreeSuspenseContextMask | ForceSuspenseFallback : renderLanes2 & SubtreeSuspenseContextMask, push2(suspenseStackCursor, renderLanes2, workInProgress2), isHydrating && pushTreeFork(workInProgress2, newProps.treeForkCount), current22;
          bubbleProperties(workInProgress2);
          return null;
        case 22:
        case 23:
          return popSuspenseHandler(workInProgress2), popHiddenContext(workInProgress2), newProps = null !== workInProgress2.memoizedState, null !== current22 ? null !== current22.memoizedState !== newProps && (workInProgress2.flags |= 8192) : newProps && (workInProgress2.flags |= 8192), newProps ? 0 !== (renderLanes2 & 536870912) && 0 === (workInProgress2.flags & 128) && (bubbleProperties(workInProgress2), workInProgress2.subtreeFlags & 6 && (workInProgress2.flags |= 8192)) : bubbleProperties(workInProgress2), renderLanes2 = workInProgress2.updateQueue, null !== renderLanes2 && scheduleRetryEffect(workInProgress2, renderLanes2.retryQueue), renderLanes2 = null, null !== current22 && null !== current22.memoizedState && null !== current22.memoizedState.cachePool && (renderLanes2 = current22.memoizedState.cachePool.pool), newProps = null, null !== workInProgress2.memoizedState && null !== workInProgress2.memoizedState.cachePool && (newProps = workInProgress2.memoizedState.cachePool.pool), newProps !== renderLanes2 && (workInProgress2.flags |= 2048), null !== current22 && pop2(resumedCache, workInProgress2), null;
        case 24:
          return renderLanes2 = null, null !== current22 && (renderLanes2 = current22.memoizedState.cache), workInProgress2.memoizedState.cache !== renderLanes2 && (workInProgress2.flags |= 2048), popProvider(CacheContext, workInProgress2), bubbleProperties(workInProgress2), null;
        case 25:
          return null;
        case 30:
          return null;
      }
      throw Error(
        "Unknown unit of work tag (" + workInProgress2.tag + "). This error is likely caused by a bug in React. Please file an issue."
      );
    }
    function unwindWork(current22, workInProgress2) {
      popTreeContext(workInProgress2);
      switch (workInProgress2.tag) {
        case 1:
          return current22 = workInProgress2.flags, current22 & 65536 ? (workInProgress2.flags = current22 & -65537 | 128, (workInProgress2.mode & ProfileMode) !== NoMode && transferActualDuration(workInProgress2), workInProgress2) : null;
        case 3:
          return popProvider(CacheContext, workInProgress2), popHostContainer(workInProgress2), current22 = workInProgress2.flags, 0 !== (current22 & 65536) && 0 === (current22 & 128) ? (workInProgress2.flags = current22 & -65537 | 128, workInProgress2) : null;
        case 26:
        case 27:
        case 5:
          return popHostContext(workInProgress2), null;
        case 31:
          if (null !== workInProgress2.memoizedState) {
            popSuspenseHandler(workInProgress2);
            if (null === workInProgress2.alternate)
              throw Error(
                "Threw in newly mounted dehydrated component. This is likely a bug in React. Please file an issue."
              );
            resetHydrationState();
          }
          current22 = workInProgress2.flags;
          return current22 & 65536 ? (workInProgress2.flags = current22 & -65537 | 128, (workInProgress2.mode & ProfileMode) !== NoMode && transferActualDuration(workInProgress2), workInProgress2) : null;
        case 13:
          popSuspenseHandler(workInProgress2);
          current22 = workInProgress2.memoizedState;
          if (null !== current22 && null !== current22.dehydrated) {
            if (null === workInProgress2.alternate)
              throw Error(
                "Threw in newly mounted dehydrated component. This is likely a bug in React. Please file an issue."
              );
            resetHydrationState();
          }
          current22 = workInProgress2.flags;
          return current22 & 65536 ? (workInProgress2.flags = current22 & -65537 | 128, (workInProgress2.mode & ProfileMode) !== NoMode && transferActualDuration(workInProgress2), workInProgress2) : null;
        case 19:
          return pop2(suspenseStackCursor, workInProgress2), null;
        case 4:
          return popHostContainer(workInProgress2), null;
        case 10:
          return popProvider(workInProgress2.type, workInProgress2), null;
        case 22:
        case 23:
          return popSuspenseHandler(workInProgress2), popHiddenContext(workInProgress2), null !== current22 && pop2(resumedCache, workInProgress2), current22 = workInProgress2.flags, current22 & 65536 ? (workInProgress2.flags = current22 & -65537 | 128, (workInProgress2.mode & ProfileMode) !== NoMode && transferActualDuration(workInProgress2), workInProgress2) : null;
        case 24:
          return popProvider(CacheContext, workInProgress2), null;
        case 25:
          return null;
        default:
          return null;
      }
    }
    function unwindInterruptedWork(current22, interruptedWork) {
      popTreeContext(interruptedWork);
      switch (interruptedWork.tag) {
        case 3:
          popProvider(CacheContext, interruptedWork);
          popHostContainer(interruptedWork);
          break;
        case 26:
        case 27:
        case 5:
          popHostContext(interruptedWork);
          break;
        case 4:
          popHostContainer(interruptedWork);
          break;
        case 31:
          null !== interruptedWork.memoizedState && popSuspenseHandler(interruptedWork);
          break;
        case 13:
          popSuspenseHandler(interruptedWork);
          break;
        case 19:
          pop2(suspenseStackCursor, interruptedWork);
          break;
        case 10:
          popProvider(interruptedWork.type, interruptedWork);
          break;
        case 22:
        case 23:
          popSuspenseHandler(interruptedWork);
          popHiddenContext(interruptedWork);
          null !== current22 && pop2(resumedCache, interruptedWork);
          break;
        case 24:
          popProvider(CacheContext, interruptedWork);
      }
    }
    function shouldProfile(current22) {
      return (current22.mode & ProfileMode) !== NoMode;
    }
    function commitHookLayoutEffects(finishedWork, hookFlags) {
      shouldProfile(finishedWork) ? (startEffectTimer(), commitHookEffectListMount(hookFlags, finishedWork), recordEffectDuration()) : commitHookEffectListMount(hookFlags, finishedWork);
    }
    function commitHookLayoutUnmountEffects(finishedWork, nearestMountedAncestor, hookFlags) {
      shouldProfile(finishedWork) ? (startEffectTimer(), commitHookEffectListUnmount(
        hookFlags,
        finishedWork,
        nearestMountedAncestor
      ), recordEffectDuration()) : commitHookEffectListUnmount(
        hookFlags,
        finishedWork,
        nearestMountedAncestor
      );
    }
    function commitHookEffectListMount(flags, finishedWork) {
      try {
        var updateQueue = finishedWork.updateQueue, lastEffect = null !== updateQueue ? updateQueue.lastEffect : null;
        if (null !== lastEffect) {
          var firstEffect = lastEffect.next;
          updateQueue = firstEffect;
          do {
            if ((updateQueue.tag & flags) === flags && (lastEffect = void 0, (flags & Insertion) !== NoFlags && (isRunningInsertionEffect = true), lastEffect = runWithFiberInDEV(
              finishedWork,
              callCreateInDEV,
              updateQueue
            ), (flags & Insertion) !== NoFlags && (isRunningInsertionEffect = false), void 0 !== lastEffect && "function" !== typeof lastEffect)) {
              var hookName = void 0;
              hookName = 0 !== (updateQueue.tag & Layout) ? "useLayoutEffect" : 0 !== (updateQueue.tag & Insertion) ? "useInsertionEffect" : "useEffect";
              var addendum = void 0;
              addendum = null === lastEffect ? " You returned null. If your effect does not require clean up, return undefined (or nothing)." : "function" === typeof lastEffect.then ? "\n\nIt looks like you wrote " + hookName + "(async () => ...) or returned a Promise. Instead, write the async function inside your effect and call it immediately:\n\n" + hookName + "(() => {\n  async function fetchData() {\n    // You can await here\n    const response = await MyAPI.getData(someId);\n    // ...\n  }\n  fetchData();\n}, [someId]); // Or [] if effect doesn't need props or state\n\nLearn more about data fetching with Hooks: https://react.dev/link/hooks-data-fetching" : " You returned: " + lastEffect;
              runWithFiberInDEV(
                finishedWork,
                function(n2, a2) {
                  console.error(
                    "%s must not return anything besides a function, which is used for clean-up.%s",
                    n2,
                    a2
                  );
                },
                hookName,
                addendum
              );
            }
            updateQueue = updateQueue.next;
          } while (updateQueue !== firstEffect);
        }
      } catch (error2) {
        captureCommitPhaseError(finishedWork, finishedWork.return, error2);
      }
    }
    function commitHookEffectListUnmount(flags, finishedWork, nearestMountedAncestor) {
      try {
        var updateQueue = finishedWork.updateQueue, lastEffect = null !== updateQueue ? updateQueue.lastEffect : null;
        if (null !== lastEffect) {
          var firstEffect = lastEffect.next;
          updateQueue = firstEffect;
          do {
            if ((updateQueue.tag & flags) === flags) {
              var inst = updateQueue.inst, destroy2 = inst.destroy;
              void 0 !== destroy2 && (inst.destroy = void 0, (flags & Insertion) !== NoFlags && (isRunningInsertionEffect = true), lastEffect = finishedWork, runWithFiberInDEV(
                lastEffect,
                callDestroyInDEV,
                lastEffect,
                nearestMountedAncestor,
                destroy2
              ), (flags & Insertion) !== NoFlags && (isRunningInsertionEffect = false));
            }
            updateQueue = updateQueue.next;
          } while (updateQueue !== firstEffect);
        }
      } catch (error2) {
        captureCommitPhaseError(finishedWork, finishedWork.return, error2);
      }
    }
    function commitHookPassiveMountEffects(finishedWork, hookFlags) {
      shouldProfile(finishedWork) ? (startEffectTimer(), commitHookEffectListMount(hookFlags, finishedWork), recordEffectDuration()) : commitHookEffectListMount(hookFlags, finishedWork);
    }
    function commitHookPassiveUnmountEffects(finishedWork, nearestMountedAncestor, hookFlags) {
      shouldProfile(finishedWork) ? (startEffectTimer(), commitHookEffectListUnmount(
        hookFlags,
        finishedWork,
        nearestMountedAncestor
      ), recordEffectDuration()) : commitHookEffectListUnmount(
        hookFlags,
        finishedWork,
        nearestMountedAncestor
      );
    }
    function commitClassCallbacks(finishedWork) {
      var updateQueue = finishedWork.updateQueue;
      if (null !== updateQueue) {
        var instance2 = finishedWork.stateNode;
        finishedWork.type.defaultProps || "ref" in finishedWork.memoizedProps || didWarnAboutReassigningProps || (instance2.props !== finishedWork.memoizedProps && console.error(
          "Expected %s props to match memoized props before processing the update queue. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.",
          getComponentNameFromFiber(finishedWork) || "instance"
        ), instance2.state !== finishedWork.memoizedState && console.error(
          "Expected %s state to match memoized state before processing the update queue. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.",
          getComponentNameFromFiber(finishedWork) || "instance"
        ));
        try {
          runWithFiberInDEV(
            finishedWork,
            commitCallbacks,
            updateQueue,
            instance2
          );
        } catch (error2) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error2);
        }
      }
    }
    function callGetSnapshotBeforeUpdates(instance2, prevProps, prevState) {
      return instance2.getSnapshotBeforeUpdate(prevProps, prevState);
    }
    function commitClassSnapshot(finishedWork, current22) {
      var prevProps = current22.memoizedProps, prevState = current22.memoizedState;
      current22 = finishedWork.stateNode;
      finishedWork.type.defaultProps || "ref" in finishedWork.memoizedProps || didWarnAboutReassigningProps || (current22.props !== finishedWork.memoizedProps && console.error(
        "Expected %s props to match memoized props before getSnapshotBeforeUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.",
        getComponentNameFromFiber(finishedWork) || "instance"
      ), current22.state !== finishedWork.memoizedState && console.error(
        "Expected %s state to match memoized state before getSnapshotBeforeUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.",
        getComponentNameFromFiber(finishedWork) || "instance"
      ));
      try {
        var resolvedPrevProps = resolveClassComponentProps(
          finishedWork.type,
          prevProps
        );
        var snapshot = runWithFiberInDEV(
          finishedWork,
          callGetSnapshotBeforeUpdates,
          current22,
          resolvedPrevProps,
          prevState
        );
        prevProps = didWarnAboutUndefinedSnapshotBeforeUpdate;
        void 0 !== snapshot || prevProps.has(finishedWork.type) || (prevProps.add(finishedWork.type), runWithFiberInDEV(finishedWork, function() {
          console.error(
            "%s.getSnapshotBeforeUpdate(): A snapshot value (or null) must be returned. You have returned undefined.",
            getComponentNameFromFiber(finishedWork)
          );
        }));
        current22.__reactInternalSnapshotBeforeUpdate = snapshot;
      } catch (error2) {
        captureCommitPhaseError(finishedWork, finishedWork.return, error2);
      }
    }
    function safelyCallComponentWillUnmount(current22, nearestMountedAncestor, instance2) {
      instance2.props = resolveClassComponentProps(
        current22.type,
        current22.memoizedProps
      );
      instance2.state = current22.memoizedState;
      shouldProfile(current22) ? (startEffectTimer(), runWithFiberInDEV(
        current22,
        callComponentWillUnmountInDEV,
        current22,
        nearestMountedAncestor,
        instance2
      ), recordEffectDuration()) : runWithFiberInDEV(
        current22,
        callComponentWillUnmountInDEV,
        current22,
        nearestMountedAncestor,
        instance2
      );
    }
    function commitAttachRef(finishedWork) {
      var ref2 = finishedWork.ref;
      if (null !== ref2) {
        switch (finishedWork.tag) {
          case 26:
          case 27:
          case 5:
            var instanceToUse = finishedWork.stateNode;
            break;
          case 30:
            instanceToUse = finishedWork.stateNode;
            break;
          default:
            instanceToUse = finishedWork.stateNode;
        }
        if ("function" === typeof ref2)
          if (shouldProfile(finishedWork))
            try {
              startEffectTimer(), finishedWork.refCleanup = ref2(instanceToUse);
            } finally {
              recordEffectDuration();
            }
          else finishedWork.refCleanup = ref2(instanceToUse);
        else
          "string" === typeof ref2 ? console.error("String refs are no longer supported.") : ref2.hasOwnProperty("current") || console.error(
            "Unexpected ref object provided for %s. Use either a ref-setter function or React.createRef().",
            getComponentNameFromFiber(finishedWork)
          ), ref2.current = instanceToUse;
      }
    }
    function safelyAttachRef(current22, nearestMountedAncestor) {
      try {
        runWithFiberInDEV(current22, commitAttachRef, current22);
      } catch (error2) {
        captureCommitPhaseError(current22, nearestMountedAncestor, error2);
      }
    }
    function safelyDetachRef(current22, nearestMountedAncestor) {
      var ref2 = current22.ref, refCleanup = current22.refCleanup;
      if (null !== ref2)
        if ("function" === typeof refCleanup)
          try {
            if (shouldProfile(current22))
              try {
                startEffectTimer(), runWithFiberInDEV(current22, refCleanup);
              } finally {
                recordEffectDuration(current22);
              }
            else runWithFiberInDEV(current22, refCleanup);
          } catch (error2) {
            captureCommitPhaseError(current22, nearestMountedAncestor, error2);
          } finally {
            current22.refCleanup = null, current22 = current22.alternate, null != current22 && (current22.refCleanup = null);
          }
        else if ("function" === typeof ref2)
          try {
            if (shouldProfile(current22))
              try {
                startEffectTimer(), runWithFiberInDEV(current22, ref2, null);
              } finally {
                recordEffectDuration(current22);
              }
            else runWithFiberInDEV(current22, ref2, null);
          } catch (error$7) {
            captureCommitPhaseError(current22, nearestMountedAncestor, error$7);
          }
        else ref2.current = null;
    }
    function commitProfiler(finishedWork, current22, commitStartTime2, effectDuration) {
      var _finishedWork$memoize = finishedWork.memoizedProps, id2 = _finishedWork$memoize.id, onCommit = _finishedWork$memoize.onCommit;
      _finishedWork$memoize = _finishedWork$memoize.onRender;
      current22 = null === current22 ? "mount" : "update";
      currentUpdateIsNested && (current22 = "nested-update");
      "function" === typeof _finishedWork$memoize && _finishedWork$memoize(
        id2,
        current22,
        finishedWork.actualDuration,
        finishedWork.treeBaseDuration,
        finishedWork.actualStartTime,
        commitStartTime2
      );
      "function" === typeof onCommit && onCommit(id2, current22, effectDuration, commitStartTime2);
    }
    function commitProfilerPostCommitImpl(finishedWork, current22, commitStartTime2, passiveEffectDuration) {
      var _finishedWork$memoize2 = finishedWork.memoizedProps;
      finishedWork = _finishedWork$memoize2.id;
      _finishedWork$memoize2 = _finishedWork$memoize2.onPostCommit;
      current22 = null === current22 ? "mount" : "update";
      currentUpdateIsNested && (current22 = "nested-update");
      "function" === typeof _finishedWork$memoize2 && _finishedWork$memoize2(
        finishedWork,
        current22,
        passiveEffectDuration,
        commitStartTime2
      );
    }
    function commitHostMount(finishedWork) {
      var type = finishedWork.type, props = finishedWork.memoizedProps, instance2 = finishedWork.stateNode;
      try {
        runWithFiberInDEV(
          finishedWork,
          commitMount,
          instance2,
          type,
          props,
          finishedWork
        );
      } catch (error2) {
        captureCommitPhaseError(finishedWork, finishedWork.return, error2);
      }
    }
    function commitHostUpdate(finishedWork, newProps, oldProps) {
      try {
        runWithFiberInDEV(
          finishedWork,
          commitUpdate,
          finishedWork.stateNode,
          finishedWork.type,
          oldProps,
          newProps,
          finishedWork
        );
      } catch (error2) {
        captureCommitPhaseError(finishedWork, finishedWork.return, error2);
      }
    }
    function isHostParent(fiber) {
      return 5 === fiber.tag || 3 === fiber.tag || 26 === fiber.tag || 27 === fiber.tag && isSingletonScope(fiber.type) || 4 === fiber.tag;
    }
    function getHostSibling(fiber) {
      a: for (; ; ) {
        for (; null === fiber.sibling; ) {
          if (null === fiber.return || isHostParent(fiber.return)) return null;
          fiber = fiber.return;
        }
        fiber.sibling.return = fiber.return;
        for (fiber = fiber.sibling; 5 !== fiber.tag && 6 !== fiber.tag && 18 !== fiber.tag; ) {
          if (27 === fiber.tag && isSingletonScope(fiber.type)) continue a;
          if (fiber.flags & 2) continue a;
          if (null === fiber.child || 4 === fiber.tag) continue a;
          else fiber.child.return = fiber, fiber = fiber.child;
        }
        if (!(fiber.flags & 2)) return fiber.stateNode;
      }
    }
    function insertOrAppendPlacementNodeIntoContainer(node2, before, parent) {
      var tag = node2.tag;
      if (5 === tag || 6 === tag)
        node2 = node2.stateNode, before ? (warnForReactChildrenConflict(parent), (9 === parent.nodeType ? parent.body : "HTML" === parent.nodeName ? parent.ownerDocument.body : parent).insertBefore(node2, before)) : (warnForReactChildrenConflict(parent), before = 9 === parent.nodeType ? parent.body : "HTML" === parent.nodeName ? parent.ownerDocument.body : parent, before.appendChild(node2), parent = parent._reactRootContainer, null !== parent && void 0 !== parent || null !== before.onclick || (before.onclick = noop$12));
      else if (4 !== tag && (27 === tag && isSingletonScope(node2.type) && (parent = node2.stateNode, before = null), node2 = node2.child, null !== node2))
        for (insertOrAppendPlacementNodeIntoContainer(node2, before, parent), node2 = node2.sibling; null !== node2; )
          insertOrAppendPlacementNodeIntoContainer(node2, before, parent), node2 = node2.sibling;
    }
    function insertOrAppendPlacementNode(node2, before, parent) {
      var tag = node2.tag;
      if (5 === tag || 6 === tag)
        node2 = node2.stateNode, before ? parent.insertBefore(node2, before) : parent.appendChild(node2);
      else if (4 !== tag && (27 === tag && isSingletonScope(node2.type) && (parent = node2.stateNode), node2 = node2.child, null !== node2))
        for (insertOrAppendPlacementNode(node2, before, parent), node2 = node2.sibling; null !== node2; )
          insertOrAppendPlacementNode(node2, before, parent), node2 = node2.sibling;
    }
    function commitPlacement(finishedWork) {
      for (var hostParentFiber, parentFiber = finishedWork.return; null !== parentFiber; ) {
        if (isHostParent(parentFiber)) {
          hostParentFiber = parentFiber;
          break;
        }
        parentFiber = parentFiber.return;
      }
      if (null == hostParentFiber)
        throw Error(
          "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue."
        );
      switch (hostParentFiber.tag) {
        case 27:
          hostParentFiber = hostParentFiber.stateNode;
          parentFiber = getHostSibling(finishedWork);
          insertOrAppendPlacementNode(
            finishedWork,
            parentFiber,
            hostParentFiber
          );
          break;
        case 5:
          parentFiber = hostParentFiber.stateNode;
          hostParentFiber.flags & 32 && (resetTextContent(parentFiber), hostParentFiber.flags &= -33);
          hostParentFiber = getHostSibling(finishedWork);
          insertOrAppendPlacementNode(
            finishedWork,
            hostParentFiber,
            parentFiber
          );
          break;
        case 3:
        case 4:
          hostParentFiber = hostParentFiber.stateNode.containerInfo;
          parentFiber = getHostSibling(finishedWork);
          insertOrAppendPlacementNodeIntoContainer(
            finishedWork,
            parentFiber,
            hostParentFiber
          );
          break;
        default:
          throw Error(
            "Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue."
          );
      }
    }
    function commitHostSingletonAcquisition(finishedWork) {
      var singleton = finishedWork.stateNode, props = finishedWork.memoizedProps;
      try {
        runWithFiberInDEV(
          finishedWork,
          acquireSingletonInstance,
          finishedWork.type,
          props,
          singleton,
          finishedWork
        );
      } catch (error2) {
        captureCommitPhaseError(finishedWork, finishedWork.return, error2);
      }
    }
    function isHydratingParent(current22, finishedWork) {
      return 31 === finishedWork.tag ? (finishedWork = finishedWork.memoizedState, null !== current22.memoizedState && null === finishedWork) : 13 === finishedWork.tag ? (current22 = current22.memoizedState, finishedWork = finishedWork.memoizedState, null !== current22 && null !== current22.dehydrated && (null === finishedWork || null === finishedWork.dehydrated)) : 3 === finishedWork.tag ? current22.memoizedState.isDehydrated && 0 === (finishedWork.flags & 256) : false;
    }
    function commitBeforeMutationEffects(root22, firstChild) {
      root22 = root22.containerInfo;
      eventsEnabled = _enabled;
      root22 = getActiveElementDeep(root22);
      if (hasSelectionCapabilities(root22)) {
        if ("selectionStart" in root22)
          var JSCompiler_temp = {
            start: root22.selectionStart,
            end: root22.selectionEnd
          };
        else
          a: {
            JSCompiler_temp = (JSCompiler_temp = root22.ownerDocument) && JSCompiler_temp.defaultView || window;
            var selection = JSCompiler_temp.getSelection && JSCompiler_temp.getSelection();
            if (selection && 0 !== selection.rangeCount) {
              JSCompiler_temp = selection.anchorNode;
              var anchorOffset = selection.anchorOffset, focusNode = selection.focusNode;
              selection = selection.focusOffset;
              try {
                JSCompiler_temp.nodeType, focusNode.nodeType;
              } catch (e$2) {
                JSCompiler_temp = null;
                break a;
              }
              var length2 = 0, start2 = -1, end2 = -1, indexWithinAnchor = 0, indexWithinFocus = 0, node2 = root22, parentNode = null;
              b: for (; ; ) {
                for (var next; ; ) {
                  node2 !== JSCompiler_temp || 0 !== anchorOffset && 3 !== node2.nodeType || (start2 = length2 + anchorOffset);
                  node2 !== focusNode || 0 !== selection && 3 !== node2.nodeType || (end2 = length2 + selection);
                  3 === node2.nodeType && (length2 += node2.nodeValue.length);
                  if (null === (next = node2.firstChild)) break;
                  parentNode = node2;
                  node2 = next;
                }
                for (; ; ) {
                  if (node2 === root22) break b;
                  parentNode === JSCompiler_temp && ++indexWithinAnchor === anchorOffset && (start2 = length2);
                  parentNode === focusNode && ++indexWithinFocus === selection && (end2 = length2);
                  if (null !== (next = node2.nextSibling)) break;
                  node2 = parentNode;
                  parentNode = node2.parentNode;
                }
                node2 = next;
              }
              JSCompiler_temp = -1 === start2 || -1 === end2 ? null : { start: start2, end: end2 };
            } else JSCompiler_temp = null;
          }
        JSCompiler_temp = JSCompiler_temp || { start: 0, end: 0 };
      } else JSCompiler_temp = null;
      selectionInformation = {
        focusedElem: root22,
        selectionRange: JSCompiler_temp
      };
      _enabled = false;
      for (nextEffect = firstChild; null !== nextEffect; )
        if (firstChild = nextEffect, root22 = firstChild.child, 0 !== (firstChild.subtreeFlags & 1028) && null !== root22)
          root22.return = firstChild, nextEffect = root22;
        else
          for (; null !== nextEffect; ) {
            root22 = firstChild = nextEffect;
            JSCompiler_temp = root22.alternate;
            anchorOffset = root22.flags;
            switch (root22.tag) {
              case 0:
                if (0 !== (anchorOffset & 4) && (root22 = root22.updateQueue, root22 = null !== root22 ? root22.events : null, null !== root22))
                  for (JSCompiler_temp = 0; JSCompiler_temp < root22.length; JSCompiler_temp++)
                    anchorOffset = root22[JSCompiler_temp], anchorOffset.ref.impl = anchorOffset.nextImpl;
                break;
              case 11:
              case 15:
                break;
              case 1:
                0 !== (anchorOffset & 1024) && null !== JSCompiler_temp && commitClassSnapshot(root22, JSCompiler_temp);
                break;
              case 3:
                if (0 !== (anchorOffset & 1024)) {
                  if (root22 = root22.stateNode.containerInfo, JSCompiler_temp = root22.nodeType, 9 === JSCompiler_temp)
                    clearContainerSparingly(root22);
                  else if (1 === JSCompiler_temp)
                    switch (root22.nodeName) {
                      case "HEAD":
                      case "HTML":
                      case "BODY":
                        clearContainerSparingly(root22);
                        break;
                      default:
                        root22.textContent = "";
                    }
                }
                break;
              case 5:
              case 26:
              case 27:
              case 6:
              case 4:
              case 17:
                break;
              default:
                if (0 !== (anchorOffset & 1024))
                  throw Error(
                    "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue."
                  );
            }
            root22 = firstChild.sibling;
            if (null !== root22) {
              root22.return = firstChild.return;
              nextEffect = root22;
              break;
            }
            nextEffect = firstChild.return;
          }
    }
    function commitLayoutEffectOnFiber(finishedRoot, current22, finishedWork) {
      var prevEffectStart = pushComponentEffectStart(), prevEffectDuration = pushComponentEffectDuration(), prevEffectErrors = pushComponentEffectErrors(), prevEffectDidSpawnUpdate = pushComponentEffectDidSpawnUpdate(), flags = finishedWork.flags;
      switch (finishedWork.tag) {
        case 0:
        case 11:
        case 15:
          recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
          flags & 4 && commitHookLayoutEffects(finishedWork, Layout | HasEffect);
          break;
        case 1:
          recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
          if (flags & 4)
            if (finishedRoot = finishedWork.stateNode, null === current22)
              finishedWork.type.defaultProps || "ref" in finishedWork.memoizedProps || didWarnAboutReassigningProps || (finishedRoot.props !== finishedWork.memoizedProps && console.error(
                "Expected %s props to match memoized props before componentDidMount. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.",
                getComponentNameFromFiber(finishedWork) || "instance"
              ), finishedRoot.state !== finishedWork.memoizedState && console.error(
                "Expected %s state to match memoized state before componentDidMount. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.",
                getComponentNameFromFiber(finishedWork) || "instance"
              )), shouldProfile(finishedWork) ? (startEffectTimer(), runWithFiberInDEV(
                finishedWork,
                callComponentDidMountInDEV,
                finishedWork,
                finishedRoot
              ), recordEffectDuration()) : runWithFiberInDEV(
                finishedWork,
                callComponentDidMountInDEV,
                finishedWork,
                finishedRoot
              );
            else {
              var prevProps = resolveClassComponentProps(
                finishedWork.type,
                current22.memoizedProps
              );
              current22 = current22.memoizedState;
              finishedWork.type.defaultProps || "ref" in finishedWork.memoizedProps || didWarnAboutReassigningProps || (finishedRoot.props !== finishedWork.memoizedProps && console.error(
                "Expected %s props to match memoized props before componentDidUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.",
                getComponentNameFromFiber(finishedWork) || "instance"
              ), finishedRoot.state !== finishedWork.memoizedState && console.error(
                "Expected %s state to match memoized state before componentDidUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.",
                getComponentNameFromFiber(finishedWork) || "instance"
              ));
              shouldProfile(finishedWork) ? (startEffectTimer(), runWithFiberInDEV(
                finishedWork,
                callComponentDidUpdateInDEV,
                finishedWork,
                finishedRoot,
                prevProps,
                current22,
                finishedRoot.__reactInternalSnapshotBeforeUpdate
              ), recordEffectDuration()) : runWithFiberInDEV(
                finishedWork,
                callComponentDidUpdateInDEV,
                finishedWork,
                finishedRoot,
                prevProps,
                current22,
                finishedRoot.__reactInternalSnapshotBeforeUpdate
              );
            }
          flags & 64 && commitClassCallbacks(finishedWork);
          flags & 512 && safelyAttachRef(finishedWork, finishedWork.return);
          break;
        case 3:
          current22 = pushNestedEffectDurations();
          recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
          if (flags & 64 && (flags = finishedWork.updateQueue, null !== flags)) {
            prevProps = null;
            if (null !== finishedWork.child)
              switch (finishedWork.child.tag) {
                case 27:
                case 5:
                  prevProps = finishedWork.child.stateNode;
                  break;
                case 1:
                  prevProps = finishedWork.child.stateNode;
              }
            try {
              runWithFiberInDEV(
                finishedWork,
                commitCallbacks,
                flags,
                prevProps
              );
            } catch (error2) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error2);
            }
          }
          finishedRoot.effectDuration += popNestedEffectDurations(current22);
          break;
        case 27:
          null === current22 && flags & 4 && commitHostSingletonAcquisition(finishedWork);
        case 26:
        case 5:
          recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
          if (null === current22) {
            if (flags & 4) commitHostMount(finishedWork);
            else if (flags & 64) {
              finishedRoot = finishedWork.type;
              current22 = finishedWork.memoizedProps;
              prevProps = finishedWork.stateNode;
              try {
                runWithFiberInDEV(
                  finishedWork,
                  commitHydratedInstance,
                  prevProps,
                  finishedRoot,
                  current22,
                  finishedWork
                );
              } catch (error2) {
                captureCommitPhaseError(
                  finishedWork,
                  finishedWork.return,
                  error2
                );
              }
            }
          }
          flags & 512 && safelyAttachRef(finishedWork, finishedWork.return);
          break;
        case 12:
          if (flags & 4) {
            flags = pushNestedEffectDurations();
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            finishedRoot = finishedWork.stateNode;
            finishedRoot.effectDuration += bubbleNestedEffectDurations(flags);
            try {
              runWithFiberInDEV(
                finishedWork,
                commitProfiler,
                finishedWork,
                current22,
                commitStartTime,
                finishedRoot.effectDuration
              );
            } catch (error2) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error2);
            }
          } else recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
          break;
        case 31:
          recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
          flags & 4 && commitActivityHydrationCallbacks(finishedRoot, finishedWork);
          break;
        case 13:
          recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
          flags & 4 && commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
          flags & 64 && (finishedRoot = finishedWork.memoizedState, null !== finishedRoot && (finishedRoot = finishedRoot.dehydrated, null !== finishedRoot && (flags = retryDehydratedSuspenseBoundary.bind(
            null,
            finishedWork
          ), registerSuspenseInstanceRetry(finishedRoot, flags))));
          break;
        case 22:
          flags = null !== finishedWork.memoizedState || offscreenSubtreeIsHidden;
          if (!flags) {
            current22 = null !== current22 && null !== current22.memoizedState || offscreenSubtreeWasHidden;
            prevProps = offscreenSubtreeIsHidden;
            var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
            offscreenSubtreeIsHidden = flags;
            (offscreenSubtreeWasHidden = current22) && !prevOffscreenSubtreeWasHidden ? (recursivelyTraverseReappearLayoutEffects(
              finishedRoot,
              finishedWork,
              0 !== (finishedWork.subtreeFlags & 8772)
            ), (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && 0.05 < componentEffectEndTime - componentEffectStartTime && logComponentReappeared(
              finishedWork,
              componentEffectStartTime,
              componentEffectEndTime
            )) : recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            offscreenSubtreeIsHidden = prevProps;
            offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
          }
          break;
        case 30:
          break;
        default:
          recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
      }
      (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && ((componentEffectSpawnedUpdate || 0.05 < componentEffectDuration) && logComponentEffect(
        finishedWork,
        componentEffectStartTime,
        componentEffectEndTime,
        componentEffectDuration,
        componentEffectErrors
      ), null === finishedWork.alternate && null !== finishedWork.return && null !== finishedWork.return.alternate && 0.05 < componentEffectEndTime - componentEffectStartTime && (isHydratingParent(
        finishedWork.return.alternate,
        finishedWork.return
      ) || logComponentTrigger(
        finishedWork,
        componentEffectStartTime,
        componentEffectEndTime,
        "Mount"
      )));
      popComponentEffectStart(prevEffectStart);
      popComponentEffectDuration(prevEffectDuration);
      componentEffectErrors = prevEffectErrors;
      componentEffectSpawnedUpdate = prevEffectDidSpawnUpdate;
    }
    function detachFiberAfterEffects(fiber) {
      var alternate = fiber.alternate;
      null !== alternate && (fiber.alternate = null, detachFiberAfterEffects(alternate));
      fiber.child = null;
      fiber.deletions = null;
      fiber.sibling = null;
      5 === fiber.tag && (alternate = fiber.stateNode, null !== alternate && detachDeletedInstance(alternate));
      fiber.stateNode = null;
      fiber._debugOwner = null;
      fiber.return = null;
      fiber.dependencies = null;
      fiber.memoizedProps = null;
      fiber.memoizedState = null;
      fiber.pendingProps = null;
      fiber.stateNode = null;
      fiber.updateQueue = null;
    }
    function recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, parent) {
      for (parent = parent.child; null !== parent; )
        commitDeletionEffectsOnFiber(
          finishedRoot,
          nearestMountedAncestor,
          parent
        ), parent = parent.sibling;
    }
    function commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, deletedFiber) {
      if (injectedHook && "function" === typeof injectedHook.onCommitFiberUnmount)
        try {
          injectedHook.onCommitFiberUnmount(rendererID, deletedFiber);
        } catch (err) {
          hasLoggedError || (hasLoggedError = true, console.error(
            "React instrumentation encountered an error: %o",
            err
          ));
        }
      var prevEffectStart = pushComponentEffectStart(), prevEffectDuration = pushComponentEffectDuration(), prevEffectErrors = pushComponentEffectErrors(), prevEffectDidSpawnUpdate = pushComponentEffectDidSpawnUpdate();
      switch (deletedFiber.tag) {
        case 26:
          offscreenSubtreeWasHidden || safelyDetachRef(deletedFiber, nearestMountedAncestor);
          recursivelyTraverseDeletionEffects(
            finishedRoot,
            nearestMountedAncestor,
            deletedFiber
          );
          deletedFiber.memoizedState ? deletedFiber.memoizedState.count-- : deletedFiber.stateNode && (finishedRoot = deletedFiber.stateNode, finishedRoot.parentNode.removeChild(finishedRoot));
          break;
        case 27:
          offscreenSubtreeWasHidden || safelyDetachRef(deletedFiber, nearestMountedAncestor);
          var prevHostParent = hostParent, prevHostParentIsContainer = hostParentIsContainer;
          isSingletonScope(deletedFiber.type) && (hostParent = deletedFiber.stateNode, hostParentIsContainer = false);
          recursivelyTraverseDeletionEffects(
            finishedRoot,
            nearestMountedAncestor,
            deletedFiber
          );
          runWithFiberInDEV(
            deletedFiber,
            releaseSingletonInstance,
            deletedFiber.stateNode
          );
          hostParent = prevHostParent;
          hostParentIsContainer = prevHostParentIsContainer;
          break;
        case 5:
          offscreenSubtreeWasHidden || safelyDetachRef(deletedFiber, nearestMountedAncestor);
        case 6:
          prevHostParent = hostParent;
          prevHostParentIsContainer = hostParentIsContainer;
          hostParent = null;
          recursivelyTraverseDeletionEffects(
            finishedRoot,
            nearestMountedAncestor,
            deletedFiber
          );
          hostParent = prevHostParent;
          hostParentIsContainer = prevHostParentIsContainer;
          if (null !== hostParent)
            if (hostParentIsContainer)
              try {
                runWithFiberInDEV(
                  deletedFiber,
                  removeChildFromContainer,
                  hostParent,
                  deletedFiber.stateNode
                );
              } catch (error2) {
                captureCommitPhaseError(
                  deletedFiber,
                  nearestMountedAncestor,
                  error2
                );
              }
            else
              try {
                runWithFiberInDEV(
                  deletedFiber,
                  removeChild,
                  hostParent,
                  deletedFiber.stateNode
                );
              } catch (error2) {
                captureCommitPhaseError(
                  deletedFiber,
                  nearestMountedAncestor,
                  error2
                );
              }
          break;
        case 18:
          null !== hostParent && (hostParentIsContainer ? (finishedRoot = hostParent, clearHydrationBoundary(
            9 === finishedRoot.nodeType ? finishedRoot.body : "HTML" === finishedRoot.nodeName ? finishedRoot.ownerDocument.body : finishedRoot,
            deletedFiber.stateNode
          ), retryIfBlockedOn(finishedRoot)) : clearHydrationBoundary(hostParent, deletedFiber.stateNode));
          break;
        case 4:
          prevHostParent = hostParent;
          prevHostParentIsContainer = hostParentIsContainer;
          hostParent = deletedFiber.stateNode.containerInfo;
          hostParentIsContainer = true;
          recursivelyTraverseDeletionEffects(
            finishedRoot,
            nearestMountedAncestor,
            deletedFiber
          );
          hostParent = prevHostParent;
          hostParentIsContainer = prevHostParentIsContainer;
          break;
        case 0:
        case 11:
        case 14:
        case 15:
          commitHookEffectListUnmount(
            Insertion,
            deletedFiber,
            nearestMountedAncestor
          );
          offscreenSubtreeWasHidden || commitHookLayoutUnmountEffects(
            deletedFiber,
            nearestMountedAncestor,
            Layout
          );
          recursivelyTraverseDeletionEffects(
            finishedRoot,
            nearestMountedAncestor,
            deletedFiber
          );
          break;
        case 1:
          offscreenSubtreeWasHidden || (safelyDetachRef(deletedFiber, nearestMountedAncestor), prevHostParent = deletedFiber.stateNode, "function" === typeof prevHostParent.componentWillUnmount && safelyCallComponentWillUnmount(
            deletedFiber,
            nearestMountedAncestor,
            prevHostParent
          ));
          recursivelyTraverseDeletionEffects(
            finishedRoot,
            nearestMountedAncestor,
            deletedFiber
          );
          break;
        case 21:
          recursivelyTraverseDeletionEffects(
            finishedRoot,
            nearestMountedAncestor,
            deletedFiber
          );
          break;
        case 22:
          offscreenSubtreeWasHidden = (prevHostParent = offscreenSubtreeWasHidden) || null !== deletedFiber.memoizedState;
          recursivelyTraverseDeletionEffects(
            finishedRoot,
            nearestMountedAncestor,
            deletedFiber
          );
          offscreenSubtreeWasHidden = prevHostParent;
          break;
        default:
          recursivelyTraverseDeletionEffects(
            finishedRoot,
            nearestMountedAncestor,
            deletedFiber
          );
      }
      (deletedFiber.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && (componentEffectSpawnedUpdate || 0.05 < componentEffectDuration) && logComponentEffect(
        deletedFiber,
        componentEffectStartTime,
        componentEffectEndTime,
        componentEffectDuration,
        componentEffectErrors
      );
      popComponentEffectStart(prevEffectStart);
      popComponentEffectDuration(prevEffectDuration);
      componentEffectErrors = prevEffectErrors;
      componentEffectSpawnedUpdate = prevEffectDidSpawnUpdate;
    }
    function commitActivityHydrationCallbacks(finishedRoot, finishedWork) {
      if (null === finishedWork.memoizedState && (finishedRoot = finishedWork.alternate, null !== finishedRoot && (finishedRoot = finishedRoot.memoizedState, null !== finishedRoot))) {
        finishedRoot = finishedRoot.dehydrated;
        try {
          runWithFiberInDEV(
            finishedWork,
            commitHydratedActivityInstance,
            finishedRoot
          );
        } catch (error2) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error2);
        }
      }
    }
    function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) {
      if (null === finishedWork.memoizedState && (finishedRoot = finishedWork.alternate, null !== finishedRoot && (finishedRoot = finishedRoot.memoizedState, null !== finishedRoot && (finishedRoot = finishedRoot.dehydrated, null !== finishedRoot))))
        try {
          runWithFiberInDEV(
            finishedWork,
            commitHydratedSuspenseInstance,
            finishedRoot
          );
        } catch (error2) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error2);
        }
    }
    function getRetryCache(finishedWork) {
      switch (finishedWork.tag) {
        case 31:
        case 13:
        case 19:
          var retryCache = finishedWork.stateNode;
          null === retryCache && (retryCache = finishedWork.stateNode = new PossiblyWeakSet());
          return retryCache;
        case 22:
          return finishedWork = finishedWork.stateNode, retryCache = finishedWork._retryCache, null === retryCache && (retryCache = finishedWork._retryCache = new PossiblyWeakSet()), retryCache;
        default:
          throw Error(
            "Unexpected Suspense handler tag (" + finishedWork.tag + "). This is a bug in React."
          );
      }
    }
    function attachSuspenseRetryListeners(finishedWork, wakeables) {
      var retryCache = getRetryCache(finishedWork);
      wakeables.forEach(function(wakeable) {
        if (!retryCache.has(wakeable)) {
          retryCache.add(wakeable);
          if (isDevToolsPresent)
            if (null !== inProgressLanes && null !== inProgressRoot)
              restorePendingUpdaters(inProgressRoot, inProgressLanes);
            else
              throw Error(
                "Expected finished root and lanes to be set. This is a bug in React."
              );
          var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable);
          wakeable.then(retry, retry);
        }
      });
    }
    function recursivelyTraverseMutationEffects(root$jscomp$0, parentFiber) {
      var deletions = parentFiber.deletions;
      if (null !== deletions)
        for (var i2 = 0; i2 < deletions.length; i2++) {
          var root22 = root$jscomp$0, returnFiber = parentFiber, deletedFiber = deletions[i2], prevEffectStart = pushComponentEffectStart(), parent = returnFiber;
          a: for (; null !== parent; ) {
            switch (parent.tag) {
              case 27:
                if (isSingletonScope(parent.type)) {
                  hostParent = parent.stateNode;
                  hostParentIsContainer = false;
                  break a;
                }
                break;
              case 5:
                hostParent = parent.stateNode;
                hostParentIsContainer = false;
                break a;
              case 3:
              case 4:
                hostParent = parent.stateNode.containerInfo;
                hostParentIsContainer = true;
                break a;
            }
            parent = parent.return;
          }
          if (null === hostParent)
            throw Error(
              "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue."
            );
          commitDeletionEffectsOnFiber(root22, returnFiber, deletedFiber);
          hostParent = null;
          hostParentIsContainer = false;
          (deletedFiber.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && 0.05 < componentEffectEndTime - componentEffectStartTime && logComponentTrigger(
            deletedFiber,
            componentEffectStartTime,
            componentEffectEndTime,
            "Unmount"
          );
          popComponentEffectStart(prevEffectStart);
          root22 = deletedFiber;
          returnFiber = root22.alternate;
          null !== returnFiber && (returnFiber.return = null);
          root22.return = null;
        }
      if (parentFiber.subtreeFlags & 13886)
        for (parentFiber = parentFiber.child; null !== parentFiber; )
          commitMutationEffectsOnFiber(parentFiber, root$jscomp$0), parentFiber = parentFiber.sibling;
    }
    function commitMutationEffectsOnFiber(finishedWork, root22) {
      var prevEffectStart = pushComponentEffectStart(), prevEffectDuration = pushComponentEffectDuration(), prevEffectErrors = pushComponentEffectErrors(), prevEffectDidSpawnUpdate = pushComponentEffectDidSpawnUpdate(), current22 = finishedWork.alternate, flags = finishedWork.flags;
      switch (finishedWork.tag) {
        case 0:
        case 11:
        case 14:
        case 15:
          recursivelyTraverseMutationEffects(root22, finishedWork);
          commitReconciliationEffects(finishedWork);
          flags & 4 && (commitHookEffectListUnmount(
            Insertion | HasEffect,
            finishedWork,
            finishedWork.return
          ), commitHookEffectListMount(Insertion | HasEffect, finishedWork), commitHookLayoutUnmountEffects(
            finishedWork,
            finishedWork.return,
            Layout | HasEffect
          ));
          break;
        case 1:
          recursivelyTraverseMutationEffects(root22, finishedWork);
          commitReconciliationEffects(finishedWork);
          flags & 512 && (offscreenSubtreeWasHidden || null === current22 || safelyDetachRef(current22, current22.return));
          if (flags & 64 && offscreenSubtreeIsHidden && (flags = finishedWork.updateQueue, null !== flags && (current22 = flags.callbacks, null !== current22))) {
            var existingHiddenCallbacks = flags.shared.hiddenCallbacks;
            flags.shared.hiddenCallbacks = null === existingHiddenCallbacks ? current22 : existingHiddenCallbacks.concat(current22);
          }
          break;
        case 26:
          existingHiddenCallbacks = currentHoistableRoot;
          recursivelyTraverseMutationEffects(root22, finishedWork);
          commitReconciliationEffects(finishedWork);
          flags & 512 && (offscreenSubtreeWasHidden || null === current22 || safelyDetachRef(current22, current22.return));
          if (flags & 4) {
            var currentResource = null !== current22 ? current22.memoizedState : null;
            flags = finishedWork.memoizedState;
            if (null === current22)
              if (null === flags)
                if (null === finishedWork.stateNode) {
                  a: {
                    flags = finishedWork.type;
                    current22 = finishedWork.memoizedProps;
                    existingHiddenCallbacks = existingHiddenCallbacks.ownerDocument || existingHiddenCallbacks;
                    b: switch (flags) {
                      case "title":
                        currentResource = existingHiddenCallbacks.getElementsByTagName(
                          "title"
                        )[0];
                        if (!currentResource || currentResource[internalHoistableMarker] || currentResource[internalInstanceKey] || currentResource.namespaceURI === SVG_NAMESPACE || currentResource.hasAttribute("itemprop"))
                          currentResource = existingHiddenCallbacks.createElement(flags), existingHiddenCallbacks.head.insertBefore(
                            currentResource,
                            existingHiddenCallbacks.querySelector(
                              "head > title"
                            )
                          );
                        setInitialProperties(currentResource, flags, current22);
                        currentResource[internalInstanceKey] = finishedWork;
                        markNodeAsHoistable(currentResource);
                        flags = currentResource;
                        break a;
                      case "link":
                        var maybeNodes = getHydratableHoistableCache(
                          "link",
                          "href",
                          existingHiddenCallbacks
                        ).get(flags + (current22.href || ""));
                        if (maybeNodes) {
                          for (var i2 = 0; i2 < maybeNodes.length; i2++)
                            if (currentResource = maybeNodes[i2], currentResource.getAttribute("href") === (null == current22.href || "" === current22.href ? null : current22.href) && currentResource.getAttribute("rel") === (null == current22.rel ? null : current22.rel) && currentResource.getAttribute("title") === (null == current22.title ? null : current22.title) && currentResource.getAttribute("crossorigin") === (null == current22.crossOrigin ? null : current22.crossOrigin)) {
                              maybeNodes.splice(i2, 1);
                              break b;
                            }
                        }
                        currentResource = existingHiddenCallbacks.createElement(flags);
                        setInitialProperties(currentResource, flags, current22);
                        existingHiddenCallbacks.head.appendChild(
                          currentResource
                        );
                        break;
                      case "meta":
                        if (maybeNodes = getHydratableHoistableCache(
                          "meta",
                          "content",
                          existingHiddenCallbacks
                        ).get(flags + (current22.content || ""))) {
                          for (i2 = 0; i2 < maybeNodes.length; i2++)
                            if (currentResource = maybeNodes[i2], checkAttributeStringCoercion(
                              current22.content,
                              "content"
                            ), currentResource.getAttribute("content") === (null == current22.content ? null : "" + current22.content) && currentResource.getAttribute("name") === (null == current22.name ? null : current22.name) && currentResource.getAttribute("property") === (null == current22.property ? null : current22.property) && currentResource.getAttribute("http-equiv") === (null == current22.httpEquiv ? null : current22.httpEquiv) && currentResource.getAttribute("charset") === (null == current22.charSet ? null : current22.charSet)) {
                              maybeNodes.splice(i2, 1);
                              break b;
                            }
                        }
                        currentResource = existingHiddenCallbacks.createElement(flags);
                        setInitialProperties(currentResource, flags, current22);
                        existingHiddenCallbacks.head.appendChild(
                          currentResource
                        );
                        break;
                      default:
                        throw Error(
                          'getNodesForType encountered a type it did not expect: "' + flags + '". This is a bug in React.'
                        );
                    }
                    currentResource[internalInstanceKey] = finishedWork;
                    markNodeAsHoistable(currentResource);
                    flags = currentResource;
                  }
                  finishedWork.stateNode = flags;
                } else
                  mountHoistable(
                    existingHiddenCallbacks,
                    finishedWork.type,
                    finishedWork.stateNode
                  );
              else
                finishedWork.stateNode = acquireResource(
                  existingHiddenCallbacks,
                  flags,
                  finishedWork.memoizedProps
                );
            else
              currentResource !== flags ? (null === currentResource ? null !== current22.stateNode && (current22 = current22.stateNode, current22.parentNode.removeChild(current22)) : currentResource.count--, null === flags ? mountHoistable(
                existingHiddenCallbacks,
                finishedWork.type,
                finishedWork.stateNode
              ) : acquireResource(
                existingHiddenCallbacks,
                flags,
                finishedWork.memoizedProps
              )) : null === flags && null !== finishedWork.stateNode && commitHostUpdate(
                finishedWork,
                finishedWork.memoizedProps,
                current22.memoizedProps
              );
          }
          break;
        case 27:
          recursivelyTraverseMutationEffects(root22, finishedWork);
          commitReconciliationEffects(finishedWork);
          flags & 512 && (offscreenSubtreeWasHidden || null === current22 || safelyDetachRef(current22, current22.return));
          null !== current22 && flags & 4 && commitHostUpdate(
            finishedWork,
            finishedWork.memoizedProps,
            current22.memoizedProps
          );
          break;
        case 5:
          recursivelyTraverseMutationEffects(root22, finishedWork);
          commitReconciliationEffects(finishedWork);
          flags & 512 && (offscreenSubtreeWasHidden || null === current22 || safelyDetachRef(current22, current22.return));
          if (finishedWork.flags & 32) {
            existingHiddenCallbacks = finishedWork.stateNode;
            try {
              runWithFiberInDEV(
                finishedWork,
                resetTextContent,
                existingHiddenCallbacks
              );
            } catch (error2) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error2);
            }
          }
          flags & 4 && null != finishedWork.stateNode && (existingHiddenCallbacks = finishedWork.memoizedProps, commitHostUpdate(
            finishedWork,
            existingHiddenCallbacks,
            null !== current22 ? current22.memoizedProps : existingHiddenCallbacks
          ));
          flags & 1024 && (needsFormReset = true, "form" !== finishedWork.type && console.error(
            "Unexpected host component type. Expected a form. This is a bug in React."
          ));
          break;
        case 6:
          recursivelyTraverseMutationEffects(root22, finishedWork);
          commitReconciliationEffects(finishedWork);
          if (flags & 4) {
            if (null === finishedWork.stateNode)
              throw Error(
                "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue."
              );
            flags = finishedWork.memoizedProps;
            current22 = null !== current22 ? current22.memoizedProps : flags;
            existingHiddenCallbacks = finishedWork.stateNode;
            try {
              runWithFiberInDEV(
                finishedWork,
                commitTextUpdate,
                existingHiddenCallbacks,
                current22,
                flags
              );
            } catch (error2) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error2);
            }
          }
          break;
        case 3:
          existingHiddenCallbacks = pushNestedEffectDurations();
          tagCaches = null;
          currentResource = currentHoistableRoot;
          currentHoistableRoot = getHoistableRoot(root22.containerInfo);
          recursivelyTraverseMutationEffects(root22, finishedWork);
          currentHoistableRoot = currentResource;
          commitReconciliationEffects(finishedWork);
          if (flags & 4 && null !== current22 && current22.memoizedState.isDehydrated)
            try {
              runWithFiberInDEV(
                finishedWork,
                commitHydratedContainer,
                root22.containerInfo
              );
            } catch (error2) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error2);
            }
          needsFormReset && (needsFormReset = false, recursivelyResetForms(finishedWork));
          root22.effectDuration += popNestedEffectDurations(
            existingHiddenCallbacks
          );
          break;
        case 4:
          flags = currentHoistableRoot;
          currentHoistableRoot = getHoistableRoot(
            finishedWork.stateNode.containerInfo
          );
          recursivelyTraverseMutationEffects(root22, finishedWork);
          commitReconciliationEffects(finishedWork);
          currentHoistableRoot = flags;
          break;
        case 12:
          flags = pushNestedEffectDurations();
          recursivelyTraverseMutationEffects(root22, finishedWork);
          commitReconciliationEffects(finishedWork);
          finishedWork.stateNode.effectDuration += bubbleNestedEffectDurations(flags);
          break;
        case 31:
          recursivelyTraverseMutationEffects(root22, finishedWork);
          commitReconciliationEffects(finishedWork);
          flags & 4 && (flags = finishedWork.updateQueue, null !== flags && (finishedWork.updateQueue = null, attachSuspenseRetryListeners(finishedWork, flags)));
          break;
        case 13:
          recursivelyTraverseMutationEffects(root22, finishedWork);
          commitReconciliationEffects(finishedWork);
          finishedWork.child.flags & 8192 && null !== finishedWork.memoizedState !== (null !== current22 && null !== current22.memoizedState) && (globalMostRecentFallbackTime = now$1());
          flags & 4 && (flags = finishedWork.updateQueue, null !== flags && (finishedWork.updateQueue = null, attachSuspenseRetryListeners(finishedWork, flags)));
          break;
        case 22:
          existingHiddenCallbacks = null !== finishedWork.memoizedState;
          var wasHidden = null !== current22 && null !== current22.memoizedState, prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden, prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
          offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden || existingHiddenCallbacks;
          offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || wasHidden;
          recursivelyTraverseMutationEffects(root22, finishedWork);
          offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
          offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden;
          wasHidden && !existingHiddenCallbacks && !prevOffscreenSubtreeIsHidden && !prevOffscreenSubtreeWasHidden && (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && 0.05 < componentEffectEndTime - componentEffectStartTime && logComponentReappeared(
            finishedWork,
            componentEffectStartTime,
            componentEffectEndTime
          );
          commitReconciliationEffects(finishedWork);
          if (flags & 8192)
            a: for (root22 = finishedWork.stateNode, root22._visibility = existingHiddenCallbacks ? root22._visibility & ~OffscreenVisible : root22._visibility | OffscreenVisible, !existingHiddenCallbacks || null === current22 || wasHidden || offscreenSubtreeIsHidden || offscreenSubtreeWasHidden || (recursivelyTraverseDisappearLayoutEffects(finishedWork), (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && 0.05 < componentEffectEndTime - componentEffectStartTime && logComponentTrigger(
              finishedWork,
              componentEffectStartTime,
              componentEffectEndTime,
              "Disconnect"
            )), current22 = null, root22 = finishedWork; ; ) {
              if (5 === root22.tag || 26 === root22.tag) {
                if (null === current22) {
                  wasHidden = current22 = root22;
                  try {
                    currentResource = wasHidden.stateNode, existingHiddenCallbacks ? runWithFiberInDEV(
                      wasHidden,
                      hideInstance,
                      currentResource
                    ) : runWithFiberInDEV(
                      wasHidden,
                      unhideInstance,
                      wasHidden.stateNode,
                      wasHidden.memoizedProps
                    );
                  } catch (error2) {
                    captureCommitPhaseError(wasHidden, wasHidden.return, error2);
                  }
                }
              } else if (6 === root22.tag) {
                if (null === current22) {
                  wasHidden = root22;
                  try {
                    maybeNodes = wasHidden.stateNode, existingHiddenCallbacks ? runWithFiberInDEV(
                      wasHidden,
                      hideTextInstance,
                      maybeNodes
                    ) : runWithFiberInDEV(
                      wasHidden,
                      unhideTextInstance,
                      maybeNodes,
                      wasHidden.memoizedProps
                    );
                  } catch (error2) {
                    captureCommitPhaseError(wasHidden, wasHidden.return, error2);
                  }
                }
              } else if (18 === root22.tag) {
                if (null === current22) {
                  wasHidden = root22;
                  try {
                    i2 = wasHidden.stateNode, existingHiddenCallbacks ? runWithFiberInDEV(
                      wasHidden,
                      hideDehydratedBoundary,
                      i2
                    ) : runWithFiberInDEV(
                      wasHidden,
                      unhideDehydratedBoundary,
                      wasHidden.stateNode
                    );
                  } catch (error2) {
                    captureCommitPhaseError(wasHidden, wasHidden.return, error2);
                  }
                }
              } else if ((22 !== root22.tag && 23 !== root22.tag || null === root22.memoizedState || root22 === finishedWork) && null !== root22.child) {
                root22.child.return = root22;
                root22 = root22.child;
                continue;
              }
              if (root22 === finishedWork) break a;
              for (; null === root22.sibling; ) {
                if (null === root22.return || root22.return === finishedWork)
                  break a;
                current22 === root22 && (current22 = null);
                root22 = root22.return;
              }
              current22 === root22 && (current22 = null);
              root22.sibling.return = root22.return;
              root22 = root22.sibling;
            }
          flags & 4 && (flags = finishedWork.updateQueue, null !== flags && (current22 = flags.retryQueue, null !== current22 && (flags.retryQueue = null, attachSuspenseRetryListeners(finishedWork, current22))));
          break;
        case 19:
          recursivelyTraverseMutationEffects(root22, finishedWork);
          commitReconciliationEffects(finishedWork);
          flags & 4 && (flags = finishedWork.updateQueue, null !== flags && (finishedWork.updateQueue = null, attachSuspenseRetryListeners(finishedWork, flags)));
          break;
        case 30:
          break;
        case 21:
          break;
        default:
          recursivelyTraverseMutationEffects(root22, finishedWork), commitReconciliationEffects(finishedWork);
      }
      (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && ((componentEffectSpawnedUpdate || 0.05 < componentEffectDuration) && logComponentEffect(
        finishedWork,
        componentEffectStartTime,
        componentEffectEndTime,
        componentEffectDuration,
        componentEffectErrors
      ), null === finishedWork.alternate && null !== finishedWork.return && null !== finishedWork.return.alternate && 0.05 < componentEffectEndTime - componentEffectStartTime && (isHydratingParent(
        finishedWork.return.alternate,
        finishedWork.return
      ) || logComponentTrigger(
        finishedWork,
        componentEffectStartTime,
        componentEffectEndTime,
        "Mount"
      )));
      popComponentEffectStart(prevEffectStart);
      popComponentEffectDuration(prevEffectDuration);
      componentEffectErrors = prevEffectErrors;
      componentEffectSpawnedUpdate = prevEffectDidSpawnUpdate;
    }
    function commitReconciliationEffects(finishedWork) {
      var flags = finishedWork.flags;
      if (flags & 2) {
        try {
          runWithFiberInDEV(finishedWork, commitPlacement, finishedWork);
        } catch (error2) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error2);
        }
        finishedWork.flags &= -3;
      }
      flags & 4096 && (finishedWork.flags &= -4097);
    }
    function recursivelyResetForms(parentFiber) {
      if (parentFiber.subtreeFlags & 1024)
        for (parentFiber = parentFiber.child; null !== parentFiber; ) {
          var fiber = parentFiber;
          recursivelyResetForms(fiber);
          5 === fiber.tag && fiber.flags & 1024 && fiber.stateNode.reset();
          parentFiber = parentFiber.sibling;
        }
    }
    function recursivelyTraverseLayoutEffects(root22, parentFiber) {
      if (parentFiber.subtreeFlags & 8772)
        for (parentFiber = parentFiber.child; null !== parentFiber; )
          commitLayoutEffectOnFiber(root22, parentFiber.alternate, parentFiber), parentFiber = parentFiber.sibling;
    }
    function disappearLayoutEffects(finishedWork) {
      var prevEffectStart = pushComponentEffectStart(), prevEffectDuration = pushComponentEffectDuration(), prevEffectErrors = pushComponentEffectErrors(), prevEffectDidSpawnUpdate = pushComponentEffectDidSpawnUpdate();
      switch (finishedWork.tag) {
        case 0:
        case 11:
        case 14:
        case 15:
          commitHookLayoutUnmountEffects(
            finishedWork,
            finishedWork.return,
            Layout
          );
          recursivelyTraverseDisappearLayoutEffects(finishedWork);
          break;
        case 1:
          safelyDetachRef(finishedWork, finishedWork.return);
          var instance2 = finishedWork.stateNode;
          "function" === typeof instance2.componentWillUnmount && safelyCallComponentWillUnmount(
            finishedWork,
            finishedWork.return,
            instance2
          );
          recursivelyTraverseDisappearLayoutEffects(finishedWork);
          break;
        case 27:
          runWithFiberInDEV(
            finishedWork,
            releaseSingletonInstance,
            finishedWork.stateNode
          );
        case 26:
        case 5:
          safelyDetachRef(finishedWork, finishedWork.return);
          recursivelyTraverseDisappearLayoutEffects(finishedWork);
          break;
        case 22:
          null === finishedWork.memoizedState && recursivelyTraverseDisappearLayoutEffects(finishedWork);
          break;
        case 30:
          recursivelyTraverseDisappearLayoutEffects(finishedWork);
          break;
        default:
          recursivelyTraverseDisappearLayoutEffects(finishedWork);
      }
      (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && (componentEffectSpawnedUpdate || 0.05 < componentEffectDuration) && logComponentEffect(
        finishedWork,
        componentEffectStartTime,
        componentEffectEndTime,
        componentEffectDuration,
        componentEffectErrors
      );
      popComponentEffectStart(prevEffectStart);
      popComponentEffectDuration(prevEffectDuration);
      componentEffectErrors = prevEffectErrors;
      componentEffectSpawnedUpdate = prevEffectDidSpawnUpdate;
    }
    function recursivelyTraverseDisappearLayoutEffects(parentFiber) {
      for (parentFiber = parentFiber.child; null !== parentFiber; )
        disappearLayoutEffects(parentFiber), parentFiber = parentFiber.sibling;
    }
    function reappearLayoutEffects(finishedRoot, current22, finishedWork, includeWorkInProgressEffects) {
      var prevEffectStart = pushComponentEffectStart(), prevEffectDuration = pushComponentEffectDuration(), prevEffectErrors = pushComponentEffectErrors(), prevEffectDidSpawnUpdate = pushComponentEffectDidSpawnUpdate(), flags = finishedWork.flags;
      switch (finishedWork.tag) {
        case 0:
        case 11:
        case 15:
          recursivelyTraverseReappearLayoutEffects(
            finishedRoot,
            finishedWork,
            includeWorkInProgressEffects
          );
          commitHookLayoutEffects(finishedWork, Layout);
          break;
        case 1:
          recursivelyTraverseReappearLayoutEffects(
            finishedRoot,
            finishedWork,
            includeWorkInProgressEffects
          );
          current22 = finishedWork.stateNode;
          "function" === typeof current22.componentDidMount && runWithFiberInDEV(
            finishedWork,
            callComponentDidMountInDEV,
            finishedWork,
            current22
          );
          current22 = finishedWork.updateQueue;
          if (null !== current22) {
            finishedRoot = finishedWork.stateNode;
            try {
              runWithFiberInDEV(
                finishedWork,
                commitHiddenCallbacks,
                current22,
                finishedRoot
              );
            } catch (error2) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error2);
            }
          }
          includeWorkInProgressEffects && flags & 64 && commitClassCallbacks(finishedWork);
          safelyAttachRef(finishedWork, finishedWork.return);
          break;
        case 27:
          commitHostSingletonAcquisition(finishedWork);
        case 26:
        case 5:
          recursivelyTraverseReappearLayoutEffects(
            finishedRoot,
            finishedWork,
            includeWorkInProgressEffects
          );
          includeWorkInProgressEffects && null === current22 && flags & 4 && commitHostMount(finishedWork);
          safelyAttachRef(finishedWork, finishedWork.return);
          break;
        case 12:
          if (includeWorkInProgressEffects && flags & 4) {
            flags = pushNestedEffectDurations();
            recursivelyTraverseReappearLayoutEffects(
              finishedRoot,
              finishedWork,
              includeWorkInProgressEffects
            );
            includeWorkInProgressEffects = finishedWork.stateNode;
            includeWorkInProgressEffects.effectDuration += bubbleNestedEffectDurations(flags);
            try {
              runWithFiberInDEV(
                finishedWork,
                commitProfiler,
                finishedWork,
                current22,
                commitStartTime,
                includeWorkInProgressEffects.effectDuration
              );
            } catch (error2) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error2);
            }
          } else
            recursivelyTraverseReappearLayoutEffects(
              finishedRoot,
              finishedWork,
              includeWorkInProgressEffects
            );
          break;
        case 31:
          recursivelyTraverseReappearLayoutEffects(
            finishedRoot,
            finishedWork,
            includeWorkInProgressEffects
          );
          includeWorkInProgressEffects && flags & 4 && commitActivityHydrationCallbacks(finishedRoot, finishedWork);
          break;
        case 13:
          recursivelyTraverseReappearLayoutEffects(
            finishedRoot,
            finishedWork,
            includeWorkInProgressEffects
          );
          includeWorkInProgressEffects && flags & 4 && commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
          break;
        case 22:
          null === finishedWork.memoizedState && recursivelyTraverseReappearLayoutEffects(
            finishedRoot,
            finishedWork,
            includeWorkInProgressEffects
          );
          safelyAttachRef(finishedWork, finishedWork.return);
          break;
        case 30:
          break;
        default:
          recursivelyTraverseReappearLayoutEffects(
            finishedRoot,
            finishedWork,
            includeWorkInProgressEffects
          );
      }
      (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && (componentEffectSpawnedUpdate || 0.05 < componentEffectDuration) && logComponentEffect(
        finishedWork,
        componentEffectStartTime,
        componentEffectEndTime,
        componentEffectDuration,
        componentEffectErrors
      );
      popComponentEffectStart(prevEffectStart);
      popComponentEffectDuration(prevEffectDuration);
      componentEffectErrors = prevEffectErrors;
      componentEffectSpawnedUpdate = prevEffectDidSpawnUpdate;
    }
    function recursivelyTraverseReappearLayoutEffects(finishedRoot, parentFiber, includeWorkInProgressEffects) {
      includeWorkInProgressEffects = includeWorkInProgressEffects && 0 !== (parentFiber.subtreeFlags & 8772);
      for (parentFiber = parentFiber.child; null !== parentFiber; )
        reappearLayoutEffects(
          finishedRoot,
          parentFiber.alternate,
          parentFiber,
          includeWorkInProgressEffects
        ), parentFiber = parentFiber.sibling;
    }
    function commitOffscreenPassiveMountEffects(current22, finishedWork) {
      var previousCache = null;
      null !== current22 && null !== current22.memoizedState && null !== current22.memoizedState.cachePool && (previousCache = current22.memoizedState.cachePool.pool);
      current22 = null;
      null !== finishedWork.memoizedState && null !== finishedWork.memoizedState.cachePool && (current22 = finishedWork.memoizedState.cachePool.pool);
      current22 !== previousCache && (null != current22 && retainCache(current22), null != previousCache && releaseCache(previousCache));
    }
    function commitCachePassiveMountEffect(current22, finishedWork) {
      current22 = null;
      null !== finishedWork.alternate && (current22 = finishedWork.alternate.memoizedState.cache);
      finishedWork = finishedWork.memoizedState.cache;
      finishedWork !== current22 && (retainCache(finishedWork), null != current22 && releaseCache(current22));
    }
    function recursivelyTraversePassiveMountEffects(root22, parentFiber, committedLanes, committedTransitions, endTime) {
      if (parentFiber.subtreeFlags & 10256 || 0 !== parentFiber.actualDuration && (null === parentFiber.alternate || parentFiber.alternate.child !== parentFiber.child))
        for (parentFiber = parentFiber.child; null !== parentFiber; ) {
          var nextSibling = parentFiber.sibling;
          commitPassiveMountOnFiber(
            root22,
            parentFiber,
            committedLanes,
            committedTransitions,
            null !== nextSibling ? nextSibling.actualStartTime : endTime
          );
          parentFiber = nextSibling;
        }
    }
    function commitPassiveMountOnFiber(finishedRoot, finishedWork, committedLanes, committedTransitions, endTime) {
      var prevEffectStart = pushComponentEffectStart(), prevEffectDuration = pushComponentEffectDuration(), prevEffectErrors = pushComponentEffectErrors(), prevEffectDidSpawnUpdate = pushComponentEffectDidSpawnUpdate(), prevDeepEquality = alreadyWarnedForDeepEquality, flags = finishedWork.flags;
      switch (finishedWork.tag) {
        case 0:
        case 11:
        case 15:
          (finishedWork.mode & ProfileMode) !== NoMode && 0 < finishedWork.actualStartTime && 0 !== (finishedWork.flags & 1) && logComponentRender(
            finishedWork,
            finishedWork.actualStartTime,
            endTime,
            inHydratedSubtree,
            committedLanes
          );
          recursivelyTraversePassiveMountEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            endTime
          );
          flags & 2048 && commitHookPassiveMountEffects(finishedWork, Passive | HasEffect);
          break;
        case 1:
          (finishedWork.mode & ProfileMode) !== NoMode && 0 < finishedWork.actualStartTime && (0 !== (finishedWork.flags & 128) ? logComponentErrored(
            finishedWork,
            finishedWork.actualStartTime,
            endTime,
            []
          ) : 0 !== (finishedWork.flags & 1) && logComponentRender(
            finishedWork,
            finishedWork.actualStartTime,
            endTime,
            inHydratedSubtree,
            committedLanes
          ));
          recursivelyTraversePassiveMountEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            endTime
          );
          break;
        case 3:
          var prevProfilerEffectDuration = pushNestedEffectDurations(), wasInHydratedSubtree = inHydratedSubtree;
          inHydratedSubtree = null !== finishedWork.alternate && finishedWork.alternate.memoizedState.isDehydrated && 0 === (finishedWork.flags & 256);
          recursivelyTraversePassiveMountEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            endTime
          );
          inHydratedSubtree = wasInHydratedSubtree;
          flags & 2048 && (committedLanes = null, null !== finishedWork.alternate && (committedLanes = finishedWork.alternate.memoizedState.cache), committedTransitions = finishedWork.memoizedState.cache, committedTransitions !== committedLanes && (retainCache(committedTransitions), null != committedLanes && releaseCache(committedLanes)));
          finishedRoot.passiveEffectDuration += popNestedEffectDurations(
            prevProfilerEffectDuration
          );
          break;
        case 12:
          if (flags & 2048) {
            flags = pushNestedEffectDurations();
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              endTime
            );
            finishedRoot = finishedWork.stateNode;
            finishedRoot.passiveEffectDuration += bubbleNestedEffectDurations(flags);
            try {
              runWithFiberInDEV(
                finishedWork,
                commitProfilerPostCommitImpl,
                finishedWork,
                finishedWork.alternate,
                commitStartTime,
                finishedRoot.passiveEffectDuration
              );
            } catch (error2) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error2);
            }
          } else
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              endTime
            );
          break;
        case 31:
          flags = inHydratedSubtree;
          prevProfilerEffectDuration = null !== finishedWork.alternate ? finishedWork.alternate.memoizedState : null;
          wasInHydratedSubtree = finishedWork.memoizedState;
          null !== prevProfilerEffectDuration && null === wasInHydratedSubtree ? (wasInHydratedSubtree = finishedWork.deletions, null !== wasInHydratedSubtree && 0 < wasInHydratedSubtree.length && 18 === wasInHydratedSubtree[0].tag ? (inHydratedSubtree = false, prevProfilerEffectDuration = prevProfilerEffectDuration.hydrationErrors, null !== prevProfilerEffectDuration && logComponentErrored(
            finishedWork,
            finishedWork.actualStartTime,
            endTime,
            prevProfilerEffectDuration
          )) : inHydratedSubtree = true) : inHydratedSubtree = false;
          recursivelyTraversePassiveMountEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            endTime
          );
          inHydratedSubtree = flags;
          break;
        case 13:
          flags = inHydratedSubtree;
          prevProfilerEffectDuration = null !== finishedWork.alternate ? finishedWork.alternate.memoizedState : null;
          wasInHydratedSubtree = finishedWork.memoizedState;
          null === prevProfilerEffectDuration || null === prevProfilerEffectDuration.dehydrated || null !== wasInHydratedSubtree && null !== wasInHydratedSubtree.dehydrated ? inHydratedSubtree = false : (wasInHydratedSubtree = finishedWork.deletions, null !== wasInHydratedSubtree && 0 < wasInHydratedSubtree.length && 18 === wasInHydratedSubtree[0].tag ? (inHydratedSubtree = false, prevProfilerEffectDuration = prevProfilerEffectDuration.hydrationErrors, null !== prevProfilerEffectDuration && logComponentErrored(
            finishedWork,
            finishedWork.actualStartTime,
            endTime,
            prevProfilerEffectDuration
          )) : inHydratedSubtree = true);
          recursivelyTraversePassiveMountEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            endTime
          );
          inHydratedSubtree = flags;
          break;
        case 23:
          break;
        case 22:
          wasInHydratedSubtree = finishedWork.stateNode;
          prevProfilerEffectDuration = finishedWork.alternate;
          null !== finishedWork.memoizedState ? wasInHydratedSubtree._visibility & OffscreenPassiveEffectsConnected ? recursivelyTraversePassiveMountEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            endTime
          ) : recursivelyTraverseAtomicPassiveEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            endTime
          ) : wasInHydratedSubtree._visibility & OffscreenPassiveEffectsConnected ? recursivelyTraversePassiveMountEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            endTime
          ) : (wasInHydratedSubtree._visibility |= OffscreenPassiveEffectsConnected, recursivelyTraverseReconnectPassiveEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            0 !== (finishedWork.subtreeFlags & 10256) || 0 !== finishedWork.actualDuration && (null === finishedWork.alternate || finishedWork.alternate.child !== finishedWork.child),
            endTime
          ), (finishedWork.mode & ProfileMode) === NoMode || inHydratedSubtree || (finishedRoot = finishedWork.actualStartTime, 0 <= finishedRoot && 0.05 < endTime - finishedRoot && logComponentReappeared(finishedWork, finishedRoot, endTime), 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && 0.05 < componentEffectEndTime - componentEffectStartTime && logComponentReappeared(
            finishedWork,
            componentEffectStartTime,
            componentEffectEndTime
          )));
          flags & 2048 && commitOffscreenPassiveMountEffects(
            prevProfilerEffectDuration,
            finishedWork
          );
          break;
        case 24:
          recursivelyTraversePassiveMountEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            endTime
          );
          flags & 2048 && commitCachePassiveMountEffect(finishedWork.alternate, finishedWork);
          break;
        default:
          recursivelyTraversePassiveMountEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            endTime
          );
      }
      if ((finishedWork.mode & ProfileMode) !== NoMode) {
        if (finishedRoot = !inHydratedSubtree && null === finishedWork.alternate && null !== finishedWork.return && null !== finishedWork.return.alternate)
          committedLanes = finishedWork.actualStartTime, 0 <= committedLanes && 0.05 < endTime - committedLanes && logComponentTrigger(
            finishedWork,
            committedLanes,
            endTime,
            "Mount"
          );
        0 <= componentEffectStartTime && 0 <= componentEffectEndTime && ((componentEffectSpawnedUpdate || 0.05 < componentEffectDuration) && logComponentEffect(
          finishedWork,
          componentEffectStartTime,
          componentEffectEndTime,
          componentEffectDuration,
          componentEffectErrors
        ), finishedRoot && 0.05 < componentEffectEndTime - componentEffectStartTime && logComponentTrigger(
          finishedWork,
          componentEffectStartTime,
          componentEffectEndTime,
          "Mount"
        ));
      }
      popComponentEffectStart(prevEffectStart);
      popComponentEffectDuration(prevEffectDuration);
      componentEffectErrors = prevEffectErrors;
      componentEffectSpawnedUpdate = prevEffectDidSpawnUpdate;
      alreadyWarnedForDeepEquality = prevDeepEquality;
    }
    function recursivelyTraverseReconnectPassiveEffects(finishedRoot, parentFiber, committedLanes, committedTransitions, includeWorkInProgressEffects, endTime) {
      includeWorkInProgressEffects = includeWorkInProgressEffects && (0 !== (parentFiber.subtreeFlags & 10256) || 0 !== parentFiber.actualDuration && (null === parentFiber.alternate || parentFiber.alternate.child !== parentFiber.child));
      for (parentFiber = parentFiber.child; null !== parentFiber; ) {
        var nextSibling = parentFiber.sibling;
        reconnectPassiveEffects(
          finishedRoot,
          parentFiber,
          committedLanes,
          committedTransitions,
          includeWorkInProgressEffects,
          null !== nextSibling ? nextSibling.actualStartTime : endTime
        );
        parentFiber = nextSibling;
      }
    }
    function reconnectPassiveEffects(finishedRoot, finishedWork, committedLanes, committedTransitions, includeWorkInProgressEffects, endTime) {
      var prevEffectStart = pushComponentEffectStart(), prevEffectDuration = pushComponentEffectDuration(), prevEffectErrors = pushComponentEffectErrors(), prevEffectDidSpawnUpdate = pushComponentEffectDidSpawnUpdate(), prevDeepEquality = alreadyWarnedForDeepEquality;
      includeWorkInProgressEffects && (finishedWork.mode & ProfileMode) !== NoMode && 0 < finishedWork.actualStartTime && 0 !== (finishedWork.flags & 1) && logComponentRender(
        finishedWork,
        finishedWork.actualStartTime,
        endTime,
        inHydratedSubtree,
        committedLanes
      );
      var flags = finishedWork.flags;
      switch (finishedWork.tag) {
        case 0:
        case 11:
        case 15:
          recursivelyTraverseReconnectPassiveEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            includeWorkInProgressEffects,
            endTime
          );
          commitHookPassiveMountEffects(finishedWork, Passive);
          break;
        case 23:
          break;
        case 22:
          var _instance2 = finishedWork.stateNode;
          null !== finishedWork.memoizedState ? _instance2._visibility & OffscreenPassiveEffectsConnected ? recursivelyTraverseReconnectPassiveEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            includeWorkInProgressEffects,
            endTime
          ) : recursivelyTraverseAtomicPassiveEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            endTime
          ) : (_instance2._visibility |= OffscreenPassiveEffectsConnected, recursivelyTraverseReconnectPassiveEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            includeWorkInProgressEffects,
            endTime
          ));
          includeWorkInProgressEffects && flags & 2048 && commitOffscreenPassiveMountEffects(
            finishedWork.alternate,
            finishedWork
          );
          break;
        case 24:
          recursivelyTraverseReconnectPassiveEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            includeWorkInProgressEffects,
            endTime
          );
          includeWorkInProgressEffects && flags & 2048 && commitCachePassiveMountEffect(finishedWork.alternate, finishedWork);
          break;
        default:
          recursivelyTraverseReconnectPassiveEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            includeWorkInProgressEffects,
            endTime
          );
      }
      (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && (componentEffectSpawnedUpdate || 0.05 < componentEffectDuration) && logComponentEffect(
        finishedWork,
        componentEffectStartTime,
        componentEffectEndTime,
        componentEffectDuration,
        componentEffectErrors
      );
      popComponentEffectStart(prevEffectStart);
      popComponentEffectDuration(prevEffectDuration);
      componentEffectErrors = prevEffectErrors;
      componentEffectSpawnedUpdate = prevEffectDidSpawnUpdate;
      alreadyWarnedForDeepEquality = prevDeepEquality;
    }
    function recursivelyTraverseAtomicPassiveEffects(finishedRoot$jscomp$0, parentFiber, committedLanes$jscomp$0, committedTransitions$jscomp$0, endTime$jscomp$0) {
      if (parentFiber.subtreeFlags & 10256 || 0 !== parentFiber.actualDuration && (null === parentFiber.alternate || parentFiber.alternate.child !== parentFiber.child))
        for (var child = parentFiber.child; null !== child; ) {
          parentFiber = child.sibling;
          var finishedRoot = finishedRoot$jscomp$0, committedLanes = committedLanes$jscomp$0, committedTransitions = committedTransitions$jscomp$0, endTime = null !== parentFiber ? parentFiber.actualStartTime : endTime$jscomp$0, prevDeepEquality = alreadyWarnedForDeepEquality;
          (child.mode & ProfileMode) !== NoMode && 0 < child.actualStartTime && 0 !== (child.flags & 1) && logComponentRender(
            child,
            child.actualStartTime,
            endTime,
            inHydratedSubtree,
            committedLanes
          );
          var flags = child.flags;
          switch (child.tag) {
            case 22:
              recursivelyTraverseAtomicPassiveEffects(
                finishedRoot,
                child,
                committedLanes,
                committedTransitions,
                endTime
              );
              flags & 2048 && commitOffscreenPassiveMountEffects(child.alternate, child);
              break;
            case 24:
              recursivelyTraverseAtomicPassiveEffects(
                finishedRoot,
                child,
                committedLanes,
                committedTransitions,
                endTime
              );
              flags & 2048 && commitCachePassiveMountEffect(child.alternate, child);
              break;
            default:
              recursivelyTraverseAtomicPassiveEffects(
                finishedRoot,
                child,
                committedLanes,
                committedTransitions,
                endTime
              );
          }
          alreadyWarnedForDeepEquality = prevDeepEquality;
          child = parentFiber;
        }
    }
    function recursivelyAccumulateSuspenseyCommit(parentFiber, committedLanes, suspendedState) {
      if (parentFiber.subtreeFlags & suspenseyCommitFlag)
        for (parentFiber = parentFiber.child; null !== parentFiber; )
          accumulateSuspenseyCommitOnFiber(
            parentFiber,
            committedLanes,
            suspendedState
          ), parentFiber = parentFiber.sibling;
    }
    function accumulateSuspenseyCommitOnFiber(fiber, committedLanes, suspendedState) {
      switch (fiber.tag) {
        case 26:
          recursivelyAccumulateSuspenseyCommit(
            fiber,
            committedLanes,
            suspendedState
          );
          fiber.flags & suspenseyCommitFlag && null !== fiber.memoizedState && suspendResource(
            suspendedState,
            currentHoistableRoot,
            fiber.memoizedState,
            fiber.memoizedProps
          );
          break;
        case 5:
          recursivelyAccumulateSuspenseyCommit(
            fiber,
            committedLanes,
            suspendedState
          );
          break;
        case 3:
        case 4:
          var previousHoistableRoot = currentHoistableRoot;
          currentHoistableRoot = getHoistableRoot(
            fiber.stateNode.containerInfo
          );
          recursivelyAccumulateSuspenseyCommit(
            fiber,
            committedLanes,
            suspendedState
          );
          currentHoistableRoot = previousHoistableRoot;
          break;
        case 22:
          null === fiber.memoizedState && (previousHoistableRoot = fiber.alternate, null !== previousHoistableRoot && null !== previousHoistableRoot.memoizedState ? (previousHoistableRoot = suspenseyCommitFlag, suspenseyCommitFlag = 16777216, recursivelyAccumulateSuspenseyCommit(
            fiber,
            committedLanes,
            suspendedState
          ), suspenseyCommitFlag = previousHoistableRoot) : recursivelyAccumulateSuspenseyCommit(
            fiber,
            committedLanes,
            suspendedState
          ));
          break;
        default:
          recursivelyAccumulateSuspenseyCommit(
            fiber,
            committedLanes,
            suspendedState
          );
      }
    }
    function detachAlternateSiblings(parentFiber) {
      var previousFiber = parentFiber.alternate;
      if (null !== previousFiber && (parentFiber = previousFiber.child, null !== parentFiber)) {
        previousFiber.child = null;
        do
          previousFiber = parentFiber.sibling, parentFiber.sibling = null, parentFiber = previousFiber;
        while (null !== parentFiber);
      }
    }
    function recursivelyTraversePassiveUnmountEffects(parentFiber) {
      var deletions = parentFiber.deletions;
      if (0 !== (parentFiber.flags & 16)) {
        if (null !== deletions)
          for (var i2 = 0; i2 < deletions.length; i2++) {
            var childToDelete = deletions[i2], prevEffectStart = pushComponentEffectStart();
            nextEffect = childToDelete;
            commitPassiveUnmountEffectsInsideOfDeletedTree_begin(
              childToDelete,
              parentFiber
            );
            (childToDelete.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && 0.05 < componentEffectEndTime - componentEffectStartTime && logComponentTrigger(
              childToDelete,
              componentEffectStartTime,
              componentEffectEndTime,
              "Unmount"
            );
            popComponentEffectStart(prevEffectStart);
          }
        detachAlternateSiblings(parentFiber);
      }
      if (parentFiber.subtreeFlags & 10256)
        for (parentFiber = parentFiber.child; null !== parentFiber; )
          commitPassiveUnmountOnFiber(parentFiber), parentFiber = parentFiber.sibling;
    }
    function commitPassiveUnmountOnFiber(finishedWork) {
      var prevEffectStart = pushComponentEffectStart(), prevEffectDuration = pushComponentEffectDuration(), prevEffectErrors = pushComponentEffectErrors(), prevEffectDidSpawnUpdate = pushComponentEffectDidSpawnUpdate();
      switch (finishedWork.tag) {
        case 0:
        case 11:
        case 15:
          recursivelyTraversePassiveUnmountEffects(finishedWork);
          finishedWork.flags & 2048 && commitHookPassiveUnmountEffects(
            finishedWork,
            finishedWork.return,
            Passive | HasEffect
          );
          break;
        case 3:
          var prevProfilerEffectDuration = pushNestedEffectDurations();
          recursivelyTraversePassiveUnmountEffects(finishedWork);
          finishedWork.stateNode.passiveEffectDuration += popNestedEffectDurations(prevProfilerEffectDuration);
          break;
        case 12:
          prevProfilerEffectDuration = pushNestedEffectDurations();
          recursivelyTraversePassiveUnmountEffects(finishedWork);
          finishedWork.stateNode.passiveEffectDuration += bubbleNestedEffectDurations(prevProfilerEffectDuration);
          break;
        case 22:
          prevProfilerEffectDuration = finishedWork.stateNode;
          null !== finishedWork.memoizedState && prevProfilerEffectDuration._visibility & OffscreenPassiveEffectsConnected && (null === finishedWork.return || 13 !== finishedWork.return.tag) ? (prevProfilerEffectDuration._visibility &= ~OffscreenPassiveEffectsConnected, recursivelyTraverseDisconnectPassiveEffects(finishedWork), (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && 0.05 < componentEffectEndTime - componentEffectStartTime && logComponentTrigger(
            finishedWork,
            componentEffectStartTime,
            componentEffectEndTime,
            "Disconnect"
          )) : recursivelyTraversePassiveUnmountEffects(finishedWork);
          break;
        default:
          recursivelyTraversePassiveUnmountEffects(finishedWork);
      }
      (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && (componentEffectSpawnedUpdate || 0.05 < componentEffectDuration) && logComponentEffect(
        finishedWork,
        componentEffectStartTime,
        componentEffectEndTime,
        componentEffectDuration,
        componentEffectErrors
      );
      popComponentEffectStart(prevEffectStart);
      popComponentEffectDuration(prevEffectDuration);
      componentEffectSpawnedUpdate = prevEffectDidSpawnUpdate;
      componentEffectErrors = prevEffectErrors;
    }
    function recursivelyTraverseDisconnectPassiveEffects(parentFiber) {
      var deletions = parentFiber.deletions;
      if (0 !== (parentFiber.flags & 16)) {
        if (null !== deletions)
          for (var i2 = 0; i2 < deletions.length; i2++) {
            var childToDelete = deletions[i2], prevEffectStart = pushComponentEffectStart();
            nextEffect = childToDelete;
            commitPassiveUnmountEffectsInsideOfDeletedTree_begin(
              childToDelete,
              parentFiber
            );
            (childToDelete.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && 0.05 < componentEffectEndTime - componentEffectStartTime && logComponentTrigger(
              childToDelete,
              componentEffectStartTime,
              componentEffectEndTime,
              "Unmount"
            );
            popComponentEffectStart(prevEffectStart);
          }
        detachAlternateSiblings(parentFiber);
      }
      for (parentFiber = parentFiber.child; null !== parentFiber; )
        disconnectPassiveEffect(parentFiber), parentFiber = parentFiber.sibling;
    }
    function disconnectPassiveEffect(finishedWork) {
      var prevEffectStart = pushComponentEffectStart(), prevEffectDuration = pushComponentEffectDuration(), prevEffectErrors = pushComponentEffectErrors(), prevEffectDidSpawnUpdate = pushComponentEffectDidSpawnUpdate();
      switch (finishedWork.tag) {
        case 0:
        case 11:
        case 15:
          commitHookPassiveUnmountEffects(
            finishedWork,
            finishedWork.return,
            Passive
          );
          recursivelyTraverseDisconnectPassiveEffects(finishedWork);
          break;
        case 22:
          var instance2 = finishedWork.stateNode;
          instance2._visibility & OffscreenPassiveEffectsConnected && (instance2._visibility &= ~OffscreenPassiveEffectsConnected, recursivelyTraverseDisconnectPassiveEffects(finishedWork));
          break;
        default:
          recursivelyTraverseDisconnectPassiveEffects(finishedWork);
      }
      (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && (componentEffectSpawnedUpdate || 0.05 < componentEffectDuration) && logComponentEffect(
        finishedWork,
        componentEffectStartTime,
        componentEffectEndTime,
        componentEffectDuration,
        componentEffectErrors
      );
      popComponentEffectStart(prevEffectStart);
      popComponentEffectDuration(prevEffectDuration);
      componentEffectSpawnedUpdate = prevEffectDidSpawnUpdate;
      componentEffectErrors = prevEffectErrors;
    }
    function commitPassiveUnmountEffectsInsideOfDeletedTree_begin(deletedSubtreeRoot, nearestMountedAncestor$jscomp$0) {
      for (; null !== nextEffect; ) {
        var fiber = nextEffect, current22 = fiber, nearestMountedAncestor = nearestMountedAncestor$jscomp$0, prevEffectStart = pushComponentEffectStart(), prevEffectDuration = pushComponentEffectDuration(), prevEffectErrors = pushComponentEffectErrors(), prevEffectDidSpawnUpdate = pushComponentEffectDidSpawnUpdate();
        switch (current22.tag) {
          case 0:
          case 11:
          case 15:
            commitHookPassiveUnmountEffects(
              current22,
              nearestMountedAncestor,
              Passive
            );
            break;
          case 23:
          case 22:
            null !== current22.memoizedState && null !== current22.memoizedState.cachePool && (nearestMountedAncestor = current22.memoizedState.cachePool.pool, null != nearestMountedAncestor && retainCache(nearestMountedAncestor));
            break;
          case 24:
            releaseCache(current22.memoizedState.cache);
        }
        (current22.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && (componentEffectSpawnedUpdate || 0.05 < componentEffectDuration) && logComponentEffect(
          current22,
          componentEffectStartTime,
          componentEffectEndTime,
          componentEffectDuration,
          componentEffectErrors
        );
        popComponentEffectStart(prevEffectStart);
        popComponentEffectDuration(prevEffectDuration);
        componentEffectSpawnedUpdate = prevEffectDidSpawnUpdate;
        componentEffectErrors = prevEffectErrors;
        current22 = fiber.child;
        if (null !== current22) current22.return = fiber, nextEffect = current22;
        else
          a: for (fiber = deletedSubtreeRoot; null !== nextEffect; ) {
            current22 = nextEffect;
            prevEffectStart = current22.sibling;
            prevEffectDuration = current22.return;
            detachFiberAfterEffects(current22);
            if (current22 === fiber) {
              nextEffect = null;
              break a;
            }
            if (null !== prevEffectStart) {
              prevEffectStart.return = prevEffectDuration;
              nextEffect = prevEffectStart;
              break a;
            }
            nextEffect = prevEffectDuration;
          }
      }
    }
    function onCommitRoot() {
      commitHooks.forEach(function(commitHook) {
        return commitHook();
      });
    }
    function isConcurrentActEnvironment() {
      var isReactActEnvironmentGlobal = "undefined" !== typeof IS_REACT_ACT_ENVIRONMENT ? IS_REACT_ACT_ENVIRONMENT : void 0;
      isReactActEnvironmentGlobal || null === ReactSharedInternals.actQueue || console.error(
        "The current testing environment is not configured to support act(...)"
      );
      return isReactActEnvironmentGlobal;
    }
    function requestUpdateLane(fiber) {
      if ((executionContext & RenderContext) !== NoContext && 0 !== workInProgressRootRenderLanes)
        return workInProgressRootRenderLanes & -workInProgressRootRenderLanes;
      var transition = ReactSharedInternals.T;
      return null !== transition ? (transition._updatedFibers || (transition._updatedFibers = /* @__PURE__ */ new Set()), transition._updatedFibers.add(fiber), requestTransitionLane()) : resolveUpdatePriority();
    }
    function requestDeferredLane() {
      if (0 === workInProgressDeferredLane)
        if (0 === (workInProgressRootRenderLanes & 536870912) || isHydrating) {
          var lane = nextTransitionDeferredLane;
          nextTransitionDeferredLane <<= 1;
          0 === (nextTransitionDeferredLane & 3932160) && (nextTransitionDeferredLane = 262144);
          workInProgressDeferredLane = lane;
        } else workInProgressDeferredLane = 536870912;
      lane = suspenseHandlerStackCursor.current;
      null !== lane && (lane.flags |= 32);
      return workInProgressDeferredLane;
    }
    function scheduleUpdateOnFiber(root22, fiber, lane) {
      isRunningInsertionEffect && console.error("useInsertionEffect must not schedule updates.");
      isFlushingPassiveEffects && (didScheduleUpdateDuringPassiveEffects = true);
      if (root22 === workInProgressRoot && (workInProgressSuspendedReason === SuspendedOnData || workInProgressSuspendedReason === SuspendedOnAction) || null !== root22.cancelPendingCommit)
        prepareFreshStack(root22, 0), markRootSuspended(
          root22,
          workInProgressRootRenderLanes,
          workInProgressDeferredLane,
          false
        );
      markRootUpdated$1(root22, lane);
      if ((executionContext & RenderContext) !== NoContext && root22 === workInProgressRoot) {
        if (isRendering)
          switch (fiber.tag) {
            case 0:
            case 11:
            case 15:
              root22 = workInProgress && getComponentNameFromFiber(workInProgress) || "Unknown";
              didWarnAboutUpdateInRenderForAnotherComponent.has(root22) || (didWarnAboutUpdateInRenderForAnotherComponent.add(root22), fiber = getComponentNameFromFiber(fiber) || "Unknown", console.error(
                "Cannot update a component (`%s`) while rendering a different component (`%s`). To locate the bad setState() call inside `%s`, follow the stack trace as described in https://react.dev/link/setstate-in-render",
                fiber,
                root22,
                root22
              ));
              break;
            case 1:
              didWarnAboutUpdateInRender || (console.error(
                "Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state."
              ), didWarnAboutUpdateInRender = true);
          }
      } else
        isDevToolsPresent && addFiberToLanesMap(root22, fiber, lane), warnIfUpdatesNotWrappedWithActDEV(fiber), root22 === workInProgressRoot && ((executionContext & RenderContext) === NoContext && (workInProgressRootInterleavedUpdatedLanes |= lane), workInProgressRootExitStatus === RootSuspendedWithDelay && markRootSuspended(
          root22,
          workInProgressRootRenderLanes,
          workInProgressDeferredLane,
          false
        )), ensureRootIsScheduled(root22);
    }
    function performWorkOnRoot(root22, lanes, forceSync) {
      if ((executionContext & (RenderContext | CommitContext)) !== NoContext)
        throw Error("Should not already be working.");
      if (0 !== workInProgressRootRenderLanes && null !== workInProgress) {
        var yieldedFiber = workInProgress, yieldEndTime = now$1();
        switch (yieldReason) {
          case SuspendedOnImmediate:
          case SuspendedOnData:
            var startTime = yieldStartTime;
            supportsUserTiming && ((yieldedFiber = yieldedFiber._debugTask) ? yieldedFiber.run(
              console.timeStamp.bind(
                console,
                "Suspended",
                startTime,
                yieldEndTime,
                COMPONENTS_TRACK,
                void 0,
                "primary-light"
              )
            ) : console.timeStamp(
              "Suspended",
              startTime,
              yieldEndTime,
              COMPONENTS_TRACK,
              void 0,
              "primary-light"
            ));
            break;
          case SuspendedOnAction:
            startTime = yieldStartTime;
            supportsUserTiming && ((yieldedFiber = yieldedFiber._debugTask) ? yieldedFiber.run(
              console.timeStamp.bind(
                console,
                "Action",
                startTime,
                yieldEndTime,
                COMPONENTS_TRACK,
                void 0,
                "primary-light"
              )
            ) : console.timeStamp(
              "Action",
              startTime,
              yieldEndTime,
              COMPONENTS_TRACK,
              void 0,
              "primary-light"
            ));
            break;
          default:
            supportsUserTiming && (yieldedFiber = yieldEndTime - yieldStartTime, 3 > yieldedFiber || console.timeStamp(
              "Blocked",
              yieldStartTime,
              yieldEndTime,
              COMPONENTS_TRACK,
              void 0,
              5 > yieldedFiber ? "primary-light" : 10 > yieldedFiber ? "primary" : 100 > yieldedFiber ? "primary-dark" : "error"
            ));
        }
      }
      startTime = (forceSync = !forceSync && 0 === (lanes & 127) && 0 === (lanes & root22.expiredLanes) || checkIfRootIsPrerendering(root22, lanes)) ? renderRootConcurrent(root22, lanes) : renderRootSync(root22, lanes, true);
      var renderWasConcurrent = forceSync;
      do {
        if (startTime === RootInProgress) {
          workInProgressRootIsPrerendering && !forceSync && markRootSuspended(root22, lanes, 0, false);
          lanes = workInProgressSuspendedReason;
          yieldStartTime = now2();
          yieldReason = lanes;
          break;
        } else {
          yieldedFiber = now$1();
          yieldEndTime = root22.current.alternate;
          if (renderWasConcurrent && !isRenderConsistentWithExternalStores(yieldEndTime)) {
            setCurrentTrackFromLanes(lanes);
            yieldEndTime = renderStartTime;
            startTime = yieldedFiber;
            !supportsUserTiming || startTime <= yieldEndTime || (workInProgressUpdateTask ? workInProgressUpdateTask.run(
              console.timeStamp.bind(
                console,
                "Teared Render",
                yieldEndTime,
                startTime,
                currentTrack,
                LANES_TRACK_GROUP,
                "error"
              )
            ) : console.timeStamp(
              "Teared Render",
              yieldEndTime,
              startTime,
              currentTrack,
              LANES_TRACK_GROUP,
              "error"
            ));
            finalizeRender(lanes, yieldedFiber);
            startTime = renderRootSync(root22, lanes, false);
            renderWasConcurrent = false;
            continue;
          }
          if (startTime === RootErrored) {
            renderWasConcurrent = lanes;
            if (root22.errorRecoveryDisabledLanes & renderWasConcurrent)
              var errorRetryLanes = 0;
            else
              errorRetryLanes = root22.pendingLanes & -536870913, errorRetryLanes = 0 !== errorRetryLanes ? errorRetryLanes : errorRetryLanes & 536870912 ? 536870912 : 0;
            if (0 !== errorRetryLanes) {
              setCurrentTrackFromLanes(lanes);
              logErroredRenderPhase(
                renderStartTime,
                yieldedFiber,
                lanes,
                workInProgressUpdateTask
              );
              finalizeRender(lanes, yieldedFiber);
              lanes = errorRetryLanes;
              a: {
                yieldedFiber = root22;
                startTime = renderWasConcurrent;
                renderWasConcurrent = workInProgressRootConcurrentErrors;
                var wasRootDehydrated = yieldedFiber.current.memoizedState.isDehydrated;
                wasRootDehydrated && (prepareFreshStack(yieldedFiber, errorRetryLanes).flags |= 256);
                errorRetryLanes = renderRootSync(
                  yieldedFiber,
                  errorRetryLanes,
                  false
                );
                if (errorRetryLanes !== RootErrored) {
                  if (workInProgressRootDidAttachPingListener && !wasRootDehydrated) {
                    yieldedFiber.errorRecoveryDisabledLanes |= startTime;
                    workInProgressRootInterleavedUpdatedLanes |= startTime;
                    startTime = RootSuspendedWithDelay;
                    break a;
                  }
                  yieldedFiber = workInProgressRootRecoverableErrors;
                  workInProgressRootRecoverableErrors = renderWasConcurrent;
                  null !== yieldedFiber && (null === workInProgressRootRecoverableErrors ? workInProgressRootRecoverableErrors = yieldedFiber : workInProgressRootRecoverableErrors.push.apply(
                    workInProgressRootRecoverableErrors,
                    yieldedFiber
                  ));
                }
                startTime = errorRetryLanes;
              }
              renderWasConcurrent = false;
              if (startTime !== RootErrored) continue;
              else yieldedFiber = now$1();
            }
          }
          if (startTime === RootFatalErrored) {
            setCurrentTrackFromLanes(lanes);
            logErroredRenderPhase(
              renderStartTime,
              yieldedFiber,
              lanes,
              workInProgressUpdateTask
            );
            finalizeRender(lanes, yieldedFiber);
            prepareFreshStack(root22, 0);
            markRootSuspended(root22, lanes, 0, true);
            break;
          }
          a: {
            forceSync = root22;
            switch (startTime) {
              case RootInProgress:
              case RootFatalErrored:
                throw Error("Root did not complete. This is a bug in React.");
              case RootSuspendedWithDelay:
                if ((lanes & 4194048) !== lanes) break;
              case RootSuspendedAtTheShell:
                setCurrentTrackFromLanes(lanes);
                logSuspendedRenderPhase(
                  renderStartTime,
                  yieldedFiber,
                  lanes,
                  workInProgressUpdateTask
                );
                finalizeRender(lanes, yieldedFiber);
                yieldEndTime = lanes;
                0 !== (yieldEndTime & 127) ? blockingSuspendedTime = yieldedFiber : 0 !== (yieldEndTime & 4194048) && (transitionSuspendedTime = yieldedFiber);
                markRootSuspended(
                  forceSync,
                  lanes,
                  workInProgressDeferredLane,
                  !workInProgressRootDidSkipSuspendedSiblings
                );
                break a;
              case RootErrored:
                workInProgressRootRecoverableErrors = null;
                break;
              case RootSuspended:
              case RootCompleted:
                break;
              default:
                throw Error("Unknown root exit status.");
            }
            if (null !== ReactSharedInternals.actQueue)
              commitRoot(
                forceSync,
                yieldEndTime,
                lanes,
                workInProgressRootRecoverableErrors,
                workInProgressTransitions,
                workInProgressRootDidIncludeRecursiveRenderUpdate,
                workInProgressDeferredLane,
                workInProgressRootInterleavedUpdatedLanes,
                workInProgressSuspendedRetryLanes,
                startTime,
                null,
                null,
                renderStartTime,
                yieldedFiber
              );
            else {
              if ((lanes & 62914560) === lanes && (renderWasConcurrent = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now$1(), 10 < renderWasConcurrent)) {
                markRootSuspended(
                  forceSync,
                  lanes,
                  workInProgressDeferredLane,
                  !workInProgressRootDidSkipSuspendedSiblings
                );
                if (0 !== getNextLanes(forceSync, 0, true)) break a;
                pendingEffectsLanes = lanes;
                forceSync.timeoutHandle = scheduleTimeout(
                  commitRootWhenReady.bind(
                    null,
                    forceSync,
                    yieldEndTime,
                    workInProgressRootRecoverableErrors,
                    workInProgressTransitions,
                    workInProgressRootDidIncludeRecursiveRenderUpdate,
                    lanes,
                    workInProgressDeferredLane,
                    workInProgressRootInterleavedUpdatedLanes,
                    workInProgressSuspendedRetryLanes,
                    workInProgressRootDidSkipSuspendedSiblings,
                    startTime,
                    "Throttled",
                    renderStartTime,
                    yieldedFiber
                  ),
                  renderWasConcurrent
                );
                break a;
              }
              commitRootWhenReady(
                forceSync,
                yieldEndTime,
                workInProgressRootRecoverableErrors,
                workInProgressTransitions,
                workInProgressRootDidIncludeRecursiveRenderUpdate,
                lanes,
                workInProgressDeferredLane,
                workInProgressRootInterleavedUpdatedLanes,
                workInProgressSuspendedRetryLanes,
                workInProgressRootDidSkipSuspendedSiblings,
                startTime,
                null,
                renderStartTime,
                yieldedFiber
              );
            }
          }
        }
        break;
      } while (1);
      ensureRootIsScheduled(root22);
    }
    function commitRootWhenReady(root22, finishedWork, recoverableErrors, transitions, didIncludeRenderPhaseUpdate, lanes, spawnedLane, updatedLanes, suspendedRetryLanes, didSkipSuspendedSiblings, exitStatus, suspendedCommitReason, completedRenderStartTime, completedRenderEndTime) {
      root22.timeoutHandle = noTimeout;
      var subtreeFlags = finishedWork.subtreeFlags, suspendedState = null;
      if (subtreeFlags & 8192 || 16785408 === (subtreeFlags & 16785408)) {
        if (suspendedState = {
          stylesheets: null,
          count: 0,
          imgCount: 0,
          imgBytes: 0,
          suspenseyImages: [],
          waitingForImages: true,
          waitingForViewTransition: false,
          unsuspend: noop$12
        }, accumulateSuspenseyCommitOnFiber(finishedWork, lanes, suspendedState), subtreeFlags = (lanes & 62914560) === lanes ? globalMostRecentFallbackTime - now$1() : (lanes & 4194048) === lanes ? globalMostRecentTransitionTime - now$1() : 0, subtreeFlags = waitForCommitToBeReady(suspendedState, subtreeFlags), null !== subtreeFlags) {
          pendingEffectsLanes = lanes;
          root22.cancelPendingCommit = subtreeFlags(
            commitRoot.bind(
              null,
              root22,
              finishedWork,
              lanes,
              recoverableErrors,
              transitions,
              didIncludeRenderPhaseUpdate,
              spawnedLane,
              updatedLanes,
              suspendedRetryLanes,
              exitStatus,
              suspendedState,
              suspendedState.waitingForViewTransition ? "Waiting for the previous Animation" : 0 < suspendedState.count ? 0 < suspendedState.imgCount ? "Suspended on CSS and Images" : "Suspended on CSS" : 1 === suspendedState.imgCount ? "Suspended on an Image" : 0 < suspendedState.imgCount ? "Suspended on Images" : null,
              completedRenderStartTime,
              completedRenderEndTime
            )
          );
          markRootSuspended(
            root22,
            lanes,
            spawnedLane,
            !didSkipSuspendedSiblings
          );
          return;
        }
      }
      commitRoot(
        root22,
        finishedWork,
        lanes,
        recoverableErrors,
        transitions,
        didIncludeRenderPhaseUpdate,
        spawnedLane,
        updatedLanes,
        suspendedRetryLanes,
        exitStatus,
        suspendedState,
        suspendedCommitReason,
        completedRenderStartTime,
        completedRenderEndTime
      );
    }
    function isRenderConsistentWithExternalStores(finishedWork) {
      for (var node2 = finishedWork; ; ) {
        var tag = node2.tag;
        if ((0 === tag || 11 === tag || 15 === tag) && node2.flags & 16384 && (tag = node2.updateQueue, null !== tag && (tag = tag.stores, null !== tag)))
          for (var i2 = 0; i2 < tag.length; i2++) {
            var check2 = tag[i2], getSnapshot = check2.getSnapshot;
            check2 = check2.value;
            try {
              if (!objectIs(getSnapshot(), check2)) return false;
            } catch (error2) {
              return false;
            }
          }
        tag = node2.child;
        if (node2.subtreeFlags & 16384 && null !== tag)
          tag.return = node2, node2 = tag;
        else {
          if (node2 === finishedWork) break;
          for (; null === node2.sibling; ) {
            if (null === node2.return || node2.return === finishedWork) return true;
            node2 = node2.return;
          }
          node2.sibling.return = node2.return;
          node2 = node2.sibling;
        }
      }
      return true;
    }
    function markRootSuspended(root22, suspendedLanes, spawnedLane, didAttemptEntireTree) {
      suspendedLanes &= ~workInProgressRootPingedLanes;
      suspendedLanes &= ~workInProgressRootInterleavedUpdatedLanes;
      root22.suspendedLanes |= suspendedLanes;
      root22.pingedLanes &= ~suspendedLanes;
      didAttemptEntireTree && (root22.warmLanes |= suspendedLanes);
      didAttemptEntireTree = root22.expirationTimes;
      for (var lanes = suspendedLanes; 0 < lanes; ) {
        var index = 31 - clz322(lanes), lane = 1 << index;
        didAttemptEntireTree[index] = -1;
        lanes &= ~lane;
      }
      0 !== spawnedLane && markSpawnedDeferredLane(root22, spawnedLane, suspendedLanes);
    }
    function flushSyncWork$1() {
      return (executionContext & (RenderContext | CommitContext)) === NoContext ? (flushSyncWorkAcrossRoots_impl(0), false) : true;
    }
    function resetWorkInProgressStack() {
      if (null !== workInProgress) {
        if (workInProgressSuspendedReason === NotSuspended)
          var interruptedWork = workInProgress.return;
        else
          interruptedWork = workInProgress, resetContextDependencies(), resetHooksOnUnwind(interruptedWork), thenableState$1 = null, thenableIndexCounter$1 = 0, interruptedWork = workInProgress;
        for (; null !== interruptedWork; )
          unwindInterruptedWork(interruptedWork.alternate, interruptedWork), interruptedWork = interruptedWork.return;
        workInProgress = null;
      }
    }
    function finalizeRender(lanes, finalizationTime) {
      0 !== (lanes & 127) && (blockingClampTime = finalizationTime);
      0 !== (lanes & 4194048) && (transitionClampTime = finalizationTime);
      0 !== (lanes & 62914560) && (retryClampTime = finalizationTime);
      0 !== (lanes & 2080374784) && (idleClampTime = finalizationTime);
    }
    function prepareFreshStack(root22, lanes) {
      supportsUserTiming && (console.timeStamp(
        "Blocking Track",
        3e-3,
        3e-3,
        "Blocking",
        LANES_TRACK_GROUP,
        "primary-light"
      ), console.timeStamp(
        "Transition Track",
        3e-3,
        3e-3,
        "Transition",
        LANES_TRACK_GROUP,
        "primary-light"
      ), console.timeStamp(
        "Suspense Track",
        3e-3,
        3e-3,
        "Suspense",
        LANES_TRACK_GROUP,
        "primary-light"
      ), console.timeStamp(
        "Idle Track",
        3e-3,
        3e-3,
        "Idle",
        LANES_TRACK_GROUP,
        "primary-light"
      ));
      var previousRenderStartTime = renderStartTime;
      renderStartTime = now2();
      if (0 !== workInProgressRootRenderLanes && 0 < previousRenderStartTime) {
        setCurrentTrackFromLanes(workInProgressRootRenderLanes);
        if (workInProgressRootExitStatus === RootSuspended || workInProgressRootExitStatus === RootSuspendedWithDelay)
          logSuspendedRenderPhase(
            previousRenderStartTime,
            renderStartTime,
            lanes,
            workInProgressUpdateTask
          );
        else {
          var endTime = renderStartTime, debugTask = workInProgressUpdateTask;
          if (supportsUserTiming && !(endTime <= previousRenderStartTime)) {
            var color = (lanes & 738197653) === lanes ? "tertiary-dark" : "primary-dark", label2 = (lanes & 536870912) === lanes ? "Prewarm" : (lanes & 201326741) === lanes ? "Interrupted Hydration" : "Interrupted Render";
            debugTask ? debugTask.run(
              console.timeStamp.bind(
                console,
                label2,
                previousRenderStartTime,
                endTime,
                currentTrack,
                LANES_TRACK_GROUP,
                color
              )
            ) : console.timeStamp(
              label2,
              previousRenderStartTime,
              endTime,
              currentTrack,
              LANES_TRACK_GROUP,
              color
            );
          }
        }
        finalizeRender(workInProgressRootRenderLanes, renderStartTime);
      }
      previousRenderStartTime = workInProgressUpdateTask;
      workInProgressUpdateTask = null;
      if (0 !== (lanes & 127)) {
        workInProgressUpdateTask = blockingUpdateTask;
        debugTask = 0 <= blockingUpdateTime && blockingUpdateTime < blockingClampTime ? blockingClampTime : blockingUpdateTime;
        endTime = 0 <= blockingEventTime && blockingEventTime < blockingClampTime ? blockingClampTime : blockingEventTime;
        color = 0 <= endTime ? endTime : 0 <= debugTask ? debugTask : renderStartTime;
        0 <= blockingSuspendedTime ? (setCurrentTrackFromLanes(2), logSuspendedWithDelayPhase(
          blockingSuspendedTime,
          color,
          lanes,
          previousRenderStartTime
        )) : 0 !== (animatingLanes & 127);
        previousRenderStartTime = debugTask;
        var eventTime = endTime, eventType = blockingEventType, eventIsRepeat = 0 < blockingEventRepeatTime, isSpawnedUpdate = blockingUpdateType === SPAWNED_UPDATE, isPingedUpdate = blockingUpdateType === PINGED_UPDATE;
        debugTask = renderStartTime;
        endTime = blockingUpdateTask;
        color = blockingUpdateMethodName;
        label2 = blockingUpdateComponentName;
        if (supportsUserTiming) {
          currentTrack = "Blocking";
          0 < previousRenderStartTime ? previousRenderStartTime > debugTask && (previousRenderStartTime = debugTask) : previousRenderStartTime = debugTask;
          0 < eventTime ? eventTime > previousRenderStartTime && (eventTime = previousRenderStartTime) : eventTime = previousRenderStartTime;
          if (null !== eventType && previousRenderStartTime > eventTime) {
            var color$jscomp$0 = eventIsRepeat ? "secondary-light" : "warning";
            endTime ? endTime.run(
              console.timeStamp.bind(
                console,
                eventIsRepeat ? "Consecutive" : "Event: " + eventType,
                eventTime,
                previousRenderStartTime,
                currentTrack,
                LANES_TRACK_GROUP,
                color$jscomp$0
              )
            ) : console.timeStamp(
              eventIsRepeat ? "Consecutive" : "Event: " + eventType,
              eventTime,
              previousRenderStartTime,
              currentTrack,
              LANES_TRACK_GROUP,
              color$jscomp$0
            );
          }
          debugTask > previousRenderStartTime && (eventTime = isSpawnedUpdate ? "error" : (lanes & 738197653) === lanes ? "tertiary-light" : "primary-light", isSpawnedUpdate = isPingedUpdate ? "Promise Resolved" : isSpawnedUpdate ? "Cascading Update" : 5 < debugTask - previousRenderStartTime ? "Update Blocked" : "Update", isPingedUpdate = [], null != label2 && isPingedUpdate.push(["Component name", label2]), null != color && isPingedUpdate.push(["Method name", color]), previousRenderStartTime = {
            start: previousRenderStartTime,
            end: debugTask,
            detail: {
              devtools: {
                properties: isPingedUpdate,
                track: currentTrack,
                trackGroup: LANES_TRACK_GROUP,
                color: eventTime
              }
            }
          }, endTime ? endTime.run(
            performance.measure.bind(
              performance,
              isSpawnedUpdate,
              previousRenderStartTime
            )
          ) : performance.measure(isSpawnedUpdate, previousRenderStartTime));
        }
        blockingUpdateTime = -1.1;
        blockingUpdateType = 0;
        blockingUpdateComponentName = blockingUpdateMethodName = null;
        blockingSuspendedTime = -1.1;
        blockingEventRepeatTime = blockingEventTime;
        blockingEventTime = -1.1;
        blockingClampTime = now2();
      }
      0 !== (lanes & 4194048) && (workInProgressUpdateTask = transitionUpdateTask, debugTask = 0 <= transitionStartTime && transitionStartTime < transitionClampTime ? transitionClampTime : transitionStartTime, previousRenderStartTime = 0 <= transitionUpdateTime && transitionUpdateTime < transitionClampTime ? transitionClampTime : transitionUpdateTime, endTime = 0 <= transitionEventTime && transitionEventTime < transitionClampTime ? transitionClampTime : transitionEventTime, color = 0 <= endTime ? endTime : 0 <= previousRenderStartTime ? previousRenderStartTime : renderStartTime, 0 <= transitionSuspendedTime ? (setCurrentTrackFromLanes(256), logSuspendedWithDelayPhase(
        transitionSuspendedTime,
        color,
        lanes,
        workInProgressUpdateTask
      )) : 0 !== (animatingLanes & 4194048), isPingedUpdate = endTime, eventTime = transitionEventType, eventType = 0 < transitionEventRepeatTime, eventIsRepeat = transitionUpdateType === PINGED_UPDATE, color = renderStartTime, endTime = transitionUpdateTask, label2 = transitionUpdateMethodName, isSpawnedUpdate = transitionUpdateComponentName, supportsUserTiming && (currentTrack = "Transition", 0 < previousRenderStartTime ? previousRenderStartTime > color && (previousRenderStartTime = color) : previousRenderStartTime = color, 0 < debugTask ? debugTask > previousRenderStartTime && (debugTask = previousRenderStartTime) : debugTask = previousRenderStartTime, 0 < isPingedUpdate ? isPingedUpdate > debugTask && (isPingedUpdate = debugTask) : isPingedUpdate = debugTask, debugTask > isPingedUpdate && null !== eventTime && (color$jscomp$0 = eventType ? "secondary-light" : "warning", endTime ? endTime.run(
        console.timeStamp.bind(
          console,
          eventType ? "Consecutive" : "Event: " + eventTime,
          isPingedUpdate,
          debugTask,
          currentTrack,
          LANES_TRACK_GROUP,
          color$jscomp$0
        )
      ) : console.timeStamp(
        eventType ? "Consecutive" : "Event: " + eventTime,
        isPingedUpdate,
        debugTask,
        currentTrack,
        LANES_TRACK_GROUP,
        color$jscomp$0
      )), previousRenderStartTime > debugTask && (endTime ? endTime.run(
        console.timeStamp.bind(
          console,
          "Action",
          debugTask,
          previousRenderStartTime,
          currentTrack,
          LANES_TRACK_GROUP,
          "primary-dark"
        )
      ) : console.timeStamp(
        "Action",
        debugTask,
        previousRenderStartTime,
        currentTrack,
        LANES_TRACK_GROUP,
        "primary-dark"
      )), color > previousRenderStartTime && (debugTask = eventIsRepeat ? "Promise Resolved" : 5 < color - previousRenderStartTime ? "Update Blocked" : "Update", isPingedUpdate = [], null != isSpawnedUpdate && isPingedUpdate.push(["Component name", isSpawnedUpdate]), null != label2 && isPingedUpdate.push(["Method name", label2]), previousRenderStartTime = {
        start: previousRenderStartTime,
        end: color,
        detail: {
          devtools: {
            properties: isPingedUpdate,
            track: currentTrack,
            trackGroup: LANES_TRACK_GROUP,
            color: "primary-light"
          }
        }
      }, endTime ? endTime.run(
        performance.measure.bind(
          performance,
          debugTask,
          previousRenderStartTime
        )
      ) : performance.measure(debugTask, previousRenderStartTime))), transitionUpdateTime = transitionStartTime = -1.1, transitionUpdateType = 0, transitionSuspendedTime = -1.1, transitionEventRepeatTime = transitionEventTime, transitionEventTime = -1.1, transitionClampTime = now2());
      0 !== (lanes & 62914560) && 0 !== (animatingLanes & 62914560) && (setCurrentTrackFromLanes(4194304), logAnimatingPhase(retryClampTime, renderStartTime));
      0 !== (lanes & 2080374784) && 0 !== (animatingLanes & 2080374784) && (setCurrentTrackFromLanes(268435456), logAnimatingPhase(idleClampTime, renderStartTime));
      previousRenderStartTime = root22.timeoutHandle;
      previousRenderStartTime !== noTimeout && (root22.timeoutHandle = noTimeout, cancelTimeout(previousRenderStartTime));
      previousRenderStartTime = root22.cancelPendingCommit;
      null !== previousRenderStartTime && (root22.cancelPendingCommit = null, previousRenderStartTime());
      pendingEffectsLanes = 0;
      resetWorkInProgressStack();
      workInProgressRoot = root22;
      workInProgress = previousRenderStartTime = createWorkInProgress(
        root22.current,
        null
      );
      workInProgressRootRenderLanes = lanes;
      workInProgressSuspendedReason = NotSuspended;
      workInProgressThrownValue = null;
      workInProgressRootDidSkipSuspendedSiblings = false;
      workInProgressRootIsPrerendering = checkIfRootIsPrerendering(root22, lanes);
      workInProgressRootDidAttachPingListener = false;
      workInProgressRootExitStatus = RootInProgress;
      workInProgressSuspendedRetryLanes = workInProgressDeferredLane = workInProgressRootPingedLanes = workInProgressRootInterleavedUpdatedLanes = workInProgressRootSkippedLanes = 0;
      workInProgressRootRecoverableErrors = workInProgressRootConcurrentErrors = null;
      workInProgressRootDidIncludeRecursiveRenderUpdate = false;
      0 !== (lanes & 8) && (lanes |= lanes & 32);
      endTime = root22.entangledLanes;
      if (0 !== endTime)
        for (root22 = root22.entanglements, endTime &= lanes; 0 < endTime; )
          debugTask = 31 - clz322(endTime), color = 1 << debugTask, lanes |= root22[debugTask], endTime &= ~color;
      entangledRenderLanes = lanes;
      finishQueueingConcurrentUpdates();
      root22 = getCurrentTime();
      1e3 < root22 - lastResetTime && (ReactSharedInternals.recentlyCreatedOwnerStacks = 0, lastResetTime = root22);
      ReactStrictModeWarnings.discardPendingWarnings();
      return previousRenderStartTime;
    }
    function handleThrow(root22, thrownValue) {
      currentlyRenderingFiber = null;
      ReactSharedInternals.H = ContextOnlyDispatcher;
      ReactSharedInternals.getCurrentStack = null;
      isRendering = false;
      current3 = null;
      thrownValue === SuspenseException || thrownValue === SuspenseActionException ? (thrownValue = getSuspendedThenable(), workInProgressSuspendedReason = SuspendedOnImmediate) : thrownValue === SuspenseyCommitException ? (thrownValue = getSuspendedThenable(), workInProgressSuspendedReason = SuspendedOnInstance) : workInProgressSuspendedReason = thrownValue === SelectiveHydrationException ? SuspendedOnHydration : null !== thrownValue && "object" === typeof thrownValue && "function" === typeof thrownValue.then ? SuspendedOnDeprecatedThrowPromise : SuspendedOnError;
      workInProgressThrownValue = thrownValue;
      var erroredWork = workInProgress;
      null === erroredWork ? (workInProgressRootExitStatus = RootFatalErrored, logUncaughtError(
        root22,
        createCapturedValueAtFiber(thrownValue, root22.current)
      )) : erroredWork.mode & ProfileMode && stopProfilerTimerIfRunningAndRecordDuration(erroredWork);
    }
    function shouldRemainOnPreviousScreen() {
      var handler = suspenseHandlerStackCursor.current;
      return null === handler ? true : (workInProgressRootRenderLanes & 4194048) === workInProgressRootRenderLanes ? null === shellBoundary ? true : false : (workInProgressRootRenderLanes & 62914560) === workInProgressRootRenderLanes || 0 !== (workInProgressRootRenderLanes & 536870912) ? handler === shellBoundary : false;
    }
    function pushDispatcher() {
      var prevDispatcher = ReactSharedInternals.H;
      ReactSharedInternals.H = ContextOnlyDispatcher;
      return null === prevDispatcher ? ContextOnlyDispatcher : prevDispatcher;
    }
    function pushAsyncDispatcher() {
      var prevAsyncDispatcher = ReactSharedInternals.A;
      ReactSharedInternals.A = DefaultAsyncDispatcher;
      return prevAsyncDispatcher;
    }
    function markRenderDerivedCause(fiber) {
      null === workInProgressUpdateTask && (workInProgressUpdateTask = null == fiber._debugTask ? null : fiber._debugTask);
    }
    function renderDidSuspendDelayIfPossible() {
      workInProgressRootExitStatus = RootSuspendedWithDelay;
      workInProgressRootDidSkipSuspendedSiblings || (workInProgressRootRenderLanes & 4194048) !== workInProgressRootRenderLanes && null !== suspenseHandlerStackCursor.current || (workInProgressRootIsPrerendering = true);
      0 === (workInProgressRootSkippedLanes & 134217727) && 0 === (workInProgressRootInterleavedUpdatedLanes & 134217727) || null === workInProgressRoot || markRootSuspended(
        workInProgressRoot,
        workInProgressRootRenderLanes,
        workInProgressDeferredLane,
        false
      );
    }
    function renderRootSync(root22, lanes, shouldYieldForPrerendering) {
      var prevExecutionContext = executionContext;
      executionContext |= RenderContext;
      var prevDispatcher = pushDispatcher(), prevAsyncDispatcher = pushAsyncDispatcher();
      if (workInProgressRoot !== root22 || workInProgressRootRenderLanes !== lanes) {
        if (isDevToolsPresent) {
          var memoizedUpdaters = root22.memoizedUpdaters;
          0 < memoizedUpdaters.size && (restorePendingUpdaters(root22, workInProgressRootRenderLanes), memoizedUpdaters.clear());
          movePendingFibersToMemoized(root22, lanes);
        }
        workInProgressTransitions = null;
        prepareFreshStack(root22, lanes);
      }
      lanes = false;
      memoizedUpdaters = workInProgressRootExitStatus;
      a: do
        try {
          if (workInProgressSuspendedReason !== NotSuspended && null !== workInProgress) {
            var unitOfWork = workInProgress, thrownValue = workInProgressThrownValue;
            switch (workInProgressSuspendedReason) {
              case SuspendedOnHydration:
                resetWorkInProgressStack();
                memoizedUpdaters = RootSuspendedAtTheShell;
                break a;
              case SuspendedOnImmediate:
              case SuspendedOnData:
              case SuspendedOnAction:
              case SuspendedOnDeprecatedThrowPromise:
                null === suspenseHandlerStackCursor.current && (lanes = true);
                var reason = workInProgressSuspendedReason;
                workInProgressSuspendedReason = NotSuspended;
                workInProgressThrownValue = null;
                throwAndUnwindWorkLoop(root22, unitOfWork, thrownValue, reason);
                if (shouldYieldForPrerendering && workInProgressRootIsPrerendering) {
                  memoizedUpdaters = RootInProgress;
                  break a;
                }
                break;
              default:
                reason = workInProgressSuspendedReason, workInProgressSuspendedReason = NotSuspended, workInProgressThrownValue = null, throwAndUnwindWorkLoop(root22, unitOfWork, thrownValue, reason);
            }
          }
          workLoopSync();
          memoizedUpdaters = workInProgressRootExitStatus;
          break;
        } catch (thrownValue$8) {
          handleThrow(root22, thrownValue$8);
        }
      while (1);
      lanes && root22.shellSuspendCounter++;
      resetContextDependencies();
      executionContext = prevExecutionContext;
      ReactSharedInternals.H = prevDispatcher;
      ReactSharedInternals.A = prevAsyncDispatcher;
      null === workInProgress && (workInProgressRoot = null, workInProgressRootRenderLanes = 0, finishQueueingConcurrentUpdates());
      return memoizedUpdaters;
    }
    function workLoopSync() {
      for (; null !== workInProgress; ) performUnitOfWork(workInProgress);
    }
    function renderRootConcurrent(root22, lanes) {
      var prevExecutionContext = executionContext;
      executionContext |= RenderContext;
      var prevDispatcher = pushDispatcher(), prevAsyncDispatcher = pushAsyncDispatcher();
      if (workInProgressRoot !== root22 || workInProgressRootRenderLanes !== lanes) {
        if (isDevToolsPresent) {
          var memoizedUpdaters = root22.memoizedUpdaters;
          0 < memoizedUpdaters.size && (restorePendingUpdaters(root22, workInProgressRootRenderLanes), memoizedUpdaters.clear());
          movePendingFibersToMemoized(root22, lanes);
        }
        workInProgressTransitions = null;
        workInProgressRootRenderTargetTime = now$1() + RENDER_TIMEOUT_MS;
        prepareFreshStack(root22, lanes);
      } else
        workInProgressRootIsPrerendering = checkIfRootIsPrerendering(
          root22,
          lanes
        );
      a: do
        try {
          if (workInProgressSuspendedReason !== NotSuspended && null !== workInProgress)
            b: switch (lanes = workInProgress, memoizedUpdaters = workInProgressThrownValue, workInProgressSuspendedReason) {
              case SuspendedOnError:
                workInProgressSuspendedReason = NotSuspended;
                workInProgressThrownValue = null;
                throwAndUnwindWorkLoop(
                  root22,
                  lanes,
                  memoizedUpdaters,
                  SuspendedOnError
                );
                break;
              case SuspendedOnData:
              case SuspendedOnAction:
                if (isThenableResolved(memoizedUpdaters)) {
                  workInProgressSuspendedReason = NotSuspended;
                  workInProgressThrownValue = null;
                  replaySuspendedUnitOfWork(lanes);
                  break;
                }
                lanes = function() {
                  workInProgressSuspendedReason !== SuspendedOnData && workInProgressSuspendedReason !== SuspendedOnAction || workInProgressRoot !== root22 || (workInProgressSuspendedReason = SuspendedAndReadyToContinue);
                  ensureRootIsScheduled(root22);
                };
                memoizedUpdaters.then(lanes, lanes);
                break a;
              case SuspendedOnImmediate:
                workInProgressSuspendedReason = SuspendedAndReadyToContinue;
                break a;
              case SuspendedOnInstance:
                workInProgressSuspendedReason = SuspendedOnInstanceAndReadyToContinue;
                break a;
              case SuspendedAndReadyToContinue:
                isThenableResolved(memoizedUpdaters) ? (workInProgressSuspendedReason = NotSuspended, workInProgressThrownValue = null, replaySuspendedUnitOfWork(lanes)) : (workInProgressSuspendedReason = NotSuspended, workInProgressThrownValue = null, throwAndUnwindWorkLoop(
                  root22,
                  lanes,
                  memoizedUpdaters,
                  SuspendedAndReadyToContinue
                ));
                break;
              case SuspendedOnInstanceAndReadyToContinue:
                var resource = null;
                switch (workInProgress.tag) {
                  case 26:
                    resource = workInProgress.memoizedState;
                  case 5:
                  case 27:
                    var hostFiber = workInProgress;
                    if (resource ? preloadResource(resource) : hostFiber.stateNode.complete) {
                      workInProgressSuspendedReason = NotSuspended;
                      workInProgressThrownValue = null;
                      var sibling2 = hostFiber.sibling;
                      if (null !== sibling2) workInProgress = sibling2;
                      else {
                        var returnFiber = hostFiber.return;
                        null !== returnFiber ? (workInProgress = returnFiber, completeUnitOfWork(returnFiber)) : workInProgress = null;
                      }
                      break b;
                    }
                    break;
                  default:
                    console.error(
                      "Unexpected type of fiber triggered a suspensey commit. This is a bug in React."
                    );
                }
                workInProgressSuspendedReason = NotSuspended;
                workInProgressThrownValue = null;
                throwAndUnwindWorkLoop(
                  root22,
                  lanes,
                  memoizedUpdaters,
                  SuspendedOnInstanceAndReadyToContinue
                );
                break;
              case SuspendedOnDeprecatedThrowPromise:
                workInProgressSuspendedReason = NotSuspended;
                workInProgressThrownValue = null;
                throwAndUnwindWorkLoop(
                  root22,
                  lanes,
                  memoizedUpdaters,
                  SuspendedOnDeprecatedThrowPromise
                );
                break;
              case SuspendedOnHydration:
                resetWorkInProgressStack();
                workInProgressRootExitStatus = RootSuspendedAtTheShell;
                break a;
              default:
                throw Error(
                  "Unexpected SuspendedReason. This is a bug in React."
                );
            }
          null !== ReactSharedInternals.actQueue ? workLoopSync() : workLoopConcurrentByScheduler();
          break;
        } catch (thrownValue$9) {
          handleThrow(root22, thrownValue$9);
        }
      while (1);
      resetContextDependencies();
      ReactSharedInternals.H = prevDispatcher;
      ReactSharedInternals.A = prevAsyncDispatcher;
      executionContext = prevExecutionContext;
      if (null !== workInProgress) return RootInProgress;
      workInProgressRoot = null;
      workInProgressRootRenderLanes = 0;
      finishQueueingConcurrentUpdates();
      return workInProgressRootExitStatus;
    }
    function workLoopConcurrentByScheduler() {
      for (; null !== workInProgress && !shouldYield(); )
        performUnitOfWork(workInProgress);
    }
    function performUnitOfWork(unitOfWork) {
      var current22 = unitOfWork.alternate;
      (unitOfWork.mode & ProfileMode) !== NoMode ? (startProfilerTimer(unitOfWork), current22 = runWithFiberInDEV(
        unitOfWork,
        beginWork,
        current22,
        unitOfWork,
        entangledRenderLanes
      ), stopProfilerTimerIfRunningAndRecordDuration(unitOfWork)) : current22 = runWithFiberInDEV(
        unitOfWork,
        beginWork,
        current22,
        unitOfWork,
        entangledRenderLanes
      );
      unitOfWork.memoizedProps = unitOfWork.pendingProps;
      null === current22 ? completeUnitOfWork(unitOfWork) : workInProgress = current22;
    }
    function replaySuspendedUnitOfWork(unitOfWork) {
      var next = runWithFiberInDEV(unitOfWork, replayBeginWork, unitOfWork);
      unitOfWork.memoizedProps = unitOfWork.pendingProps;
      null === next ? completeUnitOfWork(unitOfWork) : workInProgress = next;
    }
    function replayBeginWork(unitOfWork) {
      var current22 = unitOfWork.alternate, isProfilingMode = (unitOfWork.mode & ProfileMode) !== NoMode;
      isProfilingMode && startProfilerTimer(unitOfWork);
      switch (unitOfWork.tag) {
        case 15:
        case 0:
          current22 = replayFunctionComponent(
            current22,
            unitOfWork,
            unitOfWork.pendingProps,
            unitOfWork.type,
            void 0,
            workInProgressRootRenderLanes
          );
          break;
        case 11:
          current22 = replayFunctionComponent(
            current22,
            unitOfWork,
            unitOfWork.pendingProps,
            unitOfWork.type.render,
            unitOfWork.ref,
            workInProgressRootRenderLanes
          );
          break;
        case 5:
          resetHooksOnUnwind(unitOfWork);
        default:
          unwindInterruptedWork(current22, unitOfWork), unitOfWork = workInProgress = resetWorkInProgress(unitOfWork, entangledRenderLanes), current22 = beginWork(current22, unitOfWork, entangledRenderLanes);
      }
      isProfilingMode && stopProfilerTimerIfRunningAndRecordDuration(unitOfWork);
      return current22;
    }
    function throwAndUnwindWorkLoop(root22, unitOfWork, thrownValue, suspendedReason) {
      resetContextDependencies();
      resetHooksOnUnwind(unitOfWork);
      thenableState$1 = null;
      thenableIndexCounter$1 = 0;
      var returnFiber = unitOfWork.return;
      try {
        if (throwException(
          root22,
          returnFiber,
          unitOfWork,
          thrownValue,
          workInProgressRootRenderLanes
        )) {
          workInProgressRootExitStatus = RootFatalErrored;
          logUncaughtError(
            root22,
            createCapturedValueAtFiber(thrownValue, root22.current)
          );
          workInProgress = null;
          return;
        }
      } catch (error2) {
        if (null !== returnFiber) throw workInProgress = returnFiber, error2;
        workInProgressRootExitStatus = RootFatalErrored;
        logUncaughtError(
          root22,
          createCapturedValueAtFiber(thrownValue, root22.current)
        );
        workInProgress = null;
        return;
      }
      if (unitOfWork.flags & 32768) {
        if (isHydrating || suspendedReason === SuspendedOnError) root22 = true;
        else if (workInProgressRootIsPrerendering || 0 !== (workInProgressRootRenderLanes & 536870912))
          root22 = false;
        else if (workInProgressRootDidSkipSuspendedSiblings = root22 = true, suspendedReason === SuspendedOnData || suspendedReason === SuspendedOnAction || suspendedReason === SuspendedOnImmediate || suspendedReason === SuspendedOnDeprecatedThrowPromise)
          suspendedReason = suspenseHandlerStackCursor.current, null !== suspendedReason && 13 === suspendedReason.tag && (suspendedReason.flags |= 16384);
        unwindUnitOfWork(unitOfWork, root22);
      } else completeUnitOfWork(unitOfWork);
    }
    function completeUnitOfWork(unitOfWork) {
      var completedWork = unitOfWork;
      do {
        if (0 !== (completedWork.flags & 32768)) {
          unwindUnitOfWork(
            completedWork,
            workInProgressRootDidSkipSuspendedSiblings
          );
          return;
        }
        var current22 = completedWork.alternate;
        unitOfWork = completedWork.return;
        startProfilerTimer(completedWork);
        current22 = runWithFiberInDEV(
          completedWork,
          completeWork,
          current22,
          completedWork,
          entangledRenderLanes
        );
        (completedWork.mode & ProfileMode) !== NoMode && stopProfilerTimerIfRunningAndRecordIncompleteDuration(completedWork);
        if (null !== current22) {
          workInProgress = current22;
          return;
        }
        completedWork = completedWork.sibling;
        if (null !== completedWork) {
          workInProgress = completedWork;
          return;
        }
        workInProgress = completedWork = unitOfWork;
      } while (null !== completedWork);
      workInProgressRootExitStatus === RootInProgress && (workInProgressRootExitStatus = RootCompleted);
    }
    function unwindUnitOfWork(unitOfWork, skipSiblings) {
      do {
        var next = unwindWork(unitOfWork.alternate, unitOfWork);
        if (null !== next) {
          next.flags &= 32767;
          workInProgress = next;
          return;
        }
        if ((unitOfWork.mode & ProfileMode) !== NoMode) {
          stopProfilerTimerIfRunningAndRecordIncompleteDuration(unitOfWork);
          next = unitOfWork.actualDuration;
          for (var child = unitOfWork.child; null !== child; )
            next += child.actualDuration, child = child.sibling;
          unitOfWork.actualDuration = next;
        }
        next = unitOfWork.return;
        null !== next && (next.flags |= 32768, next.subtreeFlags = 0, next.deletions = null);
        if (!skipSiblings && (unitOfWork = unitOfWork.sibling, null !== unitOfWork)) {
          workInProgress = unitOfWork;
          return;
        }
        workInProgress = unitOfWork = next;
      } while (null !== unitOfWork);
      workInProgressRootExitStatus = RootSuspendedAtTheShell;
      workInProgress = null;
    }
    function commitRoot(root22, finishedWork, lanes, recoverableErrors, transitions, didIncludeRenderPhaseUpdate, spawnedLane, updatedLanes, suspendedRetryLanes, exitStatus, suspendedState, suspendedCommitReason, completedRenderStartTime, completedRenderEndTime) {
      root22.cancelPendingCommit = null;
      do
        flushPendingEffects();
      while (pendingEffectsStatus !== NO_PENDING_EFFECTS);
      ReactStrictModeWarnings.flushLegacyContextWarning();
      ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
      if ((executionContext & (RenderContext | CommitContext)) !== NoContext)
        throw Error("Should not already be working.");
      setCurrentTrackFromLanes(lanes);
      exitStatus === RootErrored ? logErroredRenderPhase(
        completedRenderStartTime,
        completedRenderEndTime,
        lanes,
        workInProgressUpdateTask
      ) : null !== recoverableErrors ? logRecoveredRenderPhase(
        completedRenderStartTime,
        completedRenderEndTime,
        lanes,
        recoverableErrors,
        null !== finishedWork && null !== finishedWork.alternate && finishedWork.alternate.memoizedState.isDehydrated && 0 !== (finishedWork.flags & 256),
        workInProgressUpdateTask
      ) : logRenderPhase(
        completedRenderStartTime,
        completedRenderEndTime,
        lanes,
        workInProgressUpdateTask
      );
      if (null !== finishedWork) {
        0 === lanes && console.error(
          "finishedLanes should not be empty during a commit. This is a bug in React."
        );
        if (finishedWork === root22.current)
          throw Error(
            "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue."
          );
        didIncludeRenderPhaseUpdate = finishedWork.lanes | finishedWork.childLanes;
        didIncludeRenderPhaseUpdate |= concurrentlyUpdatedLanes;
        markRootFinished(
          root22,
          lanes,
          didIncludeRenderPhaseUpdate,
          spawnedLane,
          updatedLanes,
          suspendedRetryLanes
        );
        root22 === workInProgressRoot && (workInProgress = workInProgressRoot = null, workInProgressRootRenderLanes = 0);
        pendingFinishedWork = finishedWork;
        pendingEffectsRoot = root22;
        pendingEffectsLanes = lanes;
        pendingEffectsRemainingLanes = didIncludeRenderPhaseUpdate;
        pendingPassiveTransitions = transitions;
        pendingRecoverableErrors = recoverableErrors;
        pendingEffectsRenderEndTime = completedRenderEndTime;
        pendingSuspendedCommitReason = suspendedCommitReason;
        pendingDelayedCommitReason = IMMEDIATE_COMMIT;
        pendingSuspendedViewTransitionReason = null;
        0 !== finishedWork.actualDuration || 0 !== (finishedWork.subtreeFlags & 10256) || 0 !== (finishedWork.flags & 10256) ? (root22.callbackNode = null, root22.callbackPriority = 0, scheduleCallback$1(NormalPriority$1, function() {
          schedulerEvent = window.event;
          pendingDelayedCommitReason === IMMEDIATE_COMMIT && (pendingDelayedCommitReason = DELAYED_PASSIVE_COMMIT);
          flushPassiveEffects();
          return null;
        })) : (root22.callbackNode = null, root22.callbackPriority = 0);
        commitErrors = null;
        commitStartTime = now2();
        null !== suspendedCommitReason && logSuspendedCommitPhase(
          completedRenderEndTime,
          commitStartTime,
          suspendedCommitReason,
          workInProgressUpdateTask
        );
        recoverableErrors = 0 !== (finishedWork.flags & 13878);
        if (0 !== (finishedWork.subtreeFlags & 13878) || recoverableErrors) {
          recoverableErrors = ReactSharedInternals.T;
          ReactSharedInternals.T = null;
          transitions = ReactDOMSharedInternals.p;
          ReactDOMSharedInternals.p = DiscreteEventPriority;
          spawnedLane = executionContext;
          executionContext |= CommitContext;
          try {
            commitBeforeMutationEffects(root22, finishedWork, lanes);
          } finally {
            executionContext = spawnedLane, ReactDOMSharedInternals.p = transitions, ReactSharedInternals.T = recoverableErrors;
          }
        }
        pendingEffectsStatus = PENDING_MUTATION_PHASE;
        flushMutationEffects();
        flushLayoutEffects();
        flushSpawnedWork();
      }
    }
    function flushMutationEffects() {
      if (pendingEffectsStatus === PENDING_MUTATION_PHASE) {
        pendingEffectsStatus = NO_PENDING_EFFECTS;
        var root22 = pendingEffectsRoot, finishedWork = pendingFinishedWork, lanes = pendingEffectsLanes, rootMutationHasEffect = 0 !== (finishedWork.flags & 13878);
        if (0 !== (finishedWork.subtreeFlags & 13878) || rootMutationHasEffect) {
          rootMutationHasEffect = ReactSharedInternals.T;
          ReactSharedInternals.T = null;
          var previousPriority = ReactDOMSharedInternals.p;
          ReactDOMSharedInternals.p = DiscreteEventPriority;
          var prevExecutionContext = executionContext;
          executionContext |= CommitContext;
          try {
            inProgressLanes = lanes;
            inProgressRoot = root22;
            resetComponentEffectTimers();
            commitMutationEffectsOnFiber(finishedWork, root22);
            inProgressRoot = inProgressLanes = null;
            lanes = selectionInformation;
            var curFocusedElem = getActiveElementDeep(root22.containerInfo), priorFocusedElem = lanes.focusedElem, priorSelectionRange = lanes.selectionRange;
            if (curFocusedElem !== priorFocusedElem && priorFocusedElem && priorFocusedElem.ownerDocument && containsNode(
              priorFocusedElem.ownerDocument.documentElement,
              priorFocusedElem
            )) {
              if (null !== priorSelectionRange && hasSelectionCapabilities(priorFocusedElem)) {
                var start2 = priorSelectionRange.start, end2 = priorSelectionRange.end;
                void 0 === end2 && (end2 = start2);
                if ("selectionStart" in priorFocusedElem)
                  priorFocusedElem.selectionStart = start2, priorFocusedElem.selectionEnd = Math.min(
                    end2,
                    priorFocusedElem.value.length
                  );
                else {
                  var doc = priorFocusedElem.ownerDocument || document, win = doc && doc.defaultView || window;
                  if (win.getSelection) {
                    var selection = win.getSelection(), length2 = priorFocusedElem.textContent.length, start$jscomp$0 = Math.min(
                      priorSelectionRange.start,
                      length2
                    ), end$jscomp$0 = void 0 === priorSelectionRange.end ? start$jscomp$0 : Math.min(priorSelectionRange.end, length2);
                    !selection.extend && start$jscomp$0 > end$jscomp$0 && (curFocusedElem = end$jscomp$0, end$jscomp$0 = start$jscomp$0, start$jscomp$0 = curFocusedElem);
                    var startMarker = getNodeForCharacterOffset(
                      priorFocusedElem,
                      start$jscomp$0
                    ), endMarker = getNodeForCharacterOffset(
                      priorFocusedElem,
                      end$jscomp$0
                    );
                    if (startMarker && endMarker && (1 !== selection.rangeCount || selection.anchorNode !== startMarker.node || selection.anchorOffset !== startMarker.offset || selection.focusNode !== endMarker.node || selection.focusOffset !== endMarker.offset)) {
                      var range = doc.createRange();
                      range.setStart(startMarker.node, startMarker.offset);
                      selection.removeAllRanges();
                      start$jscomp$0 > end$jscomp$0 ? (selection.addRange(range), selection.extend(endMarker.node, endMarker.offset)) : (range.setEnd(endMarker.node, endMarker.offset), selection.addRange(range));
                    }
                  }
                }
              }
              doc = [];
              for (selection = priorFocusedElem; selection = selection.parentNode; )
                1 === selection.nodeType && doc.push({
                  element: selection,
                  left: selection.scrollLeft,
                  top: selection.scrollTop
                });
              "function" === typeof priorFocusedElem.focus && priorFocusedElem.focus();
              for (priorFocusedElem = 0; priorFocusedElem < doc.length; priorFocusedElem++) {
                var info = doc[priorFocusedElem];
                info.element.scrollLeft = info.left;
                info.element.scrollTop = info.top;
              }
            }
            _enabled = !!eventsEnabled;
            selectionInformation = eventsEnabled = null;
          } finally {
            executionContext = prevExecutionContext, ReactDOMSharedInternals.p = previousPriority, ReactSharedInternals.T = rootMutationHasEffect;
          }
        }
        root22.current = finishedWork;
        pendingEffectsStatus = PENDING_LAYOUT_PHASE;
      }
    }
    function flushLayoutEffects() {
      if (pendingEffectsStatus === PENDING_LAYOUT_PHASE) {
        pendingEffectsStatus = NO_PENDING_EFFECTS;
        var suspendedViewTransitionReason = pendingSuspendedViewTransitionReason;
        if (null !== suspendedViewTransitionReason) {
          commitStartTime = now2();
          var startTime = commitEndTime, endTime = commitStartTime;
          !supportsUserTiming || endTime <= startTime || console.timeStamp(
            suspendedViewTransitionReason,
            startTime,
            endTime,
            currentTrack,
            LANES_TRACK_GROUP,
            "secondary-light"
          );
        }
        suspendedViewTransitionReason = pendingEffectsRoot;
        startTime = pendingFinishedWork;
        endTime = pendingEffectsLanes;
        var rootHasLayoutEffect = 0 !== (startTime.flags & 8772);
        if (0 !== (startTime.subtreeFlags & 8772) || rootHasLayoutEffect) {
          rootHasLayoutEffect = ReactSharedInternals.T;
          ReactSharedInternals.T = null;
          var _previousPriority = ReactDOMSharedInternals.p;
          ReactDOMSharedInternals.p = DiscreteEventPriority;
          var _prevExecutionContext = executionContext;
          executionContext |= CommitContext;
          try {
            inProgressLanes = endTime, inProgressRoot = suspendedViewTransitionReason, resetComponentEffectTimers(), commitLayoutEffectOnFiber(
              suspendedViewTransitionReason,
              startTime.alternate,
              startTime
            ), inProgressRoot = inProgressLanes = null;
          } finally {
            executionContext = _prevExecutionContext, ReactDOMSharedInternals.p = _previousPriority, ReactSharedInternals.T = rootHasLayoutEffect;
          }
        }
        suspendedViewTransitionReason = pendingEffectsRenderEndTime;
        startTime = pendingSuspendedCommitReason;
        commitEndTime = now2();
        suspendedViewTransitionReason = null === startTime ? suspendedViewTransitionReason : commitStartTime;
        startTime = commitEndTime;
        endTime = pendingDelayedCommitReason === ABORTED_VIEW_TRANSITION_COMMIT;
        rootHasLayoutEffect = workInProgressUpdateTask;
        null !== commitErrors ? logCommitErrored(
          suspendedViewTransitionReason,
          startTime,
          commitErrors,
          false,
          rootHasLayoutEffect
        ) : !supportsUserTiming || startTime <= suspendedViewTransitionReason || (rootHasLayoutEffect ? rootHasLayoutEffect.run(
          console.timeStamp.bind(
            console,
            endTime ? "Commit Interrupted View Transition" : "Commit",
            suspendedViewTransitionReason,
            startTime,
            currentTrack,
            LANES_TRACK_GROUP,
            endTime ? "error" : "secondary-dark"
          )
        ) : console.timeStamp(
          endTime ? "Commit Interrupted View Transition" : "Commit",
          suspendedViewTransitionReason,
          startTime,
          currentTrack,
          LANES_TRACK_GROUP,
          endTime ? "error" : "secondary-dark"
        ));
        pendingEffectsStatus = PENDING_AFTER_MUTATION_PHASE;
      }
    }
    function flushSpawnedWork() {
      if (pendingEffectsStatus === PENDING_SPAWNED_WORK || pendingEffectsStatus === PENDING_AFTER_MUTATION_PHASE) {
        if (pendingEffectsStatus === PENDING_SPAWNED_WORK) {
          var startViewTransitionStartTime = commitEndTime;
          commitEndTime = now2();
          var endTime = commitEndTime, abortedViewTransition = pendingDelayedCommitReason === ABORTED_VIEW_TRANSITION_COMMIT;
          !supportsUserTiming || endTime <= startViewTransitionStartTime || console.timeStamp(
            abortedViewTransition ? "Interrupted View Transition" : "Starting Animation",
            startViewTransitionStartTime,
            endTime,
            currentTrack,
            LANES_TRACK_GROUP,
            abortedViewTransition ? " error" : "secondary-light"
          );
          pendingDelayedCommitReason !== ABORTED_VIEW_TRANSITION_COMMIT && (pendingDelayedCommitReason = ANIMATION_STARTED_COMMIT);
        }
        pendingEffectsStatus = NO_PENDING_EFFECTS;
        requestPaint();
        startViewTransitionStartTime = pendingEffectsRoot;
        var finishedWork = pendingFinishedWork;
        endTime = pendingEffectsLanes;
        abortedViewTransition = pendingRecoverableErrors;
        var rootDidHavePassiveEffects = 0 !== finishedWork.actualDuration || 0 !== (finishedWork.subtreeFlags & 10256) || 0 !== (finishedWork.flags & 10256);
        rootDidHavePassiveEffects ? pendingEffectsStatus = PENDING_PASSIVE_PHASE : (pendingEffectsStatus = NO_PENDING_EFFECTS, pendingFinishedWork = pendingEffectsRoot = null, releaseRootPooledCache(
          startViewTransitionStartTime,
          startViewTransitionStartTime.pendingLanes
        ), nestedPassiveUpdateCount = 0, rootWithPassiveNestedUpdates = null);
        var remainingLanes = startViewTransitionStartTime.pendingLanes;
        0 === remainingLanes && (legacyErrorBoundariesThatAlreadyFailed = null);
        rootDidHavePassiveEffects || commitDoubleInvokeEffectsInDEV(startViewTransitionStartTime);
        remainingLanes = lanesToEventPriority(endTime);
        finishedWork = finishedWork.stateNode;
        if (injectedHook && "function" === typeof injectedHook.onCommitFiberRoot)
          try {
            var didError = 128 === (finishedWork.current.flags & 128);
            switch (remainingLanes) {
              case DiscreteEventPriority:
                var schedulerPriority = ImmediatePriority;
                break;
              case ContinuousEventPriority:
                schedulerPriority = UserBlockingPriority;
                break;
              case DefaultEventPriority:
                schedulerPriority = NormalPriority$1;
                break;
              case IdleEventPriority:
                schedulerPriority = IdlePriority;
                break;
              default:
                schedulerPriority = NormalPriority$1;
            }
            injectedHook.onCommitFiberRoot(
              rendererID,
              finishedWork,
              schedulerPriority,
              didError
            );
          } catch (err) {
            hasLoggedError || (hasLoggedError = true, console.error(
              "React instrumentation encountered an error: %o",
              err
            ));
          }
        isDevToolsPresent && startViewTransitionStartTime.memoizedUpdaters.clear();
        onCommitRoot();
        if (null !== abortedViewTransition) {
          didError = ReactSharedInternals.T;
          schedulerPriority = ReactDOMSharedInternals.p;
          ReactDOMSharedInternals.p = DiscreteEventPriority;
          ReactSharedInternals.T = null;
          try {
            var onRecoverableError = startViewTransitionStartTime.onRecoverableError;
            for (finishedWork = 0; finishedWork < abortedViewTransition.length; finishedWork++) {
              var recoverableError = abortedViewTransition[finishedWork], errorInfo = makeErrorInfo(recoverableError.stack);
              runWithFiberInDEV(
                recoverableError.source,
                onRecoverableError,
                recoverableError.value,
                errorInfo
              );
            }
          } finally {
            ReactSharedInternals.T = didError, ReactDOMSharedInternals.p = schedulerPriority;
          }
        }
        0 !== (pendingEffectsLanes & 3) && flushPendingEffects();
        ensureRootIsScheduled(startViewTransitionStartTime);
        remainingLanes = startViewTransitionStartTime.pendingLanes;
        0 !== (endTime & 261930) && 0 !== (remainingLanes & 42) ? (nestedUpdateScheduled = true, startViewTransitionStartTime === rootWithNestedUpdates ? nestedUpdateCount++ : (nestedUpdateCount = 0, rootWithNestedUpdates = startViewTransitionStartTime)) : nestedUpdateCount = 0;
        rootDidHavePassiveEffects || finalizeRender(endTime, commitEndTime);
        flushSyncWorkAcrossRoots_impl(0);
      }
    }
    function makeErrorInfo(componentStack) {
      componentStack = { componentStack };
      Object.defineProperty(componentStack, "digest", {
        get: function() {
          console.error(
            'You are accessing "digest" from the errorInfo object passed to onRecoverableError. This property is no longer provided as part of errorInfo but can be accessed as a property of the Error instance itself.'
          );
        }
      });
      return componentStack;
    }
    function releaseRootPooledCache(root22, remainingLanes) {
      0 === (root22.pooledCacheLanes &= remainingLanes) && (remainingLanes = root22.pooledCache, null != remainingLanes && (root22.pooledCache = null, releaseCache(remainingLanes)));
    }
    function flushPendingEffects() {
      flushMutationEffects();
      flushLayoutEffects();
      flushSpawnedWork();
      return flushPassiveEffects();
    }
    function flushPassiveEffects() {
      if (pendingEffectsStatus !== PENDING_PASSIVE_PHASE) return false;
      var root22 = pendingEffectsRoot, remainingLanes = pendingEffectsRemainingLanes;
      pendingEffectsRemainingLanes = 0;
      var renderPriority = lanesToEventPriority(pendingEffectsLanes), priority = DefaultEventPriority > renderPriority ? DefaultEventPriority : renderPriority;
      renderPriority = ReactSharedInternals.T;
      var previousPriority = ReactDOMSharedInternals.p;
      try {
        ReactDOMSharedInternals.p = priority;
        ReactSharedInternals.T = null;
        var transitions = pendingPassiveTransitions;
        pendingPassiveTransitions = null;
        priority = pendingEffectsRoot;
        var lanes = pendingEffectsLanes;
        pendingEffectsStatus = NO_PENDING_EFFECTS;
        pendingFinishedWork = pendingEffectsRoot = null;
        pendingEffectsLanes = 0;
        if ((executionContext & (RenderContext | CommitContext)) !== NoContext)
          throw Error("Cannot flush passive effects while already rendering.");
        setCurrentTrackFromLanes(lanes);
        isFlushingPassiveEffects = true;
        didScheduleUpdateDuringPassiveEffects = false;
        var passiveEffectStartTime = 0;
        commitErrors = null;
        passiveEffectStartTime = now$1();
        if (pendingDelayedCommitReason === ANIMATION_STARTED_COMMIT)
          logAnimatingPhase(
            commitEndTime,
            passiveEffectStartTime,
            animatingTask
          );
        else {
          var startTime = commitEndTime, endTime = passiveEffectStartTime, delayedUntilPaint = pendingDelayedCommitReason === DELAYED_PASSIVE_COMMIT;
          !supportsUserTiming || endTime <= startTime || (workInProgressUpdateTask ? workInProgressUpdateTask.run(
            console.timeStamp.bind(
              console,
              delayedUntilPaint ? "Waiting for Paint" : "Waiting",
              startTime,
              endTime,
              currentTrack,
              LANES_TRACK_GROUP,
              "secondary-light"
            )
          ) : console.timeStamp(
            delayedUntilPaint ? "Waiting for Paint" : "Waiting",
            startTime,
            endTime,
            currentTrack,
            LANES_TRACK_GROUP,
            "secondary-light"
          ));
        }
        startTime = executionContext;
        executionContext |= CommitContext;
        var finishedWork = priority.current;
        resetComponentEffectTimers();
        commitPassiveUnmountOnFiber(finishedWork);
        var finishedWork$jscomp$0 = priority.current;
        finishedWork = pendingEffectsRenderEndTime;
        resetComponentEffectTimers();
        commitPassiveMountOnFiber(
          priority,
          finishedWork$jscomp$0,
          lanes,
          transitions,
          finishedWork
        );
        commitDoubleInvokeEffectsInDEV(priority);
        executionContext = startTime;
        var passiveEffectsEndTime = now$1();
        finishedWork$jscomp$0 = passiveEffectStartTime;
        finishedWork = workInProgressUpdateTask;
        null !== commitErrors ? logCommitErrored(
          finishedWork$jscomp$0,
          passiveEffectsEndTime,
          commitErrors,
          true,
          finishedWork
        ) : !supportsUserTiming || passiveEffectsEndTime <= finishedWork$jscomp$0 || (finishedWork ? finishedWork.run(
          console.timeStamp.bind(
            console,
            "Remaining Effects",
            finishedWork$jscomp$0,
            passiveEffectsEndTime,
            currentTrack,
            LANES_TRACK_GROUP,
            "secondary-dark"
          )
        ) : console.timeStamp(
          "Remaining Effects",
          finishedWork$jscomp$0,
          passiveEffectsEndTime,
          currentTrack,
          LANES_TRACK_GROUP,
          "secondary-dark"
        ));
        finalizeRender(lanes, passiveEffectsEndTime);
        flushSyncWorkAcrossRoots_impl(0, false);
        didScheduleUpdateDuringPassiveEffects ? priority === rootWithPassiveNestedUpdates ? nestedPassiveUpdateCount++ : (nestedPassiveUpdateCount = 0, rootWithPassiveNestedUpdates = priority) : nestedPassiveUpdateCount = 0;
        didScheduleUpdateDuringPassiveEffects = isFlushingPassiveEffects = false;
        if (injectedHook && "function" === typeof injectedHook.onPostCommitFiberRoot)
          try {
            injectedHook.onPostCommitFiberRoot(rendererID, priority);
          } catch (err) {
            hasLoggedError || (hasLoggedError = true, console.error(
              "React instrumentation encountered an error: %o",
              err
            ));
          }
        var stateNode = priority.current.stateNode;
        stateNode.effectDuration = 0;
        stateNode.passiveEffectDuration = 0;
        return true;
      } finally {
        ReactDOMSharedInternals.p = previousPriority, ReactSharedInternals.T = renderPriority, releaseRootPooledCache(root22, remainingLanes);
      }
    }
    function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error2) {
      sourceFiber = createCapturedValueAtFiber(error2, sourceFiber);
      recordEffectError(sourceFiber);
      sourceFiber = createRootErrorUpdate(rootFiber.stateNode, sourceFiber, 2);
      rootFiber = enqueueUpdate(rootFiber, sourceFiber, 2);
      null !== rootFiber && (markRootUpdated$1(rootFiber, 2), ensureRootIsScheduled(rootFiber));
    }
    function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error2) {
      isRunningInsertionEffect = false;
      if (3 === sourceFiber.tag)
        captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error2);
      else {
        for (; null !== nearestMountedAncestor; ) {
          if (3 === nearestMountedAncestor.tag) {
            captureCommitPhaseErrorOnRoot(
              nearestMountedAncestor,
              sourceFiber,
              error2
            );
            return;
          }
          if (1 === nearestMountedAncestor.tag) {
            var instance2 = nearestMountedAncestor.stateNode;
            if ("function" === typeof nearestMountedAncestor.type.getDerivedStateFromError || "function" === typeof instance2.componentDidCatch && (null === legacyErrorBoundariesThatAlreadyFailed || !legacyErrorBoundariesThatAlreadyFailed.has(instance2))) {
              sourceFiber = createCapturedValueAtFiber(error2, sourceFiber);
              recordEffectError(sourceFiber);
              error2 = createClassErrorUpdate(2);
              instance2 = enqueueUpdate(nearestMountedAncestor, error2, 2);
              null !== instance2 && (initializeClassErrorUpdate(
                error2,
                instance2,
                nearestMountedAncestor,
                sourceFiber
              ), markRootUpdated$1(instance2, 2), ensureRootIsScheduled(instance2));
              return;
            }
          }
          nearestMountedAncestor = nearestMountedAncestor.return;
        }
        console.error(
          "Internal React error: Attempted to capture a commit phase error inside a detached tree. This indicates a bug in React. Potential causes include deleting the same fiber more than once, committing an already-finished tree, or an inconsistent return pointer.\n\nError message:\n\n%s",
          error2
        );
      }
    }
    function attachPingListener(root22, wakeable, lanes) {
      var pingCache = root22.pingCache;
      if (null === pingCache) {
        pingCache = root22.pingCache = new PossiblyWeakMap();
        var threadIDs = /* @__PURE__ */ new Set();
        pingCache.set(wakeable, threadIDs);
      } else
        threadIDs = pingCache.get(wakeable), void 0 === threadIDs && (threadIDs = /* @__PURE__ */ new Set(), pingCache.set(wakeable, threadIDs));
      threadIDs.has(lanes) || (workInProgressRootDidAttachPingListener = true, threadIDs.add(lanes), pingCache = pingSuspendedRoot.bind(null, root22, wakeable, lanes), isDevToolsPresent && restorePendingUpdaters(root22, lanes), wakeable.then(pingCache, pingCache));
    }
    function pingSuspendedRoot(root22, wakeable, pingedLanes) {
      var pingCache = root22.pingCache;
      null !== pingCache && pingCache.delete(wakeable);
      root22.pingedLanes |= root22.suspendedLanes & pingedLanes;
      root22.warmLanes &= ~pingedLanes;
      0 !== (pingedLanes & 127) ? 0 > blockingUpdateTime && (blockingClampTime = blockingUpdateTime = now2(), blockingUpdateTask = createTask("Promise Resolved"), blockingUpdateType = PINGED_UPDATE) : 0 !== (pingedLanes & 4194048) && 0 > transitionUpdateTime && (transitionClampTime = transitionUpdateTime = now2(), transitionUpdateTask = createTask("Promise Resolved"), transitionUpdateType = PINGED_UPDATE);
      isConcurrentActEnvironment() && null === ReactSharedInternals.actQueue && console.error(
        "A suspended resource finished loading inside a test, but the event was not wrapped in act(...).\n\nWhen testing, code that resolves suspended data should be wrapped into act(...):\n\nact(() => {\n  /* finish loading suspended data */\n});\n/* assert on the output */\n\nThis ensures that you're testing the behavior the user would see in the browser. Learn more at https://react.dev/link/wrap-tests-with-act"
      );
      workInProgressRoot === root22 && (workInProgressRootRenderLanes & pingedLanes) === pingedLanes && (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && (workInProgressRootRenderLanes & 62914560) === workInProgressRootRenderLanes && now$1() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS ? (executionContext & RenderContext) === NoContext && prepareFreshStack(root22, 0) : workInProgressRootPingedLanes |= pingedLanes, workInProgressSuspendedRetryLanes === workInProgressRootRenderLanes && (workInProgressSuspendedRetryLanes = 0));
      ensureRootIsScheduled(root22);
    }
    function retryTimedOutBoundary(boundaryFiber, retryLane) {
      0 === retryLane && (retryLane = claimNextRetryLane());
      boundaryFiber = enqueueConcurrentRenderForLane(boundaryFiber, retryLane);
      null !== boundaryFiber && (markRootUpdated$1(boundaryFiber, retryLane), ensureRootIsScheduled(boundaryFiber));
    }
    function retryDehydratedSuspenseBoundary(boundaryFiber) {
      var suspenseState = boundaryFiber.memoizedState, retryLane = 0;
      null !== suspenseState && (retryLane = suspenseState.retryLane);
      retryTimedOutBoundary(boundaryFiber, retryLane);
    }
    function resolveRetryWakeable(boundaryFiber, wakeable) {
      var retryLane = 0;
      switch (boundaryFiber.tag) {
        case 31:
        case 13:
          var retryCache = boundaryFiber.stateNode;
          var suspenseState = boundaryFiber.memoizedState;
          null !== suspenseState && (retryLane = suspenseState.retryLane);
          break;
        case 19:
          retryCache = boundaryFiber.stateNode;
          break;
        case 22:
          retryCache = boundaryFiber.stateNode._retryCache;
          break;
        default:
          throw Error(
            "Pinged unknown suspense boundary type. This is probably a bug in React."
          );
      }
      null !== retryCache && retryCache.delete(wakeable);
      retryTimedOutBoundary(boundaryFiber, retryLane);
    }
    function recursivelyTraverseAndDoubleInvokeEffectsInDEV(root$jscomp$0, parentFiber, isInStrictMode) {
      if (0 !== (parentFiber.subtreeFlags & 67117056))
        for (parentFiber = parentFiber.child; null !== parentFiber; ) {
          var root22 = root$jscomp$0, fiber = parentFiber, isStrictModeFiber = fiber.type === REACT_STRICT_MODE_TYPE;
          isStrictModeFiber = isInStrictMode || isStrictModeFiber;
          22 !== fiber.tag ? fiber.flags & 67108864 ? isStrictModeFiber && runWithFiberInDEV(
            fiber,
            doubleInvokeEffectsOnFiber,
            root22,
            fiber
          ) : recursivelyTraverseAndDoubleInvokeEffectsInDEV(
            root22,
            fiber,
            isStrictModeFiber
          ) : null === fiber.memoizedState && (isStrictModeFiber && fiber.flags & 8192 ? runWithFiberInDEV(
            fiber,
            doubleInvokeEffectsOnFiber,
            root22,
            fiber
          ) : fiber.subtreeFlags & 67108864 && runWithFiberInDEV(
            fiber,
            recursivelyTraverseAndDoubleInvokeEffectsInDEV,
            root22,
            fiber,
            isStrictModeFiber
          ));
          parentFiber = parentFiber.sibling;
        }
    }
    function doubleInvokeEffectsOnFiber(root22, fiber) {
      setIsStrictModeForDevtools(true);
      try {
        disappearLayoutEffects(fiber), disconnectPassiveEffect(fiber), reappearLayoutEffects(root22, fiber.alternate, fiber, false), reconnectPassiveEffects(root22, fiber, 0, null, false, 0);
      } finally {
        setIsStrictModeForDevtools(false);
      }
    }
    function commitDoubleInvokeEffectsInDEV(root22) {
      var doubleInvokeEffects = true;
      root22.current.mode & (StrictLegacyMode | StrictEffectsMode) || (doubleInvokeEffects = false);
      recursivelyTraverseAndDoubleInvokeEffectsInDEV(
        root22,
        root22.current,
        doubleInvokeEffects
      );
    }
    function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber) {
      if ((executionContext & RenderContext) === NoContext) {
        var tag = fiber.tag;
        if (3 === tag || 1 === tag || 0 === tag || 11 === tag || 14 === tag || 15 === tag) {
          tag = getComponentNameFromFiber(fiber) || "ReactComponent";
          if (null !== didWarnStateUpdateForNotYetMountedComponent) {
            if (didWarnStateUpdateForNotYetMountedComponent.has(tag)) return;
            didWarnStateUpdateForNotYetMountedComponent.add(tag);
          } else didWarnStateUpdateForNotYetMountedComponent = /* @__PURE__ */ new Set([tag]);
          runWithFiberInDEV(fiber, function() {
            console.error(
              "Can't perform a React state update on a component that hasn't mounted yet. This indicates that you have a side-effect in your render function that asynchronously tries to update the component. Move this work to useEffect instead."
            );
          });
        }
      }
    }
    function restorePendingUpdaters(root22, lanes) {
      isDevToolsPresent && root22.memoizedUpdaters.forEach(function(schedulingFiber) {
        addFiberToLanesMap(root22, schedulingFiber, lanes);
      });
    }
    function scheduleCallback$1(priorityLevel, callback) {
      var actQueue = ReactSharedInternals.actQueue;
      return null !== actQueue ? (actQueue.push(callback), fakeActCallbackNode$1) : scheduleCallback$3(priorityLevel, callback);
    }
    function warnIfUpdatesNotWrappedWithActDEV(fiber) {
      isConcurrentActEnvironment() && null === ReactSharedInternals.actQueue && runWithFiberInDEV(fiber, function() {
        console.error(
          "An update to %s inside a test was not wrapped in act(...).\n\nWhen testing, code that causes React state updates should be wrapped into act(...):\n\nact(() => {\n  /* fire events that update state */\n});\n/* assert on the output */\n\nThis ensures that you're testing the behavior the user would see in the browser. Learn more at https://react.dev/link/wrap-tests-with-act",
          getComponentNameFromFiber(fiber)
        );
      });
    }
    function ensureRootIsScheduled(root22) {
      root22 !== lastScheduledRoot && null === root22.next && (null === lastScheduledRoot ? firstScheduledRoot = lastScheduledRoot = root22 : lastScheduledRoot = lastScheduledRoot.next = root22);
      mightHavePendingSyncWork = true;
      null !== ReactSharedInternals.actQueue ? didScheduleMicrotask_act || (didScheduleMicrotask_act = true, scheduleImmediateRootScheduleTask()) : didScheduleMicrotask || (didScheduleMicrotask = true, scheduleImmediateRootScheduleTask());
    }
    function flushSyncWorkAcrossRoots_impl(syncTransitionLanes, onlyLegacy) {
      if (!isFlushingWork && mightHavePendingSyncWork) {
        isFlushingWork = true;
        do {
          var didPerformSomeWork = false;
          for (var root22 = firstScheduledRoot; null !== root22; ) {
            if (0 !== syncTransitionLanes) {
              var pendingLanes = root22.pendingLanes;
              if (0 === pendingLanes) var nextLanes = 0;
              else {
                var suspendedLanes = root22.suspendedLanes, pingedLanes = root22.pingedLanes;
                nextLanes = (1 << 31 - clz322(42 | syncTransitionLanes) + 1) - 1;
                nextLanes &= pendingLanes & ~(suspendedLanes & ~pingedLanes);
                nextLanes = nextLanes & 201326741 ? nextLanes & 201326741 | 1 : nextLanes ? nextLanes | 2 : 0;
              }
              0 !== nextLanes && (didPerformSomeWork = true, performSyncWorkOnRoot(root22, nextLanes));
            } else
              nextLanes = workInProgressRootRenderLanes, nextLanes = getNextLanes(
                root22,
                root22 === workInProgressRoot ? nextLanes : 0,
                null !== root22.cancelPendingCommit || root22.timeoutHandle !== noTimeout
              ), 0 === (nextLanes & 3) || checkIfRootIsPrerendering(root22, nextLanes) || (didPerformSomeWork = true, performSyncWorkOnRoot(root22, nextLanes));
            root22 = root22.next;
          }
        } while (didPerformSomeWork);
        isFlushingWork = false;
      }
    }
    function processRootScheduleInImmediateTask() {
      schedulerEvent = window.event;
      processRootScheduleInMicrotask();
    }
    function processRootScheduleInMicrotask() {
      mightHavePendingSyncWork = didScheduleMicrotask_act = didScheduleMicrotask = false;
      var syncTransitionLanes = 0;
      0 !== currentEventTransitionLane && shouldAttemptEagerTransition() && (syncTransitionLanes = currentEventTransitionLane);
      for (var currentTime = now$1(), prev = null, root22 = firstScheduledRoot; null !== root22; ) {
        var next = root22.next, nextLanes = scheduleTaskForRootDuringMicrotask(root22, currentTime);
        if (0 === nextLanes)
          root22.next = null, null === prev ? firstScheduledRoot = next : prev.next = next, null === next && (lastScheduledRoot = prev);
        else if (prev = root22, 0 !== syncTransitionLanes || 0 !== (nextLanes & 3))
          mightHavePendingSyncWork = true;
        root22 = next;
      }
      pendingEffectsStatus !== NO_PENDING_EFFECTS && pendingEffectsStatus !== PENDING_PASSIVE_PHASE || flushSyncWorkAcrossRoots_impl(syncTransitionLanes);
      0 !== currentEventTransitionLane && (currentEventTransitionLane = 0);
    }
    function scheduleTaskForRootDuringMicrotask(root22, currentTime) {
      for (var suspendedLanes = root22.suspendedLanes, pingedLanes = root22.pingedLanes, expirationTimes = root22.expirationTimes, lanes = root22.pendingLanes & -62914561; 0 < lanes; ) {
        var index = 31 - clz322(lanes), lane = 1 << index, expirationTime = expirationTimes[index];
        if (-1 === expirationTime) {
          if (0 === (lane & suspendedLanes) || 0 !== (lane & pingedLanes))
            expirationTimes[index] = computeExpirationTime(lane, currentTime);
        } else expirationTime <= currentTime && (root22.expiredLanes |= lane);
        lanes &= ~lane;
      }
      currentTime = workInProgressRoot;
      suspendedLanes = workInProgressRootRenderLanes;
      suspendedLanes = getNextLanes(
        root22,
        root22 === currentTime ? suspendedLanes : 0,
        null !== root22.cancelPendingCommit || root22.timeoutHandle !== noTimeout
      );
      pingedLanes = root22.callbackNode;
      if (0 === suspendedLanes || root22 === currentTime && (workInProgressSuspendedReason === SuspendedOnData || workInProgressSuspendedReason === SuspendedOnAction) || null !== root22.cancelPendingCommit)
        return null !== pingedLanes && cancelCallback(pingedLanes), root22.callbackNode = null, root22.callbackPriority = 0;
      if (0 === (suspendedLanes & 3) || checkIfRootIsPrerendering(root22, suspendedLanes)) {
        currentTime = suspendedLanes & -suspendedLanes;
        if (currentTime !== root22.callbackPriority || null !== ReactSharedInternals.actQueue && pingedLanes !== fakeActCallbackNode)
          cancelCallback(pingedLanes);
        else return currentTime;
        switch (lanesToEventPriority(suspendedLanes)) {
          case DiscreteEventPriority:
          case ContinuousEventPriority:
            suspendedLanes = UserBlockingPriority;
            break;
          case DefaultEventPriority:
            suspendedLanes = NormalPriority$1;
            break;
          case IdleEventPriority:
            suspendedLanes = IdlePriority;
            break;
          default:
            suspendedLanes = NormalPriority$1;
        }
        pingedLanes = performWorkOnRootViaSchedulerTask.bind(null, root22);
        null !== ReactSharedInternals.actQueue ? (ReactSharedInternals.actQueue.push(pingedLanes), suspendedLanes = fakeActCallbackNode) : suspendedLanes = scheduleCallback$3(suspendedLanes, pingedLanes);
        root22.callbackPriority = currentTime;
        root22.callbackNode = suspendedLanes;
        return currentTime;
      }
      null !== pingedLanes && cancelCallback(pingedLanes);
      root22.callbackPriority = 2;
      root22.callbackNode = null;
      return 2;
    }
    function performWorkOnRootViaSchedulerTask(root22, didTimeout) {
      nestedUpdateScheduled = currentUpdateIsNested = false;
      schedulerEvent = window.event;
      if (pendingEffectsStatus !== NO_PENDING_EFFECTS && pendingEffectsStatus !== PENDING_PASSIVE_PHASE)
        return root22.callbackNode = null, root22.callbackPriority = 0, null;
      var originalCallbackNode = root22.callbackNode;
      pendingDelayedCommitReason === IMMEDIATE_COMMIT && (pendingDelayedCommitReason = DELAYED_PASSIVE_COMMIT);
      if (flushPendingEffects() && root22.callbackNode !== originalCallbackNode)
        return null;
      var workInProgressRootRenderLanes$jscomp$0 = workInProgressRootRenderLanes;
      workInProgressRootRenderLanes$jscomp$0 = getNextLanes(
        root22,
        root22 === workInProgressRoot ? workInProgressRootRenderLanes$jscomp$0 : 0,
        null !== root22.cancelPendingCommit || root22.timeoutHandle !== noTimeout
      );
      if (0 === workInProgressRootRenderLanes$jscomp$0) return null;
      performWorkOnRoot(
        root22,
        workInProgressRootRenderLanes$jscomp$0,
        didTimeout
      );
      scheduleTaskForRootDuringMicrotask(root22, now$1());
      return null != root22.callbackNode && root22.callbackNode === originalCallbackNode ? performWorkOnRootViaSchedulerTask.bind(null, root22) : null;
    }
    function performSyncWorkOnRoot(root22, lanes) {
      if (flushPendingEffects()) return null;
      currentUpdateIsNested = nestedUpdateScheduled;
      nestedUpdateScheduled = false;
      performWorkOnRoot(root22, lanes, true);
    }
    function cancelCallback(callbackNode) {
      callbackNode !== fakeActCallbackNode && null !== callbackNode && cancelCallback$1(callbackNode);
    }
    function scheduleImmediateRootScheduleTask() {
      null !== ReactSharedInternals.actQueue && ReactSharedInternals.actQueue.push(function() {
        processRootScheduleInMicrotask();
        return null;
      });
      scheduleMicrotask(function() {
        (executionContext & (RenderContext | CommitContext)) !== NoContext ? scheduleCallback$3(
          ImmediatePriority,
          processRootScheduleInImmediateTask
        ) : processRootScheduleInMicrotask();
      });
    }
    function requestTransitionLane() {
      if (0 === currentEventTransitionLane) {
        var actionScopeLane = currentEntangledLane;
        0 === actionScopeLane && (actionScopeLane = nextTransitionUpdateLane, nextTransitionUpdateLane <<= 1, 0 === (nextTransitionUpdateLane & 261888) && (nextTransitionUpdateLane = 256));
        currentEventTransitionLane = actionScopeLane;
      }
      return currentEventTransitionLane;
    }
    function coerceFormActionProp(actionProp) {
      if (null == actionProp || "symbol" === typeof actionProp || "boolean" === typeof actionProp)
        return null;
      if ("function" === typeof actionProp) return actionProp;
      checkAttributeStringCoercion(actionProp, "action");
      return sanitizeURL("" + actionProp);
    }
    function createFormDataWithSubmitter(form, submitter) {
      var temp = submitter.ownerDocument.createElement("input");
      temp.name = submitter.name;
      temp.value = submitter.value;
      form.id && temp.setAttribute("form", form.id);
      submitter.parentNode.insertBefore(temp, submitter);
      form = new FormData(form);
      temp.parentNode.removeChild(temp);
      return form;
    }
    function extractEvents$1(dispatchQueue, domEventName, maybeTargetInst, nativeEvent, nativeEventTarget) {
      if ("submit" === domEventName && maybeTargetInst && maybeTargetInst.stateNode === nativeEventTarget) {
        var action = coerceFormActionProp(
          (nativeEventTarget[internalPropsKey] || null).action
        ), submitter = nativeEvent.submitter;
        submitter && (domEventName = (domEventName = submitter[internalPropsKey] || null) ? coerceFormActionProp(domEventName.formAction) : submitter.getAttribute("formAction"), null !== domEventName && (action = domEventName, submitter = null));
        var event = new SyntheticEvent(
          "action",
          "action",
          null,
          nativeEvent,
          nativeEventTarget
        );
        dispatchQueue.push({
          event,
          listeners: [
            {
              instance: null,
              listener: function() {
                if (nativeEvent.defaultPrevented) {
                  if (0 !== currentEventTransitionLane) {
                    var formData = submitter ? createFormDataWithSubmitter(
                      nativeEventTarget,
                      submitter
                    ) : new FormData(nativeEventTarget), pendingState = {
                      pending: true,
                      data: formData,
                      method: nativeEventTarget.method,
                      action
                    };
                    Object.freeze(pendingState);
                    startHostTransition(
                      maybeTargetInst,
                      pendingState,
                      null,
                      formData
                    );
                  }
                } else
                  "function" === typeof action && (event.preventDefault(), formData = submitter ? createFormDataWithSubmitter(
                    nativeEventTarget,
                    submitter
                  ) : new FormData(nativeEventTarget), pendingState = {
                    pending: true,
                    data: formData,
                    method: nativeEventTarget.method,
                    action
                  }, Object.freeze(pendingState), startHostTransition(
                    maybeTargetInst,
                    pendingState,
                    action,
                    formData
                  ));
              },
              currentTarget: nativeEventTarget
            }
          ]
        });
      }
    }
    function executeDispatch(event, listener, currentTarget) {
      event.currentTarget = currentTarget;
      try {
        listener(event);
      } catch (error2) {
        reportGlobalError(error2);
      }
      event.currentTarget = null;
    }
    function processDispatchQueue(dispatchQueue, eventSystemFlags) {
      eventSystemFlags = 0 !== (eventSystemFlags & 4);
      for (var i2 = 0; i2 < dispatchQueue.length; i2++) {
        var _dispatchQueue$i = dispatchQueue[i2];
        a: {
          var previousInstance = void 0, event = _dispatchQueue$i.event;
          _dispatchQueue$i = _dispatchQueue$i.listeners;
          if (eventSystemFlags)
            for (var i$jscomp$0 = _dispatchQueue$i.length - 1; 0 <= i$jscomp$0; i$jscomp$0--) {
              var _dispatchListeners$i = _dispatchQueue$i[i$jscomp$0], instance2 = _dispatchListeners$i.instance, currentTarget = _dispatchListeners$i.currentTarget;
              _dispatchListeners$i = _dispatchListeners$i.listener;
              if (instance2 !== previousInstance && event.isPropagationStopped())
                break a;
              null !== instance2 ? runWithFiberInDEV(
                instance2,
                executeDispatch,
                event,
                _dispatchListeners$i,
                currentTarget
              ) : executeDispatch(event, _dispatchListeners$i, currentTarget);
              previousInstance = instance2;
            }
          else
            for (i$jscomp$0 = 0; i$jscomp$0 < _dispatchQueue$i.length; i$jscomp$0++) {
              _dispatchListeners$i = _dispatchQueue$i[i$jscomp$0];
              instance2 = _dispatchListeners$i.instance;
              currentTarget = _dispatchListeners$i.currentTarget;
              _dispatchListeners$i = _dispatchListeners$i.listener;
              if (instance2 !== previousInstance && event.isPropagationStopped())
                break a;
              null !== instance2 ? runWithFiberInDEV(
                instance2,
                executeDispatch,
                event,
                _dispatchListeners$i,
                currentTarget
              ) : executeDispatch(event, _dispatchListeners$i, currentTarget);
              previousInstance = instance2;
            }
        }
      }
    }
    function listenToNonDelegatedEvent(domEventName, targetElement) {
      nonDelegatedEvents.has(domEventName) || console.error(
        'Did not expect a listenToNonDelegatedEvent() call for "%s". This is a bug in React. Please file an issue.',
        domEventName
      );
      var listenerSet = targetElement[internalEventHandlersKey];
      void 0 === listenerSet && (listenerSet = targetElement[internalEventHandlersKey] = /* @__PURE__ */ new Set());
      var listenerSetKey = domEventName + "__bubble";
      listenerSet.has(listenerSetKey) || (addTrappedEventListener(targetElement, domEventName, 2, false), listenerSet.add(listenerSetKey));
    }
    function listenToNativeEvent(domEventName, isCapturePhaseListener, target) {
      nonDelegatedEvents.has(domEventName) && !isCapturePhaseListener && console.error(
        'Did not expect a listenToNativeEvent() call for "%s" in the bubble phase. This is a bug in React. Please file an issue.',
        domEventName
      );
      var eventSystemFlags = 0;
      isCapturePhaseListener && (eventSystemFlags |= 4);
      addTrappedEventListener(
        target,
        domEventName,
        eventSystemFlags,
        isCapturePhaseListener
      );
    }
    function listenToAllSupportedEvents(rootContainerElement) {
      if (!rootContainerElement[listeningMarker]) {
        rootContainerElement[listeningMarker] = true;
        allNativeEvents.forEach(function(domEventName) {
          "selectionchange" !== domEventName && (nonDelegatedEvents.has(domEventName) || listenToNativeEvent(domEventName, false, rootContainerElement), listenToNativeEvent(domEventName, true, rootContainerElement));
        });
        var ownerDocument = 9 === rootContainerElement.nodeType ? rootContainerElement : rootContainerElement.ownerDocument;
        null === ownerDocument || ownerDocument[listeningMarker] || (ownerDocument[listeningMarker] = true, listenToNativeEvent("selectionchange", false, ownerDocument));
      }
    }
    function addTrappedEventListener(targetContainer, domEventName, eventSystemFlags, isCapturePhaseListener) {
      switch (getEventPriority(domEventName)) {
        case DiscreteEventPriority:
          var listenerWrapper = dispatchDiscreteEvent;
          break;
        case ContinuousEventPriority:
          listenerWrapper = dispatchContinuousEvent;
          break;
        default:
          listenerWrapper = dispatchEvent2;
      }
      eventSystemFlags = listenerWrapper.bind(
        null,
        domEventName,
        eventSystemFlags,
        targetContainer
      );
      listenerWrapper = void 0;
      !passiveBrowserEventsSupported || "touchstart" !== domEventName && "touchmove" !== domEventName && "wheel" !== domEventName || (listenerWrapper = true);
      isCapturePhaseListener ? void 0 !== listenerWrapper ? targetContainer.addEventListener(domEventName, eventSystemFlags, {
        capture: true,
        passive: listenerWrapper
      }) : targetContainer.addEventListener(domEventName, eventSystemFlags, true) : void 0 !== listenerWrapper ? targetContainer.addEventListener(domEventName, eventSystemFlags, {
        passive: listenerWrapper
      }) : targetContainer.addEventListener(
        domEventName,
        eventSystemFlags,
        false
      );
    }
    function dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, targetInst$jscomp$0, targetContainer) {
      var ancestorInst = targetInst$jscomp$0;
      if (0 === (eventSystemFlags & 1) && 0 === (eventSystemFlags & 2) && null !== targetInst$jscomp$0)
        a: for (; ; ) {
          if (null === targetInst$jscomp$0) return;
          var nodeTag = targetInst$jscomp$0.tag;
          if (3 === nodeTag || 4 === nodeTag) {
            var container2 = targetInst$jscomp$0.stateNode.containerInfo;
            if (container2 === targetContainer) break;
            if (4 === nodeTag)
              for (nodeTag = targetInst$jscomp$0.return; null !== nodeTag; ) {
                var grandTag = nodeTag.tag;
                if ((3 === grandTag || 4 === grandTag) && nodeTag.stateNode.containerInfo === targetContainer)
                  return;
                nodeTag = nodeTag.return;
              }
            for (; null !== container2; ) {
              nodeTag = getClosestInstanceFromNode(container2);
              if (null === nodeTag) return;
              grandTag = nodeTag.tag;
              if (5 === grandTag || 6 === grandTag || 26 === grandTag || 27 === grandTag) {
                targetInst$jscomp$0 = ancestorInst = nodeTag;
                continue a;
              }
              container2 = container2.parentNode;
            }
          }
          targetInst$jscomp$0 = targetInst$jscomp$0.return;
        }
      batchedUpdates$1(function() {
        var targetInst = ancestorInst, nativeEventTarget = getEventTarget(nativeEvent), dispatchQueue = [];
        a: {
          var reactName = topLevelEventsToReactNames.get(domEventName);
          if (void 0 !== reactName) {
            var SyntheticEventCtor = SyntheticEvent, reactEventType = domEventName;
            switch (domEventName) {
              case "keypress":
                if (0 === getEventCharCode(nativeEvent)) break a;
              case "keydown":
              case "keyup":
                SyntheticEventCtor = SyntheticKeyboardEvent;
                break;
              case "focusin":
                reactEventType = "focus";
                SyntheticEventCtor = SyntheticFocusEvent;
                break;
              case "focusout":
                reactEventType = "blur";
                SyntheticEventCtor = SyntheticFocusEvent;
                break;
              case "beforeblur":
              case "afterblur":
                SyntheticEventCtor = SyntheticFocusEvent;
                break;
              case "click":
                if (2 === nativeEvent.button) break a;
              case "auxclick":
              case "dblclick":
              case "mousedown":
              case "mousemove":
              case "mouseup":
              case "mouseout":
              case "mouseover":
              case "contextmenu":
                SyntheticEventCtor = SyntheticMouseEvent;
                break;
              case "drag":
              case "dragend":
              case "dragenter":
              case "dragexit":
              case "dragleave":
              case "dragover":
              case "dragstart":
              case "drop":
                SyntheticEventCtor = SyntheticDragEvent;
                break;
              case "touchcancel":
              case "touchend":
              case "touchmove":
              case "touchstart":
                SyntheticEventCtor = SyntheticTouchEvent;
                break;
              case ANIMATION_END:
              case ANIMATION_ITERATION:
              case ANIMATION_START:
                SyntheticEventCtor = SyntheticAnimationEvent;
                break;
              case TRANSITION_END:
                SyntheticEventCtor = SyntheticTransitionEvent;
                break;
              case "scroll":
              case "scrollend":
                SyntheticEventCtor = SyntheticUIEvent;
                break;
              case "wheel":
                SyntheticEventCtor = SyntheticWheelEvent;
                break;
              case "copy":
              case "cut":
              case "paste":
                SyntheticEventCtor = SyntheticClipboardEvent;
                break;
              case "gotpointercapture":
              case "lostpointercapture":
              case "pointercancel":
              case "pointerdown":
              case "pointermove":
              case "pointerout":
              case "pointerover":
              case "pointerup":
                SyntheticEventCtor = SyntheticPointerEvent;
                break;
              case "toggle":
              case "beforetoggle":
                SyntheticEventCtor = SyntheticToggleEvent;
            }
            var inCapturePhase = 0 !== (eventSystemFlags & 4), accumulateTargetOnly = !inCapturePhase && ("scroll" === domEventName || "scrollend" === domEventName), reactEventName = inCapturePhase ? null !== reactName ? reactName + "Capture" : null : reactName;
            inCapturePhase = [];
            for (var instance2 = targetInst, lastHostComponent; null !== instance2; ) {
              var _instance2 = instance2;
              lastHostComponent = _instance2.stateNode;
              _instance2 = _instance2.tag;
              5 !== _instance2 && 26 !== _instance2 && 27 !== _instance2 || null === lastHostComponent || null === reactEventName || (_instance2 = getListener2(instance2, reactEventName), null != _instance2 && inCapturePhase.push(
                createDispatchListener(
                  instance2,
                  _instance2,
                  lastHostComponent
                )
              ));
              if (accumulateTargetOnly) break;
              instance2 = instance2.return;
            }
            0 < inCapturePhase.length && (reactName = new SyntheticEventCtor(
              reactName,
              reactEventType,
              null,
              nativeEvent,
              nativeEventTarget
            ), dispatchQueue.push({
              event: reactName,
              listeners: inCapturePhase
            }));
          }
        }
        if (0 === (eventSystemFlags & 7)) {
          a: {
            reactName = "mouseover" === domEventName || "pointerover" === domEventName;
            SyntheticEventCtor = "mouseout" === domEventName || "pointerout" === domEventName;
            if (reactName && nativeEvent !== currentReplayingEvent && (reactEventType = nativeEvent.relatedTarget || nativeEvent.fromElement) && (getClosestInstanceFromNode(reactEventType) || reactEventType[internalContainerInstanceKey]))
              break a;
            if (SyntheticEventCtor || reactName) {
              reactName = nativeEventTarget.window === nativeEventTarget ? nativeEventTarget : (reactName = nativeEventTarget.ownerDocument) ? reactName.defaultView || reactName.parentWindow : window;
              if (SyntheticEventCtor) {
                if (reactEventType = nativeEvent.relatedTarget || nativeEvent.toElement, SyntheticEventCtor = targetInst, reactEventType = reactEventType ? getClosestInstanceFromNode(reactEventType) : null, null !== reactEventType && (accumulateTargetOnly = getNearestMountedFiber(reactEventType), inCapturePhase = reactEventType.tag, reactEventType !== accumulateTargetOnly || 5 !== inCapturePhase && 27 !== inCapturePhase && 6 !== inCapturePhase))
                  reactEventType = null;
              } else SyntheticEventCtor = null, reactEventType = targetInst;
              if (SyntheticEventCtor !== reactEventType) {
                inCapturePhase = SyntheticMouseEvent;
                _instance2 = "onMouseLeave";
                reactEventName = "onMouseEnter";
                instance2 = "mouse";
                if ("pointerout" === domEventName || "pointerover" === domEventName)
                  inCapturePhase = SyntheticPointerEvent, _instance2 = "onPointerLeave", reactEventName = "onPointerEnter", instance2 = "pointer";
                accumulateTargetOnly = null == SyntheticEventCtor ? reactName : getNodeFromInstance(SyntheticEventCtor);
                lastHostComponent = null == reactEventType ? reactName : getNodeFromInstance(reactEventType);
                reactName = new inCapturePhase(
                  _instance2,
                  instance2 + "leave",
                  SyntheticEventCtor,
                  nativeEvent,
                  nativeEventTarget
                );
                reactName.target = accumulateTargetOnly;
                reactName.relatedTarget = lastHostComponent;
                _instance2 = null;
                getClosestInstanceFromNode(nativeEventTarget) === targetInst && (inCapturePhase = new inCapturePhase(
                  reactEventName,
                  instance2 + "enter",
                  reactEventType,
                  nativeEvent,
                  nativeEventTarget
                ), inCapturePhase.target = lastHostComponent, inCapturePhase.relatedTarget = accumulateTargetOnly, _instance2 = inCapturePhase);
                accumulateTargetOnly = _instance2;
                if (SyntheticEventCtor && reactEventType)
                  b: {
                    inCapturePhase = getParent;
                    reactEventName = SyntheticEventCtor;
                    instance2 = reactEventType;
                    lastHostComponent = 0;
                    for (_instance2 = reactEventName; _instance2; _instance2 = inCapturePhase(_instance2))
                      lastHostComponent++;
                    _instance2 = 0;
                    for (var tempB = instance2; tempB; tempB = inCapturePhase(tempB))
                      _instance2++;
                    for (; 0 < lastHostComponent - _instance2; )
                      reactEventName = inCapturePhase(reactEventName), lastHostComponent--;
                    for (; 0 < _instance2 - lastHostComponent; )
                      instance2 = inCapturePhase(instance2), _instance2--;
                    for (; lastHostComponent--; ) {
                      if (reactEventName === instance2 || null !== instance2 && reactEventName === instance2.alternate) {
                        inCapturePhase = reactEventName;
                        break b;
                      }
                      reactEventName = inCapturePhase(reactEventName);
                      instance2 = inCapturePhase(instance2);
                    }
                    inCapturePhase = null;
                  }
                else inCapturePhase = null;
                null !== SyntheticEventCtor && accumulateEnterLeaveListenersForEvent(
                  dispatchQueue,
                  reactName,
                  SyntheticEventCtor,
                  inCapturePhase,
                  false
                );
                null !== reactEventType && null !== accumulateTargetOnly && accumulateEnterLeaveListenersForEvent(
                  dispatchQueue,
                  accumulateTargetOnly,
                  reactEventType,
                  inCapturePhase,
                  true
                );
              }
            }
          }
          a: {
            reactName = targetInst ? getNodeFromInstance(targetInst) : window;
            SyntheticEventCtor = reactName.nodeName && reactName.nodeName.toLowerCase();
            if ("select" === SyntheticEventCtor || "input" === SyntheticEventCtor && "file" === reactName.type)
              var getTargetInstFunc = getTargetInstForChangeEvent;
            else if (isTextInputElement(reactName))
              if (isInputEventSupported)
                getTargetInstFunc = getTargetInstForInputOrChangeEvent;
              else {
                getTargetInstFunc = getTargetInstForInputEventPolyfill;
                var handleEventFunc = handleEventsForInputEventPolyfill;
              }
            else
              SyntheticEventCtor = reactName.nodeName, !SyntheticEventCtor || "input" !== SyntheticEventCtor.toLowerCase() || "checkbox" !== reactName.type && "radio" !== reactName.type ? targetInst && isCustomElement(targetInst.elementType) && (getTargetInstFunc = getTargetInstForChangeEvent) : getTargetInstFunc = getTargetInstForClickEvent;
            if (getTargetInstFunc && (getTargetInstFunc = getTargetInstFunc(domEventName, targetInst))) {
              createAndAccumulateChangeEvent(
                dispatchQueue,
                getTargetInstFunc,
                nativeEvent,
                nativeEventTarget
              );
              break a;
            }
            handleEventFunc && handleEventFunc(domEventName, reactName, targetInst);
            "focusout" === domEventName && targetInst && "number" === reactName.type && null != targetInst.memoizedProps.value && setDefaultValue(reactName, "number", reactName.value);
          }
          handleEventFunc = targetInst ? getNodeFromInstance(targetInst) : window;
          switch (domEventName) {
            case "focusin":
              if (isTextInputElement(handleEventFunc) || "true" === handleEventFunc.contentEditable)
                activeElement = handleEventFunc, activeElementInst = targetInst, lastSelection = null;
              break;
            case "focusout":
              lastSelection = activeElementInst = activeElement = null;
              break;
            case "mousedown":
              mouseDown = true;
              break;
            case "contextmenu":
            case "mouseup":
            case "dragend":
              mouseDown = false;
              constructSelectEvent(
                dispatchQueue,
                nativeEvent,
                nativeEventTarget
              );
              break;
            case "selectionchange":
              if (skipSelectionChangeEvent) break;
            case "keydown":
            case "keyup":
              constructSelectEvent(
                dispatchQueue,
                nativeEvent,
                nativeEventTarget
              );
          }
          var fallbackData;
          if (canUseCompositionEvent)
            b: {
              switch (domEventName) {
                case "compositionstart":
                  var eventType = "onCompositionStart";
                  break b;
                case "compositionend":
                  eventType = "onCompositionEnd";
                  break b;
                case "compositionupdate":
                  eventType = "onCompositionUpdate";
                  break b;
              }
              eventType = void 0;
            }
          else
            isComposing ? isFallbackCompositionEnd(domEventName, nativeEvent) && (eventType = "onCompositionEnd") : "keydown" === domEventName && nativeEvent.keyCode === START_KEYCODE && (eventType = "onCompositionStart");
          eventType && (useFallbackCompositionData && "ko" !== nativeEvent.locale && (isComposing || "onCompositionStart" !== eventType ? "onCompositionEnd" === eventType && isComposing && (fallbackData = getData()) : (root2 = nativeEventTarget, startText = "value" in root2 ? root2.value : root2.textContent, isComposing = true)), handleEventFunc = accumulateTwoPhaseListeners(
            targetInst,
            eventType
          ), 0 < handleEventFunc.length && (eventType = new SyntheticCompositionEvent(
            eventType,
            domEventName,
            null,
            nativeEvent,
            nativeEventTarget
          ), dispatchQueue.push({
            event: eventType,
            listeners: handleEventFunc
          }), fallbackData ? eventType.data = fallbackData : (fallbackData = getDataFromCustomEvent(nativeEvent), null !== fallbackData && (eventType.data = fallbackData))));
          if (fallbackData = canUseTextInputEvent ? getNativeBeforeInputChars(domEventName, nativeEvent) : getFallbackBeforeInputChars(domEventName, nativeEvent))
            eventType = accumulateTwoPhaseListeners(
              targetInst,
              "onBeforeInput"
            ), 0 < eventType.length && (handleEventFunc = new SyntheticInputEvent(
              "onBeforeInput",
              "beforeinput",
              null,
              nativeEvent,
              nativeEventTarget
            ), dispatchQueue.push({
              event: handleEventFunc,
              listeners: eventType
            }), handleEventFunc.data = fallbackData);
          extractEvents$1(
            dispatchQueue,
            domEventName,
            targetInst,
            nativeEvent,
            nativeEventTarget
          );
        }
        processDispatchQueue(dispatchQueue, eventSystemFlags);
      });
    }
    function createDispatchListener(instance2, listener, currentTarget) {
      return {
        instance: instance2,
        listener,
        currentTarget
      };
    }
    function accumulateTwoPhaseListeners(targetFiber, reactName) {
      for (var captureName = reactName + "Capture", listeners = []; null !== targetFiber; ) {
        var _instance3 = targetFiber, stateNode = _instance3.stateNode;
        _instance3 = _instance3.tag;
        5 !== _instance3 && 26 !== _instance3 && 27 !== _instance3 || null === stateNode || (_instance3 = getListener2(targetFiber, captureName), null != _instance3 && listeners.unshift(
          createDispatchListener(targetFiber, _instance3, stateNode)
        ), _instance3 = getListener2(targetFiber, reactName), null != _instance3 && listeners.push(
          createDispatchListener(targetFiber, _instance3, stateNode)
        ));
        if (3 === targetFiber.tag) return listeners;
        targetFiber = targetFiber.return;
      }
      return [];
    }
    function getParent(inst) {
      if (null === inst) return null;
      do
        inst = inst.return;
      while (inst && 5 !== inst.tag && 27 !== inst.tag);
      return inst ? inst : null;
    }
    function accumulateEnterLeaveListenersForEvent(dispatchQueue, event, target, common, inCapturePhase) {
      for (var registrationName = event._reactName, listeners = []; null !== target && target !== common; ) {
        var _instance4 = target, alternate = _instance4.alternate, stateNode = _instance4.stateNode;
        _instance4 = _instance4.tag;
        if (null !== alternate && alternate === common) break;
        5 !== _instance4 && 26 !== _instance4 && 27 !== _instance4 || null === stateNode || (alternate = stateNode, inCapturePhase ? (stateNode = getListener2(target, registrationName), null != stateNode && listeners.unshift(
          createDispatchListener(target, stateNode, alternate)
        )) : inCapturePhase || (stateNode = getListener2(target, registrationName), null != stateNode && listeners.push(
          createDispatchListener(target, stateNode, alternate)
        )));
        target = target.return;
      }
      0 !== listeners.length && dispatchQueue.push({ event, listeners });
    }
    function validatePropertiesInDevelopment(type, props) {
      validateProperties$2(type, props);
      "input" !== type && "textarea" !== type && "select" !== type || null == props || null !== props.value || didWarnValueNull || (didWarnValueNull = true, "select" === type && props.multiple ? console.error(
        "`value` prop on `%s` should not be null. Consider using an empty array when `multiple` is set to `true` to clear the component or `undefined` for uncontrolled components.",
        type
      ) : console.error(
        "`value` prop on `%s` should not be null. Consider using an empty string to clear the component or `undefined` for uncontrolled components.",
        type
      ));
      var eventRegistry = {
        registrationNameDependencies,
        possibleRegistrationNames
      };
      isCustomElement(type) || "string" === typeof props.is || warnUnknownProperties(type, props, eventRegistry);
      props.contentEditable && !props.suppressContentEditableWarning && null != props.children && console.error(
        "A component is `contentEditable` and contains `children` managed by React. It is now your responsibility to guarantee that none of those nodes are unexpectedly modified or duplicated. This is probably not intentional."
      );
    }
    function warnForPropDifference(propName, serverValue, clientValue, serverDifferences) {
      serverValue !== clientValue && (clientValue = normalizeMarkupForTextOrAttribute(clientValue), normalizeMarkupForTextOrAttribute(serverValue) !== clientValue && (serverDifferences[propName] = serverValue));
    }
    function warnForExtraAttributes(domElement, attributeNames, serverDifferences) {
      attributeNames.forEach(function(attributeName) {
        serverDifferences[getPropNameFromAttributeName(attributeName)] = "style" === attributeName ? getStylesObjectFromElement(domElement) : domElement.getAttribute(attributeName);
      });
    }
    function warnForInvalidEventListener(registrationName, listener) {
      false === listener ? console.error(
        "Expected `%s` listener to be a function, instead got `false`.\n\nIf you used to conditionally omit it with %s={condition && value}, pass %s={condition ? value : undefined} instead.",
        registrationName,
        registrationName,
        registrationName
      ) : console.error(
        "Expected `%s` listener to be a function, instead got a value of `%s` type.",
        registrationName,
        typeof listener
      );
    }
    function normalizeHTML(parent, html) {
      parent = parent.namespaceURI === MATH_NAMESPACE || parent.namespaceURI === SVG_NAMESPACE ? parent.ownerDocument.createElementNS(
        parent.namespaceURI,
        parent.tagName
      ) : parent.ownerDocument.createElement(parent.tagName);
      parent.innerHTML = html;
      return parent.innerHTML;
    }
    function normalizeMarkupForTextOrAttribute(markup) {
      willCoercionThrow(markup) && (console.error(
        "The provided HTML markup uses a value of unsupported type %s. This value must be coerced to a string before using it here.",
        typeName(markup)
      ), testStringCoercion(markup));
      return ("string" === typeof markup ? markup : "" + markup).replace(NORMALIZE_NEWLINES_REGEX, "\n").replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, "");
    }
    function checkForUnmatchedText(serverText, clientText) {
      clientText = normalizeMarkupForTextOrAttribute(clientText);
      return normalizeMarkupForTextOrAttribute(serverText) === clientText ? true : false;
    }
    function setProp(domElement, tag, key2, value2, props, prevValue) {
      switch (key2) {
        case "children":
          if ("string" === typeof value2)
            validateTextNesting(value2, tag, false), "body" === tag || "textarea" === tag && "" === value2 || setTextContent(domElement, value2);
          else if ("number" === typeof value2 || "bigint" === typeof value2)
            validateTextNesting("" + value2, tag, false), "body" !== tag && setTextContent(domElement, "" + value2);
          break;
        case "className":
          setValueForKnownAttribute(domElement, "class", value2);
          break;
        case "tabIndex":
          setValueForKnownAttribute(domElement, "tabindex", value2);
          break;
        case "dir":
        case "role":
        case "viewBox":
        case "width":
        case "height":
          setValueForKnownAttribute(domElement, key2, value2);
          break;
        case "style":
          setValueForStyles(domElement, value2, prevValue);
          break;
        case "data":
          if ("object" !== tag) {
            setValueForKnownAttribute(domElement, "data", value2);
            break;
          }
        case "src":
        case "href":
          if ("" === value2 && ("a" !== tag || "href" !== key2)) {
            "src" === key2 ? console.error(
              'An empty string ("") was passed to the %s attribute. This may cause the browser to download the whole page again over the network. To fix this, either do not render the element at all or pass null to %s instead of an empty string.',
              key2,
              key2
            ) : console.error(
              'An empty string ("") was passed to the %s attribute. To fix this, either do not render the element at all or pass null to %s instead of an empty string.',
              key2,
              key2
            );
            domElement.removeAttribute(key2);
            break;
          }
          if (null == value2 || "function" === typeof value2 || "symbol" === typeof value2 || "boolean" === typeof value2) {
            domElement.removeAttribute(key2);
            break;
          }
          checkAttributeStringCoercion(value2, key2);
          value2 = sanitizeURL("" + value2);
          domElement.setAttribute(key2, value2);
          break;
        case "action":
        case "formAction":
          null != value2 && ("form" === tag ? "formAction" === key2 ? console.error(
            "You can only pass the formAction prop to <input> or <button>. Use the action prop on <form>."
          ) : "function" === typeof value2 && (null == props.encType && null == props.method || didWarnFormActionMethod || (didWarnFormActionMethod = true, console.error(
            "Cannot specify a encType or method for a form that specifies a function as the action. React provides those automatically. They will get overridden."
          )), null == props.target || didWarnFormActionTarget || (didWarnFormActionTarget = true, console.error(
            "Cannot specify a target for a form that specifies a function as the action. The function will always be executed in the same window."
          ))) : "input" === tag || "button" === tag ? "action" === key2 ? console.error(
            "You can only pass the action prop to <form>. Use the formAction prop on <input> or <button>."
          ) : "input" !== tag || "submit" === props.type || "image" === props.type || didWarnFormActionType ? "button" !== tag || null == props.type || "submit" === props.type || didWarnFormActionType ? "function" === typeof value2 && (null == props.name || didWarnFormActionName || (didWarnFormActionName = true, console.error(
            'Cannot specify a "name" prop for a button that specifies a function as a formAction. React needs it to encode which action should be invoked. It will get overridden.'
          )), null == props.formEncType && null == props.formMethod || didWarnFormActionMethod || (didWarnFormActionMethod = true, console.error(
            "Cannot specify a formEncType or formMethod for a button that specifies a function as a formAction. React provides those automatically. They will get overridden."
          )), null == props.formTarget || didWarnFormActionTarget || (didWarnFormActionTarget = true, console.error(
            "Cannot specify a formTarget for a button that specifies a function as a formAction. The function will always be executed in the same window."
          ))) : (didWarnFormActionType = true, console.error(
            'A button can only specify a formAction along with type="submit" or no type.'
          )) : (didWarnFormActionType = true, console.error(
            'An input can only specify a formAction along with type="submit" or type="image".'
          )) : "action" === key2 ? console.error(
            "You can only pass the action prop to <form>."
          ) : console.error(
            "You can only pass the formAction prop to <input> or <button>."
          ));
          if ("function" === typeof value2) {
            domElement.setAttribute(
              key2,
              "javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')"
            );
            break;
          } else
            "function" === typeof prevValue && ("formAction" === key2 ? ("input" !== tag && setProp(domElement, tag, "name", props.name, props, null), setProp(
              domElement,
              tag,
              "formEncType",
              props.formEncType,
              props,
              null
            ), setProp(
              domElement,
              tag,
              "formMethod",
              props.formMethod,
              props,
              null
            ), setProp(
              domElement,
              tag,
              "formTarget",
              props.formTarget,
              props,
              null
            )) : (setProp(
              domElement,
              tag,
              "encType",
              props.encType,
              props,
              null
            ), setProp(domElement, tag, "method", props.method, props, null), setProp(
              domElement,
              tag,
              "target",
              props.target,
              props,
              null
            )));
          if (null == value2 || "symbol" === typeof value2 || "boolean" === typeof value2) {
            domElement.removeAttribute(key2);
            break;
          }
          checkAttributeStringCoercion(value2, key2);
          value2 = sanitizeURL("" + value2);
          domElement.setAttribute(key2, value2);
          break;
        case "onClick":
          null != value2 && ("function" !== typeof value2 && warnForInvalidEventListener(key2, value2), domElement.onclick = noop$12);
          break;
        case "onScroll":
          null != value2 && ("function" !== typeof value2 && warnForInvalidEventListener(key2, value2), listenToNonDelegatedEvent("scroll", domElement));
          break;
        case "onScrollEnd":
          null != value2 && ("function" !== typeof value2 && warnForInvalidEventListener(key2, value2), listenToNonDelegatedEvent("scrollend", domElement));
          break;
        case "dangerouslySetInnerHTML":
          if (null != value2) {
            if ("object" !== typeof value2 || !("__html" in value2))
              throw Error(
                "`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://react.dev/link/dangerously-set-inner-html for more information."
              );
            key2 = value2.__html;
            if (null != key2) {
              if (null != props.children)
                throw Error(
                  "Can only set one of `children` or `props.dangerouslySetInnerHTML`."
                );
              domElement.innerHTML = key2;
            }
          }
          break;
        case "multiple":
          domElement.multiple = value2 && "function" !== typeof value2 && "symbol" !== typeof value2;
          break;
        case "muted":
          domElement.muted = value2 && "function" !== typeof value2 && "symbol" !== typeof value2;
          break;
        case "suppressContentEditableWarning":
        case "suppressHydrationWarning":
        case "defaultValue":
        case "defaultChecked":
        case "innerHTML":
        case "ref":
          break;
        case "autoFocus":
          break;
        case "xlinkHref":
          if (null == value2 || "function" === typeof value2 || "boolean" === typeof value2 || "symbol" === typeof value2) {
            domElement.removeAttribute("xlink:href");
            break;
          }
          checkAttributeStringCoercion(value2, key2);
          key2 = sanitizeURL("" + value2);
          domElement.setAttributeNS(xlinkNamespace, "xlink:href", key2);
          break;
        case "contentEditable":
        case "spellCheck":
        case "draggable":
        case "value":
        case "autoReverse":
        case "externalResourcesRequired":
        case "focusable":
        case "preserveAlpha":
          null != value2 && "function" !== typeof value2 && "symbol" !== typeof value2 ? (checkAttributeStringCoercion(value2, key2), domElement.setAttribute(key2, "" + value2)) : domElement.removeAttribute(key2);
          break;
        case "inert":
          "" !== value2 || didWarnForNewBooleanPropsWithEmptyValue[key2] || (didWarnForNewBooleanPropsWithEmptyValue[key2] = true, console.error(
            "Received an empty string for a boolean attribute `%s`. This will treat the attribute as if it were false. Either pass `false` to silence this warning, or pass `true` if you used an empty string in earlier versions of React to indicate this attribute is true.",
            key2
          ));
        case "allowFullScreen":
        case "async":
        case "autoPlay":
        case "controls":
        case "default":
        case "defer":
        case "disabled":
        case "disablePictureInPicture":
        case "disableRemotePlayback":
        case "formNoValidate":
        case "hidden":
        case "loop":
        case "noModule":
        case "noValidate":
        case "open":
        case "playsInline":
        case "readOnly":
        case "required":
        case "reversed":
        case "scoped":
        case "seamless":
        case "itemScope":
          value2 && "function" !== typeof value2 && "symbol" !== typeof value2 ? domElement.setAttribute(key2, "") : domElement.removeAttribute(key2);
          break;
        case "capture":
        case "download":
          true === value2 ? domElement.setAttribute(key2, "") : false !== value2 && null != value2 && "function" !== typeof value2 && "symbol" !== typeof value2 ? (checkAttributeStringCoercion(value2, key2), domElement.setAttribute(key2, value2)) : domElement.removeAttribute(key2);
          break;
        case "cols":
        case "rows":
        case "size":
        case "span":
          null != value2 && "function" !== typeof value2 && "symbol" !== typeof value2 && !isNaN(value2) && 1 <= value2 ? (checkAttributeStringCoercion(value2, key2), domElement.setAttribute(key2, value2)) : domElement.removeAttribute(key2);
          break;
        case "rowSpan":
        case "start":
          null == value2 || "function" === typeof value2 || "symbol" === typeof value2 || isNaN(value2) ? domElement.removeAttribute(key2) : (checkAttributeStringCoercion(value2, key2), domElement.setAttribute(key2, value2));
          break;
        case "popover":
          listenToNonDelegatedEvent("beforetoggle", domElement);
          listenToNonDelegatedEvent("toggle", domElement);
          setValueForAttribute(domElement, "popover", value2);
          break;
        case "xlinkActuate":
          setValueForNamespacedAttribute(
            domElement,
            xlinkNamespace,
            "xlink:actuate",
            value2
          );
          break;
        case "xlinkArcrole":
          setValueForNamespacedAttribute(
            domElement,
            xlinkNamespace,
            "xlink:arcrole",
            value2
          );
          break;
        case "xlinkRole":
          setValueForNamespacedAttribute(
            domElement,
            xlinkNamespace,
            "xlink:role",
            value2
          );
          break;
        case "xlinkShow":
          setValueForNamespacedAttribute(
            domElement,
            xlinkNamespace,
            "xlink:show",
            value2
          );
          break;
        case "xlinkTitle":
          setValueForNamespacedAttribute(
            domElement,
            xlinkNamespace,
            "xlink:title",
            value2
          );
          break;
        case "xlinkType":
          setValueForNamespacedAttribute(
            domElement,
            xlinkNamespace,
            "xlink:type",
            value2
          );
          break;
        case "xmlBase":
          setValueForNamespacedAttribute(
            domElement,
            xmlNamespace,
            "xml:base",
            value2
          );
          break;
        case "xmlLang":
          setValueForNamespacedAttribute(
            domElement,
            xmlNamespace,
            "xml:lang",
            value2
          );
          break;
        case "xmlSpace":
          setValueForNamespacedAttribute(
            domElement,
            xmlNamespace,
            "xml:space",
            value2
          );
          break;
        case "is":
          null != prevValue && console.error(
            'Cannot update the "is" prop after it has been initialized.'
          );
          setValueForAttribute(domElement, "is", value2);
          break;
        case "innerText":
        case "textContent":
          break;
        case "popoverTarget":
          didWarnPopoverTargetObject || null == value2 || "object" !== typeof value2 || (didWarnPopoverTargetObject = true, console.error(
            "The `popoverTarget` prop expects the ID of an Element as a string. Received %s instead.",
            value2
          ));
        default:
          !(2 < key2.length) || "o" !== key2[0] && "O" !== key2[0] || "n" !== key2[1] && "N" !== key2[1] ? (key2 = getAttributeAlias(key2), setValueForAttribute(domElement, key2, value2)) : registrationNameDependencies.hasOwnProperty(key2) && null != value2 && "function" !== typeof value2 && warnForInvalidEventListener(key2, value2);
      }
    }
    function setPropOnCustomElement(domElement, tag, key2, value2, props, prevValue) {
      switch (key2) {
        case "style":
          setValueForStyles(domElement, value2, prevValue);
          break;
        case "dangerouslySetInnerHTML":
          if (null != value2) {
            if ("object" !== typeof value2 || !("__html" in value2))
              throw Error(
                "`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://react.dev/link/dangerously-set-inner-html for more information."
              );
            key2 = value2.__html;
            if (null != key2) {
              if (null != props.children)
                throw Error(
                  "Can only set one of `children` or `props.dangerouslySetInnerHTML`."
                );
              domElement.innerHTML = key2;
            }
          }
          break;
        case "children":
          "string" === typeof value2 ? setTextContent(domElement, value2) : ("number" === typeof value2 || "bigint" === typeof value2) && setTextContent(domElement, "" + value2);
          break;
        case "onScroll":
          null != value2 && ("function" !== typeof value2 && warnForInvalidEventListener(key2, value2), listenToNonDelegatedEvent("scroll", domElement));
          break;
        case "onScrollEnd":
          null != value2 && ("function" !== typeof value2 && warnForInvalidEventListener(key2, value2), listenToNonDelegatedEvent("scrollend", domElement));
          break;
        case "onClick":
          null != value2 && ("function" !== typeof value2 && warnForInvalidEventListener(key2, value2), domElement.onclick = noop$12);
          break;
        case "suppressContentEditableWarning":
        case "suppressHydrationWarning":
        case "innerHTML":
        case "ref":
          break;
        case "innerText":
        case "textContent":
          break;
        default:
          if (registrationNameDependencies.hasOwnProperty(key2))
            null != value2 && "function" !== typeof value2 && warnForInvalidEventListener(key2, value2);
          else
            a: {
              if ("o" === key2[0] && "n" === key2[1] && (props = key2.endsWith("Capture"), tag = key2.slice(2, props ? key2.length - 7 : void 0), prevValue = domElement[internalPropsKey] || null, prevValue = null != prevValue ? prevValue[key2] : null, "function" === typeof prevValue && domElement.removeEventListener(tag, prevValue, props), "function" === typeof value2)) {
                "function" !== typeof prevValue && null !== prevValue && (key2 in domElement ? domElement[key2] = null : domElement.hasAttribute(key2) && domElement.removeAttribute(key2));
                domElement.addEventListener(tag, value2, props);
                break a;
              }
              key2 in domElement ? domElement[key2] = value2 : true === value2 ? domElement.setAttribute(key2, "") : setValueForAttribute(domElement, key2, value2);
            }
      }
    }
    function setInitialProperties(domElement, tag, props) {
      validatePropertiesInDevelopment(tag, props);
      switch (tag) {
        case "div":
        case "span":
        case "svg":
        case "path":
        case "a":
        case "g":
        case "p":
        case "li":
          break;
        case "img":
          listenToNonDelegatedEvent("error", domElement);
          listenToNonDelegatedEvent("load", domElement);
          var hasSrc = false, hasSrcSet = false, propKey;
          for (propKey in props)
            if (props.hasOwnProperty(propKey)) {
              var propValue = props[propKey];
              if (null != propValue)
                switch (propKey) {
                  case "src":
                    hasSrc = true;
                    break;
                  case "srcSet":
                    hasSrcSet = true;
                    break;
                  case "children":
                  case "dangerouslySetInnerHTML":
                    throw Error(
                      tag + " is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
                    );
                  default:
                    setProp(domElement, tag, propKey, propValue, props, null);
                }
            }
          hasSrcSet && setProp(domElement, tag, "srcSet", props.srcSet, props, null);
          hasSrc && setProp(domElement, tag, "src", props.src, props, null);
          return;
        case "input":
          checkControlledValueProps("input", props);
          listenToNonDelegatedEvent("invalid", domElement);
          var defaultValue = propKey = propValue = hasSrcSet = null, checked = null, defaultChecked = null;
          for (hasSrc in props)
            if (props.hasOwnProperty(hasSrc)) {
              var _propValue = props[hasSrc];
              if (null != _propValue)
                switch (hasSrc) {
                  case "name":
                    hasSrcSet = _propValue;
                    break;
                  case "type":
                    propValue = _propValue;
                    break;
                  case "checked":
                    checked = _propValue;
                    break;
                  case "defaultChecked":
                    defaultChecked = _propValue;
                    break;
                  case "value":
                    propKey = _propValue;
                    break;
                  case "defaultValue":
                    defaultValue = _propValue;
                    break;
                  case "children":
                  case "dangerouslySetInnerHTML":
                    if (null != _propValue)
                      throw Error(
                        tag + " is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
                      );
                    break;
                  default:
                    setProp(domElement, tag, hasSrc, _propValue, props, null);
                }
            }
          validateInputProps(domElement, props);
          initInput(
            domElement,
            propKey,
            defaultValue,
            checked,
            defaultChecked,
            propValue,
            hasSrcSet,
            false
          );
          return;
        case "select":
          checkControlledValueProps("select", props);
          listenToNonDelegatedEvent("invalid", domElement);
          hasSrc = propValue = propKey = null;
          for (hasSrcSet in props)
            if (props.hasOwnProperty(hasSrcSet) && (defaultValue = props[hasSrcSet], null != defaultValue))
              switch (hasSrcSet) {
                case "value":
                  propKey = defaultValue;
                  break;
                case "defaultValue":
                  propValue = defaultValue;
                  break;
                case "multiple":
                  hasSrc = defaultValue;
                default:
                  setProp(
                    domElement,
                    tag,
                    hasSrcSet,
                    defaultValue,
                    props,
                    null
                  );
              }
          validateSelectProps(domElement, props);
          tag = propKey;
          props = propValue;
          domElement.multiple = !!hasSrc;
          null != tag ? updateOptions(domElement, !!hasSrc, tag, false) : null != props && updateOptions(domElement, !!hasSrc, props, true);
          return;
        case "textarea":
          checkControlledValueProps("textarea", props);
          listenToNonDelegatedEvent("invalid", domElement);
          propKey = hasSrcSet = hasSrc = null;
          for (propValue in props)
            if (props.hasOwnProperty(propValue) && (defaultValue = props[propValue], null != defaultValue))
              switch (propValue) {
                case "value":
                  hasSrc = defaultValue;
                  break;
                case "defaultValue":
                  hasSrcSet = defaultValue;
                  break;
                case "children":
                  propKey = defaultValue;
                  break;
                case "dangerouslySetInnerHTML":
                  if (null != defaultValue)
                    throw Error(
                      "`dangerouslySetInnerHTML` does not make sense on <textarea>."
                    );
                  break;
                default:
                  setProp(
                    domElement,
                    tag,
                    propValue,
                    defaultValue,
                    props,
                    null
                  );
              }
          validateTextareaProps(domElement, props);
          initTextarea(domElement, hasSrc, hasSrcSet, propKey);
          return;
        case "option":
          validateOptionProps(domElement, props);
          for (checked in props)
            if (props.hasOwnProperty(checked) && (hasSrc = props[checked], null != hasSrc))
              switch (checked) {
                case "selected":
                  domElement.selected = hasSrc && "function" !== typeof hasSrc && "symbol" !== typeof hasSrc;
                  break;
                default:
                  setProp(domElement, tag, checked, hasSrc, props, null);
              }
          return;
        case "dialog":
          listenToNonDelegatedEvent("beforetoggle", domElement);
          listenToNonDelegatedEvent("toggle", domElement);
          listenToNonDelegatedEvent("cancel", domElement);
          listenToNonDelegatedEvent("close", domElement);
          break;
        case "iframe":
        case "object":
          listenToNonDelegatedEvent("load", domElement);
          break;
        case "video":
        case "audio":
          for (hasSrc = 0; hasSrc < mediaEventTypes.length; hasSrc++)
            listenToNonDelegatedEvent(mediaEventTypes[hasSrc], domElement);
          break;
        case "image":
          listenToNonDelegatedEvent("error", domElement);
          listenToNonDelegatedEvent("load", domElement);
          break;
        case "details":
          listenToNonDelegatedEvent("toggle", domElement);
          break;
        case "embed":
        case "source":
        case "link":
          listenToNonDelegatedEvent("error", domElement), listenToNonDelegatedEvent("load", domElement);
        case "area":
        case "base":
        case "br":
        case "col":
        case "hr":
        case "keygen":
        case "meta":
        case "param":
        case "track":
        case "wbr":
        case "menuitem":
          for (defaultChecked in props)
            if (props.hasOwnProperty(defaultChecked) && (hasSrc = props[defaultChecked], null != hasSrc))
              switch (defaultChecked) {
                case "children":
                case "dangerouslySetInnerHTML":
                  throw Error(
                    tag + " is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
                  );
                default:
                  setProp(domElement, tag, defaultChecked, hasSrc, props, null);
              }
          return;
        default:
          if (isCustomElement(tag)) {
            for (_propValue in props)
              props.hasOwnProperty(_propValue) && (hasSrc = props[_propValue], void 0 !== hasSrc && setPropOnCustomElement(
                domElement,
                tag,
                _propValue,
                hasSrc,
                props,
                void 0
              ));
            return;
          }
      }
      for (defaultValue in props)
        props.hasOwnProperty(defaultValue) && (hasSrc = props[defaultValue], null != hasSrc && setProp(domElement, tag, defaultValue, hasSrc, props, null));
    }
    function updateProperties(domElement, tag, lastProps, nextProps) {
      validatePropertiesInDevelopment(tag, nextProps);
      switch (tag) {
        case "div":
        case "span":
        case "svg":
        case "path":
        case "a":
        case "g":
        case "p":
        case "li":
          break;
        case "input":
          var name2 = null, type = null, value2 = null, defaultValue = null, lastDefaultValue = null, checked = null, defaultChecked = null;
          for (propKey in lastProps) {
            var lastProp = lastProps[propKey];
            if (lastProps.hasOwnProperty(propKey) && null != lastProp)
              switch (propKey) {
                case "checked":
                  break;
                case "value":
                  break;
                case "defaultValue":
                  lastDefaultValue = lastProp;
                default:
                  nextProps.hasOwnProperty(propKey) || setProp(
                    domElement,
                    tag,
                    propKey,
                    null,
                    nextProps,
                    lastProp
                  );
              }
          }
          for (var _propKey8 in nextProps) {
            var propKey = nextProps[_propKey8];
            lastProp = lastProps[_propKey8];
            if (nextProps.hasOwnProperty(_propKey8) && (null != propKey || null != lastProp))
              switch (_propKey8) {
                case "type":
                  type = propKey;
                  break;
                case "name":
                  name2 = propKey;
                  break;
                case "checked":
                  checked = propKey;
                  break;
                case "defaultChecked":
                  defaultChecked = propKey;
                  break;
                case "value":
                  value2 = propKey;
                  break;
                case "defaultValue":
                  defaultValue = propKey;
                  break;
                case "children":
                case "dangerouslySetInnerHTML":
                  if (null != propKey)
                    throw Error(
                      tag + " is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
                    );
                  break;
                default:
                  propKey !== lastProp && setProp(
                    domElement,
                    tag,
                    _propKey8,
                    propKey,
                    nextProps,
                    lastProp
                  );
              }
          }
          tag = "checkbox" === lastProps.type || "radio" === lastProps.type ? null != lastProps.checked : null != lastProps.value;
          nextProps = "checkbox" === nextProps.type || "radio" === nextProps.type ? null != nextProps.checked : null != nextProps.value;
          tag || !nextProps || didWarnUncontrolledToControlled || (console.error(
            "A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://react.dev/link/controlled-components"
          ), didWarnUncontrolledToControlled = true);
          !tag || nextProps || didWarnControlledToUncontrolled || (console.error(
            "A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://react.dev/link/controlled-components"
          ), didWarnControlledToUncontrolled = true);
          updateInput(
            domElement,
            value2,
            defaultValue,
            lastDefaultValue,
            checked,
            defaultChecked,
            type,
            name2
          );
          return;
        case "select":
          propKey = value2 = defaultValue = _propKey8 = null;
          for (type in lastProps)
            if (lastDefaultValue = lastProps[type], lastProps.hasOwnProperty(type) && null != lastDefaultValue)
              switch (type) {
                case "value":
                  break;
                case "multiple":
                  propKey = lastDefaultValue;
                default:
                  nextProps.hasOwnProperty(type) || setProp(
                    domElement,
                    tag,
                    type,
                    null,
                    nextProps,
                    lastDefaultValue
                  );
              }
          for (name2 in nextProps)
            if (type = nextProps[name2], lastDefaultValue = lastProps[name2], nextProps.hasOwnProperty(name2) && (null != type || null != lastDefaultValue))
              switch (name2) {
                case "value":
                  _propKey8 = type;
                  break;
                case "defaultValue":
                  defaultValue = type;
                  break;
                case "multiple":
                  value2 = type;
                default:
                  type !== lastDefaultValue && setProp(
                    domElement,
                    tag,
                    name2,
                    type,
                    nextProps,
                    lastDefaultValue
                  );
              }
          nextProps = defaultValue;
          tag = value2;
          lastProps = propKey;
          null != _propKey8 ? updateOptions(domElement, !!tag, _propKey8, false) : !!lastProps !== !!tag && (null != nextProps ? updateOptions(domElement, !!tag, nextProps, true) : updateOptions(domElement, !!tag, tag ? [] : "", false));
          return;
        case "textarea":
          propKey = _propKey8 = null;
          for (defaultValue in lastProps)
            if (name2 = lastProps[defaultValue], lastProps.hasOwnProperty(defaultValue) && null != name2 && !nextProps.hasOwnProperty(defaultValue))
              switch (defaultValue) {
                case "value":
                  break;
                case "children":
                  break;
                default:
                  setProp(domElement, tag, defaultValue, null, nextProps, name2);
              }
          for (value2 in nextProps)
            if (name2 = nextProps[value2], type = lastProps[value2], nextProps.hasOwnProperty(value2) && (null != name2 || null != type))
              switch (value2) {
                case "value":
                  _propKey8 = name2;
                  break;
                case "defaultValue":
                  propKey = name2;
                  break;
                case "children":
                  break;
                case "dangerouslySetInnerHTML":
                  if (null != name2)
                    throw Error(
                      "`dangerouslySetInnerHTML` does not make sense on <textarea>."
                    );
                  break;
                default:
                  name2 !== type && setProp(domElement, tag, value2, name2, nextProps, type);
              }
          updateTextarea(domElement, _propKey8, propKey);
          return;
        case "option":
          for (var _propKey13 in lastProps)
            if (_propKey8 = lastProps[_propKey13], lastProps.hasOwnProperty(_propKey13) && null != _propKey8 && !nextProps.hasOwnProperty(_propKey13))
              switch (_propKey13) {
                case "selected":
                  domElement.selected = false;
                  break;
                default:
                  setProp(
                    domElement,
                    tag,
                    _propKey13,
                    null,
                    nextProps,
                    _propKey8
                  );
              }
          for (lastDefaultValue in nextProps)
            if (_propKey8 = nextProps[lastDefaultValue], propKey = lastProps[lastDefaultValue], nextProps.hasOwnProperty(lastDefaultValue) && _propKey8 !== propKey && (null != _propKey8 || null != propKey))
              switch (lastDefaultValue) {
                case "selected":
                  domElement.selected = _propKey8 && "function" !== typeof _propKey8 && "symbol" !== typeof _propKey8;
                  break;
                default:
                  setProp(
                    domElement,
                    tag,
                    lastDefaultValue,
                    _propKey8,
                    nextProps,
                    propKey
                  );
              }
          return;
        case "img":
        case "link":
        case "area":
        case "base":
        case "br":
        case "col":
        case "embed":
        case "hr":
        case "keygen":
        case "meta":
        case "param":
        case "source":
        case "track":
        case "wbr":
        case "menuitem":
          for (var _propKey15 in lastProps)
            _propKey8 = lastProps[_propKey15], lastProps.hasOwnProperty(_propKey15) && null != _propKey8 && !nextProps.hasOwnProperty(_propKey15) && setProp(
              domElement,
              tag,
              _propKey15,
              null,
              nextProps,
              _propKey8
            );
          for (checked in nextProps)
            if (_propKey8 = nextProps[checked], propKey = lastProps[checked], nextProps.hasOwnProperty(checked) && _propKey8 !== propKey && (null != _propKey8 || null != propKey))
              switch (checked) {
                case "children":
                case "dangerouslySetInnerHTML":
                  if (null != _propKey8)
                    throw Error(
                      tag + " is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
                    );
                  break;
                default:
                  setProp(
                    domElement,
                    tag,
                    checked,
                    _propKey8,
                    nextProps,
                    propKey
                  );
              }
          return;
        default:
          if (isCustomElement(tag)) {
            for (var _propKey17 in lastProps)
              _propKey8 = lastProps[_propKey17], lastProps.hasOwnProperty(_propKey17) && void 0 !== _propKey8 && !nextProps.hasOwnProperty(_propKey17) && setPropOnCustomElement(
                domElement,
                tag,
                _propKey17,
                void 0,
                nextProps,
                _propKey8
              );
            for (defaultChecked in nextProps)
              _propKey8 = nextProps[defaultChecked], propKey = lastProps[defaultChecked], !nextProps.hasOwnProperty(defaultChecked) || _propKey8 === propKey || void 0 === _propKey8 && void 0 === propKey || setPropOnCustomElement(
                domElement,
                tag,
                defaultChecked,
                _propKey8,
                nextProps,
                propKey
              );
            return;
          }
      }
      for (var _propKey19 in lastProps)
        _propKey8 = lastProps[_propKey19], lastProps.hasOwnProperty(_propKey19) && null != _propKey8 && !nextProps.hasOwnProperty(_propKey19) && setProp(domElement, tag, _propKey19, null, nextProps, _propKey8);
      for (lastProp in nextProps)
        _propKey8 = nextProps[lastProp], propKey = lastProps[lastProp], !nextProps.hasOwnProperty(lastProp) || _propKey8 === propKey || null == _propKey8 && null == propKey || setProp(domElement, tag, lastProp, _propKey8, nextProps, propKey);
    }
    function getPropNameFromAttributeName(attrName) {
      switch (attrName) {
        case "class":
          return "className";
        case "for":
          return "htmlFor";
        default:
          return attrName;
      }
    }
    function getStylesObjectFromElement(domElement) {
      var serverValueInObjectForm = {};
      domElement = domElement.style;
      for (var i2 = 0; i2 < domElement.length; i2++) {
        var styleName = domElement[i2];
        serverValueInObjectForm[styleName] = domElement.getPropertyValue(styleName);
      }
      return serverValueInObjectForm;
    }
    function diffHydratedStyles(domElement, value$jscomp$0, serverDifferences) {
      if (null != value$jscomp$0 && "object" !== typeof value$jscomp$0)
        console.error(
          "The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX."
        );
      else {
        var clientValue;
        var delimiter2 = clientValue = "", styleName;
        for (styleName in value$jscomp$0)
          if (value$jscomp$0.hasOwnProperty(styleName)) {
            var value2 = value$jscomp$0[styleName];
            null != value2 && "boolean" !== typeof value2 && "" !== value2 && (0 === styleName.indexOf("--") ? (checkCSSPropertyStringCoercion(value2, styleName), clientValue += delimiter2 + styleName + ":" + ("" + value2).trim()) : "number" !== typeof value2 || 0 === value2 || unitlessNumbers.has(styleName) ? (checkCSSPropertyStringCoercion(value2, styleName), clientValue += delimiter2 + styleName.replace(uppercasePattern, "-$1").toLowerCase().replace(msPattern$1, "-ms-") + ":" + ("" + value2).trim()) : clientValue += delimiter2 + styleName.replace(uppercasePattern, "-$1").toLowerCase().replace(msPattern$1, "-ms-") + ":" + value2 + "px", delimiter2 = ";");
          }
        clientValue = clientValue || null;
        value$jscomp$0 = domElement.getAttribute("style");
        value$jscomp$0 !== clientValue && (clientValue = normalizeMarkupForTextOrAttribute(clientValue), normalizeMarkupForTextOrAttribute(value$jscomp$0) !== clientValue && (serverDifferences.style = getStylesObjectFromElement(domElement)));
      }
    }
    function hydrateAttribute(domElement, propKey, attributeName, value2, extraAttributes, serverDifferences) {
      extraAttributes.delete(attributeName);
      domElement = domElement.getAttribute(attributeName);
      if (null === domElement)
        switch (typeof value2) {
          case "undefined":
          case "function":
          case "symbol":
          case "boolean":
            return;
        }
      else if (null != value2)
        switch (typeof value2) {
          case "function":
          case "symbol":
          case "boolean":
            break;
          default:
            if (checkAttributeStringCoercion(value2, propKey), domElement === "" + value2)
              return;
        }
      warnForPropDifference(propKey, domElement, value2, serverDifferences);
    }
    function hydrateBooleanAttribute(domElement, propKey, attributeName, value2, extraAttributes, serverDifferences) {
      extraAttributes.delete(attributeName);
      domElement = domElement.getAttribute(attributeName);
      if (null === domElement) {
        switch (typeof value2) {
          case "function":
          case "symbol":
            return;
        }
        if (!value2) return;
      } else
        switch (typeof value2) {
          case "function":
          case "symbol":
            break;
          default:
            if (value2) return;
        }
      warnForPropDifference(propKey, domElement, value2, serverDifferences);
    }
    function hydrateBooleanishAttribute(domElement, propKey, attributeName, value2, extraAttributes, serverDifferences) {
      extraAttributes.delete(attributeName);
      domElement = domElement.getAttribute(attributeName);
      if (null === domElement)
        switch (typeof value2) {
          case "undefined":
          case "function":
          case "symbol":
            return;
        }
      else if (null != value2)
        switch (typeof value2) {
          case "function":
          case "symbol":
            break;
          default:
            if (checkAttributeStringCoercion(value2, attributeName), domElement === "" + value2)
              return;
        }
      warnForPropDifference(propKey, domElement, value2, serverDifferences);
    }
    function hydrateNumericAttribute(domElement, propKey, attributeName, value2, extraAttributes, serverDifferences) {
      extraAttributes.delete(attributeName);
      domElement = domElement.getAttribute(attributeName);
      if (null === domElement)
        switch (typeof value2) {
          case "undefined":
          case "function":
          case "symbol":
          case "boolean":
            return;
          default:
            if (isNaN(value2)) return;
        }
      else if (null != value2)
        switch (typeof value2) {
          case "function":
          case "symbol":
          case "boolean":
            break;
          default:
            if (!isNaN(value2) && (checkAttributeStringCoercion(value2, propKey), domElement === "" + value2))
              return;
        }
      warnForPropDifference(propKey, domElement, value2, serverDifferences);
    }
    function hydrateSanitizedAttribute(domElement, propKey, attributeName, value2, extraAttributes, serverDifferences) {
      extraAttributes.delete(attributeName);
      domElement = domElement.getAttribute(attributeName);
      if (null === domElement)
        switch (typeof value2) {
          case "undefined":
          case "function":
          case "symbol":
          case "boolean":
            return;
        }
      else if (null != value2)
        switch (typeof value2) {
          case "function":
          case "symbol":
          case "boolean":
            break;
          default:
            if (checkAttributeStringCoercion(value2, propKey), attributeName = sanitizeURL("" + value2), domElement === attributeName)
              return;
        }
      warnForPropDifference(propKey, domElement, value2, serverDifferences);
    }
    function diffHydratedProperties(domElement, tag, props, hostContext) {
      for (var serverDifferences = {}, extraAttributes = /* @__PURE__ */ new Set(), attributes = domElement.attributes, i2 = 0; i2 < attributes.length; i2++)
        switch (attributes[i2].name.toLowerCase()) {
          case "value":
            break;
          case "checked":
            break;
          case "selected":
            break;
          default:
            extraAttributes.add(attributes[i2].name);
        }
      if (isCustomElement(tag))
        for (var propKey in props) {
          if (props.hasOwnProperty(propKey)) {
            var value2 = props[propKey];
            if (null != value2) {
              if (registrationNameDependencies.hasOwnProperty(propKey))
                "function" !== typeof value2 && warnForInvalidEventListener(propKey, value2);
              else if (true !== props.suppressHydrationWarning)
                switch (propKey) {
                  case "children":
                    "string" !== typeof value2 && "number" !== typeof value2 || warnForPropDifference(
                      "children",
                      domElement.textContent,
                      value2,
                      serverDifferences
                    );
                    continue;
                  case "suppressContentEditableWarning":
                  case "suppressHydrationWarning":
                  case "defaultValue":
                  case "defaultChecked":
                  case "innerHTML":
                  case "ref":
                    continue;
                  case "dangerouslySetInnerHTML":
                    attributes = domElement.innerHTML;
                    value2 = value2 ? value2.__html : void 0;
                    null != value2 && (value2 = normalizeHTML(domElement, value2), warnForPropDifference(
                      propKey,
                      attributes,
                      value2,
                      serverDifferences
                    ));
                    continue;
                  case "style":
                    extraAttributes.delete(propKey);
                    diffHydratedStyles(domElement, value2, serverDifferences);
                    continue;
                  case "offsetParent":
                  case "offsetTop":
                  case "offsetLeft":
                  case "offsetWidth":
                  case "offsetHeight":
                  case "isContentEditable":
                  case "outerText":
                  case "outerHTML":
                    extraAttributes.delete(propKey.toLowerCase());
                    console.error(
                      "Assignment to read-only property will result in a no-op: `%s`",
                      propKey
                    );
                    continue;
                  case "className":
                    extraAttributes.delete("class");
                    attributes = getValueForAttributeOnCustomComponent(
                      domElement,
                      "class",
                      value2
                    );
                    warnForPropDifference(
                      "className",
                      attributes,
                      value2,
                      serverDifferences
                    );
                    continue;
                  default:
                    hostContext.context === HostContextNamespaceNone && "svg" !== tag && "math" !== tag ? extraAttributes.delete(propKey.toLowerCase()) : extraAttributes.delete(propKey), attributes = getValueForAttributeOnCustomComponent(
                      domElement,
                      propKey,
                      value2
                    ), warnForPropDifference(
                      propKey,
                      attributes,
                      value2,
                      serverDifferences
                    );
                }
            }
          }
        }
      else
        for (value2 in props)
          if (props.hasOwnProperty(value2) && (propKey = props[value2], null != propKey)) {
            if (registrationNameDependencies.hasOwnProperty(value2))
              "function" !== typeof propKey && warnForInvalidEventListener(value2, propKey);
            else if (true !== props.suppressHydrationWarning)
              switch (value2) {
                case "children":
                  "string" !== typeof propKey && "number" !== typeof propKey || warnForPropDifference(
                    "children",
                    domElement.textContent,
                    propKey,
                    serverDifferences
                  );
                  continue;
                case "suppressContentEditableWarning":
                case "suppressHydrationWarning":
                case "value":
                case "checked":
                case "selected":
                case "defaultValue":
                case "defaultChecked":
                case "innerHTML":
                case "ref":
                  continue;
                case "dangerouslySetInnerHTML":
                  attributes = domElement.innerHTML;
                  propKey = propKey ? propKey.__html : void 0;
                  null != propKey && (propKey = normalizeHTML(domElement, propKey), attributes !== propKey && (serverDifferences[value2] = { __html: attributes }));
                  continue;
                case "className":
                  hydrateAttribute(
                    domElement,
                    value2,
                    "class",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "tabIndex":
                  hydrateAttribute(
                    domElement,
                    value2,
                    "tabindex",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "style":
                  extraAttributes.delete(value2);
                  diffHydratedStyles(domElement, propKey, serverDifferences);
                  continue;
                case "multiple":
                  extraAttributes.delete(value2);
                  warnForPropDifference(
                    value2,
                    domElement.multiple,
                    propKey,
                    serverDifferences
                  );
                  continue;
                case "muted":
                  extraAttributes.delete(value2);
                  warnForPropDifference(
                    value2,
                    domElement.muted,
                    propKey,
                    serverDifferences
                  );
                  continue;
                case "autoFocus":
                  extraAttributes.delete("autofocus");
                  warnForPropDifference(
                    value2,
                    domElement.autofocus,
                    propKey,
                    serverDifferences
                  );
                  continue;
                case "data":
                  if ("object" !== tag) {
                    extraAttributes.delete(value2);
                    attributes = domElement.getAttribute("data");
                    warnForPropDifference(
                      value2,
                      attributes,
                      propKey,
                      serverDifferences
                    );
                    continue;
                  }
                case "src":
                case "href":
                  if (!("" !== propKey || "a" === tag && "href" === value2 || "object" === tag && "data" === value2)) {
                    "src" === value2 ? console.error(
                      'An empty string ("") was passed to the %s attribute. This may cause the browser to download the whole page again over the network. To fix this, either do not render the element at all or pass null to %s instead of an empty string.',
                      value2,
                      value2
                    ) : console.error(
                      'An empty string ("") was passed to the %s attribute. To fix this, either do not render the element at all or pass null to %s instead of an empty string.',
                      value2,
                      value2
                    );
                    continue;
                  }
                  hydrateSanitizedAttribute(
                    domElement,
                    value2,
                    value2,
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "action":
                case "formAction":
                  attributes = domElement.getAttribute(value2);
                  if ("function" === typeof propKey) {
                    extraAttributes.delete(value2.toLowerCase());
                    "formAction" === value2 ? (extraAttributes.delete("name"), extraAttributes.delete("formenctype"), extraAttributes.delete("formmethod"), extraAttributes.delete("formtarget")) : (extraAttributes.delete("enctype"), extraAttributes.delete("method"), extraAttributes.delete("target"));
                    continue;
                  } else if (attributes === EXPECTED_FORM_ACTION_URL) {
                    extraAttributes.delete(value2.toLowerCase());
                    warnForPropDifference(
                      value2,
                      "function",
                      propKey,
                      serverDifferences
                    );
                    continue;
                  }
                  hydrateSanitizedAttribute(
                    domElement,
                    value2,
                    value2.toLowerCase(),
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "xlinkHref":
                  hydrateSanitizedAttribute(
                    domElement,
                    value2,
                    "xlink:href",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "contentEditable":
                  hydrateBooleanishAttribute(
                    domElement,
                    value2,
                    "contenteditable",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "spellCheck":
                  hydrateBooleanishAttribute(
                    domElement,
                    value2,
                    "spellcheck",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "draggable":
                case "autoReverse":
                case "externalResourcesRequired":
                case "focusable":
                case "preserveAlpha":
                  hydrateBooleanishAttribute(
                    domElement,
                    value2,
                    value2,
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "allowFullScreen":
                case "async":
                case "autoPlay":
                case "controls":
                case "default":
                case "defer":
                case "disabled":
                case "disablePictureInPicture":
                case "disableRemotePlayback":
                case "formNoValidate":
                case "hidden":
                case "loop":
                case "noModule":
                case "noValidate":
                case "open":
                case "playsInline":
                case "readOnly":
                case "required":
                case "reversed":
                case "scoped":
                case "seamless":
                case "itemScope":
                  hydrateBooleanAttribute(
                    domElement,
                    value2,
                    value2.toLowerCase(),
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "capture":
                case "download":
                  a: {
                    i2 = domElement;
                    var attributeName = attributes = value2, serverDifferences$jscomp$0 = serverDifferences;
                    extraAttributes.delete(attributeName);
                    i2 = i2.getAttribute(attributeName);
                    if (null === i2)
                      switch (typeof propKey) {
                        case "undefined":
                        case "function":
                        case "symbol":
                          break a;
                        default:
                          if (false === propKey) break a;
                      }
                    else if (null != propKey)
                      switch (typeof propKey) {
                        case "function":
                        case "symbol":
                          break;
                        case "boolean":
                          if (true === propKey && "" === i2) break a;
                          break;
                        default:
                          if (checkAttributeStringCoercion(propKey, attributes), i2 === "" + propKey)
                            break a;
                      }
                    warnForPropDifference(
                      attributes,
                      i2,
                      propKey,
                      serverDifferences$jscomp$0
                    );
                  }
                  continue;
                case "cols":
                case "rows":
                case "size":
                case "span":
                  a: {
                    i2 = domElement;
                    attributeName = attributes = value2;
                    serverDifferences$jscomp$0 = serverDifferences;
                    extraAttributes.delete(attributeName);
                    i2 = i2.getAttribute(attributeName);
                    if (null === i2)
                      switch (typeof propKey) {
                        case "undefined":
                        case "function":
                        case "symbol":
                        case "boolean":
                          break a;
                        default:
                          if (isNaN(propKey) || 1 > propKey) break a;
                      }
                    else if (null != propKey)
                      switch (typeof propKey) {
                        case "function":
                        case "symbol":
                        case "boolean":
                          break;
                        default:
                          if (!(isNaN(propKey) || 1 > propKey) && (checkAttributeStringCoercion(propKey, attributes), i2 === "" + propKey))
                            break a;
                      }
                    warnForPropDifference(
                      attributes,
                      i2,
                      propKey,
                      serverDifferences$jscomp$0
                    );
                  }
                  continue;
                case "rowSpan":
                  hydrateNumericAttribute(
                    domElement,
                    value2,
                    "rowspan",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "start":
                  hydrateNumericAttribute(
                    domElement,
                    value2,
                    value2,
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "xHeight":
                  hydrateAttribute(
                    domElement,
                    value2,
                    "x-height",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "xlinkActuate":
                  hydrateAttribute(
                    domElement,
                    value2,
                    "xlink:actuate",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "xlinkArcrole":
                  hydrateAttribute(
                    domElement,
                    value2,
                    "xlink:arcrole",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "xlinkRole":
                  hydrateAttribute(
                    domElement,
                    value2,
                    "xlink:role",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "xlinkShow":
                  hydrateAttribute(
                    domElement,
                    value2,
                    "xlink:show",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "xlinkTitle":
                  hydrateAttribute(
                    domElement,
                    value2,
                    "xlink:title",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "xlinkType":
                  hydrateAttribute(
                    domElement,
                    value2,
                    "xlink:type",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "xmlBase":
                  hydrateAttribute(
                    domElement,
                    value2,
                    "xml:base",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "xmlLang":
                  hydrateAttribute(
                    domElement,
                    value2,
                    "xml:lang",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "xmlSpace":
                  hydrateAttribute(
                    domElement,
                    value2,
                    "xml:space",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "inert":
                  "" !== propKey || didWarnForNewBooleanPropsWithEmptyValue[value2] || (didWarnForNewBooleanPropsWithEmptyValue[value2] = true, console.error(
                    "Received an empty string for a boolean attribute `%s`. This will treat the attribute as if it were false. Either pass `false` to silence this warning, or pass `true` if you used an empty string in earlier versions of React to indicate this attribute is true.",
                    value2
                  ));
                  hydrateBooleanAttribute(
                    domElement,
                    value2,
                    value2,
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                default:
                  if (!(2 < value2.length) || "o" !== value2[0] && "O" !== value2[0] || "n" !== value2[1] && "N" !== value2[1]) {
                    i2 = getAttributeAlias(value2);
                    attributes = false;
                    hostContext.context === HostContextNamespaceNone && "svg" !== tag && "math" !== tag ? extraAttributes.delete(i2.toLowerCase()) : (attributeName = value2.toLowerCase(), attributeName = possibleStandardNames.hasOwnProperty(
                      attributeName
                    ) ? possibleStandardNames[attributeName] || null : null, null !== attributeName && attributeName !== value2 && (attributes = true, extraAttributes.delete(attributeName)), extraAttributes.delete(i2));
                    a: if (attributeName = domElement, serverDifferences$jscomp$0 = i2, i2 = propKey, isAttributeNameSafe(serverDifferences$jscomp$0))
                      if (attributeName.hasAttribute(serverDifferences$jscomp$0))
                        attributeName = attributeName.getAttribute(
                          serverDifferences$jscomp$0
                        ), checkAttributeStringCoercion(
                          i2,
                          serverDifferences$jscomp$0
                        ), i2 = attributeName === "" + i2 ? i2 : attributeName;
                      else {
                        switch (typeof i2) {
                          case "function":
                          case "symbol":
                            break a;
                          case "boolean":
                            if (attributeName = serverDifferences$jscomp$0.toLowerCase().slice(0, 5), "data-" !== attributeName && "aria-" !== attributeName)
                              break a;
                        }
                        i2 = void 0 === i2 ? void 0 : null;
                      }
                    else i2 = void 0;
                    attributes || warnForPropDifference(
                      value2,
                      i2,
                      propKey,
                      serverDifferences
                    );
                  }
              }
          }
      0 < extraAttributes.size && true !== props.suppressHydrationWarning && warnForExtraAttributes(domElement, extraAttributes, serverDifferences);
      return 0 === Object.keys(serverDifferences).length ? null : serverDifferences;
    }
    function propNamesListJoin(list2, combinator) {
      switch (list2.length) {
        case 0:
          return "";
        case 1:
          return list2[0];
        case 2:
          return list2[0] + " " + combinator + " " + list2[1];
        default:
          return list2.slice(0, -1).join(", ") + ", " + combinator + " " + list2[list2.length - 1];
      }
    }
    function isLikelyStaticResource(initiatorType) {
      switch (initiatorType) {
        case "css":
        case "script":
        case "font":
        case "img":
        case "image":
        case "input":
        case "link":
          return true;
        default:
          return false;
      }
    }
    function estimateBandwidth() {
      if ("function" === typeof performance.getEntriesByType) {
        for (var count2 = 0, bits = 0, resourceEntries = performance.getEntriesByType("resource"), i2 = 0; i2 < resourceEntries.length; i2++) {
          var entry2 = resourceEntries[i2], transferSize = entry2.transferSize, initiatorType = entry2.initiatorType, duration2 = entry2.duration;
          if (transferSize && duration2 && isLikelyStaticResource(initiatorType)) {
            initiatorType = 0;
            duration2 = entry2.responseEnd;
            for (i2 += 1; i2 < resourceEntries.length; i2++) {
              var overlapEntry = resourceEntries[i2], overlapStartTime = overlapEntry.startTime;
              if (overlapStartTime > duration2) break;
              var overlapTransferSize = overlapEntry.transferSize, overlapInitiatorType = overlapEntry.initiatorType;
              overlapTransferSize && isLikelyStaticResource(overlapInitiatorType) && (overlapEntry = overlapEntry.responseEnd, initiatorType += overlapTransferSize * (overlapEntry < duration2 ? 1 : (duration2 - overlapStartTime) / (overlapEntry - overlapStartTime)));
            }
            --i2;
            bits += 8 * (transferSize + initiatorType) / (entry2.duration / 1e3);
            count2++;
            if (10 < count2) break;
          }
        }
        if (0 < count2) return bits / count2 / 1e6;
      }
      return navigator.connection && (count2 = navigator.connection.downlink, "number" === typeof count2) ? count2 : 5;
    }
    function getOwnerDocumentFromRootContainer(rootContainerElement) {
      return 9 === rootContainerElement.nodeType ? rootContainerElement : rootContainerElement.ownerDocument;
    }
    function getOwnHostContext(namespaceURI) {
      switch (namespaceURI) {
        case SVG_NAMESPACE:
          return HostContextNamespaceSvg;
        case MATH_NAMESPACE:
          return HostContextNamespaceMath;
        default:
          return HostContextNamespaceNone;
      }
    }
    function getChildHostContextProd(parentNamespace, type) {
      if (parentNamespace === HostContextNamespaceNone)
        switch (type) {
          case "svg":
            return HostContextNamespaceSvg;
          case "math":
            return HostContextNamespaceMath;
          default:
            return HostContextNamespaceNone;
        }
      return parentNamespace === HostContextNamespaceSvg && "foreignObject" === type ? HostContextNamespaceNone : parentNamespace;
    }
    function shouldSetTextContent(type, props) {
      return "textarea" === type || "noscript" === type || "string" === typeof props.children || "number" === typeof props.children || "bigint" === typeof props.children || "object" === typeof props.dangerouslySetInnerHTML && null !== props.dangerouslySetInnerHTML && null != props.dangerouslySetInnerHTML.__html;
    }
    function shouldAttemptEagerTransition() {
      var event = window.event;
      if (event && "popstate" === event.type) {
        if (event === currentPopstateTransitionEvent) return false;
        currentPopstateTransitionEvent = event;
        return true;
      }
      currentPopstateTransitionEvent = null;
      return false;
    }
    function resolveEventType() {
      var event = window.event;
      return event && event !== schedulerEvent ? event.type : null;
    }
    function resolveEventTimeStamp() {
      var event = window.event;
      return event && event !== schedulerEvent ? event.timeStamp : -1.1;
    }
    function handleErrorInNextTick(error2) {
      setTimeout(function() {
        throw error2;
      });
    }
    function commitMount(domElement, type, newProps) {
      switch (type) {
        case "button":
        case "input":
        case "select":
        case "textarea":
          newProps.autoFocus && domElement.focus();
          break;
        case "img":
          newProps.src ? domElement.src = newProps.src : newProps.srcSet && (domElement.srcset = newProps.srcSet);
      }
    }
    function commitHydratedInstance() {
    }
    function commitUpdate(domElement, type, oldProps, newProps) {
      updateProperties(domElement, type, oldProps, newProps);
      domElement[internalPropsKey] = newProps;
    }
    function resetTextContent(domElement) {
      setTextContent(domElement, "");
    }
    function commitTextUpdate(textInstance, oldText, newText) {
      textInstance.nodeValue = newText;
    }
    function warnForReactChildrenConflict(container2) {
      if (!container2.__reactWarnedAboutChildrenConflict) {
        var props = container2[internalPropsKey] || null;
        if (null !== props) {
          var fiber = getInstanceFromNode(container2);
          null !== fiber && ("string" === typeof props.children || "number" === typeof props.children ? (container2.__reactWarnedAboutChildrenConflict = true, runWithFiberInDEV(fiber, function() {
            console.error(
              'Cannot use a ref on a React element as a container to `createRoot` or `createPortal` if that element also sets "children" text content using React. It should be a leaf with no children. Otherwise it\'s ambiguous which children should be used.'
            );
          })) : null != props.dangerouslySetInnerHTML && (container2.__reactWarnedAboutChildrenConflict = true, runWithFiberInDEV(fiber, function() {
            console.error(
              'Cannot use a ref on a React element as a container to `createRoot` or `createPortal` if that element also sets "dangerouslySetInnerHTML" using React. It should be a leaf with no children. Otherwise it\'s ambiguous which children should be used.'
            );
          })));
        }
      }
    }
    function isSingletonScope(type) {
      return "head" === type;
    }
    function removeChild(parentInstance, child) {
      parentInstance.removeChild(child);
    }
    function removeChildFromContainer(container2, child) {
      (9 === container2.nodeType ? container2.body : "HTML" === container2.nodeName ? container2.ownerDocument.body : container2).removeChild(child);
    }
    function clearHydrationBoundary(parentInstance, hydrationInstance) {
      var node2 = hydrationInstance, depth = 0;
      do {
        var nextNode = node2.nextSibling;
        parentInstance.removeChild(node2);
        if (nextNode && 8 === nextNode.nodeType)
          if (node2 = nextNode.data, node2 === SUSPENSE_END_DATA || node2 === ACTIVITY_END_DATA) {
            if (0 === depth) {
              parentInstance.removeChild(nextNode);
              retryIfBlockedOn(hydrationInstance);
              return;
            }
            depth--;
          } else if (node2 === SUSPENSE_START_DATA || node2 === SUSPENSE_PENDING_START_DATA || node2 === SUSPENSE_QUEUED_START_DATA || node2 === SUSPENSE_FALLBACK_START_DATA || node2 === ACTIVITY_START_DATA)
            depth++;
          else if (node2 === PREAMBLE_CONTRIBUTION_HTML)
            releaseSingletonInstance(
              parentInstance.ownerDocument.documentElement
            );
          else if (node2 === PREAMBLE_CONTRIBUTION_HEAD) {
            node2 = parentInstance.ownerDocument.head;
            releaseSingletonInstance(node2);
            for (var node$jscomp$0 = node2.firstChild; node$jscomp$0; ) {
              var nextNode$jscomp$0 = node$jscomp$0.nextSibling, nodeName = node$jscomp$0.nodeName;
              node$jscomp$0[internalHoistableMarker] || "SCRIPT" === nodeName || "STYLE" === nodeName || "LINK" === nodeName && "stylesheet" === node$jscomp$0.rel.toLowerCase() || node2.removeChild(node$jscomp$0);
              node$jscomp$0 = nextNode$jscomp$0;
            }
          } else
            node2 === PREAMBLE_CONTRIBUTION_BODY && releaseSingletonInstance(parentInstance.ownerDocument.body);
        node2 = nextNode;
      } while (node2);
      retryIfBlockedOn(hydrationInstance);
    }
    function hideOrUnhideDehydratedBoundary(suspenseInstance, isHidden) {
      var node2 = suspenseInstance;
      suspenseInstance = 0;
      do {
        var nextNode = node2.nextSibling;
        1 === node2.nodeType ? isHidden ? (node2._stashedDisplay = node2.style.display, node2.style.display = "none") : (node2.style.display = node2._stashedDisplay || "", "" === node2.getAttribute("style") && node2.removeAttribute("style")) : 3 === node2.nodeType && (isHidden ? (node2._stashedText = node2.nodeValue, node2.nodeValue = "") : node2.nodeValue = node2._stashedText || "");
        if (nextNode && 8 === nextNode.nodeType)
          if (node2 = nextNode.data, node2 === SUSPENSE_END_DATA)
            if (0 === suspenseInstance) break;
            else suspenseInstance--;
          else
            node2 !== SUSPENSE_START_DATA && node2 !== SUSPENSE_PENDING_START_DATA && node2 !== SUSPENSE_QUEUED_START_DATA && node2 !== SUSPENSE_FALLBACK_START_DATA || suspenseInstance++;
        node2 = nextNode;
      } while (node2);
    }
    function hideDehydratedBoundary(suspenseInstance) {
      hideOrUnhideDehydratedBoundary(suspenseInstance, true);
    }
    function hideInstance(instance2) {
      instance2 = instance2.style;
      "function" === typeof instance2.setProperty ? instance2.setProperty("display", "none", "important") : instance2.display = "none";
    }
    function hideTextInstance(textInstance) {
      textInstance.nodeValue = "";
    }
    function unhideDehydratedBoundary(dehydratedInstance) {
      hideOrUnhideDehydratedBoundary(dehydratedInstance, false);
    }
    function unhideInstance(instance2, props) {
      props = props[STYLE];
      props = void 0 !== props && null !== props && props.hasOwnProperty("display") ? props.display : null;
      instance2.style.display = null == props || "boolean" === typeof props ? "" : ("" + props).trim();
    }
    function unhideTextInstance(textInstance, text2) {
      textInstance.nodeValue = text2;
    }
    function clearContainerSparingly(container2) {
      var nextNode = container2.firstChild;
      nextNode && 10 === nextNode.nodeType && (nextNode = nextNode.nextSibling);
      for (; nextNode; ) {
        var node2 = nextNode;
        nextNode = nextNode.nextSibling;
        switch (node2.nodeName) {
          case "HTML":
          case "HEAD":
          case "BODY":
            clearContainerSparingly(node2);
            detachDeletedInstance(node2);
            continue;
          case "SCRIPT":
          case "STYLE":
            continue;
          case "LINK":
            if ("stylesheet" === node2.rel.toLowerCase()) continue;
        }
        container2.removeChild(node2);
      }
    }
    function canHydrateInstance(instance2, type, props, inRootOrSingleton) {
      for (; 1 === instance2.nodeType; ) {
        var anyProps = props;
        if (instance2.nodeName.toLowerCase() !== type.toLowerCase()) {
          if (!inRootOrSingleton && ("INPUT" !== instance2.nodeName || "hidden" !== instance2.type))
            break;
        } else if (!inRootOrSingleton)
          if ("input" === type && "hidden" === instance2.type) {
            checkAttributeStringCoercion(anyProps.name, "name");
            var name2 = null == anyProps.name ? null : "" + anyProps.name;
            if ("hidden" === anyProps.type && instance2.getAttribute("name") === name2)
              return instance2;
          } else return instance2;
        else if (!instance2[internalHoistableMarker])
          switch (type) {
            case "meta":
              if (!instance2.hasAttribute("itemprop")) break;
              return instance2;
            case "link":
              name2 = instance2.getAttribute("rel");
              if ("stylesheet" === name2 && instance2.hasAttribute("data-precedence"))
                break;
              else if (name2 !== anyProps.rel || instance2.getAttribute("href") !== (null == anyProps.href || "" === anyProps.href ? null : anyProps.href) || instance2.getAttribute("crossorigin") !== (null == anyProps.crossOrigin ? null : anyProps.crossOrigin) || instance2.getAttribute("title") !== (null == anyProps.title ? null : anyProps.title))
                break;
              return instance2;
            case "style":
              if (instance2.hasAttribute("data-precedence")) break;
              return instance2;
            case "script":
              name2 = instance2.getAttribute("src");
              if ((name2 !== (null == anyProps.src ? null : anyProps.src) || instance2.getAttribute("type") !== (null == anyProps.type ? null : anyProps.type) || instance2.getAttribute("crossorigin") !== (null == anyProps.crossOrigin ? null : anyProps.crossOrigin)) && name2 && instance2.hasAttribute("async") && !instance2.hasAttribute("itemprop"))
                break;
              return instance2;
            default:
              return instance2;
          }
        instance2 = getNextHydratable(instance2.nextSibling);
        if (null === instance2) break;
      }
      return null;
    }
    function canHydrateTextInstance(instance2, text2, inRootOrSingleton) {
      if ("" === text2) return null;
      for (; 3 !== instance2.nodeType; ) {
        if ((1 !== instance2.nodeType || "INPUT" !== instance2.nodeName || "hidden" !== instance2.type) && !inRootOrSingleton)
          return null;
        instance2 = getNextHydratable(instance2.nextSibling);
        if (null === instance2) return null;
      }
      return instance2;
    }
    function canHydrateHydrationBoundary(instance2, inRootOrSingleton) {
      for (; 8 !== instance2.nodeType; ) {
        if ((1 !== instance2.nodeType || "INPUT" !== instance2.nodeName || "hidden" !== instance2.type) && !inRootOrSingleton)
          return null;
        instance2 = getNextHydratable(instance2.nextSibling);
        if (null === instance2) return null;
      }
      return instance2;
    }
    function isSuspenseInstancePending(instance2) {
      return instance2.data === SUSPENSE_PENDING_START_DATA || instance2.data === SUSPENSE_QUEUED_START_DATA;
    }
    function isSuspenseInstanceFallback(instance2) {
      return instance2.data === SUSPENSE_FALLBACK_START_DATA || instance2.data === SUSPENSE_PENDING_START_DATA && instance2.ownerDocument.readyState !== DOCUMENT_READY_STATE_LOADING;
    }
    function registerSuspenseInstanceRetry(instance2, callback) {
      var ownerDocument = instance2.ownerDocument;
      if (instance2.data === SUSPENSE_QUEUED_START_DATA)
        instance2._reactRetry = callback;
      else if (instance2.data !== SUSPENSE_PENDING_START_DATA || ownerDocument.readyState !== DOCUMENT_READY_STATE_LOADING)
        callback();
      else {
        var listener = function() {
          callback();
          ownerDocument.removeEventListener("DOMContentLoaded", listener);
        };
        ownerDocument.addEventListener("DOMContentLoaded", listener);
        instance2._reactRetry = listener;
      }
    }
    function getNextHydratable(node2) {
      for (; null != node2; node2 = node2.nextSibling) {
        var nodeType = node2.nodeType;
        if (1 === nodeType || 3 === nodeType) break;
        if (8 === nodeType) {
          nodeType = node2.data;
          if (nodeType === SUSPENSE_START_DATA || nodeType === SUSPENSE_FALLBACK_START_DATA || nodeType === SUSPENSE_PENDING_START_DATA || nodeType === SUSPENSE_QUEUED_START_DATA || nodeType === ACTIVITY_START_DATA || nodeType === FORM_STATE_IS_MATCHING || nodeType === FORM_STATE_IS_NOT_MATCHING)
            break;
          if (nodeType === SUSPENSE_END_DATA || nodeType === ACTIVITY_END_DATA)
            return null;
        }
      }
      return node2;
    }
    function describeHydratableInstanceForDevWarnings(instance2) {
      if (1 === instance2.nodeType) {
        for (var JSCompiler_temp_const = instance2.nodeName.toLowerCase(), serverDifferences = {}, attributes = instance2.attributes, i2 = 0; i2 < attributes.length; i2++) {
          var attr = attributes[i2];
          serverDifferences[getPropNameFromAttributeName(attr.name)] = "style" === attr.name.toLowerCase() ? getStylesObjectFromElement(instance2) : attr.value;
        }
        return { type: JSCompiler_temp_const, props: serverDifferences };
      }
      return 8 === instance2.nodeType ? instance2.data === ACTIVITY_START_DATA ? { type: "Activity", props: {} } : { type: "Suspense", props: {} } : instance2.nodeValue;
    }
    function diffHydratedTextForDevWarnings(textInstance, text2, parentProps) {
      return null === parentProps || true !== parentProps[SUPPRESS_HYDRATION_WARNING] ? (textInstance.nodeValue === text2 ? textInstance = null : (text2 = normalizeMarkupForTextOrAttribute(text2), textInstance = normalizeMarkupForTextOrAttribute(textInstance.nodeValue) === text2 ? null : textInstance.nodeValue), textInstance) : null;
    }
    function getNextHydratableInstanceAfterHydrationBoundary(hydrationInstance) {
      hydrationInstance = hydrationInstance.nextSibling;
      for (var depth = 0; hydrationInstance; ) {
        if (8 === hydrationInstance.nodeType) {
          var data2 = hydrationInstance.data;
          if (data2 === SUSPENSE_END_DATA || data2 === ACTIVITY_END_DATA) {
            if (0 === depth)
              return getNextHydratable(hydrationInstance.nextSibling);
            depth--;
          } else
            data2 !== SUSPENSE_START_DATA && data2 !== SUSPENSE_FALLBACK_START_DATA && data2 !== SUSPENSE_PENDING_START_DATA && data2 !== SUSPENSE_QUEUED_START_DATA && data2 !== ACTIVITY_START_DATA || depth++;
        }
        hydrationInstance = hydrationInstance.nextSibling;
      }
      return null;
    }
    function getParentHydrationBoundary(targetInstance) {
      targetInstance = targetInstance.previousSibling;
      for (var depth = 0; targetInstance; ) {
        if (8 === targetInstance.nodeType) {
          var data2 = targetInstance.data;
          if (data2 === SUSPENSE_START_DATA || data2 === SUSPENSE_FALLBACK_START_DATA || data2 === SUSPENSE_PENDING_START_DATA || data2 === SUSPENSE_QUEUED_START_DATA || data2 === ACTIVITY_START_DATA) {
            if (0 === depth) return targetInstance;
            depth--;
          } else
            data2 !== SUSPENSE_END_DATA && data2 !== ACTIVITY_END_DATA || depth++;
        }
        targetInstance = targetInstance.previousSibling;
      }
      return null;
    }
    function commitHydratedContainer(container2) {
      retryIfBlockedOn(container2);
    }
    function commitHydratedActivityInstance(activityInstance) {
      retryIfBlockedOn(activityInstance);
    }
    function commitHydratedSuspenseInstance(suspenseInstance) {
      retryIfBlockedOn(suspenseInstance);
    }
    function resolveSingletonInstance(type, props, rootContainerInstance, hostContext, validateDOMNestingDev) {
      validateDOMNestingDev && validateDOMNesting(type, hostContext.ancestorInfo);
      props = getOwnerDocumentFromRootContainer(rootContainerInstance);
      switch (type) {
        case "html":
          type = props.documentElement;
          if (!type)
            throw Error(
              "React expected an <html> element (document.documentElement) to exist in the Document but one was not found. React never removes the documentElement for any Document it renders into so the cause is likely in some other script running on this page."
            );
          return type;
        case "head":
          type = props.head;
          if (!type)
            throw Error(
              "React expected a <head> element (document.head) to exist in the Document but one was not found. React never removes the head for any Document it renders into so the cause is likely in some other script running on this page."
            );
          return type;
        case "body":
          type = props.body;
          if (!type)
            throw Error(
              "React expected a <body> element (document.body) to exist in the Document but one was not found. React never removes the body for any Document it renders into so the cause is likely in some other script running on this page."
            );
          return type;
        default:
          throw Error(
            "resolveSingletonInstance was called with an element type that is not supported. This is a bug in React."
          );
      }
    }
    function acquireSingletonInstance(type, props, instance2, internalInstanceHandle) {
      if (!instance2[internalContainerInstanceKey] && getInstanceFromNode(instance2)) {
        var tagName = instance2.tagName.toLowerCase();
        console.error(
          "You are mounting a new %s component when a previous one has not first unmounted. It is an error to render more than one %s component at a time and attributes and children of these components will likely fail in unpredictable ways. Please only render a single instance of <%s> and if you need to mount a new one, ensure any previous ones have unmounted first.",
          tagName,
          tagName,
          tagName
        );
      }
      switch (type) {
        case "html":
        case "head":
        case "body":
          break;
        default:
          console.error(
            "acquireSingletonInstance was called with an element type that is not supported. This is a bug in React."
          );
      }
      for (tagName = instance2.attributes; tagName.length; )
        instance2.removeAttributeNode(tagName[0]);
      setInitialProperties(instance2, type, props);
      instance2[internalInstanceKey] = internalInstanceHandle;
      instance2[internalPropsKey] = props;
    }
    function releaseSingletonInstance(instance2) {
      for (var attributes = instance2.attributes; attributes.length; )
        instance2.removeAttributeNode(attributes[0]);
      detachDeletedInstance(instance2);
    }
    function getHoistableRoot(container2) {
      return "function" === typeof container2.getRootNode ? container2.getRootNode() : 9 === container2.nodeType ? container2 : container2.ownerDocument;
    }
    function preconnectAs(rel, href, crossOrigin) {
      var ownerDocument = globalDocument;
      if (ownerDocument && "string" === typeof href && href) {
        var limitedEscapedHref = escapeSelectorAttributeValueInsideDoubleQuotes(href);
        limitedEscapedHref = 'link[rel="' + rel + '"][href="' + limitedEscapedHref + '"]';
        "string" === typeof crossOrigin && (limitedEscapedHref += '[crossorigin="' + crossOrigin + '"]');
        preconnectsSet.has(limitedEscapedHref) || (preconnectsSet.add(limitedEscapedHref), rel = { rel, crossOrigin, href }, null === ownerDocument.querySelector(limitedEscapedHref) && (href = ownerDocument.createElement("link"), setInitialProperties(href, "link", rel), markNodeAsHoistable(href), ownerDocument.head.appendChild(href)));
      }
    }
    function getResource(type, currentProps, pendingProps, currentResource) {
      var resourceRoot = (resourceRoot = rootInstanceStackCursor.current) ? getHoistableRoot(resourceRoot) : null;
      if (!resourceRoot)
        throw Error(
          '"resourceRoot" was expected to exist. This is a bug in React.'
        );
      switch (type) {
        case "meta":
        case "title":
          return null;
        case "style":
          return "string" === typeof pendingProps.precedence && "string" === typeof pendingProps.href ? (pendingProps = getStyleKey(pendingProps.href), currentProps = getResourcesFromRoot(resourceRoot).hoistableStyles, currentResource = currentProps.get(pendingProps), currentResource || (currentResource = {
            type: "style",
            instance: null,
            count: 0,
            state: null
          }, currentProps.set(pendingProps, currentResource)), currentResource) : { type: "void", instance: null, count: 0, state: null };
        case "link":
          if ("stylesheet" === pendingProps.rel && "string" === typeof pendingProps.href && "string" === typeof pendingProps.precedence) {
            type = getStyleKey(pendingProps.href);
            var _styles = getResourcesFromRoot(resourceRoot).hoistableStyles, _resource = _styles.get(type);
            if (!_resource && (resourceRoot = resourceRoot.ownerDocument || resourceRoot, _resource = {
              type: "stylesheet",
              instance: null,
              count: 0,
              state: { loading: NotLoaded, preload: null }
            }, _styles.set(type, _resource), (_styles = resourceRoot.querySelector(
              getStylesheetSelectorFromKey(type)
            )) && !_styles._p && (_resource.instance = _styles, _resource.state.loading = Loaded | Inserted), !preloadPropsMap.has(type))) {
              var preloadProps = {
                rel: "preload",
                as: "style",
                href: pendingProps.href,
                crossOrigin: pendingProps.crossOrigin,
                integrity: pendingProps.integrity,
                media: pendingProps.media,
                hrefLang: pendingProps.hrefLang,
                referrerPolicy: pendingProps.referrerPolicy
              };
              preloadPropsMap.set(type, preloadProps);
              _styles || preloadStylesheet(
                resourceRoot,
                type,
                preloadProps,
                _resource.state
              );
            }
            if (currentProps && null === currentResource)
              throw pendingProps = "\n\n  - " + describeLinkForResourceErrorDEV(currentProps) + "\n  + " + describeLinkForResourceErrorDEV(pendingProps), Error(
                "Expected <link> not to update to be updated to a stylesheet with precedence. Check the `rel`, `href`, and `precedence` props of this component. Alternatively, check whether two different <link> components render in the same slot or share the same key." + pendingProps
              );
            return _resource;
          }
          if (currentProps && null !== currentResource)
            throw pendingProps = "\n\n  - " + describeLinkForResourceErrorDEV(currentProps) + "\n  + " + describeLinkForResourceErrorDEV(pendingProps), Error(
              "Expected stylesheet with precedence to not be updated to a different kind of <link>. Check the `rel`, `href`, and `precedence` props of this component. Alternatively, check whether two different <link> components render in the same slot or share the same key." + pendingProps
            );
          return null;
        case "script":
          return currentProps = pendingProps.async, pendingProps = pendingProps.src, "string" === typeof pendingProps && currentProps && "function" !== typeof currentProps && "symbol" !== typeof currentProps ? (pendingProps = getScriptKey(pendingProps), currentProps = getResourcesFromRoot(resourceRoot).hoistableScripts, currentResource = currentProps.get(pendingProps), currentResource || (currentResource = {
            type: "script",
            instance: null,
            count: 0,
            state: null
          }, currentProps.set(pendingProps, currentResource)), currentResource) : { type: "void", instance: null, count: 0, state: null };
        default:
          throw Error(
            'getResource encountered a type it did not expect: "' + type + '". this is a bug in React.'
          );
      }
    }
    function describeLinkForResourceErrorDEV(props) {
      var describedProps = 0, description2 = "<link";
      "string" === typeof props.rel ? (describedProps++, description2 += ' rel="' + props.rel + '"') : hasOwnProperty2.call(props, "rel") && (describedProps++, description2 += ' rel="' + (null === props.rel ? "null" : "invalid type " + typeof props.rel) + '"');
      "string" === typeof props.href ? (describedProps++, description2 += ' href="' + props.href + '"') : hasOwnProperty2.call(props, "href") && (describedProps++, description2 += ' href="' + (null === props.href ? "null" : "invalid type " + typeof props.href) + '"');
      "string" === typeof props.precedence ? (describedProps++, description2 += ' precedence="' + props.precedence + '"') : hasOwnProperty2.call(props, "precedence") && (describedProps++, description2 += " precedence={" + (null === props.precedence ? "null" : "invalid type " + typeof props.precedence) + "}");
      Object.getOwnPropertyNames(props).length > describedProps && (description2 += " ...");
      return description2 + " />";
    }
    function getStyleKey(href) {
      return 'href="' + escapeSelectorAttributeValueInsideDoubleQuotes(href) + '"';
    }
    function getStylesheetSelectorFromKey(key2) {
      return 'link[rel="stylesheet"][' + key2 + "]";
    }
    function stylesheetPropsFromRawProps(rawProps) {
      return assign2({}, rawProps, {
        "data-precedence": rawProps.precedence,
        precedence: null
      });
    }
    function preloadStylesheet(ownerDocument, key2, preloadProps, state) {
      ownerDocument.querySelector(
        'link[rel="preload"][as="style"][' + key2 + "]"
      ) ? state.loading = Loaded : (key2 = ownerDocument.createElement("link"), state.preload = key2, key2.addEventListener("load", function() {
        return state.loading |= Loaded;
      }), key2.addEventListener("error", function() {
        return state.loading |= Errored;
      }), setInitialProperties(key2, "link", preloadProps), markNodeAsHoistable(key2), ownerDocument.head.appendChild(key2));
    }
    function getScriptKey(src) {
      return '[src="' + escapeSelectorAttributeValueInsideDoubleQuotes(src) + '"]';
    }
    function getScriptSelectorFromKey(key2) {
      return "script[async]" + key2;
    }
    function acquireResource(hoistableRoot, resource, props) {
      resource.count++;
      if (null === resource.instance)
        switch (resource.type) {
          case "style":
            var instance2 = hoistableRoot.querySelector(
              'style[data-href~="' + escapeSelectorAttributeValueInsideDoubleQuotes(props.href) + '"]'
            );
            if (instance2)
              return resource.instance = instance2, markNodeAsHoistable(instance2), instance2;
            var styleProps = assign2({}, props, {
              "data-href": props.href,
              "data-precedence": props.precedence,
              href: null,
              precedence: null
            });
            instance2 = (hoistableRoot.ownerDocument || hoistableRoot).createElement("style");
            markNodeAsHoistable(instance2);
            setInitialProperties(instance2, "style", styleProps);
            insertStylesheet(instance2, props.precedence, hoistableRoot);
            return resource.instance = instance2;
          case "stylesheet":
            styleProps = getStyleKey(props.href);
            var _instance = hoistableRoot.querySelector(
              getStylesheetSelectorFromKey(styleProps)
            );
            if (_instance)
              return resource.state.loading |= Inserted, resource.instance = _instance, markNodeAsHoistable(_instance), _instance;
            instance2 = stylesheetPropsFromRawProps(props);
            (styleProps = preloadPropsMap.get(styleProps)) && adoptPreloadPropsForStylesheet(instance2, styleProps);
            _instance = (hoistableRoot.ownerDocument || hoistableRoot).createElement("link");
            markNodeAsHoistable(_instance);
            var linkInstance = _instance;
            linkInstance._p = new Promise(function(resolve2, reject) {
              linkInstance.onload = resolve2;
              linkInstance.onerror = reject;
            });
            setInitialProperties(_instance, "link", instance2);
            resource.state.loading |= Inserted;
            insertStylesheet(_instance, props.precedence, hoistableRoot);
            return resource.instance = _instance;
          case "script":
            _instance = getScriptKey(props.src);
            if (styleProps = hoistableRoot.querySelector(
              getScriptSelectorFromKey(_instance)
            ))
              return resource.instance = styleProps, markNodeAsHoistable(styleProps), styleProps;
            instance2 = props;
            if (styleProps = preloadPropsMap.get(_instance))
              instance2 = assign2({}, props), adoptPreloadPropsForScript(instance2, styleProps);
            hoistableRoot = hoistableRoot.ownerDocument || hoistableRoot;
            styleProps = hoistableRoot.createElement("script");
            markNodeAsHoistable(styleProps);
            setInitialProperties(styleProps, "link", instance2);
            hoistableRoot.head.appendChild(styleProps);
            return resource.instance = styleProps;
          case "void":
            return null;
          default:
            throw Error(
              'acquireResource encountered a resource type it did not expect: "' + resource.type + '". this is a bug in React.'
            );
        }
      else
        "stylesheet" === resource.type && (resource.state.loading & Inserted) === NotLoaded && (instance2 = resource.instance, resource.state.loading |= Inserted, insertStylesheet(instance2, props.precedence, hoistableRoot));
      return resource.instance;
    }
    function insertStylesheet(instance2, precedence, root22) {
      for (var nodes = root22.querySelectorAll(
        'link[rel="stylesheet"][data-precedence],style[data-precedence]'
      ), last2 = nodes.length ? nodes[nodes.length - 1] : null, prior = last2, i2 = 0; i2 < nodes.length; i2++) {
        var node2 = nodes[i2];
        if (node2.dataset.precedence === precedence) prior = node2;
        else if (prior !== last2) break;
      }
      prior ? prior.parentNode.insertBefore(instance2, prior.nextSibling) : (precedence = 9 === root22.nodeType ? root22.head : root22, precedence.insertBefore(instance2, precedence.firstChild));
    }
    function adoptPreloadPropsForStylesheet(stylesheetProps, preloadProps) {
      null == stylesheetProps.crossOrigin && (stylesheetProps.crossOrigin = preloadProps.crossOrigin);
      null == stylesheetProps.referrerPolicy && (stylesheetProps.referrerPolicy = preloadProps.referrerPolicy);
      null == stylesheetProps.title && (stylesheetProps.title = preloadProps.title);
    }
    function adoptPreloadPropsForScript(scriptProps, preloadProps) {
      null == scriptProps.crossOrigin && (scriptProps.crossOrigin = preloadProps.crossOrigin);
      null == scriptProps.referrerPolicy && (scriptProps.referrerPolicy = preloadProps.referrerPolicy);
      null == scriptProps.integrity && (scriptProps.integrity = preloadProps.integrity);
    }
    function getHydratableHoistableCache(type, keyAttribute, ownerDocument) {
      if (null === tagCaches) {
        var cache = /* @__PURE__ */ new Map();
        var caches = tagCaches = /* @__PURE__ */ new Map();
        caches.set(ownerDocument, cache);
      } else
        caches = tagCaches, cache = caches.get(ownerDocument), cache || (cache = /* @__PURE__ */ new Map(), caches.set(ownerDocument, cache));
      if (cache.has(type)) return cache;
      cache.set(type, null);
      ownerDocument = ownerDocument.getElementsByTagName(type);
      for (caches = 0; caches < ownerDocument.length; caches++) {
        var node2 = ownerDocument[caches];
        if (!(node2[internalHoistableMarker] || node2[internalInstanceKey] || "link" === type && "stylesheet" === node2.getAttribute("rel")) && node2.namespaceURI !== SVG_NAMESPACE) {
          var nodeKey = node2.getAttribute(keyAttribute) || "";
          nodeKey = type + nodeKey;
          var existing = cache.get(nodeKey);
          existing ? existing.push(node2) : cache.set(nodeKey, [node2]);
        }
      }
      return cache;
    }
    function mountHoistable(hoistableRoot, type, instance2) {
      hoistableRoot = hoistableRoot.ownerDocument || hoistableRoot;
      hoistableRoot.head.insertBefore(
        instance2,
        "title" === type ? hoistableRoot.querySelector("head > title") : null
      );
    }
    function isHostHoistableType(type, props, hostContext) {
      var outsideHostContainerContext = !hostContext.ancestorInfo.containerTagInScope;
      if (hostContext.context === HostContextNamespaceSvg || null != props.itemProp)
        return !outsideHostContainerContext || null == props.itemProp || "meta" !== type && "title" !== type && "style" !== type && "link" !== type && "script" !== type || console.error(
          "Cannot render a <%s> outside the main document if it has an `itemProp` prop. `itemProp` suggests the tag belongs to an `itemScope` which can appear anywhere in the DOM. If you were intending for React to hoist this <%s> remove the `itemProp` prop. Otherwise, try moving this tag into the <head> or <body> of the Document.",
          type,
          type
        ), false;
      switch (type) {
        case "meta":
        case "title":
          return true;
        case "style":
          if ("string" !== typeof props.precedence || "string" !== typeof props.href || "" === props.href) {
            outsideHostContainerContext && console.error(
              'Cannot render a <style> outside the main document without knowing its precedence and a unique href key. React can hoist and deduplicate <style> tags if you provide a `precedence` prop along with an `href` prop that does not conflict with the `href` values used in any other hoisted <style> or <link rel="stylesheet" ...> tags.  Note that hoisting <style> tags is considered an advanced feature that most will not use directly. Consider moving the <style> tag to the <head> or consider adding a `precedence="default"` and `href="some unique resource identifier"`.'
            );
            break;
          }
          return true;
        case "link":
          if ("string" !== typeof props.rel || "string" !== typeof props.href || "" === props.href || props.onLoad || props.onError) {
            if ("stylesheet" === props.rel && "string" === typeof props.precedence) {
              type = props.href;
              var onError = props.onError, disabled2 = props.disabled;
              hostContext = [];
              props.onLoad && hostContext.push("`onLoad`");
              onError && hostContext.push("`onError`");
              null != disabled2 && hostContext.push("`disabled`");
              onError = propNamesListJoin(hostContext, "and");
              onError += 1 === hostContext.length ? " prop" : " props";
              disabled2 = 1 === hostContext.length ? "an " + onError : "the " + onError;
              hostContext.length && console.error(
                'React encountered a <link rel="stylesheet" href="%s" ... /> with a `precedence` prop that also included %s. The presence of loading and error handlers indicates an intent to manage the stylesheet loading state from your from your Component code and React will not hoist or deduplicate this stylesheet. If your intent was to have React hoist and deduplciate this stylesheet using the `precedence` prop remove the %s, otherwise remove the `precedence` prop.',
                type,
                disabled2,
                onError
              );
            }
            outsideHostContainerContext && ("string" !== typeof props.rel || "string" !== typeof props.href || "" === props.href ? console.error(
              "Cannot render a <link> outside the main document without a `rel` and `href` prop. Try adding a `rel` and/or `href` prop to this <link> or moving the link into the <head> tag"
            ) : (props.onError || props.onLoad) && console.error(
              "Cannot render a <link> with onLoad or onError listeners outside the main document. Try removing onLoad={...} and onError={...} or moving it into the root <head> tag or somewhere in the <body>."
            ));
            break;
          }
          switch (props.rel) {
            case "stylesheet":
              return type = props.precedence, props = props.disabled, "string" !== typeof type && outsideHostContainerContext && console.error(
                'Cannot render a <link rel="stylesheet" /> outside the main document without knowing its precedence. Consider adding precedence="default" or moving it into the root <head> tag.'
              ), "string" === typeof type && null == props;
            default:
              return true;
          }
        case "script":
          type = props.async && "function" !== typeof props.async && "symbol" !== typeof props.async;
          if (!type || props.onLoad || props.onError || !props.src || "string" !== typeof props.src) {
            outsideHostContainerContext && (type ? props.onLoad || props.onError ? console.error(
              "Cannot render a <script> with onLoad or onError listeners outside the main document. Try removing onLoad={...} and onError={...} or moving it into the root <head> tag or somewhere in the <body>."
            ) : console.error(
              "Cannot render a <script> outside the main document without `async={true}` and a non-empty `src` prop. Ensure there is a valid `src` and either make the script async or move it into the root <head> tag or somewhere in the <body>."
            ) : console.error(
              'Cannot render a sync or defer <script> outside the main document without knowing its order. Try adding async="" or moving it into the root <head> tag.'
            ));
            break;
          }
          return true;
        case "noscript":
        case "template":
          outsideHostContainerContext && console.error(
            "Cannot render <%s> outside the main document. Try moving it into the root <head> tag.",
            type
          );
      }
      return false;
    }
    function preloadResource(resource) {
      return "stylesheet" === resource.type && (resource.state.loading & Settled) === NotLoaded ? false : true;
    }
    function suspendResource(state, hoistableRoot, resource, props) {
      if ("stylesheet" === resource.type && ("string" !== typeof props.media || false !== matchMedia(props.media).matches) && (resource.state.loading & Inserted) === NotLoaded) {
        if (null === resource.instance) {
          var key2 = getStyleKey(props.href), instance2 = hoistableRoot.querySelector(
            getStylesheetSelectorFromKey(key2)
          );
          if (instance2) {
            hoistableRoot = instance2._p;
            null !== hoistableRoot && "object" === typeof hoistableRoot && "function" === typeof hoistableRoot.then && (state.count++, state = onUnsuspend.bind(state), hoistableRoot.then(state, state));
            resource.state.loading |= Inserted;
            resource.instance = instance2;
            markNodeAsHoistable(instance2);
            return;
          }
          instance2 = hoistableRoot.ownerDocument || hoistableRoot;
          props = stylesheetPropsFromRawProps(props);
          (key2 = preloadPropsMap.get(key2)) && adoptPreloadPropsForStylesheet(props, key2);
          instance2 = instance2.createElement("link");
          markNodeAsHoistable(instance2);
          var linkInstance = instance2;
          linkInstance._p = new Promise(function(resolve2, reject) {
            linkInstance.onload = resolve2;
            linkInstance.onerror = reject;
          });
          setInitialProperties(instance2, "link", props);
          resource.instance = instance2;
        }
        null === state.stylesheets && (state.stylesheets = /* @__PURE__ */ new Map());
        state.stylesheets.set(resource, hoistableRoot);
        (hoistableRoot = resource.state.preload) && (resource.state.loading & Settled) === NotLoaded && (state.count++, resource = onUnsuspend.bind(state), hoistableRoot.addEventListener("load", resource), hoistableRoot.addEventListener("error", resource));
      }
    }
    function waitForCommitToBeReady(state, timeoutOffset) {
      state.stylesheets && 0 === state.count && insertSuspendedStylesheets(state, state.stylesheets);
      return 0 < state.count || 0 < state.imgCount ? function(commit) {
        var stylesheetTimer = setTimeout(function() {
          state.stylesheets && insertSuspendedStylesheets(state, state.stylesheets);
          if (state.unsuspend) {
            var unsuspend = state.unsuspend;
            state.unsuspend = null;
            unsuspend();
          }
        }, SUSPENSEY_STYLESHEET_TIMEOUT + timeoutOffset);
        0 < state.imgBytes && 0 === estimatedBytesWithinLimit && (estimatedBytesWithinLimit = 125 * estimateBandwidth() * SUSPENSEY_IMAGE_TIME_ESTIMATE);
        var imgTimer = setTimeout(
          function() {
            state.waitingForImages = false;
            if (0 === state.count && (state.stylesheets && insertSuspendedStylesheets(state, state.stylesheets), state.unsuspend)) {
              var unsuspend = state.unsuspend;
              state.unsuspend = null;
              unsuspend();
            }
          },
          (state.imgBytes > estimatedBytesWithinLimit ? 50 : SUSPENSEY_IMAGE_TIMEOUT) + timeoutOffset
        );
        state.unsuspend = commit;
        return function() {
          state.unsuspend = null;
          clearTimeout(stylesheetTimer);
          clearTimeout(imgTimer);
        };
      } : null;
    }
    function onUnsuspend() {
      this.count--;
      if (0 === this.count && (0 === this.imgCount || !this.waitingForImages)) {
        if (this.stylesheets)
          insertSuspendedStylesheets(this, this.stylesheets);
        else if (this.unsuspend) {
          var unsuspend = this.unsuspend;
          this.unsuspend = null;
          unsuspend();
        }
      }
    }
    function insertSuspendedStylesheets(state, resources) {
      state.stylesheets = null;
      null !== state.unsuspend && (state.count++, precedencesByRoot = /* @__PURE__ */ new Map(), resources.forEach(insertStylesheetIntoRoot, state), precedencesByRoot = null, onUnsuspend.call(state));
    }
    function insertStylesheetIntoRoot(root22, resource) {
      if (!(resource.state.loading & Inserted)) {
        var precedences = precedencesByRoot.get(root22);
        if (precedences) var last2 = precedences.get(LAST_PRECEDENCE);
        else {
          precedences = /* @__PURE__ */ new Map();
          precedencesByRoot.set(root22, precedences);
          for (var nodes = root22.querySelectorAll(
            "link[data-precedence],style[data-precedence]"
          ), i2 = 0; i2 < nodes.length; i2++) {
            var node2 = nodes[i2];
            if ("LINK" === node2.nodeName || "not all" !== node2.getAttribute("media"))
              precedences.set(node2.dataset.precedence, node2), last2 = node2;
          }
          last2 && precedences.set(LAST_PRECEDENCE, last2);
        }
        nodes = resource.instance;
        node2 = nodes.getAttribute("data-precedence");
        i2 = precedences.get(node2) || last2;
        i2 === last2 && precedences.set(LAST_PRECEDENCE, nodes);
        precedences.set(node2, nodes);
        this.count++;
        last2 = onUnsuspend.bind(this);
        nodes.addEventListener("load", last2);
        nodes.addEventListener("error", last2);
        i2 ? i2.parentNode.insertBefore(nodes, i2.nextSibling) : (root22 = 9 === root22.nodeType ? root22.head : root22, root22.insertBefore(nodes, root22.firstChild));
        resource.state.loading |= Inserted;
      }
    }
    function FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onUncaughtError, onCaughtError, onRecoverableError, onDefaultTransitionIndicator, formState) {
      this.tag = 1;
      this.containerInfo = containerInfo;
      this.pingCache = this.current = this.pendingChildren = null;
      this.timeoutHandle = noTimeout;
      this.callbackNode = this.next = this.pendingContext = this.context = this.cancelPendingCommit = null;
      this.callbackPriority = 0;
      this.expirationTimes = createLaneMap(-1);
      this.entangledLanes = this.shellSuspendCounter = this.errorRecoveryDisabledLanes = this.expiredLanes = this.warmLanes = this.pingedLanes = this.suspendedLanes = this.pendingLanes = 0;
      this.entanglements = createLaneMap(0);
      this.hiddenUpdates = createLaneMap(null);
      this.identifierPrefix = identifierPrefix;
      this.onUncaughtError = onUncaughtError;
      this.onCaughtError = onCaughtError;
      this.onRecoverableError = onRecoverableError;
      this.pooledCache = null;
      this.pooledCacheLanes = 0;
      this.formState = formState;
      this.incompleteTransitions = /* @__PURE__ */ new Map();
      this.passiveEffectDuration = this.effectDuration = -0;
      this.memoizedUpdaters = /* @__PURE__ */ new Set();
      containerInfo = this.pendingUpdatersLaneMap = [];
      for (tag = 0; 31 > tag; tag++) containerInfo.push(/* @__PURE__ */ new Set());
      this._debugRootType = hydrate ? "hydrateRoot()" : "createRoot()";
    }
    function createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, identifierPrefix, formState, onUncaughtError, onCaughtError, onRecoverableError, onDefaultTransitionIndicator) {
      containerInfo = new FiberRootNode(
        containerInfo,
        tag,
        hydrate,
        identifierPrefix,
        onUncaughtError,
        onCaughtError,
        onRecoverableError,
        onDefaultTransitionIndicator,
        formState
      );
      tag = ConcurrentMode;
      true === isStrictMode && (tag |= StrictLegacyMode | StrictEffectsMode);
      tag |= ProfileMode;
      isStrictMode = createFiber(3, null, null, tag);
      containerInfo.current = isStrictMode;
      isStrictMode.stateNode = containerInfo;
      tag = createCache();
      retainCache(tag);
      containerInfo.pooledCache = tag;
      retainCache(tag);
      isStrictMode.memoizedState = {
        element: initialChildren,
        isDehydrated: hydrate,
        cache: tag
      };
      initializeUpdateQueue(isStrictMode);
      return containerInfo;
    }
    function getContextForSubtree(parentComponent) {
      if (!parentComponent) return emptyContextObject;
      parentComponent = emptyContextObject;
      return parentComponent;
    }
    function updateContainerImpl(rootFiber, lane, element, container2, parentComponent, callback) {
      if (injectedHook && "function" === typeof injectedHook.onScheduleFiberRoot)
        try {
          injectedHook.onScheduleFiberRoot(rendererID, container2, element);
        } catch (err) {
          hasLoggedError || (hasLoggedError = true, console.error(
            "React instrumentation encountered an error: %o",
            err
          ));
        }
      parentComponent = getContextForSubtree(parentComponent);
      null === container2.context ? container2.context = parentComponent : container2.pendingContext = parentComponent;
      isRendering && null !== current3 && !didWarnAboutNestedUpdates && (didWarnAboutNestedUpdates = true, console.error(
        "Render methods should be a pure function of props and state; triggering nested component updates from render is not allowed. If necessary, trigger nested updates in componentDidUpdate.\n\nCheck the render method of %s.",
        getComponentNameFromFiber(current3) || "Unknown"
      ));
      container2 = createUpdate(lane);
      container2.payload = { element };
      callback = void 0 === callback ? null : callback;
      null !== callback && ("function" !== typeof callback && console.error(
        "Expected the last optional `callback` argument to be a function. Instead received: %s.",
        callback
      ), container2.callback = callback);
      element = enqueueUpdate(rootFiber, container2, lane);
      null !== element && (startUpdateTimerByLane(lane, "root.render()", null), scheduleUpdateOnFiber(element, rootFiber, lane), entangleTransitions(element, rootFiber, lane));
    }
    function markRetryLaneImpl(fiber, retryLane) {
      fiber = fiber.memoizedState;
      if (null !== fiber && null !== fiber.dehydrated) {
        var a2 = fiber.retryLane;
        fiber.retryLane = 0 !== a2 && a2 < retryLane ? a2 : retryLane;
      }
    }
    function markRetryLaneIfNotHydrated(fiber, retryLane) {
      markRetryLaneImpl(fiber, retryLane);
      (fiber = fiber.alternate) && markRetryLaneImpl(fiber, retryLane);
    }
    function attemptContinuousHydration(fiber) {
      if (13 === fiber.tag || 31 === fiber.tag) {
        var root22 = enqueueConcurrentRenderForLane(fiber, 67108864);
        null !== root22 && scheduleUpdateOnFiber(root22, fiber, 67108864);
        markRetryLaneIfNotHydrated(fiber, 67108864);
      }
    }
    function attemptHydrationAtCurrentPriority(fiber) {
      if (13 === fiber.tag || 31 === fiber.tag) {
        var lane = requestUpdateLane(fiber);
        lane = getBumpedLaneForHydrationByLane(lane);
        var root22 = enqueueConcurrentRenderForLane(fiber, lane);
        null !== root22 && scheduleUpdateOnFiber(root22, fiber, lane);
        markRetryLaneIfNotHydrated(fiber, lane);
      }
    }
    function getCurrentFiberForDevTools() {
      return current3;
    }
    function dispatchDiscreteEvent(domEventName, eventSystemFlags, container2, nativeEvent) {
      var prevTransition = ReactSharedInternals.T;
      ReactSharedInternals.T = null;
      var previousPriority = ReactDOMSharedInternals.p;
      try {
        ReactDOMSharedInternals.p = DiscreteEventPriority, dispatchEvent2(domEventName, eventSystemFlags, container2, nativeEvent);
      } finally {
        ReactDOMSharedInternals.p = previousPriority, ReactSharedInternals.T = prevTransition;
      }
    }
    function dispatchContinuousEvent(domEventName, eventSystemFlags, container2, nativeEvent) {
      var prevTransition = ReactSharedInternals.T;
      ReactSharedInternals.T = null;
      var previousPriority = ReactDOMSharedInternals.p;
      try {
        ReactDOMSharedInternals.p = ContinuousEventPriority, dispatchEvent2(domEventName, eventSystemFlags, container2, nativeEvent);
      } finally {
        ReactDOMSharedInternals.p = previousPriority, ReactSharedInternals.T = prevTransition;
      }
    }
    function dispatchEvent2(domEventName, eventSystemFlags, targetContainer, nativeEvent) {
      if (_enabled) {
        var blockedOn = findInstanceBlockingEvent(nativeEvent);
        if (null === blockedOn)
          dispatchEventForPluginEventSystem(
            domEventName,
            eventSystemFlags,
            nativeEvent,
            return_targetInst,
            targetContainer
          ), clearIfContinuousEvent(domEventName, nativeEvent);
        else if (queueIfContinuousEvent(
          blockedOn,
          domEventName,
          eventSystemFlags,
          targetContainer,
          nativeEvent
        ))
          nativeEvent.stopPropagation();
        else if (clearIfContinuousEvent(domEventName, nativeEvent), eventSystemFlags & 4 && -1 < discreteReplayableEvents.indexOf(domEventName)) {
          for (; null !== blockedOn; ) {
            var fiber = getInstanceFromNode(blockedOn);
            if (null !== fiber)
              switch (fiber.tag) {
                case 3:
                  fiber = fiber.stateNode;
                  if (fiber.current.memoizedState.isDehydrated) {
                    var lanes = getHighestPriorityLanes(fiber.pendingLanes);
                    if (0 !== lanes) {
                      var root22 = fiber;
                      root22.pendingLanes |= 2;
                      for (root22.entangledLanes |= 2; lanes; ) {
                        var lane = 1 << 31 - clz322(lanes);
                        root22.entanglements[1] |= lane;
                        lanes &= ~lane;
                      }
                      ensureRootIsScheduled(fiber);
                      (executionContext & (RenderContext | CommitContext)) === NoContext && (workInProgressRootRenderTargetTime = now$1() + RENDER_TIMEOUT_MS, flushSyncWorkAcrossRoots_impl(0));
                    }
                  }
                  break;
                case 31:
                case 13:
                  root22 = enqueueConcurrentRenderForLane(fiber, 2), null !== root22 && scheduleUpdateOnFiber(root22, fiber, 2), flushSyncWork$1(), markRetryLaneIfNotHydrated(fiber, 2);
              }
            fiber = findInstanceBlockingEvent(nativeEvent);
            null === fiber && dispatchEventForPluginEventSystem(
              domEventName,
              eventSystemFlags,
              nativeEvent,
              return_targetInst,
              targetContainer
            );
            if (fiber === blockedOn) break;
            blockedOn = fiber;
          }
          null !== blockedOn && nativeEvent.stopPropagation();
        } else
          dispatchEventForPluginEventSystem(
            domEventName,
            eventSystemFlags,
            nativeEvent,
            null,
            targetContainer
          );
      }
    }
    function findInstanceBlockingEvent(nativeEvent) {
      nativeEvent = getEventTarget(nativeEvent);
      return findInstanceBlockingTarget(nativeEvent);
    }
    function findInstanceBlockingTarget(targetNode) {
      return_targetInst = null;
      targetNode = getClosestInstanceFromNode(targetNode);
      if (null !== targetNode) {
        var nearestMounted = getNearestMountedFiber(targetNode);
        if (null === nearestMounted) targetNode = null;
        else {
          var tag = nearestMounted.tag;
          if (13 === tag) {
            targetNode = getSuspenseInstanceFromFiber(nearestMounted);
            if (null !== targetNode) return targetNode;
            targetNode = null;
          } else if (31 === tag) {
            targetNode = getActivityInstanceFromFiber(nearestMounted);
            if (null !== targetNode) return targetNode;
            targetNode = null;
          } else if (3 === tag) {
            if (nearestMounted.stateNode.current.memoizedState.isDehydrated)
              return 3 === nearestMounted.tag ? nearestMounted.stateNode.containerInfo : null;
            targetNode = null;
          } else nearestMounted !== targetNode && (targetNode = null);
        }
      }
      return_targetInst = targetNode;
      return null;
    }
    function getEventPriority(domEventName) {
      switch (domEventName) {
        case "beforetoggle":
        case "cancel":
        case "click":
        case "close":
        case "contextmenu":
        case "copy":
        case "cut":
        case "auxclick":
        case "dblclick":
        case "dragend":
        case "dragstart":
        case "drop":
        case "focusin":
        case "focusout":
        case "input":
        case "invalid":
        case "keydown":
        case "keypress":
        case "keyup":
        case "mousedown":
        case "mouseup":
        case "paste":
        case "pause":
        case "play":
        case "pointercancel":
        case "pointerdown":
        case "pointerup":
        case "ratechange":
        case "reset":
        case "resize":
        case "seeked":
        case "submit":
        case "toggle":
        case "touchcancel":
        case "touchend":
        case "touchstart":
        case "volumechange":
        case "change":
        case "selectionchange":
        case "textInput":
        case "compositionstart":
        case "compositionend":
        case "compositionupdate":
        case "beforeblur":
        case "afterblur":
        case "beforeinput":
        case "blur":
        case "fullscreenchange":
        case "focus":
        case "hashchange":
        case "popstate":
        case "select":
        case "selectstart":
          return DiscreteEventPriority;
        case "drag":
        case "dragenter":
        case "dragexit":
        case "dragleave":
        case "dragover":
        case "mousemove":
        case "mouseout":
        case "mouseover":
        case "pointermove":
        case "pointerout":
        case "pointerover":
        case "scroll":
        case "touchmove":
        case "wheel":
        case "mouseenter":
        case "mouseleave":
        case "pointerenter":
        case "pointerleave":
          return ContinuousEventPriority;
        case "message":
          switch (getCurrentPriorityLevel()) {
            case ImmediatePriority:
              return DiscreteEventPriority;
            case UserBlockingPriority:
              return ContinuousEventPriority;
            case NormalPriority$1:
            case LowPriority:
              return DefaultEventPriority;
            case IdlePriority:
              return IdleEventPriority;
            default:
              return DefaultEventPriority;
          }
        default:
          return DefaultEventPriority;
      }
    }
    function clearIfContinuousEvent(domEventName, nativeEvent) {
      switch (domEventName) {
        case "focusin":
        case "focusout":
          queuedFocus = null;
          break;
        case "dragenter":
        case "dragleave":
          queuedDrag = null;
          break;
        case "mouseover":
        case "mouseout":
          queuedMouse = null;
          break;
        case "pointerover":
        case "pointerout":
          queuedPointers.delete(nativeEvent.pointerId);
          break;
        case "gotpointercapture":
        case "lostpointercapture":
          queuedPointerCaptures.delete(nativeEvent.pointerId);
      }
    }
    function accumulateOrCreateContinuousQueuedReplayableEvent(existingQueuedEvent, blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
      if (null === existingQueuedEvent || existingQueuedEvent.nativeEvent !== nativeEvent)
        return existingQueuedEvent = {
          blockedOn,
          domEventName,
          eventSystemFlags,
          nativeEvent,
          targetContainers: [targetContainer]
        }, null !== blockedOn && (blockedOn = getInstanceFromNode(blockedOn), null !== blockedOn && attemptContinuousHydration(blockedOn)), existingQueuedEvent;
      existingQueuedEvent.eventSystemFlags |= eventSystemFlags;
      blockedOn = existingQueuedEvent.targetContainers;
      null !== targetContainer && -1 === blockedOn.indexOf(targetContainer) && blockedOn.push(targetContainer);
      return existingQueuedEvent;
    }
    function queueIfContinuousEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
      switch (domEventName) {
        case "focusin":
          return queuedFocus = accumulateOrCreateContinuousQueuedReplayableEvent(
            queuedFocus,
            blockedOn,
            domEventName,
            eventSystemFlags,
            targetContainer,
            nativeEvent
          ), true;
        case "dragenter":
          return queuedDrag = accumulateOrCreateContinuousQueuedReplayableEvent(
            queuedDrag,
            blockedOn,
            domEventName,
            eventSystemFlags,
            targetContainer,
            nativeEvent
          ), true;
        case "mouseover":
          return queuedMouse = accumulateOrCreateContinuousQueuedReplayableEvent(
            queuedMouse,
            blockedOn,
            domEventName,
            eventSystemFlags,
            targetContainer,
            nativeEvent
          ), true;
        case "pointerover":
          var pointerId = nativeEvent.pointerId;
          queuedPointers.set(
            pointerId,
            accumulateOrCreateContinuousQueuedReplayableEvent(
              queuedPointers.get(pointerId) || null,
              blockedOn,
              domEventName,
              eventSystemFlags,
              targetContainer,
              nativeEvent
            )
          );
          return true;
        case "gotpointercapture":
          return pointerId = nativeEvent.pointerId, queuedPointerCaptures.set(
            pointerId,
            accumulateOrCreateContinuousQueuedReplayableEvent(
              queuedPointerCaptures.get(pointerId) || null,
              blockedOn,
              domEventName,
              eventSystemFlags,
              targetContainer,
              nativeEvent
            )
          ), true;
      }
      return false;
    }
    function attemptExplicitHydrationTarget(queuedTarget) {
      var targetInst = getClosestInstanceFromNode(queuedTarget.target);
      if (null !== targetInst) {
        var nearestMounted = getNearestMountedFiber(targetInst);
        if (null !== nearestMounted) {
          if (targetInst = nearestMounted.tag, 13 === targetInst) {
            if (targetInst = getSuspenseInstanceFromFiber(nearestMounted), null !== targetInst) {
              queuedTarget.blockedOn = targetInst;
              runWithPriority(queuedTarget.priority, function() {
                attemptHydrationAtCurrentPriority(nearestMounted);
              });
              return;
            }
          } else if (31 === targetInst) {
            if (targetInst = getActivityInstanceFromFiber(nearestMounted), null !== targetInst) {
              queuedTarget.blockedOn = targetInst;
              runWithPriority(queuedTarget.priority, function() {
                attemptHydrationAtCurrentPriority(nearestMounted);
              });
              return;
            }
          } else if (3 === targetInst && nearestMounted.stateNode.current.memoizedState.isDehydrated) {
            queuedTarget.blockedOn = 3 === nearestMounted.tag ? nearestMounted.stateNode.containerInfo : null;
            return;
          }
        }
      }
      queuedTarget.blockedOn = null;
    }
    function attemptReplayContinuousQueuedEvent(queuedEvent) {
      if (null !== queuedEvent.blockedOn) return false;
      for (var targetContainers = queuedEvent.targetContainers; 0 < targetContainers.length; ) {
        var nextBlockedOn = findInstanceBlockingEvent(queuedEvent.nativeEvent);
        if (null === nextBlockedOn) {
          nextBlockedOn = queuedEvent.nativeEvent;
          var nativeEventClone = new nextBlockedOn.constructor(
            nextBlockedOn.type,
            nextBlockedOn
          ), event = nativeEventClone;
          null !== currentReplayingEvent && console.error(
            "Expected currently replaying event to be null. This error is likely caused by a bug in React. Please file an issue."
          );
          currentReplayingEvent = event;
          nextBlockedOn.target.dispatchEvent(nativeEventClone);
          null === currentReplayingEvent && console.error(
            "Expected currently replaying event to not be null. This error is likely caused by a bug in React. Please file an issue."
          );
          currentReplayingEvent = null;
        } else
          return targetContainers = getInstanceFromNode(nextBlockedOn), null !== targetContainers && attemptContinuousHydration(targetContainers), queuedEvent.blockedOn = nextBlockedOn, false;
        targetContainers.shift();
      }
      return true;
    }
    function attemptReplayContinuousQueuedEventInMap(queuedEvent, key2, map2) {
      attemptReplayContinuousQueuedEvent(queuedEvent) && map2.delete(key2);
    }
    function replayUnblockedEvents() {
      hasScheduledReplayAttempt = false;
      null !== queuedFocus && attemptReplayContinuousQueuedEvent(queuedFocus) && (queuedFocus = null);
      null !== queuedDrag && attemptReplayContinuousQueuedEvent(queuedDrag) && (queuedDrag = null);
      null !== queuedMouse && attemptReplayContinuousQueuedEvent(queuedMouse) && (queuedMouse = null);
      queuedPointers.forEach(attemptReplayContinuousQueuedEventInMap);
      queuedPointerCaptures.forEach(attemptReplayContinuousQueuedEventInMap);
    }
    function scheduleCallbackIfUnblocked(queuedEvent, unblocked) {
      queuedEvent.blockedOn === unblocked && (queuedEvent.blockedOn = null, hasScheduledReplayAttempt || (hasScheduledReplayAttempt = true, Scheduler.unstable_scheduleCallback(
        Scheduler.unstable_NormalPriority,
        replayUnblockedEvents
      )));
    }
    function scheduleReplayQueueIfNeeded(formReplayingQueue) {
      lastScheduledReplayQueue !== formReplayingQueue && (lastScheduledReplayQueue = formReplayingQueue, Scheduler.unstable_scheduleCallback(
        Scheduler.unstable_NormalPriority,
        function() {
          lastScheduledReplayQueue === formReplayingQueue && (lastScheduledReplayQueue = null);
          for (var i2 = 0; i2 < formReplayingQueue.length; i2 += 3) {
            var form = formReplayingQueue[i2], submitterOrAction = formReplayingQueue[i2 + 1], formData = formReplayingQueue[i2 + 2];
            if ("function" !== typeof submitterOrAction)
              if (null === findInstanceBlockingTarget(submitterOrAction || form))
                continue;
              else break;
            var formInst = getInstanceFromNode(form);
            null !== formInst && (formReplayingQueue.splice(i2, 3), i2 -= 3, form = {
              pending: true,
              data: formData,
              method: form.method,
              action: submitterOrAction
            }, Object.freeze(form), startHostTransition(
              formInst,
              form,
              submitterOrAction,
              formData
            ));
          }
        }
      ));
    }
    function retryIfBlockedOn(unblocked) {
      function unblock(queuedEvent) {
        return scheduleCallbackIfUnblocked(queuedEvent, unblocked);
      }
      null !== queuedFocus && scheduleCallbackIfUnblocked(queuedFocus, unblocked);
      null !== queuedDrag && scheduleCallbackIfUnblocked(queuedDrag, unblocked);
      null !== queuedMouse && scheduleCallbackIfUnblocked(queuedMouse, unblocked);
      queuedPointers.forEach(unblock);
      queuedPointerCaptures.forEach(unblock);
      for (var i2 = 0; i2 < queuedExplicitHydrationTargets.length; i2++) {
        var queuedTarget = queuedExplicitHydrationTargets[i2];
        queuedTarget.blockedOn === unblocked && (queuedTarget.blockedOn = null);
      }
      for (; 0 < queuedExplicitHydrationTargets.length && (i2 = queuedExplicitHydrationTargets[0], null === i2.blockedOn); )
        attemptExplicitHydrationTarget(i2), null === i2.blockedOn && queuedExplicitHydrationTargets.shift();
      i2 = (unblocked.ownerDocument || unblocked).$$reactFormReplay;
      if (null != i2)
        for (queuedTarget = 0; queuedTarget < i2.length; queuedTarget += 3) {
          var form = i2[queuedTarget], submitterOrAction = i2[queuedTarget + 1], formProps = form[internalPropsKey] || null;
          if ("function" === typeof submitterOrAction)
            formProps || scheduleReplayQueueIfNeeded(i2);
          else if (formProps) {
            var action = null;
            if (submitterOrAction && submitterOrAction.hasAttribute("formAction"))
              if (form = submitterOrAction, formProps = submitterOrAction[internalPropsKey] || null)
                action = formProps.formAction;
              else {
                if (null !== findInstanceBlockingTarget(form)) continue;
              }
            else action = formProps.action;
            "function" === typeof action ? i2[queuedTarget + 1] = action : (i2.splice(queuedTarget, 3), queuedTarget -= 3);
            scheduleReplayQueueIfNeeded(i2);
          }
        }
    }
    function defaultOnDefaultTransitionIndicator() {
      function handleNavigate(event) {
        event.canIntercept && "react-transition" === event.info && event.intercept({
          handler: function() {
            return new Promise(function(resolve2) {
              return pendingResolve = resolve2;
            });
          },
          focusReset: "manual",
          scroll: "manual"
        });
      }
      function handleNavigateComplete() {
        null !== pendingResolve && (pendingResolve(), pendingResolve = null);
        isCancelled || setTimeout(startFakeNavigation, 20);
      }
      function startFakeNavigation() {
        if (!isCancelled && !navigation.transition) {
          var currentEntry = navigation.currentEntry;
          currentEntry && null != currentEntry.url && navigation.navigate(currentEntry.url, {
            state: currentEntry.getState(),
            info: "react-transition",
            history: "replace"
          });
        }
      }
      if ("object" === typeof navigation) {
        var isCancelled = false, pendingResolve = null;
        navigation.addEventListener("navigate", handleNavigate);
        navigation.addEventListener("navigatesuccess", handleNavigateComplete);
        navigation.addEventListener("navigateerror", handleNavigateComplete);
        setTimeout(startFakeNavigation, 100);
        return function() {
          isCancelled = true;
          navigation.removeEventListener("navigate", handleNavigate);
          navigation.removeEventListener(
            "navigatesuccess",
            handleNavigateComplete
          );
          navigation.removeEventListener(
            "navigateerror",
            handleNavigateComplete
          );
          null !== pendingResolve && (pendingResolve(), pendingResolve = null);
        };
      }
    }
    function ReactDOMRoot(internalRoot) {
      this._internalRoot = internalRoot;
    }
    function ReactDOMHydrationRoot(internalRoot) {
      this._internalRoot = internalRoot;
    }
    function warnIfReactDOMContainerInDEV(container2) {
      container2[internalContainerInstanceKey] && (container2._reactRootContainer ? console.error(
        "You are calling ReactDOMClient.createRoot() on a container that was previously passed to ReactDOM.render(). This is not supported."
      ) : console.error(
        "You are calling ReactDOMClient.createRoot() on a container that has already been passed to createRoot() before. Instead, call root.render() on the existing root instead if you want to update it."
      ));
    }
    "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
    var Scheduler = requireScheduler(), React = requireReact(), ReactDOM2 = requireReactDom(), assign2 = Object.assign, REACT_LEGACY_ELEMENT_TYPE = Symbol.for("react.element"), REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = Symbol.for("react.memo"), REACT_LAZY_TYPE = Symbol.for("react.lazy");
    var REACT_ACTIVITY_TYPE = Symbol.for("react.activity");
    var REACT_MEMO_CACHE_SENTINEL = Symbol.for("react.memo_cache_sentinel");
    var MAYBE_ITERATOR_SYMBOL = Symbol.iterator, REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"), isArrayImpl = Array.isArray, ReactSharedInternals = React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, ReactDOMSharedInternals = ReactDOM2.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, NotPending = Object.freeze({
      pending: false,
      data: null,
      method: null,
      action: null
    }), valueStack = [];
    var fiberStack = [];
    var index$jscomp$0 = -1, contextStackCursor = createCursor(null), contextFiberStackCursor = createCursor(null), rootInstanceStackCursor = createCursor(null), hostTransitionProviderCursor = createCursor(null), disabledDepth = 0, prevLog, prevInfo, prevWarn, prevError, prevGroup, prevGroupCollapsed, prevGroupEnd;
    disabledLog.__reactDisabledLog = true;
    var prefix, suffix, reentry = false;
    var componentFrameCache = new ("function" === typeof WeakMap ? WeakMap : Map)();
    var current3 = null, isRendering = false, hasOwnProperty2 = Object.prototype.hasOwnProperty, scheduleCallback$3 = Scheduler.unstable_scheduleCallback, cancelCallback$1 = Scheduler.unstable_cancelCallback, shouldYield = Scheduler.unstable_shouldYield, requestPaint = Scheduler.unstable_requestPaint, now$1 = Scheduler.unstable_now, getCurrentPriorityLevel = Scheduler.unstable_getCurrentPriorityLevel, ImmediatePriority = Scheduler.unstable_ImmediatePriority, UserBlockingPriority = Scheduler.unstable_UserBlockingPriority, NormalPriority$1 = Scheduler.unstable_NormalPriority, LowPriority = Scheduler.unstable_LowPriority, IdlePriority = Scheduler.unstable_IdlePriority, log$12 = Scheduler.log, unstable_setDisableYieldValue = Scheduler.unstable_setDisableYieldValue, rendererID = null, injectedHook = null, hasLoggedError = false, isDevToolsPresent = "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__, clz322 = Math.clz32 ? Math.clz32 : clz32Fallback, log3 = Math.log, LN2 = Math.LN2, nextTransitionUpdateLane = 256, nextTransitionDeferredLane = 262144, nextRetryLane = 4194304, DiscreteEventPriority = 2, ContinuousEventPriority = 8, DefaultEventPriority = 32, IdleEventPriority = 268435456, randomKey = Math.random().toString(36).slice(2), internalInstanceKey = "__reactFiber$" + randomKey, internalPropsKey = "__reactProps$" + randomKey, internalContainerInstanceKey = "__reactContainer$" + randomKey, internalEventHandlersKey = "__reactEvents$" + randomKey, internalEventHandlerListenersKey = "__reactListeners$" + randomKey, internalEventHandlesSetKey = "__reactHandles$" + randomKey, internalRootNodeResourcesKey = "__reactResources$" + randomKey, internalHoistableMarker = "__reactMarker$" + randomKey, allNativeEvents = /* @__PURE__ */ new Set(), registrationNameDependencies = {}, possibleRegistrationNames = {}, hasReadOnlyValue = {
      button: true,
      checkbox: true,
      image: true,
      hidden: true,
      radio: true,
      reset: true,
      submit: true
    }, VALID_ATTRIBUTE_NAME_REGEX = RegExp(
      "^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"
    ), illegalAttributeNameCache = {}, validatedAttributeNameCache = {}, escapeSelectorAttributeValueInsideDoubleQuotesRegex = /[\n"\\]/g, didWarnValueDefaultValue$1 = false, didWarnCheckedDefaultChecked = false, didWarnSelectedSetOnOption = false, didWarnInvalidChild = false, didWarnInvalidInnerHTML = false;
    var didWarnValueDefaultValue = false;
    var valuePropNames = ["value", "defaultValue"], didWarnValDefaultVal = false, needsEscaping = /["'&<>\n\t]|^\s|\s$/, specialTags = "address applet area article aside base basefont bgsound blockquote body br button caption center col colgroup dd details dir div dl dt embed fieldset figcaption figure footer form frame frameset h1 h2 h3 h4 h5 h6 head header hgroup hr html iframe img input isindex li link listing main marquee menu menuitem meta nav noembed noframes noscript object ol p param plaintext pre script section select source style summary table tbody td template textarea tfoot th thead title tr track ul wbr xmp".split(
      " "
    ), inScopeTags = "applet caption html table td th marquee object template foreignObject desc title".split(
      " "
    ), buttonScopeTags = inScopeTags.concat(["button"]), impliedEndTags = "dd dt li option optgroup p rp rt".split(" "), emptyAncestorInfoDev = {
      current: null,
      formTag: null,
      aTagInScope: null,
      buttonTagInScope: null,
      nobrTagInScope: null,
      pTagInButtonScope: null,
      listItemTagAutoclosing: null,
      dlItemTagAutoclosing: null,
      containerTagInScope: null,
      implicitRootScope: false
    }, didWarn = {}, shorthandToLonghand = {
      animation: "animationDelay animationDirection animationDuration animationFillMode animationIterationCount animationName animationPlayState animationTimingFunction".split(
        " "
      ),
      background: "backgroundAttachment backgroundClip backgroundColor backgroundImage backgroundOrigin backgroundPositionX backgroundPositionY backgroundRepeat backgroundSize".split(
        " "
      ),
      backgroundPosition: ["backgroundPositionX", "backgroundPositionY"],
      border: "borderBottomColor borderBottomStyle borderBottomWidth borderImageOutset borderImageRepeat borderImageSlice borderImageSource borderImageWidth borderLeftColor borderLeftStyle borderLeftWidth borderRightColor borderRightStyle borderRightWidth borderTopColor borderTopStyle borderTopWidth".split(
        " "
      ),
      borderBlockEnd: [
        "borderBlockEndColor",
        "borderBlockEndStyle",
        "borderBlockEndWidth"
      ],
      borderBlockStart: [
        "borderBlockStartColor",
        "borderBlockStartStyle",
        "borderBlockStartWidth"
      ],
      borderBottom: [
        "borderBottomColor",
        "borderBottomStyle",
        "borderBottomWidth"
      ],
      borderColor: [
        "borderBottomColor",
        "borderLeftColor",
        "borderRightColor",
        "borderTopColor"
      ],
      borderImage: [
        "borderImageOutset",
        "borderImageRepeat",
        "borderImageSlice",
        "borderImageSource",
        "borderImageWidth"
      ],
      borderInlineEnd: [
        "borderInlineEndColor",
        "borderInlineEndStyle",
        "borderInlineEndWidth"
      ],
      borderInlineStart: [
        "borderInlineStartColor",
        "borderInlineStartStyle",
        "borderInlineStartWidth"
      ],
      borderLeft: ["borderLeftColor", "borderLeftStyle", "borderLeftWidth"],
      borderRadius: [
        "borderBottomLeftRadius",
        "borderBottomRightRadius",
        "borderTopLeftRadius",
        "borderTopRightRadius"
      ],
      borderRight: [
        "borderRightColor",
        "borderRightStyle",
        "borderRightWidth"
      ],
      borderStyle: [
        "borderBottomStyle",
        "borderLeftStyle",
        "borderRightStyle",
        "borderTopStyle"
      ],
      borderTop: ["borderTopColor", "borderTopStyle", "borderTopWidth"],
      borderWidth: [
        "borderBottomWidth",
        "borderLeftWidth",
        "borderRightWidth",
        "borderTopWidth"
      ],
      columnRule: ["columnRuleColor", "columnRuleStyle", "columnRuleWidth"],
      columns: ["columnCount", "columnWidth"],
      flex: ["flexBasis", "flexGrow", "flexShrink"],
      flexFlow: ["flexDirection", "flexWrap"],
      font: "fontFamily fontFeatureSettings fontKerning fontLanguageOverride fontSize fontSizeAdjust fontStretch fontStyle fontVariant fontVariantAlternates fontVariantCaps fontVariantEastAsian fontVariantLigatures fontVariantNumeric fontVariantPosition fontWeight lineHeight".split(
        " "
      ),
      fontVariant: "fontVariantAlternates fontVariantCaps fontVariantEastAsian fontVariantLigatures fontVariantNumeric fontVariantPosition".split(
        " "
      ),
      gap: ["columnGap", "rowGap"],
      grid: "gridAutoColumns gridAutoFlow gridAutoRows gridTemplateAreas gridTemplateColumns gridTemplateRows".split(
        " "
      ),
      gridArea: [
        "gridColumnEnd",
        "gridColumnStart",
        "gridRowEnd",
        "gridRowStart"
      ],
      gridColumn: ["gridColumnEnd", "gridColumnStart"],
      gridColumnGap: ["columnGap"],
      gridGap: ["columnGap", "rowGap"],
      gridRow: ["gridRowEnd", "gridRowStart"],
      gridRowGap: ["rowGap"],
      gridTemplate: [
        "gridTemplateAreas",
        "gridTemplateColumns",
        "gridTemplateRows"
      ],
      listStyle: ["listStyleImage", "listStylePosition", "listStyleType"],
      margin: ["marginBottom", "marginLeft", "marginRight", "marginTop"],
      marker: ["markerEnd", "markerMid", "markerStart"],
      mask: "maskClip maskComposite maskImage maskMode maskOrigin maskPositionX maskPositionY maskRepeat maskSize".split(
        " "
      ),
      maskPosition: ["maskPositionX", "maskPositionY"],
      outline: ["outlineColor", "outlineStyle", "outlineWidth"],
      overflow: ["overflowX", "overflowY"],
      padding: ["paddingBottom", "paddingLeft", "paddingRight", "paddingTop"],
      placeContent: ["alignContent", "justifyContent"],
      placeItems: ["alignItems", "justifyItems"],
      placeSelf: ["alignSelf", "justifySelf"],
      textDecoration: [
        "textDecorationColor",
        "textDecorationLine",
        "textDecorationStyle"
      ],
      textEmphasis: ["textEmphasisColor", "textEmphasisStyle"],
      transition: [
        "transitionDelay",
        "transitionDuration",
        "transitionProperty",
        "transitionTimingFunction"
      ],
      wordWrap: ["overflowWrap"]
    }, uppercasePattern = /([A-Z])/g, msPattern$1 = /^ms-/, badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/, msPattern = /^-ms-/, hyphenPattern = /-(.)/g, badStyleValueWithSemicolonPattern = /;\s*$/, warnedStyleNames = {}, warnedStyleValues = {}, warnedForNaNValue = false, warnedForInfinityValue = false, unitlessNumbers = new Set(
      "animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(
        " "
      )
    ), MATH_NAMESPACE = "http://www.w3.org/1998/Math/MathML", SVG_NAMESPACE = "http://www.w3.org/2000/svg", aliases = /* @__PURE__ */ new Map([
      ["acceptCharset", "accept-charset"],
      ["htmlFor", "for"],
      ["httpEquiv", "http-equiv"],
      ["crossOrigin", "crossorigin"],
      ["accentHeight", "accent-height"],
      ["alignmentBaseline", "alignment-baseline"],
      ["arabicForm", "arabic-form"],
      ["baselineShift", "baseline-shift"],
      ["capHeight", "cap-height"],
      ["clipPath", "clip-path"],
      ["clipRule", "clip-rule"],
      ["colorInterpolation", "color-interpolation"],
      ["colorInterpolationFilters", "color-interpolation-filters"],
      ["colorProfile", "color-profile"],
      ["colorRendering", "color-rendering"],
      ["dominantBaseline", "dominant-baseline"],
      ["enableBackground", "enable-background"],
      ["fillOpacity", "fill-opacity"],
      ["fillRule", "fill-rule"],
      ["floodColor", "flood-color"],
      ["floodOpacity", "flood-opacity"],
      ["fontFamily", "font-family"],
      ["fontSize", "font-size"],
      ["fontSizeAdjust", "font-size-adjust"],
      ["fontStretch", "font-stretch"],
      ["fontStyle", "font-style"],
      ["fontVariant", "font-variant"],
      ["fontWeight", "font-weight"],
      ["glyphName", "glyph-name"],
      ["glyphOrientationHorizontal", "glyph-orientation-horizontal"],
      ["glyphOrientationVertical", "glyph-orientation-vertical"],
      ["horizAdvX", "horiz-adv-x"],
      ["horizOriginX", "horiz-origin-x"],
      ["imageRendering", "image-rendering"],
      ["letterSpacing", "letter-spacing"],
      ["lightingColor", "lighting-color"],
      ["markerEnd", "marker-end"],
      ["markerMid", "marker-mid"],
      ["markerStart", "marker-start"],
      ["overlinePosition", "overline-position"],
      ["overlineThickness", "overline-thickness"],
      ["paintOrder", "paint-order"],
      ["panose-1", "panose-1"],
      ["pointerEvents", "pointer-events"],
      ["renderingIntent", "rendering-intent"],
      ["shapeRendering", "shape-rendering"],
      ["stopColor", "stop-color"],
      ["stopOpacity", "stop-opacity"],
      ["strikethroughPosition", "strikethrough-position"],
      ["strikethroughThickness", "strikethrough-thickness"],
      ["strokeDasharray", "stroke-dasharray"],
      ["strokeDashoffset", "stroke-dashoffset"],
      ["strokeLinecap", "stroke-linecap"],
      ["strokeLinejoin", "stroke-linejoin"],
      ["strokeMiterlimit", "stroke-miterlimit"],
      ["strokeOpacity", "stroke-opacity"],
      ["strokeWidth", "stroke-width"],
      ["textAnchor", "text-anchor"],
      ["textDecoration", "text-decoration"],
      ["textRendering", "text-rendering"],
      ["transformOrigin", "transform-origin"],
      ["underlinePosition", "underline-position"],
      ["underlineThickness", "underline-thickness"],
      ["unicodeBidi", "unicode-bidi"],
      ["unicodeRange", "unicode-range"],
      ["unitsPerEm", "units-per-em"],
      ["vAlphabetic", "v-alphabetic"],
      ["vHanging", "v-hanging"],
      ["vIdeographic", "v-ideographic"],
      ["vMathematical", "v-mathematical"],
      ["vectorEffect", "vector-effect"],
      ["vertAdvY", "vert-adv-y"],
      ["vertOriginX", "vert-origin-x"],
      ["vertOriginY", "vert-origin-y"],
      ["wordSpacing", "word-spacing"],
      ["writingMode", "writing-mode"],
      ["xmlnsXlink", "xmlns:xlink"],
      ["xHeight", "x-height"]
    ]), possibleStandardNames = {
      accept: "accept",
      acceptcharset: "acceptCharset",
      "accept-charset": "acceptCharset",
      accesskey: "accessKey",
      action: "action",
      allowfullscreen: "allowFullScreen",
      alt: "alt",
      as: "as",
      async: "async",
      autocapitalize: "autoCapitalize",
      autocomplete: "autoComplete",
      autocorrect: "autoCorrect",
      autofocus: "autoFocus",
      autoplay: "autoPlay",
      autosave: "autoSave",
      capture: "capture",
      cellpadding: "cellPadding",
      cellspacing: "cellSpacing",
      challenge: "challenge",
      charset: "charSet",
      checked: "checked",
      children: "children",
      cite: "cite",
      class: "className",
      classid: "classID",
      classname: "className",
      cols: "cols",
      colspan: "colSpan",
      content: "content",
      contenteditable: "contentEditable",
      contextmenu: "contextMenu",
      controls: "controls",
      controlslist: "controlsList",
      coords: "coords",
      crossorigin: "crossOrigin",
      dangerouslysetinnerhtml: "dangerouslySetInnerHTML",
      data: "data",
      datetime: "dateTime",
      default: "default",
      defaultchecked: "defaultChecked",
      defaultvalue: "defaultValue",
      defer: "defer",
      dir: "dir",
      disabled: "disabled",
      disablepictureinpicture: "disablePictureInPicture",
      disableremoteplayback: "disableRemotePlayback",
      download: "download",
      draggable: "draggable",
      enctype: "encType",
      enterkeyhint: "enterKeyHint",
      fetchpriority: "fetchPriority",
      for: "htmlFor",
      form: "form",
      formmethod: "formMethod",
      formaction: "formAction",
      formenctype: "formEncType",
      formnovalidate: "formNoValidate",
      formtarget: "formTarget",
      frameborder: "frameBorder",
      headers: "headers",
      height: "height",
      hidden: "hidden",
      high: "high",
      href: "href",
      hreflang: "hrefLang",
      htmlfor: "htmlFor",
      httpequiv: "httpEquiv",
      "http-equiv": "httpEquiv",
      icon: "icon",
      id: "id",
      imagesizes: "imageSizes",
      imagesrcset: "imageSrcSet",
      inert: "inert",
      innerhtml: "innerHTML",
      inputmode: "inputMode",
      integrity: "integrity",
      is: "is",
      itemid: "itemID",
      itemprop: "itemProp",
      itemref: "itemRef",
      itemscope: "itemScope",
      itemtype: "itemType",
      keyparams: "keyParams",
      keytype: "keyType",
      kind: "kind",
      label: "label",
      lang: "lang",
      list: "list",
      loop: "loop",
      low: "low",
      manifest: "manifest",
      marginwidth: "marginWidth",
      marginheight: "marginHeight",
      max: "max",
      maxlength: "maxLength",
      media: "media",
      mediagroup: "mediaGroup",
      method: "method",
      min: "min",
      minlength: "minLength",
      multiple: "multiple",
      muted: "muted",
      name: "name",
      nomodule: "noModule",
      nonce: "nonce",
      novalidate: "noValidate",
      open: "open",
      optimum: "optimum",
      pattern: "pattern",
      placeholder: "placeholder",
      playsinline: "playsInline",
      poster: "poster",
      preload: "preload",
      profile: "profile",
      radiogroup: "radioGroup",
      readonly: "readOnly",
      referrerpolicy: "referrerPolicy",
      rel: "rel",
      required: "required",
      reversed: "reversed",
      role: "role",
      rows: "rows",
      rowspan: "rowSpan",
      sandbox: "sandbox",
      scope: "scope",
      scoped: "scoped",
      scrolling: "scrolling",
      seamless: "seamless",
      selected: "selected",
      shape: "shape",
      size: "size",
      sizes: "sizes",
      span: "span",
      spellcheck: "spellCheck",
      src: "src",
      srcdoc: "srcDoc",
      srclang: "srcLang",
      srcset: "srcSet",
      start: "start",
      step: "step",
      style: "style",
      summary: "summary",
      tabindex: "tabIndex",
      target: "target",
      title: "title",
      type: "type",
      usemap: "useMap",
      value: "value",
      width: "width",
      wmode: "wmode",
      wrap: "wrap",
      about: "about",
      accentheight: "accentHeight",
      "accent-height": "accentHeight",
      accumulate: "accumulate",
      additive: "additive",
      alignmentbaseline: "alignmentBaseline",
      "alignment-baseline": "alignmentBaseline",
      allowreorder: "allowReorder",
      alphabetic: "alphabetic",
      amplitude: "amplitude",
      arabicform: "arabicForm",
      "arabic-form": "arabicForm",
      ascent: "ascent",
      attributename: "attributeName",
      attributetype: "attributeType",
      autoreverse: "autoReverse",
      azimuth: "azimuth",
      basefrequency: "baseFrequency",
      baselineshift: "baselineShift",
      "baseline-shift": "baselineShift",
      baseprofile: "baseProfile",
      bbox: "bbox",
      begin: "begin",
      bias: "bias",
      by: "by",
      calcmode: "calcMode",
      capheight: "capHeight",
      "cap-height": "capHeight",
      clip: "clip",
      clippath: "clipPath",
      "clip-path": "clipPath",
      clippathunits: "clipPathUnits",
      cliprule: "clipRule",
      "clip-rule": "clipRule",
      color: "color",
      colorinterpolation: "colorInterpolation",
      "color-interpolation": "colorInterpolation",
      colorinterpolationfilters: "colorInterpolationFilters",
      "color-interpolation-filters": "colorInterpolationFilters",
      colorprofile: "colorProfile",
      "color-profile": "colorProfile",
      colorrendering: "colorRendering",
      "color-rendering": "colorRendering",
      contentscripttype: "contentScriptType",
      contentstyletype: "contentStyleType",
      cursor: "cursor",
      cx: "cx",
      cy: "cy",
      d: "d",
      datatype: "datatype",
      decelerate: "decelerate",
      descent: "descent",
      diffuseconstant: "diffuseConstant",
      direction: "direction",
      display: "display",
      divisor: "divisor",
      dominantbaseline: "dominantBaseline",
      "dominant-baseline": "dominantBaseline",
      dur: "dur",
      dx: "dx",
      dy: "dy",
      edgemode: "edgeMode",
      elevation: "elevation",
      enablebackground: "enableBackground",
      "enable-background": "enableBackground",
      end: "end",
      exponent: "exponent",
      externalresourcesrequired: "externalResourcesRequired",
      fill: "fill",
      fillopacity: "fillOpacity",
      "fill-opacity": "fillOpacity",
      fillrule: "fillRule",
      "fill-rule": "fillRule",
      filter: "filter",
      filterres: "filterRes",
      filterunits: "filterUnits",
      floodopacity: "floodOpacity",
      "flood-opacity": "floodOpacity",
      floodcolor: "floodColor",
      "flood-color": "floodColor",
      focusable: "focusable",
      fontfamily: "fontFamily",
      "font-family": "fontFamily",
      fontsize: "fontSize",
      "font-size": "fontSize",
      fontsizeadjust: "fontSizeAdjust",
      "font-size-adjust": "fontSizeAdjust",
      fontstretch: "fontStretch",
      "font-stretch": "fontStretch",
      fontstyle: "fontStyle",
      "font-style": "fontStyle",
      fontvariant: "fontVariant",
      "font-variant": "fontVariant",
      fontweight: "fontWeight",
      "font-weight": "fontWeight",
      format: "format",
      from: "from",
      fx: "fx",
      fy: "fy",
      g1: "g1",
      g2: "g2",
      glyphname: "glyphName",
      "glyph-name": "glyphName",
      glyphorientationhorizontal: "glyphOrientationHorizontal",
      "glyph-orientation-horizontal": "glyphOrientationHorizontal",
      glyphorientationvertical: "glyphOrientationVertical",
      "glyph-orientation-vertical": "glyphOrientationVertical",
      glyphref: "glyphRef",
      gradienttransform: "gradientTransform",
      gradientunits: "gradientUnits",
      hanging: "hanging",
      horizadvx: "horizAdvX",
      "horiz-adv-x": "horizAdvX",
      horizoriginx: "horizOriginX",
      "horiz-origin-x": "horizOriginX",
      ideographic: "ideographic",
      imagerendering: "imageRendering",
      "image-rendering": "imageRendering",
      in2: "in2",
      in: "in",
      inlist: "inlist",
      intercept: "intercept",
      k1: "k1",
      k2: "k2",
      k3: "k3",
      k4: "k4",
      k: "k",
      kernelmatrix: "kernelMatrix",
      kernelunitlength: "kernelUnitLength",
      kerning: "kerning",
      keypoints: "keyPoints",
      keysplines: "keySplines",
      keytimes: "keyTimes",
      lengthadjust: "lengthAdjust",
      letterspacing: "letterSpacing",
      "letter-spacing": "letterSpacing",
      lightingcolor: "lightingColor",
      "lighting-color": "lightingColor",
      limitingconeangle: "limitingConeAngle",
      local: "local",
      markerend: "markerEnd",
      "marker-end": "markerEnd",
      markerheight: "markerHeight",
      markermid: "markerMid",
      "marker-mid": "markerMid",
      markerstart: "markerStart",
      "marker-start": "markerStart",
      markerunits: "markerUnits",
      markerwidth: "markerWidth",
      mask: "mask",
      maskcontentunits: "maskContentUnits",
      maskunits: "maskUnits",
      mathematical: "mathematical",
      mode: "mode",
      numoctaves: "numOctaves",
      offset: "offset",
      opacity: "opacity",
      operator: "operator",
      order: "order",
      orient: "orient",
      orientation: "orientation",
      origin: "origin",
      overflow: "overflow",
      overlineposition: "overlinePosition",
      "overline-position": "overlinePosition",
      overlinethickness: "overlineThickness",
      "overline-thickness": "overlineThickness",
      paintorder: "paintOrder",
      "paint-order": "paintOrder",
      panose1: "panose1",
      "panose-1": "panose1",
      pathlength: "pathLength",
      patterncontentunits: "patternContentUnits",
      patterntransform: "patternTransform",
      patternunits: "patternUnits",
      pointerevents: "pointerEvents",
      "pointer-events": "pointerEvents",
      points: "points",
      pointsatx: "pointsAtX",
      pointsaty: "pointsAtY",
      pointsatz: "pointsAtZ",
      popover: "popover",
      popovertarget: "popoverTarget",
      popovertargetaction: "popoverTargetAction",
      prefix: "prefix",
      preservealpha: "preserveAlpha",
      preserveaspectratio: "preserveAspectRatio",
      primitiveunits: "primitiveUnits",
      property: "property",
      r: "r",
      radius: "radius",
      refx: "refX",
      refy: "refY",
      renderingintent: "renderingIntent",
      "rendering-intent": "renderingIntent",
      repeatcount: "repeatCount",
      repeatdur: "repeatDur",
      requiredextensions: "requiredExtensions",
      requiredfeatures: "requiredFeatures",
      resource: "resource",
      restart: "restart",
      result: "result",
      results: "results",
      rotate: "rotate",
      rx: "rx",
      ry: "ry",
      scale: "scale",
      security: "security",
      seed: "seed",
      shaperendering: "shapeRendering",
      "shape-rendering": "shapeRendering",
      slope: "slope",
      spacing: "spacing",
      specularconstant: "specularConstant",
      specularexponent: "specularExponent",
      speed: "speed",
      spreadmethod: "spreadMethod",
      startoffset: "startOffset",
      stddeviation: "stdDeviation",
      stemh: "stemh",
      stemv: "stemv",
      stitchtiles: "stitchTiles",
      stopcolor: "stopColor",
      "stop-color": "stopColor",
      stopopacity: "stopOpacity",
      "stop-opacity": "stopOpacity",
      strikethroughposition: "strikethroughPosition",
      "strikethrough-position": "strikethroughPosition",
      strikethroughthickness: "strikethroughThickness",
      "strikethrough-thickness": "strikethroughThickness",
      string: "string",
      stroke: "stroke",
      strokedasharray: "strokeDasharray",
      "stroke-dasharray": "strokeDasharray",
      strokedashoffset: "strokeDashoffset",
      "stroke-dashoffset": "strokeDashoffset",
      strokelinecap: "strokeLinecap",
      "stroke-linecap": "strokeLinecap",
      strokelinejoin: "strokeLinejoin",
      "stroke-linejoin": "strokeLinejoin",
      strokemiterlimit: "strokeMiterlimit",
      "stroke-miterlimit": "strokeMiterlimit",
      strokewidth: "strokeWidth",
      "stroke-width": "strokeWidth",
      strokeopacity: "strokeOpacity",
      "stroke-opacity": "strokeOpacity",
      suppresscontenteditablewarning: "suppressContentEditableWarning",
      suppresshydrationwarning: "suppressHydrationWarning",
      surfacescale: "surfaceScale",
      systemlanguage: "systemLanguage",
      tablevalues: "tableValues",
      targetx: "targetX",
      targety: "targetY",
      textanchor: "textAnchor",
      "text-anchor": "textAnchor",
      textdecoration: "textDecoration",
      "text-decoration": "textDecoration",
      textlength: "textLength",
      textrendering: "textRendering",
      "text-rendering": "textRendering",
      to: "to",
      transform: "transform",
      transformorigin: "transformOrigin",
      "transform-origin": "transformOrigin",
      typeof: "typeof",
      u1: "u1",
      u2: "u2",
      underlineposition: "underlinePosition",
      "underline-position": "underlinePosition",
      underlinethickness: "underlineThickness",
      "underline-thickness": "underlineThickness",
      unicode: "unicode",
      unicodebidi: "unicodeBidi",
      "unicode-bidi": "unicodeBidi",
      unicoderange: "unicodeRange",
      "unicode-range": "unicodeRange",
      unitsperem: "unitsPerEm",
      "units-per-em": "unitsPerEm",
      unselectable: "unselectable",
      valphabetic: "vAlphabetic",
      "v-alphabetic": "vAlphabetic",
      values: "values",
      vectoreffect: "vectorEffect",
      "vector-effect": "vectorEffect",
      version: "version",
      vertadvy: "vertAdvY",
      "vert-adv-y": "vertAdvY",
      vertoriginx: "vertOriginX",
      "vert-origin-x": "vertOriginX",
      vertoriginy: "vertOriginY",
      "vert-origin-y": "vertOriginY",
      vhanging: "vHanging",
      "v-hanging": "vHanging",
      videographic: "vIdeographic",
      "v-ideographic": "vIdeographic",
      viewbox: "viewBox",
      viewtarget: "viewTarget",
      visibility: "visibility",
      vmathematical: "vMathematical",
      "v-mathematical": "vMathematical",
      vocab: "vocab",
      widths: "widths",
      wordspacing: "wordSpacing",
      "word-spacing": "wordSpacing",
      writingmode: "writingMode",
      "writing-mode": "writingMode",
      x1: "x1",
      x2: "x2",
      x: "x",
      xchannelselector: "xChannelSelector",
      xheight: "xHeight",
      "x-height": "xHeight",
      xlinkactuate: "xlinkActuate",
      "xlink:actuate": "xlinkActuate",
      xlinkarcrole: "xlinkArcrole",
      "xlink:arcrole": "xlinkArcrole",
      xlinkhref: "xlinkHref",
      "xlink:href": "xlinkHref",
      xlinkrole: "xlinkRole",
      "xlink:role": "xlinkRole",
      xlinkshow: "xlinkShow",
      "xlink:show": "xlinkShow",
      xlinktitle: "xlinkTitle",
      "xlink:title": "xlinkTitle",
      xlinktype: "xlinkType",
      "xlink:type": "xlinkType",
      xmlbase: "xmlBase",
      "xml:base": "xmlBase",
      xmllang: "xmlLang",
      "xml:lang": "xmlLang",
      xmlns: "xmlns",
      "xml:space": "xmlSpace",
      xmlnsxlink: "xmlnsXlink",
      "xmlns:xlink": "xmlnsXlink",
      xmlspace: "xmlSpace",
      y1: "y1",
      y2: "y2",
      y: "y",
      ychannelselector: "yChannelSelector",
      z: "z",
      zoomandpan: "zoomAndPan"
    }, ariaProperties = {
      "aria-current": 0,
      "aria-description": 0,
      "aria-details": 0,
      "aria-disabled": 0,
      "aria-hidden": 0,
      "aria-invalid": 0,
      "aria-keyshortcuts": 0,
      "aria-label": 0,
      "aria-roledescription": 0,
      "aria-autocomplete": 0,
      "aria-checked": 0,
      "aria-expanded": 0,
      "aria-haspopup": 0,
      "aria-level": 0,
      "aria-modal": 0,
      "aria-multiline": 0,
      "aria-multiselectable": 0,
      "aria-orientation": 0,
      "aria-placeholder": 0,
      "aria-pressed": 0,
      "aria-readonly": 0,
      "aria-required": 0,
      "aria-selected": 0,
      "aria-sort": 0,
      "aria-valuemax": 0,
      "aria-valuemin": 0,
      "aria-valuenow": 0,
      "aria-valuetext": 0,
      "aria-atomic": 0,
      "aria-busy": 0,
      "aria-live": 0,
      "aria-relevant": 0,
      "aria-dropeffect": 0,
      "aria-grabbed": 0,
      "aria-activedescendant": 0,
      "aria-colcount": 0,
      "aria-colindex": 0,
      "aria-colspan": 0,
      "aria-controls": 0,
      "aria-describedby": 0,
      "aria-errormessage": 0,
      "aria-flowto": 0,
      "aria-labelledby": 0,
      "aria-owns": 0,
      "aria-posinset": 0,
      "aria-rowcount": 0,
      "aria-rowindex": 0,
      "aria-rowspan": 0,
      "aria-setsize": 0,
      "aria-braillelabel": 0,
      "aria-brailleroledescription": 0,
      "aria-colindextext": 0,
      "aria-rowindextext": 0
    }, warnedProperties$1 = {}, rARIA$1 = RegExp(
      "^(aria)-[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"
    ), rARIACamel$1 = RegExp(
      "^(aria)[A-Z][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"
    ), didWarnValueNull = false, warnedProperties = {}, EVENT_NAME_REGEX = /^on./, INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/, rARIA = RegExp(
      "^(aria)-[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"
    ), rARIACamel = RegExp(
      "^(aria)[A-Z][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"
    ), isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i, currentReplayingEvent = null, restoreTarget = null, restoreQueue = null, isInsideEventHandler = false, canUseDOM = !("undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement), passiveBrowserEventsSupported = false;
    if (canUseDOM)
      try {
        var options$jscomp$0 = {};
        Object.defineProperty(options$jscomp$0, "passive", {
          get: function() {
            passiveBrowserEventsSupported = true;
          }
        });
        window.addEventListener("test", options$jscomp$0, options$jscomp$0);
        window.removeEventListener("test", options$jscomp$0, options$jscomp$0);
      } catch (e) {
        passiveBrowserEventsSupported = false;
      }
    var root2 = null, startText = null, fallbackText = null, EventInterface = {
      eventPhase: 0,
      bubbles: 0,
      cancelable: 0,
      timeStamp: function(event) {
        return event.timeStamp || Date.now();
      },
      defaultPrevented: 0,
      isTrusted: 0
    }, SyntheticEvent = createSyntheticEvent(EventInterface), UIEventInterface = assign2({}, EventInterface, { view: 0, detail: 0 }), SyntheticUIEvent = createSyntheticEvent(UIEventInterface), lastMovementX, lastMovementY, lastMouseEvent, MouseEventInterface = assign2({}, UIEventInterface, {
      screenX: 0,
      screenY: 0,
      clientX: 0,
      clientY: 0,
      pageX: 0,
      pageY: 0,
      ctrlKey: 0,
      shiftKey: 0,
      altKey: 0,
      metaKey: 0,
      getModifierState: getEventModifierState,
      button: 0,
      buttons: 0,
      relatedTarget: function(event) {
        return void 0 === event.relatedTarget ? event.fromElement === event.srcElement ? event.toElement : event.fromElement : event.relatedTarget;
      },
      movementX: function(event) {
        if ("movementX" in event) return event.movementX;
        event !== lastMouseEvent && (lastMouseEvent && "mousemove" === event.type ? (lastMovementX = event.screenX - lastMouseEvent.screenX, lastMovementY = event.screenY - lastMouseEvent.screenY) : lastMovementY = lastMovementX = 0, lastMouseEvent = event);
        return lastMovementX;
      },
      movementY: function(event) {
        return "movementY" in event ? event.movementY : lastMovementY;
      }
    }), SyntheticMouseEvent = createSyntheticEvent(MouseEventInterface), DragEventInterface = assign2({}, MouseEventInterface, { dataTransfer: 0 }), SyntheticDragEvent = createSyntheticEvent(DragEventInterface), FocusEventInterface = assign2({}, UIEventInterface, { relatedTarget: 0 }), SyntheticFocusEvent = createSyntheticEvent(FocusEventInterface), AnimationEventInterface = assign2({}, EventInterface, {
      animationName: 0,
      elapsedTime: 0,
      pseudoElement: 0
    }), SyntheticAnimationEvent = createSyntheticEvent(AnimationEventInterface), ClipboardEventInterface = assign2({}, EventInterface, {
      clipboardData: function(event) {
        return "clipboardData" in event ? event.clipboardData : window.clipboardData;
      }
    }), SyntheticClipboardEvent = createSyntheticEvent(ClipboardEventInterface), CompositionEventInterface = assign2({}, EventInterface, { data: 0 }), SyntheticCompositionEvent = createSyntheticEvent(
      CompositionEventInterface
    ), SyntheticInputEvent = SyntheticCompositionEvent, normalizeKey = {
      Esc: "Escape",
      Spacebar: " ",
      Left: "ArrowLeft",
      Up: "ArrowUp",
      Right: "ArrowRight",
      Down: "ArrowDown",
      Del: "Delete",
      Win: "OS",
      Menu: "ContextMenu",
      Apps: "ContextMenu",
      Scroll: "ScrollLock",
      MozPrintableKey: "Unidentified"
    }, translateToKey = {
      8: "Backspace",
      9: "Tab",
      12: "Clear",
      13: "Enter",
      16: "Shift",
      17: "Control",
      18: "Alt",
      19: "Pause",
      20: "CapsLock",
      27: "Escape",
      32: " ",
      33: "PageUp",
      34: "PageDown",
      35: "End",
      36: "Home",
      37: "ArrowLeft",
      38: "ArrowUp",
      39: "ArrowRight",
      40: "ArrowDown",
      45: "Insert",
      46: "Delete",
      112: "F1",
      113: "F2",
      114: "F3",
      115: "F4",
      116: "F5",
      117: "F6",
      118: "F7",
      119: "F8",
      120: "F9",
      121: "F10",
      122: "F11",
      123: "F12",
      144: "NumLock",
      145: "ScrollLock",
      224: "Meta"
    }, modifierKeyToProp = {
      Alt: "altKey",
      Control: "ctrlKey",
      Meta: "metaKey",
      Shift: "shiftKey"
    }, KeyboardEventInterface = assign2({}, UIEventInterface, {
      key: function(nativeEvent) {
        if (nativeEvent.key) {
          var key2 = normalizeKey[nativeEvent.key] || nativeEvent.key;
          if ("Unidentified" !== key2) return key2;
        }
        return "keypress" === nativeEvent.type ? (nativeEvent = getEventCharCode(nativeEvent), 13 === nativeEvent ? "Enter" : String.fromCharCode(nativeEvent)) : "keydown" === nativeEvent.type || "keyup" === nativeEvent.type ? translateToKey[nativeEvent.keyCode] || "Unidentified" : "";
      },
      code: 0,
      location: 0,
      ctrlKey: 0,
      shiftKey: 0,
      altKey: 0,
      metaKey: 0,
      repeat: 0,
      locale: 0,
      getModifierState: getEventModifierState,
      charCode: function(event) {
        return "keypress" === event.type ? getEventCharCode(event) : 0;
      },
      keyCode: function(event) {
        return "keydown" === event.type || "keyup" === event.type ? event.keyCode : 0;
      },
      which: function(event) {
        return "keypress" === event.type ? getEventCharCode(event) : "keydown" === event.type || "keyup" === event.type ? event.keyCode : 0;
      }
    }), SyntheticKeyboardEvent = createSyntheticEvent(KeyboardEventInterface), PointerEventInterface = assign2({}, MouseEventInterface, {
      pointerId: 0,
      width: 0,
      height: 0,
      pressure: 0,
      tangentialPressure: 0,
      tiltX: 0,
      tiltY: 0,
      twist: 0,
      pointerType: 0,
      isPrimary: 0
    }), SyntheticPointerEvent = createSyntheticEvent(PointerEventInterface), TouchEventInterface = assign2({}, UIEventInterface, {
      touches: 0,
      targetTouches: 0,
      changedTouches: 0,
      altKey: 0,
      metaKey: 0,
      ctrlKey: 0,
      shiftKey: 0,
      getModifierState: getEventModifierState
    }), SyntheticTouchEvent = createSyntheticEvent(TouchEventInterface), TransitionEventInterface = assign2({}, EventInterface, {
      propertyName: 0,
      elapsedTime: 0,
      pseudoElement: 0
    }), SyntheticTransitionEvent = createSyntheticEvent(TransitionEventInterface), WheelEventInterface = assign2({}, MouseEventInterface, {
      deltaX: function(event) {
        return "deltaX" in event ? event.deltaX : "wheelDeltaX" in event ? -event.wheelDeltaX : 0;
      },
      deltaY: function(event) {
        return "deltaY" in event ? event.deltaY : "wheelDeltaY" in event ? -event.wheelDeltaY : "wheelDelta" in event ? -event.wheelDelta : 0;
      },
      deltaZ: 0,
      deltaMode: 0
    }), SyntheticWheelEvent = createSyntheticEvent(WheelEventInterface), ToggleEventInterface = assign2({}, EventInterface, {
      newState: 0,
      oldState: 0
    }), SyntheticToggleEvent = createSyntheticEvent(ToggleEventInterface), END_KEYCODES = [9, 13, 27, 32], START_KEYCODE = 229, canUseCompositionEvent = canUseDOM && "CompositionEvent" in window, documentMode = null;
    canUseDOM && "documentMode" in document && (documentMode = document.documentMode);
    var canUseTextInputEvent = canUseDOM && "TextEvent" in window && !documentMode, useFallbackCompositionData = canUseDOM && (!canUseCompositionEvent || documentMode && 8 < documentMode && 11 >= documentMode), SPACEBAR_CODE = 32, SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE), hasSpaceKeypress = false, isComposing = false, supportedInputTypes = {
      color: true,
      date: true,
      datetime: true,
      "datetime-local": true,
      email: true,
      month: true,
      number: true,
      password: true,
      range: true,
      search: true,
      tel: true,
      text: true,
      time: true,
      url: true,
      week: true
    }, activeElement$1 = null, activeElementInst$1 = null, isInputEventSupported = false;
    canUseDOM && (isInputEventSupported = isEventSupported("input") && (!document.documentMode || 9 < document.documentMode));
    var objectIs = "function" === typeof Object.is ? Object.is : is2, skipSelectionChangeEvent = canUseDOM && "documentMode" in document && 11 >= document.documentMode, activeElement = null, activeElementInst = null, lastSelection = null, mouseDown = false, vendorPrefixes = {
      animationend: makePrefixMap("Animation", "AnimationEnd"),
      animationiteration: makePrefixMap("Animation", "AnimationIteration"),
      animationstart: makePrefixMap("Animation", "AnimationStart"),
      transitionrun: makePrefixMap("Transition", "TransitionRun"),
      transitionstart: makePrefixMap("Transition", "TransitionStart"),
      transitioncancel: makePrefixMap("Transition", "TransitionCancel"),
      transitionend: makePrefixMap("Transition", "TransitionEnd")
    }, prefixedEventNames = {}, style2 = {};
    canUseDOM && (style2 = document.createElement("div").style, "AnimationEvent" in window || (delete vendorPrefixes.animationend.animation, delete vendorPrefixes.animationiteration.animation, delete vendorPrefixes.animationstart.animation), "TransitionEvent" in window || delete vendorPrefixes.transitionend.transition);
    var ANIMATION_END = getVendorPrefixedEventName("animationend"), ANIMATION_ITERATION = getVendorPrefixedEventName("animationiteration"), ANIMATION_START = getVendorPrefixedEventName("animationstart"), TRANSITION_RUN = getVendorPrefixedEventName("transitionrun"), TRANSITION_START = getVendorPrefixedEventName("transitionstart"), TRANSITION_CANCEL = getVendorPrefixedEventName("transitioncancel"), TRANSITION_END = getVendorPrefixedEventName("transitionend"), topLevelEventsToReactNames = /* @__PURE__ */ new Map(), simpleEventPluginEvents = "abort auxClick beforeToggle cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(
      " "
    );
    simpleEventPluginEvents.push("scrollEnd");
    var lastResetTime = 0;
    if ("object" === typeof performance && "function" === typeof performance.now) {
      var localPerformance = performance;
      var getCurrentTime = function() {
        return localPerformance.now();
      };
    } else {
      var localDate = Date;
      getCurrentTime = function() {
        return localDate.now();
      };
    }
    var reportGlobalError = "function" === typeof reportError ? reportError : function(error2) {
      if ("object" === typeof window && "function" === typeof window.ErrorEvent) {
        var event = new window.ErrorEvent("error", {
          bubbles: true,
          cancelable: true,
          message: "object" === typeof error2 && null !== error2 && "string" === typeof error2.message ? String(error2.message) : String(error2),
          error: error2
        });
        if (!window.dispatchEvent(event)) return;
      } else if ("object" === typeof process && "function" === typeof process.emit) {
        process.emit("uncaughtException", error2);
        return;
      }
      console.error(error2);
    }, OMITTED_PROP_ERROR = "This object has been omitted by React in the console log to avoid sending too much data from the server. Try logging smaller or more specific objects.", EMPTY_ARRAY = 0, COMPLEX_ARRAY = 1, PRIMITIVE_ARRAY = 2, ENTRIES_ARRAY = 3, REMOVED = "– ", ADDED = "+ ", UNCHANGED = "  ", supportsUserTiming = "undefined" !== typeof console && "function" === typeof console.timeStamp && "undefined" !== typeof performance && "function" === typeof performance.measure, COMPONENTS_TRACK = "Components ⚛", LANES_TRACK_GROUP = "Scheduler ⚛", currentTrack = "Blocking", alreadyWarnedForDeepEquality = false, reusableComponentDevToolDetails = {
      color: "primary",
      properties: null,
      tooltipText: "",
      track: COMPONENTS_TRACK
    }, reusableComponentOptions = {
      start: -0,
      end: -0,
      detail: { devtools: reusableComponentDevToolDetails }
    }, resuableChangedPropsEntry = ["Changed Props", ""], DEEP_EQUALITY_WARNING = "This component received deeply equal props. It might benefit from useMemo or the React Compiler in its owner.", reusableDeeplyEqualPropsEntry = ["Changed Props", DEEP_EQUALITY_WARNING], OffscreenVisible = 1, OffscreenPassiveEffectsConnected = 2, concurrentQueues = [], concurrentQueuesIndex = 0, concurrentlyUpdatedLanes = 0, emptyContextObject = {};
    Object.freeze(emptyContextObject);
    var resolveFamily = null, failedBoundaries = null, NoMode = 0, ConcurrentMode = 1, ProfileMode = 2, StrictLegacyMode = 8, StrictEffectsMode = 16, SuspenseyImagesMode = 32;
    var hasBadMapPolyfill = false;
    try {
      var nonExtensibleObject = Object.preventExtensions({});
      /* @__PURE__ */ new Map([[nonExtensibleObject, null]]);
      /* @__PURE__ */ new Set([nonExtensibleObject]);
    } catch (e$3) {
      hasBadMapPolyfill = true;
    }
    var CapturedStacks = /* @__PURE__ */ new WeakMap(), forkStack = [], forkStackIndex = 0, treeForkProvider = null, treeForkCount = 0, idStack = [], idStackIndex = 0, treeContextProvider = null, treeContextId = 1, treeContextOverflow = "", hydrationParentFiber = null, nextHydratableInstance = null, isHydrating = false, didSuspendOrErrorDEV = false, hydrationDiffRootDEV = null, hydrationErrors = null, rootOrSingletonContext = false, HydrationMismatchException = Error(
      "Hydration Mismatch Exception: This is not a real error, and should not leak into userspace. If you're seeing this, it's likely a bug in React."
    ), valueCursor = createCursor(null);
    var rendererCursorDEV = createCursor(null);
    var rendererSigil = {};
    var currentlyRenderingFiber$1 = null, lastContextDependency = null, isDisallowedContextReadInDEV = false, AbortControllerLocal = "undefined" !== typeof AbortController ? AbortController : function() {
      var listeners = [], signal = this.signal = {
        aborted: false,
        addEventListener: function(type, listener) {
          listeners.push(listener);
        }
      };
      this.abort = function() {
        signal.aborted = true;
        listeners.forEach(function(listener) {
          return listener();
        });
      };
    }, scheduleCallback$2 = Scheduler.unstable_scheduleCallback, NormalPriority = Scheduler.unstable_NormalPriority, CacheContext = {
      $$typeof: REACT_CONTEXT_TYPE,
      Consumer: null,
      Provider: null,
      _currentValue: null,
      _currentValue2: null,
      _threadCount: 0,
      _currentRenderer: null,
      _currentRenderer2: null
    }, now2 = Scheduler.unstable_now, createTask = console.createTask ? console.createTask : function() {
      return null;
    }, SPAWNED_UPDATE = 1, PINGED_UPDATE = 2, renderStartTime = -0, commitStartTime = -0, commitEndTime = -0, commitErrors = null, profilerStartTime = -1.1, profilerEffectDuration = -0, componentEffectDuration = -0, componentEffectStartTime = -1.1, componentEffectEndTime = -1.1, componentEffectErrors = null, componentEffectSpawnedUpdate = false, blockingClampTime = -0, blockingUpdateTime = -1.1, blockingUpdateTask = null, blockingUpdateType = 0, blockingUpdateMethodName = null, blockingUpdateComponentName = null, blockingEventTime = -1.1, blockingEventType = null, blockingEventRepeatTime = -1.1, blockingSuspendedTime = -1.1, transitionClampTime = -0, transitionStartTime = -1.1, transitionUpdateTime = -1.1, transitionUpdateType = 0, transitionUpdateTask = null, transitionUpdateMethodName = null, transitionUpdateComponentName = null, transitionEventTime = -1.1, transitionEventType = null, transitionEventRepeatTime = -1.1, transitionSuspendedTime = -1.1, retryClampTime = -0, idleClampTime = -0, animatingLanes = 0, animatingTask = null, yieldReason = 0, yieldStartTime = -1.1, currentUpdateIsNested = false, nestedUpdateScheduled = false, currentEntangledListeners = null, currentEntangledPendingCount = 0, currentEntangledLane = 0, currentEntangledActionThenable = null, prevOnStartTransitionFinish = ReactSharedInternals.S;
    ReactSharedInternals.S = function(transition, returnValue) {
      globalMostRecentTransitionTime = now$1();
      if ("object" === typeof returnValue && null !== returnValue && "function" === typeof returnValue.then) {
        if (0 > transitionStartTime && 0 > transitionUpdateTime) {
          transitionStartTime = now2();
          var newEventTime = resolveEventTimeStamp(), newEventType = resolveEventType();
          if (newEventTime !== transitionEventRepeatTime || newEventType !== transitionEventType)
            transitionEventRepeatTime = -1.1;
          transitionEventTime = newEventTime;
          transitionEventType = newEventType;
        }
        entangleAsyncAction(transition, returnValue);
      }
      null !== prevOnStartTransitionFinish && prevOnStartTransitionFinish(transition, returnValue);
    };
    var resumedCache = createCursor(null), ReactStrictModeWarnings = {
      recordUnsafeLifecycleWarnings: function() {
      },
      flushPendingUnsafeLifecycleWarnings: function() {
      },
      recordLegacyContextWarning: function() {
      },
      flushLegacyContextWarning: function() {
      },
      discardPendingWarnings: function() {
      }
    }, pendingComponentWillMountWarnings = [], pendingUNSAFE_ComponentWillMountWarnings = [], pendingComponentWillReceivePropsWarnings = [], pendingUNSAFE_ComponentWillReceivePropsWarnings = [], pendingComponentWillUpdateWarnings = [], pendingUNSAFE_ComponentWillUpdateWarnings = [], didWarnAboutUnsafeLifecycles = /* @__PURE__ */ new Set();
    ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function(fiber, instance2) {
      didWarnAboutUnsafeLifecycles.has(fiber.type) || ("function" === typeof instance2.componentWillMount && true !== instance2.componentWillMount.__suppressDeprecationWarning && pendingComponentWillMountWarnings.push(fiber), fiber.mode & StrictLegacyMode && "function" === typeof instance2.UNSAFE_componentWillMount && pendingUNSAFE_ComponentWillMountWarnings.push(fiber), "function" === typeof instance2.componentWillReceiveProps && true !== instance2.componentWillReceiveProps.__suppressDeprecationWarning && pendingComponentWillReceivePropsWarnings.push(fiber), fiber.mode & StrictLegacyMode && "function" === typeof instance2.UNSAFE_componentWillReceiveProps && pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber), "function" === typeof instance2.componentWillUpdate && true !== instance2.componentWillUpdate.__suppressDeprecationWarning && pendingComponentWillUpdateWarnings.push(fiber), fiber.mode & StrictLegacyMode && "function" === typeof instance2.UNSAFE_componentWillUpdate && pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber));
    };
    ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function() {
      var componentWillMountUniqueNames = /* @__PURE__ */ new Set();
      0 < pendingComponentWillMountWarnings.length && (pendingComponentWillMountWarnings.forEach(function(fiber) {
        componentWillMountUniqueNames.add(
          getComponentNameFromFiber(fiber) || "Component"
        );
        didWarnAboutUnsafeLifecycles.add(fiber.type);
      }), pendingComponentWillMountWarnings = []);
      var UNSAFE_componentWillMountUniqueNames = /* @__PURE__ */ new Set();
      0 < pendingUNSAFE_ComponentWillMountWarnings.length && (pendingUNSAFE_ComponentWillMountWarnings.forEach(function(fiber) {
        UNSAFE_componentWillMountUniqueNames.add(
          getComponentNameFromFiber(fiber) || "Component"
        );
        didWarnAboutUnsafeLifecycles.add(fiber.type);
      }), pendingUNSAFE_ComponentWillMountWarnings = []);
      var componentWillReceivePropsUniqueNames = /* @__PURE__ */ new Set();
      0 < pendingComponentWillReceivePropsWarnings.length && (pendingComponentWillReceivePropsWarnings.forEach(function(fiber) {
        componentWillReceivePropsUniqueNames.add(
          getComponentNameFromFiber(fiber) || "Component"
        );
        didWarnAboutUnsafeLifecycles.add(fiber.type);
      }), pendingComponentWillReceivePropsWarnings = []);
      var UNSAFE_componentWillReceivePropsUniqueNames = /* @__PURE__ */ new Set();
      0 < pendingUNSAFE_ComponentWillReceivePropsWarnings.length && (pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(
        function(fiber) {
          UNSAFE_componentWillReceivePropsUniqueNames.add(
            getComponentNameFromFiber(fiber) || "Component"
          );
          didWarnAboutUnsafeLifecycles.add(fiber.type);
        }
      ), pendingUNSAFE_ComponentWillReceivePropsWarnings = []);
      var componentWillUpdateUniqueNames = /* @__PURE__ */ new Set();
      0 < pendingComponentWillUpdateWarnings.length && (pendingComponentWillUpdateWarnings.forEach(function(fiber) {
        componentWillUpdateUniqueNames.add(
          getComponentNameFromFiber(fiber) || "Component"
        );
        didWarnAboutUnsafeLifecycles.add(fiber.type);
      }), pendingComponentWillUpdateWarnings = []);
      var UNSAFE_componentWillUpdateUniqueNames = /* @__PURE__ */ new Set();
      0 < pendingUNSAFE_ComponentWillUpdateWarnings.length && (pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function(fiber) {
        UNSAFE_componentWillUpdateUniqueNames.add(
          getComponentNameFromFiber(fiber) || "Component"
        );
        didWarnAboutUnsafeLifecycles.add(fiber.type);
      }), pendingUNSAFE_ComponentWillUpdateWarnings = []);
      if (0 < UNSAFE_componentWillMountUniqueNames.size) {
        var sortedNames = setToSortedString(
          UNSAFE_componentWillMountUniqueNames
        );
        console.error(
          "Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. See https://react.dev/link/unsafe-component-lifecycles for details.\n\n* Move code with side effects to componentDidMount, and set initial state in the constructor.\n\nPlease update the following components: %s",
          sortedNames
        );
      }
      0 < UNSAFE_componentWillReceivePropsUniqueNames.size && (sortedNames = setToSortedString(
        UNSAFE_componentWillReceivePropsUniqueNames
      ), console.error(
        "Using UNSAFE_componentWillReceiveProps in strict mode is not recommended and may indicate bugs in your code. See https://react.dev/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n* If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://react.dev/link/derived-state\n\nPlease update the following components: %s",
        sortedNames
      ));
      0 < UNSAFE_componentWillUpdateUniqueNames.size && (sortedNames = setToSortedString(
        UNSAFE_componentWillUpdateUniqueNames
      ), console.error(
        "Using UNSAFE_componentWillUpdate in strict mode is not recommended and may indicate bugs in your code. See https://react.dev/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n\nPlease update the following components: %s",
        sortedNames
      ));
      0 < componentWillMountUniqueNames.size && (sortedNames = setToSortedString(componentWillMountUniqueNames), console.warn(
        "componentWillMount has been renamed, and is not recommended for use. See https://react.dev/link/unsafe-component-lifecycles for details.\n\n* Move code with side effects to componentDidMount, and set initial state in the constructor.\n* Rename componentWillMount to UNSAFE_componentWillMount to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n\nPlease update the following components: %s",
        sortedNames
      ));
      0 < componentWillReceivePropsUniqueNames.size && (sortedNames = setToSortedString(
        componentWillReceivePropsUniqueNames
      ), console.warn(
        "componentWillReceiveProps has been renamed, and is not recommended for use. See https://react.dev/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n* If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://react.dev/link/derived-state\n* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n\nPlease update the following components: %s",
        sortedNames
      ));
      0 < componentWillUpdateUniqueNames.size && (sortedNames = setToSortedString(componentWillUpdateUniqueNames), console.warn(
        "componentWillUpdate has been renamed, and is not recommended for use. See https://react.dev/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n\nPlease update the following components: %s",
        sortedNames
      ));
    };
    var pendingLegacyContextWarning = /* @__PURE__ */ new Map(), didWarnAboutLegacyContext = /* @__PURE__ */ new Set();
    ReactStrictModeWarnings.recordLegacyContextWarning = function(fiber, instance2) {
      var strictRoot = null;
      for (var node2 = fiber; null !== node2; )
        node2.mode & StrictLegacyMode && (strictRoot = node2), node2 = node2.return;
      null === strictRoot ? console.error(
        "Expected to find a StrictMode component in a strict mode tree. This error is likely caused by a bug in React. Please file an issue."
      ) : !didWarnAboutLegacyContext.has(fiber.type) && (node2 = pendingLegacyContextWarning.get(strictRoot), null != fiber.type.contextTypes || null != fiber.type.childContextTypes || null !== instance2 && "function" === typeof instance2.getChildContext) && (void 0 === node2 && (node2 = [], pendingLegacyContextWarning.set(strictRoot, node2)), node2.push(fiber));
    };
    ReactStrictModeWarnings.flushLegacyContextWarning = function() {
      pendingLegacyContextWarning.forEach(function(fiberArray) {
        if (0 !== fiberArray.length) {
          var firstFiber = fiberArray[0], uniqueNames = /* @__PURE__ */ new Set();
          fiberArray.forEach(function(fiber) {
            uniqueNames.add(getComponentNameFromFiber(fiber) || "Component");
            didWarnAboutLegacyContext.add(fiber.type);
          });
          var sortedNames = setToSortedString(uniqueNames);
          runWithFiberInDEV(firstFiber, function() {
            console.error(
              "Legacy context API has been detected within a strict-mode tree.\n\nThe old API will be supported in all 16.x releases, but applications using it should migrate to the new version.\n\nPlease update the following components: %s\n\nLearn more about this warning here: https://react.dev/link/legacy-context",
              sortedNames
            );
          });
        }
      });
    };
    ReactStrictModeWarnings.discardPendingWarnings = function() {
      pendingComponentWillMountWarnings = [];
      pendingUNSAFE_ComponentWillMountWarnings = [];
      pendingComponentWillReceivePropsWarnings = [];
      pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
      pendingComponentWillUpdateWarnings = [];
      pendingUNSAFE_ComponentWillUpdateWarnings = [];
      pendingLegacyContextWarning = /* @__PURE__ */ new Map();
    };
    var callComponent = {
      react_stack_bottom_frame: function(Component2, props, secondArg) {
        var wasRendering = isRendering;
        isRendering = true;
        try {
          return Component2(props, secondArg);
        } finally {
          isRendering = wasRendering;
        }
      }
    }, callComponentInDEV = callComponent.react_stack_bottom_frame.bind(callComponent), callRender = {
      react_stack_bottom_frame: function(instance2) {
        var wasRendering = isRendering;
        isRendering = true;
        try {
          return instance2.render();
        } finally {
          isRendering = wasRendering;
        }
      }
    }, callRenderInDEV = callRender.react_stack_bottom_frame.bind(callRender), callComponentDidMount = {
      react_stack_bottom_frame: function(finishedWork, instance2) {
        try {
          instance2.componentDidMount();
        } catch (error2) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error2);
        }
      }
    }, callComponentDidMountInDEV = callComponentDidMount.react_stack_bottom_frame.bind(
      callComponentDidMount
    ), callComponentDidUpdate = {
      react_stack_bottom_frame: function(finishedWork, instance2, prevProps, prevState, snapshot) {
        try {
          instance2.componentDidUpdate(prevProps, prevState, snapshot);
        } catch (error2) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error2);
        }
      }
    }, callComponentDidUpdateInDEV = callComponentDidUpdate.react_stack_bottom_frame.bind(
      callComponentDidUpdate
    ), callComponentDidCatch = {
      react_stack_bottom_frame: function(instance2, errorInfo) {
        var stack2 = errorInfo.stack;
        instance2.componentDidCatch(errorInfo.value, {
          componentStack: null !== stack2 ? stack2 : ""
        });
      }
    }, callComponentDidCatchInDEV = callComponentDidCatch.react_stack_bottom_frame.bind(
      callComponentDidCatch
    ), callComponentWillUnmount = {
      react_stack_bottom_frame: function(current22, nearestMountedAncestor, instance2) {
        try {
          instance2.componentWillUnmount();
        } catch (error2) {
          captureCommitPhaseError(current22, nearestMountedAncestor, error2);
        }
      }
    }, callComponentWillUnmountInDEV = callComponentWillUnmount.react_stack_bottom_frame.bind(
      callComponentWillUnmount
    ), callCreate = {
      react_stack_bottom_frame: function(effect2) {
        var create2 = effect2.create;
        effect2 = effect2.inst;
        create2 = create2();
        return effect2.destroy = create2;
      }
    }, callCreateInDEV = callCreate.react_stack_bottom_frame.bind(callCreate), callDestroy = {
      react_stack_bottom_frame: function(current22, nearestMountedAncestor, destroy2) {
        try {
          destroy2();
        } catch (error2) {
          captureCommitPhaseError(current22, nearestMountedAncestor, error2);
        }
      }
    }, callDestroyInDEV = callDestroy.react_stack_bottom_frame.bind(callDestroy), callLazyInit = {
      react_stack_bottom_frame: function(lazy) {
        var init = lazy._init;
        return init(lazy._payload);
      }
    }, callLazyInitInDEV = callLazyInit.react_stack_bottom_frame.bind(callLazyInit), SuspenseException = Error(
      "Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`."
    ), SuspenseyCommitException = Error(
      "Suspense Exception: This is not a real error, and should not leak into userspace. If you're seeing this, it's likely a bug in React."
    ), SuspenseActionException = Error(
      "Suspense Exception: This is not a real error! It's an implementation detail of `useActionState` to interrupt the current render. You must either rethrow it immediately, or move the `useActionState` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary."
    ), noopSuspenseyCommitThenable = {
      then: function() {
        console.error(
          'Internal React error: A listener was unexpectedly attached to a "noop" thenable. This is a bug in React. Please file an issue.'
        );
      }
    }, suspendedThenable = null, needsToResetSuspendedThenableDEV = false, thenableState$1 = null, thenableIndexCounter$1 = 0, currentDebugInfo = null, didWarnAboutMaps;
    var didWarnAboutGenerators = didWarnAboutMaps = false;
    var ownerHasKeyUseWarning = {};
    var ownerHasFunctionTypeWarning = {};
    var ownerHasSymbolTypeWarning = {};
    warnForMissingKey = function(returnFiber, workInProgress2, child) {
      if (null !== child && "object" === typeof child && child._store && (!child._store.validated && null == child.key || 2 === child._store.validated)) {
        if ("object" !== typeof child._store)
          throw Error(
            "React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue."
          );
        child._store.validated = 1;
        var componentName2 = getComponentNameFromFiber(returnFiber), componentKey = componentName2 || "null";
        if (!ownerHasKeyUseWarning[componentKey]) {
          ownerHasKeyUseWarning[componentKey] = true;
          child = child._owner;
          returnFiber = returnFiber._debugOwner;
          var currentComponentErrorInfo = "";
          returnFiber && "number" === typeof returnFiber.tag && (componentKey = getComponentNameFromFiber(returnFiber)) && (currentComponentErrorInfo = "\n\nCheck the render method of `" + componentKey + "`.");
          currentComponentErrorInfo || componentName2 && (currentComponentErrorInfo = "\n\nCheck the top-level render call using <" + componentName2 + ">.");
          var childOwnerAppendix = "";
          null != child && returnFiber !== child && (componentName2 = null, "number" === typeof child.tag ? componentName2 = getComponentNameFromFiber(child) : "string" === typeof child.name && (componentName2 = child.name), componentName2 && (childOwnerAppendix = " It was passed a child from " + componentName2 + "."));
          runWithFiberInDEV(workInProgress2, function() {
            console.error(
              'Each child in a list should have a unique "key" prop.%s%s See https://react.dev/link/warning-keys for more information.',
              currentComponentErrorInfo,
              childOwnerAppendix
            );
          });
        }
      }
    };
    var reconcileChildFibers = createChildReconciler(true), mountChildFibers = createChildReconciler(false), UpdateState = 0, ReplaceState = 1, ForceUpdate = 2, CaptureUpdate = 3, hasForceUpdate = false;
    var didWarnUpdateInsideUpdate = false;
    var currentlyProcessingQueue = null;
    var didReadFromEntangledAsyncAction = false, currentTreeHiddenStackCursor = createCursor(null), prevEntangledRenderLanesCursor = createCursor(0), suspenseHandlerStackCursor = createCursor(null), shellBoundary = null, SubtreeSuspenseContextMask = 1, ForceSuspenseFallback = 2, suspenseStackCursor = createCursor(0), NoFlags = 0, HasEffect = 1, Insertion = 2, Layout = 4, Passive = 8, didWarnUncachedGetSnapshot;
    var didWarnAboutMismatchedHooksForComponent = /* @__PURE__ */ new Set();
    var didWarnAboutUseWrappedInTryCatch = /* @__PURE__ */ new Set();
    var didWarnAboutAsyncClientComponent = /* @__PURE__ */ new Set();
    var didWarnAboutUseFormState = /* @__PURE__ */ new Set();
    var renderLanes = 0, currentlyRenderingFiber = null, currentHook = null, workInProgressHook = null, didScheduleRenderPhaseUpdate = false, didScheduleRenderPhaseUpdateDuringThisPass = false, shouldDoubleInvokeUserFnsInHooksDEV = false, localIdCounter = 0, thenableIndexCounter = 0, thenableState = null, globalClientIdCounter = 0, RE_RENDER_LIMIT = 25, currentHookNameInDev = null, hookTypesDev = null, hookTypesUpdateIndexDev = -1, ignorePreviousDependencies = false, ContextOnlyDispatcher = {
      readContext,
      use: use2,
      useCallback: throwInvalidHookError,
      useContext: throwInvalidHookError,
      useEffect: throwInvalidHookError,
      useImperativeHandle: throwInvalidHookError,
      useLayoutEffect: throwInvalidHookError,
      useInsertionEffect: throwInvalidHookError,
      useMemo: throwInvalidHookError,
      useReducer: throwInvalidHookError,
      useRef: throwInvalidHookError,
      useState: throwInvalidHookError,
      useDebugValue: throwInvalidHookError,
      useDeferredValue: throwInvalidHookError,
      useTransition: throwInvalidHookError,
      useSyncExternalStore: throwInvalidHookError,
      useId: throwInvalidHookError,
      useHostTransitionStatus: throwInvalidHookError,
      useFormState: throwInvalidHookError,
      useActionState: throwInvalidHookError,
      useOptimistic: throwInvalidHookError,
      useMemoCache: throwInvalidHookError,
      useCacheRefresh: throwInvalidHookError
    };
    ContextOnlyDispatcher.useEffectEvent = throwInvalidHookError;
    var HooksDispatcherOnMountInDEV = null, HooksDispatcherOnMountWithHookTypesInDEV = null, HooksDispatcherOnUpdateInDEV = null, HooksDispatcherOnRerenderInDEV = null, InvalidNestedHooksDispatcherOnMountInDEV = null, InvalidNestedHooksDispatcherOnUpdateInDEV = null, InvalidNestedHooksDispatcherOnRerenderInDEV = null;
    HooksDispatcherOnMountInDEV = {
      readContext: function(context) {
        return readContext(context);
      },
      use: use2,
      useCallback: function(callback, deps) {
        currentHookNameInDev = "useCallback";
        mountHookTypesDev();
        checkDepsAreArrayDev(deps);
        return mountCallback(callback, deps);
      },
      useContext: function(context) {
        currentHookNameInDev = "useContext";
        mountHookTypesDev();
        return readContext(context);
      },
      useEffect: function(create2, deps) {
        currentHookNameInDev = "useEffect";
        mountHookTypesDev();
        checkDepsAreArrayDev(deps);
        return mountEffect(create2, deps);
      },
      useImperativeHandle: function(ref2, create2, deps) {
        currentHookNameInDev = "useImperativeHandle";
        mountHookTypesDev();
        checkDepsAreArrayDev(deps);
        return mountImperativeHandle(ref2, create2, deps);
      },
      useInsertionEffect: function(create2, deps) {
        currentHookNameInDev = "useInsertionEffect";
        mountHookTypesDev();
        checkDepsAreArrayDev(deps);
        mountEffectImpl(4, Insertion, create2, deps);
      },
      useLayoutEffect: function(create2, deps) {
        currentHookNameInDev = "useLayoutEffect";
        mountHookTypesDev();
        checkDepsAreArrayDev(deps);
        return mountLayoutEffect(create2, deps);
      },
      useMemo: function(create2, deps) {
        currentHookNameInDev = "useMemo";
        mountHookTypesDev();
        checkDepsAreArrayDev(deps);
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
        try {
          return mountMemo(create2, deps);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useReducer: function(reducer, initialArg, init) {
        currentHookNameInDev = "useReducer";
        mountHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
        try {
          return mountReducer(reducer, initialArg, init);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useRef: function(initialValue) {
        currentHookNameInDev = "useRef";
        mountHookTypesDev();
        return mountRef(initialValue);
      },
      useState: function(initialState) {
        currentHookNameInDev = "useState";
        mountHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
        try {
          return mountState(initialState);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useDebugValue: function() {
        currentHookNameInDev = "useDebugValue";
        mountHookTypesDev();
      },
      useDeferredValue: function(value2, initialValue) {
        currentHookNameInDev = "useDeferredValue";
        mountHookTypesDev();
        return mountDeferredValue(value2, initialValue);
      },
      useTransition: function() {
        currentHookNameInDev = "useTransition";
        mountHookTypesDev();
        return mountTransition();
      },
      useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
        currentHookNameInDev = "useSyncExternalStore";
        mountHookTypesDev();
        return mountSyncExternalStore(
          subscribe,
          getSnapshot,
          getServerSnapshot
        );
      },
      useId: function() {
        currentHookNameInDev = "useId";
        mountHookTypesDev();
        return mountId();
      },
      useFormState: function(action, initialState) {
        currentHookNameInDev = "useFormState";
        mountHookTypesDev();
        warnOnUseFormStateInDev();
        return mountActionState(action, initialState);
      },
      useActionState: function(action, initialState) {
        currentHookNameInDev = "useActionState";
        mountHookTypesDev();
        return mountActionState(action, initialState);
      },
      useOptimistic: function(passthrough) {
        currentHookNameInDev = "useOptimistic";
        mountHookTypesDev();
        return mountOptimistic(passthrough);
      },
      useHostTransitionStatus,
      useMemoCache,
      useCacheRefresh: function() {
        currentHookNameInDev = "useCacheRefresh";
        mountHookTypesDev();
        return mountRefresh();
      },
      useEffectEvent: function(callback) {
        currentHookNameInDev = "useEffectEvent";
        mountHookTypesDev();
        return mountEvent(callback);
      }
    };
    HooksDispatcherOnMountWithHookTypesInDEV = {
      readContext: function(context) {
        return readContext(context);
      },
      use: use2,
      useCallback: function(callback, deps) {
        currentHookNameInDev = "useCallback";
        updateHookTypesDev();
        return mountCallback(callback, deps);
      },
      useContext: function(context) {
        currentHookNameInDev = "useContext";
        updateHookTypesDev();
        return readContext(context);
      },
      useEffect: function(create2, deps) {
        currentHookNameInDev = "useEffect";
        updateHookTypesDev();
        return mountEffect(create2, deps);
      },
      useImperativeHandle: function(ref2, create2, deps) {
        currentHookNameInDev = "useImperativeHandle";
        updateHookTypesDev();
        return mountImperativeHandle(ref2, create2, deps);
      },
      useInsertionEffect: function(create2, deps) {
        currentHookNameInDev = "useInsertionEffect";
        updateHookTypesDev();
        mountEffectImpl(4, Insertion, create2, deps);
      },
      useLayoutEffect: function(create2, deps) {
        currentHookNameInDev = "useLayoutEffect";
        updateHookTypesDev();
        return mountLayoutEffect(create2, deps);
      },
      useMemo: function(create2, deps) {
        currentHookNameInDev = "useMemo";
        updateHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
        try {
          return mountMemo(create2, deps);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useReducer: function(reducer, initialArg, init) {
        currentHookNameInDev = "useReducer";
        updateHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
        try {
          return mountReducer(reducer, initialArg, init);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useRef: function(initialValue) {
        currentHookNameInDev = "useRef";
        updateHookTypesDev();
        return mountRef(initialValue);
      },
      useState: function(initialState) {
        currentHookNameInDev = "useState";
        updateHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
        try {
          return mountState(initialState);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useDebugValue: function() {
        currentHookNameInDev = "useDebugValue";
        updateHookTypesDev();
      },
      useDeferredValue: function(value2, initialValue) {
        currentHookNameInDev = "useDeferredValue";
        updateHookTypesDev();
        return mountDeferredValue(value2, initialValue);
      },
      useTransition: function() {
        currentHookNameInDev = "useTransition";
        updateHookTypesDev();
        return mountTransition();
      },
      useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
        currentHookNameInDev = "useSyncExternalStore";
        updateHookTypesDev();
        return mountSyncExternalStore(
          subscribe,
          getSnapshot,
          getServerSnapshot
        );
      },
      useId: function() {
        currentHookNameInDev = "useId";
        updateHookTypesDev();
        return mountId();
      },
      useActionState: function(action, initialState) {
        currentHookNameInDev = "useActionState";
        updateHookTypesDev();
        return mountActionState(action, initialState);
      },
      useFormState: function(action, initialState) {
        currentHookNameInDev = "useFormState";
        updateHookTypesDev();
        warnOnUseFormStateInDev();
        return mountActionState(action, initialState);
      },
      useOptimistic: function(passthrough) {
        currentHookNameInDev = "useOptimistic";
        updateHookTypesDev();
        return mountOptimistic(passthrough);
      },
      useHostTransitionStatus,
      useMemoCache,
      useCacheRefresh: function() {
        currentHookNameInDev = "useCacheRefresh";
        updateHookTypesDev();
        return mountRefresh();
      },
      useEffectEvent: function(callback) {
        currentHookNameInDev = "useEffectEvent";
        updateHookTypesDev();
        return mountEvent(callback);
      }
    };
    HooksDispatcherOnUpdateInDEV = {
      readContext: function(context) {
        return readContext(context);
      },
      use: use2,
      useCallback: function(callback, deps) {
        currentHookNameInDev = "useCallback";
        updateHookTypesDev();
        return updateCallback(callback, deps);
      },
      useContext: function(context) {
        currentHookNameInDev = "useContext";
        updateHookTypesDev();
        return readContext(context);
      },
      useEffect: function(create2, deps) {
        currentHookNameInDev = "useEffect";
        updateHookTypesDev();
        updateEffectImpl(2048, Passive, create2, deps);
      },
      useImperativeHandle: function(ref2, create2, deps) {
        currentHookNameInDev = "useImperativeHandle";
        updateHookTypesDev();
        return updateImperativeHandle(ref2, create2, deps);
      },
      useInsertionEffect: function(create2, deps) {
        currentHookNameInDev = "useInsertionEffect";
        updateHookTypesDev();
        return updateEffectImpl(4, Insertion, create2, deps);
      },
      useLayoutEffect: function(create2, deps) {
        currentHookNameInDev = "useLayoutEffect";
        updateHookTypesDev();
        return updateEffectImpl(4, Layout, create2, deps);
      },
      useMemo: function(create2, deps) {
        currentHookNameInDev = "useMemo";
        updateHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
        try {
          return updateMemo(create2, deps);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useReducer: function(reducer, initialArg, init) {
        currentHookNameInDev = "useReducer";
        updateHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
        try {
          return updateReducer(reducer, initialArg, init);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useRef: function() {
        currentHookNameInDev = "useRef";
        updateHookTypesDev();
        return updateWorkInProgressHook().memoizedState;
      },
      useState: function() {
        currentHookNameInDev = "useState";
        updateHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
        try {
          return updateReducer(basicStateReducer);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useDebugValue: function() {
        currentHookNameInDev = "useDebugValue";
        updateHookTypesDev();
      },
      useDeferredValue: function(value2, initialValue) {
        currentHookNameInDev = "useDeferredValue";
        updateHookTypesDev();
        return updateDeferredValue(value2, initialValue);
      },
      useTransition: function() {
        currentHookNameInDev = "useTransition";
        updateHookTypesDev();
        return updateTransition();
      },
      useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
        currentHookNameInDev = "useSyncExternalStore";
        updateHookTypesDev();
        return updateSyncExternalStore(
          subscribe,
          getSnapshot,
          getServerSnapshot
        );
      },
      useId: function() {
        currentHookNameInDev = "useId";
        updateHookTypesDev();
        return updateWorkInProgressHook().memoizedState;
      },
      useFormState: function(action) {
        currentHookNameInDev = "useFormState";
        updateHookTypesDev();
        warnOnUseFormStateInDev();
        return updateActionState(action);
      },
      useActionState: function(action) {
        currentHookNameInDev = "useActionState";
        updateHookTypesDev();
        return updateActionState(action);
      },
      useOptimistic: function(passthrough, reducer) {
        currentHookNameInDev = "useOptimistic";
        updateHookTypesDev();
        return updateOptimistic(passthrough, reducer);
      },
      useHostTransitionStatus,
      useMemoCache,
      useCacheRefresh: function() {
        currentHookNameInDev = "useCacheRefresh";
        updateHookTypesDev();
        return updateWorkInProgressHook().memoizedState;
      },
      useEffectEvent: function(callback) {
        currentHookNameInDev = "useEffectEvent";
        updateHookTypesDev();
        return updateEvent(callback);
      }
    };
    HooksDispatcherOnRerenderInDEV = {
      readContext: function(context) {
        return readContext(context);
      },
      use: use2,
      useCallback: function(callback, deps) {
        currentHookNameInDev = "useCallback";
        updateHookTypesDev();
        return updateCallback(callback, deps);
      },
      useContext: function(context) {
        currentHookNameInDev = "useContext";
        updateHookTypesDev();
        return readContext(context);
      },
      useEffect: function(create2, deps) {
        currentHookNameInDev = "useEffect";
        updateHookTypesDev();
        updateEffectImpl(2048, Passive, create2, deps);
      },
      useImperativeHandle: function(ref2, create2, deps) {
        currentHookNameInDev = "useImperativeHandle";
        updateHookTypesDev();
        return updateImperativeHandle(ref2, create2, deps);
      },
      useInsertionEffect: function(create2, deps) {
        currentHookNameInDev = "useInsertionEffect";
        updateHookTypesDev();
        return updateEffectImpl(4, Insertion, create2, deps);
      },
      useLayoutEffect: function(create2, deps) {
        currentHookNameInDev = "useLayoutEffect";
        updateHookTypesDev();
        return updateEffectImpl(4, Layout, create2, deps);
      },
      useMemo: function(create2, deps) {
        currentHookNameInDev = "useMemo";
        updateHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnRerenderInDEV;
        try {
          return updateMemo(create2, deps);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useReducer: function(reducer, initialArg, init) {
        currentHookNameInDev = "useReducer";
        updateHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnRerenderInDEV;
        try {
          return rerenderReducer(reducer, initialArg, init);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useRef: function() {
        currentHookNameInDev = "useRef";
        updateHookTypesDev();
        return updateWorkInProgressHook().memoizedState;
      },
      useState: function() {
        currentHookNameInDev = "useState";
        updateHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnRerenderInDEV;
        try {
          return rerenderReducer(basicStateReducer);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useDebugValue: function() {
        currentHookNameInDev = "useDebugValue";
        updateHookTypesDev();
      },
      useDeferredValue: function(value2, initialValue) {
        currentHookNameInDev = "useDeferredValue";
        updateHookTypesDev();
        return rerenderDeferredValue(value2, initialValue);
      },
      useTransition: function() {
        currentHookNameInDev = "useTransition";
        updateHookTypesDev();
        return rerenderTransition();
      },
      useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
        currentHookNameInDev = "useSyncExternalStore";
        updateHookTypesDev();
        return updateSyncExternalStore(
          subscribe,
          getSnapshot,
          getServerSnapshot
        );
      },
      useId: function() {
        currentHookNameInDev = "useId";
        updateHookTypesDev();
        return updateWorkInProgressHook().memoizedState;
      },
      useFormState: function(action) {
        currentHookNameInDev = "useFormState";
        updateHookTypesDev();
        warnOnUseFormStateInDev();
        return rerenderActionState(action);
      },
      useActionState: function(action) {
        currentHookNameInDev = "useActionState";
        updateHookTypesDev();
        return rerenderActionState(action);
      },
      useOptimistic: function(passthrough, reducer) {
        currentHookNameInDev = "useOptimistic";
        updateHookTypesDev();
        return rerenderOptimistic(passthrough, reducer);
      },
      useHostTransitionStatus,
      useMemoCache,
      useCacheRefresh: function() {
        currentHookNameInDev = "useCacheRefresh";
        updateHookTypesDev();
        return updateWorkInProgressHook().memoizedState;
      },
      useEffectEvent: function(callback) {
        currentHookNameInDev = "useEffectEvent";
        updateHookTypesDev();
        return updateEvent(callback);
      }
    };
    InvalidNestedHooksDispatcherOnMountInDEV = {
      readContext: function(context) {
        warnInvalidContextAccess();
        return readContext(context);
      },
      use: function(usable) {
        warnInvalidHookAccess();
        return use2(usable);
      },
      useCallback: function(callback, deps) {
        currentHookNameInDev = "useCallback";
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountCallback(callback, deps);
      },
      useContext: function(context) {
        currentHookNameInDev = "useContext";
        warnInvalidHookAccess();
        mountHookTypesDev();
        return readContext(context);
      },
      useEffect: function(create2, deps) {
        currentHookNameInDev = "useEffect";
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountEffect(create2, deps);
      },
      useImperativeHandle: function(ref2, create2, deps) {
        currentHookNameInDev = "useImperativeHandle";
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountImperativeHandle(ref2, create2, deps);
      },
      useInsertionEffect: function(create2, deps) {
        currentHookNameInDev = "useInsertionEffect";
        warnInvalidHookAccess();
        mountHookTypesDev();
        mountEffectImpl(4, Insertion, create2, deps);
      },
      useLayoutEffect: function(create2, deps) {
        currentHookNameInDev = "useLayoutEffect";
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountLayoutEffect(create2, deps);
      },
      useMemo: function(create2, deps) {
        currentHookNameInDev = "useMemo";
        warnInvalidHookAccess();
        mountHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
        try {
          return mountMemo(create2, deps);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useReducer: function(reducer, initialArg, init) {
        currentHookNameInDev = "useReducer";
        warnInvalidHookAccess();
        mountHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
        try {
          return mountReducer(reducer, initialArg, init);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useRef: function(initialValue) {
        currentHookNameInDev = "useRef";
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountRef(initialValue);
      },
      useState: function(initialState) {
        currentHookNameInDev = "useState";
        warnInvalidHookAccess();
        mountHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
        try {
          return mountState(initialState);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useDebugValue: function() {
        currentHookNameInDev = "useDebugValue";
        warnInvalidHookAccess();
        mountHookTypesDev();
      },
      useDeferredValue: function(value2, initialValue) {
        currentHookNameInDev = "useDeferredValue";
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountDeferredValue(value2, initialValue);
      },
      useTransition: function() {
        currentHookNameInDev = "useTransition";
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountTransition();
      },
      useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
        currentHookNameInDev = "useSyncExternalStore";
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountSyncExternalStore(
          subscribe,
          getSnapshot,
          getServerSnapshot
        );
      },
      useId: function() {
        currentHookNameInDev = "useId";
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountId();
      },
      useFormState: function(action, initialState) {
        currentHookNameInDev = "useFormState";
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountActionState(action, initialState);
      },
      useActionState: function(action, initialState) {
        currentHookNameInDev = "useActionState";
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountActionState(action, initialState);
      },
      useOptimistic: function(passthrough) {
        currentHookNameInDev = "useOptimistic";
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountOptimistic(passthrough);
      },
      useMemoCache: function(size) {
        warnInvalidHookAccess();
        return useMemoCache(size);
      },
      useHostTransitionStatus,
      useCacheRefresh: function() {
        currentHookNameInDev = "useCacheRefresh";
        mountHookTypesDev();
        return mountRefresh();
      },
      useEffectEvent: function(callback) {
        currentHookNameInDev = "useEffectEvent";
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountEvent(callback);
      }
    };
    InvalidNestedHooksDispatcherOnUpdateInDEV = {
      readContext: function(context) {
        warnInvalidContextAccess();
        return readContext(context);
      },
      use: function(usable) {
        warnInvalidHookAccess();
        return use2(usable);
      },
      useCallback: function(callback, deps) {
        currentHookNameInDev = "useCallback";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateCallback(callback, deps);
      },
      useContext: function(context) {
        currentHookNameInDev = "useContext";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return readContext(context);
      },
      useEffect: function(create2, deps) {
        currentHookNameInDev = "useEffect";
        warnInvalidHookAccess();
        updateHookTypesDev();
        updateEffectImpl(2048, Passive, create2, deps);
      },
      useImperativeHandle: function(ref2, create2, deps) {
        currentHookNameInDev = "useImperativeHandle";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateImperativeHandle(ref2, create2, deps);
      },
      useInsertionEffect: function(create2, deps) {
        currentHookNameInDev = "useInsertionEffect";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateEffectImpl(4, Insertion, create2, deps);
      },
      useLayoutEffect: function(create2, deps) {
        currentHookNameInDev = "useLayoutEffect";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateEffectImpl(4, Layout, create2, deps);
      },
      useMemo: function(create2, deps) {
        currentHookNameInDev = "useMemo";
        warnInvalidHookAccess();
        updateHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
        try {
          return updateMemo(create2, deps);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useReducer: function(reducer, initialArg, init) {
        currentHookNameInDev = "useReducer";
        warnInvalidHookAccess();
        updateHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
        try {
          return updateReducer(reducer, initialArg, init);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useRef: function() {
        currentHookNameInDev = "useRef";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateWorkInProgressHook().memoizedState;
      },
      useState: function() {
        currentHookNameInDev = "useState";
        warnInvalidHookAccess();
        updateHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
        try {
          return updateReducer(basicStateReducer);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useDebugValue: function() {
        currentHookNameInDev = "useDebugValue";
        warnInvalidHookAccess();
        updateHookTypesDev();
      },
      useDeferredValue: function(value2, initialValue) {
        currentHookNameInDev = "useDeferredValue";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateDeferredValue(value2, initialValue);
      },
      useTransition: function() {
        currentHookNameInDev = "useTransition";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateTransition();
      },
      useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
        currentHookNameInDev = "useSyncExternalStore";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateSyncExternalStore(
          subscribe,
          getSnapshot,
          getServerSnapshot
        );
      },
      useId: function() {
        currentHookNameInDev = "useId";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateWorkInProgressHook().memoizedState;
      },
      useFormState: function(action) {
        currentHookNameInDev = "useFormState";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateActionState(action);
      },
      useActionState: function(action) {
        currentHookNameInDev = "useActionState";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateActionState(action);
      },
      useOptimistic: function(passthrough, reducer) {
        currentHookNameInDev = "useOptimistic";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateOptimistic(passthrough, reducer);
      },
      useMemoCache: function(size) {
        warnInvalidHookAccess();
        return useMemoCache(size);
      },
      useHostTransitionStatus,
      useCacheRefresh: function() {
        currentHookNameInDev = "useCacheRefresh";
        updateHookTypesDev();
        return updateWorkInProgressHook().memoizedState;
      },
      useEffectEvent: function(callback) {
        currentHookNameInDev = "useEffectEvent";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateEvent(callback);
      }
    };
    InvalidNestedHooksDispatcherOnRerenderInDEV = {
      readContext: function(context) {
        warnInvalidContextAccess();
        return readContext(context);
      },
      use: function(usable) {
        warnInvalidHookAccess();
        return use2(usable);
      },
      useCallback: function(callback, deps) {
        currentHookNameInDev = "useCallback";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateCallback(callback, deps);
      },
      useContext: function(context) {
        currentHookNameInDev = "useContext";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return readContext(context);
      },
      useEffect: function(create2, deps) {
        currentHookNameInDev = "useEffect";
        warnInvalidHookAccess();
        updateHookTypesDev();
        updateEffectImpl(2048, Passive, create2, deps);
      },
      useImperativeHandle: function(ref2, create2, deps) {
        currentHookNameInDev = "useImperativeHandle";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateImperativeHandle(ref2, create2, deps);
      },
      useInsertionEffect: function(create2, deps) {
        currentHookNameInDev = "useInsertionEffect";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateEffectImpl(4, Insertion, create2, deps);
      },
      useLayoutEffect: function(create2, deps) {
        currentHookNameInDev = "useLayoutEffect";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateEffectImpl(4, Layout, create2, deps);
      },
      useMemo: function(create2, deps) {
        currentHookNameInDev = "useMemo";
        warnInvalidHookAccess();
        updateHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
        try {
          return updateMemo(create2, deps);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useReducer: function(reducer, initialArg, init) {
        currentHookNameInDev = "useReducer";
        warnInvalidHookAccess();
        updateHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
        try {
          return rerenderReducer(reducer, initialArg, init);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useRef: function() {
        currentHookNameInDev = "useRef";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateWorkInProgressHook().memoizedState;
      },
      useState: function() {
        currentHookNameInDev = "useState";
        warnInvalidHookAccess();
        updateHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
        try {
          return rerenderReducer(basicStateReducer);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useDebugValue: function() {
        currentHookNameInDev = "useDebugValue";
        warnInvalidHookAccess();
        updateHookTypesDev();
      },
      useDeferredValue: function(value2, initialValue) {
        currentHookNameInDev = "useDeferredValue";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return rerenderDeferredValue(value2, initialValue);
      },
      useTransition: function() {
        currentHookNameInDev = "useTransition";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return rerenderTransition();
      },
      useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
        currentHookNameInDev = "useSyncExternalStore";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateSyncExternalStore(
          subscribe,
          getSnapshot,
          getServerSnapshot
        );
      },
      useId: function() {
        currentHookNameInDev = "useId";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateWorkInProgressHook().memoizedState;
      },
      useFormState: function(action) {
        currentHookNameInDev = "useFormState";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return rerenderActionState(action);
      },
      useActionState: function(action) {
        currentHookNameInDev = "useActionState";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return rerenderActionState(action);
      },
      useOptimistic: function(passthrough, reducer) {
        currentHookNameInDev = "useOptimistic";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return rerenderOptimistic(passthrough, reducer);
      },
      useMemoCache: function(size) {
        warnInvalidHookAccess();
        return useMemoCache(size);
      },
      useHostTransitionStatus,
      useCacheRefresh: function() {
        currentHookNameInDev = "useCacheRefresh";
        updateHookTypesDev();
        return updateWorkInProgressHook().memoizedState;
      },
      useEffectEvent: function(callback) {
        currentHookNameInDev = "useEffectEvent";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateEvent(callback);
      }
    };
    var fakeInternalInstance = {};
    var didWarnAboutStateAssignmentForComponent = /* @__PURE__ */ new Set();
    var didWarnAboutUninitializedState = /* @__PURE__ */ new Set();
    var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = /* @__PURE__ */ new Set();
    var didWarnAboutLegacyLifecyclesAndDerivedState = /* @__PURE__ */ new Set();
    var didWarnAboutDirectlyAssigningPropsToState = /* @__PURE__ */ new Set();
    var didWarnAboutUndefinedDerivedState = /* @__PURE__ */ new Set();
    var didWarnAboutContextTypes$1 = /* @__PURE__ */ new Set();
    var didWarnAboutChildContextTypes = /* @__PURE__ */ new Set();
    var didWarnAboutInvalidateContextType = /* @__PURE__ */ new Set();
    var didWarnOnInvalidCallback = /* @__PURE__ */ new Set();
    Object.freeze(fakeInternalInstance);
    var classComponentUpdater = {
      enqueueSetState: function(inst, payload, callback) {
        inst = inst._reactInternals;
        var lane = requestUpdateLane(inst), update2 = createUpdate(lane);
        update2.payload = payload;
        void 0 !== callback && null !== callback && (warnOnInvalidCallback(callback), update2.callback = callback);
        payload = enqueueUpdate(inst, update2, lane);
        null !== payload && (startUpdateTimerByLane(lane, "this.setState()", inst), scheduleUpdateOnFiber(payload, inst, lane), entangleTransitions(payload, inst, lane));
      },
      enqueueReplaceState: function(inst, payload, callback) {
        inst = inst._reactInternals;
        var lane = requestUpdateLane(inst), update2 = createUpdate(lane);
        update2.tag = ReplaceState;
        update2.payload = payload;
        void 0 !== callback && null !== callback && (warnOnInvalidCallback(callback), update2.callback = callback);
        payload = enqueueUpdate(inst, update2, lane);
        null !== payload && (startUpdateTimerByLane(lane, "this.replaceState()", inst), scheduleUpdateOnFiber(payload, inst, lane), entangleTransitions(payload, inst, lane));
      },
      enqueueForceUpdate: function(inst, callback) {
        inst = inst._reactInternals;
        var lane = requestUpdateLane(inst), update2 = createUpdate(lane);
        update2.tag = ForceUpdate;
        void 0 !== callback && null !== callback && (warnOnInvalidCallback(callback), update2.callback = callback);
        callback = enqueueUpdate(inst, update2, lane);
        null !== callback && (startUpdateTimerByLane(lane, "this.forceUpdate()", inst), scheduleUpdateOnFiber(callback, inst, lane), entangleTransitions(callback, inst, lane));
      }
    }, componentName = null, errorBoundaryName = null, SelectiveHydrationException = Error(
      "This is not a real error. It's an implementation detail of React's selective hydration feature. If this leaks into userspace, it's a bug in React. Please file an issue."
    ), didReceiveUpdate = false;
    var didWarnAboutBadClass = {};
    var didWarnAboutContextTypeOnFunctionComponent = {};
    var didWarnAboutContextTypes = {};
    var didWarnAboutGetDerivedStateOnFunctionComponent = {};
    var didWarnAboutReassigningProps = false;
    var didWarnAboutRevealOrder = {};
    var didWarnAboutTailOptions = {};
    var SUSPENDED_MARKER = {
      dehydrated: null,
      treeContext: null,
      retryLane: 0,
      hydrationErrors: null
    }, hasWarnedAboutUsingNoValuePropOnContextProvider = false, didWarnAboutUndefinedSnapshotBeforeUpdate = null;
    didWarnAboutUndefinedSnapshotBeforeUpdate = /* @__PURE__ */ new Set();
    var offscreenSubtreeIsHidden = false, offscreenSubtreeWasHidden = false, needsFormReset = false, PossiblyWeakSet = "function" === typeof WeakSet ? WeakSet : Set, nextEffect = null, inProgressLanes = null, inProgressRoot = null, hostParent = null, hostParentIsContainer = false, currentHoistableRoot = null, inHydratedSubtree = false, suspenseyCommitFlag = 8192, DefaultAsyncDispatcher = {
      getCacheForType: function(resourceType) {
        var cache = readContext(CacheContext), cacheForType = cache.data.get(resourceType);
        void 0 === cacheForType && (cacheForType = resourceType(), cache.data.set(resourceType, cacheForType));
        return cacheForType;
      },
      cacheSignal: function() {
        return readContext(CacheContext).controller.signal;
      },
      getOwner: function() {
        return current3;
      }
    };
    if ("function" === typeof Symbol && Symbol.for) {
      var symbolFor = Symbol.for;
      symbolFor("selector.component");
      symbolFor("selector.has_pseudo_class");
      symbolFor("selector.role");
      symbolFor("selector.test_id");
      symbolFor("selector.text");
    }
    var commitHooks = [], PossiblyWeakMap = "function" === typeof WeakMap ? WeakMap : Map, NoContext = 0, RenderContext = 2, CommitContext = 4, RootInProgress = 0, RootFatalErrored = 1, RootErrored = 2, RootSuspended = 3, RootSuspendedWithDelay = 4, RootSuspendedAtTheShell = 6, RootCompleted = 5, executionContext = NoContext, workInProgressRoot = null, workInProgress = null, workInProgressRootRenderLanes = 0, NotSuspended = 0, SuspendedOnError = 1, SuspendedOnData = 2, SuspendedOnImmediate = 3, SuspendedOnInstance = 4, SuspendedOnInstanceAndReadyToContinue = 5, SuspendedOnDeprecatedThrowPromise = 6, SuspendedAndReadyToContinue = 7, SuspendedOnHydration = 8, SuspendedOnAction = 9, workInProgressSuspendedReason = NotSuspended, workInProgressThrownValue = null, workInProgressRootDidSkipSuspendedSiblings = false, workInProgressRootIsPrerendering = false, workInProgressRootDidAttachPingListener = false, entangledRenderLanes = 0, workInProgressRootExitStatus = RootInProgress, workInProgressRootSkippedLanes = 0, workInProgressRootInterleavedUpdatedLanes = 0, workInProgressRootPingedLanes = 0, workInProgressDeferredLane = 0, workInProgressSuspendedRetryLanes = 0, workInProgressRootConcurrentErrors = null, workInProgressRootRecoverableErrors = null, workInProgressRootDidIncludeRecursiveRenderUpdate = false, globalMostRecentFallbackTime = 0, globalMostRecentTransitionTime = 0, FALLBACK_THROTTLE_MS = 300, workInProgressRootRenderTargetTime = Infinity, RENDER_TIMEOUT_MS = 500, workInProgressTransitions = null, workInProgressUpdateTask = null, legacyErrorBoundariesThatAlreadyFailed = null, IMMEDIATE_COMMIT = 0, ABORTED_VIEW_TRANSITION_COMMIT = 1, DELAYED_PASSIVE_COMMIT = 2, ANIMATION_STARTED_COMMIT = 3, NO_PENDING_EFFECTS = 0, PENDING_MUTATION_PHASE = 1, PENDING_LAYOUT_PHASE = 2, PENDING_AFTER_MUTATION_PHASE = 3, PENDING_SPAWNED_WORK = 4, PENDING_PASSIVE_PHASE = 5, pendingEffectsStatus = 0, pendingEffectsRoot = null, pendingFinishedWork = null, pendingEffectsLanes = 0, pendingEffectsRemainingLanes = 0, pendingEffectsRenderEndTime = -0, pendingPassiveTransitions = null, pendingRecoverableErrors = null, pendingSuspendedCommitReason = null, pendingDelayedCommitReason = IMMEDIATE_COMMIT, pendingSuspendedViewTransitionReason = null, NESTED_UPDATE_LIMIT = 50, nestedUpdateCount = 0, rootWithNestedUpdates = null, isFlushingPassiveEffects = false, didScheduleUpdateDuringPassiveEffects = false, NESTED_PASSIVE_UPDATE_LIMIT = 50, nestedPassiveUpdateCount = 0, rootWithPassiveNestedUpdates = null, isRunningInsertionEffect = false, didWarnStateUpdateForNotYetMountedComponent = null, didWarnAboutUpdateInRender = false;
    var didWarnAboutUpdateInRenderForAnotherComponent = /* @__PURE__ */ new Set();
    var fakeActCallbackNode$1 = {}, firstScheduledRoot = null, lastScheduledRoot = null, didScheduleMicrotask = false, didScheduleMicrotask_act = false, mightHavePendingSyncWork = false, isFlushingWork = false, currentEventTransitionLane = 0, fakeActCallbackNode = {};
    (function() {
      for (var i2 = 0; i2 < simpleEventPluginEvents.length; i2++) {
        var eventName = simpleEventPluginEvents[i2], domEventName = eventName.toLowerCase();
        eventName = eventName[0].toUpperCase() + eventName.slice(1);
        registerSimpleEvent(domEventName, "on" + eventName);
      }
      registerSimpleEvent(ANIMATION_END, "onAnimationEnd");
      registerSimpleEvent(ANIMATION_ITERATION, "onAnimationIteration");
      registerSimpleEvent(ANIMATION_START, "onAnimationStart");
      registerSimpleEvent("dblclick", "onDoubleClick");
      registerSimpleEvent("focusin", "onFocus");
      registerSimpleEvent("focusout", "onBlur");
      registerSimpleEvent(TRANSITION_RUN, "onTransitionRun");
      registerSimpleEvent(TRANSITION_START, "onTransitionStart");
      registerSimpleEvent(TRANSITION_CANCEL, "onTransitionCancel");
      registerSimpleEvent(TRANSITION_END, "onTransitionEnd");
    })();
    registerDirectEvent("onMouseEnter", ["mouseout", "mouseover"]);
    registerDirectEvent("onMouseLeave", ["mouseout", "mouseover"]);
    registerDirectEvent("onPointerEnter", ["pointerout", "pointerover"]);
    registerDirectEvent("onPointerLeave", ["pointerout", "pointerover"]);
    registerTwoPhaseEvent(
      "onChange",
      "change click focusin focusout input keydown keyup selectionchange".split(
        " "
      )
    );
    registerTwoPhaseEvent(
      "onSelect",
      "focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(
        " "
      )
    );
    registerTwoPhaseEvent("onBeforeInput", [
      "compositionend",
      "keypress",
      "textInput",
      "paste"
    ]);
    registerTwoPhaseEvent(
      "onCompositionEnd",
      "compositionend focusout keydown keypress keyup mousedown".split(" ")
    );
    registerTwoPhaseEvent(
      "onCompositionStart",
      "compositionstart focusout keydown keypress keyup mousedown".split(" ")
    );
    registerTwoPhaseEvent(
      "onCompositionUpdate",
      "compositionupdate focusout keydown keypress keyup mousedown".split(" ")
    );
    var mediaEventTypes = "abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(
      " "
    ), nonDelegatedEvents = new Set(
      "beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(mediaEventTypes)
    ), listeningMarker = "_reactListening" + Math.random().toString(36).slice(2), didWarnControlledToUncontrolled = false, didWarnUncontrolledToControlled = false, didWarnFormActionType = false, didWarnFormActionName = false, didWarnFormActionTarget = false, didWarnFormActionMethod = false, didWarnPopoverTargetObject = false;
    var didWarnForNewBooleanPropsWithEmptyValue = {};
    var NORMALIZE_NEWLINES_REGEX = /\r\n?/g, NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g, xlinkNamespace = "http://www.w3.org/1999/xlink", xmlNamespace = "http://www.w3.org/XML/1998/namespace", EXPECTED_FORM_ACTION_URL = "javascript:throw new Error('React form unexpectedly submitted.')", SUPPRESS_HYDRATION_WARNING = "suppressHydrationWarning", ACTIVITY_START_DATA = "&", ACTIVITY_END_DATA = "/&", SUSPENSE_START_DATA = "$", SUSPENSE_END_DATA = "/$", SUSPENSE_PENDING_START_DATA = "$?", SUSPENSE_QUEUED_START_DATA = "$~", SUSPENSE_FALLBACK_START_DATA = "$!", PREAMBLE_CONTRIBUTION_HTML = "html", PREAMBLE_CONTRIBUTION_BODY = "body", PREAMBLE_CONTRIBUTION_HEAD = "head", FORM_STATE_IS_MATCHING = "F!", FORM_STATE_IS_NOT_MATCHING = "F", DOCUMENT_READY_STATE_LOADING = "loading", STYLE = "style", HostContextNamespaceNone = 0, HostContextNamespaceSvg = 1, HostContextNamespaceMath = 2, eventsEnabled = null, selectionInformation = null, warnedUnknownTags = { dialog: true, webview: true }, currentPopstateTransitionEvent = null, schedulerEvent = void 0, scheduleTimeout = "function" === typeof setTimeout ? setTimeout : void 0, cancelTimeout = "function" === typeof clearTimeout ? clearTimeout : void 0, noTimeout = -1, localPromise = "function" === typeof Promise ? Promise : void 0, scheduleMicrotask = "function" === typeof queueMicrotask ? queueMicrotask : "undefined" !== typeof localPromise ? function(callback) {
      return localPromise.resolve(null).then(callback).catch(handleErrorInNextTick);
    } : scheduleTimeout, previousHydratableOnEnteringScopedSingleton = null, NotLoaded = 0, Loaded = 1, Errored = 2, Settled = 3, Inserted = 4, preloadPropsMap = /* @__PURE__ */ new Map(), preconnectsSet = /* @__PURE__ */ new Set(), previousDispatcher = ReactDOMSharedInternals.d;
    ReactDOMSharedInternals.d = {
      f: function() {
        var previousWasRendering = previousDispatcher.f(), wasRendering = flushSyncWork$1();
        return previousWasRendering || wasRendering;
      },
      r: function(form) {
        var formInst = getInstanceFromNode(form);
        null !== formInst && 5 === formInst.tag && "form" === formInst.type ? requestFormReset$1(formInst) : previousDispatcher.r(form);
      },
      D: function(href) {
        previousDispatcher.D(href);
        preconnectAs("dns-prefetch", href, null);
      },
      C: function(href, crossOrigin) {
        previousDispatcher.C(href, crossOrigin);
        preconnectAs("preconnect", href, crossOrigin);
      },
      L: function(href, as, options) {
        previousDispatcher.L(href, as, options);
        var ownerDocument = globalDocument;
        if (ownerDocument && href && as) {
          var preloadSelector = 'link[rel="preload"][as="' + escapeSelectorAttributeValueInsideDoubleQuotes(as) + '"]';
          "image" === as ? options && options.imageSrcSet ? (preloadSelector += '[imagesrcset="' + escapeSelectorAttributeValueInsideDoubleQuotes(
            options.imageSrcSet
          ) + '"]', "string" === typeof options.imageSizes && (preloadSelector += '[imagesizes="' + escapeSelectorAttributeValueInsideDoubleQuotes(
            options.imageSizes
          ) + '"]')) : preloadSelector += '[href="' + escapeSelectorAttributeValueInsideDoubleQuotes(href) + '"]' : preloadSelector += '[href="' + escapeSelectorAttributeValueInsideDoubleQuotes(href) + '"]';
          var key2 = preloadSelector;
          switch (as) {
            case "style":
              key2 = getStyleKey(href);
              break;
            case "script":
              key2 = getScriptKey(href);
          }
          preloadPropsMap.has(key2) || (href = assign2(
            {
              rel: "preload",
              href: "image" === as && options && options.imageSrcSet ? void 0 : href,
              as
            },
            options
          ), preloadPropsMap.set(key2, href), null !== ownerDocument.querySelector(preloadSelector) || "style" === as && ownerDocument.querySelector(
            getStylesheetSelectorFromKey(key2)
          ) || "script" === as && ownerDocument.querySelector(getScriptSelectorFromKey(key2)) || (as = ownerDocument.createElement("link"), setInitialProperties(as, "link", href), markNodeAsHoistable(as), ownerDocument.head.appendChild(as)));
        }
      },
      m: function(href, options) {
        previousDispatcher.m(href, options);
        var ownerDocument = globalDocument;
        if (ownerDocument && href) {
          var as = options && "string" === typeof options.as ? options.as : "script", preloadSelector = 'link[rel="modulepreload"][as="' + escapeSelectorAttributeValueInsideDoubleQuotes(as) + '"][href="' + escapeSelectorAttributeValueInsideDoubleQuotes(href) + '"]', key2 = preloadSelector;
          switch (as) {
            case "audioworklet":
            case "paintworklet":
            case "serviceworker":
            case "sharedworker":
            case "worker":
            case "script":
              key2 = getScriptKey(href);
          }
          if (!preloadPropsMap.has(key2) && (href = assign2({ rel: "modulepreload", href }, options), preloadPropsMap.set(key2, href), null === ownerDocument.querySelector(preloadSelector))) {
            switch (as) {
              case "audioworklet":
              case "paintworklet":
              case "serviceworker":
              case "sharedworker":
              case "worker":
              case "script":
                if (ownerDocument.querySelector(getScriptSelectorFromKey(key2)))
                  return;
            }
            as = ownerDocument.createElement("link");
            setInitialProperties(as, "link", href);
            markNodeAsHoistable(as);
            ownerDocument.head.appendChild(as);
          }
        }
      },
      X: function(src, options) {
        previousDispatcher.X(src, options);
        var ownerDocument = globalDocument;
        if (ownerDocument && src) {
          var scripts = getResourcesFromRoot(ownerDocument).hoistableScripts, key2 = getScriptKey(src), resource = scripts.get(key2);
          resource || (resource = ownerDocument.querySelector(
            getScriptSelectorFromKey(key2)
          ), resource || (src = assign2({ src, async: true }, options), (options = preloadPropsMap.get(key2)) && adoptPreloadPropsForScript(src, options), resource = ownerDocument.createElement("script"), markNodeAsHoistable(resource), setInitialProperties(resource, "link", src), ownerDocument.head.appendChild(resource)), resource = {
            type: "script",
            instance: resource,
            count: 1,
            state: null
          }, scripts.set(key2, resource));
        }
      },
      S: function(href, precedence, options) {
        previousDispatcher.S(href, precedence, options);
        var ownerDocument = globalDocument;
        if (ownerDocument && href) {
          var styles2 = getResourcesFromRoot(ownerDocument).hoistableStyles, key2 = getStyleKey(href);
          precedence = precedence || "default";
          var resource = styles2.get(key2);
          if (!resource) {
            var state = { loading: NotLoaded, preload: null };
            if (resource = ownerDocument.querySelector(
              getStylesheetSelectorFromKey(key2)
            ))
              state.loading = Loaded | Inserted;
            else {
              href = assign2(
                {
                  rel: "stylesheet",
                  href,
                  "data-precedence": precedence
                },
                options
              );
              (options = preloadPropsMap.get(key2)) && adoptPreloadPropsForStylesheet(href, options);
              var link2 = resource = ownerDocument.createElement("link");
              markNodeAsHoistable(link2);
              setInitialProperties(link2, "link", href);
              link2._p = new Promise(function(resolve2, reject) {
                link2.onload = resolve2;
                link2.onerror = reject;
              });
              link2.addEventListener("load", function() {
                state.loading |= Loaded;
              });
              link2.addEventListener("error", function() {
                state.loading |= Errored;
              });
              state.loading |= Inserted;
              insertStylesheet(resource, precedence, ownerDocument);
            }
            resource = {
              type: "stylesheet",
              instance: resource,
              count: 1,
              state
            };
            styles2.set(key2, resource);
          }
        }
      },
      M: function(src, options) {
        previousDispatcher.M(src, options);
        var ownerDocument = globalDocument;
        if (ownerDocument && src) {
          var scripts = getResourcesFromRoot(ownerDocument).hoistableScripts, key2 = getScriptKey(src), resource = scripts.get(key2);
          resource || (resource = ownerDocument.querySelector(
            getScriptSelectorFromKey(key2)
          ), resource || (src = assign2({ src, async: true, type: "module" }, options), (options = preloadPropsMap.get(key2)) && adoptPreloadPropsForScript(src, options), resource = ownerDocument.createElement("script"), markNodeAsHoistable(resource), setInitialProperties(resource, "link", src), ownerDocument.head.appendChild(resource)), resource = {
            type: "script",
            instance: resource,
            count: 1,
            state: null
          }, scripts.set(key2, resource));
        }
      }
    };
    var globalDocument = "undefined" === typeof document ? null : document, tagCaches = null, SUSPENSEY_STYLESHEET_TIMEOUT = 6e4, SUSPENSEY_IMAGE_TIMEOUT = 800, SUSPENSEY_IMAGE_TIME_ESTIMATE = 500, estimatedBytesWithinLimit = 0, LAST_PRECEDENCE = null, precedencesByRoot = null, NotPendingTransition = NotPending, HostTransitionContext = {
      $$typeof: REACT_CONTEXT_TYPE,
      Provider: null,
      Consumer: null,
      _currentValue: NotPendingTransition,
      _currentValue2: NotPendingTransition,
      _threadCount: 0
    }, badgeFormat = "%c%s%c", badgeStyle = "background: #e6e6e6;background: light-dark(rgba(0,0,0,0.1), rgba(255,255,255,0.25));color: #000000;color: light-dark(#000000, #ffffff);border-radius: 2px", resetStyle = "", pad3 = " ", bind = Function.prototype.bind;
    var didWarnAboutNestedUpdates = false;
    var overrideHookState = null, overrideHookStateDeletePath = null, overrideHookStateRenamePath = null, overrideProps = null, overridePropsDeletePath = null, overridePropsRenamePath = null, scheduleUpdate = null, scheduleRetry = null, setErrorHandler = null, setSuspenseHandler = null;
    overrideHookState = function(fiber, id2, path, value2) {
      id2 = findHook(fiber, id2);
      null !== id2 && (path = copyWithSetImpl(id2.memoizedState, path, 0, value2), id2.memoizedState = path, id2.baseState = path, fiber.memoizedProps = assign2({}, fiber.memoizedProps), path = enqueueConcurrentRenderForLane(fiber, 2), null !== path && scheduleUpdateOnFiber(path, fiber, 2));
    };
    overrideHookStateDeletePath = function(fiber, id2, path) {
      id2 = findHook(fiber, id2);
      null !== id2 && (path = copyWithDeleteImpl(id2.memoizedState, path, 0), id2.memoizedState = path, id2.baseState = path, fiber.memoizedProps = assign2({}, fiber.memoizedProps), path = enqueueConcurrentRenderForLane(fiber, 2), null !== path && scheduleUpdateOnFiber(path, fiber, 2));
    };
    overrideHookStateRenamePath = function(fiber, id2, oldPath, newPath) {
      id2 = findHook(fiber, id2);
      null !== id2 && (oldPath = copyWithRename(id2.memoizedState, oldPath, newPath), id2.memoizedState = oldPath, id2.baseState = oldPath, fiber.memoizedProps = assign2({}, fiber.memoizedProps), oldPath = enqueueConcurrentRenderForLane(fiber, 2), null !== oldPath && scheduleUpdateOnFiber(oldPath, fiber, 2));
    };
    overrideProps = function(fiber, path, value2) {
      fiber.pendingProps = copyWithSetImpl(fiber.memoizedProps, path, 0, value2);
      fiber.alternate && (fiber.alternate.pendingProps = fiber.pendingProps);
      path = enqueueConcurrentRenderForLane(fiber, 2);
      null !== path && scheduleUpdateOnFiber(path, fiber, 2);
    };
    overridePropsDeletePath = function(fiber, path) {
      fiber.pendingProps = copyWithDeleteImpl(fiber.memoizedProps, path, 0);
      fiber.alternate && (fiber.alternate.pendingProps = fiber.pendingProps);
      path = enqueueConcurrentRenderForLane(fiber, 2);
      null !== path && scheduleUpdateOnFiber(path, fiber, 2);
    };
    overridePropsRenamePath = function(fiber, oldPath, newPath) {
      fiber.pendingProps = copyWithRename(
        fiber.memoizedProps,
        oldPath,
        newPath
      );
      fiber.alternate && (fiber.alternate.pendingProps = fiber.pendingProps);
      oldPath = enqueueConcurrentRenderForLane(fiber, 2);
      null !== oldPath && scheduleUpdateOnFiber(oldPath, fiber, 2);
    };
    scheduleUpdate = function(fiber) {
      var root22 = enqueueConcurrentRenderForLane(fiber, 2);
      null !== root22 && scheduleUpdateOnFiber(root22, fiber, 2);
    };
    scheduleRetry = function(fiber) {
      var lane = claimNextRetryLane(), root22 = enqueueConcurrentRenderForLane(fiber, lane);
      null !== root22 && scheduleUpdateOnFiber(root22, fiber, lane);
    };
    setErrorHandler = function(newShouldErrorImpl) {
      shouldErrorImpl = newShouldErrorImpl;
    };
    setSuspenseHandler = function(newShouldSuspendImpl) {
      shouldSuspendImpl = newShouldSuspendImpl;
    };
    var _enabled = true, return_targetInst = null, hasScheduledReplayAttempt = false, queuedFocus = null, queuedDrag = null, queuedMouse = null, queuedPointers = /* @__PURE__ */ new Map(), queuedPointerCaptures = /* @__PURE__ */ new Map(), queuedExplicitHydrationTargets = [], discreteReplayableEvents = "mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset".split(
      " "
    ), lastScheduledReplayQueue = null;
    ReactDOMHydrationRoot.prototype.render = ReactDOMRoot.prototype.render = function(children2) {
      var root22 = this._internalRoot;
      if (null === root22) throw Error("Cannot update an unmounted root.");
      var args2 = arguments;
      "function" === typeof args2[1] ? console.error(
        "does not support the second callback argument. To execute a side effect after rendering, declare it in a component body with useEffect()."
      ) : isValidContainer(args2[1]) ? console.error(
        "You passed a container to the second argument of root.render(...). You don't need to pass it again since you already passed it to create the root."
      ) : "undefined" !== typeof args2[1] && console.error(
        "You passed a second argument to root.render(...) but it only accepts one argument."
      );
      args2 = children2;
      var current22 = root22.current, lane = requestUpdateLane(current22);
      updateContainerImpl(current22, lane, args2, root22, null, null);
    };
    ReactDOMHydrationRoot.prototype.unmount = ReactDOMRoot.prototype.unmount = function() {
      var args2 = arguments;
      "function" === typeof args2[0] && console.error(
        "does not support a callback argument. To execute a side effect after rendering, declare it in a component body with useEffect()."
      );
      args2 = this._internalRoot;
      if (null !== args2) {
        this._internalRoot = null;
        var container2 = args2.containerInfo;
        (executionContext & (RenderContext | CommitContext)) !== NoContext && console.error(
          "Attempted to synchronously unmount a root while React was already rendering. React cannot finish unmounting the root until the current render has completed, which may lead to a race condition."
        );
        updateContainerImpl(args2.current, 2, null, args2, null, null);
        flushSyncWork$1();
        container2[internalContainerInstanceKey] = null;
      }
    };
    ReactDOMHydrationRoot.prototype.unstable_scheduleHydration = function(target) {
      if (target) {
        var updatePriority = resolveUpdatePriority();
        target = { blockedOn: null, target, priority: updatePriority };
        for (var i2 = 0; i2 < queuedExplicitHydrationTargets.length && 0 !== updatePriority && updatePriority < queuedExplicitHydrationTargets[i2].priority; i2++) ;
        queuedExplicitHydrationTargets.splice(i2, 0, target);
        0 === i2 && attemptExplicitHydrationTarget(target);
      }
    };
    (function() {
      var isomorphicReactPackageVersion = React.version;
      if ("19.2.0" !== isomorphicReactPackageVersion)
        throw Error(
          'Incompatible React versions: The "react" and "react-dom" packages must have the exact same version. Instead got:\n  - react:      ' + (isomorphicReactPackageVersion + "\n  - react-dom:  19.2.0\nLearn more: https://react.dev/warnings/version-mismatch")
        );
    })();
    "function" === typeof Map && null != Map.prototype && "function" === typeof Map.prototype.forEach && "function" === typeof Set && null != Set.prototype && "function" === typeof Set.prototype.clear && "function" === typeof Set.prototype.forEach || console.error(
      "React depends on Map and Set built-in types. Make sure that you load a polyfill in older browsers. https://react.dev/link/react-polyfills"
    );
    ReactDOMSharedInternals.findDOMNode = function(componentOrElement) {
      var fiber = componentOrElement._reactInternals;
      if (void 0 === fiber) {
        if ("function" === typeof componentOrElement.render)
          throw Error("Unable to find node on an unmounted component.");
        componentOrElement = Object.keys(componentOrElement).join(",");
        throw Error(
          "Argument appears to not be a ReactComponent. Keys: " + componentOrElement
        );
      }
      componentOrElement = findCurrentFiberUsingSlowPath(fiber);
      componentOrElement = null !== componentOrElement ? findCurrentHostFiberImpl(componentOrElement) : null;
      componentOrElement = null === componentOrElement ? null : componentOrElement.stateNode;
      return componentOrElement;
    };
    if (!(function() {
      var internals = {
        bundleType: 1,
        version: "19.2.0",
        rendererPackageName: "react-dom",
        currentDispatcherRef: ReactSharedInternals,
        reconcilerVersion: "19.2.0"
      };
      internals.overrideHookState = overrideHookState;
      internals.overrideHookStateDeletePath = overrideHookStateDeletePath;
      internals.overrideHookStateRenamePath = overrideHookStateRenamePath;
      internals.overrideProps = overrideProps;
      internals.overridePropsDeletePath = overridePropsDeletePath;
      internals.overridePropsRenamePath = overridePropsRenamePath;
      internals.scheduleUpdate = scheduleUpdate;
      internals.scheduleRetry = scheduleRetry;
      internals.setErrorHandler = setErrorHandler;
      internals.setSuspenseHandler = setSuspenseHandler;
      internals.scheduleRefresh = scheduleRefresh;
      internals.scheduleRoot = scheduleRoot;
      internals.setRefreshHandler = setRefreshHandler;
      internals.getCurrentFiber = getCurrentFiberForDevTools;
      return injectInternals(internals);
    })() && canUseDOM && window.top === window.self && (-1 < navigator.userAgent.indexOf("Chrome") && -1 === navigator.userAgent.indexOf("Edge") || -1 < navigator.userAgent.indexOf("Firefox"))) {
      var protocol = window.location.protocol;
      /^(https?|file):$/.test(protocol) && console.info(
        "%cDownload the React DevTools for a better development experience: https://react.dev/link/react-devtools" + ("file:" === protocol ? "\nYou might need to use a local HTTP server (instead of file://): https://react.dev/link/react-devtools-faq" : ""),
        "font-weight:bold"
      );
    }
    reactDomClient_development.createRoot = function(container2, options) {
      if (!isValidContainer(container2))
        throw Error("Target container is not a DOM element.");
      warnIfReactDOMContainerInDEV(container2);
      var isStrictMode = false, identifierPrefix = "", onUncaughtError = defaultOnUncaughtError, onCaughtError = defaultOnCaughtError, onRecoverableError = defaultOnRecoverableError;
      null !== options && void 0 !== options && (options.hydrate ? console.warn(
        "hydrate through createRoot is deprecated. Use ReactDOMClient.hydrateRoot(container, <App />) instead."
      ) : "object" === typeof options && null !== options && options.$$typeof === REACT_ELEMENT_TYPE && console.error(
        "You passed a JSX element to createRoot. You probably meant to call root.render instead. Example usage:\n\n  let root = createRoot(domContainer);\n  root.render(<App />);"
      ), true === options.unstable_strictMode && (isStrictMode = true), void 0 !== options.identifierPrefix && (identifierPrefix = options.identifierPrefix), void 0 !== options.onUncaughtError && (onUncaughtError = options.onUncaughtError), void 0 !== options.onCaughtError && (onCaughtError = options.onCaughtError), void 0 !== options.onRecoverableError && (onRecoverableError = options.onRecoverableError));
      options = createFiberRoot(
        container2,
        1,
        false,
        null,
        null,
        isStrictMode,
        identifierPrefix,
        null,
        onUncaughtError,
        onCaughtError,
        onRecoverableError,
        defaultOnDefaultTransitionIndicator
      );
      container2[internalContainerInstanceKey] = options.current;
      listenToAllSupportedEvents(container2);
      return new ReactDOMRoot(options);
    };
    reactDomClient_development.hydrateRoot = function(container2, initialChildren, options) {
      if (!isValidContainer(container2))
        throw Error("Target container is not a DOM element.");
      warnIfReactDOMContainerInDEV(container2);
      void 0 === initialChildren && console.error(
        "Must provide initial children as second argument to hydrateRoot. Example usage: hydrateRoot(domContainer, <App />)"
      );
      var isStrictMode = false, identifierPrefix = "", onUncaughtError = defaultOnUncaughtError, onCaughtError = defaultOnCaughtError, onRecoverableError = defaultOnRecoverableError, formState = null;
      null !== options && void 0 !== options && (true === options.unstable_strictMode && (isStrictMode = true), void 0 !== options.identifierPrefix && (identifierPrefix = options.identifierPrefix), void 0 !== options.onUncaughtError && (onUncaughtError = options.onUncaughtError), void 0 !== options.onCaughtError && (onCaughtError = options.onCaughtError), void 0 !== options.onRecoverableError && (onRecoverableError = options.onRecoverableError), void 0 !== options.formState && (formState = options.formState));
      initialChildren = createFiberRoot(
        container2,
        1,
        true,
        initialChildren,
        null != options ? options : null,
        isStrictMode,
        identifierPrefix,
        formState,
        onUncaughtError,
        onCaughtError,
        onRecoverableError,
        defaultOnDefaultTransitionIndicator
      );
      initialChildren.context = getContextForSubtree(null);
      options = initialChildren.current;
      isStrictMode = requestUpdateLane(options);
      isStrictMode = getBumpedLaneForHydrationByLane(isStrictMode);
      identifierPrefix = createUpdate(isStrictMode);
      identifierPrefix.callback = null;
      enqueueUpdate(options, identifierPrefix, isStrictMode);
      startUpdateTimerByLane(isStrictMode, "hydrateRoot()", null);
      options = isStrictMode;
      initialChildren.current.lanes = options;
      markRootUpdated$1(initialChildren, options);
      ensureRootIsScheduled(initialChildren);
      container2[internalContainerInstanceKey] = initialChildren.current;
      listenToAllSupportedEvents(container2);
      return new ReactDOMHydrationRoot(initialChildren);
    };
    reactDomClient_development.version = "19.2.0";
    "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
  })();
  return reactDomClient_development;
}
var hasRequiredClient;
function requireClient() {
  if (hasRequiredClient) return client.exports;
  hasRequiredClient = 1;
  {
    client.exports = requireReactDomClient_development();
  }
  return client.exports;
}
var clientExports = requireClient();
var Space_Separator = /[\u1680\u2000-\u200A\u202F\u205F\u3000]/;
var ID_Start = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/;
var ID_Continue = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/;
var unicode = {
  Space_Separator,
  ID_Start,
  ID_Continue
};
var util$1 = {
  isSpaceSeparator(c2) {
    return typeof c2 === "string" && unicode.Space_Separator.test(c2);
  },
  isIdStartChar(c2) {
    return typeof c2 === "string" && (c2 >= "a" && c2 <= "z" || c2 >= "A" && c2 <= "Z" || c2 === "$" || c2 === "_" || unicode.ID_Start.test(c2));
  },
  isIdContinueChar(c2) {
    return typeof c2 === "string" && (c2 >= "a" && c2 <= "z" || c2 >= "A" && c2 <= "Z" || c2 >= "0" && c2 <= "9" || c2 === "$" || c2 === "_" || c2 === "‌" || c2 === "‍" || unicode.ID_Continue.test(c2));
  },
  isDigit(c2) {
    return typeof c2 === "string" && /[0-9]/.test(c2);
  },
  isHexDigit(c2) {
    return typeof c2 === "string" && /[0-9A-Fa-f]/.test(c2);
  }
};
let source$1;
let parseState;
let stack;
let pos;
let line;
let column$1;
let token;
let key$2;
let root$4;
var parse$5 = function parse(text2, reviver) {
  source$1 = String(text2);
  parseState = "start";
  stack = [];
  pos = 0;
  line = 1;
  column$1 = 0;
  token = void 0;
  key$2 = void 0;
  root$4 = void 0;
  do {
    token = lex();
    parseStates[parseState]();
  } while (token.type !== "eof");
  if (typeof reviver === "function") {
    return internalize({ "": root$4 }, "", reviver);
  }
  return root$4;
};
function internalize(holder, name2, reviver) {
  const value2 = holder[name2];
  if (value2 != null && typeof value2 === "object") {
    if (Array.isArray(value2)) {
      for (let i2 = 0; i2 < value2.length; i2++) {
        const key2 = String(i2);
        const replacement = internalize(value2, key2, reviver);
        if (replacement === void 0) {
          delete value2[key2];
        } else {
          Object.defineProperty(value2, key2, {
            value: replacement,
            writable: true,
            enumerable: true,
            configurable: true
          });
        }
      }
    } else {
      for (const key2 in value2) {
        const replacement = internalize(value2, key2, reviver);
        if (replacement === void 0) {
          delete value2[key2];
        } else {
          Object.defineProperty(value2, key2, {
            value: replacement,
            writable: true,
            enumerable: true,
            configurable: true
          });
        }
      }
    }
  }
  return reviver.call(holder, name2, value2);
}
let lexState;
let buffer$2;
let doubleQuote;
let sign$1;
let c;
function lex() {
  lexState = "default";
  buffer$2 = "";
  doubleQuote = false;
  sign$1 = 1;
  for (; ; ) {
    c = peek$1();
    const token2 = lexStates[lexState]();
    if (token2) {
      return token2;
    }
  }
}
function peek$1() {
  if (source$1[pos]) {
    return String.fromCodePoint(source$1.codePointAt(pos));
  }
}
function read$1() {
  const c2 = peek$1();
  if (c2 === "\n") {
    line++;
    column$1 = 0;
  } else if (c2) {
    column$1 += c2.length;
  } else {
    column$1++;
  }
  if (c2) {
    pos += c2.length;
  }
  return c2;
}
const lexStates = {
  default() {
    switch (c) {
      case "	":
      case "\v":
      case "\f":
      case " ":
      case " ":
      case "\uFEFF":
      case "\n":
      case "\r":
      case "\u2028":
      case "\u2029":
        read$1();
        return;
      case "/":
        read$1();
        lexState = "comment";
        return;
      case void 0:
        read$1();
        return newToken("eof");
    }
    if (util$1.isSpaceSeparator(c)) {
      read$1();
      return;
    }
    return lexStates[parseState]();
  },
  comment() {
    switch (c) {
      case "*":
        read$1();
        lexState = "multiLineComment";
        return;
      case "/":
        read$1();
        lexState = "singleLineComment";
        return;
    }
    throw invalidChar(read$1());
  },
  multiLineComment() {
    switch (c) {
      case "*":
        read$1();
        lexState = "multiLineCommentAsterisk";
        return;
      case void 0:
        throw invalidChar(read$1());
    }
    read$1();
  },
  multiLineCommentAsterisk() {
    switch (c) {
      case "*":
        read$1();
        return;
      case "/":
        read$1();
        lexState = "default";
        return;
      case void 0:
        throw invalidChar(read$1());
    }
    read$1();
    lexState = "multiLineComment";
  },
  singleLineComment() {
    switch (c) {
      case "\n":
      case "\r":
      case "\u2028":
      case "\u2029":
        read$1();
        lexState = "default";
        return;
      case void 0:
        read$1();
        return newToken("eof");
    }
    read$1();
  },
  value() {
    switch (c) {
      case "{":
      case "[":
        return newToken("punctuator", read$1());
      case "n":
        read$1();
        literal$1("ull");
        return newToken("null", null);
      case "t":
        read$1();
        literal$1("rue");
        return newToken("boolean", true);
      case "f":
        read$1();
        literal$1("alse");
        return newToken("boolean", false);
      case "-":
      case "+":
        if (read$1() === "-") {
          sign$1 = -1;
        }
        lexState = "sign";
        return;
      case ".":
        buffer$2 = read$1();
        lexState = "decimalPointLeading";
        return;
      case "0":
        buffer$2 = read$1();
        lexState = "zero";
        return;
      case "1":
      case "2":
      case "3":
      case "4":
      case "5":
      case "6":
      case "7":
      case "8":
      case "9":
        buffer$2 = read$1();
        lexState = "decimalInteger";
        return;
      case "I":
        read$1();
        literal$1("nfinity");
        return newToken("numeric", Infinity);
      case "N":
        read$1();
        literal$1("aN");
        return newToken("numeric", NaN);
      case '"':
      case "'":
        doubleQuote = read$1() === '"';
        buffer$2 = "";
        lexState = "string";
        return;
    }
    throw invalidChar(read$1());
  },
  identifierNameStartEscape() {
    if (c !== "u") {
      throw invalidChar(read$1());
    }
    read$1();
    const u = unicodeEscape();
    switch (u) {
      case "$":
      case "_":
        break;
      default:
        if (!util$1.isIdStartChar(u)) {
          throw invalidIdentifier();
        }
        break;
    }
    buffer$2 += u;
    lexState = "identifierName";
  },
  identifierName() {
    switch (c) {
      case "$":
      case "_":
      case "‌":
      case "‍":
        buffer$2 += read$1();
        return;
      case "\\":
        read$1();
        lexState = "identifierNameEscape";
        return;
    }
    if (util$1.isIdContinueChar(c)) {
      buffer$2 += read$1();
      return;
    }
    return newToken("identifier", buffer$2);
  },
  identifierNameEscape() {
    if (c !== "u") {
      throw invalidChar(read$1());
    }
    read$1();
    const u = unicodeEscape();
    switch (u) {
      case "$":
      case "_":
      case "‌":
      case "‍":
        break;
      default:
        if (!util$1.isIdContinueChar(u)) {
          throw invalidIdentifier();
        }
        break;
    }
    buffer$2 += u;
    lexState = "identifierName";
  },
  sign() {
    switch (c) {
      case ".":
        buffer$2 = read$1();
        lexState = "decimalPointLeading";
        return;
      case "0":
        buffer$2 = read$1();
        lexState = "zero";
        return;
      case "1":
      case "2":
      case "3":
      case "4":
      case "5":
      case "6":
      case "7":
      case "8":
      case "9":
        buffer$2 = read$1();
        lexState = "decimalInteger";
        return;
      case "I":
        read$1();
        literal$1("nfinity");
        return newToken("numeric", sign$1 * Infinity);
      case "N":
        read$1();
        literal$1("aN");
        return newToken("numeric", NaN);
    }
    throw invalidChar(read$1());
  },
  zero() {
    switch (c) {
      case ".":
        buffer$2 += read$1();
        lexState = "decimalPoint";
        return;
      case "e":
      case "E":
        buffer$2 += read$1();
        lexState = "decimalExponent";
        return;
      case "x":
      case "X":
        buffer$2 += read$1();
        lexState = "hexadecimal";
        return;
    }
    return newToken("numeric", sign$1 * 0);
  },
  decimalInteger() {
    switch (c) {
      case ".":
        buffer$2 += read$1();
        lexState = "decimalPoint";
        return;
      case "e":
      case "E":
        buffer$2 += read$1();
        lexState = "decimalExponent";
        return;
    }
    if (util$1.isDigit(c)) {
      buffer$2 += read$1();
      return;
    }
    return newToken("numeric", sign$1 * Number(buffer$2));
  },
  decimalPointLeading() {
    if (util$1.isDigit(c)) {
      buffer$2 += read$1();
      lexState = "decimalFraction";
      return;
    }
    throw invalidChar(read$1());
  },
  decimalPoint() {
    switch (c) {
      case "e":
      case "E":
        buffer$2 += read$1();
        lexState = "decimalExponent";
        return;
    }
    if (util$1.isDigit(c)) {
      buffer$2 += read$1();
      lexState = "decimalFraction";
      return;
    }
    return newToken("numeric", sign$1 * Number(buffer$2));
  },
  decimalFraction() {
    switch (c) {
      case "e":
      case "E":
        buffer$2 += read$1();
        lexState = "decimalExponent";
        return;
    }
    if (util$1.isDigit(c)) {
      buffer$2 += read$1();
      return;
    }
    return newToken("numeric", sign$1 * Number(buffer$2));
  },
  decimalExponent() {
    switch (c) {
      case "+":
      case "-":
        buffer$2 += read$1();
        lexState = "decimalExponentSign";
        return;
    }
    if (util$1.isDigit(c)) {
      buffer$2 += read$1();
      lexState = "decimalExponentInteger";
      return;
    }
    throw invalidChar(read$1());
  },
  decimalExponentSign() {
    if (util$1.isDigit(c)) {
      buffer$2 += read$1();
      lexState = "decimalExponentInteger";
      return;
    }
    throw invalidChar(read$1());
  },
  decimalExponentInteger() {
    if (util$1.isDigit(c)) {
      buffer$2 += read$1();
      return;
    }
    return newToken("numeric", sign$1 * Number(buffer$2));
  },
  hexadecimal() {
    if (util$1.isHexDigit(c)) {
      buffer$2 += read$1();
      lexState = "hexadecimalInteger";
      return;
    }
    throw invalidChar(read$1());
  },
  hexadecimalInteger() {
    if (util$1.isHexDigit(c)) {
      buffer$2 += read$1();
      return;
    }
    return newToken("numeric", sign$1 * Number(buffer$2));
  },
  string() {
    switch (c) {
      case "\\":
        read$1();
        buffer$2 += escape$2();
        return;
      case '"':
        if (doubleQuote) {
          read$1();
          return newToken("string", buffer$2);
        }
        buffer$2 += read$1();
        return;
      case "'":
        if (!doubleQuote) {
          read$1();
          return newToken("string", buffer$2);
        }
        buffer$2 += read$1();
        return;
      case "\n":
      case "\r":
        throw invalidChar(read$1());
      case "\u2028":
      case "\u2029":
        separatorChar(c);
        break;
      case void 0:
        throw invalidChar(read$1());
    }
    buffer$2 += read$1();
  },
  start() {
    switch (c) {
      case "{":
      case "[":
        return newToken("punctuator", read$1());
    }
    lexState = "value";
  },
  beforePropertyName() {
    switch (c) {
      case "$":
      case "_":
        buffer$2 = read$1();
        lexState = "identifierName";
        return;
      case "\\":
        read$1();
        lexState = "identifierNameStartEscape";
        return;
      case "}":
        return newToken("punctuator", read$1());
      case '"':
      case "'":
        doubleQuote = read$1() === '"';
        lexState = "string";
        return;
    }
    if (util$1.isIdStartChar(c)) {
      buffer$2 += read$1();
      lexState = "identifierName";
      return;
    }
    throw invalidChar(read$1());
  },
  afterPropertyName() {
    if (c === ":") {
      return newToken("punctuator", read$1());
    }
    throw invalidChar(read$1());
  },
  beforePropertyValue() {
    lexState = "value";
  },
  afterPropertyValue() {
    switch (c) {
      case ",":
      case "}":
        return newToken("punctuator", read$1());
    }
    throw invalidChar(read$1());
  },
  beforeArrayValue() {
    if (c === "]") {
      return newToken("punctuator", read$1());
    }
    lexState = "value";
  },
  afterArrayValue() {
    switch (c) {
      case ",":
      case "]":
        return newToken("punctuator", read$1());
    }
    throw invalidChar(read$1());
  },
  end() {
    throw invalidChar(read$1());
  }
};
function newToken(type, value2) {
  return {
    type,
    value: value2,
    line,
    column: column$1
  };
}
function literal$1(s) {
  for (const c2 of s) {
    const p = peek$1();
    if (p !== c2) {
      throw invalidChar(read$1());
    }
    read$1();
  }
}
function escape$2() {
  const c2 = peek$1();
  switch (c2) {
    case "b":
      read$1();
      return "\b";
    case "f":
      read$1();
      return "\f";
    case "n":
      read$1();
      return "\n";
    case "r":
      read$1();
      return "\r";
    case "t":
      read$1();
      return "	";
    case "v":
      read$1();
      return "\v";
    case "0":
      read$1();
      if (util$1.isDigit(peek$1())) {
        throw invalidChar(read$1());
      }
      return "\0";
    case "x":
      read$1();
      return hexEscape();
    case "u":
      read$1();
      return unicodeEscape();
    case "\n":
    case "\u2028":
    case "\u2029":
      read$1();
      return "";
    case "\r":
      read$1();
      if (peek$1() === "\n") {
        read$1();
      }
      return "";
    case "1":
    case "2":
    case "3":
    case "4":
    case "5":
    case "6":
    case "7":
    case "8":
    case "9":
      throw invalidChar(read$1());
    case void 0:
      throw invalidChar(read$1());
  }
  return read$1();
}
function hexEscape() {
  let buffer2 = "";
  let c2 = peek$1();
  if (!util$1.isHexDigit(c2)) {
    throw invalidChar(read$1());
  }
  buffer2 += read$1();
  c2 = peek$1();
  if (!util$1.isHexDigit(c2)) {
    throw invalidChar(read$1());
  }
  buffer2 += read$1();
  return String.fromCodePoint(parseInt(buffer2, 16));
}
function unicodeEscape() {
  let buffer2 = "";
  let count2 = 4;
  while (count2-- > 0) {
    const c2 = peek$1();
    if (!util$1.isHexDigit(c2)) {
      throw invalidChar(read$1());
    }
    buffer2 += read$1();
  }
  return String.fromCodePoint(parseInt(buffer2, 16));
}
const parseStates = {
  start() {
    if (token.type === "eof") {
      throw invalidEOF();
    }
    push();
  },
  beforePropertyName() {
    switch (token.type) {
      case "identifier":
      case "string":
        key$2 = token.value;
        parseState = "afterPropertyName";
        return;
      case "punctuator":
        pop();
        return;
      case "eof":
        throw invalidEOF();
    }
  },
  afterPropertyName() {
    if (token.type === "eof") {
      throw invalidEOF();
    }
    parseState = "beforePropertyValue";
  },
  beforePropertyValue() {
    if (token.type === "eof") {
      throw invalidEOF();
    }
    push();
  },
  beforeArrayValue() {
    if (token.type === "eof") {
      throw invalidEOF();
    }
    if (token.type === "punctuator" && token.value === "]") {
      pop();
      return;
    }
    push();
  },
  afterPropertyValue() {
    if (token.type === "eof") {
      throw invalidEOF();
    }
    switch (token.value) {
      case ",":
        parseState = "beforePropertyName";
        return;
      case "}":
        pop();
    }
  },
  afterArrayValue() {
    if (token.type === "eof") {
      throw invalidEOF();
    }
    switch (token.value) {
      case ",":
        parseState = "beforeArrayValue";
        return;
      case "]":
        pop();
    }
  },
  end() {
  }
};
function push() {
  let value2;
  switch (token.type) {
    case "punctuator":
      switch (token.value) {
        case "{":
          value2 = {};
          break;
        case "[":
          value2 = [];
          break;
      }
      break;
    case "null":
    case "boolean":
    case "numeric":
    case "string":
      value2 = token.value;
      break;
  }
  if (root$4 === void 0) {
    root$4 = value2;
  } else {
    const parent = stack[stack.length - 1];
    if (Array.isArray(parent)) {
      parent.push(value2);
    } else {
      Object.defineProperty(parent, key$2, {
        value: value2,
        writable: true,
        enumerable: true,
        configurable: true
      });
    }
  }
  if (value2 !== null && typeof value2 === "object") {
    stack.push(value2);
    if (Array.isArray(value2)) {
      parseState = "beforeArrayValue";
    } else {
      parseState = "beforePropertyName";
    }
  } else {
    const current3 = stack[stack.length - 1];
    if (current3 == null) {
      parseState = "end";
    } else if (Array.isArray(current3)) {
      parseState = "afterArrayValue";
    } else {
      parseState = "afterPropertyValue";
    }
  }
}
function pop() {
  stack.pop();
  const current3 = stack[stack.length - 1];
  if (current3 == null) {
    parseState = "end";
  } else if (Array.isArray(current3)) {
    parseState = "afterArrayValue";
  } else {
    parseState = "afterPropertyValue";
  }
}
function invalidChar(c2) {
  if (c2 === void 0) {
    return syntaxError(`JSON5: invalid end of input at ${line}:${column$1}`);
  }
  return syntaxError(`JSON5: invalid character '${formatChar(c2)}' at ${line}:${column$1}`);
}
function invalidEOF() {
  return syntaxError(`JSON5: invalid end of input at ${line}:${column$1}`);
}
function invalidIdentifier() {
  column$1 -= 5;
  return syntaxError(`JSON5: invalid identifier character at ${line}:${column$1}`);
}
function separatorChar(c2) {
  console.warn(`JSON5: '${formatChar(c2)}' in strings is not valid ECMAScript; consider escaping`);
}
function formatChar(c2) {
  const replacements = {
    "'": "\\'",
    '"': '\\"',
    "\\": "\\\\",
    "\b": "\\b",
    "\f": "\\f",
    "\n": "\\n",
    "\r": "\\r",
    "	": "\\t",
    "\v": "\\v",
    "\0": "\\0",
    "\u2028": "\\u2028",
    "\u2029": "\\u2029"
  };
  if (replacements[c2]) {
    return replacements[c2];
  }
  if (c2 < " ") {
    const hexString = c2.charCodeAt(0).toString(16);
    return "\\x" + ("00" + hexString).substring(hexString.length);
  }
  return c2;
}
function syntaxError(message2) {
  const err = new SyntaxError(message2);
  err.lineNumber = line;
  err.columnNumber = column$1;
  return err;
}
var stringify = function stringify2(value2, replacer, space) {
  const stack2 = [];
  let indent = "";
  let propertyList;
  let replacerFunc;
  let gap = "";
  let quote2;
  if (replacer != null && typeof replacer === "object" && !Array.isArray(replacer)) {
    space = replacer.space;
    quote2 = replacer.quote;
    replacer = replacer.replacer;
  }
  if (typeof replacer === "function") {
    replacerFunc = replacer;
  } else if (Array.isArray(replacer)) {
    propertyList = [];
    for (const v of replacer) {
      let item2;
      if (typeof v === "string") {
        item2 = v;
      } else if (typeof v === "number" || v instanceof String || v instanceof Number) {
        item2 = String(v);
      }
      if (item2 !== void 0 && propertyList.indexOf(item2) < 0) {
        propertyList.push(item2);
      }
    }
  }
  if (space instanceof Number) {
    space = Number(space);
  } else if (space instanceof String) {
    space = String(space);
  }
  if (typeof space === "number") {
    if (space > 0) {
      space = Math.min(10, Math.floor(space));
      gap = "          ".substr(0, space);
    }
  } else if (typeof space === "string") {
    gap = space.substr(0, 10);
  }
  return serializeProperty("", { "": value2 });
  function serializeProperty(key2, holder) {
    let value3 = holder[key2];
    if (value3 != null) {
      if (typeof value3.toJSON5 === "function") {
        value3 = value3.toJSON5(key2);
      } else if (typeof value3.toJSON === "function") {
        value3 = value3.toJSON(key2);
      }
    }
    if (replacerFunc) {
      value3 = replacerFunc.call(holder, key2, value3);
    }
    if (value3 instanceof Number) {
      value3 = Number(value3);
    } else if (value3 instanceof String) {
      value3 = String(value3);
    } else if (value3 instanceof Boolean) {
      value3 = value3.valueOf();
    }
    switch (value3) {
      case null:
        return "null";
      case true:
        return "true";
      case false:
        return "false";
    }
    if (typeof value3 === "string") {
      return quoteString(value3);
    }
    if (typeof value3 === "number") {
      return String(value3);
    }
    if (typeof value3 === "object") {
      return Array.isArray(value3) ? serializeArray(value3) : serializeObject(value3);
    }
    return void 0;
  }
  function quoteString(value3) {
    const quotes = {
      "'": 0.1,
      '"': 0.2
    };
    const replacements = {
      "'": "\\'",
      '"': '\\"',
      "\\": "\\\\",
      "\b": "\\b",
      "\f": "\\f",
      "\n": "\\n",
      "\r": "\\r",
      "	": "\\t",
      "\v": "\\v",
      "\0": "\\0",
      "\u2028": "\\u2028",
      "\u2029": "\\u2029"
    };
    let product2 = "";
    for (let i2 = 0; i2 < value3.length; i2++) {
      const c2 = value3[i2];
      switch (c2) {
        case "'":
        case '"':
          quotes[c2]++;
          product2 += c2;
          continue;
        case "\0":
          if (util$1.isDigit(value3[i2 + 1])) {
            product2 += "\\x00";
            continue;
          }
      }
      if (replacements[c2]) {
        product2 += replacements[c2];
        continue;
      }
      if (c2 < " ") {
        let hexString = c2.charCodeAt(0).toString(16);
        product2 += "\\x" + ("00" + hexString).substring(hexString.length);
        continue;
      }
      product2 += c2;
    }
    const quoteChar = quote2 || Object.keys(quotes).reduce((a2, b) => quotes[a2] < quotes[b] ? a2 : b);
    product2 = product2.replace(new RegExp(quoteChar, "g"), replacements[quoteChar]);
    return quoteChar + product2 + quoteChar;
  }
  function serializeObject(value3) {
    if (stack2.indexOf(value3) >= 0) {
      throw TypeError("Converting circular structure to JSON5");
    }
    stack2.push(value3);
    let stepback = indent;
    indent = indent + gap;
    let keys2 = propertyList || Object.keys(value3);
    let partial = [];
    for (const key2 of keys2) {
      const propertyString = serializeProperty(key2, value3);
      if (propertyString !== void 0) {
        let member = serializeKey(key2) + ":";
        if (gap !== "") {
          member += " ";
        }
        member += propertyString;
        partial.push(member);
      }
    }
    let final;
    if (partial.length === 0) {
      final = "{}";
    } else {
      let properties;
      if (gap === "") {
        properties = partial.join(",");
        final = "{" + properties + "}";
      } else {
        let separator2 = ",\n" + indent;
        properties = partial.join(separator2);
        final = "{\n" + indent + properties + ",\n" + stepback + "}";
      }
    }
    stack2.pop();
    indent = stepback;
    return final;
  }
  function serializeKey(key2) {
    if (key2.length === 0) {
      return quoteString(key2);
    }
    const firstChar = String.fromCodePoint(key2.codePointAt(0));
    if (!util$1.isIdStartChar(firstChar)) {
      return quoteString(key2);
    }
    for (let i2 = firstChar.length; i2 < key2.length; i2++) {
      if (!util$1.isIdContinueChar(String.fromCodePoint(key2.codePointAt(i2)))) {
        return quoteString(key2);
      }
    }
    return key2;
  }
  function serializeArray(value3) {
    if (stack2.indexOf(value3) >= 0) {
      throw TypeError("Converting circular structure to JSON5");
    }
    stack2.push(value3);
    let stepback = indent;
    indent = indent + gap;
    let partial = [];
    for (let i2 = 0; i2 < value3.length; i2++) {
      const propertyString = serializeProperty(String(i2), value3);
      partial.push(propertyString !== void 0 ? propertyString : "null");
    }
    let final;
    if (partial.length === 0) {
      final = "[]";
    } else {
      if (gap === "") {
        let properties = partial.join(",");
        final = "[" + properties + "]";
      } else {
        let separator2 = ",\n" + indent;
        let properties = partial.join(separator2);
        final = "[\n" + indent + properties + ",\n" + stepback + "]";
      }
    }
    stack2.pop();
    indent = stepback;
    return final;
  }
};
const JSON5 = {
  parse: parse$5,
  stringify
};
var lib$1 = JSON5;
class JsonWorkerPool {
  encoder = new TextEncoder();
  decoder = new TextDecoder();
  workers = [];
  blobURL = null;
  nextRequestId = 0;
  pendingRequests = /* @__PURE__ */ new Map();
  poolSize = 4;
  ensureWorkers() {
    if (this.workers.length === 0) {
      const blob = new Blob([kWorkerCode], { type: "application/javascript" });
      this.blobURL = URL.createObjectURL(blob);
      for (let i2 = 0; i2 < this.poolSize; i2++) {
        const worker = new Worker(this.blobURL);
        worker.onmessage = (e) => this.handleMessage(e);
        worker.onerror = (error2) => this.handleError(error2);
        this.workers.push(worker);
        worker.postMessage({
          type: "init",
          scriptContent: kJson5ScriptBase64
        });
      }
    }
  }
  handleMessage(e) {
    const { requestId, success, serialized, result: result2, error: error2, stack: stack2 } = e.data;
    const pending = this.pendingRequests.get(requestId);
    if (!pending) return;
    this.pendingRequests.delete(requestId);
    if (success) {
      if (serialized) {
        const resultString = this.decoder.decode(result2);
        pending.resolve(JSON.parse(resultString));
      } else {
        pending.resolve(result2);
      }
    } else {
      const err = new Error(error2);
      if (stack2) err.stack = stack2;
      pending.reject(err);
    }
  }
  handleError(error2) {
    const err = new Error(`Worker error: ${error2.message}`);
    for (const pending of this.pendingRequests.values()) {
      pending.reject(err);
    }
    this.pendingRequests.clear();
  }
  async parse(text2) {
    this.ensureWorkers();
    const encodedText = this.encoder.encode(text2);
    const requestId = this.nextRequestId++;
    return new Promise((resolve2, reject) => {
      this.pendingRequests.set(requestId, { resolve: resolve2, reject });
      const worker = this.workers[requestId % this.workers.length];
      worker?.postMessage(
        {
          type: "parse",
          requestId,
          encodedText
        },
        [encodedText.buffer]
      );
    });
  }
  terminate() {
    this.workers.forEach((w2) => w2.terminate());
    this.workers = [];
    if (this.blobURL) {
      URL.revokeObjectURL(this.blobURL);
      this.blobURL = null;
    }
    this.pendingRequests.clear();
  }
}
const workerPool = new JsonWorkerPool();
const asyncJsonParse = async (text2) => {
  if (text2.length < 5e4) {
    let result2 = void 0;
    try {
      result2 = JSON.parse(text2);
    } catch {
      result2 = lib$1.parse(text2);
    }
    return Promise.resolve(result2);
  } else {
    return workerPool.parse(text2);
  }
};
const kWorkerCode = `
// Store the JSON5 parser once loaded
let JSON5 = null;
const decoder = new TextDecoder();
const encoder = new TextEncoder();

self.onmessage = function (e) {
  const { type } = e.data || {};

  if (type === 'init') {
    const { scriptContent } = e.data;
    try {
      if (!JSON5) {
        const script = atob(scriptContent);
        new Function(script)();
        if (typeof self.JSON5 !== 'object' || typeof self.JSON5.parse !== 'function') {
          throw new Error('Failed to initialize JSON5 parser');
        }
        JSON5 = self.JSON5;
      }
    } catch (err) {
      // nothing to respond to yet; worker will fail on first parse if init failed
      console.error('JSON5 init error in worker', err);
    }
    return;
  }

  if (type === 'parse') {
    const { requestId, encodedText, scriptContent } = e.data;

    try {
      
      // Decode the text using TextDecoder
      const text = decoder.decode(encodedText);

      // Parse with JSON/JSON5
      let result = undefined;
      try {
        // Optimistically, try a regular JSON parse first (this is much faster)
        result = JSON.parse(text);
      } catch {
        result = JSON5.parse(text);
      }

      if (result && typeof result === 'object' &&
          (Array.isArray(result) ? result.length > 10000 : Object.keys(result).length > 10000)) {

        // Large result, use transferrable object
        const resultString = JSON.stringify(result);
        const serialized = encoder.encode(resultString);

        postMessage({
          requestId,
          success: true,
          serialized: true,
          result: serialized
        }, [serialized.buffer]);
      } else {
        // Small results, send directly
        postMessage({
          requestId,
          success: true, 
          serialized: false, 
          result: result 
        });
      }
    } catch (err) {
      postMessage({
        requestId,
        success: false, 
        error: err.message,
        stack: err.stack || ''
      });
    }
  }
};`;
const kJson5ScriptBase64 = ` `;
const NoPersistence = {
  getItem: (_name) => {
    return null;
  },
  setItem: (_name, _value) => {
  },
  removeItem: (_name) => {
  }
};
class ApiError extends Error {
  status;
  constructor(status, message2) {
    super(message2);
    this.status = status;
  }
}
function serverRequestApi(baseUrl, getHeaders) {
  const apiUrl = baseUrl;
  function buildApiUrl(path) {
    const base2 = apiUrl.endsWith("/") ? apiUrl.slice(0, -1) : apiUrl;
    const cleanPath = path.startsWith("/") ? path : `/${path}`;
    return base2 + cleanPath;
  }
  function isApiCrossOrigin() {
    try {
      return Boolean(
        apiUrl && new URL(apiUrl).origin !== window.location.origin
      );
    } catch (error2) {
      return false;
    }
  }
  const fetchType = async (method, path, request) => {
    const url = buildApiUrl(path);
    const responseHeaders = {
      Accept: "application/json",
      Pragma: "no-cache",
      Expires: "0",
      "Cache-Control": "no-cache",
      ...request?.headers
    };
    if (getHeaders) {
      const globalHeaders = await getHeaders();
      Object.assign(responseHeaders, globalHeaders);
    }
    if (request?.body) {
      responseHeaders["Content-Type"] = "application/json";
    }
    const response = await fetch(url, {
      method,
      headers: responseHeaders,
      body: request?.body,
      credentials: isApiCrossOrigin() ? "include" : "same-origin"
    });
    if (!response.ok) {
      const errorResponse = request?.handleError?.(response.status);
      if (errorResponse) {
        return {
          raw: response.statusText,
          parsed: errorResponse
        };
      }
      const message2 = await response.text() || response.statusText;
      throw new ApiError(
        response.status,
        `API Error ${response.status}: ${message2}`
      );
    }
    const text2 = await response.text();
    const parse5 = request?.parse || asyncJsonParse;
    return {
      parsed: await parse5(text2),
      raw: text2
    };
  };
  const fetchString = async (method, path, headers, body) => {
    const url = buildApiUrl(path);
    const requestHeaders = {
      Accept: "application/json",
      Pragma: "no-cache",
      Expires: "0",
      "Cache-Control": "no-cache",
      ...headers
    };
    if (getHeaders) {
      const globalHeaders = await getHeaders();
      Object.assign(requestHeaders, globalHeaders);
    }
    if (body) {
      requestHeaders["Content-Type"] = "application/json";
    }
    const response = await fetch(url, {
      method,
      headers: requestHeaders,
      body,
      credentials: isApiCrossOrigin() ? "include" : "same-origin"
    });
    if (response.ok) {
      const text2 = await response.text();
      return {
        parsed: await asyncJsonParse(text2),
        raw: text2
      };
    }
    const message2 = await response.text() || response.statusText;
    throw new ApiError(response.status, `HTTP ${response.status}: ${message2}`);
  };
  const fetchBytes = async (method, path) => {
    const url = buildApiUrl(path);
    const headers = {
      Accept: "application/octet-stream",
      Pragma: "no-cache",
      Expires: "0",
      "Cache-Control": "no-cache"
    };
    if (getHeaders) {
      const globalHeaders = await getHeaders();
      Object.assign(headers, globalHeaders);
    }
    const response = await fetch(url, {
      method,
      headers,
      credentials: isApiCrossOrigin() ? "include" : "same-origin"
    });
    if (!response.ok) {
      const message2 = await response.text() || response.statusText;
      throw new ApiError(
        response.status,
        `HTTP ${response.status}: ${message2}`
      );
    }
    return await response.arrayBuffer();
  };
  return {
    fetchString,
    fetchBytes,
    fetchType
  };
}
const apiScoutServer = (options = {}) => {
  const { apiBaseUrl, headerProvider, resultsDir } = options;
  const requestApi = serverRequestApi(apiBaseUrl || "/api", headerProvider);
  return {
    getScan: async (scanLocation) => {
      const result2 = await requestApi.fetchString(
        "GET",
        `/scan/${encodeURIComponent(scanLocation)}?status_only=true`
      );
      return asyncJsonParse(result2.raw);
    },
    getScans: async () => {
      let query2 = "/scans?status_only=true";
      if (resultsDir) {
        query2 += `&results_dir=${encodeURIComponent(resultsDir)}`;
      }
      return (await requestApi.fetchType("GET", query2)).parsed;
    },
    getScannerDataframe: async (scanLocation, scanner) => {
      return await requestApi.fetchBytes(
        "GET",
        `/scanner_df/${encodeURIComponent(
          scanLocation
        )}?scanner=${encodeURIComponent(scanner)}`
      );
    },
    storage: NoPersistence
  };
};
const kMethodGetScan = "get_scan";
const kMethodGetScans = "get_scans";
const kMethodGetScannerDataframe = "get_scanner_dataframe";
const kJsonRpcVersion = "2.0";
function webViewJsonRpcClient(vscode) {
  const target = {
    postMessage: (data2) => {
      vscode.postMessage(data2);
    },
    onMessage: (handler) => {
      const onMessage = (ev) => {
        handler(ev.data);
      };
      window.addEventListener("message", onMessage);
      return () => {
        window.removeEventListener("message", onMessage);
      };
    }
  };
  return jsonRpcPostMessageRequestTransport(target).request;
}
function jsonRpcPostMessageRequestTransport(target) {
  const requests = /* @__PURE__ */ new Map();
  const disconnect = target.onMessage((ev) => {
    const response = asJsonRpcResponse(ev);
    if (response) {
      const request = requests.get(response.id);
      if (request) {
        requests.delete(response.id);
        if (response.error) {
          request.reject(response.error);
        } else {
          request.resolve(response.result);
        }
      }
    }
  });
  return {
    request: (method, params) => {
      return new Promise((resolve2, reject) => {
        const requestId = Math.floor(Math.random() * 1e6);
        requests.set(requestId, { resolve: resolve2, reject });
        const request = {
          jsonrpc: kJsonRpcVersion,
          id: requestId,
          method,
          params
        };
        target.postMessage(request);
      });
    },
    disconnect
  };
}
function isJsonRpcMessage(message2) {
  return typeof message2 === "object" && message2 !== null && "jsonrpc" in message2 && "id" in message2;
}
function asJsonRpcMessage(data2) {
  if (isJsonRpcMessage(data2) && data2.jsonrpc === kJsonRpcVersion) {
    return data2;
  }
  return null;
}
function asJsonRpcResponse(data2) {
  const message2 = asJsonRpcMessage(data2);
  if (message2) {
    return message2;
  }
  return null;
}
const apiVscode = (vscodeApi2, rpcClient) => {
  return {
    getScan: async (scanLocation) => {
      const response = await rpcClient(kMethodGetScan, [
        scanLocation
      ]);
      if (response) {
        return lib$1.parse(response);
      } else {
        throw new Error(
          `Invalid response for getScan for scan: ${scanLocation}`
        );
      }
    },
    getScans: async () => {
      const response = await rpcClient(kMethodGetScans, []);
      if (response) {
        return lib$1.parse(response);
      } else {
        throw new Error("Invalid response for getScans");
      }
    },
    getScannerDataframe: async (scanLocation, scanner) => {
      const response = await rpcClient(kMethodGetScannerDataframe, [
        scanLocation,
        scanner
      ]);
      if (response && response instanceof Uint8Array) {
        return response;
      } else {
        throw new Error(
          `Invalid response for getScannerDataframe for scan: ${scanLocation}, scanner: ${scanner}`
        );
      }
    },
    storage: createVSCodeStore(vscodeApi2)
  };
};
const createVSCodeStore = (api2) => {
  return {
    getItem: (key2) => {
      const state = api2.getState();
      if (state && typeof state === "object") {
        const stateObj = state;
        const value2 = stateObj[key2];
        return value2 || null;
      }
      return null;
    },
    setItem: (key2, value2) => {
      const existingState = api2.getState() || {};
      const stateObj = typeof existingState === "object" ? existingState : {};
      stateObj[key2] = value2;
      api2.setState(stateObj);
    },
    removeItem: (key2) => {
      const existingState = api2.getState();
      if (existingState && typeof existingState === "object") {
        const stateObj = existingState;
        delete stateObj[key2];
        api2.setState(stateObj);
      }
    }
  };
};
var reactExports = requireReact();
const React20 = /* @__PURE__ */ getDefaultExportFromCjs(reactExports);
/**
 * react-router v7.9.5
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */
var __typeError = (msg) => {
  throw TypeError(msg);
};
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value2) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value2);
var PopStateEventType = "popstate";
function createHashHistory(options = {}) {
  function createHashLocation(window2, globalHistory) {
    let {
      pathname = "/",
      search = "",
      hash: hash2 = ""
    } = parsePath$1(window2.location.hash.substring(1));
    if (!pathname.startsWith("/") && !pathname.startsWith(".")) {
      pathname = "/" + pathname;
    }
    return createLocation(
      "",
      { pathname, search, hash: hash2 },
      // state defaults to `null` because `window.history.state` does
      globalHistory.state && globalHistory.state.usr || null,
      globalHistory.state && globalHistory.state.key || "default"
    );
  }
  function createHashHref(window2, to2) {
    let base2 = window2.document.querySelector("base");
    let href = "";
    if (base2 && base2.getAttribute("href")) {
      let url = window2.location.href;
      let hashIndex = url.indexOf("#");
      href = hashIndex === -1 ? url : url.slice(0, hashIndex);
    }
    return href + "#" + (typeof to2 === "string" ? to2 : createPath(to2));
  }
  function validateHashLocation(location, to2) {
    warning(
      location.pathname.charAt(0) === "/",
      `relative pathnames are not supported in hash history.push(${JSON.stringify(
        to2
      )})`
    );
  }
  return getUrlBasedHistory(
    createHashLocation,
    createHashHref,
    validateHashLocation,
    options
  );
}
function invariant(value2, message2) {
  if (value2 === false || value2 === null || typeof value2 === "undefined") {
    throw new Error(message2);
  }
}
function warning(cond, message2) {
  if (!cond) {
    if (typeof console !== "undefined") console.warn(message2);
    try {
      throw new Error(message2);
    } catch (e) {
    }
  }
}
function createKey() {
  return Math.random().toString(36).substring(2, 10);
}
function getHistoryState(location, index) {
  return {
    usr: location.state,
    key: location.key,
    idx: index
  };
}
function createLocation(current3, to2, state = null, key2) {
  let location = {
    pathname: typeof current3 === "string" ? current3 : current3.pathname,
    search: "",
    hash: "",
    ...typeof to2 === "string" ? parsePath$1(to2) : to2,
    state,
    // TODO: This could be cleaned up.  push/replace should probably just take
    // full Locations now and avoid the need to run through this flow at all
    // But that's a pretty big refactor to the current test suite so going to
    // keep as is for the time being and just let any incoming keys take precedence
    key: to2 && to2.key || key2 || createKey()
  };
  return location;
}
function createPath({
  pathname = "/",
  search = "",
  hash: hash2 = ""
}) {
  if (search && search !== "?")
    pathname += search.charAt(0) === "?" ? search : "?" + search;
  if (hash2 && hash2 !== "#")
    pathname += hash2.charAt(0) === "#" ? hash2 : "#" + hash2;
  return pathname;
}
function parsePath$1(path) {
  let parsedPath = {};
  if (path) {
    let hashIndex = path.indexOf("#");
    if (hashIndex >= 0) {
      parsedPath.hash = path.substring(hashIndex);
      path = path.substring(0, hashIndex);
    }
    let searchIndex = path.indexOf("?");
    if (searchIndex >= 0) {
      parsedPath.search = path.substring(searchIndex);
      path = path.substring(0, searchIndex);
    }
    if (path) {
      parsedPath.pathname = path;
    }
  }
  return parsedPath;
}
function getUrlBasedHistory(getLocation, createHref2, validateLocation, options = {}) {
  let { window: window2 = document.defaultView, v5Compat = false } = options;
  let globalHistory = window2.history;
  let action = "POP";
  let listener = null;
  let index = getIndex();
  if (index == null) {
    index = 0;
    globalHistory.replaceState({ ...globalHistory.state, idx: index }, "");
  }
  function getIndex() {
    let state = globalHistory.state || { idx: null };
    return state.idx;
  }
  function handlePop() {
    action = "POP";
    let nextIndex2 = getIndex();
    let delta = nextIndex2 == null ? null : nextIndex2 - index;
    index = nextIndex2;
    if (listener) {
      listener({ action, location: history.location, delta });
    }
  }
  function push2(to2, state) {
    action = "PUSH";
    let location = createLocation(history.location, to2, state);
    if (validateLocation) validateLocation(location, to2);
    index = getIndex() + 1;
    let historyState = getHistoryState(location, index);
    let url = history.createHref(location);
    try {
      globalHistory.pushState(historyState, "", url);
    } catch (error2) {
      if (error2 instanceof DOMException && error2.name === "DataCloneError") {
        throw error2;
      }
      window2.location.assign(url);
    }
    if (v5Compat && listener) {
      listener({ action, location: history.location, delta: 1 });
    }
  }
  function replace2(to2, state) {
    action = "REPLACE";
    let location = createLocation(history.location, to2, state);
    if (validateLocation) validateLocation(location, to2);
    index = getIndex();
    let historyState = getHistoryState(location, index);
    let url = history.createHref(location);
    globalHistory.replaceState(historyState, "", url);
    if (v5Compat && listener) {
      listener({ action, location: history.location, delta: 0 });
    }
  }
  function createURL(to2) {
    return createBrowserURLImpl(to2);
  }
  let history = {
    get action() {
      return action;
    },
    get location() {
      return getLocation(window2, globalHistory);
    },
    listen(fn3) {
      if (listener) {
        throw new Error("A history only accepts one active listener");
      }
      window2.addEventListener(PopStateEventType, handlePop);
      listener = fn3;
      return () => {
        window2.removeEventListener(PopStateEventType, handlePop);
        listener = null;
      };
    },
    createHref(to2) {
      return createHref2(window2, to2);
    },
    createURL,
    encodeLocation(to2) {
      let url = createURL(to2);
      return {
        pathname: url.pathname,
        search: url.search,
        hash: url.hash
      };
    },
    push: push2,
    replace: replace2,
    go(n2) {
      return globalHistory.go(n2);
    }
  };
  return history;
}
function createBrowserURLImpl(to2, isAbsolute = false) {
  let base2 = "http://localhost";
  if (typeof window !== "undefined") {
    base2 = window.location.origin !== "null" ? window.location.origin : window.location.href;
  }
  invariant(base2, "No window.location.(origin|href) available to create URL");
  let href = typeof to2 === "string" ? to2 : createPath(to2);
  href = href.replace(/ $/, "%20");
  if (!isAbsolute && href.startsWith("//")) {
    href = base2 + href;
  }
  return new URL(href, base2);
}
var _map;
var RouterContextProvider = class {
  /**
   * Create a new `RouterContextProvider` instance
   * @param init An optional initial context map to populate the provider with
   */
  constructor(init) {
    __privateAdd(this, _map, /* @__PURE__ */ new Map());
    if (init) {
      for (let [context, value2] of init) {
        this.set(context, value2);
      }
    }
  }
  /**
   * Access a value from the context. If no value has been set for the context,
   * it will return the context's `defaultValue` if provided, or throw an error
   * if no `defaultValue` was set.
   * @param context The context to get the value for
   * @returns The value for the context, or the context's `defaultValue` if no
   * value was set
   */
  get(context) {
    if (__privateGet(this, _map).has(context)) {
      return __privateGet(this, _map).get(context);
    }
    if (context.defaultValue !== void 0) {
      return context.defaultValue;
    }
    throw new Error("No value found for context");
  }
  /**
   * Set a value for the context. If the context already has a value set, this
   * will overwrite it.
   *
   * @param context The context to set the value for
   * @param value The value to set for the context
   * @returns {void}
   */
  set(context, value2) {
    __privateGet(this, _map).set(context, value2);
  }
};
_map = /* @__PURE__ */ new WeakMap();
var unsupportedLazyRouteObjectKeys = /* @__PURE__ */ new Set([
  "lazy",
  "caseSensitive",
  "path",
  "id",
  "index",
  "children"
]);
function isUnsupportedLazyRouteObjectKey(key2) {
  return unsupportedLazyRouteObjectKeys.has(
    key2
  );
}
var unsupportedLazyRouteFunctionKeys = /* @__PURE__ */ new Set([
  "lazy",
  "caseSensitive",
  "path",
  "id",
  "index",
  "middleware",
  "children"
]);
function isUnsupportedLazyRouteFunctionKey(key2) {
  return unsupportedLazyRouteFunctionKeys.has(
    key2
  );
}
function isIndexRoute(route) {
  return route.index === true;
}
function convertRoutesToDataRoutes(routes, mapRouteProperties2, parentPath = [], manifest = {}, allowInPlaceMutations = false) {
  return routes.map((route, index) => {
    let treePath = [...parentPath, String(index)];
    let id2 = typeof route.id === "string" ? route.id : treePath.join("-");
    invariant(
      route.index !== true || !route.children,
      `Cannot specify children on an index route`
    );
    invariant(
      allowInPlaceMutations || !manifest[id2],
      `Found a route id collision on id "${id2}".  Route id's must be globally unique within Data Router usages`
    );
    if (isIndexRoute(route)) {
      let indexRoute = {
        ...route,
        id: id2
      };
      manifest[id2] = mergeRouteUpdates(
        indexRoute,
        mapRouteProperties2(indexRoute)
      );
      return indexRoute;
    } else {
      let pathOrLayoutRoute = {
        ...route,
        id: id2,
        children: void 0
      };
      manifest[id2] = mergeRouteUpdates(
        pathOrLayoutRoute,
        mapRouteProperties2(pathOrLayoutRoute)
      );
      if (route.children) {
        pathOrLayoutRoute.children = convertRoutesToDataRoutes(
          route.children,
          mapRouteProperties2,
          treePath,
          manifest,
          allowInPlaceMutations
        );
      }
      return pathOrLayoutRoute;
    }
  });
}
function mergeRouteUpdates(route, updates) {
  return Object.assign(route, {
    ...updates,
    ...typeof updates.lazy === "object" && updates.lazy != null ? {
      lazy: {
        ...route.lazy,
        ...updates.lazy
      }
    } : {}
  });
}
function matchRoutes(routes, locationArg, basename2 = "/") {
  return matchRoutesImpl(routes, locationArg, basename2, false);
}
function matchRoutesImpl(routes, locationArg, basename2, allowPartial) {
  let location = typeof locationArg === "string" ? parsePath$1(locationArg) : locationArg;
  let pathname = stripBasename(location.pathname || "/", basename2);
  if (pathname == null) {
    return null;
  }
  let branches = flattenRoutes(routes);
  rankRouteBranches(branches);
  let matches = null;
  for (let i2 = 0; matches == null && i2 < branches.length; ++i2) {
    let decoded = decodePath(pathname);
    matches = matchRouteBranch(
      branches[i2],
      decoded,
      allowPartial
    );
  }
  return matches;
}
function convertRouteMatchToUiMatch(match3, loaderData) {
  let { route, pathname, params } = match3;
  return {
    id: route.id,
    pathname,
    params,
    data: loaderData[route.id],
    loaderData: loaderData[route.id],
    handle: route.handle
  };
}
function flattenRoutes(routes, branches = [], parentsMeta = [], parentPath = "", _hasParentOptionalSegments = false) {
  let flattenRoute = (route, index, hasParentOptionalSegments = _hasParentOptionalSegments, relativePath) => {
    let meta = {
      relativePath: relativePath === void 0 ? route.path || "" : relativePath,
      caseSensitive: route.caseSensitive === true,
      childrenIndex: index,
      route
    };
    if (meta.relativePath.startsWith("/")) {
      if (!meta.relativePath.startsWith(parentPath) && hasParentOptionalSegments) {
        return;
      }
      invariant(
        meta.relativePath.startsWith(parentPath),
        `Absolute route path "${meta.relativePath}" nested under path "${parentPath}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`
      );
      meta.relativePath = meta.relativePath.slice(parentPath.length);
    }
    let path = joinPaths([parentPath, meta.relativePath]);
    let routesMeta = parentsMeta.concat(meta);
    if (route.children && route.children.length > 0) {
      invariant(
        // Our types know better, but runtime JS may not!
        // @ts-expect-error
        route.index !== true,
        `Index routes must not have child routes. Please remove all child routes from route path "${path}".`
      );
      flattenRoutes(
        route.children,
        branches,
        routesMeta,
        path,
        hasParentOptionalSegments
      );
    }
    if (route.path == null && !route.index) {
      return;
    }
    branches.push({
      path,
      score: computeScore(path, route.index),
      routesMeta
    });
  };
  routes.forEach((route, index) => {
    if (route.path === "" || !route.path?.includes("?")) {
      flattenRoute(route, index);
    } else {
      for (let exploded of explodeOptionalSegments(route.path)) {
        flattenRoute(route, index, true, exploded);
      }
    }
  });
  return branches;
}
function explodeOptionalSegments(path) {
  let segments = path.split("/");
  if (segments.length === 0) return [];
  let [first2, ...rest] = segments;
  let isOptional = first2.endsWith("?");
  let required = first2.replace(/\?$/, "");
  if (rest.length === 0) {
    return isOptional ? [required, ""] : [required];
  }
  let restExploded = explodeOptionalSegments(rest.join("/"));
  let result2 = [];
  result2.push(
    ...restExploded.map(
      (subpath) => subpath === "" ? required : [required, subpath].join("/")
    )
  );
  if (isOptional) {
    result2.push(...restExploded);
  }
  return result2.map(
    (exploded) => path.startsWith("/") && exploded === "" ? "/" : exploded
  );
}
function rankRouteBranches(branches) {
  branches.sort(
    (a2, b) => a2.score !== b.score ? b.score - a2.score : compareIndexes(
      a2.routesMeta.map((meta) => meta.childrenIndex),
      b.routesMeta.map((meta) => meta.childrenIndex)
    )
  );
}
var paramRe = /^:[\w-]+$/;
var dynamicSegmentValue = 3;
var indexRouteValue = 2;
var emptySegmentValue = 1;
var staticSegmentValue = 10;
var splatPenalty = -2;
var isSplat = (s) => s === "*";
function computeScore(path, index) {
  let segments = path.split("/");
  let initialScore = segments.length;
  if (segments.some(isSplat)) {
    initialScore += splatPenalty;
  }
  if (index) {
    initialScore += indexRouteValue;
  }
  return segments.filter((s) => !isSplat(s)).reduce(
    (score, segment2) => score + (paramRe.test(segment2) ? dynamicSegmentValue : segment2 === "" ? emptySegmentValue : staticSegmentValue),
    initialScore
  );
}
function compareIndexes(a2, b) {
  let siblings = a2.length === b.length && a2.slice(0, -1).every((n2, i2) => n2 === b[i2]);
  return siblings ? (
    // If two routes are siblings, we should try to match the earlier sibling
    // first. This allows people to have fine-grained control over the matching
    // behavior by simply putting routes with identical paths in the order they
    // want them tried.
    a2[a2.length - 1] - b[b.length - 1]
  ) : (
    // Otherwise, it doesn't really make sense to rank non-siblings by index,
    // so they sort equally.
    0
  );
}
function matchRouteBranch(branch, pathname, allowPartial = false) {
  let { routesMeta } = branch;
  let matchedParams = {};
  let matchedPathname = "/";
  let matches = [];
  for (let i2 = 0; i2 < routesMeta.length; ++i2) {
    let meta = routesMeta[i2];
    let end2 = i2 === routesMeta.length - 1;
    let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
    let match3 = matchPath(
      { path: meta.relativePath, caseSensitive: meta.caseSensitive, end: end2 },
      remainingPathname
    );
    let route = meta.route;
    if (!match3 && end2 && allowPartial && !routesMeta[routesMeta.length - 1].route.index) {
      match3 = matchPath(
        {
          path: meta.relativePath,
          caseSensitive: meta.caseSensitive,
          end: false
        },
        remainingPathname
      );
    }
    if (!match3) {
      return null;
    }
    Object.assign(matchedParams, match3.params);
    matches.push({
      // TODO: Can this as be avoided?
      params: matchedParams,
      pathname: joinPaths([matchedPathname, match3.pathname]),
      pathnameBase: normalizePathname(
        joinPaths([matchedPathname, match3.pathnameBase])
      ),
      route
    });
    if (match3.pathnameBase !== "/") {
      matchedPathname = joinPaths([matchedPathname, match3.pathnameBase]);
    }
  }
  return matches;
}
function matchPath(pattern, pathname) {
  if (typeof pattern === "string") {
    pattern = { path: pattern, caseSensitive: false, end: true };
  }
  let [matcher, compiledParams] = compilePath(
    pattern.path,
    pattern.caseSensitive,
    pattern.end
  );
  let match3 = pathname.match(matcher);
  if (!match3) return null;
  let matchedPathname = match3[0];
  let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
  let captureGroups = match3.slice(1);
  let params = compiledParams.reduce(
    (memo2, { paramName, isOptional }, index) => {
      if (paramName === "*") {
        let splatValue = captureGroups[index] || "";
        pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
      }
      const value2 = captureGroups[index];
      if (isOptional && !value2) {
        memo2[paramName] = void 0;
      } else {
        memo2[paramName] = (value2 || "").replace(/%2F/g, "/");
      }
      return memo2;
    },
    {}
  );
  return {
    params,
    pathname: matchedPathname,
    pathnameBase,
    pattern
  };
}
function compilePath(path, caseSensitive = false, end2 = true) {
  warning(
    path === "*" || !path.endsWith("*") || path.endsWith("/*"),
    `Route path "${path}" will be treated as if it were "${path.replace(/\*$/, "/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${path.replace(/\*$/, "/*")}".`
  );
  let params = [];
  let regexpSource = "^" + path.replace(/\/*\*?$/, "").replace(/^\/*/, "/").replace(/[\\.*+^${}|()[\]]/g, "\\$&").replace(
    /\/:([\w-]+)(\?)?/g,
    (_, paramName, isOptional) => {
      params.push({ paramName, isOptional: isOptional != null });
      return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)";
    }
  ).replace(/\/([\w-]+)\?(\/|$)/g, "(/$1)?$2");
  if (path.endsWith("*")) {
    params.push({ paramName: "*" });
    regexpSource += path === "*" || path === "/*" ? "(.*)$" : "(?:\\/(.+)|\\/*)$";
  } else if (end2) {
    regexpSource += "\\/*$";
  } else if (path !== "" && path !== "/") {
    regexpSource += "(?:(?=\\/|$))";
  } else ;
  let matcher = new RegExp(regexpSource, caseSensitive ? void 0 : "i");
  return [matcher, params];
}
function decodePath(value2) {
  try {
    return value2.split("/").map((v) => decodeURIComponent(v).replace(/\//g, "%2F")).join("/");
  } catch (error2) {
    warning(
      false,
      `The URL path "${value2}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${error2}).`
    );
    return value2;
  }
}
function stripBasename(pathname, basename2) {
  if (basename2 === "/") return pathname;
  if (!pathname.toLowerCase().startsWith(basename2.toLowerCase())) {
    return null;
  }
  let startIndex = basename2.endsWith("/") ? basename2.length - 1 : basename2.length;
  let nextChar = pathname.charAt(startIndex);
  if (nextChar && nextChar !== "/") {
    return null;
  }
  return pathname.slice(startIndex) || "/";
}
function prependBasename({
  basename: basename2,
  pathname
}) {
  return pathname === "/" ? basename2 : joinPaths([basename2, pathname]);
}
function resolvePath(to2, fromPathname = "/") {
  let {
    pathname: toPathname,
    search = "",
    hash: hash2 = ""
  } = typeof to2 === "string" ? parsePath$1(to2) : to2;
  let pathname = toPathname ? toPathname.startsWith("/") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname;
  return {
    pathname,
    search: normalizeSearch(search),
    hash: normalizeHash(hash2)
  };
}
function resolvePathname(relativePath, fromPathname) {
  let segments = fromPathname.replace(/\/+$/, "").split("/");
  let relativeSegments = relativePath.split("/");
  relativeSegments.forEach((segment2) => {
    if (segment2 === "..") {
      if (segments.length > 1) segments.pop();
    } else if (segment2 !== ".") {
      segments.push(segment2);
    }
  });
  return segments.length > 1 ? segments.join("/") : "/";
}
function getInvalidPathError(char, field2, dest, path) {
  return `Cannot include a '${char}' character in a manually specified \`to.${field2}\` field [${JSON.stringify(
    path
  )}].  Please separate it out to the \`to.${dest}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`;
}
function getPathContributingMatches(matches) {
  return matches.filter(
    (match3, index) => index === 0 || match3.route.path && match3.route.path.length > 0
  );
}
function getResolveToMatches(matches) {
  let pathMatches = getPathContributingMatches(matches);
  return pathMatches.map(
    (match3, idx) => idx === pathMatches.length - 1 ? match3.pathname : match3.pathnameBase
  );
}
function resolveTo(toArg, routePathnames, locationPathname, isPathRelative = false) {
  let to2;
  if (typeof toArg === "string") {
    to2 = parsePath$1(toArg);
  } else {
    to2 = { ...toArg };
    invariant(
      !to2.pathname || !to2.pathname.includes("?"),
      getInvalidPathError("?", "pathname", "search", to2)
    );
    invariant(
      !to2.pathname || !to2.pathname.includes("#"),
      getInvalidPathError("#", "pathname", "hash", to2)
    );
    invariant(
      !to2.search || !to2.search.includes("#"),
      getInvalidPathError("#", "search", "hash", to2)
    );
  }
  let isEmptyPath = toArg === "" || to2.pathname === "";
  let toPathname = isEmptyPath ? "/" : to2.pathname;
  let from2;
  if (toPathname == null) {
    from2 = locationPathname;
  } else {
    let routePathnameIndex = routePathnames.length - 1;
    if (!isPathRelative && toPathname.startsWith("..")) {
      let toSegments = toPathname.split("/");
      while (toSegments[0] === "..") {
        toSegments.shift();
        routePathnameIndex -= 1;
      }
      to2.pathname = toSegments.join("/");
    }
    from2 = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
  }
  let path = resolvePath(to2, from2);
  let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
  let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
  if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {
    path.pathname += "/";
  }
  return path;
}
var joinPaths = (paths) => paths.join("/").replace(/\/\/+/g, "/");
var normalizePathname = (pathname) => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
var normalizeSearch = (search) => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
var normalizeHash = (hash2) => !hash2 || hash2 === "#" ? "" : hash2.startsWith("#") ? hash2 : "#" + hash2;
var ErrorResponseImpl = class {
  constructor(status, statusText, data2, internal = false) {
    this.status = status;
    this.statusText = statusText || "";
    this.internal = internal;
    if (data2 instanceof Error) {
      this.data = data2.toString();
      this.error = data2;
    } else {
      this.data = data2;
    }
  }
};
function isRouteErrorResponse(error2) {
  return error2 != null && typeof error2.status === "number" && typeof error2.statusText === "string" && typeof error2.internal === "boolean" && "data" in error2;
}
function getRoutePattern(paths) {
  return paths.filter(Boolean).join("/").replace(/\/\/*/g, "/") || "/";
}
var UninstrumentedSymbol = Symbol("Uninstrumented");
function getRouteInstrumentationUpdates(fns, route) {
  let aggregated = {
    lazy: [],
    "lazy.loader": [],
    "lazy.action": [],
    "lazy.middleware": [],
    middleware: [],
    loader: [],
    action: []
  };
  fns.forEach(
    (fn3) => fn3({
      id: route.id,
      index: route.index,
      path: route.path,
      instrument(i2) {
        let keys2 = Object.keys(aggregated);
        for (let key2 of keys2) {
          if (i2[key2]) {
            aggregated[key2].push(i2[key2]);
          }
        }
      }
    })
  );
  let updates = {};
  if (typeof route.lazy === "function" && aggregated.lazy.length > 0) {
    let instrumented = wrapImpl(aggregated.lazy, route.lazy, () => void 0);
    if (instrumented) {
      updates.lazy = instrumented;
    }
  }
  if (typeof route.lazy === "object") {
    let lazyObject = route.lazy;
    ["middleware", "loader", "action"].forEach((key2) => {
      let lazyFn = lazyObject[key2];
      let instrumentations = aggregated[`lazy.${key2}`];
      if (typeof lazyFn === "function" && instrumentations.length > 0) {
        let instrumented = wrapImpl(instrumentations, lazyFn, () => void 0);
        if (instrumented) {
          updates.lazy = Object.assign(updates.lazy || {}, {
            [key2]: instrumented
          });
        }
      }
    });
  }
  ["loader", "action"].forEach((key2) => {
    let handler = route[key2];
    if (typeof handler === "function" && aggregated[key2].length > 0) {
      let original = handler[UninstrumentedSymbol] ?? handler;
      let instrumented = wrapImpl(
        aggregated[key2],
        original,
        (...args2) => getHandlerInfo(args2[0])
      );
      if (instrumented) {
        instrumented[UninstrumentedSymbol] = original;
        updates[key2] = instrumented;
      }
    }
  });
  if (route.middleware && route.middleware.length > 0 && aggregated.middleware.length > 0) {
    updates.middleware = route.middleware.map((middleware) => {
      let original = middleware[UninstrumentedSymbol] ?? middleware;
      let instrumented = wrapImpl(
        aggregated.middleware,
        original,
        (...args2) => getHandlerInfo(args2[0])
      );
      if (instrumented) {
        instrumented[UninstrumentedSymbol] = original;
        return instrumented;
      }
      return middleware;
    });
  }
  return updates;
}
function instrumentClientSideRouter(router, fns) {
  let aggregated = {
    navigate: [],
    fetch: []
  };
  fns.forEach(
    (fn3) => fn3({
      instrument(i2) {
        let keys2 = Object.keys(i2);
        for (let key2 of keys2) {
          if (i2[key2]) {
            aggregated[key2].push(i2[key2]);
          }
        }
      }
    })
  );
  if (aggregated.navigate.length > 0) {
    let navigate = router.navigate[UninstrumentedSymbol] ?? router.navigate;
    let instrumentedNavigate = wrapImpl(
      aggregated.navigate,
      navigate,
      (...args2) => {
        let [to2, opts] = args2;
        return {
          to: typeof to2 === "number" || typeof to2 === "string" ? to2 : to2 ? createPath(to2) : ".",
          ...getRouterInfo(router, opts ?? {})
        };
      }
    );
    if (instrumentedNavigate) {
      instrumentedNavigate[UninstrumentedSymbol] = navigate;
      router.navigate = instrumentedNavigate;
    }
  }
  if (aggregated.fetch.length > 0) {
    let fetch2 = router.fetch[UninstrumentedSymbol] ?? router.fetch;
    let instrumentedFetch = wrapImpl(aggregated.fetch, fetch2, (...args2) => {
      let [key2, , href, opts] = args2;
      return {
        href: href ?? ".",
        fetcherKey: key2,
        ...getRouterInfo(router, opts ?? {})
      };
    });
    if (instrumentedFetch) {
      instrumentedFetch[UninstrumentedSymbol] = fetch2;
      router.fetch = instrumentedFetch;
    }
  }
  return router;
}
function wrapImpl(impls, handler, getInfo) {
  if (impls.length === 0) {
    return null;
  }
  return async (...args2) => {
    let result2 = await recurseRight(
      impls,
      getInfo(...args2),
      () => handler(...args2),
      impls.length - 1
    );
    if (result2.type === "error") {
      throw result2.value;
    }
    return result2.value;
  };
}
async function recurseRight(impls, info, handler, index) {
  let impl = impls[index];
  let result2;
  if (!impl) {
    try {
      let value2 = await handler();
      result2 = { type: "success", value: value2 };
    } catch (e) {
      result2 = { type: "error", value: e };
    }
  } else {
    let handlerPromise = void 0;
    let callHandler = async () => {
      if (handlerPromise) {
        console.error("You cannot call instrumented handlers more than once");
      } else {
        handlerPromise = recurseRight(impls, info, handler, index - 1);
      }
      result2 = await handlerPromise;
      invariant(result2, "Expected a result");
      if (result2.type === "error" && result2.value instanceof Error) {
        return { status: "error", error: result2.value };
      }
      return { status: "success", error: void 0 };
    };
    try {
      await impl(callHandler, info);
    } catch (e) {
      console.error("An instrumentation function threw an error:", e);
    }
    if (!handlerPromise) {
      await callHandler();
    }
    await handlerPromise;
  }
  if (result2) {
    return result2;
  }
  return {
    type: "error",
    value: new Error("No result assigned in instrumentation chain.")
  };
}
function getHandlerInfo(args2) {
  let { request, context, params, unstable_pattern } = args2;
  return {
    request: getReadonlyRequest(request),
    params: { ...params },
    unstable_pattern,
    context: getReadonlyContext(context)
  };
}
function getRouterInfo(router, opts) {
  return {
    currentUrl: createPath(router.state.location),
    ..."formMethod" in opts ? { formMethod: opts.formMethod } : {},
    ..."formEncType" in opts ? { formEncType: opts.formEncType } : {},
    ..."formData" in opts ? { formData: opts.formData } : {},
    ..."body" in opts ? { body: opts.body } : {}
  };
}
function getReadonlyRequest(request) {
  return {
    method: request.method,
    url: request.url,
    headers: {
      get: (...args2) => request.headers.get(...args2)
    }
  };
}
function getReadonlyContext(context) {
  if (isPlainObject$1(context)) {
    let frozen = { ...context };
    Object.freeze(frozen);
    return frozen;
  } else {
    return {
      get: (ctx) => context.get(ctx)
    };
  }
}
var objectProtoNames = Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
function isPlainObject$1(thing) {
  if (thing === null || typeof thing !== "object") {
    return false;
  }
  const proto = Object.getPrototypeOf(thing);
  return proto === Object.prototype || proto === null || Object.getOwnPropertyNames(proto).sort().join("\0") === objectProtoNames;
}
var validMutationMethodsArr = [
  "POST",
  "PUT",
  "PATCH",
  "DELETE"
];
var validMutationMethods = new Set(
  validMutationMethodsArr
);
var validRequestMethodsArr = [
  "GET",
  ...validMutationMethodsArr
];
var validRequestMethods = new Set(validRequestMethodsArr);
var redirectStatusCodes = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
var redirectPreserveMethodStatusCodes = /* @__PURE__ */ new Set([307, 308]);
var IDLE_NAVIGATION = {
  state: "idle",
  location: void 0,
  formMethod: void 0,
  formAction: void 0,
  formEncType: void 0,
  formData: void 0,
  json: void 0,
  text: void 0
};
var IDLE_FETCHER = {
  state: "idle",
  data: void 0,
  formMethod: void 0,
  formAction: void 0,
  formEncType: void 0,
  formData: void 0,
  json: void 0,
  text: void 0
};
var IDLE_BLOCKER = {
  state: "unblocked",
  proceed: void 0,
  reset: void 0,
  location: void 0
};
var ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
var isAbsoluteUrl = (url) => ABSOLUTE_URL_REGEX.test(url);
var defaultMapRouteProperties = (route) => ({
  hasErrorBoundary: Boolean(route.hasErrorBoundary)
});
var TRANSITIONS_STORAGE_KEY = "remix-router-transitions";
var ResetLoaderDataSymbol = Symbol("ResetLoaderData");
function createRouter(init) {
  const routerWindow = init.window ? init.window : typeof window !== "undefined" ? window : void 0;
  const isBrowser2 = typeof routerWindow !== "undefined" && typeof routerWindow.document !== "undefined" && typeof routerWindow.document.createElement !== "undefined";
  invariant(
    init.routes.length > 0,
    "You must provide a non-empty routes array to createRouter"
  );
  let hydrationRouteProperties2 = init.hydrationRouteProperties || [];
  let _mapRouteProperties = init.mapRouteProperties || defaultMapRouteProperties;
  let mapRouteProperties2 = _mapRouteProperties;
  if (init.unstable_instrumentations) {
    let instrumentations = init.unstable_instrumentations;
    mapRouteProperties2 = (route) => {
      return {
        ..._mapRouteProperties(route),
        ...getRouteInstrumentationUpdates(
          instrumentations.map((i2) => i2.route).filter(Boolean),
          route
        )
      };
    };
  }
  let manifest = {};
  let dataRoutes = convertRoutesToDataRoutes(
    init.routes,
    mapRouteProperties2,
    void 0,
    manifest
  );
  let inFlightDataRoutes;
  let basename2 = init.basename || "/";
  if (!basename2.startsWith("/")) {
    basename2 = `/${basename2}`;
  }
  let dataStrategyImpl = init.dataStrategy || defaultDataStrategyWithMiddleware;
  let future = {
    ...init.future
  };
  let unlistenHistory = null;
  let subscribers = /* @__PURE__ */ new Set();
  let savedScrollPositions2 = null;
  let getScrollRestorationKey2 = null;
  let getScrollPosition = null;
  let initialScrollRestored = init.hydrationData != null;
  let initialMatches = matchRoutes(dataRoutes, init.history.location, basename2);
  let initialMatchesIsFOW = false;
  let initialErrors = null;
  let initialized;
  if (initialMatches == null && !init.patchRoutesOnNavigation) {
    let error2 = getInternalRouterError(404, {
      pathname: init.history.location.pathname
    });
    let { matches, route } = getShortCircuitMatches(dataRoutes);
    initialized = true;
    initialMatches = matches;
    initialErrors = { [route.id]: error2 };
  } else {
    if (initialMatches && !init.hydrationData) {
      let fogOfWar = checkFogOfWar(
        initialMatches,
        dataRoutes,
        init.history.location.pathname
      );
      if (fogOfWar.active) {
        initialMatches = null;
      }
    }
    if (!initialMatches) {
      initialized = false;
      initialMatches = [];
      let fogOfWar = checkFogOfWar(
        null,
        dataRoutes,
        init.history.location.pathname
      );
      if (fogOfWar.active && fogOfWar.matches) {
        initialMatchesIsFOW = true;
        initialMatches = fogOfWar.matches;
      }
    } else if (initialMatches.some((m) => m.route.lazy)) {
      initialized = false;
    } else if (!initialMatches.some((m) => routeHasLoaderOrMiddleware(m.route))) {
      initialized = true;
    } else {
      let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;
      let errors2 = init.hydrationData ? init.hydrationData.errors : null;
      if (errors2) {
        let idx = initialMatches.findIndex(
          (m) => errors2[m.route.id] !== void 0
        );
        initialized = initialMatches.slice(0, idx + 1).every(
          (m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors2)
        );
      } else {
        initialized = initialMatches.every(
          (m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors2)
        );
      }
    }
  }
  let router;
  let state = {
    historyAction: init.history.action,
    location: init.history.location,
    matches: initialMatches,
    initialized,
    navigation: IDLE_NAVIGATION,
    // Don't restore on initial updateState() if we were SSR'd
    restoreScrollPosition: init.hydrationData != null ? false : null,
    preventScrollReset: false,
    revalidation: "idle",
    loaderData: init.hydrationData && init.hydrationData.loaderData || {},
    actionData: init.hydrationData && init.hydrationData.actionData || null,
    errors: init.hydrationData && init.hydrationData.errors || initialErrors,
    fetchers: /* @__PURE__ */ new Map(),
    blockers: /* @__PURE__ */ new Map()
  };
  let pendingAction = "POP";
  let pendingPreventScrollReset = false;
  let pendingNavigationController;
  let pendingViewTransitionEnabled = false;
  let appliedViewTransitions = /* @__PURE__ */ new Map();
  let removePageHideEventListener = null;
  let isUninterruptedRevalidation = false;
  let isRevalidationRequired = false;
  let cancelledFetcherLoads = /* @__PURE__ */ new Set();
  let fetchControllers = /* @__PURE__ */ new Map();
  let incrementingLoadId = 0;
  let pendingNavigationLoadId = -1;
  let fetchReloadIds = /* @__PURE__ */ new Map();
  let fetchRedirectIds = /* @__PURE__ */ new Set();
  let fetchLoadMatches = /* @__PURE__ */ new Map();
  let activeFetchers = /* @__PURE__ */ new Map();
  let fetchersQueuedForDeletion = /* @__PURE__ */ new Set();
  let blockerFunctions = /* @__PURE__ */ new Map();
  let unblockBlockerHistoryUpdate = void 0;
  let pendingRevalidationDfd = null;
  function initialize() {
    unlistenHistory = init.history.listen(
      ({ action: historyAction, location, delta }) => {
        if (unblockBlockerHistoryUpdate) {
          unblockBlockerHistoryUpdate();
          unblockBlockerHistoryUpdate = void 0;
          return;
        }
        warning(
          blockerFunctions.size === 0 || delta != null,
          "You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs.  This can also happen if you are using createHashRouter and the user manually changes the URL."
        );
        let blockerKey = shouldBlockNavigation({
          currentLocation: state.location,
          nextLocation: location,
          historyAction
        });
        if (blockerKey && delta != null) {
          let nextHistoryUpdatePromise = new Promise((resolve2) => {
            unblockBlockerHistoryUpdate = resolve2;
          });
          init.history.go(delta * -1);
          updateBlocker(blockerKey, {
            state: "blocked",
            location,
            proceed() {
              updateBlocker(blockerKey, {
                state: "proceeding",
                proceed: void 0,
                reset: void 0,
                location
              });
              nextHistoryUpdatePromise.then(() => init.history.go(delta));
            },
            reset() {
              let blockers = new Map(state.blockers);
              blockers.set(blockerKey, IDLE_BLOCKER);
              updateState({ blockers });
            }
          });
          return;
        }
        return startNavigation(historyAction, location);
      }
    );
    if (isBrowser2) {
      restoreAppliedTransitions(routerWindow, appliedViewTransitions);
      let _saveAppliedTransitions = () => persistAppliedTransitions(routerWindow, appliedViewTransitions);
      routerWindow.addEventListener("pagehide", _saveAppliedTransitions);
      removePageHideEventListener = () => routerWindow.removeEventListener("pagehide", _saveAppliedTransitions);
    }
    if (!state.initialized) {
      startNavigation("POP", state.location, {
        initialHydration: true
      });
    }
    return router;
  }
  function dispose2() {
    if (unlistenHistory) {
      unlistenHistory();
    }
    if (removePageHideEventListener) {
      removePageHideEventListener();
    }
    subscribers.clear();
    pendingNavigationController && pendingNavigationController.abort();
    state.fetchers.forEach((_, key2) => deleteFetcher(key2));
    state.blockers.forEach((_, key2) => deleteBlocker(key2));
  }
  function subscribe(fn3) {
    subscribers.add(fn3);
    return () => subscribers.delete(fn3);
  }
  function updateState(newState, opts = {}) {
    if (newState.matches) {
      newState.matches = newState.matches.map((m) => {
        let route = manifest[m.route.id];
        let matchRoute = m.route;
        if (matchRoute.element !== route.element || matchRoute.errorElement !== route.errorElement || matchRoute.hydrateFallbackElement !== route.hydrateFallbackElement) {
          return {
            ...m,
            route
          };
        }
        return m;
      });
    }
    state = {
      ...state,
      ...newState
    };
    let unmountedFetchers = [];
    let mountedFetchers = [];
    state.fetchers.forEach((fetcher, key2) => {
      if (fetcher.state === "idle") {
        if (fetchersQueuedForDeletion.has(key2)) {
          unmountedFetchers.push(key2);
        } else {
          mountedFetchers.push(key2);
        }
      }
    });
    fetchersQueuedForDeletion.forEach((key2) => {
      if (!state.fetchers.has(key2) && !fetchControllers.has(key2)) {
        unmountedFetchers.push(key2);
      }
    });
    [...subscribers].forEach(
      (subscriber) => subscriber(state, {
        deletedFetchers: unmountedFetchers,
        viewTransitionOpts: opts.viewTransitionOpts,
        flushSync: opts.flushSync === true
      })
    );
    unmountedFetchers.forEach((key2) => deleteFetcher(key2));
    mountedFetchers.forEach((key2) => state.fetchers.delete(key2));
  }
  function completeNavigation(location, newState, { flushSync } = {}) {
    let isActionReload = state.actionData != null && state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && state.navigation.state === "loading" && location.state?._isRedirect !== true;
    let actionData;
    if (newState.actionData) {
      if (Object.keys(newState.actionData).length > 0) {
        actionData = newState.actionData;
      } else {
        actionData = null;
      }
    } else if (isActionReload) {
      actionData = state.actionData;
    } else {
      actionData = null;
    }
    let loaderData = newState.loaderData ? mergeLoaderData(
      state.loaderData,
      newState.loaderData,
      newState.matches || [],
      newState.errors
    ) : state.loaderData;
    let blockers = state.blockers;
    if (blockers.size > 0) {
      blockers = new Map(blockers);
      blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));
    }
    let restoreScrollPosition = isUninterruptedRevalidation ? false : getSavedScrollPosition(location, newState.matches || state.matches);
    let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && location.state?._isRedirect !== true;
    if (inFlightDataRoutes) {
      dataRoutes = inFlightDataRoutes;
      inFlightDataRoutes = void 0;
    }
    if (isUninterruptedRevalidation) ;
    else if (pendingAction === "POP") ;
    else if (pendingAction === "PUSH") {
      init.history.push(location, location.state);
    } else if (pendingAction === "REPLACE") {
      init.history.replace(location, location.state);
    }
    let viewTransitionOpts;
    if (pendingAction === "POP") {
      let priorPaths = appliedViewTransitions.get(state.location.pathname);
      if (priorPaths && priorPaths.has(location.pathname)) {
        viewTransitionOpts = {
          currentLocation: state.location,
          nextLocation: location
        };
      } else if (appliedViewTransitions.has(location.pathname)) {
        viewTransitionOpts = {
          currentLocation: location,
          nextLocation: state.location
        };
      }
    } else if (pendingViewTransitionEnabled) {
      let toPaths = appliedViewTransitions.get(state.location.pathname);
      if (toPaths) {
        toPaths.add(location.pathname);
      } else {
        toPaths = /* @__PURE__ */ new Set([location.pathname]);
        appliedViewTransitions.set(state.location.pathname, toPaths);
      }
      viewTransitionOpts = {
        currentLocation: state.location,
        nextLocation: location
      };
    }
    updateState(
      {
        ...newState,
        // matches, errors, fetchers go through as-is
        actionData,
        loaderData,
        historyAction: pendingAction,
        location,
        initialized: true,
        navigation: IDLE_NAVIGATION,
        revalidation: "idle",
        restoreScrollPosition,
        preventScrollReset,
        blockers
      },
      {
        viewTransitionOpts,
        flushSync: flushSync === true
      }
    );
    pendingAction = "POP";
    pendingPreventScrollReset = false;
    pendingViewTransitionEnabled = false;
    isUninterruptedRevalidation = false;
    isRevalidationRequired = false;
    pendingRevalidationDfd?.resolve();
    pendingRevalidationDfd = null;
  }
  async function navigate(to2, opts) {
    if (typeof to2 === "number") {
      init.history.go(to2);
      return;
    }
    let normalizedPath = normalizeTo(
      state.location,
      state.matches,
      basename2,
      to2,
      opts?.fromRouteId,
      opts?.relative
    );
    let { path, submission, error: error2 } = normalizeNavigateOptions(
      false,
      normalizedPath,
      opts
    );
    let currentLocation = state.location;
    let nextLocation = createLocation(state.location, path, opts && opts.state);
    nextLocation = {
      ...nextLocation,
      ...init.history.encodeLocation(nextLocation)
    };
    let userReplace = opts && opts.replace != null ? opts.replace : void 0;
    let historyAction = "PUSH";
    if (userReplace === true) {
      historyAction = "REPLACE";
    } else if (userReplace === false) ;
    else if (submission != null && isMutationMethod(submission.formMethod) && submission.formAction === state.location.pathname + state.location.search) {
      historyAction = "REPLACE";
    }
    let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : void 0;
    let flushSync = (opts && opts.flushSync) === true;
    let blockerKey = shouldBlockNavigation({
      currentLocation,
      nextLocation,
      historyAction
    });
    if (blockerKey) {
      updateBlocker(blockerKey, {
        state: "blocked",
        location: nextLocation,
        proceed() {
          updateBlocker(blockerKey, {
            state: "proceeding",
            proceed: void 0,
            reset: void 0,
            location: nextLocation
          });
          navigate(to2, opts);
        },
        reset() {
          let blockers = new Map(state.blockers);
          blockers.set(blockerKey, IDLE_BLOCKER);
          updateState({ blockers });
        }
      });
      return;
    }
    await startNavigation(historyAction, nextLocation, {
      submission,
      // Send through the formData serialization error if we have one so we can
      // render at the right error boundary after we match routes
      pendingError: error2,
      preventScrollReset,
      replace: opts && opts.replace,
      enableViewTransition: opts && opts.viewTransition,
      flushSync
    });
  }
  function revalidate() {
    if (!pendingRevalidationDfd) {
      pendingRevalidationDfd = createDeferred();
    }
    interruptActiveLoads();
    updateState({ revalidation: "loading" });
    let promise = pendingRevalidationDfd.promise;
    if (state.navigation.state === "submitting") {
      return promise;
    }
    if (state.navigation.state === "idle") {
      startNavigation(state.historyAction, state.location, {
        startUninterruptedRevalidation: true
      });
      return promise;
    }
    startNavigation(
      pendingAction || state.historyAction,
      state.navigation.location,
      {
        overrideNavigation: state.navigation,
        // Proxy through any rending view transition
        enableViewTransition: pendingViewTransitionEnabled === true
      }
    );
    return promise;
  }
  async function startNavigation(historyAction, location, opts) {
    pendingNavigationController && pendingNavigationController.abort();
    pendingNavigationController = null;
    pendingAction = historyAction;
    isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true;
    saveScrollPosition(state.location, state.matches);
    pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;
    pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;
    let routesToUse = inFlightDataRoutes || dataRoutes;
    let loadingNavigation = opts && opts.overrideNavigation;
    let matches = opts?.initialHydration && state.matches && state.matches.length > 0 && !initialMatchesIsFOW ? (
      // `matchRoutes()` has already been called if we're in here via `router.initialize()`
      state.matches
    ) : matchRoutes(routesToUse, location, basename2);
    let flushSync = (opts && opts.flushSync) === true;
    if (matches && state.initialized && !isRevalidationRequired && isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) {
      completeNavigation(location, { matches }, { flushSync });
      return;
    }
    let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);
    if (fogOfWar.active && fogOfWar.matches) {
      matches = fogOfWar.matches;
    }
    if (!matches) {
      let { error: error2, notFoundMatches, route } = handleNavigational404(
        location.pathname
      );
      completeNavigation(
        location,
        {
          matches: notFoundMatches,
          loaderData: {},
          errors: {
            [route.id]: error2
          }
        },
        { flushSync }
      );
      return;
    }
    pendingNavigationController = new AbortController();
    let request = createClientSideRequest(
      init.history,
      location,
      pendingNavigationController.signal,
      opts && opts.submission
    );
    let scopedContext = init.getContext ? await init.getContext() : new RouterContextProvider();
    let pendingActionResult;
    if (opts && opts.pendingError) {
      pendingActionResult = [
        findNearestBoundary(matches).route.id,
        { type: "error", error: opts.pendingError }
      ];
    } else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) {
      let actionResult = await handleAction(
        request,
        location,
        opts.submission,
        matches,
        scopedContext,
        fogOfWar.active,
        opts && opts.initialHydration === true,
        { replace: opts.replace, flushSync }
      );
      if (actionResult.shortCircuited) {
        return;
      }
      if (actionResult.pendingActionResult) {
        let [routeId, result2] = actionResult.pendingActionResult;
        if (isErrorResult(result2) && isRouteErrorResponse(result2.error) && result2.error.status === 404) {
          pendingNavigationController = null;
          completeNavigation(location, {
            matches: actionResult.matches,
            loaderData: {},
            errors: {
              [routeId]: result2.error
            }
          });
          return;
        }
      }
      matches = actionResult.matches || matches;
      pendingActionResult = actionResult.pendingActionResult;
      loadingNavigation = getLoadingNavigation(location, opts.submission);
      flushSync = false;
      fogOfWar.active = false;
      request = createClientSideRequest(
        init.history,
        request.url,
        request.signal
      );
    }
    let {
      shortCircuited,
      matches: updatedMatches,
      loaderData,
      errors: errors2
    } = await handleLoaders(
      request,
      location,
      matches,
      scopedContext,
      fogOfWar.active,
      loadingNavigation,
      opts && opts.submission,
      opts && opts.fetcherSubmission,
      opts && opts.replace,
      opts && opts.initialHydration === true,
      flushSync,
      pendingActionResult
    );
    if (shortCircuited) {
      return;
    }
    pendingNavigationController = null;
    completeNavigation(location, {
      matches: updatedMatches || matches,
      ...getActionDataForCommit(pendingActionResult),
      loaderData,
      errors: errors2
    });
  }
  async function handleAction(request, location, submission, matches, scopedContext, isFogOfWar, initialHydration, opts = {}) {
    interruptActiveLoads();
    let navigation2 = getSubmittingNavigation(location, submission);
    updateState({ navigation: navigation2 }, { flushSync: opts.flushSync === true });
    if (isFogOfWar) {
      let discoverResult = await discoverRoutes(
        matches,
        location.pathname,
        request.signal
      );
      if (discoverResult.type === "aborted") {
        return { shortCircuited: true };
      } else if (discoverResult.type === "error") {
        if (discoverResult.partialMatches.length === 0) {
          let { matches: matches2, route } = getShortCircuitMatches(dataRoutes);
          return {
            matches: matches2,
            pendingActionResult: [
              route.id,
              {
                type: "error",
                error: discoverResult.error
              }
            ]
          };
        }
        let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;
        return {
          matches: discoverResult.partialMatches,
          pendingActionResult: [
            boundaryId,
            {
              type: "error",
              error: discoverResult.error
            }
          ]
        };
      } else if (!discoverResult.matches) {
        let { notFoundMatches, error: error2, route } = handleNavigational404(
          location.pathname
        );
        return {
          matches: notFoundMatches,
          pendingActionResult: [
            route.id,
            {
              type: "error",
              error: error2
            }
          ]
        };
      } else {
        matches = discoverResult.matches;
      }
    }
    let result2;
    let actionMatch = getTargetMatch(matches, location);
    if (!actionMatch.route.action && !actionMatch.route.lazy) {
      result2 = {
        type: "error",
        error: getInternalRouterError(405, {
          method: request.method,
          pathname: location.pathname,
          routeId: actionMatch.route.id
        })
      };
    } else {
      let dsMatches = getTargetedDataStrategyMatches(
        mapRouteProperties2,
        manifest,
        request,
        matches,
        actionMatch,
        initialHydration ? [] : hydrationRouteProperties2,
        scopedContext
      );
      let results = await callDataStrategy(
        request,
        dsMatches,
        scopedContext,
        null
      );
      result2 = results[actionMatch.route.id];
      if (!result2) {
        for (let match3 of matches) {
          if (results[match3.route.id]) {
            result2 = results[match3.route.id];
            break;
          }
        }
      }
      if (request.signal.aborted) {
        return { shortCircuited: true };
      }
    }
    if (isRedirectResult(result2)) {
      let replace2;
      if (opts && opts.replace != null) {
        replace2 = opts.replace;
      } else {
        let location2 = normalizeRedirectLocation(
          result2.response.headers.get("Location"),
          new URL(request.url),
          basename2
        );
        replace2 = location2 === state.location.pathname + state.location.search;
      }
      await startRedirectNavigation(request, result2, true, {
        submission,
        replace: replace2
      });
      return { shortCircuited: true };
    }
    if (isErrorResult(result2)) {
      let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);
      if ((opts && opts.replace) !== true) {
        pendingAction = "PUSH";
      }
      return {
        matches,
        pendingActionResult: [
          boundaryMatch.route.id,
          result2,
          actionMatch.route.id
        ]
      };
    }
    return {
      matches,
      pendingActionResult: [actionMatch.route.id, result2]
    };
  }
  async function handleLoaders(request, location, matches, scopedContext, isFogOfWar, overrideNavigation, submission, fetcherSubmission, replace2, initialHydration, flushSync, pendingActionResult) {
    let loadingNavigation = overrideNavigation || getLoadingNavigation(location, submission);
    let activeSubmission = submission || fetcherSubmission || getSubmissionFromNavigation(loadingNavigation);
    let shouldUpdateNavigationState = !isUninterruptedRevalidation && !initialHydration;
    if (isFogOfWar) {
      if (shouldUpdateNavigationState) {
        let actionData = getUpdatedActionData(pendingActionResult);
        updateState(
          {
            navigation: loadingNavigation,
            ...actionData !== void 0 ? { actionData } : {}
          },
          {
            flushSync
          }
        );
      }
      let discoverResult = await discoverRoutes(
        matches,
        location.pathname,
        request.signal
      );
      if (discoverResult.type === "aborted") {
        return { shortCircuited: true };
      } else if (discoverResult.type === "error") {
        if (discoverResult.partialMatches.length === 0) {
          let { matches: matches2, route } = getShortCircuitMatches(dataRoutes);
          return {
            matches: matches2,
            loaderData: {},
            errors: {
              [route.id]: discoverResult.error
            }
          };
        }
        let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;
        return {
          matches: discoverResult.partialMatches,
          loaderData: {},
          errors: {
            [boundaryId]: discoverResult.error
          }
        };
      } else if (!discoverResult.matches) {
        let { error: error2, notFoundMatches, route } = handleNavigational404(
          location.pathname
        );
        return {
          matches: notFoundMatches,
          loaderData: {},
          errors: {
            [route.id]: error2
          }
        };
      } else {
        matches = discoverResult.matches;
      }
    }
    let routesToUse = inFlightDataRoutes || dataRoutes;
    let { dsMatches, revalidatingFetchers } = getMatchesToLoad(
      request,
      scopedContext,
      mapRouteProperties2,
      manifest,
      init.history,
      state,
      matches,
      activeSubmission,
      location,
      initialHydration ? [] : hydrationRouteProperties2,
      initialHydration === true,
      isRevalidationRequired,
      cancelledFetcherLoads,
      fetchersQueuedForDeletion,
      fetchLoadMatches,
      fetchRedirectIds,
      routesToUse,
      basename2,
      init.patchRoutesOnNavigation != null,
      pendingActionResult
    );
    pendingNavigationLoadId = ++incrementingLoadId;
    if (!init.dataStrategy && !dsMatches.some((m) => m.shouldLoad) && !dsMatches.some(
      (m) => m.route.middleware && m.route.middleware.length > 0
    ) && revalidatingFetchers.length === 0) {
      let updatedFetchers2 = markFetchRedirectsDone();
      completeNavigation(
        location,
        {
          matches,
          loaderData: {},
          // Commit pending error if we're short circuiting
          errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? { [pendingActionResult[0]]: pendingActionResult[1].error } : null,
          ...getActionDataForCommit(pendingActionResult),
          ...updatedFetchers2 ? { fetchers: new Map(state.fetchers) } : {}
        },
        { flushSync }
      );
      return { shortCircuited: true };
    }
    if (shouldUpdateNavigationState) {
      let updates = {};
      if (!isFogOfWar) {
        updates.navigation = loadingNavigation;
        let actionData = getUpdatedActionData(pendingActionResult);
        if (actionData !== void 0) {
          updates.actionData = actionData;
        }
      }
      if (revalidatingFetchers.length > 0) {
        updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);
      }
      updateState(updates, { flushSync });
    }
    revalidatingFetchers.forEach((rf) => {
      abortFetcher(rf.key);
      if (rf.controller) {
        fetchControllers.set(rf.key, rf.controller);
      }
    });
    let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach((f) => abortFetcher(f.key));
    if (pendingNavigationController) {
      pendingNavigationController.signal.addEventListener(
        "abort",
        abortPendingFetchRevalidations
      );
    }
    let { loaderResults, fetcherResults } = await callLoadersAndMaybeResolveData(
      dsMatches,
      revalidatingFetchers,
      request,
      scopedContext
    );
    if (request.signal.aborted) {
      return { shortCircuited: true };
    }
    if (pendingNavigationController) {
      pendingNavigationController.signal.removeEventListener(
        "abort",
        abortPendingFetchRevalidations
      );
    }
    revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));
    let redirect2 = findRedirect(loaderResults);
    if (redirect2) {
      await startRedirectNavigation(request, redirect2.result, true, {
        replace: replace2
      });
      return { shortCircuited: true };
    }
    redirect2 = findRedirect(fetcherResults);
    if (redirect2) {
      fetchRedirectIds.add(redirect2.key);
      await startRedirectNavigation(request, redirect2.result, true, {
        replace: replace2
      });
      return { shortCircuited: true };
    }
    let { loaderData, errors: errors2 } = processLoaderData(
      state,
      matches,
      loaderResults,
      pendingActionResult,
      revalidatingFetchers,
      fetcherResults
    );
    if (initialHydration && state.errors) {
      errors2 = { ...state.errors, ...errors2 };
    }
    let updatedFetchers = markFetchRedirectsDone();
    let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);
    let shouldUpdateFetchers = updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;
    return {
      matches,
      loaderData,
      errors: errors2,
      ...shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}
    };
  }
  function getUpdatedActionData(pendingActionResult) {
    if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {
      return {
        [pendingActionResult[0]]: pendingActionResult[1].data
      };
    } else if (state.actionData) {
      if (Object.keys(state.actionData).length === 0) {
        return null;
      } else {
        return state.actionData;
      }
    }
  }
  function getUpdatedRevalidatingFetchers(revalidatingFetchers) {
    revalidatingFetchers.forEach((rf) => {
      let fetcher = state.fetchers.get(rf.key);
      let revalidatingFetcher = getLoadingFetcher(
        void 0,
        fetcher ? fetcher.data : void 0
      );
      state.fetchers.set(rf.key, revalidatingFetcher);
    });
    return new Map(state.fetchers);
  }
  async function fetch2(key2, routeId, href, opts) {
    abortFetcher(key2);
    let flushSync = (opts && opts.flushSync) === true;
    let routesToUse = inFlightDataRoutes || dataRoutes;
    let normalizedPath = normalizeTo(
      state.location,
      state.matches,
      basename2,
      href,
      routeId,
      opts?.relative
    );
    let matches = matchRoutes(routesToUse, normalizedPath, basename2);
    let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath);
    if (fogOfWar.active && fogOfWar.matches) {
      matches = fogOfWar.matches;
    }
    if (!matches) {
      setFetcherError(
        key2,
        routeId,
        getInternalRouterError(404, { pathname: normalizedPath }),
        { flushSync }
      );
      return;
    }
    let { path, submission, error: error2 } = normalizeNavigateOptions(
      true,
      normalizedPath,
      opts
    );
    if (error2) {
      setFetcherError(key2, routeId, error2, { flushSync });
      return;
    }
    let scopedContext = init.getContext ? await init.getContext() : new RouterContextProvider();
    let preventScrollReset = (opts && opts.preventScrollReset) === true;
    if (submission && isMutationMethod(submission.formMethod)) {
      await handleFetcherAction(
        key2,
        routeId,
        path,
        matches,
        scopedContext,
        fogOfWar.active,
        flushSync,
        preventScrollReset,
        submission
      );
      return;
    }
    fetchLoadMatches.set(key2, { routeId, path });
    await handleFetcherLoader(
      key2,
      routeId,
      path,
      matches,
      scopedContext,
      fogOfWar.active,
      flushSync,
      preventScrollReset,
      submission
    );
  }
  async function handleFetcherAction(key2, routeId, path, requestMatches, scopedContext, isFogOfWar, flushSync, preventScrollReset, submission) {
    interruptActiveLoads();
    fetchLoadMatches.delete(key2);
    let existingFetcher = state.fetchers.get(key2);
    updateFetcherState(key2, getSubmittingFetcher(submission, existingFetcher), {
      flushSync
    });
    let abortController = new AbortController();
    let fetchRequest = createClientSideRequest(
      init.history,
      path,
      abortController.signal,
      submission
    );
    if (isFogOfWar) {
      let discoverResult = await discoverRoutes(
        requestMatches,
        new URL(fetchRequest.url).pathname,
        fetchRequest.signal,
        key2
      );
      if (discoverResult.type === "aborted") {
        return;
      } else if (discoverResult.type === "error") {
        setFetcherError(key2, routeId, discoverResult.error, { flushSync });
        return;
      } else if (!discoverResult.matches) {
        setFetcherError(
          key2,
          routeId,
          getInternalRouterError(404, { pathname: path }),
          { flushSync }
        );
        return;
      } else {
        requestMatches = discoverResult.matches;
      }
    }
    let match3 = getTargetMatch(requestMatches, path);
    if (!match3.route.action && !match3.route.lazy) {
      let error2 = getInternalRouterError(405, {
        method: submission.formMethod,
        pathname: path,
        routeId
      });
      setFetcherError(key2, routeId, error2, { flushSync });
      return;
    }
    fetchControllers.set(key2, abortController);
    let originatingLoadId = incrementingLoadId;
    let fetchMatches = getTargetedDataStrategyMatches(
      mapRouteProperties2,
      manifest,
      fetchRequest,
      requestMatches,
      match3,
      hydrationRouteProperties2,
      scopedContext
    );
    let actionResults = await callDataStrategy(
      fetchRequest,
      fetchMatches,
      scopedContext,
      key2
    );
    let actionResult = actionResults[match3.route.id];
    if (fetchRequest.signal.aborted) {
      if (fetchControllers.get(key2) === abortController) {
        fetchControllers.delete(key2);
      }
      return;
    }
    if (fetchersQueuedForDeletion.has(key2)) {
      if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {
        updateFetcherState(key2, getDoneFetcher(void 0));
        return;
      }
    } else {
      if (isRedirectResult(actionResult)) {
        fetchControllers.delete(key2);
        if (pendingNavigationLoadId > originatingLoadId) {
          updateFetcherState(key2, getDoneFetcher(void 0));
          return;
        } else {
          fetchRedirectIds.add(key2);
          updateFetcherState(key2, getLoadingFetcher(submission));
          return startRedirectNavigation(fetchRequest, actionResult, false, {
            fetcherSubmission: submission,
            preventScrollReset
          });
        }
      }
      if (isErrorResult(actionResult)) {
        setFetcherError(key2, routeId, actionResult.error);
        return;
      }
    }
    let nextLocation = state.navigation.location || state.location;
    let revalidationRequest = createClientSideRequest(
      init.history,
      nextLocation,
      abortController.signal
    );
    let routesToUse = inFlightDataRoutes || dataRoutes;
    let matches = state.navigation.state !== "idle" ? matchRoutes(routesToUse, state.navigation.location, basename2) : state.matches;
    invariant(matches, "Didn't find any matches after fetcher action");
    let loadId = ++incrementingLoadId;
    fetchReloadIds.set(key2, loadId);
    let loadFetcher = getLoadingFetcher(submission, actionResult.data);
    state.fetchers.set(key2, loadFetcher);
    let { dsMatches, revalidatingFetchers } = getMatchesToLoad(
      revalidationRequest,
      scopedContext,
      mapRouteProperties2,
      manifest,
      init.history,
      state,
      matches,
      submission,
      nextLocation,
      hydrationRouteProperties2,
      false,
      isRevalidationRequired,
      cancelledFetcherLoads,
      fetchersQueuedForDeletion,
      fetchLoadMatches,
      fetchRedirectIds,
      routesToUse,
      basename2,
      init.patchRoutesOnNavigation != null,
      [match3.route.id, actionResult]
    );
    revalidatingFetchers.filter((rf) => rf.key !== key2).forEach((rf) => {
      let staleKey = rf.key;
      let existingFetcher2 = state.fetchers.get(staleKey);
      let revalidatingFetcher = getLoadingFetcher(
        void 0,
        existingFetcher2 ? existingFetcher2.data : void 0
      );
      state.fetchers.set(staleKey, revalidatingFetcher);
      abortFetcher(staleKey);
      if (rf.controller) {
        fetchControllers.set(staleKey, rf.controller);
      }
    });
    updateState({ fetchers: new Map(state.fetchers) });
    let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));
    abortController.signal.addEventListener(
      "abort",
      abortPendingFetchRevalidations
    );
    let { loaderResults, fetcherResults } = await callLoadersAndMaybeResolveData(
      dsMatches,
      revalidatingFetchers,
      revalidationRequest,
      scopedContext
    );
    if (abortController.signal.aborted) {
      return;
    }
    abortController.signal.removeEventListener(
      "abort",
      abortPendingFetchRevalidations
    );
    fetchReloadIds.delete(key2);
    fetchControllers.delete(key2);
    revalidatingFetchers.forEach((r2) => fetchControllers.delete(r2.key));
    if (state.fetchers.has(key2)) {
      let doneFetcher = getDoneFetcher(actionResult.data);
      state.fetchers.set(key2, doneFetcher);
    }
    let redirect2 = findRedirect(loaderResults);
    if (redirect2) {
      return startRedirectNavigation(
        revalidationRequest,
        redirect2.result,
        false,
        { preventScrollReset }
      );
    }
    redirect2 = findRedirect(fetcherResults);
    if (redirect2) {
      fetchRedirectIds.add(redirect2.key);
      return startRedirectNavigation(
        revalidationRequest,
        redirect2.result,
        false,
        { preventScrollReset }
      );
    }
    let { loaderData, errors: errors2 } = processLoaderData(
      state,
      matches,
      loaderResults,
      void 0,
      revalidatingFetchers,
      fetcherResults
    );
    abortStaleFetchLoads(loadId);
    if (state.navigation.state === "loading" && loadId > pendingNavigationLoadId) {
      invariant(pendingAction, "Expected pending action");
      pendingNavigationController && pendingNavigationController.abort();
      completeNavigation(state.navigation.location, {
        matches,
        loaderData,
        errors: errors2,
        fetchers: new Map(state.fetchers)
      });
    } else {
      updateState({
        errors: errors2,
        loaderData: mergeLoaderData(
          state.loaderData,
          loaderData,
          matches,
          errors2
        ),
        fetchers: new Map(state.fetchers)
      });
      isRevalidationRequired = false;
    }
  }
  async function handleFetcherLoader(key2, routeId, path, matches, scopedContext, isFogOfWar, flushSync, preventScrollReset, submission) {
    let existingFetcher = state.fetchers.get(key2);
    updateFetcherState(
      key2,
      getLoadingFetcher(
        submission,
        existingFetcher ? existingFetcher.data : void 0
      ),
      { flushSync }
    );
    let abortController = new AbortController();
    let fetchRequest = createClientSideRequest(
      init.history,
      path,
      abortController.signal
    );
    if (isFogOfWar) {
      let discoverResult = await discoverRoutes(
        matches,
        new URL(fetchRequest.url).pathname,
        fetchRequest.signal,
        key2
      );
      if (discoverResult.type === "aborted") {
        return;
      } else if (discoverResult.type === "error") {
        setFetcherError(key2, routeId, discoverResult.error, { flushSync });
        return;
      } else if (!discoverResult.matches) {
        setFetcherError(
          key2,
          routeId,
          getInternalRouterError(404, { pathname: path }),
          { flushSync }
        );
        return;
      } else {
        matches = discoverResult.matches;
      }
    }
    let match3 = getTargetMatch(matches, path);
    fetchControllers.set(key2, abortController);
    let originatingLoadId = incrementingLoadId;
    let dsMatches = getTargetedDataStrategyMatches(
      mapRouteProperties2,
      manifest,
      fetchRequest,
      matches,
      match3,
      hydrationRouteProperties2,
      scopedContext
    );
    let results = await callDataStrategy(
      fetchRequest,
      dsMatches,
      scopedContext,
      key2
    );
    let result2 = results[match3.route.id];
    if (fetchControllers.get(key2) === abortController) {
      fetchControllers.delete(key2);
    }
    if (fetchRequest.signal.aborted) {
      return;
    }
    if (fetchersQueuedForDeletion.has(key2)) {
      updateFetcherState(key2, getDoneFetcher(void 0));
      return;
    }
    if (isRedirectResult(result2)) {
      if (pendingNavigationLoadId > originatingLoadId) {
        updateFetcherState(key2, getDoneFetcher(void 0));
        return;
      } else {
        fetchRedirectIds.add(key2);
        await startRedirectNavigation(fetchRequest, result2, false, {
          preventScrollReset
        });
        return;
      }
    }
    if (isErrorResult(result2)) {
      setFetcherError(key2, routeId, result2.error);
      return;
    }
    updateFetcherState(key2, getDoneFetcher(result2.data));
  }
  async function startRedirectNavigation(request, redirect2, isNavigation, {
    submission,
    fetcherSubmission,
    preventScrollReset,
    replace: replace2
  } = {}) {
    if (redirect2.response.headers.has("X-Remix-Revalidate")) {
      isRevalidationRequired = true;
    }
    let location = redirect2.response.headers.get("Location");
    invariant(location, "Expected a Location header on the redirect Response");
    location = normalizeRedirectLocation(
      location,
      new URL(request.url),
      basename2
    );
    let redirectLocation = createLocation(state.location, location, {
      _isRedirect: true
    });
    if (isBrowser2) {
      let isDocumentReload = false;
      if (redirect2.response.headers.has("X-Remix-Reload-Document")) {
        isDocumentReload = true;
      } else if (isAbsoluteUrl(location)) {
        const url = createBrowserURLImpl(location, true);
        isDocumentReload = // Hard reload if it's an absolute URL to a new origin
        url.origin !== routerWindow.location.origin || // Hard reload if it's an absolute URL that does not match our basename
        stripBasename(url.pathname, basename2) == null;
      }
      if (isDocumentReload) {
        if (replace2) {
          routerWindow.location.replace(location);
        } else {
          routerWindow.location.assign(location);
        }
        return;
      }
    }
    pendingNavigationController = null;
    let redirectNavigationType = replace2 === true || redirect2.response.headers.has("X-Remix-Replace") ? "REPLACE" : "PUSH";
    let { formMethod, formAction, formEncType } = state.navigation;
    if (!submission && !fetcherSubmission && formMethod && formAction && formEncType) {
      submission = getSubmissionFromNavigation(state.navigation);
    }
    let activeSubmission = submission || fetcherSubmission;
    if (redirectPreserveMethodStatusCodes.has(redirect2.response.status) && activeSubmission && isMutationMethod(activeSubmission.formMethod)) {
      await startNavigation(redirectNavigationType, redirectLocation, {
        submission: {
          ...activeSubmission,
          formAction: location
        },
        // Preserve these flags across redirects
        preventScrollReset: preventScrollReset || pendingPreventScrollReset,
        enableViewTransition: isNavigation ? pendingViewTransitionEnabled : void 0
      });
    } else {
      let overrideNavigation = getLoadingNavigation(
        redirectLocation,
        submission
      );
      await startNavigation(redirectNavigationType, redirectLocation, {
        overrideNavigation,
        // Send fetcher submissions through for shouldRevalidate
        fetcherSubmission,
        // Preserve these flags across redirects
        preventScrollReset: preventScrollReset || pendingPreventScrollReset,
        enableViewTransition: isNavigation ? pendingViewTransitionEnabled : void 0
      });
    }
  }
  async function callDataStrategy(request, matches, scopedContext, fetcherKey) {
    let results;
    let dataResults = {};
    try {
      results = await callDataStrategyImpl(
        dataStrategyImpl,
        request,
        matches,
        fetcherKey,
        scopedContext,
        false
      );
    } catch (e) {
      matches.filter((m) => m.shouldLoad).forEach((m) => {
        dataResults[m.route.id] = {
          type: "error",
          error: e
        };
      });
      return dataResults;
    }
    if (request.signal.aborted) {
      return dataResults;
    }
    for (let [routeId, result2] of Object.entries(results)) {
      if (isRedirectDataStrategyResult(result2)) {
        let response = result2.result;
        dataResults[routeId] = {
          type: "redirect",
          response: normalizeRelativeRoutingRedirectResponse(
            response,
            request,
            routeId,
            matches,
            basename2
          )
        };
      } else {
        dataResults[routeId] = await convertDataStrategyResultToDataResult(result2);
      }
    }
    return dataResults;
  }
  async function callLoadersAndMaybeResolveData(matches, fetchersToLoad, request, scopedContext) {
    let loaderResultsPromise = callDataStrategy(
      request,
      matches,
      scopedContext,
      null
    );
    let fetcherResultsPromise = Promise.all(
      fetchersToLoad.map(async (f) => {
        if (f.matches && f.match && f.request && f.controller) {
          let results = await callDataStrategy(
            f.request,
            f.matches,
            scopedContext,
            f.key
          );
          let result2 = results[f.match.route.id];
          return { [f.key]: result2 };
        } else {
          return Promise.resolve({
            [f.key]: {
              type: "error",
              error: getInternalRouterError(404, {
                pathname: f.path
              })
            }
          });
        }
      })
    );
    let loaderResults = await loaderResultsPromise;
    let fetcherResults = (await fetcherResultsPromise).reduce(
      (acc, r2) => Object.assign(acc, r2),
      {}
    );
    return {
      loaderResults,
      fetcherResults
    };
  }
  function interruptActiveLoads() {
    isRevalidationRequired = true;
    fetchLoadMatches.forEach((_, key2) => {
      if (fetchControllers.has(key2)) {
        cancelledFetcherLoads.add(key2);
      }
      abortFetcher(key2);
    });
  }
  function updateFetcherState(key2, fetcher, opts = {}) {
    state.fetchers.set(key2, fetcher);
    updateState(
      { fetchers: new Map(state.fetchers) },
      { flushSync: (opts && opts.flushSync) === true }
    );
  }
  function setFetcherError(key2, routeId, error2, opts = {}) {
    let boundaryMatch = findNearestBoundary(state.matches, routeId);
    deleteFetcher(key2);
    updateState(
      {
        errors: {
          [boundaryMatch.route.id]: error2
        },
        fetchers: new Map(state.fetchers)
      },
      { flushSync: (opts && opts.flushSync) === true }
    );
  }
  function getFetcher(key2) {
    activeFetchers.set(key2, (activeFetchers.get(key2) || 0) + 1);
    if (fetchersQueuedForDeletion.has(key2)) {
      fetchersQueuedForDeletion.delete(key2);
    }
    return state.fetchers.get(key2) || IDLE_FETCHER;
  }
  function resetFetcher(key2, opts) {
    abortFetcher(key2, opts?.reason);
    updateFetcherState(key2, getDoneFetcher(null));
  }
  function deleteFetcher(key2) {
    let fetcher = state.fetchers.get(key2);
    if (fetchControllers.has(key2) && !(fetcher && fetcher.state === "loading" && fetchReloadIds.has(key2))) {
      abortFetcher(key2);
    }
    fetchLoadMatches.delete(key2);
    fetchReloadIds.delete(key2);
    fetchRedirectIds.delete(key2);
    fetchersQueuedForDeletion.delete(key2);
    cancelledFetcherLoads.delete(key2);
    state.fetchers.delete(key2);
  }
  function queueFetcherForDeletion(key2) {
    let count2 = (activeFetchers.get(key2) || 0) - 1;
    if (count2 <= 0) {
      activeFetchers.delete(key2);
      fetchersQueuedForDeletion.add(key2);
    } else {
      activeFetchers.set(key2, count2);
    }
    updateState({ fetchers: new Map(state.fetchers) });
  }
  function abortFetcher(key2, reason) {
    let controller = fetchControllers.get(key2);
    if (controller) {
      controller.abort(reason);
      fetchControllers.delete(key2);
    }
  }
  function markFetchersDone(keys2) {
    for (let key2 of keys2) {
      let fetcher = getFetcher(key2);
      let doneFetcher = getDoneFetcher(fetcher.data);
      state.fetchers.set(key2, doneFetcher);
    }
  }
  function markFetchRedirectsDone() {
    let doneKeys = [];
    let updatedFetchers = false;
    for (let key2 of fetchRedirectIds) {
      let fetcher = state.fetchers.get(key2);
      invariant(fetcher, `Expected fetcher: ${key2}`);
      if (fetcher.state === "loading") {
        fetchRedirectIds.delete(key2);
        doneKeys.push(key2);
        updatedFetchers = true;
      }
    }
    markFetchersDone(doneKeys);
    return updatedFetchers;
  }
  function abortStaleFetchLoads(landedId) {
    let yeetedKeys = [];
    for (let [key2, id2] of fetchReloadIds) {
      if (id2 < landedId) {
        let fetcher = state.fetchers.get(key2);
        invariant(fetcher, `Expected fetcher: ${key2}`);
        if (fetcher.state === "loading") {
          abortFetcher(key2);
          fetchReloadIds.delete(key2);
          yeetedKeys.push(key2);
        }
      }
    }
    markFetchersDone(yeetedKeys);
    return yeetedKeys.length > 0;
  }
  function getBlocker(key2, fn3) {
    let blocker = state.blockers.get(key2) || IDLE_BLOCKER;
    if (blockerFunctions.get(key2) !== fn3) {
      blockerFunctions.set(key2, fn3);
    }
    return blocker;
  }
  function deleteBlocker(key2) {
    state.blockers.delete(key2);
    blockerFunctions.delete(key2);
  }
  function updateBlocker(key2, newBlocker) {
    let blocker = state.blockers.get(key2) || IDLE_BLOCKER;
    invariant(
      blocker.state === "unblocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "proceeding" || blocker.state === "blocked" && newBlocker.state === "unblocked" || blocker.state === "proceeding" && newBlocker.state === "unblocked",
      `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}`
    );
    let blockers = new Map(state.blockers);
    blockers.set(key2, newBlocker);
    updateState({ blockers });
  }
  function shouldBlockNavigation({
    currentLocation,
    nextLocation,
    historyAction
  }) {
    if (blockerFunctions.size === 0) {
      return;
    }
    if (blockerFunctions.size > 1) {
      warning(false, "A router only supports one blocker at a time");
    }
    let entries2 = Array.from(blockerFunctions.entries());
    let [blockerKey, blockerFunction] = entries2[entries2.length - 1];
    let blocker = state.blockers.get(blockerKey);
    if (blocker && blocker.state === "proceeding") {
      return;
    }
    if (blockerFunction({ currentLocation, nextLocation, historyAction })) {
      return blockerKey;
    }
  }
  function handleNavigational404(pathname) {
    let error2 = getInternalRouterError(404, { pathname });
    let routesToUse = inFlightDataRoutes || dataRoutes;
    let { matches, route } = getShortCircuitMatches(routesToUse);
    return { notFoundMatches: matches, route, error: error2 };
  }
  function enableScrollRestoration(positions, getPosition, getKey) {
    savedScrollPositions2 = positions;
    getScrollPosition = getPosition;
    getScrollRestorationKey2 = getKey || null;
    if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {
      initialScrollRestored = true;
      let y = getSavedScrollPosition(state.location, state.matches);
      if (y != null) {
        updateState({ restoreScrollPosition: y });
      }
    }
    return () => {
      savedScrollPositions2 = null;
      getScrollPosition = null;
      getScrollRestorationKey2 = null;
    };
  }
  function getScrollKey(location, matches) {
    if (getScrollRestorationKey2) {
      let key2 = getScrollRestorationKey2(
        location,
        matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))
      );
      return key2 || location.key;
    }
    return location.key;
  }
  function saveScrollPosition(location, matches) {
    if (savedScrollPositions2 && getScrollPosition) {
      let key2 = getScrollKey(location, matches);
      savedScrollPositions2[key2] = getScrollPosition();
    }
  }
  function getSavedScrollPosition(location, matches) {
    if (savedScrollPositions2) {
      let key2 = getScrollKey(location, matches);
      let y = savedScrollPositions2[key2];
      if (typeof y === "number") {
        return y;
      }
    }
    return null;
  }
  function checkFogOfWar(matches, routesToUse, pathname) {
    if (init.patchRoutesOnNavigation) {
      if (!matches) {
        let fogMatches = matchRoutesImpl(
          routesToUse,
          pathname,
          basename2,
          true
        );
        return { active: true, matches: fogMatches || [] };
      } else {
        if (Object.keys(matches[0].params).length > 0) {
          let partialMatches = matchRoutesImpl(
            routesToUse,
            pathname,
            basename2,
            true
          );
          return { active: true, matches: partialMatches };
        }
      }
    }
    return { active: false, matches: null };
  }
  async function discoverRoutes(matches, pathname, signal, fetcherKey) {
    if (!init.patchRoutesOnNavigation) {
      return { type: "success", matches };
    }
    let partialMatches = matches;
    while (true) {
      let isNonHMR = inFlightDataRoutes == null;
      let routesToUse = inFlightDataRoutes || dataRoutes;
      let localManifest = manifest;
      try {
        await init.patchRoutesOnNavigation({
          signal,
          path: pathname,
          matches: partialMatches,
          fetcherKey,
          patch: (routeId, children2) => {
            if (signal.aborted) return;
            patchRoutesImpl(
              routeId,
              children2,
              routesToUse,
              localManifest,
              mapRouteProperties2,
              false
            );
          }
        });
      } catch (e) {
        return { type: "error", error: e, partialMatches };
      } finally {
        if (isNonHMR && !signal.aborted) {
          dataRoutes = [...dataRoutes];
        }
      }
      if (signal.aborted) {
        return { type: "aborted" };
      }
      let newMatches = matchRoutes(routesToUse, pathname, basename2);
      if (newMatches) {
        return { type: "success", matches: newMatches };
      }
      let newPartialMatches = matchRoutesImpl(
        routesToUse,
        pathname,
        basename2,
        true
      );
      if (!newPartialMatches || partialMatches.length === newPartialMatches.length && partialMatches.every(
        (m, i2) => m.route.id === newPartialMatches[i2].route.id
      )) {
        return { type: "success", matches: null };
      }
      partialMatches = newPartialMatches;
    }
  }
  function _internalSetRoutes(newRoutes) {
    manifest = {};
    inFlightDataRoutes = convertRoutesToDataRoutes(
      newRoutes,
      mapRouteProperties2,
      void 0,
      manifest
    );
  }
  function patchRoutes(routeId, children2, unstable_allowElementMutations = false) {
    let isNonHMR = inFlightDataRoutes == null;
    let routesToUse = inFlightDataRoutes || dataRoutes;
    patchRoutesImpl(
      routeId,
      children2,
      routesToUse,
      manifest,
      mapRouteProperties2,
      unstable_allowElementMutations
    );
    if (isNonHMR) {
      dataRoutes = [...dataRoutes];
      updateState({});
    }
  }
  router = {
    get basename() {
      return basename2;
    },
    get future() {
      return future;
    },
    get state() {
      return state;
    },
    get routes() {
      return dataRoutes;
    },
    get window() {
      return routerWindow;
    },
    initialize,
    subscribe,
    enableScrollRestoration,
    navigate,
    fetch: fetch2,
    revalidate,
    // Passthrough to history-aware createHref used by useHref so we get proper
    // hash-aware URLs in DOM paths
    createHref: (to2) => init.history.createHref(to2),
    encodeLocation: (to2) => init.history.encodeLocation(to2),
    getFetcher,
    resetFetcher,
    deleteFetcher: queueFetcherForDeletion,
    dispose: dispose2,
    getBlocker,
    deleteBlocker,
    patchRoutes,
    _internalFetchControllers: fetchControllers,
    // TODO: Remove setRoutes, it's temporary to avoid dealing with
    // updating the tree while validating the update algorithm.
    _internalSetRoutes,
    _internalSetStateDoNotUseOrYouWillBreakYourApp(newState) {
      updateState(newState);
    }
  };
  if (init.unstable_instrumentations) {
    router = instrumentClientSideRouter(
      router,
      init.unstable_instrumentations.map((i2) => i2.router).filter(Boolean)
    );
  }
  return router;
}
function isSubmissionNavigation(opts) {
  return opts != null && ("formData" in opts && opts.formData != null || "body" in opts && opts.body !== void 0);
}
function normalizeTo(location, matches, basename2, to2, fromRouteId, relative) {
  let contextualMatches;
  let activeRouteMatch;
  if (fromRouteId) {
    contextualMatches = [];
    for (let match3 of matches) {
      contextualMatches.push(match3);
      if (match3.route.id === fromRouteId) {
        activeRouteMatch = match3;
        break;
      }
    }
  } else {
    contextualMatches = matches;
    activeRouteMatch = matches[matches.length - 1];
  }
  let path = resolveTo(
    to2 ? to2 : ".",
    getResolveToMatches(contextualMatches),
    stripBasename(location.pathname, basename2) || location.pathname,
    relative === "path"
  );
  if (to2 == null) {
    path.search = location.search;
    path.hash = location.hash;
  }
  if ((to2 == null || to2 === "" || to2 === ".") && activeRouteMatch) {
    let nakedIndex = hasNakedIndexQuery(path.search);
    if (activeRouteMatch.route.index && !nakedIndex) {
      path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
    } else if (!activeRouteMatch.route.index && nakedIndex) {
      let params = new URLSearchParams(path.search);
      let indexValues = params.getAll("index");
      params.delete("index");
      indexValues.filter((v) => v).forEach((v) => params.append("index", v));
      let qs = params.toString();
      path.search = qs ? `?${qs}` : "";
    }
  }
  if (basename2 !== "/") {
    path.pathname = prependBasename({ basename: basename2, pathname: path.pathname });
  }
  return createPath(path);
}
function normalizeNavigateOptions(isFetcher, path, opts) {
  if (!opts || !isSubmissionNavigation(opts)) {
    return { path };
  }
  if (opts.formMethod && !isValidMethod(opts.formMethod)) {
    return {
      path,
      error: getInternalRouterError(405, { method: opts.formMethod })
    };
  }
  let getInvalidBodyError = () => ({
    path,
    error: getInternalRouterError(400, { type: "invalid-body" })
  });
  let rawFormMethod = opts.formMethod || "get";
  let formMethod = rawFormMethod.toUpperCase();
  let formAction = stripHashFromPath(path);
  if (opts.body !== void 0) {
    if (opts.formEncType === "text/plain") {
      if (!isMutationMethod(formMethod)) {
        return getInvalidBodyError();
      }
      let text2 = typeof opts.body === "string" ? opts.body : opts.body instanceof FormData || opts.body instanceof URLSearchParams ? (
        // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data
        Array.from(opts.body.entries()).reduce(
          (acc, [name2, value2]) => `${acc}${name2}=${value2}
`,
          ""
        )
      ) : String(opts.body);
      return {
        path,
        submission: {
          formMethod,
          formAction,
          formEncType: opts.formEncType,
          formData: void 0,
          json: void 0,
          text: text2
        }
      };
    } else if (opts.formEncType === "application/json") {
      if (!isMutationMethod(formMethod)) {
        return getInvalidBodyError();
      }
      try {
        let json2 = typeof opts.body === "string" ? JSON.parse(opts.body) : opts.body;
        return {
          path,
          submission: {
            formMethod,
            formAction,
            formEncType: opts.formEncType,
            formData: void 0,
            json: json2,
            text: void 0
          }
        };
      } catch (e) {
        return getInvalidBodyError();
      }
    }
  }
  invariant(
    typeof FormData === "function",
    "FormData is not available in this environment"
  );
  let searchParams;
  let formData;
  if (opts.formData) {
    searchParams = convertFormDataToSearchParams(opts.formData);
    formData = opts.formData;
  } else if (opts.body instanceof FormData) {
    searchParams = convertFormDataToSearchParams(opts.body);
    formData = opts.body;
  } else if (opts.body instanceof URLSearchParams) {
    searchParams = opts.body;
    formData = convertSearchParamsToFormData(searchParams);
  } else if (opts.body == null) {
    searchParams = new URLSearchParams();
    formData = new FormData();
  } else {
    try {
      searchParams = new URLSearchParams(opts.body);
      formData = convertSearchParamsToFormData(searchParams);
    } catch (e) {
      return getInvalidBodyError();
    }
  }
  let submission = {
    formMethod,
    formAction,
    formEncType: opts && opts.formEncType || "application/x-www-form-urlencoded",
    formData,
    json: void 0,
    text: void 0
  };
  if (isMutationMethod(submission.formMethod)) {
    return { path, submission };
  }
  let parsedPath = parsePath$1(path);
  if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {
    searchParams.append("index", "");
  }
  parsedPath.search = `?${searchParams}`;
  return { path: createPath(parsedPath), submission };
}
function getMatchesToLoad(request, scopedContext, mapRouteProperties2, manifest, history, state, matches, submission, location, lazyRoutePropertiesToSkip, initialHydration, isRevalidationRequired, cancelledFetcherLoads, fetchersQueuedForDeletion, fetchLoadMatches, fetchRedirectIds, routesToUse, basename2, hasPatchRoutesOnNavigation, pendingActionResult) {
  let actionResult = pendingActionResult ? isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : pendingActionResult[1].data : void 0;
  let currentUrl = history.createURL(state.location);
  let nextUrl = history.createURL(location);
  let maxIdx;
  if (initialHydration && state.errors) {
    let boundaryId = Object.keys(state.errors)[0];
    maxIdx = matches.findIndex((m) => m.route.id === boundaryId);
  } else if (pendingActionResult && isErrorResult(pendingActionResult[1])) {
    let boundaryId = pendingActionResult[0];
    maxIdx = matches.findIndex((m) => m.route.id === boundaryId) - 1;
  }
  let actionStatus = pendingActionResult ? pendingActionResult[1].statusCode : void 0;
  let shouldSkipRevalidation = actionStatus && actionStatus >= 400;
  let baseShouldRevalidateArgs = {
    currentUrl,
    currentParams: state.matches[0]?.params || {},
    nextUrl,
    nextParams: matches[0].params,
    ...submission,
    actionResult,
    actionStatus
  };
  let pattern = getRoutePattern(matches.map((m) => m.route.path));
  let dsMatches = matches.map((match3, index) => {
    let { route } = match3;
    let forceShouldLoad = null;
    if (maxIdx != null && index > maxIdx) {
      forceShouldLoad = false;
    } else if (route.lazy) {
      forceShouldLoad = true;
    } else if (!routeHasLoaderOrMiddleware(route)) {
      forceShouldLoad = false;
    } else if (initialHydration) {
      forceShouldLoad = shouldLoadRouteOnHydration(
        route,
        state.loaderData,
        state.errors
      );
    } else if (isNewLoader(state.loaderData, state.matches[index], match3)) {
      forceShouldLoad = true;
    }
    if (forceShouldLoad !== null) {
      return getDataStrategyMatch(
        mapRouteProperties2,
        manifest,
        request,
        pattern,
        match3,
        lazyRoutePropertiesToSkip,
        scopedContext,
        forceShouldLoad
      );
    }
    let defaultShouldRevalidate = shouldSkipRevalidation ? false : (
      // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate
      isRevalidationRequired || currentUrl.pathname + currentUrl.search === nextUrl.pathname + nextUrl.search || // Search params affect all loaders
      currentUrl.search !== nextUrl.search || isNewRouteInstance(state.matches[index], match3)
    );
    let shouldRevalidateArgs = {
      ...baseShouldRevalidateArgs,
      defaultShouldRevalidate
    };
    let shouldLoad = shouldRevalidateLoader(match3, shouldRevalidateArgs);
    return getDataStrategyMatch(
      mapRouteProperties2,
      manifest,
      request,
      pattern,
      match3,
      lazyRoutePropertiesToSkip,
      scopedContext,
      shouldLoad,
      shouldRevalidateArgs
    );
  });
  let revalidatingFetchers = [];
  fetchLoadMatches.forEach((f, key2) => {
    if (initialHydration || !matches.some((m) => m.route.id === f.routeId) || fetchersQueuedForDeletion.has(key2)) {
      return;
    }
    let fetcher = state.fetchers.get(key2);
    let isMidInitialLoad = fetcher && fetcher.state !== "idle" && fetcher.data === void 0;
    let fetcherMatches = matchRoutes(routesToUse, f.path, basename2);
    if (!fetcherMatches) {
      if (hasPatchRoutesOnNavigation && isMidInitialLoad) {
        return;
      }
      revalidatingFetchers.push({
        key: key2,
        routeId: f.routeId,
        path: f.path,
        matches: null,
        match: null,
        request: null,
        controller: null
      });
      return;
    }
    if (fetchRedirectIds.has(key2)) {
      return;
    }
    let fetcherMatch = getTargetMatch(fetcherMatches, f.path);
    let fetchController = new AbortController();
    let fetchRequest = createClientSideRequest(
      history,
      f.path,
      fetchController.signal
    );
    let fetcherDsMatches = null;
    if (cancelledFetcherLoads.has(key2)) {
      cancelledFetcherLoads.delete(key2);
      fetcherDsMatches = getTargetedDataStrategyMatches(
        mapRouteProperties2,
        manifest,
        fetchRequest,
        fetcherMatches,
        fetcherMatch,
        lazyRoutePropertiesToSkip,
        scopedContext
      );
    } else if (isMidInitialLoad) {
      if (isRevalidationRequired) {
        fetcherDsMatches = getTargetedDataStrategyMatches(
          mapRouteProperties2,
          manifest,
          fetchRequest,
          fetcherMatches,
          fetcherMatch,
          lazyRoutePropertiesToSkip,
          scopedContext
        );
      }
    } else {
      let shouldRevalidateArgs = {
        ...baseShouldRevalidateArgs,
        defaultShouldRevalidate: shouldSkipRevalidation ? false : isRevalidationRequired
      };
      if (shouldRevalidateLoader(fetcherMatch, shouldRevalidateArgs)) {
        fetcherDsMatches = getTargetedDataStrategyMatches(
          mapRouteProperties2,
          manifest,
          fetchRequest,
          fetcherMatches,
          fetcherMatch,
          lazyRoutePropertiesToSkip,
          scopedContext,
          shouldRevalidateArgs
        );
      }
    }
    if (fetcherDsMatches) {
      revalidatingFetchers.push({
        key: key2,
        routeId: f.routeId,
        path: f.path,
        matches: fetcherDsMatches,
        match: fetcherMatch,
        request: fetchRequest,
        controller: fetchController
      });
    }
  });
  return { dsMatches, revalidatingFetchers };
}
function routeHasLoaderOrMiddleware(route) {
  return route.loader != null || route.middleware != null && route.middleware.length > 0;
}
function shouldLoadRouteOnHydration(route, loaderData, errors2) {
  if (route.lazy) {
    return true;
  }
  if (!routeHasLoaderOrMiddleware(route)) {
    return false;
  }
  let hasData = loaderData != null && route.id in loaderData;
  let hasError = errors2 != null && errors2[route.id] !== void 0;
  if (!hasData && hasError) {
    return false;
  }
  if (typeof route.loader === "function" && route.loader.hydrate === true) {
    return true;
  }
  return !hasData && !hasError;
}
function isNewLoader(currentLoaderData, currentMatch, match3) {
  let isNew = (
    // [a] -> [a, b]
    !currentMatch || // [a, b] -> [a, c]
    match3.route.id !== currentMatch.route.id
  );
  let isMissingData = !currentLoaderData.hasOwnProperty(match3.route.id);
  return isNew || isMissingData;
}
function isNewRouteInstance(currentMatch, match3) {
  let currentPath = currentMatch.route.path;
  return (
    // param change for this match, /users/123 -> /users/456
    currentMatch.pathname !== match3.pathname || // splat param changed, which is not present in match.path
    // e.g. /files/images/avatar.jpg -> files/finances.xls
    currentPath != null && currentPath.endsWith("*") && currentMatch.params["*"] !== match3.params["*"]
  );
}
function shouldRevalidateLoader(loaderMatch, arg) {
  if (loaderMatch.route.shouldRevalidate) {
    let routeChoice = loaderMatch.route.shouldRevalidate(arg);
    if (typeof routeChoice === "boolean") {
      return routeChoice;
    }
  }
  return arg.defaultShouldRevalidate;
}
function patchRoutesImpl(routeId, children2, routesToUse, manifest, mapRouteProperties2, allowElementMutations) {
  let childrenToPatch;
  if (routeId) {
    let route = manifest[routeId];
    invariant(
      route,
      `No route found to patch children into: routeId = ${routeId}`
    );
    if (!route.children) {
      route.children = [];
    }
    childrenToPatch = route.children;
  } else {
    childrenToPatch = routesToUse;
  }
  let uniqueChildren = [];
  let existingChildren = [];
  children2.forEach((newRoute) => {
    let existingRoute = childrenToPatch.find(
      (existingRoute2) => isSameRoute(newRoute, existingRoute2)
    );
    if (existingRoute) {
      existingChildren.push({ existingRoute, newRoute });
    } else {
      uniqueChildren.push(newRoute);
    }
  });
  if (uniqueChildren.length > 0) {
    let newRoutes = convertRoutesToDataRoutes(
      uniqueChildren,
      mapRouteProperties2,
      [routeId || "_", "patch", String(childrenToPatch?.length || "0")],
      manifest
    );
    childrenToPatch.push(...newRoutes);
  }
  if (allowElementMutations && existingChildren.length > 0) {
    for (let i2 = 0; i2 < existingChildren.length; i2++) {
      let { existingRoute, newRoute } = existingChildren[i2];
      let existingRouteTyped = existingRoute;
      let [newRouteTyped] = convertRoutesToDataRoutes(
        [newRoute],
        mapRouteProperties2,
        [],
        // Doesn't matter for mutated routes since they already have an id
        {},
        // Don't touch the manifest here since we're updating in place
        true
      );
      Object.assign(existingRouteTyped, {
        element: newRouteTyped.element ? newRouteTyped.element : existingRouteTyped.element,
        errorElement: newRouteTyped.errorElement ? newRouteTyped.errorElement : existingRouteTyped.errorElement,
        hydrateFallbackElement: newRouteTyped.hydrateFallbackElement ? newRouteTyped.hydrateFallbackElement : existingRouteTyped.hydrateFallbackElement
      });
    }
  }
}
function isSameRoute(newRoute, existingRoute) {
  if ("id" in newRoute && "id" in existingRoute && newRoute.id === existingRoute.id) {
    return true;
  }
  if (!(newRoute.index === existingRoute.index && newRoute.path === existingRoute.path && newRoute.caseSensitive === existingRoute.caseSensitive)) {
    return false;
  }
  if ((!newRoute.children || newRoute.children.length === 0) && (!existingRoute.children || existingRoute.children.length === 0)) {
    return true;
  }
  return newRoute.children.every(
    (aChild, i2) => existingRoute.children?.some((bChild) => isSameRoute(aChild, bChild))
  );
}
var lazyRoutePropertyCache = /* @__PURE__ */ new WeakMap();
var loadLazyRouteProperty = ({
  key: key2,
  route,
  manifest,
  mapRouteProperties: mapRouteProperties2
}) => {
  let routeToUpdate = manifest[route.id];
  invariant(routeToUpdate, "No route found in manifest");
  if (!routeToUpdate.lazy || typeof routeToUpdate.lazy !== "object") {
    return;
  }
  let lazyFn = routeToUpdate.lazy[key2];
  if (!lazyFn) {
    return;
  }
  let cache = lazyRoutePropertyCache.get(routeToUpdate);
  if (!cache) {
    cache = {};
    lazyRoutePropertyCache.set(routeToUpdate, cache);
  }
  let cachedPromise = cache[key2];
  if (cachedPromise) {
    return cachedPromise;
  }
  let propertyPromise = (async () => {
    let isUnsupported = isUnsupportedLazyRouteObjectKey(key2);
    let staticRouteValue = routeToUpdate[key2];
    let isStaticallyDefined = staticRouteValue !== void 0 && key2 !== "hasErrorBoundary";
    if (isUnsupported) {
      warning(
        !isUnsupported,
        "Route property " + key2 + " is not a supported lazy route property. This property will be ignored."
      );
      cache[key2] = Promise.resolve();
    } else if (isStaticallyDefined) {
      warning(
        false,
        `Route "${routeToUpdate.id}" has a static property "${key2}" defined. The lazy property will be ignored.`
      );
    } else {
      let value2 = await lazyFn();
      if (value2 != null) {
        Object.assign(routeToUpdate, { [key2]: value2 });
        Object.assign(routeToUpdate, mapRouteProperties2(routeToUpdate));
      }
    }
    if (typeof routeToUpdate.lazy === "object") {
      routeToUpdate.lazy[key2] = void 0;
      if (Object.values(routeToUpdate.lazy).every((value2) => value2 === void 0)) {
        routeToUpdate.lazy = void 0;
      }
    }
  })();
  cache[key2] = propertyPromise;
  return propertyPromise;
};
var lazyRouteFunctionCache = /* @__PURE__ */ new WeakMap();
function loadLazyRoute(route, type, manifest, mapRouteProperties2, lazyRoutePropertiesToSkip) {
  let routeToUpdate = manifest[route.id];
  invariant(routeToUpdate, "No route found in manifest");
  if (!route.lazy) {
    return {
      lazyRoutePromise: void 0,
      lazyHandlerPromise: void 0
    };
  }
  if (typeof route.lazy === "function") {
    let cachedPromise = lazyRouteFunctionCache.get(routeToUpdate);
    if (cachedPromise) {
      return {
        lazyRoutePromise: cachedPromise,
        lazyHandlerPromise: cachedPromise
      };
    }
    let lazyRoutePromise2 = (async () => {
      invariant(
        typeof route.lazy === "function",
        "No lazy route function found"
      );
      let lazyRoute = await route.lazy();
      let routeUpdates = {};
      for (let lazyRouteProperty in lazyRoute) {
        let lazyValue = lazyRoute[lazyRouteProperty];
        if (lazyValue === void 0) {
          continue;
        }
        let isUnsupported = isUnsupportedLazyRouteFunctionKey(lazyRouteProperty);
        let staticRouteValue = routeToUpdate[lazyRouteProperty];
        let isStaticallyDefined = staticRouteValue !== void 0 && // This property isn't static since it should always be updated based
        // on the route updates
        lazyRouteProperty !== "hasErrorBoundary";
        if (isUnsupported) {
          warning(
            !isUnsupported,
            "Route property " + lazyRouteProperty + " is not a supported property to be returned from a lazy route function. This property will be ignored."
          );
        } else if (isStaticallyDefined) {
          warning(
            !isStaticallyDefined,
            `Route "${routeToUpdate.id}" has a static property "${lazyRouteProperty}" defined but its lazy function is also returning a value for this property. The lazy route property "${lazyRouteProperty}" will be ignored.`
          );
        } else {
          routeUpdates[lazyRouteProperty] = lazyValue;
        }
      }
      Object.assign(routeToUpdate, routeUpdates);
      Object.assign(routeToUpdate, {
        // To keep things framework agnostic, we use the provided `mapRouteProperties`
        // function to set the framework-aware properties (`element`/`hasErrorBoundary`)
        // since the logic will differ between frameworks.
        ...mapRouteProperties2(routeToUpdate),
        lazy: void 0
      });
    })();
    lazyRouteFunctionCache.set(routeToUpdate, lazyRoutePromise2);
    lazyRoutePromise2.catch(() => {
    });
    return {
      lazyRoutePromise: lazyRoutePromise2,
      lazyHandlerPromise: lazyRoutePromise2
    };
  }
  let lazyKeys = Object.keys(route.lazy);
  let lazyPropertyPromises = [];
  let lazyHandlerPromise = void 0;
  for (let key2 of lazyKeys) {
    if (lazyRoutePropertiesToSkip && lazyRoutePropertiesToSkip.includes(key2)) {
      continue;
    }
    let promise = loadLazyRouteProperty({
      key: key2,
      route,
      manifest,
      mapRouteProperties: mapRouteProperties2
    });
    if (promise) {
      lazyPropertyPromises.push(promise);
      if (key2 === type) {
        lazyHandlerPromise = promise;
      }
    }
  }
  let lazyRoutePromise = lazyPropertyPromises.length > 0 ? Promise.all(lazyPropertyPromises).then(() => {
  }) : void 0;
  lazyRoutePromise?.catch(() => {
  });
  lazyHandlerPromise?.catch(() => {
  });
  return {
    lazyRoutePromise,
    lazyHandlerPromise
  };
}
async function defaultDataStrategy(args2) {
  let matchesToLoad = args2.matches.filter((m) => m.shouldLoad);
  let keyedResults = {};
  let results = await Promise.all(matchesToLoad.map((m) => m.resolve()));
  results.forEach((result2, i2) => {
    keyedResults[matchesToLoad[i2].route.id] = result2;
  });
  return keyedResults;
}
async function defaultDataStrategyWithMiddleware(args2) {
  if (!args2.matches.some((m) => m.route.middleware)) {
    return defaultDataStrategy(args2);
  }
  return runClientMiddlewarePipeline(args2, () => defaultDataStrategy(args2));
}
function runClientMiddlewarePipeline(args2, handler) {
  return runMiddlewarePipeline(
    args2,
    handler,
    (r2) => r2,
    // No post-processing needed on the client
    isDataStrategyResults,
    errorHandler
  );
  function errorHandler(error2, routeId, nextResult) {
    if (nextResult) {
      return Promise.resolve(
        Object.assign(nextResult.value, {
          [routeId]: { type: "error", result: error2 }
        })
      );
    } else {
      let { matches } = args2;
      let maxBoundaryIdx = Math.min(
        // Throwing route
        Math.max(
          matches.findIndex((m) => m.route.id === routeId),
          0
        ),
        // or the shallowest route that needs to load data
        Math.max(
          matches.findIndex((m) => m.unstable_shouldCallHandler()),
          0
        )
      );
      let boundaryRouteId = findNearestBoundary(
        matches,
        matches[maxBoundaryIdx].route.id
      ).route.id;
      return Promise.resolve({
        [boundaryRouteId]: { type: "error", result: error2 }
      });
    }
  }
}
async function runMiddlewarePipeline(args2, handler, processResult2, isResult, errorHandler) {
  let { matches, request, params, context, unstable_pattern } = args2;
  let tuples = matches.flatMap(
    (m) => m.route.middleware ? m.route.middleware.map((fn3) => [m.route.id, fn3]) : []
  );
  let result2 = await callRouteMiddleware(
    {
      request,
      params,
      context,
      unstable_pattern
    },
    tuples,
    handler,
    processResult2,
    isResult,
    errorHandler
  );
  return result2;
}
async function callRouteMiddleware(args2, middlewares, handler, processResult2, isResult, errorHandler, idx = 0) {
  let { request } = args2;
  if (request.signal.aborted) {
    throw request.signal.reason ?? new Error(`Request aborted: ${request.method} ${request.url}`);
  }
  let tuple = middlewares[idx];
  if (!tuple) {
    let result2 = await handler();
    return result2;
  }
  let [routeId, middleware] = tuple;
  let nextResult;
  let next = async () => {
    if (nextResult) {
      throw new Error("You may only call `next()` once per middleware");
    }
    try {
      let result2 = await callRouteMiddleware(
        args2,
        middlewares,
        handler,
        processResult2,
        isResult,
        errorHandler,
        idx + 1
      );
      nextResult = { value: result2 };
      return nextResult.value;
    } catch (error2) {
      nextResult = { value: await errorHandler(error2, routeId, nextResult) };
      return nextResult.value;
    }
  };
  try {
    let value2 = await middleware(args2, next);
    let result2 = value2 != null ? processResult2(value2) : void 0;
    if (isResult(result2)) {
      return result2;
    } else if (nextResult) {
      return result2 ?? nextResult.value;
    } else {
      nextResult = { value: await next() };
      return nextResult.value;
    }
  } catch (error2) {
    let response = await errorHandler(error2, routeId, nextResult);
    return response;
  }
}
function getDataStrategyMatchLazyPromises(mapRouteProperties2, manifest, request, match3, lazyRoutePropertiesToSkip) {
  let lazyMiddlewarePromise = loadLazyRouteProperty({
    key: "middleware",
    route: match3.route,
    manifest,
    mapRouteProperties: mapRouteProperties2
  });
  let lazyRoutePromises = loadLazyRoute(
    match3.route,
    isMutationMethod(request.method) ? "action" : "loader",
    manifest,
    mapRouteProperties2,
    lazyRoutePropertiesToSkip
  );
  return {
    middleware: lazyMiddlewarePromise,
    route: lazyRoutePromises.lazyRoutePromise,
    handler: lazyRoutePromises.lazyHandlerPromise
  };
}
function getDataStrategyMatch(mapRouteProperties2, manifest, request, unstable_pattern, match3, lazyRoutePropertiesToSkip, scopedContext, shouldLoad, unstable_shouldRevalidateArgs = null) {
  let isUsingNewApi = false;
  let _lazyPromises = getDataStrategyMatchLazyPromises(
    mapRouteProperties2,
    manifest,
    request,
    match3,
    lazyRoutePropertiesToSkip
  );
  return {
    ...match3,
    _lazyPromises,
    shouldLoad,
    unstable_shouldRevalidateArgs,
    unstable_shouldCallHandler(defaultShouldRevalidate) {
      isUsingNewApi = true;
      if (!unstable_shouldRevalidateArgs) {
        return shouldLoad;
      }
      if (typeof defaultShouldRevalidate === "boolean") {
        return shouldRevalidateLoader(match3, {
          ...unstable_shouldRevalidateArgs,
          defaultShouldRevalidate
        });
      }
      return shouldRevalidateLoader(match3, unstable_shouldRevalidateArgs);
    },
    resolve(handlerOverride) {
      let { lazy, loader, middleware } = match3.route;
      let callHandler = isUsingNewApi || shouldLoad || handlerOverride && !isMutationMethod(request.method) && (lazy || loader);
      let isMiddlewareOnlyRoute = middleware && middleware.length > 0 && !loader && !lazy;
      if (callHandler && (isMutationMethod(request.method) || !isMiddlewareOnlyRoute)) {
        return callLoaderOrAction({
          request,
          unstable_pattern,
          match: match3,
          lazyHandlerPromise: _lazyPromises?.handler,
          lazyRoutePromise: _lazyPromises?.route,
          handlerOverride,
          scopedContext
        });
      }
      return Promise.resolve({ type: "data", result: void 0 });
    }
  };
}
function getTargetedDataStrategyMatches(mapRouteProperties2, manifest, request, matches, targetMatch, lazyRoutePropertiesToSkip, scopedContext, shouldRevalidateArgs = null) {
  return matches.map((match3) => {
    if (match3.route.id !== targetMatch.route.id) {
      return {
        ...match3,
        shouldLoad: false,
        unstable_shouldRevalidateArgs: shouldRevalidateArgs,
        unstable_shouldCallHandler: () => false,
        _lazyPromises: getDataStrategyMatchLazyPromises(
          mapRouteProperties2,
          manifest,
          request,
          match3,
          lazyRoutePropertiesToSkip
        ),
        resolve: () => Promise.resolve({ type: "data", result: void 0 })
      };
    }
    return getDataStrategyMatch(
      mapRouteProperties2,
      manifest,
      request,
      getRoutePattern(matches.map((m) => m.route.path)),
      match3,
      lazyRoutePropertiesToSkip,
      scopedContext,
      true,
      shouldRevalidateArgs
    );
  });
}
async function callDataStrategyImpl(dataStrategyImpl, request, matches, fetcherKey, scopedContext, isStaticHandler) {
  if (matches.some((m) => m._lazyPromises?.middleware)) {
    await Promise.all(matches.map((m) => m._lazyPromises?.middleware));
  }
  let dataStrategyArgs = {
    request,
    unstable_pattern: getRoutePattern(matches.map((m) => m.route.path)),
    params: matches[0].params,
    context: scopedContext,
    matches
  };
  let runClientMiddleware = (cb) => {
    let typedDataStrategyArgs = dataStrategyArgs;
    return runClientMiddlewarePipeline(typedDataStrategyArgs, () => {
      return cb({
        ...typedDataStrategyArgs,
        fetcherKey,
        runClientMiddleware: () => {
          throw new Error(
            "Cannot call `runClientMiddleware()` from within an `runClientMiddleware` handler"
          );
        }
      });
    });
  };
  let results = await dataStrategyImpl({
    ...dataStrategyArgs,
    fetcherKey,
    runClientMiddleware
  });
  try {
    await Promise.all(
      matches.flatMap((m) => [
        m._lazyPromises?.handler,
        m._lazyPromises?.route
      ])
    );
  } catch (e) {
  }
  return results;
}
async function callLoaderOrAction({
  request,
  unstable_pattern,
  match: match3,
  lazyHandlerPromise,
  lazyRoutePromise,
  handlerOverride,
  scopedContext
}) {
  let result2;
  let onReject;
  let isAction = isMutationMethod(request.method);
  let type = isAction ? "action" : "loader";
  let runHandler = (handler) => {
    let reject;
    let abortPromise = new Promise((_, r2) => reject = r2);
    onReject = () => reject();
    request.signal.addEventListener("abort", onReject);
    let actualHandler = (ctx) => {
      if (typeof handler !== "function") {
        return Promise.reject(
          new Error(
            `You cannot call the handler for a route which defines a boolean "${type}" [routeId: ${match3.route.id}]`
          )
        );
      }
      return handler(
        {
          request,
          unstable_pattern,
          params: match3.params,
          context: scopedContext
        },
        ...ctx !== void 0 ? [ctx] : []
      );
    };
    let handlerPromise = (async () => {
      try {
        let val = await (handlerOverride ? handlerOverride((ctx) => actualHandler(ctx)) : actualHandler());
        return { type: "data", result: val };
      } catch (e) {
        return { type: "error", result: e };
      }
    })();
    return Promise.race([handlerPromise, abortPromise]);
  };
  try {
    let handler = isAction ? match3.route.action : match3.route.loader;
    if (lazyHandlerPromise || lazyRoutePromise) {
      if (handler) {
        let handlerError;
        let [value2] = await Promise.all([
          // If the handler throws, don't let it immediately bubble out,
          // since we need to let the lazy() execution finish so we know if this
          // route has a boundary that can handle the error
          runHandler(handler).catch((e) => {
            handlerError = e;
          }),
          // Ensure all lazy route promises are resolved before continuing
          lazyHandlerPromise,
          lazyRoutePromise
        ]);
        if (handlerError !== void 0) {
          throw handlerError;
        }
        result2 = value2;
      } else {
        await lazyHandlerPromise;
        let handler2 = isAction ? match3.route.action : match3.route.loader;
        if (handler2) {
          [result2] = await Promise.all([runHandler(handler2), lazyRoutePromise]);
        } else if (type === "action") {
          let url = new URL(request.url);
          let pathname = url.pathname + url.search;
          throw getInternalRouterError(405, {
            method: request.method,
            pathname,
            routeId: match3.route.id
          });
        } else {
          return { type: "data", result: void 0 };
        }
      }
    } else if (!handler) {
      let url = new URL(request.url);
      let pathname = url.pathname + url.search;
      throw getInternalRouterError(404, {
        pathname
      });
    } else {
      result2 = await runHandler(handler);
    }
  } catch (e) {
    return { type: "error", result: e };
  } finally {
    if (onReject) {
      request.signal.removeEventListener("abort", onReject);
    }
  }
  return result2;
}
async function parseResponseBody(response) {
  let contentType = response.headers.get("Content-Type");
  if (contentType && /\bapplication\/json\b/.test(contentType)) {
    return response.body == null ? null : response.json();
  }
  return response.text();
}
async function convertDataStrategyResultToDataResult(dataStrategyResult) {
  let { result: result2, type } = dataStrategyResult;
  if (isResponse(result2)) {
    let data2;
    try {
      data2 = await parseResponseBody(result2);
    } catch (e) {
      return { type: "error", error: e };
    }
    if (type === "error") {
      return {
        type: "error",
        error: new ErrorResponseImpl(result2.status, result2.statusText, data2),
        statusCode: result2.status,
        headers: result2.headers
      };
    }
    return {
      type: "data",
      data: data2,
      statusCode: result2.status,
      headers: result2.headers
    };
  }
  if (type === "error") {
    if (isDataWithResponseInit(result2)) {
      if (result2.data instanceof Error) {
        return {
          type: "error",
          error: result2.data,
          statusCode: result2.init?.status,
          headers: result2.init?.headers ? new Headers(result2.init.headers) : void 0
        };
      }
      return {
        type: "error",
        error: new ErrorResponseImpl(
          result2.init?.status || 500,
          void 0,
          result2.data
        ),
        statusCode: isRouteErrorResponse(result2) ? result2.status : void 0,
        headers: result2.init?.headers ? new Headers(result2.init.headers) : void 0
      };
    }
    return {
      type: "error",
      error: result2,
      statusCode: isRouteErrorResponse(result2) ? result2.status : void 0
    };
  }
  if (isDataWithResponseInit(result2)) {
    return {
      type: "data",
      data: result2.data,
      statusCode: result2.init?.status,
      headers: result2.init?.headers ? new Headers(result2.init.headers) : void 0
    };
  }
  return { type: "data", data: result2 };
}
function normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename2) {
  let location = response.headers.get("Location");
  invariant(
    location,
    "Redirects returned/thrown from loaders/actions must have a Location header"
  );
  if (!isAbsoluteUrl(location)) {
    let trimmedMatches = matches.slice(
      0,
      matches.findIndex((m) => m.route.id === routeId) + 1
    );
    location = normalizeTo(
      new URL(request.url),
      trimmedMatches,
      basename2,
      location
    );
    response.headers.set("Location", location);
  }
  return response;
}
function normalizeRedirectLocation(location, currentUrl, basename2) {
  if (isAbsoluteUrl(location)) {
    let normalizedLocation = location;
    let url = normalizedLocation.startsWith("//") ? new URL(currentUrl.protocol + normalizedLocation) : new URL(normalizedLocation);
    let isSameBasename = stripBasename(url.pathname, basename2) != null;
    if (url.origin === currentUrl.origin && isSameBasename) {
      return url.pathname + url.search + url.hash;
    }
  }
  return location;
}
function createClientSideRequest(history, location, signal, submission) {
  let url = history.createURL(stripHashFromPath(location)).toString();
  let init = { signal };
  if (submission && isMutationMethod(submission.formMethod)) {
    let { formMethod, formEncType } = submission;
    init.method = formMethod.toUpperCase();
    if (formEncType === "application/json") {
      init.headers = new Headers({ "Content-Type": formEncType });
      init.body = JSON.stringify(submission.json);
    } else if (formEncType === "text/plain") {
      init.body = submission.text;
    } else if (formEncType === "application/x-www-form-urlencoded" && submission.formData) {
      init.body = convertFormDataToSearchParams(submission.formData);
    } else {
      init.body = submission.formData;
    }
  }
  return new Request(url, init);
}
function convertFormDataToSearchParams(formData) {
  let searchParams = new URLSearchParams();
  for (let [key2, value2] of formData.entries()) {
    searchParams.append(key2, typeof value2 === "string" ? value2 : value2.name);
  }
  return searchParams;
}
function convertSearchParamsToFormData(searchParams) {
  let formData = new FormData();
  for (let [key2, value2] of searchParams.entries()) {
    formData.append(key2, value2);
  }
  return formData;
}
function processRouteLoaderData(matches, results, pendingActionResult, isStaticHandler = false, skipLoaderErrorBubbling = false) {
  let loaderData = {};
  let errors2 = null;
  let statusCode;
  let foundError = false;
  let loaderHeaders = {};
  let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : void 0;
  matches.forEach((match3) => {
    if (!(match3.route.id in results)) {
      return;
    }
    let id2 = match3.route.id;
    let result2 = results[id2];
    invariant(
      !isRedirectResult(result2),
      "Cannot handle redirect results in processLoaderData"
    );
    if (isErrorResult(result2)) {
      let error2 = result2.error;
      if (pendingError !== void 0) {
        error2 = pendingError;
        pendingError = void 0;
      }
      errors2 = errors2 || {};
      if (skipLoaderErrorBubbling) {
        errors2[id2] = error2;
      } else {
        let boundaryMatch = findNearestBoundary(matches, id2);
        if (errors2[boundaryMatch.route.id] == null) {
          errors2[boundaryMatch.route.id] = error2;
        }
      }
      if (!isStaticHandler) {
        loaderData[id2] = ResetLoaderDataSymbol;
      }
      if (!foundError) {
        foundError = true;
        statusCode = isRouteErrorResponse(result2.error) ? result2.error.status : 500;
      }
      if (result2.headers) {
        loaderHeaders[id2] = result2.headers;
      }
    } else {
      loaderData[id2] = result2.data;
      if (result2.statusCode && result2.statusCode !== 200 && !foundError) {
        statusCode = result2.statusCode;
      }
      if (result2.headers) {
        loaderHeaders[id2] = result2.headers;
      }
    }
  });
  if (pendingError !== void 0 && pendingActionResult) {
    errors2 = { [pendingActionResult[0]]: pendingError };
    if (pendingActionResult[2]) {
      loaderData[pendingActionResult[2]] = void 0;
    }
  }
  return {
    loaderData,
    errors: errors2,
    statusCode: statusCode || 200,
    loaderHeaders
  };
}
function processLoaderData(state, matches, results, pendingActionResult, revalidatingFetchers, fetcherResults) {
  let { loaderData, errors: errors2 } = processRouteLoaderData(
    matches,
    results,
    pendingActionResult
  );
  revalidatingFetchers.filter((f) => !f.matches || f.matches.some((m) => m.shouldLoad)).forEach((rf) => {
    let { key: key2, match: match3, controller } = rf;
    if (controller && controller.signal.aborted) {
      return;
    }
    let result2 = fetcherResults[key2];
    invariant(result2, "Did not find corresponding fetcher result");
    if (isErrorResult(result2)) {
      let boundaryMatch = findNearestBoundary(state.matches, match3?.route.id);
      if (!(errors2 && errors2[boundaryMatch.route.id])) {
        errors2 = {
          ...errors2,
          [boundaryMatch.route.id]: result2.error
        };
      }
      state.fetchers.delete(key2);
    } else if (isRedirectResult(result2)) {
      invariant(false, "Unhandled fetcher revalidation redirect");
    } else {
      let doneFetcher = getDoneFetcher(result2.data);
      state.fetchers.set(key2, doneFetcher);
    }
  });
  return { loaderData, errors: errors2 };
}
function mergeLoaderData(loaderData, newLoaderData, matches, errors2) {
  let mergedLoaderData = Object.entries(newLoaderData).filter(([, v]) => v !== ResetLoaderDataSymbol).reduce((merged, [k, v]) => {
    merged[k] = v;
    return merged;
  }, {});
  for (let match3 of matches) {
    let id2 = match3.route.id;
    if (!newLoaderData.hasOwnProperty(id2) && loaderData.hasOwnProperty(id2) && match3.route.loader) {
      mergedLoaderData[id2] = loaderData[id2];
    }
    if (errors2 && errors2.hasOwnProperty(id2)) {
      break;
    }
  }
  return mergedLoaderData;
}
function getActionDataForCommit(pendingActionResult) {
  if (!pendingActionResult) {
    return {};
  }
  return isErrorResult(pendingActionResult[1]) ? {
    // Clear out prior actionData on errors
    actionData: {}
  } : {
    actionData: {
      [pendingActionResult[0]]: pendingActionResult[1].data
    }
  };
}
function findNearestBoundary(matches, routeId) {
  let eligibleMatches = routeId ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1) : [...matches];
  return eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) || matches[0];
}
function getShortCircuitMatches(routes) {
  let route = routes.length === 1 ? routes[0] : routes.find((r2) => r2.index || !r2.path || r2.path === "/") || {
    id: `__shim-error-route__`
  };
  return {
    matches: [
      {
        params: {},
        pathname: "",
        pathnameBase: "",
        route
      }
    ],
    route
  };
}
function getInternalRouterError(status, {
  pathname,
  routeId,
  method,
  type,
  message: message2
} = {}) {
  let statusText = "Unknown Server Error";
  let errorMessage = "Unknown @remix-run/router error";
  if (status === 400) {
    statusText = "Bad Request";
    if (method && pathname && routeId) {
      errorMessage = `You made a ${method} request to "${pathname}" but did not provide a \`loader\` for route "${routeId}", so there is no way to handle the request.`;
    } else if (type === "invalid-body") {
      errorMessage = "Unable to encode submission body";
    }
  } else if (status === 403) {
    statusText = "Forbidden";
    errorMessage = `Route "${routeId}" does not match URL "${pathname}"`;
  } else if (status === 404) {
    statusText = "Not Found";
    errorMessage = `No route matches URL "${pathname}"`;
  } else if (status === 405) {
    statusText = "Method Not Allowed";
    if (method && pathname && routeId) {
      errorMessage = `You made a ${method.toUpperCase()} request to "${pathname}" but did not provide an \`action\` for route "${routeId}", so there is no way to handle the request.`;
    } else if (method) {
      errorMessage = `Invalid request method "${method.toUpperCase()}"`;
    }
  }
  return new ErrorResponseImpl(
    status || 500,
    statusText,
    new Error(errorMessage),
    true
  );
}
function findRedirect(results) {
  let entries2 = Object.entries(results);
  for (let i2 = entries2.length - 1; i2 >= 0; i2--) {
    let [key2, result2] = entries2[i2];
    if (isRedirectResult(result2)) {
      return { key: key2, result: result2 };
    }
  }
}
function stripHashFromPath(path) {
  let parsedPath = typeof path === "string" ? parsePath$1(path) : path;
  return createPath({ ...parsedPath, hash: "" });
}
function isHashChangeOnly(a2, b) {
  if (a2.pathname !== b.pathname || a2.search !== b.search) {
    return false;
  }
  if (a2.hash === "") {
    return b.hash !== "";
  } else if (a2.hash === b.hash) {
    return true;
  } else if (b.hash !== "") {
    return true;
  }
  return false;
}
function isDataStrategyResults(result2) {
  return result2 != null && typeof result2 === "object" && Object.entries(result2).every(
    ([key2, value2]) => typeof key2 === "string" && isDataStrategyResult(value2)
  );
}
function isDataStrategyResult(result2) {
  return result2 != null && typeof result2 === "object" && "type" in result2 && "result" in result2 && (result2.type === "data" || result2.type === "error");
}
function isRedirectDataStrategyResult(result2) {
  return isResponse(result2.result) && redirectStatusCodes.has(result2.result.status);
}
function isErrorResult(result2) {
  return result2.type === "error";
}
function isRedirectResult(result2) {
  return (result2 && result2.type) === "redirect";
}
function isDataWithResponseInit(value2) {
  return typeof value2 === "object" && value2 != null && "type" in value2 && "data" in value2 && "init" in value2 && value2.type === "DataWithResponseInit";
}
function isResponse(value2) {
  return value2 != null && typeof value2.status === "number" && typeof value2.statusText === "string" && typeof value2.headers === "object" && typeof value2.body !== "undefined";
}
function isValidMethod(method) {
  return validRequestMethods.has(method.toUpperCase());
}
function isMutationMethod(method) {
  return validMutationMethods.has(method.toUpperCase());
}
function hasNakedIndexQuery(search) {
  return new URLSearchParams(search).getAll("index").some((v) => v === "");
}
function getTargetMatch(matches, location) {
  let search = typeof location === "string" ? parsePath$1(location).search : location.search;
  if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) {
    return matches[matches.length - 1];
  }
  let pathMatches = getPathContributingMatches(matches);
  return pathMatches[pathMatches.length - 1];
}
function getSubmissionFromNavigation(navigation2) {
  let { formMethod, formAction, formEncType, text: text2, formData, json: json2 } = navigation2;
  if (!formMethod || !formAction || !formEncType) {
    return;
  }
  if (text2 != null) {
    return {
      formMethod,
      formAction,
      formEncType,
      formData: void 0,
      json: void 0,
      text: text2
    };
  } else if (formData != null) {
    return {
      formMethod,
      formAction,
      formEncType,
      formData,
      json: void 0,
      text: void 0
    };
  } else if (json2 !== void 0) {
    return {
      formMethod,
      formAction,
      formEncType,
      formData: void 0,
      json: json2,
      text: void 0
    };
  }
}
function getLoadingNavigation(location, submission) {
  if (submission) {
    let navigation2 = {
      state: "loading",
      location,
      formMethod: submission.formMethod,
      formAction: submission.formAction,
      formEncType: submission.formEncType,
      formData: submission.formData,
      json: submission.json,
      text: submission.text
    };
    return navigation2;
  } else {
    let navigation2 = {
      state: "loading",
      location,
      formMethod: void 0,
      formAction: void 0,
      formEncType: void 0,
      formData: void 0,
      json: void 0,
      text: void 0
    };
    return navigation2;
  }
}
function getSubmittingNavigation(location, submission) {
  let navigation2 = {
    state: "submitting",
    location,
    formMethod: submission.formMethod,
    formAction: submission.formAction,
    formEncType: submission.formEncType,
    formData: submission.formData,
    json: submission.json,
    text: submission.text
  };
  return navigation2;
}
function getLoadingFetcher(submission, data2) {
  if (submission) {
    let fetcher = {
      state: "loading",
      formMethod: submission.formMethod,
      formAction: submission.formAction,
      formEncType: submission.formEncType,
      formData: submission.formData,
      json: submission.json,
      text: submission.text,
      data: data2
    };
    return fetcher;
  } else {
    let fetcher = {
      state: "loading",
      formMethod: void 0,
      formAction: void 0,
      formEncType: void 0,
      formData: void 0,
      json: void 0,
      text: void 0,
      data: data2
    };
    return fetcher;
  }
}
function getSubmittingFetcher(submission, existingFetcher) {
  let fetcher = {
    state: "submitting",
    formMethod: submission.formMethod,
    formAction: submission.formAction,
    formEncType: submission.formEncType,
    formData: submission.formData,
    json: submission.json,
    text: submission.text,
    data: existingFetcher ? existingFetcher.data : void 0
  };
  return fetcher;
}
function getDoneFetcher(data2) {
  let fetcher = {
    state: "idle",
    formMethod: void 0,
    formAction: void 0,
    formEncType: void 0,
    formData: void 0,
    json: void 0,
    text: void 0,
    data: data2
  };
  return fetcher;
}
function restoreAppliedTransitions(_window, transitions) {
  try {
    let sessionPositions = _window.sessionStorage.getItem(
      TRANSITIONS_STORAGE_KEY
    );
    if (sessionPositions) {
      let json2 = JSON.parse(sessionPositions);
      for (let [k, v] of Object.entries(json2 || {})) {
        if (v && Array.isArray(v)) {
          transitions.set(k, new Set(v || []));
        }
      }
    }
  } catch (e) {
  }
}
function persistAppliedTransitions(_window, transitions) {
  if (transitions.size > 0) {
    let json2 = {};
    for (let [k, v] of transitions) {
      json2[k] = [...v];
    }
    try {
      _window.sessionStorage.setItem(
        TRANSITIONS_STORAGE_KEY,
        JSON.stringify(json2)
      );
    } catch (error2) {
      warning(
        false,
        `Failed to save applied view transitions in sessionStorage (${error2}).`
      );
    }
  }
}
function createDeferred() {
  let resolve2;
  let reject;
  let promise = new Promise((res, rej) => {
    resolve2 = async (val) => {
      res(val);
      try {
        await promise;
      } catch (e) {
      }
    };
    reject = async (error2) => {
      rej(error2);
      try {
        await promise;
      } catch (e) {
      }
    };
  });
  return {
    promise,
    //@ts-ignore
    resolve: resolve2,
    //@ts-ignore
    reject
  };
}
var DataRouterContext = reactExports.createContext(null);
DataRouterContext.displayName = "DataRouter";
var DataRouterStateContext = reactExports.createContext(null);
DataRouterStateContext.displayName = "DataRouterState";
reactExports.createContext(false);
var ViewTransitionContext = reactExports.createContext({
  isTransitioning: false
});
ViewTransitionContext.displayName = "ViewTransition";
var FetchersContext = reactExports.createContext(
  /* @__PURE__ */ new Map()
);
FetchersContext.displayName = "Fetchers";
var AwaitContext = reactExports.createContext(null);
AwaitContext.displayName = "Await";
var NavigationContext = reactExports.createContext(
  null
);
NavigationContext.displayName = "Navigation";
var LocationContext = reactExports.createContext(
  null
);
LocationContext.displayName = "Location";
var RouteContext = reactExports.createContext({
  outlet: null,
  matches: [],
  isDataRoute: false
});
RouteContext.displayName = "Route";
var RouteErrorContext = reactExports.createContext(null);
RouteErrorContext.displayName = "RouteError";
function useHref(to2, { relative } = {}) {
  invariant(
    useInRouterContext(),
    // TODO: This error is probably because they somehow have 2 versions of the
    // router loaded. We can help them understand how to avoid that.
    `useHref() may be used only in the context of a <Router> component.`
  );
  let { basename: basename2, navigator: navigator2 } = reactExports.useContext(NavigationContext);
  let { hash: hash2, pathname, search } = useResolvedPath(to2, { relative });
  let joinedPathname = pathname;
  if (basename2 !== "/") {
    joinedPathname = pathname === "/" ? basename2 : joinPaths([basename2, pathname]);
  }
  return navigator2.createHref({ pathname: joinedPathname, search, hash: hash2 });
}
function useInRouterContext() {
  return reactExports.useContext(LocationContext) != null;
}
function useLocation() {
  invariant(
    useInRouterContext(),
    // TODO: This error is probably because they somehow have 2 versions of the
    // router loaded. We can help them understand how to avoid that.
    `useLocation() may be used only in the context of a <Router> component.`
  );
  return reactExports.useContext(LocationContext).location;
}
var navigateEffectWarning = `You should call navigate() in a React.useEffect(), not when your component is first rendered.`;
function useIsomorphicLayoutEffect$1(cb) {
  let isStatic = reactExports.useContext(NavigationContext).static;
  if (!isStatic) {
    reactExports.useLayoutEffect(cb);
  }
}
function useNavigate() {
  let { isDataRoute } = reactExports.useContext(RouteContext);
  return isDataRoute ? useNavigateStable() : useNavigateUnstable();
}
function useNavigateUnstable() {
  invariant(
    useInRouterContext(),
    // TODO: This error is probably because they somehow have 2 versions of the
    // router loaded. We can help them understand how to avoid that.
    `useNavigate() may be used only in the context of a <Router> component.`
  );
  let dataRouterContext = reactExports.useContext(DataRouterContext);
  let { basename: basename2, navigator: navigator2 } = reactExports.useContext(NavigationContext);
  let { matches } = reactExports.useContext(RouteContext);
  let { pathname: locationPathname } = useLocation();
  let routePathnamesJson = JSON.stringify(getResolveToMatches(matches));
  let activeRef = reactExports.useRef(false);
  useIsomorphicLayoutEffect$1(() => {
    activeRef.current = true;
  });
  let navigate = reactExports.useCallback(
    (to2, options = {}) => {
      warning(activeRef.current, navigateEffectWarning);
      if (!activeRef.current) return;
      if (typeof to2 === "number") {
        navigator2.go(to2);
        return;
      }
      let path = resolveTo(
        to2,
        JSON.parse(routePathnamesJson),
        locationPathname,
        options.relative === "path"
      );
      if (dataRouterContext == null && basename2 !== "/") {
        path.pathname = path.pathname === "/" ? basename2 : joinPaths([basename2, path.pathname]);
      }
      (!!options.replace ? navigator2.replace : navigator2.push)(
        path,
        options.state,
        options
      );
    },
    [
      basename2,
      navigator2,
      routePathnamesJson,
      locationPathname,
      dataRouterContext
    ]
  );
  return navigate;
}
var OutletContext = reactExports.createContext(null);
function useOutlet(context) {
  let outlet = reactExports.useContext(RouteContext).outlet;
  return reactExports.useMemo(
    () => outlet && /* @__PURE__ */ reactExports.createElement(OutletContext.Provider, { value: context }, outlet),
    [outlet, context]
  );
}
function useParams() {
  let { matches } = reactExports.useContext(RouteContext);
  let routeMatch = matches[matches.length - 1];
  return routeMatch ? routeMatch.params : {};
}
function useResolvedPath(to2, { relative } = {}) {
  let { matches } = reactExports.useContext(RouteContext);
  let { pathname: locationPathname } = useLocation();
  let routePathnamesJson = JSON.stringify(getResolveToMatches(matches));
  return reactExports.useMemo(
    () => resolveTo(
      to2,
      JSON.parse(routePathnamesJson),
      locationPathname,
      relative === "path"
    ),
    [to2, routePathnamesJson, locationPathname, relative]
  );
}
function useRoutesImpl(routes, locationArg, dataRouterState, unstable_onError, future) {
  invariant(
    useInRouterContext(),
    // TODO: This error is probably because they somehow have 2 versions of the
    // router loaded. We can help them understand how to avoid that.
    `useRoutes() may be used only in the context of a <Router> component.`
  );
  let { navigator: navigator2 } = reactExports.useContext(NavigationContext);
  let { matches: parentMatches } = reactExports.useContext(RouteContext);
  let routeMatch = parentMatches[parentMatches.length - 1];
  let parentParams = routeMatch ? routeMatch.params : {};
  let parentPathname = routeMatch ? routeMatch.pathname : "/";
  let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
  let parentRoute = routeMatch && routeMatch.route;
  {
    let parentPath = parentRoute && parentRoute.path || "";
    warningOnce(
      parentPathname,
      !parentRoute || parentPath.endsWith("*") || parentPath.endsWith("*?"),
      `You rendered descendant <Routes> (or called \`useRoutes()\`) at "${parentPathname}" (under <Route path="${parentPath}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.

Please change the parent <Route path="${parentPath}"> to <Route path="${parentPath === "/" ? "*" : `${parentPath}/*`}">.`
    );
  }
  let locationFromContext = useLocation();
  let location;
  {
    location = locationFromContext;
  }
  let pathname = location.pathname || "/";
  let remainingPathname = pathname;
  if (parentPathnameBase !== "/") {
    let parentSegments = parentPathnameBase.replace(/^\//, "").split("/");
    let segments = pathname.replace(/^\//, "").split("/");
    remainingPathname = "/" + segments.slice(parentSegments.length).join("/");
  }
  let matches = matchRoutes(routes, { pathname: remainingPathname });
  {
    warning(
      parentRoute || matches != null,
      `No routes matched location "${location.pathname}${location.search}${location.hash}" `
    );
    warning(
      matches == null || matches[matches.length - 1].route.element !== void 0 || matches[matches.length - 1].route.Component !== void 0 || matches[matches.length - 1].route.lazy !== void 0,
      `Matched leaf route at location "${location.pathname}${location.search}${location.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`
    );
  }
  let renderedMatches = _renderMatches(
    matches && matches.map(
      (match3) => Object.assign({}, match3, {
        params: Object.assign({}, parentParams, match3.params),
        pathname: joinPaths([
          parentPathnameBase,
          // Re-encode pathnames that were decoded inside matchRoutes.
          // Pre-encode `?` and `#` ahead of `encodeLocation` because it uses
          // `new URL()` internally and we need to prevent it from treating
          // them as separators
          navigator2.encodeLocation ? navigator2.encodeLocation(
            match3.pathname.replace(/\?/g, "%3F").replace(/#/g, "%23")
          ).pathname : match3.pathname
        ]),
        pathnameBase: match3.pathnameBase === "/" ? parentPathnameBase : joinPaths([
          parentPathnameBase,
          // Re-encode pathnames that were decoded inside matchRoutes
          // Pre-encode `?` and `#` ahead of `encodeLocation` because it uses
          // `new URL()` internally and we need to prevent it from treating
          // them as separators
          navigator2.encodeLocation ? navigator2.encodeLocation(
            match3.pathnameBase.replace(/\?/g, "%3F").replace(/#/g, "%23")
          ).pathname : match3.pathnameBase
        ])
      })
    ),
    parentMatches,
    dataRouterState,
    unstable_onError,
    future
  );
  return renderedMatches;
}
function DefaultErrorComponent() {
  let error2 = useRouteError();
  let message2 = isRouteErrorResponse(error2) ? `${error2.status} ${error2.statusText}` : error2 instanceof Error ? error2.message : JSON.stringify(error2);
  let stack2 = error2 instanceof Error ? error2.stack : null;
  let lightgrey = "rgba(200,200,200, 0.5)";
  let preStyles = { padding: "0.5rem", backgroundColor: lightgrey };
  let codeStyles = { padding: "2px 4px", backgroundColor: lightgrey };
  let devInfo = null;
  {
    console.error(
      "Error handled by React Router default ErrorBoundary:",
      error2
    );
    devInfo = /* @__PURE__ */ reactExports.createElement(reactExports.Fragment, null, /* @__PURE__ */ reactExports.createElement("p", null, "💿 Hey developer 👋"), /* @__PURE__ */ reactExports.createElement("p", null, "You can provide a way better UX than this when your app throws errors by providing your own ", /* @__PURE__ */ reactExports.createElement("code", { style: codeStyles }, "ErrorBoundary"), " or", " ", /* @__PURE__ */ reactExports.createElement("code", { style: codeStyles }, "errorElement"), " prop on your route."));
  }
  return /* @__PURE__ */ reactExports.createElement(reactExports.Fragment, null, /* @__PURE__ */ reactExports.createElement("h2", null, "Unexpected Application Error!"), /* @__PURE__ */ reactExports.createElement("h3", { style: { fontStyle: "italic" } }, message2), stack2 ? /* @__PURE__ */ reactExports.createElement("pre", { style: preStyles }, stack2) : null, devInfo);
}
var defaultErrorElement = /* @__PURE__ */ reactExports.createElement(DefaultErrorComponent, null);
var RenderErrorBoundary = class extends reactExports.Component {
  constructor(props) {
    super(props);
    this.state = {
      location: props.location,
      revalidation: props.revalidation,
      error: props.error
    };
  }
  static getDerivedStateFromError(error2) {
    return { error: error2 };
  }
  static getDerivedStateFromProps(props, state) {
    if (state.location !== props.location || state.revalidation !== "idle" && props.revalidation === "idle") {
      return {
        error: props.error,
        location: props.location,
        revalidation: props.revalidation
      };
    }
    return {
      error: props.error !== void 0 ? props.error : state.error,
      location: state.location,
      revalidation: props.revalidation || state.revalidation
    };
  }
  componentDidCatch(error2, errorInfo) {
    if (this.props.unstable_onError) {
      this.props.unstable_onError(error2, errorInfo);
    } else {
      console.error(
        "React Router caught the following error during render",
        error2
      );
    }
  }
  render() {
    return this.state.error !== void 0 ? /* @__PURE__ */ reactExports.createElement(RouteContext.Provider, { value: this.props.routeContext }, /* @__PURE__ */ reactExports.createElement(
      RouteErrorContext.Provider,
      {
        value: this.state.error,
        children: this.props.component
      }
    )) : this.props.children;
  }
};
function RenderedRoute({ routeContext, match: match3, children: children2 }) {
  let dataRouterContext = reactExports.useContext(DataRouterContext);
  if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && (match3.route.errorElement || match3.route.ErrorBoundary)) {
    dataRouterContext.staticContext._deepestRenderedBoundaryId = match3.route.id;
  }
  return /* @__PURE__ */ reactExports.createElement(RouteContext.Provider, { value: routeContext }, children2);
}
function _renderMatches(matches, parentMatches = [], dataRouterState = null, unstable_onError = null, future = null) {
  if (matches == null) {
    if (!dataRouterState) {
      return null;
    }
    if (dataRouterState.errors) {
      matches = dataRouterState.matches;
    } else if (parentMatches.length === 0 && !dataRouterState.initialized && dataRouterState.matches.length > 0) {
      matches = dataRouterState.matches;
    } else {
      return null;
    }
  }
  let renderedMatches = matches;
  let errors2 = dataRouterState?.errors;
  if (errors2 != null) {
    let errorIndex = renderedMatches.findIndex(
      (m) => m.route.id && errors2?.[m.route.id] !== void 0
    );
    invariant(
      errorIndex >= 0,
      `Could not find a matching route for errors on route IDs: ${Object.keys(
        errors2
      ).join(",")}`
    );
    renderedMatches = renderedMatches.slice(
      0,
      Math.min(renderedMatches.length, errorIndex + 1)
    );
  }
  let renderFallback = false;
  let fallbackIndex = -1;
  if (dataRouterState) {
    for (let i2 = 0; i2 < renderedMatches.length; i2++) {
      let match3 = renderedMatches[i2];
      if (match3.route.HydrateFallback || match3.route.hydrateFallbackElement) {
        fallbackIndex = i2;
      }
      if (match3.route.id) {
        let { loaderData, errors: errors22 } = dataRouterState;
        let needsToRunLoader = match3.route.loader && !loaderData.hasOwnProperty(match3.route.id) && (!errors22 || errors22[match3.route.id] === void 0);
        if (match3.route.lazy || needsToRunLoader) {
          renderFallback = true;
          if (fallbackIndex >= 0) {
            renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);
          } else {
            renderedMatches = [renderedMatches[0]];
          }
          break;
        }
      }
    }
  }
  return renderedMatches.reduceRight(
    (outlet, match3, index) => {
      let error2;
      let shouldRenderHydrateFallback = false;
      let errorElement = null;
      let hydrateFallbackElement = null;
      if (dataRouterState) {
        error2 = errors2 && match3.route.id ? errors2[match3.route.id] : void 0;
        errorElement = match3.route.errorElement || defaultErrorElement;
        if (renderFallback) {
          if (fallbackIndex < 0 && index === 0) {
            warningOnce(
              "route-fallback",
              false,
              "No `HydrateFallback` element provided to render during initial hydration"
            );
            shouldRenderHydrateFallback = true;
            hydrateFallbackElement = null;
          } else if (fallbackIndex === index) {
            shouldRenderHydrateFallback = true;
            hydrateFallbackElement = match3.route.hydrateFallbackElement || null;
          }
        }
      }
      let matches2 = parentMatches.concat(renderedMatches.slice(0, index + 1));
      let getChildren = () => {
        let children2;
        if (error2) {
          children2 = errorElement;
        } else if (shouldRenderHydrateFallback) {
          children2 = hydrateFallbackElement;
        } else if (match3.route.Component) {
          children2 = /* @__PURE__ */ reactExports.createElement(match3.route.Component, null);
        } else if (match3.route.element) {
          children2 = match3.route.element;
        } else {
          children2 = outlet;
        }
        return /* @__PURE__ */ reactExports.createElement(
          RenderedRoute,
          {
            match: match3,
            routeContext: {
              outlet,
              matches: matches2,
              isDataRoute: dataRouterState != null
            },
            children: children2
          }
        );
      };
      return dataRouterState && (match3.route.ErrorBoundary || match3.route.errorElement || index === 0) ? /* @__PURE__ */ reactExports.createElement(
        RenderErrorBoundary,
        {
          location: dataRouterState.location,
          revalidation: dataRouterState.revalidation,
          component: errorElement,
          error: error2,
          children: getChildren(),
          routeContext: { outlet: null, matches: matches2, isDataRoute: true },
          unstable_onError
        }
      ) : getChildren();
    },
    null
  );
}
function getDataRouterConsoleError(hookName) {
  return `${hookName} must be used within a data router.  See https://reactrouter.com/en/main/routers/picking-a-router.`;
}
function useDataRouterContext(hookName) {
  let ctx = reactExports.useContext(DataRouterContext);
  invariant(ctx, getDataRouterConsoleError(hookName));
  return ctx;
}
function useDataRouterState(hookName) {
  let state = reactExports.useContext(DataRouterStateContext);
  invariant(state, getDataRouterConsoleError(hookName));
  return state;
}
function useRouteContext(hookName) {
  let route = reactExports.useContext(RouteContext);
  invariant(route, getDataRouterConsoleError(hookName));
  return route;
}
function useCurrentRouteId(hookName) {
  let route = useRouteContext(hookName);
  let thisRoute = route.matches[route.matches.length - 1];
  invariant(
    thisRoute.route.id,
    `${hookName} can only be used on routes that contain a unique "id"`
  );
  return thisRoute.route.id;
}
function useRouteId() {
  return useCurrentRouteId(
    "useRouteId"
    /* UseRouteId */
  );
}
function useRouteError() {
  let error2 = reactExports.useContext(RouteErrorContext);
  let state = useDataRouterState(
    "useRouteError"
    /* UseRouteError */
  );
  let routeId = useCurrentRouteId(
    "useRouteError"
    /* UseRouteError */
  );
  if (error2 !== void 0) {
    return error2;
  }
  return state.errors?.[routeId];
}
function useNavigateStable() {
  let { router } = useDataRouterContext(
    "useNavigate"
    /* UseNavigateStable */
  );
  let id2 = useCurrentRouteId(
    "useNavigate"
    /* UseNavigateStable */
  );
  let activeRef = reactExports.useRef(false);
  useIsomorphicLayoutEffect$1(() => {
    activeRef.current = true;
  });
  let navigate = reactExports.useCallback(
    async (to2, options = {}) => {
      warning(activeRef.current, navigateEffectWarning);
      if (!activeRef.current) return;
      if (typeof to2 === "number") {
        router.navigate(to2);
      } else {
        await router.navigate(to2, { fromRouteId: id2, ...options });
      }
    },
    [router, id2]
  );
  return navigate;
}
var alreadyWarned = {};
function warningOnce(key2, cond, message2) {
  if (!cond && !alreadyWarned[key2]) {
    alreadyWarned[key2] = true;
    warning(false, message2);
  }
}
var alreadyWarned2 = {};
function warnOnce(condition, message2) {
  if (!condition && !alreadyWarned2[message2]) {
    alreadyWarned2[message2] = true;
    console.warn(message2);
  }
}
function mapRouteProperties(route) {
  let updates = {
    // Note: this check also occurs in createRoutesFromChildren so update
    // there if you change this -- please and thank you!
    hasErrorBoundary: route.hasErrorBoundary || route.ErrorBoundary != null || route.errorElement != null
  };
  if (route.Component) {
    {
      if (route.element) {
        warning(
          false,
          "You should not include both `Component` and `element` on your route - `Component` will be used."
        );
      }
    }
    Object.assign(updates, {
      element: reactExports.createElement(route.Component),
      Component: void 0
    });
  }
  if (route.HydrateFallback) {
    {
      if (route.hydrateFallbackElement) {
        warning(
          false,
          "You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - `HydrateFallback` will be used."
        );
      }
    }
    Object.assign(updates, {
      hydrateFallbackElement: reactExports.createElement(route.HydrateFallback),
      HydrateFallback: void 0
    });
  }
  if (route.ErrorBoundary) {
    {
      if (route.errorElement) {
        warning(
          false,
          "You should not include both `ErrorBoundary` and `errorElement` on your route - `ErrorBoundary` will be used."
        );
      }
    }
    Object.assign(updates, {
      errorElement: reactExports.createElement(route.ErrorBoundary),
      ErrorBoundary: void 0
    });
  }
  return updates;
}
var hydrationRouteProperties = [
  "HydrateFallback",
  "hydrateFallbackElement"
];
var Deferred = class {
  constructor() {
    this.status = "pending";
    this.promise = new Promise((resolve2, reject) => {
      this.resolve = (value2) => {
        if (this.status === "pending") {
          this.status = "resolved";
          resolve2(value2);
        }
      };
      this.reject = (reason) => {
        if (this.status === "pending") {
          this.status = "rejected";
          reject(reason);
        }
      };
    });
  }
};
function RouterProvider({
  router,
  flushSync: reactDomFlushSyncImpl,
  unstable_onError
}) {
  let [state, setStateImpl] = reactExports.useState(router.state);
  let [pendingState, setPendingState] = reactExports.useState();
  let [vtContext, setVtContext] = reactExports.useState({
    isTransitioning: false
  });
  let [renderDfd, setRenderDfd] = reactExports.useState();
  let [transition, setTransition] = reactExports.useState();
  let [interruption, setInterruption] = reactExports.useState();
  let fetcherData = reactExports.useRef(/* @__PURE__ */ new Map());
  let logErrorsAndSetState = reactExports.useCallback(
    (newState) => {
      setStateImpl((prevState) => {
        if (newState.errors && unstable_onError) {
          Object.entries(newState.errors).forEach(([routeId, error2]) => {
            if (prevState.errors?.[routeId] !== error2) {
              unstable_onError(error2);
            }
          });
        }
        return newState;
      });
    },
    [unstable_onError]
  );
  let setState2 = reactExports.useCallback(
    (newState, { deletedFetchers, flushSync, viewTransitionOpts }) => {
      newState.fetchers.forEach((fetcher, key2) => {
        if (fetcher.data !== void 0) {
          fetcherData.current.set(key2, fetcher.data);
        }
      });
      deletedFetchers.forEach((key2) => fetcherData.current.delete(key2));
      warnOnce(
        flushSync === false || reactDomFlushSyncImpl != null,
        'You provided the `flushSync` option to a router update, but you are not using the `<RouterProvider>` from `react-router/dom` so `ReactDOM.flushSync()` is unavailable.  Please update your app to `import { RouterProvider } from "react-router/dom"` and ensure you have `react-dom` installed as a dependency to use the `flushSync` option.'
      );
      let isViewTransitionAvailable = router.window != null && router.window.document != null && typeof router.window.document.startViewTransition === "function";
      warnOnce(
        viewTransitionOpts == null || isViewTransitionAvailable,
        "You provided the `viewTransition` option to a router update, but you do not appear to be running in a DOM environment as `window.startViewTransition` is not available."
      );
      if (!viewTransitionOpts || !isViewTransitionAvailable) {
        if (reactDomFlushSyncImpl && flushSync) {
          reactDomFlushSyncImpl(() => logErrorsAndSetState(newState));
        } else {
          reactExports.startTransition(() => logErrorsAndSetState(newState));
        }
        return;
      }
      if (reactDomFlushSyncImpl && flushSync) {
        reactDomFlushSyncImpl(() => {
          if (transition) {
            renderDfd && renderDfd.resolve();
            transition.skipTransition();
          }
          setVtContext({
            isTransitioning: true,
            flushSync: true,
            currentLocation: viewTransitionOpts.currentLocation,
            nextLocation: viewTransitionOpts.nextLocation
          });
        });
        let t2 = router.window.document.startViewTransition(() => {
          reactDomFlushSyncImpl(() => logErrorsAndSetState(newState));
        });
        t2.finished.finally(() => {
          reactDomFlushSyncImpl(() => {
            setRenderDfd(void 0);
            setTransition(void 0);
            setPendingState(void 0);
            setVtContext({ isTransitioning: false });
          });
        });
        reactDomFlushSyncImpl(() => setTransition(t2));
        return;
      }
      if (transition) {
        renderDfd && renderDfd.resolve();
        transition.skipTransition();
        setInterruption({
          state: newState,
          currentLocation: viewTransitionOpts.currentLocation,
          nextLocation: viewTransitionOpts.nextLocation
        });
      } else {
        setPendingState(newState);
        setVtContext({
          isTransitioning: true,
          flushSync: false,
          currentLocation: viewTransitionOpts.currentLocation,
          nextLocation: viewTransitionOpts.nextLocation
        });
      }
    },
    [
      router.window,
      reactDomFlushSyncImpl,
      transition,
      renderDfd,
      logErrorsAndSetState
    ]
  );
  reactExports.useLayoutEffect(() => router.subscribe(setState2), [router, setState2]);
  reactExports.useEffect(() => {
    if (vtContext.isTransitioning && !vtContext.flushSync) {
      setRenderDfd(new Deferred());
    }
  }, [vtContext]);
  reactExports.useEffect(() => {
    if (renderDfd && pendingState && router.window) {
      let newState = pendingState;
      let renderPromise = renderDfd.promise;
      let transition2 = router.window.document.startViewTransition(async () => {
        reactExports.startTransition(() => logErrorsAndSetState(newState));
        await renderPromise;
      });
      transition2.finished.finally(() => {
        setRenderDfd(void 0);
        setTransition(void 0);
        setPendingState(void 0);
        setVtContext({ isTransitioning: false });
      });
      setTransition(transition2);
    }
  }, [pendingState, renderDfd, router.window, logErrorsAndSetState]);
  reactExports.useEffect(() => {
    if (renderDfd && pendingState && state.location.key === pendingState.location.key) {
      renderDfd.resolve();
    }
  }, [renderDfd, transition, state.location, pendingState]);
  reactExports.useEffect(() => {
    if (!vtContext.isTransitioning && interruption) {
      setPendingState(interruption.state);
      setVtContext({
        isTransitioning: true,
        flushSync: false,
        currentLocation: interruption.currentLocation,
        nextLocation: interruption.nextLocation
      });
      setInterruption(void 0);
    }
  }, [vtContext.isTransitioning, interruption]);
  let navigator2 = reactExports.useMemo(() => {
    return {
      createHref: router.createHref,
      encodeLocation: router.encodeLocation,
      go: (n2) => router.navigate(n2),
      push: (to2, state2, opts) => router.navigate(to2, {
        state: state2,
        preventScrollReset: opts?.preventScrollReset
      }),
      replace: (to2, state2, opts) => router.navigate(to2, {
        replace: true,
        state: state2,
        preventScrollReset: opts?.preventScrollReset
      })
    };
  }, [router]);
  let basename2 = router.basename || "/";
  let dataRouterContext = reactExports.useMemo(
    () => ({
      router,
      navigator: navigator2,
      static: false,
      basename: basename2,
      unstable_onError
    }),
    [router, navigator2, basename2, unstable_onError]
  );
  return /* @__PURE__ */ reactExports.createElement(reactExports.Fragment, null, /* @__PURE__ */ reactExports.createElement(DataRouterContext.Provider, { value: dataRouterContext }, /* @__PURE__ */ reactExports.createElement(DataRouterStateContext.Provider, { value: state }, /* @__PURE__ */ reactExports.createElement(FetchersContext.Provider, { value: fetcherData.current }, /* @__PURE__ */ reactExports.createElement(ViewTransitionContext.Provider, { value: vtContext }, /* @__PURE__ */ reactExports.createElement(
    Router,
    {
      basename: basename2,
      location: state.location,
      navigationType: state.historyAction,
      navigator: navigator2
    },
    /* @__PURE__ */ reactExports.createElement(
      MemoizedDataRoutes,
      {
        routes: router.routes,
        future: router.future,
        state,
        unstable_onError
      }
    )
  ))))), null);
}
var MemoizedDataRoutes = reactExports.memo(DataRoutes);
function DataRoutes({
  routes,
  future,
  state,
  unstable_onError
}) {
  return useRoutesImpl(routes, void 0, state, unstable_onError, future);
}
function Navigate({
  to: to2,
  replace: replace2,
  state,
  relative
}) {
  invariant(
    useInRouterContext(),
    // TODO: This error is probably because they somehow have 2 versions of
    // the router loaded. We can help them understand how to avoid that.
    `<Navigate> may be used only in the context of a <Router> component.`
  );
  let { static: isStatic } = reactExports.useContext(NavigationContext);
  warning(
    !isStatic,
    `<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.`
  );
  let { matches } = reactExports.useContext(RouteContext);
  let { pathname: locationPathname } = useLocation();
  let navigate = useNavigate();
  let path = resolveTo(
    to2,
    getResolveToMatches(matches),
    locationPathname,
    relative === "path"
  );
  let jsonPath = JSON.stringify(path);
  reactExports.useEffect(() => {
    navigate(JSON.parse(jsonPath), { replace: replace2, state, relative });
  }, [navigate, jsonPath, relative, replace2, state]);
  return null;
}
function Outlet(props) {
  return useOutlet(props.context);
}
function Router({
  basename: basenameProp = "/",
  children: children2 = null,
  location: locationProp,
  navigationType = "POP",
  navigator: navigator2,
  static: staticProp = false
}) {
  invariant(
    !useInRouterContext(),
    `You cannot render a <Router> inside another <Router>. You should never have more than one in your app.`
  );
  let basename2 = basenameProp.replace(/^\/*/, "/");
  let navigationContext = reactExports.useMemo(
    () => ({
      basename: basename2,
      navigator: navigator2,
      static: staticProp,
      future: {}
    }),
    [basename2, navigator2, staticProp]
  );
  if (typeof locationProp === "string") {
    locationProp = parsePath$1(locationProp);
  }
  let {
    pathname = "/",
    search = "",
    hash: hash2 = "",
    state = null,
    key: key2 = "default"
  } = locationProp;
  let locationContext = reactExports.useMemo(() => {
    let trailingPathname = stripBasename(pathname, basename2);
    if (trailingPathname == null) {
      return null;
    }
    return {
      location: {
        pathname: trailingPathname,
        search,
        hash: hash2,
        state,
        key: key2
      },
      navigationType
    };
  }, [basename2, pathname, search, hash2, state, key2, navigationType]);
  warning(
    locationContext != null,
    `<Router basename="${basename2}"> is not able to match the URL "${pathname}${search}${hash2}" because it does not start with the basename, so the <Router> won't render anything.`
  );
  if (locationContext == null) {
    return null;
  }
  return /* @__PURE__ */ reactExports.createElement(NavigationContext.Provider, { value: navigationContext }, /* @__PURE__ */ reactExports.createElement(LocationContext.Provider, { children: children2, value: locationContext }));
}
var defaultMethod = "get";
var defaultEncType = "application/x-www-form-urlencoded";
function isHtmlElement(object2) {
  return object2 != null && typeof object2.tagName === "string";
}
function isButtonElement(object2) {
  return isHtmlElement(object2) && object2.tagName.toLowerCase() === "button";
}
function isFormElement(object2) {
  return isHtmlElement(object2) && object2.tagName.toLowerCase() === "form";
}
function isInputElement(object2) {
  return isHtmlElement(object2) && object2.tagName.toLowerCase() === "input";
}
function isModifiedEvent(event) {
  return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
function shouldProcessLinkClick(event, target) {
  return event.button === 0 && // Ignore everything but left clicks
  (!target || target === "_self") && // Let browser handle "target=_blank" etc.
  !isModifiedEvent(event);
}
function createSearchParams(init = "") {
  return new URLSearchParams(
    typeof init === "string" || Array.isArray(init) || init instanceof URLSearchParams ? init : Object.keys(init).reduce((memo2, key2) => {
      let value2 = init[key2];
      return memo2.concat(
        Array.isArray(value2) ? value2.map((v) => [key2, v]) : [[key2, value2]]
      );
    }, [])
  );
}
function getSearchParamsForLocation(locationSearch, defaultSearchParams) {
  let searchParams = createSearchParams(locationSearch);
  if (defaultSearchParams) {
    defaultSearchParams.forEach((_, key2) => {
      if (!searchParams.has(key2)) {
        defaultSearchParams.getAll(key2).forEach((value2) => {
          searchParams.append(key2, value2);
        });
      }
    });
  }
  return searchParams;
}
var _formDataSupportsSubmitter = null;
function isFormDataSubmitterSupported() {
  if (_formDataSupportsSubmitter === null) {
    try {
      new FormData(
        document.createElement("form"),
        // @ts-expect-error if FormData supports the submitter parameter, this will throw
        0
      );
      _formDataSupportsSubmitter = false;
    } catch (e) {
      _formDataSupportsSubmitter = true;
    }
  }
  return _formDataSupportsSubmitter;
}
var supportedFormEncTypes = /* @__PURE__ */ new Set([
  "application/x-www-form-urlencoded",
  "multipart/form-data",
  "text/plain"
]);
function getFormEncType(encType) {
  if (encType != null && !supportedFormEncTypes.has(encType)) {
    warning(
      false,
      `"${encType}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${defaultEncType}"`
    );
    return null;
  }
  return encType;
}
function getFormSubmissionInfo(target, basename2) {
  let method;
  let action;
  let encType;
  let formData;
  let body;
  if (isFormElement(target)) {
    let attr = target.getAttribute("action");
    action = attr ? stripBasename(attr, basename2) : null;
    method = target.getAttribute("method") || defaultMethod;
    encType = getFormEncType(target.getAttribute("enctype")) || defaultEncType;
    formData = new FormData(target);
  } else if (isButtonElement(target) || isInputElement(target) && (target.type === "submit" || target.type === "image")) {
    let form = target.form;
    if (form == null) {
      throw new Error(
        `Cannot submit a <button> or <input type="submit"> without a <form>`
      );
    }
    let attr = target.getAttribute("formaction") || form.getAttribute("action");
    action = attr ? stripBasename(attr, basename2) : null;
    method = target.getAttribute("formmethod") || form.getAttribute("method") || defaultMethod;
    encType = getFormEncType(target.getAttribute("formenctype")) || getFormEncType(form.getAttribute("enctype")) || defaultEncType;
    formData = new FormData(form, target);
    if (!isFormDataSubmitterSupported()) {
      let { name: name2, type, value: value2 } = target;
      if (type === "image") {
        let prefix = name2 ? `${name2}.` : "";
        formData.append(`${prefix}x`, "0");
        formData.append(`${prefix}y`, "0");
      } else if (name2) {
        formData.append(name2, value2);
      }
    }
  } else if (isHtmlElement(target)) {
    throw new Error(
      `Cannot submit element that is not <form>, <button>, or <input type="submit|image">`
    );
  } else {
    method = defaultMethod;
    action = null;
    encType = defaultEncType;
    body = target;
  }
  if (formData && encType === "text/plain") {
    body = formData;
    formData = void 0;
  }
  return { action, method: method.toLowerCase(), encType, formData, body };
}
Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
function invariant2(value2, message2) {
  if (value2 === false || value2 === null || typeof value2 === "undefined") {
    throw new Error(message2);
  }
}
function singleFetchUrl(reqUrl, basename2, extension) {
  let url = typeof reqUrl === "string" ? new URL(
    reqUrl,
    // This can be called during the SSR flow via PrefetchPageLinksImpl so
    // don't assume window is available
    typeof window === "undefined" ? "server://singlefetch/" : window.location.origin
  ) : reqUrl;
  if (url.pathname === "/") {
    url.pathname = `_root.${extension}`;
  } else if (basename2 && stripBasename(url.pathname, basename2) === "/") {
    url.pathname = `${basename2.replace(/\/$/, "")}/_root.${extension}`;
  } else {
    url.pathname = `${url.pathname.replace(/\/$/, "")}.${extension}`;
  }
  return url;
}
async function loadRouteModule(route, routeModulesCache) {
  if (route.id in routeModulesCache) {
    return routeModulesCache[route.id];
  }
  try {
    let routeModule = await import(
      /* @vite-ignore */
      /* webpackIgnore: true */
      route.module
    );
    routeModulesCache[route.id] = routeModule;
    return routeModule;
  } catch (error2) {
    console.error(
      `Error loading route module \`${route.module}\`, reloading page...`
    );
    console.error(error2);
    if (window.__reactRouterContext && window.__reactRouterContext.isSpaMode && // @ts-expect-error
    void 0) ;
    window.location.reload();
    return new Promise(() => {
    });
  }
}
function isHtmlLinkDescriptor(object2) {
  if (object2 == null) {
    return false;
  }
  if (object2.href == null) {
    return object2.rel === "preload" && typeof object2.imageSrcSet === "string" && typeof object2.imageSizes === "string";
  }
  return typeof object2.rel === "string" && typeof object2.href === "string";
}
async function getKeyedPrefetchLinks(matches, manifest, routeModules) {
  let links2 = await Promise.all(
    matches.map(async (match3) => {
      let route = manifest.routes[match3.route.id];
      if (route) {
        let mod2 = await loadRouteModule(route, routeModules);
        return mod2.links ? mod2.links() : [];
      }
      return [];
    })
  );
  return dedupeLinkDescriptors(
    links2.flat(1).filter(isHtmlLinkDescriptor).filter((link2) => link2.rel === "stylesheet" || link2.rel === "preload").map(
      (link2) => link2.rel === "stylesheet" ? { ...link2, rel: "prefetch", as: "style" } : { ...link2, rel: "prefetch" }
    )
  );
}
function getNewMatchesForLinks(page, nextMatches, currentMatches, manifest, location, mode) {
  let isNew = (match3, index) => {
    if (!currentMatches[index]) return true;
    return match3.route.id !== currentMatches[index].route.id;
  };
  let matchPathChanged = (match3, index) => {
    return (
      // param change, /users/123 -> /users/456
      currentMatches[index].pathname !== match3.pathname || // splat param changed, which is not present in match.path
      // e.g. /files/images/avatar.jpg -> files/finances.xls
      currentMatches[index].route.path?.endsWith("*") && currentMatches[index].params["*"] !== match3.params["*"]
    );
  };
  if (mode === "assets") {
    return nextMatches.filter(
      (match3, index) => isNew(match3, index) || matchPathChanged(match3, index)
    );
  }
  if (mode === "data") {
    return nextMatches.filter((match3, index) => {
      let manifestRoute = manifest.routes[match3.route.id];
      if (!manifestRoute || !manifestRoute.hasLoader) {
        return false;
      }
      if (isNew(match3, index) || matchPathChanged(match3, index)) {
        return true;
      }
      if (match3.route.shouldRevalidate) {
        let routeChoice = match3.route.shouldRevalidate({
          currentUrl: new URL(
            location.pathname + location.search + location.hash,
            window.origin
          ),
          currentParams: currentMatches[0]?.params || {},
          nextUrl: new URL(page, window.origin),
          nextParams: match3.params,
          defaultShouldRevalidate: true
        });
        if (typeof routeChoice === "boolean") {
          return routeChoice;
        }
      }
      return true;
    });
  }
  return [];
}
function getModuleLinkHrefs(matches, manifest, { includeHydrateFallback } = {}) {
  return dedupeHrefs(
    matches.map((match3) => {
      let route = manifest.routes[match3.route.id];
      if (!route) return [];
      let hrefs = [route.module];
      if (route.clientActionModule) {
        hrefs = hrefs.concat(route.clientActionModule);
      }
      if (route.clientLoaderModule) {
        hrefs = hrefs.concat(route.clientLoaderModule);
      }
      if (includeHydrateFallback && route.hydrateFallbackModule) {
        hrefs = hrefs.concat(route.hydrateFallbackModule);
      }
      if (route.imports) {
        hrefs = hrefs.concat(route.imports);
      }
      return hrefs;
    }).flat(1)
  );
}
function dedupeHrefs(hrefs) {
  return [...new Set(hrefs)];
}
function sortKeys(obj) {
  let sorted = {};
  let keys2 = Object.keys(obj).sort();
  for (let key2 of keys2) {
    sorted[key2] = obj[key2];
  }
  return sorted;
}
function dedupeLinkDescriptors(descriptors, preloads) {
  let set3 = /* @__PURE__ */ new Set();
  new Set(preloads);
  return descriptors.reduce((deduped, descriptor) => {
    let key2 = JSON.stringify(sortKeys(descriptor));
    if (!set3.has(key2)) {
      set3.add(key2);
      deduped.push({ key: key2, link: descriptor });
    }
    return deduped;
  }, []);
}
function useDataRouterContext2() {
  let context = reactExports.useContext(DataRouterContext);
  invariant2(
    context,
    "You must render this element inside a <DataRouterContext.Provider> element"
  );
  return context;
}
function useDataRouterStateContext() {
  let context = reactExports.useContext(DataRouterStateContext);
  invariant2(
    context,
    "You must render this element inside a <DataRouterStateContext.Provider> element"
  );
  return context;
}
var FrameworkContext = reactExports.createContext(void 0);
FrameworkContext.displayName = "FrameworkContext";
function useFrameworkContext() {
  let context = reactExports.useContext(FrameworkContext);
  invariant2(
    context,
    "You must render this element inside a <HydratedRouter> element"
  );
  return context;
}
function usePrefetchBehavior(prefetch, theirElementProps) {
  let frameworkContext = reactExports.useContext(FrameworkContext);
  let [maybePrefetch, setMaybePrefetch] = reactExports.useState(false);
  let [shouldPrefetch, setShouldPrefetch] = reactExports.useState(false);
  let { onFocus, onBlur, onMouseEnter, onMouseLeave, onTouchStart } = theirElementProps;
  let ref2 = reactExports.useRef(null);
  reactExports.useEffect(() => {
    if (prefetch === "render") {
      setShouldPrefetch(true);
    }
    if (prefetch === "viewport") {
      let callback = (entries2) => {
        entries2.forEach((entry2) => {
          setShouldPrefetch(entry2.isIntersecting);
        });
      };
      let observer = new IntersectionObserver(callback, { threshold: 0.5 });
      if (ref2.current) observer.observe(ref2.current);
      return () => {
        observer.disconnect();
      };
    }
  }, [prefetch]);
  reactExports.useEffect(() => {
    if (maybePrefetch) {
      let id2 = setTimeout(() => {
        setShouldPrefetch(true);
      }, 100);
      return () => {
        clearTimeout(id2);
      };
    }
  }, [maybePrefetch]);
  let setIntent = () => {
    setMaybePrefetch(true);
  };
  let cancelIntent = () => {
    setMaybePrefetch(false);
    setShouldPrefetch(false);
  };
  if (!frameworkContext) {
    return [false, ref2, {}];
  }
  if (prefetch !== "intent") {
    return [shouldPrefetch, ref2, {}];
  }
  return [
    shouldPrefetch,
    ref2,
    {
      onFocus: composeEventHandlers(onFocus, setIntent),
      onBlur: composeEventHandlers(onBlur, cancelIntent),
      onMouseEnter: composeEventHandlers(onMouseEnter, setIntent),
      onMouseLeave: composeEventHandlers(onMouseLeave, cancelIntent),
      onTouchStart: composeEventHandlers(onTouchStart, setIntent)
    }
  ];
}
function composeEventHandlers(theirHandler, ourHandler) {
  return (event) => {
    theirHandler && theirHandler(event);
    if (!event.defaultPrevented) {
      ourHandler(event);
    }
  };
}
function PrefetchPageLinks({ page, ...linkProps }) {
  let { router } = useDataRouterContext2();
  let matches = reactExports.useMemo(
    () => matchRoutes(router.routes, page, router.basename),
    [router.routes, page, router.basename]
  );
  if (!matches) {
    return null;
  }
  return /* @__PURE__ */ reactExports.createElement(PrefetchPageLinksImpl, { page, matches, ...linkProps });
}
function useKeyedPrefetchLinks(matches) {
  let { manifest, routeModules } = useFrameworkContext();
  let [keyedPrefetchLinks, setKeyedPrefetchLinks] = reactExports.useState([]);
  reactExports.useEffect(() => {
    let interrupted = false;
    void getKeyedPrefetchLinks(matches, manifest, routeModules).then(
      (links2) => {
        if (!interrupted) {
          setKeyedPrefetchLinks(links2);
        }
      }
    );
    return () => {
      interrupted = true;
    };
  }, [matches, manifest, routeModules]);
  return keyedPrefetchLinks;
}
function PrefetchPageLinksImpl({
  page,
  matches: nextMatches,
  ...linkProps
}) {
  let location = useLocation();
  let { manifest, routeModules } = useFrameworkContext();
  let { basename: basename2 } = useDataRouterContext2();
  let { loaderData, matches } = useDataRouterStateContext();
  let newMatchesForData = reactExports.useMemo(
    () => getNewMatchesForLinks(
      page,
      nextMatches,
      matches,
      manifest,
      location,
      "data"
    ),
    [page, nextMatches, matches, manifest, location]
  );
  let newMatchesForAssets = reactExports.useMemo(
    () => getNewMatchesForLinks(
      page,
      nextMatches,
      matches,
      manifest,
      location,
      "assets"
    ),
    [page, nextMatches, matches, manifest, location]
  );
  let dataHrefs = reactExports.useMemo(() => {
    if (page === location.pathname + location.search + location.hash) {
      return [];
    }
    let routesParams = /* @__PURE__ */ new Set();
    let foundOptOutRoute = false;
    nextMatches.forEach((m) => {
      let manifestRoute = manifest.routes[m.route.id];
      if (!manifestRoute || !manifestRoute.hasLoader) {
        return;
      }
      if (!newMatchesForData.some((m2) => m2.route.id === m.route.id) && m.route.id in loaderData && routeModules[m.route.id]?.shouldRevalidate) {
        foundOptOutRoute = true;
      } else if (manifestRoute.hasClientLoader) {
        foundOptOutRoute = true;
      } else {
        routesParams.add(m.route.id);
      }
    });
    if (routesParams.size === 0) {
      return [];
    }
    let url = singleFetchUrl(page, basename2, "data");
    if (foundOptOutRoute && routesParams.size > 0) {
      url.searchParams.set(
        "_routes",
        nextMatches.filter((m) => routesParams.has(m.route.id)).map((m) => m.route.id).join(",")
      );
    }
    return [url.pathname + url.search];
  }, [
    basename2,
    loaderData,
    location,
    manifest,
    newMatchesForData,
    nextMatches,
    page,
    routeModules
  ]);
  let moduleHrefs = reactExports.useMemo(
    () => getModuleLinkHrefs(newMatchesForAssets, manifest),
    [newMatchesForAssets, manifest]
  );
  let keyedPrefetchLinks = useKeyedPrefetchLinks(newMatchesForAssets);
  return /* @__PURE__ */ reactExports.createElement(reactExports.Fragment, null, dataHrefs.map((href) => /* @__PURE__ */ reactExports.createElement("link", { key: href, rel: "prefetch", as: "fetch", href, ...linkProps })), moduleHrefs.map((href) => /* @__PURE__ */ reactExports.createElement("link", { key: href, rel: "modulepreload", href, ...linkProps })), keyedPrefetchLinks.map(({ key: key2, link: link2 }) => (
    // these don't spread `linkProps` because they are full link descriptors
    // already with their own props
    /* @__PURE__ */ reactExports.createElement("link", { key: key2, nonce: linkProps.nonce, ...link2 })
  )));
}
function mergeRefs(...refs) {
  return (value2) => {
    refs.forEach((ref2) => {
      if (typeof ref2 === "function") {
        ref2(value2);
      } else if (ref2 != null) {
        ref2.current = value2;
      }
    });
  };
}
var isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
try {
  if (isBrowser) {
    window.__reactRouterVersion = // @ts-expect-error
    "7.9.5";
  }
} catch (e) {
}
function createHashRouter(routes, opts) {
  return createRouter({
    basename: opts?.basename,
    getContext: opts?.getContext,
    future: opts?.future,
    history: createHashHistory({ window: opts?.window }),
    hydrationData: opts?.hydrationData || parseHydrationData(),
    routes,
    mapRouteProperties,
    hydrationRouteProperties,
    dataStrategy: opts?.dataStrategy,
    patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,
    window: opts?.window,
    unstable_instrumentations: opts?.unstable_instrumentations
  }).initialize();
}
function parseHydrationData() {
  let state = window?.__staticRouterHydrationData;
  if (state && state.errors) {
    state = {
      ...state,
      errors: deserializeErrors(state.errors)
    };
  }
  return state;
}
function deserializeErrors(errors2) {
  if (!errors2) return null;
  let entries2 = Object.entries(errors2);
  let serialized = {};
  for (let [key2, val] of entries2) {
    if (val && val.__type === "RouteErrorResponse") {
      serialized[key2] = new ErrorResponseImpl(
        val.status,
        val.statusText,
        val.data,
        val.internal === true
      );
    } else if (val && val.__type === "Error") {
      if (val.__subType) {
        let ErrorConstructor = window[val.__subType];
        if (typeof ErrorConstructor === "function") {
          try {
            let error2 = new ErrorConstructor(val.message);
            error2.stack = "";
            serialized[key2] = error2;
          } catch (e) {
          }
        }
      }
      if (serialized[key2] == null) {
        let error2 = new Error(val.message);
        error2.stack = "";
        serialized[key2] = error2;
      }
    } else {
      serialized[key2] = val;
    }
  }
  return serialized;
}
var ABSOLUTE_URL_REGEX2 = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
var Link = reactExports.forwardRef(
  function LinkWithRef({
    onClick,
    discover = "render",
    prefetch = "none",
    relative,
    reloadDocument,
    replace: replace2,
    state,
    target,
    to: to2,
    preventScrollReset,
    viewTransition,
    ...rest
  }, forwardedRef) {
    let { basename: basename2 } = reactExports.useContext(NavigationContext);
    let isAbsolute = typeof to2 === "string" && ABSOLUTE_URL_REGEX2.test(to2);
    let absoluteHref;
    let isExternal = false;
    if (typeof to2 === "string" && isAbsolute) {
      absoluteHref = to2;
      if (isBrowser) {
        try {
          let currentUrl = new URL(window.location.href);
          let targetUrl = to2.startsWith("//") ? new URL(currentUrl.protocol + to2) : new URL(to2);
          let path = stripBasename(targetUrl.pathname, basename2);
          if (targetUrl.origin === currentUrl.origin && path != null) {
            to2 = path + targetUrl.search + targetUrl.hash;
          } else {
            isExternal = true;
          }
        } catch (e) {
          warning(
            false,
            `<Link to="${to2}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`
          );
        }
      }
    }
    let href = useHref(to2, { relative });
    let [shouldPrefetch, prefetchRef, prefetchHandlers] = usePrefetchBehavior(
      prefetch,
      rest
    );
    let internalOnClick = useLinkClickHandler(to2, {
      replace: replace2,
      state,
      target,
      preventScrollReset,
      relative,
      viewTransition
    });
    function handleClick(event) {
      if (onClick) onClick(event);
      if (!event.defaultPrevented) {
        internalOnClick(event);
      }
    }
    let link2 = (
      // eslint-disable-next-line jsx-a11y/anchor-has-content
      /* @__PURE__ */ reactExports.createElement(
        "a",
        {
          ...rest,
          ...prefetchHandlers,
          href: absoluteHref || href,
          onClick: isExternal || reloadDocument ? onClick : handleClick,
          ref: mergeRefs(forwardedRef, prefetchRef),
          target,
          "data-discover": !isAbsolute && discover === "render" ? "true" : void 0
        }
      )
    );
    return shouldPrefetch && !isAbsolute ? /* @__PURE__ */ reactExports.createElement(reactExports.Fragment, null, link2, /* @__PURE__ */ reactExports.createElement(PrefetchPageLinks, { page: href })) : link2;
  }
);
Link.displayName = "Link";
var NavLink = reactExports.forwardRef(
  function NavLinkWithRef({
    "aria-current": ariaCurrentProp = "page",
    caseSensitive = false,
    className: classNameProp = "",
    end: end2 = false,
    style: styleProp,
    to: to2,
    viewTransition,
    children: children2,
    ...rest
  }, ref2) {
    let path = useResolvedPath(to2, { relative: rest.relative });
    let location = useLocation();
    let routerState = reactExports.useContext(DataRouterStateContext);
    let { navigator: navigator2, basename: basename2 } = reactExports.useContext(NavigationContext);
    let isTransitioning = routerState != null && // Conditional usage is OK here because the usage of a data router is static
    // eslint-disable-next-line react-hooks/rules-of-hooks
    useViewTransitionState(path) && viewTransition === true;
    let toPathname = navigator2.encodeLocation ? navigator2.encodeLocation(path).pathname : path.pathname;
    let locationPathname = location.pathname;
    let nextLocationPathname = routerState && routerState.navigation && routerState.navigation.location ? routerState.navigation.location.pathname : null;
    if (!caseSensitive) {
      locationPathname = locationPathname.toLowerCase();
      nextLocationPathname = nextLocationPathname ? nextLocationPathname.toLowerCase() : null;
      toPathname = toPathname.toLowerCase();
    }
    if (nextLocationPathname && basename2) {
      nextLocationPathname = stripBasename(nextLocationPathname, basename2) || nextLocationPathname;
    }
    const endSlashPosition = toPathname !== "/" && toPathname.endsWith("/") ? toPathname.length - 1 : toPathname.length;
    let isActive = locationPathname === toPathname || !end2 && locationPathname.startsWith(toPathname) && locationPathname.charAt(endSlashPosition) === "/";
    let isPending = nextLocationPathname != null && (nextLocationPathname === toPathname || !end2 && nextLocationPathname.startsWith(toPathname) && nextLocationPathname.charAt(toPathname.length) === "/");
    let renderProps = {
      isActive,
      isPending,
      isTransitioning
    };
    let ariaCurrent = isActive ? ariaCurrentProp : void 0;
    let className2;
    if (typeof classNameProp === "function") {
      className2 = classNameProp(renderProps);
    } else {
      className2 = [
        classNameProp,
        isActive ? "active" : null,
        isPending ? "pending" : null,
        isTransitioning ? "transitioning" : null
      ].filter(Boolean).join(" ");
    }
    let style2 = typeof styleProp === "function" ? styleProp(renderProps) : styleProp;
    return /* @__PURE__ */ reactExports.createElement(
      Link,
      {
        ...rest,
        "aria-current": ariaCurrent,
        className: className2,
        ref: ref2,
        style: style2,
        to: to2,
        viewTransition
      },
      typeof children2 === "function" ? children2(renderProps) : children2
    );
  }
);
NavLink.displayName = "NavLink";
var Form = reactExports.forwardRef(
  ({
    discover = "render",
    fetcherKey,
    navigate,
    reloadDocument,
    replace: replace2,
    state,
    method = defaultMethod,
    action,
    onSubmit,
    relative,
    preventScrollReset,
    viewTransition,
    ...props
  }, forwardedRef) => {
    let submit = useSubmit();
    let formAction = useFormAction(action, { relative });
    let formMethod = method.toLowerCase() === "get" ? "get" : "post";
    let isAbsolute = typeof action === "string" && ABSOLUTE_URL_REGEX2.test(action);
    let submitHandler = (event) => {
      onSubmit && onSubmit(event);
      if (event.defaultPrevented) return;
      event.preventDefault();
      let submitter = event.nativeEvent.submitter;
      let submitMethod = submitter?.getAttribute("formmethod") || method;
      submit(submitter || event.currentTarget, {
        fetcherKey,
        method: submitMethod,
        navigate,
        replace: replace2,
        state,
        relative,
        preventScrollReset,
        viewTransition
      });
    };
    return /* @__PURE__ */ reactExports.createElement(
      "form",
      {
        ref: forwardedRef,
        method: formMethod,
        action: formAction,
        onSubmit: reloadDocument ? onSubmit : submitHandler,
        ...props,
        "data-discover": !isAbsolute && discover === "render" ? "true" : void 0
      }
    );
  }
);
Form.displayName = "Form";
function getDataRouterConsoleError2(hookName) {
  return `${hookName} must be used within a data router.  See https://reactrouter.com/en/main/routers/picking-a-router.`;
}
function useDataRouterContext3(hookName) {
  let ctx = reactExports.useContext(DataRouterContext);
  invariant(ctx, getDataRouterConsoleError2(hookName));
  return ctx;
}
function useLinkClickHandler(to2, {
  target,
  replace: replaceProp,
  state,
  preventScrollReset,
  relative,
  viewTransition
} = {}) {
  let navigate = useNavigate();
  let location = useLocation();
  let path = useResolvedPath(to2, { relative });
  return reactExports.useCallback(
    (event) => {
      if (shouldProcessLinkClick(event, target)) {
        event.preventDefault();
        let replace2 = replaceProp !== void 0 ? replaceProp : createPath(location) === createPath(path);
        navigate(to2, {
          replace: replace2,
          state,
          preventScrollReset,
          relative,
          viewTransition
        });
      }
    },
    [
      location,
      navigate,
      path,
      replaceProp,
      state,
      target,
      to2,
      preventScrollReset,
      relative,
      viewTransition
    ]
  );
}
function useSearchParams(defaultInit) {
  warning(
    typeof URLSearchParams !== "undefined",
    `You cannot use the \`useSearchParams\` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.`
  );
  let defaultSearchParamsRef = reactExports.useRef(createSearchParams(defaultInit));
  let hasSetSearchParamsRef = reactExports.useRef(false);
  let location = useLocation();
  let searchParams = reactExports.useMemo(
    () => (
      // Only merge in the defaults if we haven't yet called setSearchParams.
      // Once we call that we want those to take precedence, otherwise you can't
      // remove a param with setSearchParams({}) if it has an initial value
      getSearchParamsForLocation(
        location.search,
        hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current
      )
    ),
    [location.search]
  );
  let navigate = useNavigate();
  let setSearchParams = reactExports.useCallback(
    (nextInit, navigateOptions) => {
      const newSearchParams = createSearchParams(
        typeof nextInit === "function" ? nextInit(new URLSearchParams(searchParams)) : nextInit
      );
      hasSetSearchParamsRef.current = true;
      navigate("?" + newSearchParams, navigateOptions);
    },
    [navigate, searchParams]
  );
  return [searchParams, setSearchParams];
}
var fetcherId = 0;
var getUniqueFetcherId = () => `__${String(++fetcherId)}__`;
function useSubmit() {
  let { router } = useDataRouterContext3(
    "useSubmit"
    /* UseSubmit */
  );
  let { basename: basename2 } = reactExports.useContext(NavigationContext);
  let currentRouteId = useRouteId();
  return reactExports.useCallback(
    async (target, options = {}) => {
      let { action, method, encType, formData, body } = getFormSubmissionInfo(
        target,
        basename2
      );
      if (options.navigate === false) {
        let key2 = options.fetcherKey || getUniqueFetcherId();
        await router.fetch(key2, currentRouteId, options.action || action, {
          preventScrollReset: options.preventScrollReset,
          formData,
          body,
          formMethod: options.method || method,
          formEncType: options.encType || encType,
          flushSync: options.flushSync
        });
      } else {
        await router.navigate(options.action || action, {
          preventScrollReset: options.preventScrollReset,
          formData,
          body,
          formMethod: options.method || method,
          formEncType: options.encType || encType,
          replace: options.replace,
          state: options.state,
          fromRouteId: currentRouteId,
          flushSync: options.flushSync,
          viewTransition: options.viewTransition
        });
      }
    },
    [router, basename2, currentRouteId]
  );
}
function useFormAction(action, { relative } = {}) {
  let { basename: basename2 } = reactExports.useContext(NavigationContext);
  let routeContext = reactExports.useContext(RouteContext);
  invariant(routeContext, "useFormAction must be used inside a RouteContext");
  let [match3] = routeContext.matches.slice(-1);
  let path = { ...useResolvedPath(action ? action : ".", { relative }) };
  let location = useLocation();
  if (action == null) {
    path.search = location.search;
    let params = new URLSearchParams(path.search);
    let indexValues = params.getAll("index");
    let hasNakedIndexParam = indexValues.some((v) => v === "");
    if (hasNakedIndexParam) {
      params.delete("index");
      indexValues.filter((v) => v).forEach((v) => params.append("index", v));
      let qs = params.toString();
      path.search = qs ? `?${qs}` : "";
    }
  }
  if ((!action || action === ".") && match3.route.index) {
    path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
  }
  if (basename2 !== "/") {
    path.pathname = path.pathname === "/" ? basename2 : joinPaths([basename2, path.pathname]);
  }
  return createPath(path);
}
function useViewTransitionState(to2, { relative } = {}) {
  let vtContext = reactExports.useContext(ViewTransitionContext);
  invariant(
    vtContext != null,
    "`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`.  Did you accidentally import `RouterProvider` from `react-router`?"
  );
  let { basename: basename2 } = useDataRouterContext3(
    "useViewTransitionState"
    /* useViewTransitionState */
  );
  let path = useResolvedPath(to2, { relative });
  if (!vtContext.isTransitioning) {
    return false;
  }
  let currentPath = stripBasename(vtContext.currentLocation.pathname, basename2) || vtContext.currentLocation.pathname;
  let nextPath = stripBasename(vtContext.nextLocation.pathname, basename2) || vtContext.nextLocation.pathname;
  return matchPath(path.pathname, nextPath) != null || matchPath(path.pathname, currentPath) != null;
}
var reactDomExports = requireReactDom();
const ReactDOM = /* @__PURE__ */ getDefaultExportFromCjs(reactDomExports);
function RouterProvider2(props) {
  return /* @__PURE__ */ reactExports.createElement(RouterProvider, { flushSync: reactDomExports.flushSync, ...props });
}
function r$1(e) {
  var t2, f, n2 = "";
  if ("string" == typeof e || "number" == typeof e) n2 += e;
  else if ("object" == typeof e) if (Array.isArray(e)) {
    var o = e.length;
    for (t2 = 0; t2 < o; t2++) e[t2] && (f = r$1(e[t2])) && (n2 && (n2 += " "), n2 += f);
  } else for (f in e) e[f] && (n2 && (n2 += " "), n2 += f);
  return n2;
}
function clsx() {
  for (var e, t2, f = 0, n2 = "", o = arguments.length; f < o; f++) (e = arguments[f]) && (t2 = r$1(e)) && (n2 && (n2 += " "), n2 += t2);
  return n2;
}
const wrapper$2 = "_wrapper_1tajk_1";
const container$i = "_container_1tajk_12";
const animate = "_animate_1tajk_21";
const styles$1n = {
  wrapper: wrapper$2,
  container: container$i,
  animate
};
const ActivityBar = ({ animating }) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$1n.wrapper), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "div",
    {
      className: clsx(styles$1n.container),
      role: "progressbar",
      "aria-label": "Progress bar",
      "aria-valuenow": 25,
      "aria-valuemin": 0,
      "aria-valuemax": 100,
      children: animating && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: styles$1n.animate }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/ActivityBar.tsx",
        lineNumber: 21,
        columnNumber: 23
      }, void 0)
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/ActivityBar.tsx",
      lineNumber: 13,
      columnNumber: 7
    },
    void 0
  ) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/ActivityBar.tsx",
    lineNumber: 12,
    columnNumber: 5
  }, void 0);
};
const ExtendedFindContext = reactExports.createContext(null);
const useExtendedFind = () => {
  const context = reactExports.useContext(ExtendedFindContext);
  if (!context) {
    throw new Error("useSearch must be used within a SearchProvider");
  }
  return context;
};
const ExtendedFindProvider = ({
  children: children2
}) => {
  const virtualLists = reactExports.useRef(/* @__PURE__ */ new Map());
  const extendedFindTerm = reactExports.useCallback(
    async (term, direction) => {
      for (const [, searchFn] of virtualLists.current) {
        const found = await new Promise((resolve2) => {
          let callbackFired = false;
          const onContentReady = () => {
            if (!callbackFired) {
              callbackFired = true;
              resolve2(true);
            }
          };
          searchFn(term, direction, onContentReady).then((found2) => {
            if (!found2 && !callbackFired) {
              callbackFired = true;
              resolve2(false);
            }
          }).catch(() => {
            if (!callbackFired) {
              callbackFired = true;
              resolve2(false);
            }
          });
        });
        if (found) {
          return true;
        }
      }
      return false;
    },
    []
  );
  const registerVirtualList = reactExports.useCallback(
    (id2, searchFn) => {
      virtualLists.current.set(id2, searchFn);
      return () => {
        virtualLists.current.delete(id2);
      };
    },
    []
  );
  const contextValue = {
    extendedFindTerm,
    registerVirtualList
  };
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ExtendedFindContext.Provider, { value: contextValue, children: children2 }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/ExtendedFindProvider.tsx",
    lineNumber: 79,
    columnNumber: 5
  }, void 0);
};
const maybeBase64 = (str, minLen = 256) => {
  const base64Pattern = /^(?:[A-Za-z0-9+/]{4})*?(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
  return str.length > minLen && base64Pattern.test(str);
};
var prism = { exports: {} };
var hasRequiredPrism;
function requirePrism() {
  if (hasRequiredPrism) return prism.exports;
  hasRequiredPrism = 1;
  (function(module) {
    var _self = typeof window !== "undefined" ? window : typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope ? self : {};
    /**
     * Prism: Lightweight, robust, elegant syntax highlighting
     *
     * @license MIT <https://opensource.org/licenses/MIT>
     * @author Lea Verou <https://lea.verou.me>
     * @namespace
     * @public
     */
    var Prism2 = (function(_self2) {
      var lang = /(?:^|\s)lang(?:uage)?-([\w-]+)(?=\s|$)/i;
      var uniqueId = 0;
      var plainTextGrammar = {};
      var _ = {
        /**
         * By default, Prism will attempt to highlight all code elements (by calling {@link Prism.highlightAll}) on the
         * current page after the page finished loading. This might be a problem if e.g. you wanted to asynchronously load
         * additional languages or plugins yourself.
         *
         * By setting this value to `true`, Prism will not automatically highlight all code elements on the page.
         *
         * You obviously have to change this value before the automatic highlighting started. To do this, you can add an
         * empty Prism object into the global scope before loading the Prism script like this:
         *
         * ```js
         * window.Prism = window.Prism || {};
         * Prism.manual = true;
         * // add a new <script> to load Prism's script
         * ```
         *
         * @default false
         * @type {boolean}
         * @memberof Prism
         * @public
         */
        manual: _self2.Prism && _self2.Prism.manual,
        /**
         * By default, if Prism is in a web worker, it assumes that it is in a worker it created itself, so it uses
         * `addEventListener` to communicate with its parent instance. However, if you're using Prism manually in your
         * own worker, you don't want it to do this.
         *
         * By setting this value to `true`, Prism will not add its own listeners to the worker.
         *
         * You obviously have to change this value before Prism executes. To do this, you can add an
         * empty Prism object into the global scope before loading the Prism script like this:
         *
         * ```js
         * window.Prism = window.Prism || {};
         * Prism.disableWorkerMessageHandler = true;
         * // Load Prism's script
         * ```
         *
         * @default false
         * @type {boolean}
         * @memberof Prism
         * @public
         */
        disableWorkerMessageHandler: _self2.Prism && _self2.Prism.disableWorkerMessageHandler,
        /**
         * A namespace for utility methods.
         *
         * All function in this namespace that are not explicitly marked as _public_ are for __internal use only__ and may
         * change or disappear at any time.
         *
         * @namespace
         * @memberof Prism
         */
        util: {
          encode: function encode2(tokens) {
            if (tokens instanceof Token3) {
              return new Token3(tokens.type, encode2(tokens.content), tokens.alias);
            } else if (Array.isArray(tokens)) {
              return tokens.map(encode2);
            } else {
              return tokens.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/\u00a0/g, " ");
            }
          },
          /**
           * Returns the name of the type of the given value.
           *
           * @param {any} o
           * @returns {string}
           * @example
           * type(null)      === 'Null'
           * type(undefined) === 'Undefined'
           * type(123)       === 'Number'
           * type('foo')     === 'String'
           * type(true)      === 'Boolean'
           * type([1, 2])    === 'Array'
           * type({})        === 'Object'
           * type(String)    === 'Function'
           * type(/abc+/)    === 'RegExp'
           */
          type: function(o) {
            return Object.prototype.toString.call(o).slice(8, -1);
          },
          /**
           * Returns a unique number for the given object. Later calls will still return the same number.
           *
           * @param {Object} obj
           * @returns {number}
           */
          objId: function(obj) {
            if (!obj["__id"]) {
              Object.defineProperty(obj, "__id", { value: ++uniqueId });
            }
            return obj["__id"];
          },
          /**
           * Creates a deep clone of the given object.
           *
           * The main intended use of this function is to clone language definitions.
           *
           * @param {T} o
           * @param {Record<number, any>} [visited]
           * @returns {T}
           * @template T
           */
          clone: function deepClone(o, visited) {
            visited = visited || {};
            var clone2;
            var id2;
            switch (_.util.type(o)) {
              case "Object":
                id2 = _.util.objId(o);
                if (visited[id2]) {
                  return visited[id2];
                }
                clone2 = /** @type {Record<string, any>} */
                {};
                visited[id2] = clone2;
                for (var key2 in o) {
                  if (o.hasOwnProperty(key2)) {
                    clone2[key2] = deepClone(o[key2], visited);
                  }
                }
                return (
                  /** @type {any} */
                  clone2
                );
              case "Array":
                id2 = _.util.objId(o);
                if (visited[id2]) {
                  return visited[id2];
                }
                clone2 = [];
                visited[id2] = clone2;
                /** @type {Array} */
                /** @type {any} */
                o.forEach(function(v, i2) {
                  clone2[i2] = deepClone(v, visited);
                });
                return (
                  /** @type {any} */
                  clone2
                );
              default:
                return o;
            }
          },
          /**
           * Returns the Prism language of the given element set by a `language-xxxx` or `lang-xxxx` class.
           *
           * If no language is set for the element or the element is `null` or `undefined`, `none` will be returned.
           *
           * @param {Element} element
           * @returns {string}
           */
          getLanguage: function(element) {
            while (element) {
              var m = lang.exec(element.className);
              if (m) {
                return m[1].toLowerCase();
              }
              element = element.parentElement;
            }
            return "none";
          },
          /**
           * Sets the Prism `language-xxxx` class of the given element.
           *
           * @param {Element} element
           * @param {string} language
           * @returns {void}
           */
          setLanguage: function(element, language) {
            element.className = element.className.replace(RegExp(lang, "gi"), "");
            element.classList.add("language-" + language);
          },
          /**
           * Returns the script element that is currently executing.
           *
           * This does __not__ work for line script element.
           *
           * @returns {HTMLScriptElement | null}
           */
          currentScript: function() {
            if (typeof document === "undefined") {
              return null;
            }
            if (document.currentScript && document.currentScript.tagName === "SCRIPT" && 1 < 2) {
              return (
                /** @type {any} */
                document.currentScript
              );
            }
            try {
              throw new Error();
            } catch (err) {
              var src = (/at [^(\r\n]*\((.*):[^:]+:[^:]+\)$/i.exec(err.stack) || [])[1];
              if (src) {
                var scripts = document.getElementsByTagName("script");
                for (var i2 in scripts) {
                  if (scripts[i2].src == src) {
                    return scripts[i2];
                  }
                }
              }
              return null;
            }
          },
          /**
           * Returns whether a given class is active for `element`.
           *
           * The class can be activated if `element` or one of its ancestors has the given class and it can be deactivated
           * if `element` or one of its ancestors has the negated version of the given class. The _negated version_ of the
           * given class is just the given class with a `no-` prefix.
           *
           * Whether the class is active is determined by the closest ancestor of `element` (where `element` itself is
           * closest ancestor) that has the given class or the negated version of it. If neither `element` nor any of its
           * ancestors have the given class or the negated version of it, then the default activation will be returned.
           *
           * In the paradoxical situation where the closest ancestor contains __both__ the given class and the negated
           * version of it, the class is considered active.
           *
           * @param {Element} element
           * @param {string} className
           * @param {boolean} [defaultActivation=false]
           * @returns {boolean}
           */
          isActive: function(element, className2, defaultActivation) {
            var no2 = "no-" + className2;
            while (element) {
              var classList = element.classList;
              if (classList.contains(className2)) {
                return true;
              }
              if (classList.contains(no2)) {
                return false;
              }
              element = element.parentElement;
            }
            return !!defaultActivation;
          }
        },
        /**
         * This namespace contains all currently loaded languages and the some helper functions to create and modify languages.
         *
         * @namespace
         * @memberof Prism
         * @public
         */
        languages: {
          /**
           * The grammar for plain, unformatted text.
           */
          plain: plainTextGrammar,
          plaintext: plainTextGrammar,
          text: plainTextGrammar,
          txt: plainTextGrammar,
          /**
           * Creates a deep copy of the language with the given id and appends the given tokens.
           *
           * If a token in `redef` also appears in the copied language, then the existing token in the copied language
           * will be overwritten at its original position.
           *
           * ## Best practices
           *
           * Since the position of overwriting tokens (token in `redef` that overwrite tokens in the copied language)
           * doesn't matter, they can technically be in any order. However, this can be confusing to others that trying to
           * understand the language definition because, normally, the order of tokens matters in Prism grammars.
           *
           * Therefore, it is encouraged to order overwriting tokens according to the positions of the overwritten tokens.
           * Furthermore, all non-overwriting tokens should be placed after the overwriting ones.
           *
           * @param {string} id The id of the language to extend. This has to be a key in `Prism.languages`.
           * @param {Grammar} redef The new tokens to append.
           * @returns {Grammar} The new language created.
           * @public
           * @example
           * Prism.languages['css-with-colors'] = Prism.languages.extend('css', {
           *     // Prism.languages.css already has a 'comment' token, so this token will overwrite CSS' 'comment' token
           *     // at its original position
           *     'comment': { ... },
           *     // CSS doesn't have a 'color' token, so this token will be appended
           *     'color': /\b(?:red|green|blue)\b/
           * });
           */
          extend: function(id2, redef) {
            var lang2 = _.util.clone(_.languages[id2]);
            for (var key2 in redef) {
              lang2[key2] = redef[key2];
            }
            return lang2;
          },
          /**
           * Inserts tokens _before_ another token in a language definition or any other grammar.
           *
           * ## Usage
           *
           * This helper method makes it easy to modify existing languages. For example, the CSS language definition
           * not only defines CSS highlighting for CSS documents, but also needs to define highlighting for CSS embedded
           * in HTML through `<style>` elements. To do this, it needs to modify `Prism.languages.markup` and add the
           * appropriate tokens. However, `Prism.languages.markup` is a regular JavaScript object literal, so if you do
           * this:
           *
           * ```js
           * Prism.languages.markup.style = {
           *     // token
           * };
           * ```
           *
           * then the `style` token will be added (and processed) at the end. `insertBefore` allows you to insert tokens
           * before existing tokens. For the CSS example above, you would use it like this:
           *
           * ```js
           * Prism.languages.insertBefore('markup', 'cdata', {
           *     'style': {
           *         // token
           *     }
           * });
           * ```
           *
           * ## Special cases
           *
           * If the grammars of `inside` and `insert` have tokens with the same name, the tokens in `inside`'s grammar
           * will be ignored.
           *
           * This behavior can be used to insert tokens after `before`:
           *
           * ```js
           * Prism.languages.insertBefore('markup', 'comment', {
           *     'comment': Prism.languages.markup.comment,
           *     // tokens after 'comment'
           * });
           * ```
           *
           * ## Limitations
           *
           * The main problem `insertBefore` has to solve is iteration order. Since ES2015, the iteration order for object
           * properties is guaranteed to be the insertion order (except for integer keys) but some browsers behave
           * differently when keys are deleted and re-inserted. So `insertBefore` can't be implemented by temporarily
           * deleting properties which is necessary to insert at arbitrary positions.
           *
           * To solve this problem, `insertBefore` doesn't actually insert the given tokens into the target object.
           * Instead, it will create a new object and replace all references to the target object with the new one. This
           * can be done without temporarily deleting properties, so the iteration order is well-defined.
           *
           * However, only references that can be reached from `Prism.languages` or `insert` will be replaced. I.e. if
           * you hold the target object in a variable, then the value of the variable will not change.
           *
           * ```js
           * var oldMarkup = Prism.languages.markup;
           * var newMarkup = Prism.languages.insertBefore('markup', 'comment', { ... });
           *
           * assert(oldMarkup !== Prism.languages.markup);
           * assert(newMarkup === Prism.languages.markup);
           * ```
           *
           * @param {string} inside The property of `root` (e.g. a language id in `Prism.languages`) that contains the
           * object to be modified.
           * @param {string} before The key to insert before.
           * @param {Grammar} insert An object containing the key-value pairs to be inserted.
           * @param {Object<string, any>} [root] The object containing `inside`, i.e. the object that contains the
           * object to be modified.
           *
           * Defaults to `Prism.languages`.
           * @returns {Grammar} The new grammar object.
           * @public
           */
          insertBefore: function(inside, before, insert2, root2) {
            root2 = root2 || /** @type {any} */
            _.languages;
            var grammar = root2[inside];
            var ret = {};
            for (var token2 in grammar) {
              if (grammar.hasOwnProperty(token2)) {
                if (token2 == before) {
                  for (var newToken2 in insert2) {
                    if (insert2.hasOwnProperty(newToken2)) {
                      ret[newToken2] = insert2[newToken2];
                    }
                  }
                }
                if (!insert2.hasOwnProperty(token2)) {
                  ret[token2] = grammar[token2];
                }
              }
            }
            var old = root2[inside];
            root2[inside] = ret;
            _.languages.DFS(_.languages, function(key2, value2) {
              if (value2 === old && key2 != inside) {
                this[key2] = ret;
              }
            });
            return ret;
          },
          // Traverse a language definition with Depth First Search
          DFS: function DFS(o, callback, type, visited) {
            visited = visited || {};
            var objId = _.util.objId;
            for (var i2 in o) {
              if (o.hasOwnProperty(i2)) {
                callback.call(o, i2, o[i2], type || i2);
                var property = o[i2];
                var propertyType = _.util.type(property);
                if (propertyType === "Object" && !visited[objId(property)]) {
                  visited[objId(property)] = true;
                  DFS(property, callback, null, visited);
                } else if (propertyType === "Array" && !visited[objId(property)]) {
                  visited[objId(property)] = true;
                  DFS(property, callback, i2, visited);
                }
              }
            }
          }
        },
        plugins: {},
        /**
         * This is the most high-level function in Prism’s API.
         * It fetches all the elements that have a `.language-xxxx` class and then calls {@link Prism.highlightElement} on
         * each one of them.
         *
         * This is equivalent to `Prism.highlightAllUnder(document, async, callback)`.
         *
         * @param {boolean} [async=false] Same as in {@link Prism.highlightAllUnder}.
         * @param {HighlightCallback} [callback] Same as in {@link Prism.highlightAllUnder}.
         * @memberof Prism
         * @public
         */
        highlightAll: function(async, callback) {
          _.highlightAllUnder(document, async, callback);
        },
        /**
         * Fetches all the descendants of `container` that have a `.language-xxxx` class and then calls
         * {@link Prism.highlightElement} on each one of them.
         *
         * The following hooks will be run:
         * 1. `before-highlightall`
         * 2. `before-all-elements-highlight`
         * 3. All hooks of {@link Prism.highlightElement} for each element.
         *
         * @param {ParentNode} container The root element, whose descendants that have a `.language-xxxx` class will be highlighted.
         * @param {boolean} [async=false] Whether each element is to be highlighted asynchronously using Web Workers.
         * @param {HighlightCallback} [callback] An optional callback to be invoked on each element after its highlighting is done.
         * @memberof Prism
         * @public
         */
        highlightAllUnder: function(container2, async, callback) {
          var env = {
            callback,
            container: container2,
            selector: 'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'
          };
          _.hooks.run("before-highlightall", env);
          env.elements = Array.prototype.slice.apply(env.container.querySelectorAll(env.selector));
          _.hooks.run("before-all-elements-highlight", env);
          for (var i2 = 0, element; element = env.elements[i2++]; ) {
            _.highlightElement(element, async === true, env.callback);
          }
        },
        /**
         * Highlights the code inside a single element.
         *
         * The following hooks will be run:
         * 1. `before-sanity-check`
         * 2. `before-highlight`
         * 3. All hooks of {@link Prism.highlight}. These hooks will be run by an asynchronous worker if `async` is `true`.
         * 4. `before-insert`
         * 5. `after-highlight`
         * 6. `complete`
         *
         * Some the above hooks will be skipped if the element doesn't contain any text or there is no grammar loaded for
         * the element's language.
         *
         * @param {Element} element The element containing the code.
         * It must have a class of `language-xxxx` to be processed, where `xxxx` is a valid language identifier.
         * @param {boolean} [async=false] Whether the element is to be highlighted asynchronously using Web Workers
         * to improve performance and avoid blocking the UI when highlighting very large chunks of code. This option is
         * [disabled by default](https://prismjs.com/faq.html#why-is-asynchronous-highlighting-disabled-by-default).
         *
         * Note: All language definitions required to highlight the code must be included in the main `prism.js` file for
         * asynchronous highlighting to work. You can build your own bundle on the
         * [Download page](https://prismjs.com/download.html).
         * @param {HighlightCallback} [callback] An optional callback to be invoked after the highlighting is done.
         * Mostly useful when `async` is `true`, since in that case, the highlighting is done asynchronously.
         * @memberof Prism
         * @public
         */
        highlightElement: function(element, async, callback) {
          var language = _.util.getLanguage(element);
          var grammar = _.languages[language];
          _.util.setLanguage(element, language);
          var parent = element.parentElement;
          if (parent && parent.nodeName.toLowerCase() === "pre") {
            _.util.setLanguage(parent, language);
          }
          var code2 = element.textContent;
          var env = {
            element,
            language,
            grammar,
            code: code2
          };
          function insertHighlightedCode(highlightedCode) {
            env.highlightedCode = highlightedCode;
            _.hooks.run("before-insert", env);
            env.element.innerHTML = env.highlightedCode;
            _.hooks.run("after-highlight", env);
            _.hooks.run("complete", env);
            callback && callback.call(env.element);
          }
          _.hooks.run("before-sanity-check", env);
          parent = env.element.parentElement;
          if (parent && parent.nodeName.toLowerCase() === "pre" && !parent.hasAttribute("tabindex")) {
            parent.setAttribute("tabindex", "0");
          }
          if (!env.code) {
            _.hooks.run("complete", env);
            callback && callback.call(env.element);
            return;
          }
          _.hooks.run("before-highlight", env);
          if (!env.grammar) {
            insertHighlightedCode(_.util.encode(env.code));
            return;
          }
          if (async && _self2.Worker) {
            var worker = new Worker(_.filename);
            worker.onmessage = function(evt) {
              insertHighlightedCode(evt.data);
            };
            worker.postMessage(JSON.stringify({
              language: env.language,
              code: env.code,
              immediateClose: true
            }));
          } else {
            insertHighlightedCode(_.highlight(env.code, env.grammar, env.language));
          }
        },
        /**
         * Low-level function, only use if you know what you’re doing. It accepts a string of text as input
         * and the language definitions to use, and returns a string with the HTML produced.
         *
         * The following hooks will be run:
         * 1. `before-tokenize`
         * 2. `after-tokenize`
         * 3. `wrap`: On each {@link Token}.
         *
         * @param {string} text A string with the code to be highlighted.
         * @param {Grammar} grammar An object containing the tokens to use.
         *
         * Usually a language definition like `Prism.languages.markup`.
         * @param {string} language The name of the language definition passed to `grammar`.
         * @returns {string} The highlighted HTML.
         * @memberof Prism
         * @public
         * @example
         * Prism.highlight('var foo = true;', Prism.languages.javascript, 'javascript');
         */
        highlight: function(text2, grammar, language) {
          var env = {
            code: text2,
            grammar,
            language
          };
          _.hooks.run("before-tokenize", env);
          if (!env.grammar) {
            throw new Error('The language "' + env.language + '" has no grammar.');
          }
          env.tokens = _.tokenize(env.code, env.grammar);
          _.hooks.run("after-tokenize", env);
          return Token3.stringify(_.util.encode(env.tokens), env.language);
        },
        /**
         * This is the heart of Prism, and the most low-level function you can use. It accepts a string of text as input
         * and the language definitions to use, and returns an array with the tokenized code.
         *
         * When the language definition includes nested tokens, the function is called recursively on each of these tokens.
         *
         * This method could be useful in other contexts as well, as a very crude parser.
         *
         * @param {string} text A string with the code to be highlighted.
         * @param {Grammar} grammar An object containing the tokens to use.
         *
         * Usually a language definition like `Prism.languages.markup`.
         * @returns {TokenStream} An array of strings and tokens, a token stream.
         * @memberof Prism
         * @public
         * @example
         * let code = `var foo = 0;`;
         * let tokens = Prism.tokenize(code, Prism.languages.javascript);
         * tokens.forEach(token => {
         *     if (token instanceof Prism.Token && token.type === 'number') {
         *         console.log(`Found numeric literal: ${token.content}`);
         *     }
         * });
         */
        tokenize: function(text2, grammar) {
          var rest = grammar.rest;
          if (rest) {
            for (var token2 in rest) {
              grammar[token2] = rest[token2];
            }
            delete grammar.rest;
          }
          var tokenList = new LinkedList();
          addAfter(tokenList, tokenList.head, text2);
          matchGrammar(text2, tokenList, grammar, tokenList.head, 0);
          return toArray2(tokenList);
        },
        /**
         * @namespace
         * @memberof Prism
         * @public
         */
        hooks: {
          all: {},
          /**
           * Adds the given callback to the list of callbacks for the given hook.
           *
           * The callback will be invoked when the hook it is registered for is run.
           * Hooks are usually directly run by a highlight function but you can also run hooks yourself.
           *
           * One callback function can be registered to multiple hooks and the same hook multiple times.
           *
           * @param {string} name The name of the hook.
           * @param {HookCallback} callback The callback function which is given environment variables.
           * @public
           */
          add: function(name2, callback) {
            var hooks = _.hooks.all;
            hooks[name2] = hooks[name2] || [];
            hooks[name2].push(callback);
          },
          /**
           * Runs a hook invoking all registered callbacks with the given environment variables.
           *
           * Callbacks will be invoked synchronously and in the order in which they were registered.
           *
           * @param {string} name The name of the hook.
           * @param {Object<string, any>} env The environment variables of the hook passed to all callbacks registered.
           * @public
           */
          run: function(name2, env) {
            var callbacks = _.hooks.all[name2];
            if (!callbacks || !callbacks.length) {
              return;
            }
            for (var i2 = 0, callback; callback = callbacks[i2++]; ) {
              callback(env);
            }
          }
        },
        Token: Token3
      };
      _self2.Prism = _;
      function Token3(type, content2, alias, matchedStr) {
        this.type = type;
        this.content = content2;
        this.alias = alias;
        this.length = (matchedStr || "").length | 0;
      }
      Token3.stringify = function stringify3(o, language) {
        if (typeof o == "string") {
          return o;
        }
        if (Array.isArray(o)) {
          var s = "";
          o.forEach(function(e) {
            s += stringify3(e, language);
          });
          return s;
        }
        var env = {
          type: o.type,
          content: stringify3(o.content, language),
          tag: "span",
          classes: ["token", o.type],
          attributes: {},
          language
        };
        var aliases = o.alias;
        if (aliases) {
          if (Array.isArray(aliases)) {
            Array.prototype.push.apply(env.classes, aliases);
          } else {
            env.classes.push(aliases);
          }
        }
        _.hooks.run("wrap", env);
        var attributes = "";
        for (var name2 in env.attributes) {
          attributes += " " + name2 + '="' + (env.attributes[name2] || "").replace(/"/g, "&quot;") + '"';
        }
        return "<" + env.tag + ' class="' + env.classes.join(" ") + '"' + attributes + ">" + env.content + "</" + env.tag + ">";
      };
      function matchPattern(pattern, pos2, text2, lookbehind) {
        pattern.lastIndex = pos2;
        var match3 = pattern.exec(text2);
        if (match3 && lookbehind && match3[1]) {
          var lookbehindLength = match3[1].length;
          match3.index += lookbehindLength;
          match3[0] = match3[0].slice(lookbehindLength);
        }
        return match3;
      }
      function matchGrammar(text2, tokenList, grammar, startNode, startPos, rematch) {
        for (var token2 in grammar) {
          if (!grammar.hasOwnProperty(token2) || !grammar[token2]) {
            continue;
          }
          var patterns = grammar[token2];
          patterns = Array.isArray(patterns) ? patterns : [patterns];
          for (var j2 = 0; j2 < patterns.length; ++j2) {
            if (rematch && rematch.cause == token2 + "," + j2) {
              return;
            }
            var patternObj = patterns[j2];
            var inside = patternObj.inside;
            var lookbehind = !!patternObj.lookbehind;
            var greedy = !!patternObj.greedy;
            var alias = patternObj.alias;
            if (greedy && !patternObj.pattern.global) {
              var flags = patternObj.pattern.toString().match(/[imsuy]*$/)[0];
              patternObj.pattern = RegExp(patternObj.pattern.source, flags + "g");
            }
            var pattern = patternObj.pattern || patternObj;
            for (var currentNode = startNode.next, pos2 = startPos; currentNode !== tokenList.tail; pos2 += currentNode.value.length, currentNode = currentNode.next) {
              if (rematch && pos2 >= rematch.reach) {
                break;
              }
              var str = currentNode.value;
              if (tokenList.length > text2.length) {
                return;
              }
              if (str instanceof Token3) {
                continue;
              }
              var removeCount = 1;
              var match3;
              if (greedy) {
                match3 = matchPattern(pattern, pos2, text2, lookbehind);
                if (!match3 || match3.index >= text2.length) {
                  break;
                }
                var from2 = match3.index;
                var to2 = match3.index + match3[0].length;
                var p = pos2;
                p += currentNode.value.length;
                while (from2 >= p) {
                  currentNode = currentNode.next;
                  p += currentNode.value.length;
                }
                p -= currentNode.value.length;
                pos2 = p;
                if (currentNode.value instanceof Token3) {
                  continue;
                }
                for (var k = currentNode; k !== tokenList.tail && (p < to2 || typeof k.value === "string"); k = k.next) {
                  removeCount++;
                  p += k.value.length;
                }
                removeCount--;
                str = text2.slice(pos2, p);
                match3.index -= pos2;
              } else {
                match3 = matchPattern(pattern, 0, str, lookbehind);
                if (!match3) {
                  continue;
                }
              }
              var from2 = match3.index;
              var matchStr = match3[0];
              var before = str.slice(0, from2);
              var after = str.slice(from2 + matchStr.length);
              var reach = pos2 + str.length;
              if (rematch && reach > rematch.reach) {
                rematch.reach = reach;
              }
              var removeFrom = currentNode.prev;
              if (before) {
                removeFrom = addAfter(tokenList, removeFrom, before);
                pos2 += before.length;
              }
              removeRange(tokenList, removeFrom, removeCount);
              var wrapped = new Token3(token2, inside ? _.tokenize(matchStr, inside) : matchStr, alias, matchStr);
              currentNode = addAfter(tokenList, removeFrom, wrapped);
              if (after) {
                addAfter(tokenList, currentNode, after);
              }
              if (removeCount > 1) {
                var nestedRematch = {
                  cause: token2 + "," + j2,
                  reach
                };
                matchGrammar(text2, tokenList, grammar, currentNode.prev, pos2, nestedRematch);
                if (rematch && nestedRematch.reach > rematch.reach) {
                  rematch.reach = nestedRematch.reach;
                }
              }
            }
          }
        }
      }
      function LinkedList() {
        var head = { value: null, prev: null, next: null };
        var tail = { value: null, prev: head, next: null };
        head.next = tail;
        this.head = head;
        this.tail = tail;
        this.length = 0;
      }
      function addAfter(list2, node2, value2) {
        var next = node2.next;
        var newNode = { value: value2, prev: node2, next };
        node2.next = newNode;
        next.prev = newNode;
        list2.length++;
        return newNode;
      }
      function removeRange(list2, node2, count2) {
        var next = node2.next;
        for (var i2 = 0; i2 < count2 && next !== list2.tail; i2++) {
          next = next.next;
        }
        node2.next = next;
        next.prev = node2;
        list2.length -= i2;
      }
      function toArray2(list2) {
        var array2 = [];
        var node2 = list2.head.next;
        while (node2 !== list2.tail) {
          array2.push(node2.value);
          node2 = node2.next;
        }
        return array2;
      }
      if (!_self2.document) {
        if (!_self2.addEventListener) {
          return _;
        }
        if (!_.disableWorkerMessageHandler) {
          _self2.addEventListener("message", function(evt) {
            var message2 = JSON.parse(evt.data);
            var lang2 = message2.language;
            var code2 = message2.code;
            var immediateClose = message2.immediateClose;
            _self2.postMessage(_.highlight(code2, _.languages[lang2], lang2));
            if (immediateClose) {
              _self2.close();
            }
          }, false);
        }
        return _;
      }
      var script = _.util.currentScript();
      if (script) {
        _.filename = script.src;
        if (script.hasAttribute("data-manual")) {
          _.manual = true;
        }
      }
      function highlightAutomaticallyCallback() {
        if (!_.manual) {
          _.highlightAll();
        }
      }
      if (!_.manual) {
        var readyState = document.readyState;
        if (readyState === "loading" || readyState === "interactive" && script && script.defer) {
          document.addEventListener("DOMContentLoaded", highlightAutomaticallyCallback);
        } else {
          if (window.requestAnimationFrame) {
            window.requestAnimationFrame(highlightAutomaticallyCallback);
          } else {
            window.setTimeout(highlightAutomaticallyCallback, 16);
          }
        }
      }
      return _;
    })(_self);
    if (module.exports) {
      module.exports = Prism2;
    }
    if (typeof commonjsGlobal !== "undefined") {
      commonjsGlobal.Prism = Prism2;
    }
    Prism2.languages.markup = {
      "comment": {
        pattern: /<!--(?:(?!<!--)[\s\S])*?-->/,
        greedy: true
      },
      "prolog": {
        pattern: /<\?[\s\S]+?\?>/,
        greedy: true
      },
      "doctype": {
        // https://www.w3.org/TR/xml/#NT-doctypedecl
        pattern: /<!DOCTYPE(?:[^>"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|<!--(?:[^-]|-(?!->))*-->)*\]\s*)?>/i,
        greedy: true,
        inside: {
          "internal-subset": {
            pattern: /(^[^\[]*\[)[\s\S]+(?=\]>$)/,
            lookbehind: true,
            greedy: true,
            inside: null
            // see below
          },
          "string": {
            pattern: /"[^"]*"|'[^']*'/,
            greedy: true
          },
          "punctuation": /^<!|>$|[[\]]/,
          "doctype-tag": /^DOCTYPE/i,
          "name": /[^\s<>'"]+/
        }
      },
      "cdata": {
        pattern: /<!\[CDATA\[[\s\S]*?\]\]>/i,
        greedy: true
      },
      "tag": {
        pattern: /<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,
        greedy: true,
        inside: {
          "tag": {
            pattern: /^<\/?[^\s>\/]+/,
            inside: {
              "punctuation": /^<\/?/,
              "namespace": /^[^\s>\/:]+:/
            }
          },
          "special-attr": [],
          "attr-value": {
            pattern: /=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,
            inside: {
              "punctuation": [
                {
                  pattern: /^=/,
                  alias: "attr-equals"
                },
                {
                  pattern: /^(\s*)["']|["']$/,
                  lookbehind: true
                }
              ]
            }
          },
          "punctuation": /\/?>/,
          "attr-name": {
            pattern: /[^\s>\/]+/,
            inside: {
              "namespace": /^[^\s>\/:]+:/
            }
          }
        }
      },
      "entity": [
        {
          pattern: /&[\da-z]{1,8};/i,
          alias: "named-entity"
        },
        /&#x?[\da-f]{1,8};/i
      ]
    };
    Prism2.languages.markup["tag"].inside["attr-value"].inside["entity"] = Prism2.languages.markup["entity"];
    Prism2.languages.markup["doctype"].inside["internal-subset"].inside = Prism2.languages.markup;
    Prism2.hooks.add("wrap", function(env) {
      if (env.type === "entity") {
        env.attributes["title"] = env.content.replace(/&amp;/, "&");
      }
    });
    Object.defineProperty(Prism2.languages.markup.tag, "addInlined", {
      /**
       * Adds an inlined language to markup.
       *
       * An example of an inlined language is CSS with `<style>` tags.
       *
       * @param {string} tagName The name of the tag that contains the inlined language. This name will be treated as
       * case insensitive.
       * @param {string} lang The language key.
       * @example
       * addInlined('style', 'css');
       */
      value: function addInlined(tagName, lang) {
        var includedCdataInside = {};
        includedCdataInside["language-" + lang] = {
          pattern: /(^<!\[CDATA\[)[\s\S]+?(?=\]\]>$)/i,
          lookbehind: true,
          inside: Prism2.languages[lang]
        };
        includedCdataInside["cdata"] = /^<!\[CDATA\[|\]\]>$/i;
        var inside = {
          "included-cdata": {
            pattern: /<!\[CDATA\[[\s\S]*?\]\]>/i,
            inside: includedCdataInside
          }
        };
        inside["language-" + lang] = {
          pattern: /[\s\S]+/,
          inside: Prism2.languages[lang]
        };
        var def = {};
        def[tagName] = {
          pattern: RegExp(/(<__[^>]*>)(?:<!\[CDATA\[(?:[^\]]|\](?!\]>))*\]\]>|(?!<!\[CDATA\[)[\s\S])*?(?=<\/__>)/.source.replace(/__/g, function() {
            return tagName;
          }), "i"),
          lookbehind: true,
          greedy: true,
          inside
        };
        Prism2.languages.insertBefore("markup", "cdata", def);
      }
    });
    Object.defineProperty(Prism2.languages.markup.tag, "addAttribute", {
      /**
       * Adds an pattern to highlight languages embedded in HTML attributes.
       *
       * An example of an inlined language is CSS with `style` attributes.
       *
       * @param {string} attrName The name of the tag that contains the inlined language. This name will be treated as
       * case insensitive.
       * @param {string} lang The language key.
       * @example
       * addAttribute('style', 'css');
       */
      value: function(attrName, lang) {
        Prism2.languages.markup.tag.inside["special-attr"].push({
          pattern: RegExp(
            /(^|["'\s])/.source + "(?:" + attrName + ")" + /\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))/.source,
            "i"
          ),
          lookbehind: true,
          inside: {
            "attr-name": /^[^\s=]+/,
            "attr-value": {
              pattern: /=[\s\S]+/,
              inside: {
                "value": {
                  pattern: /(^=\s*(["']|(?!["'])))\S[\s\S]*(?=\2$)/,
                  lookbehind: true,
                  alias: [lang, "language-" + lang],
                  inside: Prism2.languages[lang]
                },
                "punctuation": [
                  {
                    pattern: /^=/,
                    alias: "attr-equals"
                  },
                  /"|'/
                ]
              }
            }
          }
        });
      }
    });
    Prism2.languages.html = Prism2.languages.markup;
    Prism2.languages.mathml = Prism2.languages.markup;
    Prism2.languages.svg = Prism2.languages.markup;
    Prism2.languages.xml = Prism2.languages.extend("markup", {});
    Prism2.languages.ssml = Prism2.languages.xml;
    Prism2.languages.atom = Prism2.languages.xml;
    Prism2.languages.rss = Prism2.languages.xml;
    (function(Prism3) {
      var string2 = /(?:"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n])*')/;
      Prism3.languages.css = {
        "comment": /\/\*[\s\S]*?\*\//,
        "atrule": {
          pattern: RegExp("@[\\w-](?:" + /[^;{\s"']|\s+(?!\s)/.source + "|" + string2.source + ")*?" + /(?:;|(?=\s*\{))/.source),
          inside: {
            "rule": /^@[\w-]+/,
            "selector-function-argument": {
              pattern: /(\bselector\s*\(\s*(?![\s)]))(?:[^()\s]|\s+(?![\s)])|\((?:[^()]|\([^()]*\))*\))+(?=\s*\))/,
              lookbehind: true,
              alias: "selector"
            },
            "keyword": {
              pattern: /(^|[^\w-])(?:and|not|only|or)(?![\w-])/,
              lookbehind: true
            }
            // See rest below
          }
        },
        "url": {
          // https://drafts.csswg.org/css-values-3/#urls
          pattern: RegExp("\\burl\\((?:" + string2.source + "|" + /(?:[^\\\r\n()"']|\\[\s\S])*/.source + ")\\)", "i"),
          greedy: true,
          inside: {
            "function": /^url/i,
            "punctuation": /^\(|\)$/,
            "string": {
              pattern: RegExp("^" + string2.source + "$"),
              alias: "url"
            }
          }
        },
        "selector": {
          pattern: RegExp(`(^|[{}\\s])[^{}\\s](?:[^{};"'\\s]|\\s+(?![\\s{])|` + string2.source + ")*(?=\\s*\\{)"),
          lookbehind: true
        },
        "string": {
          pattern: string2,
          greedy: true
        },
        "property": {
          pattern: /(^|[^-\w\xA0-\uFFFF])(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*(?=\s*:)/i,
          lookbehind: true
        },
        "important": /!important\b/i,
        "function": {
          pattern: /(^|[^-a-z0-9])[-a-z0-9]+(?=\()/i,
          lookbehind: true
        },
        "punctuation": /[(){};:,]/
      };
      Prism3.languages.css["atrule"].inside.rest = Prism3.languages.css;
      var markup = Prism3.languages.markup;
      if (markup) {
        markup.tag.addInlined("style", "css");
        markup.tag.addAttribute("style", "css");
      }
    })(Prism2);
    Prism2.languages.clike = {
      "comment": [
        {
          pattern: /(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,
          lookbehind: true,
          greedy: true
        },
        {
          pattern: /(^|[^\\:])\/\/.*/,
          lookbehind: true,
          greedy: true
        }
      ],
      "string": {
        pattern: /(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,
        greedy: true
      },
      "class-name": {
        pattern: /(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+|\bcatch\s+\()[\w.\\]+/i,
        lookbehind: true,
        inside: {
          "punctuation": /[.\\]/
        }
      },
      "keyword": /\b(?:break|catch|continue|do|else|finally|for|function|if|in|instanceof|new|null|return|throw|try|while)\b/,
      "boolean": /\b(?:false|true)\b/,
      "function": /\b\w+(?=\()/,
      "number": /\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,
      "operator": /[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,
      "punctuation": /[{}[\];(),.:]/
    };
    Prism2.languages.javascript = Prism2.languages.extend("clike", {
      "class-name": [
        Prism2.languages.clike["class-name"],
        {
          pattern: /(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,
          lookbehind: true
        }
      ],
      "keyword": [
        {
          pattern: /((?:^|\})\s*)catch\b/,
          lookbehind: true
        },
        {
          pattern: /(^|[^.]|\.\.\.\s*)\b(?:as|assert(?=\s*\{)|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally(?=\s*(?:\{|$))|for|from(?=\s*(?:['"]|$))|function|(?:get|set)(?=\s*(?:[#\[$\w\xA0-\uFFFF]|$))|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,
          lookbehind: true
        }
      ],
      // Allow for all non-ASCII characters (See http://stackoverflow.com/a/2008444)
      "function": /#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,
      "number": {
        pattern: RegExp(
          /(^|[^\w$])/.source + "(?:" + // constant
          (/NaN|Infinity/.source + "|" + // binary integer
          /0[bB][01]+(?:_[01]+)*n?/.source + "|" + // octal integer
          /0[oO][0-7]+(?:_[0-7]+)*n?/.source + "|" + // hexadecimal integer
          /0[xX][\dA-Fa-f]+(?:_[\dA-Fa-f]+)*n?/.source + "|" + // decimal bigint
          /\d+(?:_\d+)*n/.source + "|" + // decimal number (integer or float) but no bigint
          /(?:\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\.\d+(?:_\d+)*)(?:[Ee][+-]?\d+(?:_\d+)*)?/.source) + ")" + /(?![\w$])/.source
        ),
        lookbehind: true
      },
      "operator": /--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/
    });
    Prism2.languages.javascript["class-name"][0].pattern = /(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/;
    Prism2.languages.insertBefore("javascript", "keyword", {
      "regex": {
        pattern: RegExp(
          // lookbehind
          // eslint-disable-next-line regexp/no-dupe-characters-character-class
          /((?:^|[^$\w\xA0-\uFFFF."'\])\s]|\b(?:return|yield))\s*)/.source + // Regex pattern:
          // There are 2 regex patterns here. The RegExp set notation proposal added support for nested character
          // classes if the `v` flag is present. Unfortunately, nested CCs are both context-free and incompatible
          // with the only syntax, so we have to define 2 different regex patterns.
          /\//.source + "(?:" + /(?:\[(?:[^\]\\\r\n]|\\.)*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}/.source + "|" + // `v` flag syntax. This supports 3 levels of nested character classes.
          /(?:\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.)*\])*\])*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}v[dgimyus]{0,7}/.source + ")" + // lookahead
          /(?=(?:\s|\/\*(?:[^*]|\*(?!\/))*\*\/)*(?:$|[\r\n,.;:})\]]|\/\/))/.source
        ),
        lookbehind: true,
        greedy: true,
        inside: {
          "regex-source": {
            pattern: /^(\/)[\s\S]+(?=\/[a-z]*$)/,
            lookbehind: true,
            alias: "language-regex",
            inside: Prism2.languages.regex
          },
          "regex-delimiter": /^\/|\/$/,
          "regex-flags": /^[a-z]+$/
        }
      },
      // This must be declared before keyword because we use "function" inside the look-forward
      "function-variable": {
        pattern: /#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/,
        alias: "function"
      },
      "parameter": [
        {
          pattern: /(function(?:\s+(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)?\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\))/,
          lookbehind: true,
          inside: Prism2.languages.javascript
        },
        {
          pattern: /(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,
          lookbehind: true,
          inside: Prism2.languages.javascript
        },
        {
          pattern: /(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,
          lookbehind: true,
          inside: Prism2.languages.javascript
        },
        {
          pattern: /((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*)\(\s*|\]\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*\{)/,
          lookbehind: true,
          inside: Prism2.languages.javascript
        }
      ],
      "constant": /\b[A-Z](?:[A-Z_]|\dx?)*\b/
    });
    Prism2.languages.insertBefore("javascript", "string", {
      "hashbang": {
        pattern: /^#!.*/,
        greedy: true,
        alias: "comment"
      },
      "template-string": {
        pattern: /`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,
        greedy: true,
        inside: {
          "template-punctuation": {
            pattern: /^`|`$/,
            alias: "string"
          },
          "interpolation": {
            pattern: /((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,
            lookbehind: true,
            inside: {
              "interpolation-punctuation": {
                pattern: /^\$\{|\}$/,
                alias: "punctuation"
              },
              rest: Prism2.languages.javascript
            }
          },
          "string": /[\s\S]+/
        }
      },
      "string-property": {
        pattern: /((?:^|[,{])[ \t]*)(["'])(?:\\(?:\r\n|[\s\S])|(?!\2)[^\\\r\n])*\2(?=\s*:)/m,
        lookbehind: true,
        greedy: true,
        alias: "property"
      }
    });
    Prism2.languages.insertBefore("javascript", "operator", {
      "literal-property": {
        pattern: /((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,
        lookbehind: true,
        alias: "property"
      }
    });
    if (Prism2.languages.markup) {
      Prism2.languages.markup.tag.addInlined("script", "javascript");
      Prism2.languages.markup.tag.addAttribute(
        /on(?:abort|blur|change|click|composition(?:end|start|update)|dblclick|error|focus(?:in|out)?|key(?:down|up)|load|mouse(?:down|enter|leave|move|out|over|up)|reset|resize|scroll|select|slotchange|submit|unload|wheel)/.source,
        "javascript"
      );
    }
    Prism2.languages.js = Prism2.languages.javascript;
    (function() {
      if (typeof Prism2 === "undefined" || typeof document === "undefined") {
        return;
      }
      if (!Element.prototype.matches) {
        Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
      }
      var LOADING_MESSAGE = "Loading…";
      var FAILURE_MESSAGE = function(status, message2) {
        return "✖ Error " + status + " while fetching file: " + message2;
      };
      var FAILURE_EMPTY_MESSAGE = "✖ Error: File does not exist or is empty";
      var EXTENSIONS = {
        "js": "javascript",
        "py": "python",
        "rb": "ruby",
        "ps1": "powershell",
        "psm1": "powershell",
        "sh": "bash",
        "bat": "batch",
        "h": "c",
        "tex": "latex"
      };
      var STATUS_ATTR = "data-src-status";
      var STATUS_LOADING = "loading";
      var STATUS_LOADED = "loaded";
      var STATUS_FAILED = "failed";
      var SELECTOR = "pre[data-src]:not([" + STATUS_ATTR + '="' + STATUS_LOADED + '"]):not([' + STATUS_ATTR + '="' + STATUS_LOADING + '"])';
      function loadFile(src, success, error2) {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", src, true);
        xhr.onreadystatechange = function() {
          if (xhr.readyState == 4) {
            if (xhr.status < 400 && xhr.responseText) {
              success(xhr.responseText);
            } else {
              if (xhr.status >= 400) {
                error2(FAILURE_MESSAGE(xhr.status, xhr.statusText));
              } else {
                error2(FAILURE_EMPTY_MESSAGE);
              }
            }
          }
        };
        xhr.send(null);
      }
      function parseRange(range) {
        var m = /^\s*(\d+)\s*(?:(,)\s*(?:(\d+)\s*)?)?$/.exec(range || "");
        if (m) {
          var start2 = Number(m[1]);
          var comma = m[2];
          var end2 = m[3];
          if (!comma) {
            return [start2, start2];
          }
          if (!end2) {
            return [start2, void 0];
          }
          return [start2, Number(end2)];
        }
        return void 0;
      }
      Prism2.hooks.add("before-highlightall", function(env) {
        env.selector += ", " + SELECTOR;
      });
      Prism2.hooks.add("before-sanity-check", function(env) {
        var pre2 = (
          /** @type {HTMLPreElement} */
          env.element
        );
        if (pre2.matches(SELECTOR)) {
          env.code = "";
          pre2.setAttribute(STATUS_ATTR, STATUS_LOADING);
          var code2 = pre2.appendChild(document.createElement("CODE"));
          code2.textContent = LOADING_MESSAGE;
          var src = pre2.getAttribute("data-src");
          var language = env.language;
          if (language === "none") {
            var extension = (/\.(\w+)$/.exec(src) || [, "none"])[1];
            language = EXTENSIONS[extension] || extension;
          }
          Prism2.util.setLanguage(code2, language);
          Prism2.util.setLanguage(pre2, language);
          var autoloader = Prism2.plugins.autoloader;
          if (autoloader) {
            autoloader.loadLanguages(language);
          }
          loadFile(
            src,
            function(text2) {
              pre2.setAttribute(STATUS_ATTR, STATUS_LOADED);
              var range = parseRange(pre2.getAttribute("data-range"));
              if (range) {
                var lines = text2.split(/\r\n?|\n/g);
                var start2 = range[0];
                var end2 = range[1] == null ? lines.length : range[1];
                if (start2 < 0) {
                  start2 += lines.length;
                }
                start2 = Math.max(0, Math.min(start2 - 1, lines.length));
                if (end2 < 0) {
                  end2 += lines.length;
                }
                end2 = Math.max(0, Math.min(end2, lines.length));
                text2 = lines.slice(start2, end2).join("\n");
                if (!pre2.hasAttribute("data-start")) {
                  pre2.setAttribute("data-start", String(start2 + 1));
                }
              }
              code2.textContent = text2;
              Prism2.highlightElement(code2);
            },
            function(error2) {
              pre2.setAttribute(STATUS_ATTR, STATUS_FAILED);
              code2.textContent = error2;
            }
          );
        }
      });
      Prism2.plugins.fileHighlight = {
        /**
         * Executes the File Highlight plugin for all matching `pre` elements under the given container.
         *
         * Note: Elements which are already loaded or currently loading will not be touched by this method.
         *
         * @param {ParentNode} [container=document]
         */
        highlight: function highlight2(container2) {
          var elements = (container2 || document).querySelectorAll(SELECTOR);
          for (var i2 = 0, element; element = elements[i2++]; ) {
            Prism2.highlightElement(element);
          }
        }
      };
      var logged = false;
      Prism2.fileHighlight = function() {
        if (!logged) {
          console.warn("Prism.fileHighlight is deprecated. Use `Prism.plugins.fileHighlight.highlight` instead.");
          logged = true;
        }
        Prism2.plugins.fileHighlight.highlight.apply(this, arguments);
      };
    })();
  })(prism);
  return prism.exports;
}
var prismExports = requirePrism();
const kPrismRenderMaxSize = 25e4;
const usePrismHighlight = (containerRef, contentLength) => {
  reactExports.useEffect(() => {
    requestAnimationFrame(() => {
      if (contentLength > 0 && containerRef.current !== null && contentLength <= kPrismRenderMaxSize) {
        const codeBlocks = containerRef.current.querySelectorAll("pre code");
        codeBlocks.forEach((block2) => {
          if (block2.className.includes("language-")) {
            block2.classList.add("sourceCode");
            prismExports.highlightElement(block2);
          }
        });
      }
    });
  }, [contentLength, containerRef]);
};
const kMaxStringValueDisplay = 1048576;
const JSONPanel = ({
  id: id2,
  json: json2,
  data: data2,
  simple: simple2 = false,
  style: style2,
  className: className2
}) => {
  const sourceCode = reactExports.useMemo(() => {
    return json2 || data2 ? JSON.stringify(resolveBase64(data2), void 0, 2) : "";
  }, [json2, data2]);
  const sourceCodeRef = reactExports.useRef(null);
  usePrismHighlight(sourceCodeRef, sourceCode.length);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { ref: sourceCodeRef, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "pre",
    {
      className: clsx("json-panel", simple2 ? "simple" : "", className2),
      style: style2,
      children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("code", { id: id2, className: clsx("source-code", "language-javascript"), children: sourceCode }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/JsonPanel.tsx",
        lineNumber: 43,
        columnNumber: 9
      }, void 0)
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/JsonPanel.tsx",
      lineNumber: 39,
      columnNumber: 7
    },
    void 0
  ) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/JsonPanel.tsx",
    lineNumber: 38,
    columnNumber: 5
  }, void 0);
};
const resolveBase64 = (value2) => {
  const prefix = "data:image";
  if (Array.isArray(value2)) {
    return value2.map((v) => resolveBase64(v));
  }
  if (value2 && typeof value2 === "object") {
    const resolvedObject = {};
    for (const key2 of Object.keys(value2)) {
      const record = value2;
      resolvedObject[key2] = resolveBase64(record[key2]);
    }
    return resolvedObject;
  }
  if (typeof value2 === "string") {
    let resolvedValue = value2;
    if (resolvedValue.startsWith(prefix)) {
      resolvedValue = "[base64 image]";
    } else if (resolvedValue.length > kMaxStringValueDisplay) {
      resolvedValue = "[long data]";
    } else if (maybeBase64(resolvedValue)) {
      resolvedValue = "[base64 data]";
    }
    return resolvedValue;
  }
  return value2;
};
const getEnabledNamespaces = () => {
  return "*".split(",").map((ns) => ns.trim()).filter(Boolean);
};
new Set(getEnabledNamespaces());
const createLogger = (namespace) => {
  const logger = {
    debug: (message2, ...args2) => {
    },
    info: (message2, ...args2) => {
    },
    warn: (message2, ...args2) => {
    },
    // Always log errors, even in production
    error: (message2, ...args2) => {
      console.error(`[${namespace}] ${message2}`, ...args2);
    },
    // Lazy evaluation for expensive logs
    debugIf: (fn3) => {
    }
  };
  return logger;
};
function debounce$2(func2, wait, options = {}) {
  let timeout = null;
  let args2;
  let result2;
  let lastCallTime = null;
  const later = () => {
    const last2 = Date.now() - (lastCallTime || 0);
    if (last2 < wait && last2 >= 0) {
      timeout = setTimeout(later, wait - last2);
    } else {
      timeout = null;
      if (!options.leading) {
        result2 = func2(...args2);
        if (!timeout) {
          args2 = null;
        }
      }
    }
  };
  const debounced = (...callArgs) => {
    args2 = callArgs;
    lastCallTime = Date.now();
    const callNow = options.leading && !timeout;
    if (!timeout) {
      timeout = setTimeout(later, wait);
    }
    if (callNow) {
      result2 = func2(...args2);
      args2 = null;
    }
    return result2;
  };
  return debounced;
}
const createStoreImpl = (createState) => {
  let state;
  const listeners = /* @__PURE__ */ new Set();
  const setState2 = (partial, replace2) => {
    const nextState = typeof partial === "function" ? partial(state) : partial;
    if (!Object.is(nextState, state)) {
      const previousState = state;
      state = (replace2 != null ? replace2 : typeof nextState !== "object" || nextState === null) ? nextState : Object.assign({}, state, nextState);
      listeners.forEach((listener) => listener(state, previousState));
    }
  };
  const getState2 = () => state;
  const getInitialState = () => initialState;
  const subscribe = (listener) => {
    listeners.add(listener);
    return () => listeners.delete(listener);
  };
  const api2 = { setState: setState2, getState: getState2, getInitialState, subscribe };
  const initialState = state = createState(setState2, getState2, api2);
  return api2;
};
const createStore$2 = ((createState) => createState ? createStoreImpl(createState) : createStoreImpl);
const identity$2 = (arg) => arg;
function useStore$1(api2, selector = identity$2) {
  const slice2 = React20.useSyncExternalStore(
    api2.subscribe,
    React20.useCallback(() => selector(api2.getState()), [api2, selector]),
    React20.useCallback(() => selector(api2.getInitialState()), [api2, selector])
  );
  React20.useDebugValue(slice2);
  return slice2;
}
const createImpl = (createState) => {
  const api2 = createStore$2(createState);
  const useBoundStore = (selector) => useStore$1(api2, selector);
  Object.assign(useBoundStore, api2);
  return useBoundStore;
};
const create$2 = ((createState) => createImpl);
const __vite_import_meta_env__ = { "BASE_URL": "./", "DEV": true, "MODE": "development", "PROD": false, "SSR": false };
const trackedConnections = /* @__PURE__ */ new Map();
const getTrackedConnectionState = (name2) => {
  const api2 = trackedConnections.get(name2);
  if (!api2) return {};
  return Object.fromEntries(
    Object.entries(api2.stores).map(([key2, api22]) => [key2, api22.getState()])
  );
};
const extractConnectionInformation = (store2, extensionConnector, options) => {
  if (store2 === void 0) {
    return {
      type: "untracked",
      connection: extensionConnector.connect(options)
    };
  }
  const existingConnection = trackedConnections.get(options.name);
  if (existingConnection) {
    return { type: "tracked", store: store2, ...existingConnection };
  }
  const newConnection = {
    connection: extensionConnector.connect(options),
    stores: {}
  };
  trackedConnections.set(options.name, newConnection);
  return { type: "tracked", store: store2, ...newConnection };
};
const removeStoreFromTrackedConnections = (name2, store2) => {
  if (store2 === void 0) return;
  const connectionInfo = trackedConnections.get(name2);
  if (!connectionInfo) return;
  delete connectionInfo.stores[store2];
  if (Object.keys(connectionInfo.stores).length === 0) {
    trackedConnections.delete(name2);
  }
};
const findCallerName = (stack2) => {
  var _a2, _b2;
  if (!stack2) return void 0;
  const traceLines = stack2.split("\n");
  const apiSetStateLineIndex = traceLines.findIndex(
    (traceLine) => traceLine.includes("api.setState")
  );
  if (apiSetStateLineIndex < 0) return void 0;
  const callerLine = ((_a2 = traceLines[apiSetStateLineIndex + 1]) == null ? void 0 : _a2.trim()) || "";
  return (_b2 = /.+ (.+) .+/.exec(callerLine)) == null ? void 0 : _b2[1];
};
const devtoolsImpl = (fn3, devtoolsOptions = {}) => (set3, get2, api2) => {
  const { enabled, anonymousActionType, store: store2, ...options } = devtoolsOptions;
  let extensionConnector;
  try {
    extensionConnector = (enabled != null ? enabled : (__vite_import_meta_env__ ? "development" : void 0) !== "production") && window.__REDUX_DEVTOOLS_EXTENSION__;
  } catch (e) {
  }
  if (!extensionConnector) {
    return fn3(set3, get2, api2);
  }
  const { connection, ...connectionInformation } = extractConnectionInformation(store2, extensionConnector, options);
  let isRecording = true;
  api2.setState = ((state, replace2, nameOrAction) => {
    const r2 = set3(state, replace2);
    if (!isRecording) return r2;
    const action = nameOrAction === void 0 ? {
      type: anonymousActionType || findCallerName(new Error().stack) || "anonymous"
    } : typeof nameOrAction === "string" ? { type: nameOrAction } : nameOrAction;
    if (store2 === void 0) {
      connection == null ? void 0 : connection.send(action, get2());
      return r2;
    }
    connection == null ? void 0 : connection.send(
      {
        ...action,
        type: `${store2}/${action.type}`
      },
      {
        ...getTrackedConnectionState(options.name),
        [store2]: api2.getState()
      }
    );
    return r2;
  });
  api2.devtools = {
    cleanup: () => {
      if (connection && typeof connection.unsubscribe === "function") {
        connection.unsubscribe();
      }
      removeStoreFromTrackedConnections(options.name, store2);
    }
  };
  const setStateFromDevtools = (...a2) => {
    const originalIsRecording = isRecording;
    isRecording = false;
    set3(...a2);
    isRecording = originalIsRecording;
  };
  const initialState = fn3(api2.setState, get2, api2);
  if (connectionInformation.type === "untracked") {
    connection == null ? void 0 : connection.init(initialState);
  } else {
    connectionInformation.stores[connectionInformation.store] = api2;
    connection == null ? void 0 : connection.init(
      Object.fromEntries(
        Object.entries(connectionInformation.stores).map(([key2, store22]) => [
          key2,
          key2 === connectionInformation.store ? initialState : store22.getState()
        ])
      )
    );
  }
  if (api2.dispatchFromDevtools && typeof api2.dispatch === "function") {
    let didWarnAboutReservedActionType = false;
    const originalDispatch = api2.dispatch;
    api2.dispatch = (...args2) => {
      if ((__vite_import_meta_env__ ? "development" : void 0) !== "production" && args2[0].type === "__setState" && !didWarnAboutReservedActionType) {
        console.warn(
          '[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'
        );
        didWarnAboutReservedActionType = true;
      }
      originalDispatch(...args2);
    };
  }
  connection.subscribe((message2) => {
    var _a2;
    switch (message2.type) {
      case "ACTION":
        if (typeof message2.payload !== "string") {
          console.error(
            "[zustand devtools middleware] Unsupported action format"
          );
          return;
        }
        return parseJsonThen(
          message2.payload,
          (action) => {
            if (action.type === "__setState") {
              if (store2 === void 0) {
                setStateFromDevtools(action.state);
                return;
              }
              if (Object.keys(action.state).length !== 1) {
                console.error(
                  `
                    [zustand devtools middleware] Unsupported __setState action format.
                    When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),
                    and value of this only key should be a state object. Example: { "type": "__setState", "state": { "abc123Store": { "foo": "bar" } } }
                    `
                );
              }
              const stateFromDevtools = action.state[store2];
              if (stateFromDevtools === void 0 || stateFromDevtools === null) {
                return;
              }
              if (JSON.stringify(api2.getState()) !== JSON.stringify(stateFromDevtools)) {
                setStateFromDevtools(stateFromDevtools);
              }
              return;
            }
            if (!api2.dispatchFromDevtools) return;
            if (typeof api2.dispatch !== "function") return;
            api2.dispatch(action);
          }
        );
      case "DISPATCH":
        switch (message2.payload.type) {
          case "RESET":
            setStateFromDevtools(initialState);
            if (store2 === void 0) {
              return connection == null ? void 0 : connection.init(api2.getState());
            }
            return connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));
          case "COMMIT":
            if (store2 === void 0) {
              connection == null ? void 0 : connection.init(api2.getState());
              return;
            }
            return connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));
          case "ROLLBACK":
            return parseJsonThen(message2.state, (state) => {
              if (store2 === void 0) {
                setStateFromDevtools(state);
                connection == null ? void 0 : connection.init(api2.getState());
                return;
              }
              setStateFromDevtools(state[store2]);
              connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));
            });
          case "JUMP_TO_STATE":
          case "JUMP_TO_ACTION":
            return parseJsonThen(message2.state, (state) => {
              if (store2 === void 0) {
                setStateFromDevtools(state);
                return;
              }
              if (JSON.stringify(api2.getState()) !== JSON.stringify(state[store2])) {
                setStateFromDevtools(state[store2]);
              }
            });
          case "IMPORT_STATE": {
            const { nextLiftedState } = message2.payload;
            const lastComputedState = (_a2 = nextLiftedState.computedStates.slice(-1)[0]) == null ? void 0 : _a2.state;
            if (!lastComputedState) return;
            if (store2 === void 0) {
              setStateFromDevtools(lastComputedState);
            } else {
              setStateFromDevtools(lastComputedState[store2]);
            }
            connection == null ? void 0 : connection.send(
              null,
              // FIXME no-any
              nextLiftedState
            );
            return;
          }
          case "PAUSE_RECORDING":
            return isRecording = !isRecording;
        }
        return;
    }
  });
  return initialState;
};
const devtools = devtoolsImpl;
const parseJsonThen = (stringified, fn3) => {
  let parsed;
  try {
    parsed = JSON.parse(stringified);
  } catch (e) {
    console.error(
      "[zustand devtools middleware] Could not parse the received json",
      e
    );
  }
  if (parsed !== void 0) fn3(parsed);
};
function createJSONStorage(getStorage, options) {
  let storage;
  try {
    storage = getStorage();
  } catch (e) {
    return;
  }
  const persistStorage = {
    getItem: (name2) => {
      var _a2;
      const parse5 = (str2) => {
        if (str2 === null) {
          return null;
        }
        return JSON.parse(str2, void 0);
      };
      const str = (_a2 = storage.getItem(name2)) != null ? _a2 : null;
      if (str instanceof Promise) {
        return str.then(parse5);
      }
      return parse5(str);
    },
    setItem: (name2, newValue) => storage.setItem(name2, JSON.stringify(newValue, void 0)),
    removeItem: (name2) => storage.removeItem(name2)
  };
  return persistStorage;
}
const toThenable = (fn3) => (input2) => {
  try {
    const result2 = fn3(input2);
    if (result2 instanceof Promise) {
      return result2;
    }
    return {
      then(onFulfilled) {
        return toThenable(onFulfilled)(result2);
      },
      catch(_onRejected) {
        return this;
      }
    };
  } catch (e) {
    return {
      then(_onFulfilled) {
        return this;
      },
      catch(onRejected) {
        return toThenable(onRejected)(e);
      }
    };
  }
};
const persistImpl = (config2, baseOptions) => (set3, get2, api2) => {
  let options = {
    storage: createJSONStorage(() => localStorage),
    partialize: (state) => state,
    version: 0,
    merge: (persistedState, currentState) => ({
      ...currentState,
      ...persistedState
    }),
    ...baseOptions
  };
  let hasHydrated = false;
  const hydrationListeners = /* @__PURE__ */ new Set();
  const finishHydrationListeners = /* @__PURE__ */ new Set();
  let storage = options.storage;
  if (!storage) {
    return config2(
      (...args2) => {
        console.warn(
          `[zustand persist middleware] Unable to update item '${options.name}', the given storage is currently unavailable.`
        );
        set3(...args2);
      },
      get2,
      api2
    );
  }
  const setItem = () => {
    const state = options.partialize({ ...get2() });
    return storage.setItem(options.name, {
      state,
      version: options.version
    });
  };
  const savedSetState = api2.setState;
  api2.setState = (state, replace2) => {
    savedSetState(state, replace2);
    return setItem();
  };
  const configResult = config2(
    (...args2) => {
      set3(...args2);
      return setItem();
    },
    get2,
    api2
  );
  api2.getInitialState = () => configResult;
  let stateFromStorage;
  const hydrate = () => {
    var _a2, _b2;
    if (!storage) return;
    hasHydrated = false;
    hydrationListeners.forEach((cb) => {
      var _a22;
      return cb((_a22 = get2()) != null ? _a22 : configResult);
    });
    const postRehydrationCallback = ((_b2 = options.onRehydrateStorage) == null ? void 0 : _b2.call(options, (_a2 = get2()) != null ? _a2 : configResult)) || void 0;
    return toThenable(storage.getItem.bind(storage))(options.name).then((deserializedStorageValue) => {
      if (deserializedStorageValue) {
        if (typeof deserializedStorageValue.version === "number" && deserializedStorageValue.version !== options.version) {
          if (options.migrate) {
            const migration = options.migrate(
              deserializedStorageValue.state,
              deserializedStorageValue.version
            );
            if (migration instanceof Promise) {
              return migration.then((result2) => [true, result2]);
            }
            return [true, migration];
          }
          console.error(
            `State loaded from storage couldn't be migrated since no migrate function was provided`
          );
        } else {
          return [false, deserializedStorageValue.state];
        }
      }
      return [false, void 0];
    }).then((migrationResult) => {
      var _a22;
      const [migrated, migratedState] = migrationResult;
      stateFromStorage = options.merge(
        migratedState,
        (_a22 = get2()) != null ? _a22 : configResult
      );
      set3(stateFromStorage, true);
      if (migrated) {
        return setItem();
      }
    }).then(() => {
      postRehydrationCallback == null ? void 0 : postRehydrationCallback(stateFromStorage, void 0);
      stateFromStorage = get2();
      hasHydrated = true;
      finishHydrationListeners.forEach((cb) => cb(stateFromStorage));
    }).catch((e) => {
      postRehydrationCallback == null ? void 0 : postRehydrationCallback(void 0, e);
    });
  };
  api2.persist = {
    setOptions: (newOptions) => {
      options = {
        ...options,
        ...newOptions
      };
      if (newOptions.storage) {
        storage = newOptions.storage;
      }
    },
    clearStorage: () => {
      storage == null ? void 0 : storage.removeItem(options.name);
    },
    getOptions: () => options,
    rehydrate: () => hydrate(),
    hasHydrated: () => hasHydrated,
    onHydrate: (cb) => {
      hydrationListeners.add(cb);
      return () => {
        hydrationListeners.delete(cb);
      };
    },
    onFinishHydration: (cb) => {
      finishHydrationListeners.add(cb);
      return () => {
        finishHydrationListeners.delete(cb);
      };
    }
  };
  if (!options.skipHydration) {
    hydrate();
  }
  return stateFromStorage || configResult;
};
const persist = persistImpl;
var NOTHING = Symbol.for("immer-nothing");
var DRAFTABLE = Symbol.for("immer-draftable");
var DRAFT_STATE = Symbol.for("immer-state");
var errors$1 = [
  // All error codes, starting by 0:
  function(plugin) {
    return `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \`enable${plugin}()\` when initializing your application.`;
  },
  function(thing) {
    return `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`;
  },
  "This object has been frozen and should not be mutated",
  function(data2) {
    return "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " + data2;
  },
  "An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.",
  "Immer forbids circular references",
  "The first or second argument to `produce` must be a function",
  "The third argument to `produce` must be a function or undefined",
  "First argument to `createDraft` must be a plain object, an array, or an immerable object",
  "First argument to `finishDraft` must be a draft returned by `createDraft`",
  function(thing) {
    return `'current' expects a draft, got: ${thing}`;
  },
  "Object.defineProperty() cannot be used on an Immer draft",
  "Object.setPrototypeOf() cannot be used on an Immer draft",
  "Immer only supports deleting array indices",
  "Immer only supports setting array indices and the 'length' property",
  function(thing) {
    return `'original' expects a draft, got: ${thing}`;
  }
  // Note: if more errors are added, the errorOffset in Patches.ts should be increased
  // See Patches.ts for additional errors
];
function die(error2, ...args2) {
  {
    const e = errors$1[error2];
    const msg = typeof e === "function" ? e.apply(null, args2) : e;
    throw new Error(`[Immer] ${msg}`);
  }
}
var getPrototypeOf = Object.getPrototypeOf;
function isDraft(value2) {
  return !!value2 && !!value2[DRAFT_STATE];
}
function isDraftable(value2) {
  if (!value2)
    return false;
  return isPlainObject(value2) || Array.isArray(value2) || !!value2[DRAFTABLE] || !!value2.constructor?.[DRAFTABLE] || isMap$1(value2) || isSet$1(value2);
}
var objectCtorString = Object.prototype.constructor.toString();
var cachedCtorStrings = /* @__PURE__ */ new WeakMap();
function isPlainObject(value2) {
  if (!value2 || typeof value2 !== "object")
    return false;
  const proto = Object.getPrototypeOf(value2);
  if (proto === null || proto === Object.prototype)
    return true;
  const Ctor = Object.hasOwnProperty.call(proto, "constructor") && proto.constructor;
  if (Ctor === Object)
    return true;
  if (typeof Ctor !== "function")
    return false;
  let ctorString = cachedCtorStrings.get(Ctor);
  if (ctorString === void 0) {
    ctorString = Function.toString.call(Ctor);
    cachedCtorStrings.set(Ctor, ctorString);
  }
  return ctorString === objectCtorString;
}
function each(obj, iter, strict = true) {
  if (getArchtype(obj) === 0) {
    const keys2 = strict ? Reflect.ownKeys(obj) : Object.keys(obj);
    keys2.forEach((key2) => {
      iter(key2, obj[key2], obj);
    });
  } else {
    obj.forEach((entry2, index) => iter(index, entry2, obj));
  }
}
function getArchtype(thing) {
  const state = thing[DRAFT_STATE];
  return state ? state.type_ : Array.isArray(thing) ? 1 : isMap$1(thing) ? 2 : isSet$1(thing) ? 3 : 0;
}
function has$2(thing, prop) {
  return getArchtype(thing) === 2 ? thing.has(prop) : Object.prototype.hasOwnProperty.call(thing, prop);
}
function set(thing, propOrOldValue, value2) {
  const t2 = getArchtype(thing);
  if (t2 === 2)
    thing.set(propOrOldValue, value2);
  else if (t2 === 3) {
    thing.add(value2);
  } else
    thing[propOrOldValue] = value2;
}
function is$1(x, y) {
  if (x === y) {
    return x !== 0 || 1 / x === 1 / y;
  } else {
    return x !== x && y !== y;
  }
}
function isMap$1(target) {
  return target instanceof Map;
}
function isSet$1(target) {
  return target instanceof Set;
}
function latest(state) {
  return state.copy_ || state.base_;
}
function shallowCopy(base2, strict) {
  if (isMap$1(base2)) {
    return new Map(base2);
  }
  if (isSet$1(base2)) {
    return new Set(base2);
  }
  if (Array.isArray(base2))
    return Array.prototype.slice.call(base2);
  const isPlain = isPlainObject(base2);
  if (strict === true || strict === "class_only" && !isPlain) {
    const descriptors = Object.getOwnPropertyDescriptors(base2);
    delete descriptors[DRAFT_STATE];
    let keys2 = Reflect.ownKeys(descriptors);
    for (let i2 = 0; i2 < keys2.length; i2++) {
      const key2 = keys2[i2];
      const desc = descriptors[key2];
      if (desc.writable === false) {
        desc.writable = true;
        desc.configurable = true;
      }
      if (desc.get || desc.set)
        descriptors[key2] = {
          configurable: true,
          writable: true,
          // could live with !!desc.set as well here...
          enumerable: desc.enumerable,
          value: base2[key2]
        };
    }
    return Object.create(getPrototypeOf(base2), descriptors);
  } else {
    const proto = getPrototypeOf(base2);
    if (proto !== null && isPlain) {
      return { ...base2 };
    }
    const obj = Object.create(proto);
    return Object.assign(obj, base2);
  }
}
function freeze(obj, deep = false) {
  if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj))
    return obj;
  if (getArchtype(obj) > 1) {
    Object.defineProperties(obj, {
      set: dontMutateMethodOverride,
      add: dontMutateMethodOverride,
      clear: dontMutateMethodOverride,
      delete: dontMutateMethodOverride
    });
  }
  Object.freeze(obj);
  if (deep)
    Object.values(obj).forEach((value2) => freeze(value2, true));
  return obj;
}
function dontMutateFrozenCollections() {
  die(2);
}
var dontMutateMethodOverride = {
  value: dontMutateFrozenCollections
};
function isFrozen(obj) {
  if (obj === null || typeof obj !== "object")
    return true;
  return Object.isFrozen(obj);
}
var plugins = {};
function getPlugin(pluginKey) {
  const plugin = plugins[pluginKey];
  if (!plugin) {
    die(0, pluginKey);
  }
  return plugin;
}
var currentScope;
function getCurrentScope() {
  return currentScope;
}
function createScope(parent_, immer_) {
  return {
    drafts_: [],
    parent_,
    immer_,
    // Whenever the modified draft contains a draft from another scope, we
    // need to prevent auto-freezing so the unowned draft can be finalized.
    canAutoFreeze_: true,
    unfinalizedDrafts_: 0
  };
}
function usePatchesInScope(scope, patchListener) {
  if (patchListener) {
    getPlugin("Patches");
    scope.patches_ = [];
    scope.inversePatches_ = [];
    scope.patchListener_ = patchListener;
  }
}
function revokeScope(scope) {
  leaveScope(scope);
  scope.drafts_.forEach(revokeDraft);
  scope.drafts_ = null;
}
function leaveScope(scope) {
  if (scope === currentScope) {
    currentScope = scope.parent_;
  }
}
function enterScope(immer2) {
  return currentScope = createScope(currentScope, immer2);
}
function revokeDraft(draft) {
  const state = draft[DRAFT_STATE];
  if (state.type_ === 0 || state.type_ === 1)
    state.revoke_();
  else
    state.revoked_ = true;
}
function processResult(result2, scope) {
  scope.unfinalizedDrafts_ = scope.drafts_.length;
  const baseDraft = scope.drafts_[0];
  const isReplaced = result2 !== void 0 && result2 !== baseDraft;
  if (isReplaced) {
    if (baseDraft[DRAFT_STATE].modified_) {
      revokeScope(scope);
      die(4);
    }
    if (isDraftable(result2)) {
      result2 = finalize(scope, result2);
      if (!scope.parent_)
        maybeFreeze(scope, result2);
    }
    if (scope.patches_) {
      getPlugin("Patches").generateReplacementPatches_(
        baseDraft[DRAFT_STATE].base_,
        result2,
        scope.patches_,
        scope.inversePatches_
      );
    }
  } else {
    result2 = finalize(scope, baseDraft, []);
  }
  revokeScope(scope);
  if (scope.patches_) {
    scope.patchListener_(scope.patches_, scope.inversePatches_);
  }
  return result2 !== NOTHING ? result2 : void 0;
}
function finalize(rootScope, value2, path) {
  if (isFrozen(value2))
    return value2;
  const useStrictIteration = rootScope.immer_.shouldUseStrictIteration();
  const state = value2[DRAFT_STATE];
  if (!state) {
    each(
      value2,
      (key2, childValue) => finalizeProperty(rootScope, state, value2, key2, childValue, path),
      useStrictIteration
    );
    return value2;
  }
  if (state.scope_ !== rootScope)
    return value2;
  if (!state.modified_) {
    maybeFreeze(rootScope, state.base_, true);
    return state.base_;
  }
  if (!state.finalized_) {
    state.finalized_ = true;
    state.scope_.unfinalizedDrafts_--;
    const result2 = state.copy_;
    let resultEach = result2;
    let isSet2 = false;
    if (state.type_ === 3) {
      resultEach = new Set(result2);
      result2.clear();
      isSet2 = true;
    }
    each(
      resultEach,
      (key2, childValue) => finalizeProperty(
        rootScope,
        state,
        result2,
        key2,
        childValue,
        path,
        isSet2
      ),
      useStrictIteration
    );
    maybeFreeze(rootScope, result2, false);
    if (path && rootScope.patches_) {
      getPlugin("Patches").generatePatches_(
        state,
        path,
        rootScope.patches_,
        rootScope.inversePatches_
      );
    }
  }
  return state.copy_;
}
function finalizeProperty(rootScope, parentState, targetObject, prop, childValue, rootPath, targetIsSet) {
  if (childValue == null) {
    return;
  }
  if (typeof childValue !== "object" && !targetIsSet) {
    return;
  }
  const childIsFrozen = isFrozen(childValue);
  if (childIsFrozen && !targetIsSet) {
    return;
  }
  if (childValue === targetObject)
    die(5);
  if (isDraft(childValue)) {
    const path = rootPath && parentState && parentState.type_ !== 3 && // Set objects are atomic since they have no keys.
    !has$2(parentState.assigned_, prop) ? rootPath.concat(prop) : void 0;
    const res = finalize(rootScope, childValue, path);
    set(targetObject, prop, res);
    if (isDraft(res)) {
      rootScope.canAutoFreeze_ = false;
    } else
      return;
  } else if (targetIsSet) {
    targetObject.add(childValue);
  }
  if (isDraftable(childValue) && !childIsFrozen) {
    if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {
      return;
    }
    if (parentState && parentState.base_ && parentState.base_[prop] === childValue && childIsFrozen) {
      return;
    }
    finalize(rootScope, childValue);
    if ((!parentState || !parentState.scope_.parent_) && typeof prop !== "symbol" && (isMap$1(targetObject) ? targetObject.has(prop) : Object.prototype.propertyIsEnumerable.call(targetObject, prop)))
      maybeFreeze(rootScope, childValue);
  }
}
function maybeFreeze(scope, value2, deep = false) {
  if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {
    freeze(value2, deep);
  }
}
function createProxyProxy(base2, parent) {
  const isArray2 = Array.isArray(base2);
  const state = {
    type_: isArray2 ? 1 : 0,
    // Track which produce call this is associated with.
    scope_: parent ? parent.scope_ : getCurrentScope(),
    // True for both shallow and deep changes.
    modified_: false,
    // Used during finalization.
    finalized_: false,
    // Track which properties have been assigned (true) or deleted (false).
    assigned_: {},
    // The parent draft state.
    parent_: parent,
    // The base state.
    base_: base2,
    // The base proxy.
    draft_: null,
    // set below
    // The base copy with any updated values.
    copy_: null,
    // Called by the `produce` function.
    revoke_: null,
    isManual_: false
  };
  let target = state;
  let traps = objectTraps;
  if (isArray2) {
    target = [state];
    traps = arrayTraps;
  }
  const { revoke, proxy } = Proxy.revocable(target, traps);
  state.draft_ = proxy;
  state.revoke_ = revoke;
  return proxy;
}
var objectTraps = {
  get(state, prop) {
    if (prop === DRAFT_STATE)
      return state;
    const source2 = latest(state);
    if (!has$2(source2, prop)) {
      return readPropFromProto(state, source2, prop);
    }
    const value2 = source2[prop];
    if (state.finalized_ || !isDraftable(value2)) {
      return value2;
    }
    if (value2 === peek(state.base_, prop)) {
      prepareCopy(state);
      return state.copy_[prop] = createProxy(value2, state);
    }
    return value2;
  },
  has(state, prop) {
    return prop in latest(state);
  },
  ownKeys(state) {
    return Reflect.ownKeys(latest(state));
  },
  set(state, prop, value2) {
    const desc = getDescriptorFromProto(latest(state), prop);
    if (desc?.set) {
      desc.set.call(state.draft_, value2);
      return true;
    }
    if (!state.modified_) {
      const current22 = peek(latest(state), prop);
      const currentState = current22?.[DRAFT_STATE];
      if (currentState && currentState.base_ === value2) {
        state.copy_[prop] = value2;
        state.assigned_[prop] = false;
        return true;
      }
      if (is$1(value2, current22) && (value2 !== void 0 || has$2(state.base_, prop)))
        return true;
      prepareCopy(state);
      markChanged(state);
    }
    if (state.copy_[prop] === value2 && // special case: handle new props with value 'undefined'
    (value2 !== void 0 || prop in state.copy_) || // special case: NaN
    Number.isNaN(value2) && Number.isNaN(state.copy_[prop]))
      return true;
    state.copy_[prop] = value2;
    state.assigned_[prop] = true;
    return true;
  },
  deleteProperty(state, prop) {
    if (peek(state.base_, prop) !== void 0 || prop in state.base_) {
      state.assigned_[prop] = false;
      prepareCopy(state);
      markChanged(state);
    } else {
      delete state.assigned_[prop];
    }
    if (state.copy_) {
      delete state.copy_[prop];
    }
    return true;
  },
  // Note: We never coerce `desc.value` into an Immer draft, because we can't make
  // the same guarantee in ES5 mode.
  getOwnPropertyDescriptor(state, prop) {
    const owner = latest(state);
    const desc = Reflect.getOwnPropertyDescriptor(owner, prop);
    if (!desc)
      return desc;
    return {
      writable: true,
      configurable: state.type_ !== 1 || prop !== "length",
      enumerable: desc.enumerable,
      value: owner[prop]
    };
  },
  defineProperty() {
    die(11);
  },
  getPrototypeOf(state) {
    return getPrototypeOf(state.base_);
  },
  setPrototypeOf() {
    die(12);
  }
};
var arrayTraps = {};
each(objectTraps, (key2, fn3) => {
  arrayTraps[key2] = function() {
    arguments[0] = arguments[0][0];
    return fn3.apply(this, arguments);
  };
});
arrayTraps.deleteProperty = function(state, prop) {
  if (isNaN(parseInt(prop)))
    die(13);
  return arrayTraps.set.call(this, state, prop, void 0);
};
arrayTraps.set = function(state, prop, value2) {
  if (prop !== "length" && isNaN(parseInt(prop)))
    die(14);
  return objectTraps.set.call(this, state[0], prop, value2, state[0]);
};
function peek(draft, prop) {
  const state = draft[DRAFT_STATE];
  const source2 = state ? latest(state) : draft;
  return source2[prop];
}
function readPropFromProto(state, source2, prop) {
  const desc = getDescriptorFromProto(source2, prop);
  return desc ? `value` in desc ? desc.value : (
    // This is a very special case, if the prop is a getter defined by the
    // prototype, we should invoke it with the draft as context!
    desc.get?.call(state.draft_)
  ) : void 0;
}
function getDescriptorFromProto(source2, prop) {
  if (!(prop in source2))
    return void 0;
  let proto = getPrototypeOf(source2);
  while (proto) {
    const desc = Object.getOwnPropertyDescriptor(proto, prop);
    if (desc)
      return desc;
    proto = getPrototypeOf(proto);
  }
  return void 0;
}
function markChanged(state) {
  if (!state.modified_) {
    state.modified_ = true;
    if (state.parent_) {
      markChanged(state.parent_);
    }
  }
}
function prepareCopy(state) {
  if (!state.copy_) {
    state.copy_ = shallowCopy(
      state.base_,
      state.scope_.immer_.useStrictShallowCopy_
    );
  }
}
var Immer2 = class {
  constructor(config2) {
    this.autoFreeze_ = true;
    this.useStrictShallowCopy_ = false;
    this.useStrictIteration_ = true;
    this.produce = (base2, recipe, patchListener) => {
      if (typeof base2 === "function" && typeof recipe !== "function") {
        const defaultBase = recipe;
        recipe = base2;
        const self2 = this;
        return function curriedProduce(base22 = defaultBase, ...args2) {
          return self2.produce(base22, (draft) => recipe.call(this, draft, ...args2));
        };
      }
      if (typeof recipe !== "function")
        die(6);
      if (patchListener !== void 0 && typeof patchListener !== "function")
        die(7);
      let result2;
      if (isDraftable(base2)) {
        const scope = enterScope(this);
        const proxy = createProxy(base2, void 0);
        let hasError = true;
        try {
          result2 = recipe(proxy);
          hasError = false;
        } finally {
          if (hasError)
            revokeScope(scope);
          else
            leaveScope(scope);
        }
        usePatchesInScope(scope, patchListener);
        return processResult(result2, scope);
      } else if (!base2 || typeof base2 !== "object") {
        result2 = recipe(base2);
        if (result2 === void 0)
          result2 = base2;
        if (result2 === NOTHING)
          result2 = void 0;
        if (this.autoFreeze_)
          freeze(result2, true);
        if (patchListener) {
          const p = [];
          const ip = [];
          getPlugin("Patches").generateReplacementPatches_(base2, result2, p, ip);
          patchListener(p, ip);
        }
        return result2;
      } else
        die(1, base2);
    };
    this.produceWithPatches = (base2, recipe) => {
      if (typeof base2 === "function") {
        return (state, ...args2) => this.produceWithPatches(state, (draft) => base2(draft, ...args2));
      }
      let patches, inversePatches;
      const result2 = this.produce(base2, recipe, (p, ip) => {
        patches = p;
        inversePatches = ip;
      });
      return [result2, patches, inversePatches];
    };
    if (typeof config2?.autoFreeze === "boolean")
      this.setAutoFreeze(config2.autoFreeze);
    if (typeof config2?.useStrictShallowCopy === "boolean")
      this.setUseStrictShallowCopy(config2.useStrictShallowCopy);
    if (typeof config2?.useStrictIteration === "boolean")
      this.setUseStrictIteration(config2.useStrictIteration);
  }
  createDraft(base2) {
    if (!isDraftable(base2))
      die(8);
    if (isDraft(base2))
      base2 = current(base2);
    const scope = enterScope(this);
    const proxy = createProxy(base2, void 0);
    proxy[DRAFT_STATE].isManual_ = true;
    leaveScope(scope);
    return proxy;
  }
  finishDraft(draft, patchListener) {
    const state = draft && draft[DRAFT_STATE];
    if (!state || !state.isManual_)
      die(9);
    const { scope_: scope } = state;
    usePatchesInScope(scope, patchListener);
    return processResult(void 0, scope);
  }
  /**
   * Pass true to automatically freeze all copies created by Immer.
   *
   * By default, auto-freezing is enabled.
   */
  setAutoFreeze(value2) {
    this.autoFreeze_ = value2;
  }
  /**
   * Pass true to enable strict shallow copy.
   *
   * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.
   */
  setUseStrictShallowCopy(value2) {
    this.useStrictShallowCopy_ = value2;
  }
  /**
   * Pass false to use faster iteration that skips non-enumerable properties
   * but still handles symbols for compatibility.
   *
   * By default, strict iteration is enabled (includes all own properties).
   */
  setUseStrictIteration(value2) {
    this.useStrictIteration_ = value2;
  }
  shouldUseStrictIteration() {
    return this.useStrictIteration_;
  }
  applyPatches(base2, patches) {
    let i2;
    for (i2 = patches.length - 1; i2 >= 0; i2--) {
      const patch = patches[i2];
      if (patch.path.length === 0 && patch.op === "replace") {
        base2 = patch.value;
        break;
      }
    }
    if (i2 > -1) {
      patches = patches.slice(i2 + 1);
    }
    const applyPatchesImpl = getPlugin("Patches").applyPatches_;
    if (isDraft(base2)) {
      return applyPatchesImpl(base2, patches);
    }
    return this.produce(
      base2,
      (draft) => applyPatchesImpl(draft, patches)
    );
  }
};
function createProxy(value2, parent) {
  const draft = isMap$1(value2) ? getPlugin("MapSet").proxyMap_(value2, parent) : isSet$1(value2) ? getPlugin("MapSet").proxySet_(value2, parent) : createProxyProxy(value2, parent);
  const scope = parent ? parent.scope_ : getCurrentScope();
  scope.drafts_.push(draft);
  return draft;
}
function current(value2) {
  if (!isDraft(value2))
    die(10, value2);
  return currentImpl(value2);
}
function currentImpl(value2) {
  if (!isDraftable(value2) || isFrozen(value2))
    return value2;
  const state = value2[DRAFT_STATE];
  let copy;
  let strict = true;
  if (state) {
    if (!state.modified_)
      return state.base_;
    state.finalized_ = true;
    copy = shallowCopy(value2, state.scope_.immer_.useStrictShallowCopy_);
    strict = state.scope_.immer_.shouldUseStrictIteration();
  } else {
    copy = shallowCopy(value2, true);
  }
  each(
    copy,
    (key2, childValue) => {
      set(copy, key2, currentImpl(childValue));
    },
    strict
  );
  if (state) {
    state.finalized_ = false;
  }
  return copy;
}
var immer$1 = new Immer2();
var produce = immer$1.produce;
const immerImpl = (initializer) => (set3, get2, store2) => {
  store2.setState = (updater, replace2, ...args2) => {
    const nextState = typeof updater === "function" ? produce(updater) : updater;
    return set3(nextState, replace2, ...args2);
  };
  return initializer(store2.setState, get2, store2);
};
const immer = immerImpl;
const selectedScanResultDataRef = {
  data: void 0,
  scanner: void 0,
  previews: void 0
};
const createDebouncedPersistStorage = (storage, delay = 2e3) => {
  if (!storage) {
    throw new Error("Storage is required");
  }
  const debouncedSetItem = debounce$2((key2, value2) => {
    storage.setItem(key2, value2);
  }, delay);
  return {
    ...storage,
    setItem: (key2, value2) => {
      debouncedSetItem(key2, value2);
    }
  };
};
const createStore$1 = (api2) => create$2()(
  devtools(
    persist(
      immer((set3, get2) => ({
        // Initial state
        scans: [],
        resultsStoredInRef: false,
        resultDataInState: false,
        properties: {},
        scrollPositions: {},
        listPositions: {},
        visibleRanges: {},
        gridStates: {},
        loading: 0,
        loadingData: 0,
        collapsedBuckets: {},
        transcriptCollapsedEvents: {},
        scopedErrors: {},
        visibleScannerResults: [],
        visibleScannerResultsCount: 0,
        highlightLabeled: false,
        // Actions
        setSingleFileMode: (enabled) => {
          set3((state) => {
            state.singleFileMode = enabled;
          });
        },
        setHasInitializedEmbeddedData: (initialized) => {
          set3((state) => {
            state.hasInitializedEmbeddedData = initialized;
          });
        },
        setHasInitializedRouting: (initialized) => {
          set3((state) => {
            state.hasInitializedRouting = initialized;
          });
        },
        setError: (scope, error2) => {
          set3((state) => {
            state.scopedErrors[scope] = error2;
          });
        },
        clearError: (scope) => {
          set3((state) => {
            state.scopedErrors[scope] = void 0;
          });
        },
        setLoading: (loading) => {
          set3((state) => {
            if (loading) {
              state.loading += 1;
            } else {
              state.loading = Math.max(0, state.loading - 1);
            }
          });
        },
        setLoadingData: (loading) => {
          set3((state) => {
            if (loading) {
              state.loading += 1;
            } else {
              state.loading = Math.max(0, state.loading - 1);
            }
          });
        },
        setResultsDir: (dir) => set3((state) => {
          state.resultsDir = dir;
        }),
        setScans: (scans) => set3((state) => {
          state.scans = scans;
        }),
        setVisibleScanJobCount: (count2) => set3((state) => {
          state.visibleScanJobCount = count2;
        }),
        setSelectedScanLocation: (location) => set3((state) => {
          state.selectedScanLocation = location;
        }),
        setSelectedScanStatus: (status) => {
          set3((state) => {
            state.selectedScanStatus = status;
          });
        },
        clearSelectedScanStatus: () => {
          set3((state) => {
            state.selectedScanStatus = void 0;
          });
        },
        setSelectedScanner: (scanner) => {
          set3((state) => {
            state.selectedScanner = scanner;
          });
        },
        setSelectedScanResult: (result2) => set3((state) => {
          state.selectedScanResult = result2;
        }),
        setSelectedScanResultData: (scanner, data2) => {
          selectedScanResultDataRef.data = data2;
          selectedScanResultDataRef.scanner = scanner;
          selectedScanResultDataRef.previews = void 0;
        },
        getSelectedScanResultData: (scanner) => {
          if (selectedScanResultDataRef.scanner === scanner) {
            return selectedScanResultDataRef.data;
          }
          return void 0;
        },
        setVisibleScannerResults: (results) => {
          set3((state) => {
            state.visibleScannerResults = results;
          });
        },
        setVisibleScannerResultsCount(count2) {
          set3((state) => {
            state.visibleScannerResultsCount = count2;
          });
        },
        setSelectedScanResultPreviews: (scanner, previews) => {
          if (selectedScanResultDataRef.scanner === scanner) {
            selectedScanResultDataRef.previews = previews;
          } else {
            throw new Error(
              "Attempting to store previews for unmatched scanner"
            );
          }
        },
        getSelectedScanResultPreviews: (scanner) => {
          if (selectedScanResultDataRef.scanner === scanner) {
            return selectedScanResultDataRef.previews;
          }
          return void 0;
        },
        clearScanState: () => {
          set3((state) => {
            state.selectedResultsTab = void 0;
            state.collapsedBuckets = {};
            state.transcriptCollapsedEvents = {};
            state.transcriptOutlineId = void 0;
            state.selectedResultTab = void 0;
            state.groupResultsBy = void 0;
            state.scansSearchText = void 0;
          });
        },
        clearScansState: () => {
          selectedScanResultDataRef.data = void 0;
          selectedScanResultDataRef.scanner = void 0;
          set3((state) => {
            state.clearSelectedScanStatus();
            state.selectedScanStatus = void 0;
            state.selectedResultsView = void 0;
            state.selectedFilter = void 0;
            state.selectedScanner = void 0;
            state.selectedScanResult = void 0;
            state.sortResults = void 0;
          });
        },
        setPropertyValue(id2, propertyName, value2) {
          set3((state) => {
            if (!state.properties[id2]) {
              state.properties[id2] = {};
            }
            state.properties[id2][propertyName] = value2;
          });
        },
        getPropertyValue(id2, propertyName, defaultValue) {
          const value2 = get2().properties[id2]?.[propertyName];
          return value2 !== void 0 ? value2 : defaultValue;
        },
        removePropertyValue(id2, propertyName) {
          set3((state) => {
            const propertyGroup = state.properties[id2];
            if (!propertyGroup || !propertyGroup[propertyName]) {
              return;
            }
            const { [propertyName]: _removed, ...remainingProperties } = propertyGroup;
            if (Object.keys(remainingProperties).length === 0) {
              const { [id2]: _removedGroup, ...remainingGroups } = state.properties;
              state.properties = remainingGroups;
              return;
            }
            state.properties[id2] = remainingProperties;
          });
        },
        setCollapsed: (bucket, key2, value2) => {
          set3((state) => {
            state.collapsedBuckets[bucket] = state.collapsedBuckets[bucket] || {};
            state.collapsedBuckets[bucket][key2] = value2;
          });
        },
        clearCollapsed: (bucket) => {
          set3((state) => {
            state.collapsedBuckets[bucket] = {};
          });
        },
        getScrollPosition(path) {
          const state = get2();
          return state.scrollPositions[path];
        },
        setScrollPosition(path, position) {
          set3((state) => {
            state.scrollPositions[path] = position;
          });
        },
        setListPosition: (name2, position) => {
          set3((state) => {
            state.listPositions[name2] = position;
          });
        },
        clearListPosition: (name2) => {
          set3((state) => {
            const newListPositions = { ...state.listPositions };
            delete newListPositions[name2];
            return {
              listPositions: newListPositions
            };
          });
        },
        setGridState: (name2, gridState) => {
          set3((state) => {
            state.gridStates[name2] = gridState;
          });
        },
        clearGridState: (name2) => {
          set3((state) => {
            const newGridStates = { ...state.gridStates };
            delete newGridStates[name2];
            return {
              ...state,
              gridStates: newGridStates
            };
          });
        },
        getVisibleRange: (name2) => {
          return get2().visibleRanges[name2] ?? { startIndex: 0, endIndex: 0 };
        },
        setVisibleRange: (name2, value2) => {
          set3((state) => {
            state.visibleRanges[name2] = value2;
          });
        },
        clearVisibleRange: (name2) => {
          set3((state) => {
            const newVisibleRanges = { ...state.visibleRanges };
            delete newVisibleRanges[name2];
            return {
              ...state,
              visibleRanges: newVisibleRanges
            };
          });
        },
        setSelectedResultsTab: (tab2) => {
          set3((state) => {
            state.selectedResultsTab = tab2;
          });
        },
        setSelectedResultTab: (tab2) => {
          set3((state) => {
            state.selectedResultTab = tab2;
          });
        },
        setTranscriptOutlineId: (id2) => {
          set3((state) => {
            state.transcriptOutlineId = id2;
          });
        },
        clearTranscriptOutlineId: () => {
          set3((state) => {
            state.transcriptOutlineId = void 0;
          });
        },
        setTranscriptCollapsedEvent: (scope, event, collapsed) => {
          set3((state) => {
            if (!state.transcriptCollapsedEvents[scope]) {
              state.transcriptCollapsedEvents[scope] = {};
            }
            state.transcriptCollapsedEvents[scope][event] = collapsed;
          });
        },
        setTranscriptCollapsedEvents: (scope, events) => {
          set3((state) => {
            state.transcriptCollapsedEvents[scope] = events;
          });
        },
        clearTranscriptCollapsedEvents: (scope) => {
          set3((state) => {
            state.transcriptCollapsedEvents[scope] = {};
          });
        },
        setSelectedResultsView: (view) => {
          set3((state) => {
            state.selectedResultsView = view;
          });
        },
        setSelectedFilter: (filter2) => {
          set3((state) => {
            state.selectedFilter = filter2;
          });
        },
        setShowingRefPopover: (popoverKey2) => {
          set3((state) => {
            state.showingRefPopover = popoverKey2;
          });
        },
        clearShowingRefPopover: () => {
          set3((state) => {
            state.showingRefPopover = void 0;
          });
        },
        setGroupResultsBy: (groupBy) => {
          set3((state) => {
            state.groupResultsBy = groupBy;
          });
        },
        setSortResults: (sortColumns2) => {
          set3((state) => {
            state.sortResults = sortColumns2;
          });
        },
        setScansSearchText: (text2) => {
          set3((state) => {
            state.scansSearchText = text2;
          });
        },
        setHighlightLabeled: (highlight2) => {
          set3((state) => {
            state.highlightLabeled = highlight2;
          });
        },
        setSelectedResultRow: (row2) => {
          set3((state) => {
            state.selectedResultRow = row2;
          });
        },
        setDataframeWrapText: (wrap2) => {
          set3((state) => {
            state.dataframeWrapText = wrap2;
          });
        },
        setDataframeFilterColumns: (columns2) => {
          set3((state) => {
            state.dataframeFilterColumns = columns2;
          });
        },
        setDataframeShowFilterColumns: (show) => {
          set3((state) => {
            state.dataframeShowFilterColumns = show;
          });
        }
      })),
      {
        name: "inspect-scout-storage",
        storage: createDebouncedPersistStorage(
          createJSONStorage(() => api2.storage)
        ),
        version: 1,
        partialize: (state) => {
          const {
            hasInitializedRouting,
            visibleScannerResults,
            ...persistedState
          } = state;
          return persistedState;
        }
      }
    )
  )
);
const StoreContext = reactExports.createContext(null);
const ApiContext = reactExports.createContext(null);
const StoreProvider = StoreContext.Provider;
const ApiProvider = ApiContext.Provider;
const useStore = (selector) => {
  const store2 = reactExports.useContext(StoreContext);
  if (!store2) throw new Error("useStore must be used within StoreProvider");
  if (!selector) {
    return store2((state) => state);
  }
  return store2(selector);
};
const useApi = () => {
  const api2 = reactExports.useContext(ApiContext);
  if (!api2) throw new Error("useApi must be used within ApiProvider");
  return api2;
};
const log$1 = createLogger("scrolling");
function useStatefulScrollPosition(elementRef, elementKey, delay = 1e3, scrollable2 = true) {
  const getScrollPosition = useStore((state) => state.getScrollPosition);
  const setScrollPosition = useStore((state) => state.setScrollPosition);
  const handleScrollInner = reactExports.useCallback(
    (e) => {
      const target = e.target;
      const position = target.scrollTop;
      log$1.debug(`Storing scroll position`, elementKey, position);
      setScrollPosition(elementKey, position);
    },
    [elementKey, setScrollPosition]
  );
  const handleScroll = reactExports.useMemo(
    () => debounce$2(handleScrollInner, delay),
    [handleScrollInner, delay]
  );
  const restoreScrollPosition = reactExports.useCallback(() => {
    const element = elementRef.current;
    const savedPosition = getScrollPosition(elementKey);
    if (element && savedPosition !== void 0) {
      requestAnimationFrame(() => {
        element.scrollTop = savedPosition;
        requestAnimationFrame(() => {
          if (element.scrollTop !== savedPosition) {
            element.scrollTop = savedPosition;
          }
        });
      });
    }
  }, [elementKey, getScrollPosition, elementRef]);
  reactExports.useEffect(() => {
    const element = elementRef.current;
    if (!element || !scrollable2) {
      return;
    }
    log$1.debug(`Restore Scroll Hook`, elementKey);
    const savedPosition = getScrollPosition(elementKey);
    if (savedPosition !== void 0) {
      log$1.debug(`Restoring scroll position`, savedPosition);
      const tryRestoreScroll = () => {
        if (element.scrollHeight > element.clientHeight) {
          if (element.scrollTop !== savedPosition) {
            element.scrollTop = savedPosition;
            log$1.debug(`Scroll position restored to ${savedPosition}`);
          }
          return true;
        }
        return false;
      };
      if (!tryRestoreScroll()) {
        let attempts = 0;
        const maxAttempts = 5;
        const pollForRender = () => {
          if (tryRestoreScroll() || attempts >= maxAttempts) {
            if (attempts >= maxAttempts) {
              log$1.debug(
                `Failed to restore scroll after ${maxAttempts} attempts`
              );
            }
            return;
          }
          attempts++;
          setTimeout(pollForRender, 1e3);
        };
        setTimeout(pollForRender, 1e3);
      }
    }
    if (element.addEventListener) {
      element.addEventListener("scroll", handleScroll);
    } else {
      log$1.warn("Element has no way to add event listener", element);
    }
    return () => {
      if (element.removeEventListener) {
        element.removeEventListener("scroll", handleScroll);
      } else {
        log$1.warn("Element has no way to remove event listener", element);
      }
    };
  }, [elementKey, elementRef, getScrollPosition, handleScroll, scrollable2]);
  return { restoreScrollPosition };
}
const useVirtuosoState = (virtuosoRef, elementKey, delay = 1e3) => {
  const restoreState = useStore(
    reactExports.useCallback((state) => state.listPositions[elementKey], [elementKey])
  );
  const setListPosition = useStore(
    reactExports.useCallback((state) => state.setListPosition, [])
  );
  const clearListPosition = useStore(
    reactExports.useCallback((state) => state.clearListPosition, [])
  );
  const debouncedFnRef = reactExports.useRef(null);
  const handleStateChange = reactExports.useCallback(
    (state) => {
      log$1.debug(`Storing list state: [${elementKey}]`, state);
      setListPosition(elementKey, state);
    },
    [elementKey, setListPosition]
  );
  reactExports.useEffect(() => {
    debouncedFnRef.current = debounce$2((isScrolling2) => {
      log$1.debug("List scroll", isScrolling2);
      const element = virtuosoRef.current;
      if (!element) {
        return;
      }
      element.getState(handleStateChange);
    }, delay);
    return () => {
      clearListPosition(elementKey);
    };
  }, [delay, elementKey, handleStateChange, clearListPosition, virtuosoRef]);
  const isScrolling = reactExports.useCallback((scrolling) => {
    if (!scrolling) {
      return;
    }
    if (debouncedFnRef.current) {
      debouncedFnRef.current(scrolling);
    }
  }, []);
  const stateRef = reactExports.useRef(restoreState);
  reactExports.useEffect(() => {
    stateRef.current = restoreState;
  }, [restoreState]);
  const getRestoreState = reactExports.useCallback(() => stateRef.current, []);
  const setVisibleRangeRaw = useStore((state) => state.setVisibleRange);
  const setVisibleRange = reactExports.useCallback(
    (value2) => {
      setVisibleRangeRaw(elementKey, value2);
    },
    [setVisibleRangeRaw, elementKey]
  );
  const visibleRanges = useStore((state) => state.visibleRanges);
  const visibleRange = reactExports.useMemo(() => {
    return visibleRanges[elementKey] || {
      startIndex: 0,
      endIndex: 0
    };
  }, [visibleRanges, elementKey]);
  return { getRestoreState, isScrolling, visibleRange, setVisibleRange };
};
function useRafThrottle(callback) {
  const rafRef = reactExports.useRef(null);
  const callbackRef = reactExports.useRef(callback);
  reactExports.useEffect(() => {
    callbackRef.current = callback;
  }, [callback]);
  const throttledCallback = reactExports.useCallback((...args2) => {
    if (rafRef.current) {
      return;
    }
    rafRef.current = requestAnimationFrame(() => {
      callbackRef.current(...args2);
      rafRef.current = null;
    });
  }, []);
  reactExports.useEffect(() => {
    return () => {
      if (rafRef.current) {
        cancelAnimationFrame(rafRef.current);
        rafRef.current = null;
      }
    };
  }, []);
  return throttledCallback;
}
const tabs$2 = "_tabs_1sz0h_1";
const tabContents = "_tabContents_1sz0h_5";
const scrollable = "_scrollable_1sz0h_10";
const tab$1 = "_tab_1sz0h_1";
const tabItem = "_tabItem_1sz0h_25";
const tabIcon = "_tabIcon_1sz0h_29";
const tabTools = "_tabTools_1sz0h_33";
const tabStyle = "_tabStyle_1sz0h_43";
const moduleStyles = {
  tabs: tabs$2,
  tabContents,
  scrollable,
  tab: tab$1,
  tabItem,
  tabIcon,
  tabTools,
  tabStyle
};
const TabSet = ({
  id: id2,
  type = "tabs",
  className: className2,
  tabPanelsClassName,
  tabControlsClassName,
  tools: tools2,
  tabsRef,
  children: children2
}) => {
  const validTabs = flattenChildren(children2);
  if (validTabs.length === 0) return null;
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(reactExports.Fragment, { children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "ul",
      {
        ref: tabsRef,
        id: id2,
        className: clsx(
          "nav",
          `nav-${type}`,
          type === "tabs" ? moduleStyles.tabStyle : void 0,
          className2,
          moduleStyles.tabs
        ),
        role: "tablist",
        "aria-orientation": "horizontal",
        children: [
          validTabs.map((tab2, index) => /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            Tab,
            {
              index,
              type,
              tab: tab2,
              className: clsx(tabControlsClassName)
            },
            tab2.props.id,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/TabSet.tsx",
              lineNumber: 76,
              columnNumber: 11
            },
            void 0
          )),
          tools2 && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(TabTools, { tools: tools2 }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/TabSet.tsx",
            lineNumber: 84,
            columnNumber: 19
          }, void 0)
        ]
      },
      void 0,
      true,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/TabSet.tsx",
        lineNumber: 62,
        columnNumber: 7
      },
      void 0
    ),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(TabPanels, { id: id2, tabs: validTabs, className: tabPanelsClassName }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/TabSet.tsx",
      lineNumber: 86,
      columnNumber: 7
    }, void 0)
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/TabSet.tsx",
    lineNumber: 61,
    columnNumber: 5
  }, void 0);
};
const Tab = ({ type = "tabs", tab: tab2, index, className: className2 }) => {
  const tabId = tab2.props.id || computeTabId("tabset", index);
  const tabContentsId = computeTabContentsId(tab2.props.id);
  const isActive = tab2.props.selected;
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("li", { role: "presentation", className: clsx("nav-item", moduleStyles.tabItem), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "button",
    {
      id: tabId,
      className: clsx(
        "nav-link",
        className2,
        isActive && "active",
        type === "pills" ? moduleStyles.pill : moduleStyles.tab,
        "text-size-small",
        "text-style-label"
      ),
      type: "button",
      role: "tab",
      "aria-controls": tabContentsId,
      "aria-selected": isActive,
      onClick: tab2.props.onSelected,
      children: [
        tab2.props.icon && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("i", { className: clsx(tab2.props.icon, moduleStyles.tabIcon) }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/TabSet.tsx",
          lineNumber: 121,
          columnNumber: 11
        }, void 0),
        tab2.props.title
      ]
    },
    void 0,
    true,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/TabSet.tsx",
      lineNumber: 104,
      columnNumber: 7
    },
    void 0
  ) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/TabSet.tsx",
    lineNumber: 103,
    columnNumber: 5
  }, void 0);
};
const TabPanels = ({ id: id2, tabs: tabs2, className: className2 }) => /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("tab-content", className2), id: `${id2}-content`, children: tabs2.map((tab2, index) => /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(TabPanel, { ...tab2.props, index }, tab2.props.id, false, {
  fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/TabSet.tsx",
  lineNumber: 137,
  columnNumber: 7
}, void 0)) }, void 0, false, {
  fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/TabSet.tsx",
  lineNumber: 135,
  columnNumber: 3
}, void 0);
const TabPanel = ({
  id: id2,
  selected: selected2,
  style: style2,
  scrollable: scrollable2 = true,
  scrollRef,
  className: className2,
  children: children2
}) => {
  const tabContentsId = computeTabContentsId(id2);
  const panelRef = reactExports.useRef(null);
  const tabContentsRef = scrollRef || panelRef;
  useStatefulScrollPosition(tabContentsRef, tabContentsId, 1e3, scrollable2);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "div",
    {
      id: tabContentsId,
      ref: tabContentsRef,
      className: clsx(
        "tab-pane",
        selected2 && "show active",
        className2,
        moduleStyles.tabContents,
        scrollable2 && moduleStyles.scrollable
      ),
      style: style2,
      children: selected2 ? children2 : null
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/TabSet.tsx",
      lineNumber: 160,
      columnNumber: 5
    },
    void 0
  );
};
const TabTools = ({ tools: tools2 }) => /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("tab-tools", moduleStyles.tabTools), children: tools2 }, void 0, false, {
  fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/TabSet.tsx",
  lineNumber: 179,
  columnNumber: 3
}, void 0);
const computeTabId = (id2, index) => `${id2}-${index}`;
const computeTabContentsId = (id2) => `${id2}-contents`;
const flattenChildren = (children2) => {
  return reactExports.Children.toArray(children2).flatMap((child) => {
    if (reactExports.isValidElement(child)) {
      const element = child;
      if (element.type === reactExports.Fragment) {
        return flattenChildren(element.props.children);
      }
      return element;
    }
    return [];
  });
};
const kScansRouteUrlPattern = "/scans";
const kScansWithPathRouteUrlPattern = "/scans/*";
const kScanRouteUrlPattern = "/scan/*";
const kScanIdPattern = /scan_id=[a-zA-Z0-9_.-]{22}$/;
const kScannerQueryParam = "scanner";
const scanRoute = (relativePath, searchParams) => {
  const route = `/scan/${relativePath}`;
  searchParams?.delete("tab");
  return searchParams?.toString() ? `${route}?${searchParams.toString()}` : route;
};
const scansRoute = (relativePath, searchParams) => {
  const route = relativePath ? `/scans/${relativePath}` : "/scans";
  return route;
};
const scanResultRoute = (scanRelativePath, scanResultId, searchParams) => {
  const route = `/scan/${scanRelativePath}/${scanResultId}`;
  return searchParams?.toString() ? `${route}?${searchParams.toString()}` : route;
};
const isValidScanPath = (path) => {
  path = path.startsWith("/") ? path : "/" + path;
  return kScanIdPattern.test(path);
};
const getRelativePathFromParams = (params) => {
  return params["*"] || "";
};
const parseScanResultPath = (fullPath) => {
  const scanIdMatch = fullPath.match(/scan_id=[a-zA-Z0-9_.-]{22}/);
  if (!scanIdMatch || scanIdMatch.index === void 0) {
    return { scanPath: fullPath };
  }
  const scanIdEndIndex = scanIdMatch.index + scanIdMatch[0].length;
  const scanPath = fullPath.slice(0, scanIdEndIndex);
  const remainingPath = fullPath.slice(scanIdEndIndex);
  if (remainingPath && remainingPath.length > 1) {
    const scanResultUuid = remainingPath.startsWith("/") ? remainingPath.slice(1) : remainingPath;
    return { scanPath, scanResultUuid };
  }
  return { scanPath };
};
const updateScannerParam = (searchParams, scanner) => {
  const newParams = new URLSearchParams(searchParams);
  newParams.set(kScannerQueryParam, scanner);
  return newParams;
};
const getScannerParam = (searchParams) => {
  return searchParams.get(kScannerQueryParam) || void 0;
};
const loggingIcons = {
  notset: "bi bi-card-text",
  debug: "bi bi-bug",
  http: "bi bi-download",
  info: "bi bi-info-square",
  warning: "bi bi-exclamation-triangle",
  error: "bi bi-x-circle",
  critical: "bi bi-fire"
};
const iconForMimeType = (mimeType) => {
  if (mimeType === "application/pdf") {
    return "bi bi-file-pdf";
  } else if (mimeType.startsWith("image/")) {
    return "bi bi-file-image";
  } else {
    return "bi bi-file-earmark";
  }
};
const ApplicationIcons = {
  // bi bi-x-diamond
  approve: "bi bi-shield",
  approvals: {
    approve: "bi bi-shield-check",
    reject: "bi bi-shield-x",
    terminate: "bi bi-shield-exclamation",
    escalate: "bi bi-box-arrow-up",
    modify: "bi bi-pencil-square"
  },
  arrows: {
    right: "bi bi-arrow-right",
    down: "bi bi-arrow-down",
    up: "bi bi-arrow-up"
  },
  check: "bi bi-check",
  checkbox: {
    checked: "bi bi-check-circle",
    unchecked: "bi bi-circle"
  },
  chevron: {
    right: "bi bi-chevron-right",
    down: "bi bi-chevron-down"
  },
  "clear-text": "bi bi-x-circle-fill",
  close: "bi bi-x",
  confirm: "bi bi-check",
  copy: "bi bi-copy",
  edit: "bi bi-pencil-square",
  error: "bi bi-exclamation-circle-fill",
  file: "bi bi-file-code",
  filter: "bi bi-funnel",
  folder: "bi bi-folder",
  highlight: "bi bi-highlighter",
  info: "bi bi-info-circle",
  input: "bi bi-terminal",
  limits: {
    messages: "bi bi-chat-right-text",
    custom: "bi bi-exclamation-triangle",
    operator: "bi bi-person-workspace",
    tokens: "bi bi-list",
    time: "bi bi-clock",
    execution: "bi bi-stopwatch"
  },
  link: "bi bi-link-45deg",
  logging: loggingIcons,
  metadata: "bi bi-table",
  model: "bi bi-grid-3x3-gap",
  navbar: {
    home: "ii inspect-icon-home",
    back: "ii inspect-icon-back",
    forward: "ii inspect-icon-forward"
  },
  next: "bi bi-chevron-right",
  noSamples: "bi bi-ban",
  pendingTask: "bi bi-clock-fill",
  play: "bi bi-play-fill",
  previous: "bi bi-chevron-left",
  refuse: "bi bi-ban",
  role: {
    tool: "bi bi-tools"
  },
  sample: "bi bi-database",
  samples: "bi bi-file-spreadsheet",
  sandbox: "bi bi-box-seam",
  scorer: "bi bi-calculator",
  search: "bi bi-search",
  solvers: {
    use_tools: "bi bi-tools"
  },
  success: "bi bi-check-circle-fill",
  tree: {
    open: "bi bi-caret-down-fill",
    closed: "bi bi-caret-right-fill"
  },
  wrap: "bi bi-text-wrap",
  x: "bi bi-x"
};
const toolButton = "_toolButton_1y0d0_1";
const latched = "_latched_1y0d0_17";
const styles$1m = {
  toolButton,
  latched
};
const ToolButton = reactExports.forwardRef(
  ({ label: label2, icon: icon2, className: className2, latched: latched2, ...rest }, ref2) => {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "button",
      {
        ref: ref2,
        type: "button",
        className: clsx(
          styles$1m.toolButton,
          "btn",
          "btn-tools",
          className2,
          latched2 ? styles$1m.latched : void 0
        ),
        ...rest,
        children: [
          icon2 && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("i", { className: `${icon2}` }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/components/ToolButton.tsx",
            lineNumber: 29,
            columnNumber: 18
          }, void 0),
          label2
        ]
      },
      void 0,
      true,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/components/ToolButton.tsx",
        lineNumber: 17,
        columnNumber: 7
      },
      void 0
    );
  }
);
ToolButton.displayName = "ToolButton";
function __awaiter(thisArg, _arguments, P2, generator) {
  function adopt(value2) {
    return value2 instanceof P2 ? value2 : new P2(function(resolve2) {
      resolve2(value2);
    });
  }
  return new (P2 || (P2 = Promise))(function(resolve2, reject) {
    function fulfilled(value2) {
      try {
        step(generator.next(value2));
      } catch (e) {
        reject(e);
      }
    }
    function rejected(value2) {
      try {
        step(generator["throw"](value2));
      } catch (e) {
        reject(e);
      }
    }
    function step(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}
function __values(o) {
  var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i2 = 0;
  if (m) return m.call(o);
  if (o && typeof o.length === "number") return {
    next: function() {
      if (o && i2 >= o.length) o = void 0;
      return { value: o && o[i2++], done: !o };
    }
  };
  throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __await(v) {
  return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var g = generator.apply(thisArg, _arguments || []), i2, q = [];
  return i2 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i2[Symbol.asyncIterator] = function() {
    return this;
  }, i2;
  function awaitReturn(f) {
    return function(v) {
      return Promise.resolve(v).then(f, reject);
    };
  }
  function verb(n2, f) {
    if (g[n2]) {
      i2[n2] = function(v) {
        return new Promise(function(a2, b) {
          q.push([n2, v, a2, b]) > 1 || resume(n2, v);
        });
      };
      if (f) i2[n2] = f(i2[n2]);
    }
  }
  function resume(n2, v) {
    try {
      step(g[n2](v));
    } catch (e) {
      settle(q[0][3], e);
    }
  }
  function step(r2) {
    r2.value instanceof __await ? Promise.resolve(r2.value.v).then(fulfill, reject) : settle(q[0][2], r2);
  }
  function fulfill(value2) {
    resume("next", value2);
  }
  function reject(value2) {
    resume("throw", value2);
  }
  function settle(f, v) {
    if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
  }
}
function __asyncDelegator(o) {
  var i2, p;
  return i2 = {}, verb("next"), verb("throw", function(e) {
    throw e;
  }), verb("return"), i2[Symbol.iterator] = function() {
    return this;
  }, i2;
  function verb(n2, f) {
    i2[n2] = o[n2] ? function(v) {
      return (p = !p) ? { value: __await(o[n2](v)), done: false } : f ? f(v) : v;
    } : f;
  }
}
function __asyncValues(o) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var m = o[Symbol.asyncIterator], i2;
  return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i2 = {}, verb("next"), verb("throw"), verb("return"), i2[Symbol.asyncIterator] = function() {
    return this;
  }, i2);
  function verb(n2) {
    i2[n2] = o[n2] && function(v) {
      return new Promise(function(resolve2, reject) {
        v = o[n2](v), settle(resolve2, reject, v.done, v.value);
      });
    };
  }
  function settle(resolve2, reject, d, v) {
    Promise.resolve(v).then(function(v2) {
      resolve2({ value: v2, done: d });
    }, reject);
  }
}
typeof SuppressedError === "function" ? SuppressedError : function(error2, suppressed, message2) {
  var e = new Error(message2);
  return e.name = "SuppressedError", e.error = error2, e.suppressed = suppressed, e;
};
const decoder = new TextDecoder("utf-8");
const decodeUtf8$1 = decoder.decode.bind(decoder);
const encoder = new TextEncoder();
const encodeUtf8$1 = (value2) => encoder.encode(value2);
const isNumber$2 = (x) => typeof x === "number";
const isBoolean = (x) => typeof x === "boolean";
const isFunction$2 = (x) => typeof x === "function";
const isObject$2 = (x) => x != null && Object(x) === x;
const isPromise = (x) => {
  return isObject$2(x) && isFunction$2(x.then);
};
const isIterable$1 = (x) => {
  return isObject$2(x) && isFunction$2(x[Symbol.iterator]);
};
const isAsyncIterable = (x) => {
  return isObject$2(x) && isFunction$2(x[Symbol.asyncIterator]);
};
const isArrowJSON = (x) => {
  return isObject$2(x) && isObject$2(x["schema"]);
};
const isIteratorResult = (x) => {
  return isObject$2(x) && "done" in x && "value" in x;
};
const isFileHandle = (x) => {
  return isObject$2(x) && isFunction$2(x["stat"]) && isNumber$2(x["fd"]);
};
const isFetchResponse = (x) => {
  return isObject$2(x) && isReadableDOMStream(x["body"]);
};
const isReadableInterop = (x) => "_getDOMStream" in x && "_getNodeStream" in x;
const isWritableDOMStream = (x) => {
  return isObject$2(x) && isFunction$2(x["abort"]) && isFunction$2(x["getWriter"]) && !isReadableInterop(x);
};
const isReadableDOMStream = (x) => {
  return isObject$2(x) && isFunction$2(x["cancel"]) && isFunction$2(x["getReader"]) && !isReadableInterop(x);
};
const isWritableNodeStream = (x) => {
  return isObject$2(x) && isFunction$2(x["end"]) && isFunction$2(x["write"]) && isBoolean(x["writable"]) && !isReadableInterop(x);
};
const isReadableNodeStream = (x) => {
  return isObject$2(x) && isFunction$2(x["read"]) && isFunction$2(x["pipe"]) && isBoolean(x["readable"]) && !isReadableInterop(x);
};
const isFlatbuffersByteBuffer = (x) => {
  return isObject$2(x) && isFunction$2(x["clear"]) && isFunction$2(x["bytes"]) && isFunction$2(x["position"]) && isFunction$2(x["setPosition"]) && isFunction$2(x["capacity"]) && isFunction$2(x["getBufferIdentifier"]) && isFunction$2(x["createLong"]);
};
const SharedArrayBuf = typeof SharedArrayBuffer !== "undefined" ? SharedArrayBuffer : ArrayBuffer;
function collapseContiguousByteRanges(chunks) {
  const result2 = chunks[0] ? [chunks[0]] : [];
  let xOffset, yOffset, xLen, yLen;
  for (let x, y, i2 = 0, j2 = 0, n2 = chunks.length; ++i2 < n2; ) {
    x = result2[j2];
    y = chunks[i2];
    if (!x || !y || x.buffer !== y.buffer || y.byteOffset < x.byteOffset) {
      y && (result2[++j2] = y);
      continue;
    }
    ({ byteOffset: xOffset, byteLength: xLen } = x);
    ({ byteOffset: yOffset, byteLength: yLen } = y);
    if (xOffset + xLen < yOffset || yOffset + yLen < xOffset) {
      y && (result2[++j2] = y);
      continue;
    }
    result2[j2] = new Uint8Array(x.buffer, xOffset, yOffset - xOffset + yLen);
  }
  return result2;
}
function memcpy(target, source2, targetByteOffset = 0, sourceByteLength = source2.byteLength) {
  const targetByteLength = target.byteLength;
  const dst = new Uint8Array(target.buffer, target.byteOffset, targetByteLength);
  const src = new Uint8Array(source2.buffer, source2.byteOffset, Math.min(sourceByteLength, targetByteLength));
  dst.set(src, targetByteOffset);
  return target;
}
function joinUint8Arrays(chunks, size) {
  const result2 = collapseContiguousByteRanges(chunks);
  const byteLength = result2.reduce((x, b) => x + b.byteLength, 0);
  let source2, sliced, buffer2;
  let offset3 = 0, index = -1;
  const length2 = Math.min(size || Number.POSITIVE_INFINITY, byteLength);
  for (const n2 = result2.length; ++index < n2; ) {
    source2 = result2[index];
    sliced = source2.subarray(0, Math.min(source2.length, length2 - offset3));
    if (length2 <= offset3 + sliced.length) {
      if (sliced.length < source2.length) {
        result2[index] = source2.subarray(sliced.length);
      } else if (sliced.length === source2.length) {
        index++;
      }
      buffer2 ? memcpy(buffer2, sliced, offset3) : buffer2 = sliced;
      break;
    }
    memcpy(buffer2 || (buffer2 = new Uint8Array(length2)), sliced, offset3);
    offset3 += sliced.length;
  }
  return [buffer2 || new Uint8Array(0), result2.slice(index), byteLength - (buffer2 ? buffer2.byteLength : 0)];
}
function toArrayBufferView(ArrayBufferViewCtor, input2) {
  let value2 = isIteratorResult(input2) ? input2.value : input2;
  if (value2 instanceof ArrayBufferViewCtor) {
    if (ArrayBufferViewCtor === Uint8Array) {
      return new ArrayBufferViewCtor(value2.buffer, value2.byteOffset, value2.byteLength);
    }
    return value2;
  }
  if (!value2) {
    return new ArrayBufferViewCtor(0);
  }
  if (typeof value2 === "string") {
    value2 = encodeUtf8$1(value2);
  }
  if (value2 instanceof ArrayBuffer) {
    return new ArrayBufferViewCtor(value2);
  }
  if (value2 instanceof SharedArrayBuf) {
    return new ArrayBufferViewCtor(value2);
  }
  if (isFlatbuffersByteBuffer(value2)) {
    return toArrayBufferView(ArrayBufferViewCtor, value2.bytes());
  }
  return !ArrayBuffer.isView(value2) ? ArrayBufferViewCtor.from(value2) : value2.byteLength <= 0 ? new ArrayBufferViewCtor(0) : new ArrayBufferViewCtor(value2.buffer, value2.byteOffset, value2.byteLength / ArrayBufferViewCtor.BYTES_PER_ELEMENT);
}
const toInt32Array = (input2) => toArrayBufferView(Int32Array, input2);
const toBigInt64Array = (input2) => toArrayBufferView(BigInt64Array, input2);
const toUint8Array = (input2) => toArrayBufferView(Uint8Array, input2);
const pump$1 = (iterator) => {
  iterator.next();
  return iterator;
};
function* toArrayBufferViewIterator(ArrayCtor, source2) {
  const wrap2 = function* (x) {
    yield x;
  };
  const buffers = typeof source2 === "string" ? wrap2(source2) : ArrayBuffer.isView(source2) ? wrap2(source2) : source2 instanceof ArrayBuffer ? wrap2(source2) : source2 instanceof SharedArrayBuf ? wrap2(source2) : !isIterable$1(source2) ? wrap2(source2) : source2;
  yield* pump$1((function* (it) {
    let r2 = null;
    do {
      r2 = it.next(yield toArrayBufferView(ArrayCtor, r2));
    } while (!r2.done);
  })(buffers[Symbol.iterator]()));
  return new ArrayCtor();
}
const toUint8ArrayIterator = (input2) => toArrayBufferViewIterator(Uint8Array, input2);
function toArrayBufferViewAsyncIterator(ArrayCtor, source2) {
  return __asyncGenerator(this, arguments, function* toArrayBufferViewAsyncIterator_1() {
    if (isPromise(source2)) {
      return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(toArrayBufferViewAsyncIterator(ArrayCtor, yield __await(source2))))));
    }
    const wrap2 = function(x) {
      return __asyncGenerator(this, arguments, function* () {
        yield yield __await(yield __await(x));
      });
    };
    const emit = function(source3) {
      return __asyncGenerator(this, arguments, function* () {
        yield __await(yield* __asyncDelegator(__asyncValues(pump$1((function* (it) {
          let r2 = null;
          do {
            r2 = it.next(yield r2 === null || r2 === void 0 ? void 0 : r2.value);
          } while (!r2.done);
        })(source3[Symbol.iterator]())))));
      });
    };
    const buffers = typeof source2 === "string" ? wrap2(source2) : ArrayBuffer.isView(source2) ? wrap2(source2) : source2 instanceof ArrayBuffer ? wrap2(source2) : source2 instanceof SharedArrayBuf ? wrap2(source2) : isIterable$1(source2) ? emit(source2) : !isAsyncIterable(source2) ? wrap2(source2) : source2;
    yield __await(
      // otherwise if AsyncIterable, use it
      yield* __asyncDelegator(__asyncValues(pump$1((function(it) {
        return __asyncGenerator(this, arguments, function* () {
          let r2 = null;
          do {
            r2 = yield __await(it.next(yield yield __await(toArrayBufferView(ArrayCtor, r2))));
          } while (!r2.done);
        });
      })(buffers[Symbol.asyncIterator]()))))
    );
    return yield __await(new ArrayCtor());
  });
}
const toUint8ArrayAsyncIterator = (input2) => toArrayBufferViewAsyncIterator(Uint8Array, input2);
function rebaseValueOffsets(offset3, length2, valueOffsets) {
  if (offset3 !== 0) {
    valueOffsets = valueOffsets.slice(0, length2);
    for (let i2 = -1, n2 = valueOffsets.length; ++i2 < n2; ) {
      valueOffsets[i2] += offset3;
    }
  }
  return valueOffsets.subarray(0, length2);
}
function compareArrayLike(a2, b) {
  let i2 = 0;
  const n2 = a2.length;
  if (n2 !== b.length) {
    return false;
  }
  if (n2 > 0) {
    do {
      if (a2[i2] !== b[i2]) {
        return false;
      }
    } while (++i2 < n2);
  }
  return true;
}
const streamAdapters = {
  fromIterable(source2) {
    return pump(fromIterable$1(source2));
  },
  fromAsyncIterable(source2) {
    return pump(fromAsyncIterable(source2));
  },
  fromDOMStream(source2) {
    return pump(fromDOMStream(source2));
  },
  fromNodeStream(stream) {
    return pump(fromNodeStream(stream));
  },
  // @ts-ignore
  toDOMStream(source2, options) {
    throw new Error(`"toDOMStream" not available in this environment`);
  },
  // @ts-ignore
  toNodeStream(source2, options) {
    throw new Error(`"toNodeStream" not available in this environment`);
  }
};
const pump = (iterator) => {
  iterator.next();
  return iterator;
};
function* fromIterable$1(source2) {
  let done, threw = false;
  let buffers = [], buffer2;
  let cmd, size, bufferLength = 0;
  function byteRange() {
    if (cmd === "peek") {
      return joinUint8Arrays(buffers, size)[0];
    }
    [buffer2, buffers, bufferLength] = joinUint8Arrays(buffers, size);
    return buffer2;
  }
  ({ cmd, size } = (yield /* @__PURE__ */ (() => null)()) || { cmd: "read", size: 0 });
  const it = toUint8ArrayIterator(source2)[Symbol.iterator]();
  try {
    do {
      ({ done, value: buffer2 } = Number.isNaN(size - bufferLength) ? it.next() : it.next(size - bufferLength));
      if (!done && buffer2.byteLength > 0) {
        buffers.push(buffer2);
        bufferLength += buffer2.byteLength;
      }
      if (done || size <= bufferLength) {
        do {
          ({ cmd, size } = yield byteRange());
        } while (size < bufferLength);
      }
    } while (!done);
  } catch (e) {
    threw = true;
    typeof it.throw === "function" && it.throw(e);
  } finally {
    threw === false && typeof it.return === "function" && it.return(null);
  }
  return null;
}
function fromAsyncIterable(source2) {
  return __asyncGenerator(this, arguments, function* fromAsyncIterable_1() {
    let done, threw = false;
    let buffers = [], buffer2;
    let cmd, size, bufferLength = 0;
    function byteRange() {
      if (cmd === "peek") {
        return joinUint8Arrays(buffers, size)[0];
      }
      [buffer2, buffers, bufferLength] = joinUint8Arrays(buffers, size);
      return buffer2;
    }
    ({ cmd, size } = (yield yield __await(/* @__PURE__ */ (() => null)())) || { cmd: "read", size: 0 });
    const it = toUint8ArrayAsyncIterator(source2)[Symbol.asyncIterator]();
    try {
      do {
        ({ done, value: buffer2 } = Number.isNaN(size - bufferLength) ? yield __await(it.next()) : yield __await(it.next(size - bufferLength)));
        if (!done && buffer2.byteLength > 0) {
          buffers.push(buffer2);
          bufferLength += buffer2.byteLength;
        }
        if (done || size <= bufferLength) {
          do {
            ({ cmd, size } = yield yield __await(byteRange()));
          } while (size < bufferLength);
        }
      } while (!done);
    } catch (e) {
      threw = true;
      typeof it.throw === "function" && (yield __await(it.throw(e)));
    } finally {
      threw === false && typeof it.return === "function" && (yield __await(it.return(new Uint8Array(0))));
    }
    return yield __await(null);
  });
}
function fromDOMStream(source2) {
  return __asyncGenerator(this, arguments, function* fromDOMStream_1() {
    let done = false, threw = false;
    let buffers = [], buffer2;
    let cmd, size, bufferLength = 0;
    function byteRange() {
      if (cmd === "peek") {
        return joinUint8Arrays(buffers, size)[0];
      }
      [buffer2, buffers, bufferLength] = joinUint8Arrays(buffers, size);
      return buffer2;
    }
    ({ cmd, size } = (yield yield __await(/* @__PURE__ */ (() => null)())) || { cmd: "read", size: 0 });
    const it = new AdaptiveByteReader(source2);
    try {
      do {
        ({ done, value: buffer2 } = Number.isNaN(size - bufferLength) ? yield __await(it["read"]()) : yield __await(it["read"](size - bufferLength)));
        if (!done && buffer2.byteLength > 0) {
          buffers.push(toUint8Array(buffer2));
          bufferLength += buffer2.byteLength;
        }
        if (done || size <= bufferLength) {
          do {
            ({ cmd, size } = yield yield __await(byteRange()));
          } while (size < bufferLength);
        }
      } while (!done);
    } catch (e) {
      threw = true;
      yield __await(it["cancel"](e));
    } finally {
      threw === false ? yield __await(it["cancel"]()) : source2["locked"] && it.releaseLock();
    }
    return yield __await(null);
  });
}
class AdaptiveByteReader {
  constructor(source2) {
    this.source = source2;
    this.reader = null;
    this.reader = this.source["getReader"]();
    this.reader["closed"].catch(() => {
    });
  }
  get closed() {
    return this.reader ? this.reader["closed"].catch(() => {
    }) : Promise.resolve();
  }
  releaseLock() {
    if (this.reader) {
      this.reader.releaseLock();
    }
    this.reader = null;
  }
  cancel(reason) {
    return __awaiter(this, void 0, void 0, function* () {
      const { reader, source: source2 } = this;
      reader && (yield reader["cancel"](reason).catch(() => {
      }));
      source2 && (source2["locked"] && this.releaseLock());
    });
  }
  read(size) {
    return __awaiter(this, void 0, void 0, function* () {
      if (size === 0) {
        return { done: this.reader == null, value: new Uint8Array(0) };
      }
      const result2 = yield this.reader.read();
      !result2.done && (result2.value = toUint8Array(result2));
      return result2;
    });
  }
}
const onEvent = (stream, event) => {
  const handler = (_) => resolve2([event, _]);
  let resolve2;
  return [event, handler, new Promise((r2) => (resolve2 = r2) && stream["once"](event, handler))];
};
function fromNodeStream(stream) {
  return __asyncGenerator(this, arguments, function* fromNodeStream_1() {
    const events = [];
    let event = "error";
    let done = false, err = null;
    let cmd, size, bufferLength = 0;
    let buffers = [], buffer2;
    function byteRange() {
      if (cmd === "peek") {
        return joinUint8Arrays(buffers, size)[0];
      }
      [buffer2, buffers, bufferLength] = joinUint8Arrays(buffers, size);
      return buffer2;
    }
    ({ cmd, size } = (yield yield __await(/* @__PURE__ */ (() => null)())) || { cmd: "read", size: 0 });
    if (stream["isTTY"]) {
      yield yield __await(new Uint8Array(0));
      return yield __await(null);
    }
    try {
      events[0] = onEvent(stream, "end");
      events[1] = onEvent(stream, "error");
      do {
        events[2] = onEvent(stream, "readable");
        [event, err] = yield __await(Promise.race(events.map((x) => x[2])));
        if (event === "error") {
          break;
        }
        if (!(done = event === "end")) {
          if (!Number.isFinite(size - bufferLength)) {
            buffer2 = toUint8Array(stream["read"]());
          } else {
            buffer2 = toUint8Array(stream["read"](size - bufferLength));
            if (buffer2.byteLength < size - bufferLength) {
              buffer2 = toUint8Array(stream["read"]());
            }
          }
          if (buffer2.byteLength > 0) {
            buffers.push(buffer2);
            bufferLength += buffer2.byteLength;
          }
        }
        if (done || size <= bufferLength) {
          do {
            ({ cmd, size } = yield yield __await(byteRange()));
          } while (size < bufferLength);
        }
      } while (!done);
    } finally {
      yield __await(cleanup(events, event === "error" ? err : null));
    }
    return yield __await(null);
    function cleanup(events2, err2) {
      buffer2 = buffers = null;
      return new Promise((resolve2, reject) => {
        for (const [evt, fn3] of events2) {
          stream["off"](evt, fn3);
        }
        try {
          const destroy2 = stream["destroy"];
          destroy2 && destroy2.call(stream, err2);
          err2 = void 0;
        } catch (e) {
          err2 = e || err2;
        } finally {
          err2 != null ? reject(err2) : resolve2();
        }
      });
    }
  });
}
var MetadataVersion;
(function(MetadataVersion2) {
  MetadataVersion2[MetadataVersion2["V1"] = 0] = "V1";
  MetadataVersion2[MetadataVersion2["V2"] = 1] = "V2";
  MetadataVersion2[MetadataVersion2["V3"] = 2] = "V3";
  MetadataVersion2[MetadataVersion2["V4"] = 3] = "V4";
  MetadataVersion2[MetadataVersion2["V5"] = 4] = "V5";
})(MetadataVersion || (MetadataVersion = {}));
var UnionMode$1;
(function(UnionMode2) {
  UnionMode2[UnionMode2["Sparse"] = 0] = "Sparse";
  UnionMode2[UnionMode2["Dense"] = 1] = "Dense";
})(UnionMode$1 || (UnionMode$1 = {}));
var Precision$1;
(function(Precision2) {
  Precision2[Precision2["HALF"] = 0] = "HALF";
  Precision2[Precision2["SINGLE"] = 1] = "SINGLE";
  Precision2[Precision2["DOUBLE"] = 2] = "DOUBLE";
})(Precision$1 || (Precision$1 = {}));
var DateUnit$1;
(function(DateUnit2) {
  DateUnit2[DateUnit2["DAY"] = 0] = "DAY";
  DateUnit2[DateUnit2["MILLISECOND"] = 1] = "MILLISECOND";
})(DateUnit$1 || (DateUnit$1 = {}));
var TimeUnit$1;
(function(TimeUnit2) {
  TimeUnit2[TimeUnit2["SECOND"] = 0] = "SECOND";
  TimeUnit2[TimeUnit2["MILLISECOND"] = 1] = "MILLISECOND";
  TimeUnit2[TimeUnit2["MICROSECOND"] = 2] = "MICROSECOND";
  TimeUnit2[TimeUnit2["NANOSECOND"] = 3] = "NANOSECOND";
})(TimeUnit$1 || (TimeUnit$1 = {}));
var IntervalUnit$1;
(function(IntervalUnit2) {
  IntervalUnit2[IntervalUnit2["YEAR_MONTH"] = 0] = "YEAR_MONTH";
  IntervalUnit2[IntervalUnit2["DAY_TIME"] = 1] = "DAY_TIME";
  IntervalUnit2[IntervalUnit2["MONTH_DAY_NANO"] = 2] = "MONTH_DAY_NANO";
})(IntervalUnit$1 || (IntervalUnit$1 = {}));
const SIZEOF_SHORT$1 = 2;
const SIZEOF_INT$1 = 4;
const FILE_IDENTIFIER_LENGTH = 4;
const SIZE_PREFIX_LENGTH = 4;
const int32$1 = new Int32Array(2);
const float32$1 = new Float32Array(int32$1.buffer);
const float64$1 = new Float64Array(int32$1.buffer);
const isLittleEndian$1 = new Uint16Array(new Uint8Array([1, 0]).buffer)[0] === 1;
var Encoding;
(function(Encoding2) {
  Encoding2[Encoding2["UTF8_BYTES"] = 1] = "UTF8_BYTES";
  Encoding2[Encoding2["UTF16_STRING"] = 2] = "UTF16_STRING";
})(Encoding || (Encoding = {}));
let ByteBuffer$2 = class ByteBuffer {
  /**
   * Create a new ByteBuffer with a given array of bytes (`Uint8Array`)
   */
  constructor(bytes_) {
    this.bytes_ = bytes_;
    this.position_ = 0;
    this.text_decoder_ = new TextDecoder();
  }
  /**
   * Create and allocate a new ByteBuffer with a given size.
   */
  static allocate(byte_size) {
    return new ByteBuffer(new Uint8Array(byte_size));
  }
  clear() {
    this.position_ = 0;
  }
  /**
   * Get the underlying `Uint8Array`.
   */
  bytes() {
    return this.bytes_;
  }
  /**
   * Get the buffer's position.
   */
  position() {
    return this.position_;
  }
  /**
   * Set the buffer's position.
   */
  setPosition(position) {
    this.position_ = position;
  }
  /**
   * Get the buffer's capacity.
   */
  capacity() {
    return this.bytes_.length;
  }
  readInt8(offset3) {
    return this.readUint8(offset3) << 24 >> 24;
  }
  readUint8(offset3) {
    return this.bytes_[offset3];
  }
  readInt16(offset3) {
    return this.readUint16(offset3) << 16 >> 16;
  }
  readUint16(offset3) {
    return this.bytes_[offset3] | this.bytes_[offset3 + 1] << 8;
  }
  readInt32(offset3) {
    return this.bytes_[offset3] | this.bytes_[offset3 + 1] << 8 | this.bytes_[offset3 + 2] << 16 | this.bytes_[offset3 + 3] << 24;
  }
  readUint32(offset3) {
    return this.readInt32(offset3) >>> 0;
  }
  readInt64(offset3) {
    return BigInt.asIntN(64, BigInt(this.readUint32(offset3)) + (BigInt(this.readUint32(offset3 + 4)) << BigInt(32)));
  }
  readUint64(offset3) {
    return BigInt.asUintN(64, BigInt(this.readUint32(offset3)) + (BigInt(this.readUint32(offset3 + 4)) << BigInt(32)));
  }
  readFloat32(offset3) {
    int32$1[0] = this.readInt32(offset3);
    return float32$1[0];
  }
  readFloat64(offset3) {
    int32$1[isLittleEndian$1 ? 0 : 1] = this.readInt32(offset3);
    int32$1[isLittleEndian$1 ? 1 : 0] = this.readInt32(offset3 + 4);
    return float64$1[0];
  }
  writeInt8(offset3, value2) {
    this.bytes_[offset3] = value2;
  }
  writeUint8(offset3, value2) {
    this.bytes_[offset3] = value2;
  }
  writeInt16(offset3, value2) {
    this.bytes_[offset3] = value2;
    this.bytes_[offset3 + 1] = value2 >> 8;
  }
  writeUint16(offset3, value2) {
    this.bytes_[offset3] = value2;
    this.bytes_[offset3 + 1] = value2 >> 8;
  }
  writeInt32(offset3, value2) {
    this.bytes_[offset3] = value2;
    this.bytes_[offset3 + 1] = value2 >> 8;
    this.bytes_[offset3 + 2] = value2 >> 16;
    this.bytes_[offset3 + 3] = value2 >> 24;
  }
  writeUint32(offset3, value2) {
    this.bytes_[offset3] = value2;
    this.bytes_[offset3 + 1] = value2 >> 8;
    this.bytes_[offset3 + 2] = value2 >> 16;
    this.bytes_[offset3 + 3] = value2 >> 24;
  }
  writeInt64(offset3, value2) {
    this.writeInt32(offset3, Number(BigInt.asIntN(32, value2)));
    this.writeInt32(offset3 + 4, Number(BigInt.asIntN(32, value2 >> BigInt(32))));
  }
  writeUint64(offset3, value2) {
    this.writeUint32(offset3, Number(BigInt.asUintN(32, value2)));
    this.writeUint32(offset3 + 4, Number(BigInt.asUintN(32, value2 >> BigInt(32))));
  }
  writeFloat32(offset3, value2) {
    float32$1[0] = value2;
    this.writeInt32(offset3, int32$1[0]);
  }
  writeFloat64(offset3, value2) {
    float64$1[0] = value2;
    this.writeInt32(offset3, int32$1[isLittleEndian$1 ? 0 : 1]);
    this.writeInt32(offset3 + 4, int32$1[isLittleEndian$1 ? 1 : 0]);
  }
  /**
   * Return the file identifier.   Behavior is undefined for FlatBuffers whose
   * schema does not include a file_identifier (likely points at padding or the
   * start of a the root vtable).
   */
  getBufferIdentifier() {
    if (this.bytes_.length < this.position_ + SIZEOF_INT$1 + FILE_IDENTIFIER_LENGTH) {
      throw new Error("FlatBuffers: ByteBuffer is too short to contain an identifier.");
    }
    let result2 = "";
    for (let i2 = 0; i2 < FILE_IDENTIFIER_LENGTH; i2++) {
      result2 += String.fromCharCode(this.readInt8(this.position_ + SIZEOF_INT$1 + i2));
    }
    return result2;
  }
  /**
   * Look up a field in the vtable, return an offset into the object, or 0 if the
   * field is not present.
   */
  __offset(bb_pos, vtable_offset) {
    const vtable = bb_pos - this.readInt32(bb_pos);
    return vtable_offset < this.readInt16(vtable) ? this.readInt16(vtable + vtable_offset) : 0;
  }
  /**
   * Initialize any Table-derived type to point to the union at the given offset.
   */
  __union(t2, offset3) {
    t2.bb_pos = offset3 + this.readInt32(offset3);
    t2.bb = this;
    return t2;
  }
  /**
   * Create a JavaScript string from UTF-8 data stored inside the FlatBuffer.
   * This allocates a new string and converts to wide chars upon each access.
   *
   * To avoid the conversion to string, pass Encoding.UTF8_BYTES as the
   * "optionalEncoding" argument. This is useful for avoiding conversion when
   * the data will just be packaged back up in another FlatBuffer later on.
   *
   * @param offset
   * @param opt_encoding Defaults to UTF16_STRING
   */
  __string(offset3, opt_encoding) {
    offset3 += this.readInt32(offset3);
    const length2 = this.readInt32(offset3);
    offset3 += SIZEOF_INT$1;
    const utf8bytes = this.bytes_.subarray(offset3, offset3 + length2);
    if (opt_encoding === Encoding.UTF8_BYTES)
      return utf8bytes;
    else
      return this.text_decoder_.decode(utf8bytes);
  }
  /**
   * Handle unions that can contain string as its member, if a Table-derived type then initialize it,
   * if a string then return a new one
   *
   * WARNING: strings are immutable in JS so we can't change the string that the user gave us, this
   * makes the behaviour of __union_with_string different compared to __union
   */
  __union_with_string(o, offset3) {
    if (typeof o === "string") {
      return this.__string(offset3);
    }
    return this.__union(o, offset3);
  }
  /**
   * Retrieve the relative offset stored at "offset"
   */
  __indirect(offset3) {
    return offset3 + this.readInt32(offset3);
  }
  /**
   * Get the start of data of a vector whose offset is stored at "offset" in this object.
   */
  __vector(offset3) {
    return offset3 + this.readInt32(offset3) + SIZEOF_INT$1;
  }
  /**
   * Get the length of a vector whose offset is stored at "offset" in this object.
   */
  __vector_len(offset3) {
    return this.readInt32(offset3 + this.readInt32(offset3));
  }
  __has_identifier(ident) {
    if (ident.length != FILE_IDENTIFIER_LENGTH) {
      throw new Error("FlatBuffers: file identifier must be length " + FILE_IDENTIFIER_LENGTH);
    }
    for (let i2 = 0; i2 < FILE_IDENTIFIER_LENGTH; i2++) {
      if (ident.charCodeAt(i2) != this.readInt8(this.position() + SIZEOF_INT$1 + i2)) {
        return false;
      }
    }
    return true;
  }
  /**
   * A helper function for generating list for obj api
   */
  createScalarList(listAccessor, listLength) {
    const ret = [];
    for (let i2 = 0; i2 < listLength; ++i2) {
      const val = listAccessor(i2);
      if (val !== null) {
        ret.push(val);
      }
    }
    return ret;
  }
  /**
   * A helper function for generating list for obj api
   * @param listAccessor function that accepts an index and return data at that index
   * @param listLength listLength
   * @param res result list
   */
  createObjList(listAccessor, listLength) {
    const ret = [];
    for (let i2 = 0; i2 < listLength; ++i2) {
      const val = listAccessor(i2);
      if (val !== null) {
        ret.push(val.unpack());
      }
    }
    return ret;
  }
};
let Builder$3 = class Builder {
  /**
   * Create a FlatBufferBuilder.
   */
  constructor(opt_initial_size) {
    this.minalign = 1;
    this.vtable = null;
    this.vtable_in_use = 0;
    this.isNested = false;
    this.object_start = 0;
    this.vtables = [];
    this.vector_num_elems = 0;
    this.force_defaults = false;
    this.string_maps = null;
    this.text_encoder = new TextEncoder();
    let initial_size;
    if (!opt_initial_size) {
      initial_size = 1024;
    } else {
      initial_size = opt_initial_size;
    }
    this.bb = ByteBuffer$2.allocate(initial_size);
    this.space = initial_size;
  }
  clear() {
    this.bb.clear();
    this.space = this.bb.capacity();
    this.minalign = 1;
    this.vtable = null;
    this.vtable_in_use = 0;
    this.isNested = false;
    this.object_start = 0;
    this.vtables = [];
    this.vector_num_elems = 0;
    this.force_defaults = false;
    this.string_maps = null;
  }
  /**
   * In order to save space, fields that are set to their default value
   * don't get serialized into the buffer. Forcing defaults provides a
   * way to manually disable this optimization.
   *
   * @param forceDefaults true always serializes default values
   */
  forceDefaults(forceDefaults) {
    this.force_defaults = forceDefaults;
  }
  /**
   * Get the ByteBuffer representing the FlatBuffer. Only call this after you've
   * called finish(). The actual data starts at the ByteBuffer's current position,
   * not necessarily at 0.
   */
  dataBuffer() {
    return this.bb;
  }
  /**
   * Get the bytes representing the FlatBuffer. Only call this after you've
   * called finish().
   */
  asUint8Array() {
    return this.bb.bytes().subarray(this.bb.position(), this.bb.position() + this.offset());
  }
  /**
   * Prepare to write an element of `size` after `additional_bytes` have been
   * written, e.g. if you write a string, you need to align such the int length
   * field is aligned to 4 bytes, and the string data follows it directly. If all
   * you need to do is alignment, `additional_bytes` will be 0.
   *
   * @param size This is the of the new element to write
   * @param additional_bytes The padding size
   */
  prep(size, additional_bytes) {
    if (size > this.minalign) {
      this.minalign = size;
    }
    const align_size = ~(this.bb.capacity() - this.space + additional_bytes) + 1 & size - 1;
    while (this.space < align_size + size + additional_bytes) {
      const old_buf_size = this.bb.capacity();
      this.bb = Builder.growByteBuffer(this.bb);
      this.space += this.bb.capacity() - old_buf_size;
    }
    this.pad(align_size);
  }
  pad(byte_size) {
    for (let i2 = 0; i2 < byte_size; i2++) {
      this.bb.writeInt8(--this.space, 0);
    }
  }
  writeInt8(value2) {
    this.bb.writeInt8(this.space -= 1, value2);
  }
  writeInt16(value2) {
    this.bb.writeInt16(this.space -= 2, value2);
  }
  writeInt32(value2) {
    this.bb.writeInt32(this.space -= 4, value2);
  }
  writeInt64(value2) {
    this.bb.writeInt64(this.space -= 8, value2);
  }
  writeFloat32(value2) {
    this.bb.writeFloat32(this.space -= 4, value2);
  }
  writeFloat64(value2) {
    this.bb.writeFloat64(this.space -= 8, value2);
  }
  /**
   * Add an `int8` to the buffer, properly aligned, and grows the buffer (if necessary).
   * @param value The `int8` to add the buffer.
   */
  addInt8(value2) {
    this.prep(1, 0);
    this.writeInt8(value2);
  }
  /**
   * Add an `int16` to the buffer, properly aligned, and grows the buffer (if necessary).
   * @param value The `int16` to add the buffer.
   */
  addInt16(value2) {
    this.prep(2, 0);
    this.writeInt16(value2);
  }
  /**
   * Add an `int32` to the buffer, properly aligned, and grows the buffer (if necessary).
   * @param value The `int32` to add the buffer.
   */
  addInt32(value2) {
    this.prep(4, 0);
    this.writeInt32(value2);
  }
  /**
   * Add an `int64` to the buffer, properly aligned, and grows the buffer (if necessary).
   * @param value The `int64` to add the buffer.
   */
  addInt64(value2) {
    this.prep(8, 0);
    this.writeInt64(value2);
  }
  /**
   * Add a `float32` to the buffer, properly aligned, and grows the buffer (if necessary).
   * @param value The `float32` to add the buffer.
   */
  addFloat32(value2) {
    this.prep(4, 0);
    this.writeFloat32(value2);
  }
  /**
   * Add a `float64` to the buffer, properly aligned, and grows the buffer (if necessary).
   * @param value The `float64` to add the buffer.
   */
  addFloat64(value2) {
    this.prep(8, 0);
    this.writeFloat64(value2);
  }
  addFieldInt8(voffset, value2, defaultValue) {
    if (this.force_defaults || value2 != defaultValue) {
      this.addInt8(value2);
      this.slot(voffset);
    }
  }
  addFieldInt16(voffset, value2, defaultValue) {
    if (this.force_defaults || value2 != defaultValue) {
      this.addInt16(value2);
      this.slot(voffset);
    }
  }
  addFieldInt32(voffset, value2, defaultValue) {
    if (this.force_defaults || value2 != defaultValue) {
      this.addInt32(value2);
      this.slot(voffset);
    }
  }
  addFieldInt64(voffset, value2, defaultValue) {
    if (this.force_defaults || value2 !== defaultValue) {
      this.addInt64(value2);
      this.slot(voffset);
    }
  }
  addFieldFloat32(voffset, value2, defaultValue) {
    if (this.force_defaults || value2 != defaultValue) {
      this.addFloat32(value2);
      this.slot(voffset);
    }
  }
  addFieldFloat64(voffset, value2, defaultValue) {
    if (this.force_defaults || value2 != defaultValue) {
      this.addFloat64(value2);
      this.slot(voffset);
    }
  }
  addFieldOffset(voffset, value2, defaultValue) {
    if (this.force_defaults || value2 != defaultValue) {
      this.addOffset(value2);
      this.slot(voffset);
    }
  }
  /**
   * Structs are stored inline, so nothing additional is being added. `d` is always 0.
   */
  addFieldStruct(voffset, value2, defaultValue) {
    if (value2 != defaultValue) {
      this.nested(value2);
      this.slot(voffset);
    }
  }
  /**
   * Structures are always stored inline, they need to be created right
   * where they're used.  You'll get this assertion failure if you
   * created it elsewhere.
   */
  nested(obj) {
    if (obj != this.offset()) {
      throw new TypeError("FlatBuffers: struct must be serialized inline.");
    }
  }
  /**
   * Should not be creating any other object, string or vector
   * while an object is being constructed
   */
  notNested() {
    if (this.isNested) {
      throw new TypeError("FlatBuffers: object serialization must not be nested.");
    }
  }
  /**
   * Set the current vtable at `voffset` to the current location in the buffer.
   */
  slot(voffset) {
    if (this.vtable !== null)
      this.vtable[voffset] = this.offset();
  }
  /**
   * @returns Offset relative to the end of the buffer.
   */
  offset() {
    return this.bb.capacity() - this.space;
  }
  /**
   * Doubles the size of the backing ByteBuffer and copies the old data towards
   * the end of the new buffer (since we build the buffer backwards).
   *
   * @param bb The current buffer with the existing data
   * @returns A new byte buffer with the old data copied
   * to it. The data is located at the end of the buffer.
   *
   * uint8Array.set() formally takes {Array<number>|ArrayBufferView}, so to pass
   * it a uint8Array we need to suppress the type check:
   * @suppress {checkTypes}
   */
  static growByteBuffer(bb) {
    const old_buf_size = bb.capacity();
    if (old_buf_size & 3221225472) {
      throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes.");
    }
    const new_buf_size = old_buf_size << 1;
    const nbb = ByteBuffer$2.allocate(new_buf_size);
    nbb.setPosition(new_buf_size - old_buf_size);
    nbb.bytes().set(bb.bytes(), new_buf_size - old_buf_size);
    return nbb;
  }
  /**
   * Adds on offset, relative to where it will be written.
   *
   * @param offset The offset to add.
   */
  addOffset(offset3) {
    this.prep(SIZEOF_INT$1, 0);
    this.writeInt32(this.offset() - offset3 + SIZEOF_INT$1);
  }
  /**
   * Start encoding a new object in the buffer.  Users will not usually need to
   * call this directly. The FlatBuffers compiler will generate helper methods
   * that call this method internally.
   */
  startObject(numfields) {
    this.notNested();
    if (this.vtable == null) {
      this.vtable = [];
    }
    this.vtable_in_use = numfields;
    for (let i2 = 0; i2 < numfields; i2++) {
      this.vtable[i2] = 0;
    }
    this.isNested = true;
    this.object_start = this.offset();
  }
  /**
   * Finish off writing the object that is under construction.
   *
   * @returns The offset to the object inside `dataBuffer`
   */
  endObject() {
    if (this.vtable == null || !this.isNested) {
      throw new Error("FlatBuffers: endObject called without startObject");
    }
    this.addInt32(0);
    const vtableloc = this.offset();
    let i2 = this.vtable_in_use - 1;
    for (; i2 >= 0 && this.vtable[i2] == 0; i2--) {
    }
    const trimmed_size = i2 + 1;
    for (; i2 >= 0; i2--) {
      this.addInt16(this.vtable[i2] != 0 ? vtableloc - this.vtable[i2] : 0);
    }
    const standard_fields = 2;
    this.addInt16(vtableloc - this.object_start);
    const len = (trimmed_size + standard_fields) * SIZEOF_SHORT$1;
    this.addInt16(len);
    let existing_vtable = 0;
    const vt1 = this.space;
    outer_loop: for (i2 = 0; i2 < this.vtables.length; i2++) {
      const vt2 = this.bb.capacity() - this.vtables[i2];
      if (len == this.bb.readInt16(vt2)) {
        for (let j2 = SIZEOF_SHORT$1; j2 < len; j2 += SIZEOF_SHORT$1) {
          if (this.bb.readInt16(vt1 + j2) != this.bb.readInt16(vt2 + j2)) {
            continue outer_loop;
          }
        }
        existing_vtable = this.vtables[i2];
        break;
      }
    }
    if (existing_vtable) {
      this.space = this.bb.capacity() - vtableloc;
      this.bb.writeInt32(this.space, existing_vtable - vtableloc);
    } else {
      this.vtables.push(this.offset());
      this.bb.writeInt32(this.bb.capacity() - vtableloc, this.offset() - vtableloc);
    }
    this.isNested = false;
    return vtableloc;
  }
  /**
   * Finalize a buffer, poiting to the given `root_table`.
   */
  finish(root_table, opt_file_identifier, opt_size_prefix) {
    const size_prefix = opt_size_prefix ? SIZE_PREFIX_LENGTH : 0;
    if (opt_file_identifier) {
      const file_identifier = opt_file_identifier;
      this.prep(this.minalign, SIZEOF_INT$1 + FILE_IDENTIFIER_LENGTH + size_prefix);
      if (file_identifier.length != FILE_IDENTIFIER_LENGTH) {
        throw new TypeError("FlatBuffers: file identifier must be length " + FILE_IDENTIFIER_LENGTH);
      }
      for (let i2 = FILE_IDENTIFIER_LENGTH - 1; i2 >= 0; i2--) {
        this.writeInt8(file_identifier.charCodeAt(i2));
      }
    }
    this.prep(this.minalign, SIZEOF_INT$1 + size_prefix);
    this.addOffset(root_table);
    if (size_prefix) {
      this.addInt32(this.bb.capacity() - this.space);
    }
    this.bb.setPosition(this.space);
  }
  /**
   * Finalize a size prefixed buffer, pointing to the given `root_table`.
   */
  finishSizePrefixed(root_table, opt_file_identifier) {
    this.finish(root_table, opt_file_identifier, true);
  }
  /**
   * This checks a required field has been set in a given table that has
   * just been constructed.
   */
  requiredField(table2, field2) {
    const table_start = this.bb.capacity() - table2;
    const vtable_start = table_start - this.bb.readInt32(table_start);
    const ok = field2 < this.bb.readInt16(vtable_start) && this.bb.readInt16(vtable_start + field2) != 0;
    if (!ok) {
      throw new TypeError("FlatBuffers: field " + field2 + " must be set");
    }
  }
  /**
   * Start a new array/vector of objects.  Users usually will not call
   * this directly. The FlatBuffers compiler will create a start/end
   * method for vector types in generated code.
   *
   * @param elem_size The size of each element in the array
   * @param num_elems The number of elements in the array
   * @param alignment The alignment of the array
   */
  startVector(elem_size, num_elems, alignment) {
    this.notNested();
    this.vector_num_elems = num_elems;
    this.prep(SIZEOF_INT$1, elem_size * num_elems);
    this.prep(alignment, elem_size * num_elems);
  }
  /**
   * Finish off the creation of an array and all its elements. The array must be
   * created with `startVector`.
   *
   * @returns The offset at which the newly created array
   * starts.
   */
  endVector() {
    this.writeInt32(this.vector_num_elems);
    return this.offset();
  }
  /**
   * Encode the string `s` in the buffer using UTF-8. If the string passed has
   * already been seen, we return the offset of the already written string
   *
   * @param s The string to encode
   * @return The offset in the buffer where the encoded string starts
   */
  createSharedString(s) {
    if (!s) {
      return 0;
    }
    if (!this.string_maps) {
      this.string_maps = /* @__PURE__ */ new Map();
    }
    if (this.string_maps.has(s)) {
      return this.string_maps.get(s);
    }
    const offset3 = this.createString(s);
    this.string_maps.set(s, offset3);
    return offset3;
  }
  /**
   * Encode the string `s` in the buffer using UTF-8. If a Uint8Array is passed
   * instead of a string, it is assumed to contain valid UTF-8 encoded data.
   *
   * @param s The string to encode
   * @return The offset in the buffer where the encoded string starts
   */
  createString(s) {
    if (s === null || s === void 0) {
      return 0;
    }
    let utf82;
    if (s instanceof Uint8Array) {
      utf82 = s;
    } else {
      utf82 = this.text_encoder.encode(s);
    }
    this.addInt8(0);
    this.startVector(1, utf82.length, 1);
    this.bb.setPosition(this.space -= utf82.length);
    this.bb.bytes().set(utf82, this.space);
    return this.endVector();
  }
  /**
   * Create a byte vector.
   *
   * @param v The bytes to add
   * @returns The offset in the buffer where the byte vector starts
   */
  createByteVector(v) {
    if (v === null || v === void 0) {
      return 0;
    }
    this.startVector(1, v.length, 1);
    this.bb.setPosition(this.space -= v.length);
    this.bb.bytes().set(v, this.space);
    return this.endVector();
  }
  /**
   * A helper function to pack an object
   *
   * @returns offset of obj
   */
  createObjectOffset(obj) {
    if (obj === null) {
      return 0;
    }
    if (typeof obj === "string") {
      return this.createString(obj);
    } else {
      return obj.pack(this);
    }
  }
  /**
   * A helper function to pack a list of object
   *
   * @returns list of offsets of each non null object
   */
  createObjectOffsetList(list2) {
    const ret = [];
    for (let i2 = 0; i2 < list2.length; ++i2) {
      const val = list2[i2];
      if (val !== null) {
        ret.push(this.createObjectOffset(val));
      } else {
        throw new TypeError("FlatBuffers: Argument for createObjectOffsetList cannot contain null.");
      }
    }
    return ret;
  }
  createStructOffsetList(list2, startFunc) {
    startFunc(this, list2.length);
    this.createObjectOffsetList(list2.slice().reverse());
    return this.endVector();
  }
};
var BodyCompressionMethod;
(function(BodyCompressionMethod2) {
  BodyCompressionMethod2[BodyCompressionMethod2["BUFFER"] = 0] = "BUFFER";
})(BodyCompressionMethod || (BodyCompressionMethod = {}));
var CompressionType;
(function(CompressionType2) {
  CompressionType2[CompressionType2["LZ4_FRAME"] = 0] = "LZ4_FRAME";
  CompressionType2[CompressionType2["ZSTD"] = 1] = "ZSTD";
})(CompressionType || (CompressionType = {}));
let BodyCompression$1 = class BodyCompression {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  static getRootAsBodyCompression(bb, obj) {
    return (obj || new BodyCompression()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static getSizePrefixedRootAsBodyCompression(bb, obj) {
    bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
    return (obj || new BodyCompression()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  /**
   * Compressor library.
   * For LZ4_FRAME, each compressed buffer must consist of a single frame.
   */
  codec() {
    const offset3 = this.bb.__offset(this.bb_pos, 4);
    return offset3 ? this.bb.readInt8(this.bb_pos + offset3) : CompressionType.LZ4_FRAME;
  }
  /**
   * Indicates the way the record batch body was compressed
   */
  method() {
    const offset3 = this.bb.__offset(this.bb_pos, 6);
    return offset3 ? this.bb.readInt8(this.bb_pos + offset3) : BodyCompressionMethod.BUFFER;
  }
  static startBodyCompression(builder2) {
    builder2.startObject(2);
  }
  static addCodec(builder2, codec) {
    builder2.addFieldInt8(0, codec, CompressionType.LZ4_FRAME);
  }
  static addMethod(builder2, method) {
    builder2.addFieldInt8(1, method, BodyCompressionMethod.BUFFER);
  }
  static endBodyCompression(builder2) {
    const offset3 = builder2.endObject();
    return offset3;
  }
  static createBodyCompression(builder2, codec, method) {
    BodyCompression.startBodyCompression(builder2);
    BodyCompression.addCodec(builder2, codec);
    BodyCompression.addMethod(builder2, method);
    return BodyCompression.endBodyCompression(builder2);
  }
};
let Buffer$1 = class Buffer {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  /**
   * The relative offset into the shared memory page where the bytes for this
   * buffer starts
   */
  offset() {
    return this.bb.readInt64(this.bb_pos);
  }
  /**
   * The absolute length (in bytes) of the memory buffer. The memory is found
   * from offset (inclusive) to offset + length (non-inclusive). When building
   * messages using the encapsulated IPC message, padding bytes may be written
   * after a buffer, but such padding bytes do not need to be accounted for in
   * the size here.
   */
  length() {
    return this.bb.readInt64(this.bb_pos + 8);
  }
  static sizeOf() {
    return 16;
  }
  static createBuffer(builder2, offset3, length2) {
    builder2.prep(8, 16);
    builder2.writeInt64(BigInt(length2 !== null && length2 !== void 0 ? length2 : 0));
    builder2.writeInt64(BigInt(offset3 !== null && offset3 !== void 0 ? offset3 : 0));
    return builder2.offset();
  }
};
let FieldNode$1 = class FieldNode {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  /**
   * The number of value slots in the Arrow array at this level of a nested
   * tree
   */
  length() {
    return this.bb.readInt64(this.bb_pos);
  }
  /**
   * The number of observed nulls. Fields with null_count == 0 may choose not
   * to write their physical validity bitmap out as a materialized buffer,
   * instead setting the length of the bitmap buffer to 0.
   */
  nullCount() {
    return this.bb.readInt64(this.bb_pos + 8);
  }
  static sizeOf() {
    return 16;
  }
  static createFieldNode(builder2, length2, null_count) {
    builder2.prep(8, 16);
    builder2.writeInt64(BigInt(null_count !== null && null_count !== void 0 ? null_count : 0));
    builder2.writeInt64(BigInt(length2 !== null && length2 !== void 0 ? length2 : 0));
    return builder2.offset();
  }
};
let RecordBatch$2 = class RecordBatch {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  static getRootAsRecordBatch(bb, obj) {
    return (obj || new RecordBatch()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static getSizePrefixedRootAsRecordBatch(bb, obj) {
    bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
    return (obj || new RecordBatch()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  /**
   * number of records / rows. The arrays in the batch should all have this
   * length
   */
  length() {
    const offset3 = this.bb.__offset(this.bb_pos, 4);
    return offset3 ? this.bb.readInt64(this.bb_pos + offset3) : BigInt("0");
  }
  /**
   * Nodes correspond to the pre-ordered flattened logical schema
   */
  nodes(index, obj) {
    const offset3 = this.bb.__offset(this.bb_pos, 6);
    return offset3 ? (obj || new FieldNode$1()).__init(this.bb.__vector(this.bb_pos + offset3) + index * 16, this.bb) : null;
  }
  nodesLength() {
    const offset3 = this.bb.__offset(this.bb_pos, 6);
    return offset3 ? this.bb.__vector_len(this.bb_pos + offset3) : 0;
  }
  /**
   * Buffers correspond to the pre-ordered flattened buffer tree
   *
   * The number of buffers appended to this list depends on the schema. For
   * example, most primitive arrays will have 2 buffers, 1 for the validity
   * bitmap and 1 for the values. For struct arrays, there will only be a
   * single buffer for the validity (nulls) bitmap
   */
  buffers(index, obj) {
    const offset3 = this.bb.__offset(this.bb_pos, 8);
    return offset3 ? (obj || new Buffer$1()).__init(this.bb.__vector(this.bb_pos + offset3) + index * 16, this.bb) : null;
  }
  buffersLength() {
    const offset3 = this.bb.__offset(this.bb_pos, 8);
    return offset3 ? this.bb.__vector_len(this.bb_pos + offset3) : 0;
  }
  /**
   * Optional compression of the message body
   */
  compression(obj) {
    const offset3 = this.bb.__offset(this.bb_pos, 10);
    return offset3 ? (obj || new BodyCompression$1()).__init(this.bb.__indirect(this.bb_pos + offset3), this.bb) : null;
  }
  static startRecordBatch(builder2) {
    builder2.startObject(4);
  }
  static addLength(builder2, length2) {
    builder2.addFieldInt64(0, length2, BigInt("0"));
  }
  static addNodes(builder2, nodesOffset) {
    builder2.addFieldOffset(1, nodesOffset, 0);
  }
  static startNodesVector(builder2, numElems) {
    builder2.startVector(16, numElems, 8);
  }
  static addBuffers(builder2, buffersOffset) {
    builder2.addFieldOffset(2, buffersOffset, 0);
  }
  static startBuffersVector(builder2, numElems) {
    builder2.startVector(16, numElems, 8);
  }
  static addCompression(builder2, compressionOffset) {
    builder2.addFieldOffset(3, compressionOffset, 0);
  }
  static endRecordBatch(builder2) {
    const offset3 = builder2.endObject();
    return offset3;
  }
};
let DictionaryBatch$2 = class DictionaryBatch {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  static getRootAsDictionaryBatch(bb, obj) {
    return (obj || new DictionaryBatch()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static getSizePrefixedRootAsDictionaryBatch(bb, obj) {
    bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
    return (obj || new DictionaryBatch()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  id() {
    const offset3 = this.bb.__offset(this.bb_pos, 4);
    return offset3 ? this.bb.readInt64(this.bb_pos + offset3) : BigInt("0");
  }
  data(obj) {
    const offset3 = this.bb.__offset(this.bb_pos, 6);
    return offset3 ? (obj || new RecordBatch$2()).__init(this.bb.__indirect(this.bb_pos + offset3), this.bb) : null;
  }
  /**
   * If isDelta is true the values in the dictionary are to be appended to a
   * dictionary with the indicated id. If isDelta is false this dictionary
   * should replace the existing dictionary.
   */
  isDelta() {
    const offset3 = this.bb.__offset(this.bb_pos, 8);
    return offset3 ? !!this.bb.readInt8(this.bb_pos + offset3) : false;
  }
  static startDictionaryBatch(builder2) {
    builder2.startObject(3);
  }
  static addId(builder2, id2) {
    builder2.addFieldInt64(0, id2, BigInt("0"));
  }
  static addData(builder2, dataOffset) {
    builder2.addFieldOffset(1, dataOffset, 0);
  }
  static addIsDelta(builder2, isDelta) {
    builder2.addFieldInt8(2, +isDelta, 0);
  }
  static endDictionaryBatch(builder2) {
    const offset3 = builder2.endObject();
    return offset3;
  }
};
var Endianness$1;
(function(Endianness2) {
  Endianness2[Endianness2["Little"] = 0] = "Little";
  Endianness2[Endianness2["Big"] = 1] = "Big";
})(Endianness$1 || (Endianness$1 = {}));
var DictionaryKind;
(function(DictionaryKind2) {
  DictionaryKind2[DictionaryKind2["DenseArray"] = 0] = "DenseArray";
})(DictionaryKind || (DictionaryKind = {}));
class Int {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  static getRootAsInt(bb, obj) {
    return (obj || new Int()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static getSizePrefixedRootAsInt(bb, obj) {
    bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
    return (obj || new Int()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  bitWidth() {
    const offset3 = this.bb.__offset(this.bb_pos, 4);
    return offset3 ? this.bb.readInt32(this.bb_pos + offset3) : 0;
  }
  isSigned() {
    const offset3 = this.bb.__offset(this.bb_pos, 6);
    return offset3 ? !!this.bb.readInt8(this.bb_pos + offset3) : false;
  }
  static startInt(builder2) {
    builder2.startObject(2);
  }
  static addBitWidth(builder2, bitWidth) {
    builder2.addFieldInt32(0, bitWidth, 0);
  }
  static addIsSigned(builder2, isSigned) {
    builder2.addFieldInt8(1, +isSigned, 0);
  }
  static endInt(builder2) {
    const offset3 = builder2.endObject();
    return offset3;
  }
  static createInt(builder2, bitWidth, isSigned) {
    Int.startInt(builder2);
    Int.addBitWidth(builder2, bitWidth);
    Int.addIsSigned(builder2, isSigned);
    return Int.endInt(builder2);
  }
}
class DictionaryEncoding {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  static getRootAsDictionaryEncoding(bb, obj) {
    return (obj || new DictionaryEncoding()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static getSizePrefixedRootAsDictionaryEncoding(bb, obj) {
    bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
    return (obj || new DictionaryEncoding()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  /**
   * The known dictionary id in the application where this data is used. In
   * the file or streaming formats, the dictionary ids are found in the
   * DictionaryBatch messages
   */
  id() {
    const offset3 = this.bb.__offset(this.bb_pos, 4);
    return offset3 ? this.bb.readInt64(this.bb_pos + offset3) : BigInt("0");
  }
  /**
   * The dictionary indices are constrained to be non-negative integers. If
   * this field is null, the indices must be signed int32. To maximize
   * cross-language compatibility and performance, implementations are
   * recommended to prefer signed integer types over unsigned integer types
   * and to avoid uint64 indices unless they are required by an application.
   */
  indexType(obj) {
    const offset3 = this.bb.__offset(this.bb_pos, 6);
    return offset3 ? (obj || new Int()).__init(this.bb.__indirect(this.bb_pos + offset3), this.bb) : null;
  }
  /**
   * By default, dictionaries are not ordered, or the order does not have
   * semantic meaning. In some statistical, applications, dictionary-encoding
   * is used to represent ordered categorical data, and we provide a way to
   * preserve that metadata here
   */
  isOrdered() {
    const offset3 = this.bb.__offset(this.bb_pos, 8);
    return offset3 ? !!this.bb.readInt8(this.bb_pos + offset3) : false;
  }
  dictionaryKind() {
    const offset3 = this.bb.__offset(this.bb_pos, 10);
    return offset3 ? this.bb.readInt16(this.bb_pos + offset3) : DictionaryKind.DenseArray;
  }
  static startDictionaryEncoding(builder2) {
    builder2.startObject(4);
  }
  static addId(builder2, id2) {
    builder2.addFieldInt64(0, id2, BigInt("0"));
  }
  static addIndexType(builder2, indexTypeOffset) {
    builder2.addFieldOffset(1, indexTypeOffset, 0);
  }
  static addIsOrdered(builder2, isOrdered) {
    builder2.addFieldInt8(2, +isOrdered, 0);
  }
  static addDictionaryKind(builder2, dictionaryKind) {
    builder2.addFieldInt16(3, dictionaryKind, DictionaryKind.DenseArray);
  }
  static endDictionaryEncoding(builder2) {
    const offset3 = builder2.endObject();
    return offset3;
  }
}
class KeyValue {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  static getRootAsKeyValue(bb, obj) {
    return (obj || new KeyValue()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static getSizePrefixedRootAsKeyValue(bb, obj) {
    bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
    return (obj || new KeyValue()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  key(optionalEncoding) {
    const offset3 = this.bb.__offset(this.bb_pos, 4);
    return offset3 ? this.bb.__string(this.bb_pos + offset3, optionalEncoding) : null;
  }
  value(optionalEncoding) {
    const offset3 = this.bb.__offset(this.bb_pos, 6);
    return offset3 ? this.bb.__string(this.bb_pos + offset3, optionalEncoding) : null;
  }
  static startKeyValue(builder2) {
    builder2.startObject(2);
  }
  static addKey(builder2, keyOffset) {
    builder2.addFieldOffset(0, keyOffset, 0);
  }
  static addValue(builder2, valueOffset) {
    builder2.addFieldOffset(1, valueOffset, 0);
  }
  static endKeyValue(builder2) {
    const offset3 = builder2.endObject();
    return offset3;
  }
  static createKeyValue(builder2, keyOffset, valueOffset) {
    KeyValue.startKeyValue(builder2);
    KeyValue.addKey(builder2, keyOffset);
    KeyValue.addValue(builder2, valueOffset);
    return KeyValue.endKeyValue(builder2);
  }
}
let Binary$1 = class Binary {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  static getRootAsBinary(bb, obj) {
    return (obj || new Binary()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static getSizePrefixedRootAsBinary(bb, obj) {
    bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
    return (obj || new Binary()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static startBinary(builder2) {
    builder2.startObject(0);
  }
  static endBinary(builder2) {
    const offset3 = builder2.endObject();
    return offset3;
  }
  static createBinary(builder2) {
    Binary.startBinary(builder2);
    return Binary.endBinary(builder2);
  }
};
let Bool$1 = class Bool {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  static getRootAsBool(bb, obj) {
    return (obj || new Bool()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static getSizePrefixedRootAsBool(bb, obj) {
    bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
    return (obj || new Bool()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static startBool(builder2) {
    builder2.startObject(0);
  }
  static endBool(builder2) {
    const offset3 = builder2.endObject();
    return offset3;
  }
  static createBool(builder2) {
    Bool.startBool(builder2);
    return Bool.endBool(builder2);
  }
};
let Date$1 = class Date2 {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  static getRootAsDate(bb, obj) {
    return (obj || new Date2()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static getSizePrefixedRootAsDate(bb, obj) {
    bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
    return (obj || new Date2()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  unit() {
    const offset3 = this.bb.__offset(this.bb_pos, 4);
    return offset3 ? this.bb.readInt16(this.bb_pos + offset3) : DateUnit$1.MILLISECOND;
  }
  static startDate(builder2) {
    builder2.startObject(1);
  }
  static addUnit(builder2, unit) {
    builder2.addFieldInt16(0, unit, DateUnit$1.MILLISECOND);
  }
  static endDate(builder2) {
    const offset3 = builder2.endObject();
    return offset3;
  }
  static createDate(builder2, unit) {
    Date2.startDate(builder2);
    Date2.addUnit(builder2, unit);
    return Date2.endDate(builder2);
  }
};
let Decimal$1 = class Decimal {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  static getRootAsDecimal(bb, obj) {
    return (obj || new Decimal()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static getSizePrefixedRootAsDecimal(bb, obj) {
    bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
    return (obj || new Decimal()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  /**
   * Total number of decimal digits
   */
  precision() {
    const offset3 = this.bb.__offset(this.bb_pos, 4);
    return offset3 ? this.bb.readInt32(this.bb_pos + offset3) : 0;
  }
  /**
   * Number of digits after the decimal point "."
   */
  scale() {
    const offset3 = this.bb.__offset(this.bb_pos, 6);
    return offset3 ? this.bb.readInt32(this.bb_pos + offset3) : 0;
  }
  /**
   * Number of bits per value. The only accepted widths are 128 and 256.
   * We use bitWidth for consistency with Int::bitWidth.
   */
  bitWidth() {
    const offset3 = this.bb.__offset(this.bb_pos, 8);
    return offset3 ? this.bb.readInt32(this.bb_pos + offset3) : 128;
  }
  static startDecimal(builder2) {
    builder2.startObject(3);
  }
  static addPrecision(builder2, precision) {
    builder2.addFieldInt32(0, precision, 0);
  }
  static addScale(builder2, scale) {
    builder2.addFieldInt32(1, scale, 0);
  }
  static addBitWidth(builder2, bitWidth) {
    builder2.addFieldInt32(2, bitWidth, 128);
  }
  static endDecimal(builder2) {
    const offset3 = builder2.endObject();
    return offset3;
  }
  static createDecimal(builder2, precision, scale, bitWidth) {
    Decimal.startDecimal(builder2);
    Decimal.addPrecision(builder2, precision);
    Decimal.addScale(builder2, scale);
    Decimal.addBitWidth(builder2, bitWidth);
    return Decimal.endDecimal(builder2);
  }
};
let Duration$1 = class Duration {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  static getRootAsDuration(bb, obj) {
    return (obj || new Duration()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static getSizePrefixedRootAsDuration(bb, obj) {
    bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
    return (obj || new Duration()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  unit() {
    const offset3 = this.bb.__offset(this.bb_pos, 4);
    return offset3 ? this.bb.readInt16(this.bb_pos + offset3) : TimeUnit$1.MILLISECOND;
  }
  static startDuration(builder2) {
    builder2.startObject(1);
  }
  static addUnit(builder2, unit) {
    builder2.addFieldInt16(0, unit, TimeUnit$1.MILLISECOND);
  }
  static endDuration(builder2) {
    const offset3 = builder2.endObject();
    return offset3;
  }
  static createDuration(builder2, unit) {
    Duration.startDuration(builder2);
    Duration.addUnit(builder2, unit);
    return Duration.endDuration(builder2);
  }
};
let FixedSizeBinary$1 = class FixedSizeBinary {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  static getRootAsFixedSizeBinary(bb, obj) {
    return (obj || new FixedSizeBinary()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static getSizePrefixedRootAsFixedSizeBinary(bb, obj) {
    bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
    return (obj || new FixedSizeBinary()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  /**
   * Number of bytes per value
   */
  byteWidth() {
    const offset3 = this.bb.__offset(this.bb_pos, 4);
    return offset3 ? this.bb.readInt32(this.bb_pos + offset3) : 0;
  }
  static startFixedSizeBinary(builder2) {
    builder2.startObject(1);
  }
  static addByteWidth(builder2, byteWidth) {
    builder2.addFieldInt32(0, byteWidth, 0);
  }
  static endFixedSizeBinary(builder2) {
    const offset3 = builder2.endObject();
    return offset3;
  }
  static createFixedSizeBinary(builder2, byteWidth) {
    FixedSizeBinary.startFixedSizeBinary(builder2);
    FixedSizeBinary.addByteWidth(builder2, byteWidth);
    return FixedSizeBinary.endFixedSizeBinary(builder2);
  }
};
let FixedSizeList$1 = class FixedSizeList {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  static getRootAsFixedSizeList(bb, obj) {
    return (obj || new FixedSizeList()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static getSizePrefixedRootAsFixedSizeList(bb, obj) {
    bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
    return (obj || new FixedSizeList()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  /**
   * Number of list items per value
   */
  listSize() {
    const offset3 = this.bb.__offset(this.bb_pos, 4);
    return offset3 ? this.bb.readInt32(this.bb_pos + offset3) : 0;
  }
  static startFixedSizeList(builder2) {
    builder2.startObject(1);
  }
  static addListSize(builder2, listSize) {
    builder2.addFieldInt32(0, listSize, 0);
  }
  static endFixedSizeList(builder2) {
    const offset3 = builder2.endObject();
    return offset3;
  }
  static createFixedSizeList(builder2, listSize) {
    FixedSizeList.startFixedSizeList(builder2);
    FixedSizeList.addListSize(builder2, listSize);
    return FixedSizeList.endFixedSizeList(builder2);
  }
};
class FloatingPoint {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  static getRootAsFloatingPoint(bb, obj) {
    return (obj || new FloatingPoint()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static getSizePrefixedRootAsFloatingPoint(bb, obj) {
    bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
    return (obj || new FloatingPoint()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  precision() {
    const offset3 = this.bb.__offset(this.bb_pos, 4);
    return offset3 ? this.bb.readInt16(this.bb_pos + offset3) : Precision$1.HALF;
  }
  static startFloatingPoint(builder2) {
    builder2.startObject(1);
  }
  static addPrecision(builder2, precision) {
    builder2.addFieldInt16(0, precision, Precision$1.HALF);
  }
  static endFloatingPoint(builder2) {
    const offset3 = builder2.endObject();
    return offset3;
  }
  static createFloatingPoint(builder2, precision) {
    FloatingPoint.startFloatingPoint(builder2);
    FloatingPoint.addPrecision(builder2, precision);
    return FloatingPoint.endFloatingPoint(builder2);
  }
}
class Interval {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  static getRootAsInterval(bb, obj) {
    return (obj || new Interval()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static getSizePrefixedRootAsInterval(bb, obj) {
    bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
    return (obj || new Interval()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  unit() {
    const offset3 = this.bb.__offset(this.bb_pos, 4);
    return offset3 ? this.bb.readInt16(this.bb_pos + offset3) : IntervalUnit$1.YEAR_MONTH;
  }
  static startInterval(builder2) {
    builder2.startObject(1);
  }
  static addUnit(builder2, unit) {
    builder2.addFieldInt16(0, unit, IntervalUnit$1.YEAR_MONTH);
  }
  static endInterval(builder2) {
    const offset3 = builder2.endObject();
    return offset3;
  }
  static createInterval(builder2, unit) {
    Interval.startInterval(builder2);
    Interval.addUnit(builder2, unit);
    return Interval.endInterval(builder2);
  }
}
let LargeBinary$1 = class LargeBinary {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  static getRootAsLargeBinary(bb, obj) {
    return (obj || new LargeBinary()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static getSizePrefixedRootAsLargeBinary(bb, obj) {
    bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
    return (obj || new LargeBinary()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static startLargeBinary(builder2) {
    builder2.startObject(0);
  }
  static endLargeBinary(builder2) {
    const offset3 = builder2.endObject();
    return offset3;
  }
  static createLargeBinary(builder2) {
    LargeBinary.startLargeBinary(builder2);
    return LargeBinary.endLargeBinary(builder2);
  }
};
let LargeUtf8$1 = class LargeUtf8 {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  static getRootAsLargeUtf8(bb, obj) {
    return (obj || new LargeUtf8()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static getSizePrefixedRootAsLargeUtf8(bb, obj) {
    bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
    return (obj || new LargeUtf8()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static startLargeUtf8(builder2) {
    builder2.startObject(0);
  }
  static endLargeUtf8(builder2) {
    const offset3 = builder2.endObject();
    return offset3;
  }
  static createLargeUtf8(builder2) {
    LargeUtf8.startLargeUtf8(builder2);
    return LargeUtf8.endLargeUtf8(builder2);
  }
};
let List$1 = class List {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  static getRootAsList(bb, obj) {
    return (obj || new List()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static getSizePrefixedRootAsList(bb, obj) {
    bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
    return (obj || new List()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static startList(builder2) {
    builder2.startObject(0);
  }
  static endList(builder2) {
    const offset3 = builder2.endObject();
    return offset3;
  }
  static createList(builder2) {
    List.startList(builder2);
    return List.endList(builder2);
  }
};
let Map$2 = class Map2 {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  static getRootAsMap(bb, obj) {
    return (obj || new Map2()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static getSizePrefixedRootAsMap(bb, obj) {
    bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
    return (obj || new Map2()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  /**
   * Set to true if the keys within each value are sorted
   */
  keysSorted() {
    const offset3 = this.bb.__offset(this.bb_pos, 4);
    return offset3 ? !!this.bb.readInt8(this.bb_pos + offset3) : false;
  }
  static startMap(builder2) {
    builder2.startObject(1);
  }
  static addKeysSorted(builder2, keysSorted) {
    builder2.addFieldInt8(0, +keysSorted, 0);
  }
  static endMap(builder2) {
    const offset3 = builder2.endObject();
    return offset3;
  }
  static createMap(builder2, keysSorted) {
    Map2.startMap(builder2);
    Map2.addKeysSorted(builder2, keysSorted);
    return Map2.endMap(builder2);
  }
};
let Null$1 = class Null {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  static getRootAsNull(bb, obj) {
    return (obj || new Null()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static getSizePrefixedRootAsNull(bb, obj) {
    bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
    return (obj || new Null()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static startNull(builder2) {
    builder2.startObject(0);
  }
  static endNull(builder2) {
    const offset3 = builder2.endObject();
    return offset3;
  }
  static createNull(builder2) {
    Null.startNull(builder2);
    return Null.endNull(builder2);
  }
};
class Struct_ {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  static getRootAsStruct_(bb, obj) {
    return (obj || new Struct_()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static getSizePrefixedRootAsStruct_(bb, obj) {
    bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
    return (obj || new Struct_()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static startStruct_(builder2) {
    builder2.startObject(0);
  }
  static endStruct_(builder2) {
    const offset3 = builder2.endObject();
    return offset3;
  }
  static createStruct_(builder2) {
    Struct_.startStruct_(builder2);
    return Struct_.endStruct_(builder2);
  }
}
class Time {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  static getRootAsTime(bb, obj) {
    return (obj || new Time()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static getSizePrefixedRootAsTime(bb, obj) {
    bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
    return (obj || new Time()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  unit() {
    const offset3 = this.bb.__offset(this.bb_pos, 4);
    return offset3 ? this.bb.readInt16(this.bb_pos + offset3) : TimeUnit$1.MILLISECOND;
  }
  bitWidth() {
    const offset3 = this.bb.__offset(this.bb_pos, 6);
    return offset3 ? this.bb.readInt32(this.bb_pos + offset3) : 32;
  }
  static startTime(builder2) {
    builder2.startObject(2);
  }
  static addUnit(builder2, unit) {
    builder2.addFieldInt16(0, unit, TimeUnit$1.MILLISECOND);
  }
  static addBitWidth(builder2, bitWidth) {
    builder2.addFieldInt32(1, bitWidth, 32);
  }
  static endTime(builder2) {
    const offset3 = builder2.endObject();
    return offset3;
  }
  static createTime(builder2, unit, bitWidth) {
    Time.startTime(builder2);
    Time.addUnit(builder2, unit);
    Time.addBitWidth(builder2, bitWidth);
    return Time.endTime(builder2);
  }
}
class Timestamp {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  static getRootAsTimestamp(bb, obj) {
    return (obj || new Timestamp()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static getSizePrefixedRootAsTimestamp(bb, obj) {
    bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
    return (obj || new Timestamp()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  unit() {
    const offset3 = this.bb.__offset(this.bb_pos, 4);
    return offset3 ? this.bb.readInt16(this.bb_pos + offset3) : TimeUnit$1.SECOND;
  }
  timezone(optionalEncoding) {
    const offset3 = this.bb.__offset(this.bb_pos, 6);
    return offset3 ? this.bb.__string(this.bb_pos + offset3, optionalEncoding) : null;
  }
  static startTimestamp(builder2) {
    builder2.startObject(2);
  }
  static addUnit(builder2, unit) {
    builder2.addFieldInt16(0, unit, TimeUnit$1.SECOND);
  }
  static addTimezone(builder2, timezoneOffset) {
    builder2.addFieldOffset(1, timezoneOffset, 0);
  }
  static endTimestamp(builder2) {
    const offset3 = builder2.endObject();
    return offset3;
  }
  static createTimestamp(builder2, unit, timezoneOffset) {
    Timestamp.startTimestamp(builder2);
    Timestamp.addUnit(builder2, unit);
    Timestamp.addTimezone(builder2, timezoneOffset);
    return Timestamp.endTimestamp(builder2);
  }
}
class Union {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  static getRootAsUnion(bb, obj) {
    return (obj || new Union()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static getSizePrefixedRootAsUnion(bb, obj) {
    bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
    return (obj || new Union()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  mode() {
    const offset3 = this.bb.__offset(this.bb_pos, 4);
    return offset3 ? this.bb.readInt16(this.bb_pos + offset3) : UnionMode$1.Sparse;
  }
  typeIds(index) {
    const offset3 = this.bb.__offset(this.bb_pos, 6);
    return offset3 ? this.bb.readInt32(this.bb.__vector(this.bb_pos + offset3) + index * 4) : 0;
  }
  typeIdsLength() {
    const offset3 = this.bb.__offset(this.bb_pos, 6);
    return offset3 ? this.bb.__vector_len(this.bb_pos + offset3) : 0;
  }
  typeIdsArray() {
    const offset3 = this.bb.__offset(this.bb_pos, 6);
    return offset3 ? new Int32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset3), this.bb.__vector_len(this.bb_pos + offset3)) : null;
  }
  static startUnion(builder2) {
    builder2.startObject(2);
  }
  static addMode(builder2, mode) {
    builder2.addFieldInt16(0, mode, UnionMode$1.Sparse);
  }
  static addTypeIds(builder2, typeIdsOffset) {
    builder2.addFieldOffset(1, typeIdsOffset, 0);
  }
  static createTypeIdsVector(builder2, data2) {
    builder2.startVector(4, data2.length, 4);
    for (let i2 = data2.length - 1; i2 >= 0; i2--) {
      builder2.addInt32(data2[i2]);
    }
    return builder2.endVector();
  }
  static startTypeIdsVector(builder2, numElems) {
    builder2.startVector(4, numElems, 4);
  }
  static endUnion(builder2) {
    const offset3 = builder2.endObject();
    return offset3;
  }
  static createUnion(builder2, mode, typeIdsOffset) {
    Union.startUnion(builder2);
    Union.addMode(builder2, mode);
    Union.addTypeIds(builder2, typeIdsOffset);
    return Union.endUnion(builder2);
  }
}
let Utf8$1 = class Utf8 {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  static getRootAsUtf8(bb, obj) {
    return (obj || new Utf8()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static getSizePrefixedRootAsUtf8(bb, obj) {
    bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
    return (obj || new Utf8()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static startUtf8(builder2) {
    builder2.startObject(0);
  }
  static endUtf8(builder2) {
    const offset3 = builder2.endObject();
    return offset3;
  }
  static createUtf8(builder2) {
    Utf8.startUtf8(builder2);
    return Utf8.endUtf8(builder2);
  }
};
var Type$2;
(function(Type2) {
  Type2[Type2["NONE"] = 0] = "NONE";
  Type2[Type2["Null"] = 1] = "Null";
  Type2[Type2["Int"] = 2] = "Int";
  Type2[Type2["FloatingPoint"] = 3] = "FloatingPoint";
  Type2[Type2["Binary"] = 4] = "Binary";
  Type2[Type2["Utf8"] = 5] = "Utf8";
  Type2[Type2["Bool"] = 6] = "Bool";
  Type2[Type2["Decimal"] = 7] = "Decimal";
  Type2[Type2["Date"] = 8] = "Date";
  Type2[Type2["Time"] = 9] = "Time";
  Type2[Type2["Timestamp"] = 10] = "Timestamp";
  Type2[Type2["Interval"] = 11] = "Interval";
  Type2[Type2["List"] = 12] = "List";
  Type2[Type2["Struct_"] = 13] = "Struct_";
  Type2[Type2["Union"] = 14] = "Union";
  Type2[Type2["FixedSizeBinary"] = 15] = "FixedSizeBinary";
  Type2[Type2["FixedSizeList"] = 16] = "FixedSizeList";
  Type2[Type2["Map"] = 17] = "Map";
  Type2[Type2["Duration"] = 18] = "Duration";
  Type2[Type2["LargeBinary"] = 19] = "LargeBinary";
  Type2[Type2["LargeUtf8"] = 20] = "LargeUtf8";
  Type2[Type2["LargeList"] = 21] = "LargeList";
  Type2[Type2["RunEndEncoded"] = 22] = "RunEndEncoded";
})(Type$2 || (Type$2 = {}));
let Field$1 = class Field {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  static getRootAsField(bb, obj) {
    return (obj || new Field()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static getSizePrefixedRootAsField(bb, obj) {
    bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
    return (obj || new Field()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  name(optionalEncoding) {
    const offset3 = this.bb.__offset(this.bb_pos, 4);
    return offset3 ? this.bb.__string(this.bb_pos + offset3, optionalEncoding) : null;
  }
  /**
   * Whether or not this field can contain nulls. Should be true in general.
   */
  nullable() {
    const offset3 = this.bb.__offset(this.bb_pos, 6);
    return offset3 ? !!this.bb.readInt8(this.bb_pos + offset3) : false;
  }
  typeType() {
    const offset3 = this.bb.__offset(this.bb_pos, 8);
    return offset3 ? this.bb.readUint8(this.bb_pos + offset3) : Type$2.NONE;
  }
  /**
   * This is the type of the decoded value if the field is dictionary encoded.
   */
  type(obj) {
    const offset3 = this.bb.__offset(this.bb_pos, 10);
    return offset3 ? this.bb.__union(obj, this.bb_pos + offset3) : null;
  }
  /**
   * Present only if the field is dictionary encoded.
   */
  dictionary(obj) {
    const offset3 = this.bb.__offset(this.bb_pos, 12);
    return offset3 ? (obj || new DictionaryEncoding()).__init(this.bb.__indirect(this.bb_pos + offset3), this.bb) : null;
  }
  /**
   * children apply only to nested data types like Struct, List and Union. For
   * primitive types children will have length 0.
   */
  children(index, obj) {
    const offset3 = this.bb.__offset(this.bb_pos, 14);
    return offset3 ? (obj || new Field()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset3) + index * 4), this.bb) : null;
  }
  childrenLength() {
    const offset3 = this.bb.__offset(this.bb_pos, 14);
    return offset3 ? this.bb.__vector_len(this.bb_pos + offset3) : 0;
  }
  /**
   * User-defined metadata
   */
  customMetadata(index, obj) {
    const offset3 = this.bb.__offset(this.bb_pos, 16);
    return offset3 ? (obj || new KeyValue()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset3) + index * 4), this.bb) : null;
  }
  customMetadataLength() {
    const offset3 = this.bb.__offset(this.bb_pos, 16);
    return offset3 ? this.bb.__vector_len(this.bb_pos + offset3) : 0;
  }
  static startField(builder2) {
    builder2.startObject(7);
  }
  static addName(builder2, nameOffset) {
    builder2.addFieldOffset(0, nameOffset, 0);
  }
  static addNullable(builder2, nullable) {
    builder2.addFieldInt8(1, +nullable, 0);
  }
  static addTypeType(builder2, typeType) {
    builder2.addFieldInt8(2, typeType, Type$2.NONE);
  }
  static addType(builder2, typeOffset) {
    builder2.addFieldOffset(3, typeOffset, 0);
  }
  static addDictionary(builder2, dictionaryOffset) {
    builder2.addFieldOffset(4, dictionaryOffset, 0);
  }
  static addChildren(builder2, childrenOffset) {
    builder2.addFieldOffset(5, childrenOffset, 0);
  }
  static createChildrenVector(builder2, data2) {
    builder2.startVector(4, data2.length, 4);
    for (let i2 = data2.length - 1; i2 >= 0; i2--) {
      builder2.addOffset(data2[i2]);
    }
    return builder2.endVector();
  }
  static startChildrenVector(builder2, numElems) {
    builder2.startVector(4, numElems, 4);
  }
  static addCustomMetadata(builder2, customMetadataOffset) {
    builder2.addFieldOffset(6, customMetadataOffset, 0);
  }
  static createCustomMetadataVector(builder2, data2) {
    builder2.startVector(4, data2.length, 4);
    for (let i2 = data2.length - 1; i2 >= 0; i2--) {
      builder2.addOffset(data2[i2]);
    }
    return builder2.endVector();
  }
  static startCustomMetadataVector(builder2, numElems) {
    builder2.startVector(4, numElems, 4);
  }
  static endField(builder2) {
    const offset3 = builder2.endObject();
    return offset3;
  }
};
let Schema$1 = class Schema {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  static getRootAsSchema(bb, obj) {
    return (obj || new Schema()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static getSizePrefixedRootAsSchema(bb, obj) {
    bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
    return (obj || new Schema()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  /**
   * endianness of the buffer
   * it is Little Endian by default
   * if endianness doesn't match the underlying system then the vectors need to be converted
   */
  endianness() {
    const offset3 = this.bb.__offset(this.bb_pos, 4);
    return offset3 ? this.bb.readInt16(this.bb_pos + offset3) : Endianness$1.Little;
  }
  fields(index, obj) {
    const offset3 = this.bb.__offset(this.bb_pos, 6);
    return offset3 ? (obj || new Field$1()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset3) + index * 4), this.bb) : null;
  }
  fieldsLength() {
    const offset3 = this.bb.__offset(this.bb_pos, 6);
    return offset3 ? this.bb.__vector_len(this.bb_pos + offset3) : 0;
  }
  customMetadata(index, obj) {
    const offset3 = this.bb.__offset(this.bb_pos, 8);
    return offset3 ? (obj || new KeyValue()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset3) + index * 4), this.bb) : null;
  }
  customMetadataLength() {
    const offset3 = this.bb.__offset(this.bb_pos, 8);
    return offset3 ? this.bb.__vector_len(this.bb_pos + offset3) : 0;
  }
  /**
   * Features used in the stream/file.
   */
  features(index) {
    const offset3 = this.bb.__offset(this.bb_pos, 10);
    return offset3 ? this.bb.readInt64(this.bb.__vector(this.bb_pos + offset3) + index * 8) : BigInt(0);
  }
  featuresLength() {
    const offset3 = this.bb.__offset(this.bb_pos, 10);
    return offset3 ? this.bb.__vector_len(this.bb_pos + offset3) : 0;
  }
  static startSchema(builder2) {
    builder2.startObject(4);
  }
  static addEndianness(builder2, endianness) {
    builder2.addFieldInt16(0, endianness, Endianness$1.Little);
  }
  static addFields(builder2, fieldsOffset) {
    builder2.addFieldOffset(1, fieldsOffset, 0);
  }
  static createFieldsVector(builder2, data2) {
    builder2.startVector(4, data2.length, 4);
    for (let i2 = data2.length - 1; i2 >= 0; i2--) {
      builder2.addOffset(data2[i2]);
    }
    return builder2.endVector();
  }
  static startFieldsVector(builder2, numElems) {
    builder2.startVector(4, numElems, 4);
  }
  static addCustomMetadata(builder2, customMetadataOffset) {
    builder2.addFieldOffset(2, customMetadataOffset, 0);
  }
  static createCustomMetadataVector(builder2, data2) {
    builder2.startVector(4, data2.length, 4);
    for (let i2 = data2.length - 1; i2 >= 0; i2--) {
      builder2.addOffset(data2[i2]);
    }
    return builder2.endVector();
  }
  static startCustomMetadataVector(builder2, numElems) {
    builder2.startVector(4, numElems, 4);
  }
  static addFeatures(builder2, featuresOffset) {
    builder2.addFieldOffset(3, featuresOffset, 0);
  }
  static createFeaturesVector(builder2, data2) {
    builder2.startVector(8, data2.length, 8);
    for (let i2 = data2.length - 1; i2 >= 0; i2--) {
      builder2.addInt64(data2[i2]);
    }
    return builder2.endVector();
  }
  static startFeaturesVector(builder2, numElems) {
    builder2.startVector(8, numElems, 8);
  }
  static endSchema(builder2) {
    const offset3 = builder2.endObject();
    return offset3;
  }
  static finishSchemaBuffer(builder2, offset3) {
    builder2.finish(offset3);
  }
  static finishSizePrefixedSchemaBuffer(builder2, offset3) {
    builder2.finish(offset3, void 0, true);
  }
  static createSchema(builder2, endianness, fieldsOffset, customMetadataOffset, featuresOffset) {
    Schema.startSchema(builder2);
    Schema.addEndianness(builder2, endianness);
    Schema.addFields(builder2, fieldsOffset);
    Schema.addCustomMetadata(builder2, customMetadataOffset);
    Schema.addFeatures(builder2, featuresOffset);
    return Schema.endSchema(builder2);
  }
};
var MessageHeader$1;
(function(MessageHeader2) {
  MessageHeader2[MessageHeader2["NONE"] = 0] = "NONE";
  MessageHeader2[MessageHeader2["Schema"] = 1] = "Schema";
  MessageHeader2[MessageHeader2["DictionaryBatch"] = 2] = "DictionaryBatch";
  MessageHeader2[MessageHeader2["RecordBatch"] = 3] = "RecordBatch";
  MessageHeader2[MessageHeader2["Tensor"] = 4] = "Tensor";
  MessageHeader2[MessageHeader2["SparseTensor"] = 5] = "SparseTensor";
})(MessageHeader$1 || (MessageHeader$1 = {}));
var Type$1;
(function(Type2) {
  Type2[Type2["NONE"] = 0] = "NONE";
  Type2[Type2["Null"] = 1] = "Null";
  Type2[Type2["Int"] = 2] = "Int";
  Type2[Type2["Float"] = 3] = "Float";
  Type2[Type2["Binary"] = 4] = "Binary";
  Type2[Type2["Utf8"] = 5] = "Utf8";
  Type2[Type2["Bool"] = 6] = "Bool";
  Type2[Type2["Decimal"] = 7] = "Decimal";
  Type2[Type2["Date"] = 8] = "Date";
  Type2[Type2["Time"] = 9] = "Time";
  Type2[Type2["Timestamp"] = 10] = "Timestamp";
  Type2[Type2["Interval"] = 11] = "Interval";
  Type2[Type2["List"] = 12] = "List";
  Type2[Type2["Struct"] = 13] = "Struct";
  Type2[Type2["Union"] = 14] = "Union";
  Type2[Type2["FixedSizeBinary"] = 15] = "FixedSizeBinary";
  Type2[Type2["FixedSizeList"] = 16] = "FixedSizeList";
  Type2[Type2["Map"] = 17] = "Map";
  Type2[Type2["Duration"] = 18] = "Duration";
  Type2[Type2["LargeBinary"] = 19] = "LargeBinary";
  Type2[Type2["LargeUtf8"] = 20] = "LargeUtf8";
  Type2[Type2["Dictionary"] = -1] = "Dictionary";
  Type2[Type2["Int8"] = -2] = "Int8";
  Type2[Type2["Int16"] = -3] = "Int16";
  Type2[Type2["Int32"] = -4] = "Int32";
  Type2[Type2["Int64"] = -5] = "Int64";
  Type2[Type2["Uint8"] = -6] = "Uint8";
  Type2[Type2["Uint16"] = -7] = "Uint16";
  Type2[Type2["Uint32"] = -8] = "Uint32";
  Type2[Type2["Uint64"] = -9] = "Uint64";
  Type2[Type2["Float16"] = -10] = "Float16";
  Type2[Type2["Float32"] = -11] = "Float32";
  Type2[Type2["Float64"] = -12] = "Float64";
  Type2[Type2["DateDay"] = -13] = "DateDay";
  Type2[Type2["DateMillisecond"] = -14] = "DateMillisecond";
  Type2[Type2["TimestampSecond"] = -15] = "TimestampSecond";
  Type2[Type2["TimestampMillisecond"] = -16] = "TimestampMillisecond";
  Type2[Type2["TimestampMicrosecond"] = -17] = "TimestampMicrosecond";
  Type2[Type2["TimestampNanosecond"] = -18] = "TimestampNanosecond";
  Type2[Type2["TimeSecond"] = -19] = "TimeSecond";
  Type2[Type2["TimeMillisecond"] = -20] = "TimeMillisecond";
  Type2[Type2["TimeMicrosecond"] = -21] = "TimeMicrosecond";
  Type2[Type2["TimeNanosecond"] = -22] = "TimeNanosecond";
  Type2[Type2["DenseUnion"] = -23] = "DenseUnion";
  Type2[Type2["SparseUnion"] = -24] = "SparseUnion";
  Type2[Type2["IntervalDayTime"] = -25] = "IntervalDayTime";
  Type2[Type2["IntervalYearMonth"] = -26] = "IntervalYearMonth";
  Type2[Type2["DurationSecond"] = -27] = "DurationSecond";
  Type2[Type2["DurationMillisecond"] = -28] = "DurationMillisecond";
  Type2[Type2["DurationMicrosecond"] = -29] = "DurationMicrosecond";
  Type2[Type2["DurationNanosecond"] = -30] = "DurationNanosecond";
  Type2[Type2["IntervalMonthDayNano"] = -31] = "IntervalMonthDayNano";
})(Type$1 || (Type$1 = {}));
var BufferType;
(function(BufferType2) {
  BufferType2[BufferType2["OFFSET"] = 0] = "OFFSET";
  BufferType2[BufferType2["DATA"] = 1] = "DATA";
  BufferType2[BufferType2["VALIDITY"] = 2] = "VALIDITY";
  BufferType2[BufferType2["TYPE"] = 3] = "TYPE";
})(BufferType || (BufferType = {}));
const undf = void 0;
function valueToString(x) {
  if (x === null) {
    return "null";
  }
  if (x === undf) {
    return "undefined";
  }
  switch (typeof x) {
    case "number":
      return `${x}`;
    case "bigint":
      return `${x}`;
    case "string":
      return `"${x}"`;
  }
  if (typeof x[Symbol.toPrimitive] === "function") {
    return x[Symbol.toPrimitive]("string");
  }
  if (ArrayBuffer.isView(x)) {
    if (x instanceof BigInt64Array || x instanceof BigUint64Array) {
      return `[${[...x].map((x2) => valueToString(x2))}]`;
    }
    return `[${x}]`;
  }
  return ArrayBuffer.isView(x) ? `[${x}]` : JSON.stringify(x, (_, y) => typeof y === "bigint" ? `${y}` : y);
}
function bigIntToNumber(number2) {
  if (typeof number2 === "bigint" && (number2 < Number.MIN_SAFE_INTEGER || number2 > Number.MAX_SAFE_INTEGER)) {
    throw new TypeError(`${number2} is not safe to convert to a number.`);
  }
  return Number(number2);
}
function divideBigInts(number2, divisor) {
  return bigIntToNumber(number2 / divisor) + bigIntToNumber(number2 % divisor) / bigIntToNumber(divisor);
}
const isArrowBigNumSymbol = Symbol.for("isArrowBigNum");
function BigNum(x, ...xs) {
  if (xs.length === 0) {
    return Object.setPrototypeOf(toArrayBufferView(this["TypedArray"], x), this.constructor.prototype);
  }
  return Object.setPrototypeOf(new this["TypedArray"](x, ...xs), this.constructor.prototype);
}
BigNum.prototype[isArrowBigNumSymbol] = true;
BigNum.prototype.toJSON = function() {
  return `"${bigNumToString(this)}"`;
};
BigNum.prototype.valueOf = function(scale) {
  return bigNumToNumber(this, scale);
};
BigNum.prototype.toString = function() {
  return bigNumToString(this);
};
BigNum.prototype[Symbol.toPrimitive] = function(hint = "default") {
  switch (hint) {
    case "number":
      return bigNumToNumber(this);
    case "string":
      return bigNumToString(this);
    case "default":
      return bigNumToBigInt(this);
  }
  return bigNumToString(this);
};
function SignedBigNum(...args2) {
  return BigNum.apply(this, args2);
}
function UnsignedBigNum(...args2) {
  return BigNum.apply(this, args2);
}
function DecimalBigNum(...args2) {
  return BigNum.apply(this, args2);
}
Object.setPrototypeOf(SignedBigNum.prototype, Object.create(Int32Array.prototype));
Object.setPrototypeOf(UnsignedBigNum.prototype, Object.create(Uint32Array.prototype));
Object.setPrototypeOf(DecimalBigNum.prototype, Object.create(Uint32Array.prototype));
Object.assign(SignedBigNum.prototype, BigNum.prototype, { "constructor": SignedBigNum, "signed": true, "TypedArray": Int32Array, "BigIntArray": BigInt64Array });
Object.assign(UnsignedBigNum.prototype, BigNum.prototype, { "constructor": UnsignedBigNum, "signed": false, "TypedArray": Uint32Array, "BigIntArray": BigUint64Array });
Object.assign(DecimalBigNum.prototype, BigNum.prototype, { "constructor": DecimalBigNum, "signed": true, "TypedArray": Uint32Array, "BigIntArray": BigUint64Array });
const TWO_TO_THE_64 = BigInt(4294967296) * BigInt(4294967296);
const TWO_TO_THE_64_MINUS_1 = TWO_TO_THE_64 - BigInt(1);
function bigNumToNumber(bn2, scale) {
  const { buffer: buffer2, byteOffset, byteLength, "signed": signed } = bn2;
  const words = new BigUint64Array(buffer2, byteOffset, byteLength / 8);
  const negative = signed && words.at(-1) & BigInt(1) << BigInt(63);
  let number2 = BigInt(0);
  let i2 = 0;
  if (negative) {
    for (const word of words) {
      number2 |= (word ^ TWO_TO_THE_64_MINUS_1) * (BigInt(1) << BigInt(64 * i2++));
    }
    number2 *= BigInt(-1);
    number2 -= BigInt(1);
  } else {
    for (const word of words) {
      number2 |= word * (BigInt(1) << BigInt(64 * i2++));
    }
  }
  if (typeof scale === "number" && scale > 0) {
    const denominator = BigInt("1".padEnd(scale + 1, "0"));
    const quotient = number2 / denominator;
    const remainder = negative ? -(number2 % denominator) : number2 % denominator;
    const integerPart = bigIntToNumber(quotient);
    const fractionPart = `${remainder}`.padStart(scale, "0");
    const sign2 = negative && integerPart === 0 ? "-" : "";
    return +`${sign2}${integerPart}.${fractionPart}`;
  }
  return bigIntToNumber(number2);
}
function bigNumToString(a2) {
  if (a2.byteLength === 8) {
    const bigIntArray = new a2["BigIntArray"](a2.buffer, a2.byteOffset, 1);
    return `${bigIntArray[0]}`;
  }
  if (!a2["signed"]) {
    return unsignedBigNumToString(a2);
  }
  let array2 = new Uint16Array(a2.buffer, a2.byteOffset, a2.byteLength / 2);
  const highOrderWord = new Int16Array([array2.at(-1)])[0];
  if (highOrderWord >= 0) {
    return unsignedBigNumToString(a2);
  }
  array2 = array2.slice();
  let carry = 1;
  for (let i2 = 0; i2 < array2.length; i2++) {
    const elem = array2[i2];
    const updated = ~elem + carry;
    array2[i2] = updated;
    carry &= elem === 0 ? 1 : 0;
  }
  const negated = unsignedBigNumToString(array2);
  return `-${negated}`;
}
function bigNumToBigInt(a2) {
  if (a2.byteLength === 8) {
    const bigIntArray = new a2["BigIntArray"](a2.buffer, a2.byteOffset, 1);
    return bigIntArray[0];
  } else {
    return bigNumToString(a2);
  }
}
function unsignedBigNumToString(a2) {
  let digits = "";
  const base64 = new Uint32Array(2);
  let base32 = new Uint16Array(a2.buffer, a2.byteOffset, a2.byteLength / 2);
  const checks = new Uint32Array((base32 = new Uint16Array(base32).reverse()).buffer);
  let i2 = -1;
  const n2 = base32.length - 1;
  do {
    for (base64[0] = base32[i2 = 0]; i2 < n2; ) {
      base32[i2++] = base64[1] = base64[0] / 10;
      base64[0] = (base64[0] - base64[1] * 10 << 16) + base32[i2];
    }
    base32[i2] = base64[1] = base64[0] / 10;
    base64[0] = base64[0] - base64[1] * 10;
    digits = `${base64[0]}${digits}`;
  } while (checks[0] || checks[1] || checks[2] || checks[3]);
  return digits !== null && digits !== void 0 ? digits : `0`;
}
class BN {
  /** @nocollapse */
  static new(num, isSigned) {
    switch (isSigned) {
      case true:
        return new SignedBigNum(num);
      case false:
        return new UnsignedBigNum(num);
    }
    switch (num.constructor) {
      case Int8Array:
      case Int16Array:
      case Int32Array:
      case BigInt64Array:
        return new SignedBigNum(num);
    }
    if (num.byteLength === 16) {
      return new DecimalBigNum(num);
    }
    return new UnsignedBigNum(num);
  }
  /** @nocollapse */
  static signed(num) {
    return new SignedBigNum(num);
  }
  /** @nocollapse */
  static unsigned(num) {
    return new UnsignedBigNum(num);
  }
  /** @nocollapse */
  static decimal(num) {
    return new DecimalBigNum(num);
  }
  constructor(num, isSigned) {
    return BN.new(num, isSigned);
  }
}
var _a$5, _b, _c, _d, _e$1, _f, _g, _h, _j, _k, _l, _m, _o$1, _p, _q, _r, _s, _t, _u, _v, _w, _x;
class DataType {
  /** @nocollapse */
  static isNull(x) {
    return (x === null || x === void 0 ? void 0 : x.typeId) === Type$1.Null;
  }
  /** @nocollapse */
  static isInt(x) {
    return (x === null || x === void 0 ? void 0 : x.typeId) === Type$1.Int;
  }
  /** @nocollapse */
  static isFloat(x) {
    return (x === null || x === void 0 ? void 0 : x.typeId) === Type$1.Float;
  }
  /** @nocollapse */
  static isBinary(x) {
    return (x === null || x === void 0 ? void 0 : x.typeId) === Type$1.Binary;
  }
  /** @nocollapse */
  static isLargeBinary(x) {
    return (x === null || x === void 0 ? void 0 : x.typeId) === Type$1.LargeBinary;
  }
  /** @nocollapse */
  static isUtf8(x) {
    return (x === null || x === void 0 ? void 0 : x.typeId) === Type$1.Utf8;
  }
  /** @nocollapse */
  static isLargeUtf8(x) {
    return (x === null || x === void 0 ? void 0 : x.typeId) === Type$1.LargeUtf8;
  }
  /** @nocollapse */
  static isBool(x) {
    return (x === null || x === void 0 ? void 0 : x.typeId) === Type$1.Bool;
  }
  /** @nocollapse */
  static isDecimal(x) {
    return (x === null || x === void 0 ? void 0 : x.typeId) === Type$1.Decimal;
  }
  /** @nocollapse */
  static isDate(x) {
    return (x === null || x === void 0 ? void 0 : x.typeId) === Type$1.Date;
  }
  /** @nocollapse */
  static isTime(x) {
    return (x === null || x === void 0 ? void 0 : x.typeId) === Type$1.Time;
  }
  /** @nocollapse */
  static isTimestamp(x) {
    return (x === null || x === void 0 ? void 0 : x.typeId) === Type$1.Timestamp;
  }
  /** @nocollapse */
  static isInterval(x) {
    return (x === null || x === void 0 ? void 0 : x.typeId) === Type$1.Interval;
  }
  /** @nocollapse */
  static isDuration(x) {
    return (x === null || x === void 0 ? void 0 : x.typeId) === Type$1.Duration;
  }
  /** @nocollapse */
  static isList(x) {
    return (x === null || x === void 0 ? void 0 : x.typeId) === Type$1.List;
  }
  /** @nocollapse */
  static isStruct(x) {
    return (x === null || x === void 0 ? void 0 : x.typeId) === Type$1.Struct;
  }
  /** @nocollapse */
  static isUnion(x) {
    return (x === null || x === void 0 ? void 0 : x.typeId) === Type$1.Union;
  }
  /** @nocollapse */
  static isFixedSizeBinary(x) {
    return (x === null || x === void 0 ? void 0 : x.typeId) === Type$1.FixedSizeBinary;
  }
  /** @nocollapse */
  static isFixedSizeList(x) {
    return (x === null || x === void 0 ? void 0 : x.typeId) === Type$1.FixedSizeList;
  }
  /** @nocollapse */
  static isMap(x) {
    return (x === null || x === void 0 ? void 0 : x.typeId) === Type$1.Map;
  }
  /** @nocollapse */
  static isDictionary(x) {
    return (x === null || x === void 0 ? void 0 : x.typeId) === Type$1.Dictionary;
  }
  /** @nocollapse */
  static isDenseUnion(x) {
    return DataType.isUnion(x) && x.mode === UnionMode$1.Dense;
  }
  /** @nocollapse */
  static isSparseUnion(x) {
    return DataType.isUnion(x) && x.mode === UnionMode$1.Sparse;
  }
  constructor(typeId) {
    this.typeId = typeId;
  }
}
_a$5 = Symbol.toStringTag;
DataType[_a$5] = ((proto) => {
  proto.children = null;
  proto.ArrayType = Array;
  proto.OffsetArrayType = Int32Array;
  return proto[Symbol.toStringTag] = "DataType";
})(DataType.prototype);
class Null2 extends DataType {
  constructor() {
    super(Type$1.Null);
  }
  toString() {
    return `Null`;
  }
}
_b = Symbol.toStringTag;
Null2[_b] = ((proto) => proto[Symbol.toStringTag] = "Null")(Null2.prototype);
class Int_ extends DataType {
  constructor(isSigned, bitWidth) {
    super(Type$1.Int);
    this.isSigned = isSigned;
    this.bitWidth = bitWidth;
  }
  get ArrayType() {
    switch (this.bitWidth) {
      case 8:
        return this.isSigned ? Int8Array : Uint8Array;
      case 16:
        return this.isSigned ? Int16Array : Uint16Array;
      case 32:
        return this.isSigned ? Int32Array : Uint32Array;
      case 64:
        return this.isSigned ? BigInt64Array : BigUint64Array;
    }
    throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`);
  }
  toString() {
    return `${this.isSigned ? `I` : `Ui`}nt${this.bitWidth}`;
  }
}
_c = Symbol.toStringTag;
Int_[_c] = ((proto) => {
  proto.isSigned = null;
  proto.bitWidth = null;
  return proto[Symbol.toStringTag] = "Int";
})(Int_.prototype);
class Int32 extends Int_ {
  constructor() {
    super(true, 32);
  }
  get ArrayType() {
    return Int32Array;
  }
}
Object.defineProperty(Int32.prototype, "ArrayType", { value: Int32Array });
class Float extends DataType {
  constructor(precision) {
    super(Type$1.Float);
    this.precision = precision;
  }
  get ArrayType() {
    switch (this.precision) {
      case Precision$1.HALF:
        return Uint16Array;
      case Precision$1.SINGLE:
        return Float32Array;
      case Precision$1.DOUBLE:
        return Float64Array;
    }
    throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`);
  }
  toString() {
    return `Float${this.precision << 5 || 16}`;
  }
}
_d = Symbol.toStringTag;
Float[_d] = ((proto) => {
  proto.precision = null;
  return proto[Symbol.toStringTag] = "Float";
})(Float.prototype);
class Binary2 extends DataType {
  constructor() {
    super(Type$1.Binary);
  }
  toString() {
    return `Binary`;
  }
}
_e$1 = Symbol.toStringTag;
Binary2[_e$1] = ((proto) => {
  proto.ArrayType = Uint8Array;
  return proto[Symbol.toStringTag] = "Binary";
})(Binary2.prototype);
class LargeBinary2 extends DataType {
  constructor() {
    super(Type$1.LargeBinary);
  }
  toString() {
    return `LargeBinary`;
  }
}
_f = Symbol.toStringTag;
LargeBinary2[_f] = ((proto) => {
  proto.ArrayType = Uint8Array;
  proto.OffsetArrayType = BigInt64Array;
  return proto[Symbol.toStringTag] = "LargeBinary";
})(LargeBinary2.prototype);
class Utf82 extends DataType {
  constructor() {
    super(Type$1.Utf8);
  }
  toString() {
    return `Utf8`;
  }
}
_g = Symbol.toStringTag;
Utf82[_g] = ((proto) => {
  proto.ArrayType = Uint8Array;
  return proto[Symbol.toStringTag] = "Utf8";
})(Utf82.prototype);
class LargeUtf82 extends DataType {
  constructor() {
    super(Type$1.LargeUtf8);
  }
  toString() {
    return `LargeUtf8`;
  }
}
_h = Symbol.toStringTag;
LargeUtf82[_h] = ((proto) => {
  proto.ArrayType = Uint8Array;
  proto.OffsetArrayType = BigInt64Array;
  return proto[Symbol.toStringTag] = "LargeUtf8";
})(LargeUtf82.prototype);
class Bool2 extends DataType {
  constructor() {
    super(Type$1.Bool);
  }
  toString() {
    return `Bool`;
  }
}
_j = Symbol.toStringTag;
Bool2[_j] = ((proto) => {
  proto.ArrayType = Uint8Array;
  return proto[Symbol.toStringTag] = "Bool";
})(Bool2.prototype);
class Decimal2 extends DataType {
  constructor(scale, precision, bitWidth = 128) {
    super(Type$1.Decimal);
    this.scale = scale;
    this.precision = precision;
    this.bitWidth = bitWidth;
  }
  toString() {
    return `Decimal[${this.precision}e${this.scale > 0 ? `+` : ``}${this.scale}]`;
  }
}
_k = Symbol.toStringTag;
Decimal2[_k] = ((proto) => {
  proto.scale = null;
  proto.precision = null;
  proto.ArrayType = Uint32Array;
  return proto[Symbol.toStringTag] = "Decimal";
})(Decimal2.prototype);
class Date_ extends DataType {
  constructor(unit) {
    super(Type$1.Date);
    this.unit = unit;
  }
  toString() {
    return `Date${(this.unit + 1) * 32}<${DateUnit$1[this.unit]}>`;
  }
  get ArrayType() {
    return this.unit === DateUnit$1.DAY ? Int32Array : BigInt64Array;
  }
}
_l = Symbol.toStringTag;
Date_[_l] = ((proto) => {
  proto.unit = null;
  return proto[Symbol.toStringTag] = "Date";
})(Date_.prototype);
class Time_ extends DataType {
  constructor(unit, bitWidth) {
    super(Type$1.Time);
    this.unit = unit;
    this.bitWidth = bitWidth;
  }
  toString() {
    return `Time${this.bitWidth}<${TimeUnit$1[this.unit]}>`;
  }
  get ArrayType() {
    switch (this.bitWidth) {
      case 32:
        return Int32Array;
      case 64:
        return BigInt64Array;
    }
    throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`);
  }
}
_m = Symbol.toStringTag;
Time_[_m] = ((proto) => {
  proto.unit = null;
  proto.bitWidth = null;
  return proto[Symbol.toStringTag] = "Time";
})(Time_.prototype);
class Timestamp_ extends DataType {
  constructor(unit, timezone) {
    super(Type$1.Timestamp);
    this.unit = unit;
    this.timezone = timezone;
  }
  toString() {
    return `Timestamp<${TimeUnit$1[this.unit]}${this.timezone ? `, ${this.timezone}` : ``}>`;
  }
}
_o$1 = Symbol.toStringTag;
Timestamp_[_o$1] = ((proto) => {
  proto.unit = null;
  proto.timezone = null;
  proto.ArrayType = BigInt64Array;
  return proto[Symbol.toStringTag] = "Timestamp";
})(Timestamp_.prototype);
class Interval_ extends DataType {
  constructor(unit) {
    super(Type$1.Interval);
    this.unit = unit;
  }
  toString() {
    return `Interval<${IntervalUnit$1[this.unit]}>`;
  }
}
_p = Symbol.toStringTag;
Interval_[_p] = ((proto) => {
  proto.unit = null;
  proto.ArrayType = Int32Array;
  return proto[Symbol.toStringTag] = "Interval";
})(Interval_.prototype);
class Duration2 extends DataType {
  constructor(unit) {
    super(Type$1.Duration);
    this.unit = unit;
  }
  toString() {
    return `Duration<${TimeUnit$1[this.unit]}>`;
  }
}
_q = Symbol.toStringTag;
Duration2[_q] = ((proto) => {
  proto.unit = null;
  proto.ArrayType = BigInt64Array;
  return proto[Symbol.toStringTag] = "Duration";
})(Duration2.prototype);
class List2 extends DataType {
  constructor(child) {
    super(Type$1.List);
    this.children = [child];
  }
  toString() {
    return `List<${this.valueType}>`;
  }
  get valueType() {
    return this.children[0].type;
  }
  get valueField() {
    return this.children[0];
  }
  get ArrayType() {
    return this.valueType.ArrayType;
  }
}
_r = Symbol.toStringTag;
List2[_r] = ((proto) => {
  proto.children = null;
  return proto[Symbol.toStringTag] = "List";
})(List2.prototype);
class Struct extends DataType {
  constructor(children2) {
    super(Type$1.Struct);
    this.children = children2;
  }
  toString() {
    return `Struct<{${this.children.map((f) => `${f.name}:${f.type}`).join(`, `)}}>`;
  }
}
_s = Symbol.toStringTag;
Struct[_s] = ((proto) => {
  proto.children = null;
  return proto[Symbol.toStringTag] = "Struct";
})(Struct.prototype);
class Union_ extends DataType {
  constructor(mode, typeIds, children2) {
    super(Type$1.Union);
    this.mode = mode;
    this.children = children2;
    this.typeIds = typeIds = Int32Array.from(typeIds);
    this.typeIdToChildIndex = typeIds.reduce((typeIdToChildIndex, typeId, idx) => (typeIdToChildIndex[typeId] = idx) && typeIdToChildIndex || typeIdToChildIndex, /* @__PURE__ */ Object.create(null));
  }
  toString() {
    return `${this[Symbol.toStringTag]}<${this.children.map((x) => `${x.type}`).join(` | `)}>`;
  }
}
_t = Symbol.toStringTag;
Union_[_t] = ((proto) => {
  proto.mode = null;
  proto.typeIds = null;
  proto.children = null;
  proto.typeIdToChildIndex = null;
  proto.ArrayType = Int8Array;
  return proto[Symbol.toStringTag] = "Union";
})(Union_.prototype);
class FixedSizeBinary2 extends DataType {
  constructor(byteWidth) {
    super(Type$1.FixedSizeBinary);
    this.byteWidth = byteWidth;
  }
  toString() {
    return `FixedSizeBinary[${this.byteWidth}]`;
  }
}
_u = Symbol.toStringTag;
FixedSizeBinary2[_u] = ((proto) => {
  proto.byteWidth = null;
  proto.ArrayType = Uint8Array;
  return proto[Symbol.toStringTag] = "FixedSizeBinary";
})(FixedSizeBinary2.prototype);
class FixedSizeList2 extends DataType {
  constructor(listSize, child) {
    super(Type$1.FixedSizeList);
    this.listSize = listSize;
    this.children = [child];
  }
  get valueType() {
    return this.children[0].type;
  }
  get valueField() {
    return this.children[0];
  }
  get ArrayType() {
    return this.valueType.ArrayType;
  }
  toString() {
    return `FixedSizeList[${this.listSize}]<${this.valueType}>`;
  }
}
_v = Symbol.toStringTag;
FixedSizeList2[_v] = ((proto) => {
  proto.children = null;
  proto.listSize = null;
  return proto[Symbol.toStringTag] = "FixedSizeList";
})(FixedSizeList2.prototype);
class Map_ extends DataType {
  constructor(entries2, keysSorted = false) {
    var _y, _z, _0;
    super(Type$1.Map);
    this.children = [entries2];
    this.keysSorted = keysSorted;
    if (entries2) {
      entries2["name"] = "entries";
      if ((_y = entries2 === null || entries2 === void 0 ? void 0 : entries2.type) === null || _y === void 0 ? void 0 : _y.children) {
        const key2 = (_z = entries2 === null || entries2 === void 0 ? void 0 : entries2.type) === null || _z === void 0 ? void 0 : _z.children[0];
        if (key2) {
          key2["name"] = "key";
        }
        const val = (_0 = entries2 === null || entries2 === void 0 ? void 0 : entries2.type) === null || _0 === void 0 ? void 0 : _0.children[1];
        if (val) {
          val["name"] = "value";
        }
      }
    }
  }
  get keyType() {
    return this.children[0].type.children[0].type;
  }
  get valueType() {
    return this.children[0].type.children[1].type;
  }
  get childType() {
    return this.children[0].type;
  }
  toString() {
    return `Map<{${this.children[0].type.children.map((f) => `${f.name}:${f.type}`).join(`, `)}}>`;
  }
}
_w = Symbol.toStringTag;
Map_[_w] = ((proto) => {
  proto.children = null;
  proto.keysSorted = null;
  return proto[Symbol.toStringTag] = "Map_";
})(Map_.prototype);
const getId = /* @__PURE__ */ ((atomicDictionaryId) => () => ++atomicDictionaryId)(-1);
let Dictionary$1 = class Dictionary extends DataType {
  constructor(dictionary2, indices, id2, isOrdered) {
    super(Type$1.Dictionary);
    this.indices = indices;
    this.dictionary = dictionary2;
    this.isOrdered = isOrdered || false;
    this.id = id2 == null ? getId() : bigIntToNumber(id2);
  }
  get children() {
    return this.dictionary.children;
  }
  get valueType() {
    return this.dictionary;
  }
  get ArrayType() {
    return this.dictionary.ArrayType;
  }
  toString() {
    return `Dictionary<${this.indices}, ${this.dictionary}>`;
  }
};
_x = Symbol.toStringTag;
Dictionary$1[_x] = ((proto) => {
  proto.id = null;
  proto.indices = null;
  proto.isOrdered = null;
  proto.dictionary = null;
  return proto[Symbol.toStringTag] = "Dictionary";
})(Dictionary$1.prototype);
function strideForType(type) {
  const t2 = type;
  switch (type.typeId) {
    case Type$1.Decimal:
      return type.bitWidth / 32;
    case Type$1.Interval: {
      if (t2.unit === IntervalUnit$1.MONTH_DAY_NANO) {
        return 4;
      }
      return 1 + t2.unit;
    }
    // case Type.Int: return 1 + +((t as Int_).bitWidth > 32);
    // case Type.Time: return 1 + +((t as Time_).bitWidth > 32);
    case Type$1.FixedSizeList:
      return t2.listSize;
    case Type$1.FixedSizeBinary:
      return t2.byteWidth;
    default:
      return 1;
  }
}
class Visitor {
  visitMany(nodes, ...args2) {
    return nodes.map((node2, i2) => this.visit(node2, ...args2.map((x) => x[i2])));
  }
  visit(...args2) {
    return this.getVisitFn(args2[0], false).apply(this, args2);
  }
  getVisitFn(node2, throwIfNotFound = true) {
    return getVisitFn(this, node2, throwIfNotFound);
  }
  getVisitFnByTypeId(typeId, throwIfNotFound = true) {
    return getVisitFnByTypeId(this, typeId, throwIfNotFound);
  }
  visitNull(_node, ..._args) {
    return null;
  }
  visitBool(_node, ..._args) {
    return null;
  }
  visitInt(_node, ..._args) {
    return null;
  }
  visitFloat(_node, ..._args) {
    return null;
  }
  visitUtf8(_node, ..._args) {
    return null;
  }
  visitLargeUtf8(_node, ..._args) {
    return null;
  }
  visitBinary(_node, ..._args) {
    return null;
  }
  visitLargeBinary(_node, ..._args) {
    return null;
  }
  visitFixedSizeBinary(_node, ..._args) {
    return null;
  }
  visitDate(_node, ..._args) {
    return null;
  }
  visitTimestamp(_node, ..._args) {
    return null;
  }
  visitTime(_node, ..._args) {
    return null;
  }
  visitDecimal(_node, ..._args) {
    return null;
  }
  visitList(_node, ..._args) {
    return null;
  }
  visitStruct(_node, ..._args) {
    return null;
  }
  visitUnion(_node, ..._args) {
    return null;
  }
  visitDictionary(_node, ..._args) {
    return null;
  }
  visitInterval(_node, ..._args) {
    return null;
  }
  visitDuration(_node, ..._args) {
    return null;
  }
  visitFixedSizeList(_node, ..._args) {
    return null;
  }
  visitMap(_node, ..._args) {
    return null;
  }
}
function getVisitFn(visitor, node2, throwIfNotFound = true) {
  if (typeof node2 === "number") {
    return getVisitFnByTypeId(visitor, node2, throwIfNotFound);
  }
  if (typeof node2 === "string" && node2 in Type$1) {
    return getVisitFnByTypeId(visitor, Type$1[node2], throwIfNotFound);
  }
  if (node2 && node2 instanceof DataType) {
    return getVisitFnByTypeId(visitor, inferDType(node2), throwIfNotFound);
  }
  if ((node2 === null || node2 === void 0 ? void 0 : node2.type) && node2.type instanceof DataType) {
    return getVisitFnByTypeId(visitor, inferDType(node2.type), throwIfNotFound);
  }
  return getVisitFnByTypeId(visitor, Type$1.NONE, throwIfNotFound);
}
function getVisitFnByTypeId(visitor, dtype, throwIfNotFound = true) {
  let fn3 = null;
  switch (dtype) {
    case Type$1.Null:
      fn3 = visitor.visitNull;
      break;
    case Type$1.Bool:
      fn3 = visitor.visitBool;
      break;
    case Type$1.Int:
      fn3 = visitor.visitInt;
      break;
    case Type$1.Int8:
      fn3 = visitor.visitInt8 || visitor.visitInt;
      break;
    case Type$1.Int16:
      fn3 = visitor.visitInt16 || visitor.visitInt;
      break;
    case Type$1.Int32:
      fn3 = visitor.visitInt32 || visitor.visitInt;
      break;
    case Type$1.Int64:
      fn3 = visitor.visitInt64 || visitor.visitInt;
      break;
    case Type$1.Uint8:
      fn3 = visitor.visitUint8 || visitor.visitInt;
      break;
    case Type$1.Uint16:
      fn3 = visitor.visitUint16 || visitor.visitInt;
      break;
    case Type$1.Uint32:
      fn3 = visitor.visitUint32 || visitor.visitInt;
      break;
    case Type$1.Uint64:
      fn3 = visitor.visitUint64 || visitor.visitInt;
      break;
    case Type$1.Float:
      fn3 = visitor.visitFloat;
      break;
    case Type$1.Float16:
      fn3 = visitor.visitFloat16 || visitor.visitFloat;
      break;
    case Type$1.Float32:
      fn3 = visitor.visitFloat32 || visitor.visitFloat;
      break;
    case Type$1.Float64:
      fn3 = visitor.visitFloat64 || visitor.visitFloat;
      break;
    case Type$1.Utf8:
      fn3 = visitor.visitUtf8;
      break;
    case Type$1.LargeUtf8:
      fn3 = visitor.visitLargeUtf8;
      break;
    case Type$1.Binary:
      fn3 = visitor.visitBinary;
      break;
    case Type$1.LargeBinary:
      fn3 = visitor.visitLargeBinary;
      break;
    case Type$1.FixedSizeBinary:
      fn3 = visitor.visitFixedSizeBinary;
      break;
    case Type$1.Date:
      fn3 = visitor.visitDate;
      break;
    case Type$1.DateDay:
      fn3 = visitor.visitDateDay || visitor.visitDate;
      break;
    case Type$1.DateMillisecond:
      fn3 = visitor.visitDateMillisecond || visitor.visitDate;
      break;
    case Type$1.Timestamp:
      fn3 = visitor.visitTimestamp;
      break;
    case Type$1.TimestampSecond:
      fn3 = visitor.visitTimestampSecond || visitor.visitTimestamp;
      break;
    case Type$1.TimestampMillisecond:
      fn3 = visitor.visitTimestampMillisecond || visitor.visitTimestamp;
      break;
    case Type$1.TimestampMicrosecond:
      fn3 = visitor.visitTimestampMicrosecond || visitor.visitTimestamp;
      break;
    case Type$1.TimestampNanosecond:
      fn3 = visitor.visitTimestampNanosecond || visitor.visitTimestamp;
      break;
    case Type$1.Time:
      fn3 = visitor.visitTime;
      break;
    case Type$1.TimeSecond:
      fn3 = visitor.visitTimeSecond || visitor.visitTime;
      break;
    case Type$1.TimeMillisecond:
      fn3 = visitor.visitTimeMillisecond || visitor.visitTime;
      break;
    case Type$1.TimeMicrosecond:
      fn3 = visitor.visitTimeMicrosecond || visitor.visitTime;
      break;
    case Type$1.TimeNanosecond:
      fn3 = visitor.visitTimeNanosecond || visitor.visitTime;
      break;
    case Type$1.Decimal:
      fn3 = visitor.visitDecimal;
      break;
    case Type$1.List:
      fn3 = visitor.visitList;
      break;
    case Type$1.Struct:
      fn3 = visitor.visitStruct;
      break;
    case Type$1.Union:
      fn3 = visitor.visitUnion;
      break;
    case Type$1.DenseUnion:
      fn3 = visitor.visitDenseUnion || visitor.visitUnion;
      break;
    case Type$1.SparseUnion:
      fn3 = visitor.visitSparseUnion || visitor.visitUnion;
      break;
    case Type$1.Dictionary:
      fn3 = visitor.visitDictionary;
      break;
    case Type$1.Interval:
      fn3 = visitor.visitInterval;
      break;
    case Type$1.IntervalDayTime:
      fn3 = visitor.visitIntervalDayTime || visitor.visitInterval;
      break;
    case Type$1.IntervalYearMonth:
      fn3 = visitor.visitIntervalYearMonth || visitor.visitInterval;
      break;
    case Type$1.IntervalMonthDayNano:
      fn3 = visitor.visitIntervalMonthDayNano || visitor.visitInterval;
      break;
    case Type$1.Duration:
      fn3 = visitor.visitDuration;
      break;
    case Type$1.DurationSecond:
      fn3 = visitor.visitDurationSecond || visitor.visitDuration;
      break;
    case Type$1.DurationMillisecond:
      fn3 = visitor.visitDurationMillisecond || visitor.visitDuration;
      break;
    case Type$1.DurationMicrosecond:
      fn3 = visitor.visitDurationMicrosecond || visitor.visitDuration;
      break;
    case Type$1.DurationNanosecond:
      fn3 = visitor.visitDurationNanosecond || visitor.visitDuration;
      break;
    case Type$1.FixedSizeList:
      fn3 = visitor.visitFixedSizeList;
      break;
    case Type$1.Map:
      fn3 = visitor.visitMap;
      break;
  }
  if (typeof fn3 === "function")
    return fn3;
  if (!throwIfNotFound)
    return () => null;
  throw new Error(`Unrecognized type '${Type$1[dtype]}'`);
}
function inferDType(type) {
  switch (type.typeId) {
    case Type$1.Null:
      return Type$1.Null;
    case Type$1.Int: {
      const { bitWidth, isSigned } = type;
      switch (bitWidth) {
        case 8:
          return isSigned ? Type$1.Int8 : Type$1.Uint8;
        case 16:
          return isSigned ? Type$1.Int16 : Type$1.Uint16;
        case 32:
          return isSigned ? Type$1.Int32 : Type$1.Uint32;
        case 64:
          return isSigned ? Type$1.Int64 : Type$1.Uint64;
      }
      return Type$1.Int;
    }
    case Type$1.Float:
      switch (type.precision) {
        case Precision$1.HALF:
          return Type$1.Float16;
        case Precision$1.SINGLE:
          return Type$1.Float32;
        case Precision$1.DOUBLE:
          return Type$1.Float64;
      }
      return Type$1.Float;
    case Type$1.Binary:
      return Type$1.Binary;
    case Type$1.LargeBinary:
      return Type$1.LargeBinary;
    case Type$1.Utf8:
      return Type$1.Utf8;
    case Type$1.LargeUtf8:
      return Type$1.LargeUtf8;
    case Type$1.Bool:
      return Type$1.Bool;
    case Type$1.Decimal:
      return Type$1.Decimal;
    case Type$1.Time:
      switch (type.unit) {
        case TimeUnit$1.SECOND:
          return Type$1.TimeSecond;
        case TimeUnit$1.MILLISECOND:
          return Type$1.TimeMillisecond;
        case TimeUnit$1.MICROSECOND:
          return Type$1.TimeMicrosecond;
        case TimeUnit$1.NANOSECOND:
          return Type$1.TimeNanosecond;
      }
      return Type$1.Time;
    case Type$1.Timestamp:
      switch (type.unit) {
        case TimeUnit$1.SECOND:
          return Type$1.TimestampSecond;
        case TimeUnit$1.MILLISECOND:
          return Type$1.TimestampMillisecond;
        case TimeUnit$1.MICROSECOND:
          return Type$1.TimestampMicrosecond;
        case TimeUnit$1.NANOSECOND:
          return Type$1.TimestampNanosecond;
      }
      return Type$1.Timestamp;
    case Type$1.Date:
      switch (type.unit) {
        case DateUnit$1.DAY:
          return Type$1.DateDay;
        case DateUnit$1.MILLISECOND:
          return Type$1.DateMillisecond;
      }
      return Type$1.Date;
    case Type$1.Interval:
      switch (type.unit) {
        case IntervalUnit$1.DAY_TIME:
          return Type$1.IntervalDayTime;
        case IntervalUnit$1.YEAR_MONTH:
          return Type$1.IntervalYearMonth;
        case IntervalUnit$1.MONTH_DAY_NANO:
          return Type$1.IntervalMonthDayNano;
      }
      return Type$1.Interval;
    case Type$1.Duration:
      switch (type.unit) {
        case TimeUnit$1.SECOND:
          return Type$1.DurationSecond;
        case TimeUnit$1.MILLISECOND:
          return Type$1.DurationMillisecond;
        case TimeUnit$1.MICROSECOND:
          return Type$1.DurationMicrosecond;
        case TimeUnit$1.NANOSECOND:
          return Type$1.DurationNanosecond;
      }
      return Type$1.Duration;
    case Type$1.Map:
      return Type$1.Map;
    case Type$1.List:
      return Type$1.List;
    case Type$1.Struct:
      return Type$1.Struct;
    case Type$1.Union:
      switch (type.mode) {
        case UnionMode$1.Dense:
          return Type$1.DenseUnion;
        case UnionMode$1.Sparse:
          return Type$1.SparseUnion;
      }
      return Type$1.Union;
    case Type$1.FixedSizeBinary:
      return Type$1.FixedSizeBinary;
    case Type$1.FixedSizeList:
      return Type$1.FixedSizeList;
    case Type$1.Dictionary:
      return Type$1.Dictionary;
  }
  throw new Error(`Unrecognized type '${Type$1[type.typeId]}'`);
}
Visitor.prototype.visitInt8 = null;
Visitor.prototype.visitInt16 = null;
Visitor.prototype.visitInt32 = null;
Visitor.prototype.visitInt64 = null;
Visitor.prototype.visitUint8 = null;
Visitor.prototype.visitUint16 = null;
Visitor.prototype.visitUint32 = null;
Visitor.prototype.visitUint64 = null;
Visitor.prototype.visitFloat16 = null;
Visitor.prototype.visitFloat32 = null;
Visitor.prototype.visitFloat64 = null;
Visitor.prototype.visitDateDay = null;
Visitor.prototype.visitDateMillisecond = null;
Visitor.prototype.visitTimestampSecond = null;
Visitor.prototype.visitTimestampMillisecond = null;
Visitor.prototype.visitTimestampMicrosecond = null;
Visitor.prototype.visitTimestampNanosecond = null;
Visitor.prototype.visitTimeSecond = null;
Visitor.prototype.visitTimeMillisecond = null;
Visitor.prototype.visitTimeMicrosecond = null;
Visitor.prototype.visitTimeNanosecond = null;
Visitor.prototype.visitDenseUnion = null;
Visitor.prototype.visitSparseUnion = null;
Visitor.prototype.visitIntervalDayTime = null;
Visitor.prototype.visitIntervalYearMonth = null;
Visitor.prototype.visitIntervalMonthDayNano = null;
Visitor.prototype.visitDuration = null;
Visitor.prototype.visitDurationSecond = null;
Visitor.prototype.visitDurationMillisecond = null;
Visitor.prototype.visitDurationMicrosecond = null;
Visitor.prototype.visitDurationNanosecond = null;
const f64$1 = new Float64Array(1);
const u32$1 = new Uint32Array(f64$1.buffer);
function uint16ToFloat64(h) {
  const expo = (h & 31744) >> 10;
  const sigf = (h & 1023) / 1024;
  const sign2 = Math.pow(-1, (h & 32768) >> 15);
  switch (expo) {
    case 31:
      return sign2 * (sigf ? Number.NaN : 1 / 0);
    case 0:
      return sign2 * (sigf ? 6103515625e-14 * sigf : 0);
  }
  return sign2 * Math.pow(2, expo - 15) * (1 + sigf);
}
function float64ToUint16(d) {
  if (d !== d) {
    return 32256;
  }
  f64$1[0] = d;
  const sign2 = (u32$1[1] & 2147483648) >> 16 & 65535;
  let expo = u32$1[1] & 2146435072, sigf = 0;
  if (expo >= 1089470464) {
    if (u32$1[0] > 0) {
      expo = 31744;
    } else {
      expo = (expo & 2080374784) >> 16;
      sigf = (u32$1[1] & 1048575) >> 10;
    }
  } else if (expo <= 1056964608) {
    sigf = 1048576 + (u32$1[1] & 1048575);
    sigf = 1048576 + (sigf << (expo >> 20) - 998) >> 21;
    expo = 0;
  } else {
    expo = expo - 1056964608 >> 10;
    sigf = (u32$1[1] & 1048575) + 512 >> 10;
  }
  return sign2 | expo | sigf & 65535;
}
class SetVisitor extends Visitor {
}
function wrapSet(fn3) {
  return (data2, _1, _2) => {
    if (data2.setValid(_1, _2 != null)) {
      return fn3(data2, _1, _2);
    }
  };
}
const setEpochMsToDays = (data2, index, epochMs) => {
  data2[index] = Math.floor(epochMs / 864e5);
};
const setVariableWidthBytes = (values2, valueOffsets, index, value2) => {
  if (index + 1 < valueOffsets.length) {
    const x = bigIntToNumber(valueOffsets[index]);
    const y = bigIntToNumber(valueOffsets[index + 1]);
    values2.set(value2.subarray(0, y - x), x);
  }
};
const setBool = ({ offset: offset3, values: values2 }, index, val) => {
  const idx = offset3 + index;
  val ? values2[idx >> 3] |= 1 << idx % 8 : values2[idx >> 3] &= ~(1 << idx % 8);
};
const setInt = ({ values: values2 }, index, value2) => {
  values2[index] = value2;
};
const setFloat = ({ values: values2 }, index, value2) => {
  values2[index] = value2;
};
const setFloat16 = ({ values: values2 }, index, value2) => {
  values2[index] = float64ToUint16(value2);
};
const setAnyFloat = (data2, index, value2) => {
  switch (data2.type.precision) {
    case Precision$1.HALF:
      return setFloat16(data2, index, value2);
    case Precision$1.SINGLE:
    case Precision$1.DOUBLE:
      return setFloat(data2, index, value2);
  }
};
const setDateDay = ({ values: values2 }, index, value2) => {
  setEpochMsToDays(values2, index, value2.valueOf());
};
const setDateMillisecond = ({ values: values2 }, index, value2) => {
  values2[index] = BigInt(value2);
};
const setFixedSizeBinary = ({ stride, values: values2 }, index, value2) => {
  values2.set(value2.subarray(0, stride), stride * index);
};
const setBinary = ({ values: values2, valueOffsets }, index, value2) => setVariableWidthBytes(values2, valueOffsets, index, value2);
const setUtf8 = ({ values: values2, valueOffsets }, index, value2) => setVariableWidthBytes(values2, valueOffsets, index, encodeUtf8$1(value2));
const setDate = (data2, index, value2) => {
  data2.type.unit === DateUnit$1.DAY ? setDateDay(data2, index, value2) : setDateMillisecond(data2, index, value2);
};
const setTimestampSecond = ({ values: values2 }, index, value2) => {
  values2[index] = BigInt(value2 / 1e3);
};
const setTimestampMillisecond = ({ values: values2 }, index, value2) => {
  values2[index] = BigInt(value2);
};
const setTimestampMicrosecond = ({ values: values2 }, index, value2) => {
  values2[index] = BigInt(value2 * 1e3);
};
const setTimestampNanosecond = ({ values: values2 }, index, value2) => {
  values2[index] = BigInt(value2 * 1e6);
};
const setTimestamp = (data2, index, value2) => {
  switch (data2.type.unit) {
    case TimeUnit$1.SECOND:
      return setTimestampSecond(data2, index, value2);
    case TimeUnit$1.MILLISECOND:
      return setTimestampMillisecond(data2, index, value2);
    case TimeUnit$1.MICROSECOND:
      return setTimestampMicrosecond(data2, index, value2);
    case TimeUnit$1.NANOSECOND:
      return setTimestampNanosecond(data2, index, value2);
  }
};
const setTimeSecond = ({ values: values2 }, index, value2) => {
  values2[index] = value2;
};
const setTimeMillisecond = ({ values: values2 }, index, value2) => {
  values2[index] = value2;
};
const setTimeMicrosecond = ({ values: values2 }, index, value2) => {
  values2[index] = value2;
};
const setTimeNanosecond = ({ values: values2 }, index, value2) => {
  values2[index] = value2;
};
const setTime = (data2, index, value2) => {
  switch (data2.type.unit) {
    case TimeUnit$1.SECOND:
      return setTimeSecond(data2, index, value2);
    case TimeUnit$1.MILLISECOND:
      return setTimeMillisecond(data2, index, value2);
    case TimeUnit$1.MICROSECOND:
      return setTimeMicrosecond(data2, index, value2);
    case TimeUnit$1.NANOSECOND:
      return setTimeNanosecond(data2, index, value2);
  }
};
const setDecimal = ({ values: values2, stride }, index, value2) => {
  values2.set(value2.subarray(0, stride), stride * index);
};
const setList = (data2, index, value2) => {
  const values2 = data2.children[0];
  const valueOffsets = data2.valueOffsets;
  const set3 = instance$5.getVisitFn(values2);
  if (Array.isArray(value2)) {
    for (let idx = -1, itr = valueOffsets[index], end2 = valueOffsets[index + 1]; itr < end2; ) {
      set3(values2, itr++, value2[++idx]);
    }
  } else {
    for (let idx = -1, itr = valueOffsets[index], end2 = valueOffsets[index + 1]; itr < end2; ) {
      set3(values2, itr++, value2.get(++idx));
    }
  }
};
const setMap = (data2, index, value2) => {
  const values2 = data2.children[0];
  const { valueOffsets } = data2;
  const set3 = instance$5.getVisitFn(values2);
  let { [index]: idx, [index + 1]: end2 } = valueOffsets;
  const entries2 = value2 instanceof Map ? value2.entries() : Object.entries(value2);
  for (const val of entries2) {
    set3(values2, idx, val);
    if (++idx >= end2)
      break;
  }
};
const _setStructArrayValue = (o, v) => (set3, c2, _, i2) => c2 && set3(c2, o, v[i2]);
const _setStructVectorValue = (o, v) => (set3, c2, _, i2) => c2 && set3(c2, o, v.get(i2));
const _setStructMapValue = (o, v) => (set3, c2, f, _) => c2 && set3(c2, o, v.get(f.name));
const _setStructObjectValue = (o, v) => (set3, c2, f, _) => c2 && set3(c2, o, v[f.name]);
const setStruct = (data2, index, value2) => {
  const childSetters = data2.type.children.map((f) => instance$5.getVisitFn(f.type));
  const set3 = value2 instanceof Map ? _setStructMapValue(index, value2) : value2 instanceof Vector ? _setStructVectorValue(index, value2) : Array.isArray(value2) ? _setStructArrayValue(index, value2) : _setStructObjectValue(index, value2);
  data2.type.children.forEach((f, i2) => set3(childSetters[i2], data2.children[i2], f, i2));
};
const setUnion = (data2, index, value2) => {
  data2.type.mode === UnionMode$1.Dense ? setDenseUnion(data2, index, value2) : setSparseUnion(data2, index, value2);
};
const setDenseUnion = (data2, index, value2) => {
  const childIndex = data2.type.typeIdToChildIndex[data2.typeIds[index]];
  const child = data2.children[childIndex];
  instance$5.visit(child, data2.valueOffsets[index], value2);
};
const setSparseUnion = (data2, index, value2) => {
  const childIndex = data2.type.typeIdToChildIndex[data2.typeIds[index]];
  const child = data2.children[childIndex];
  instance$5.visit(child, index, value2);
};
const setDictionary = (data2, index, value2) => {
  var _a2;
  (_a2 = data2.dictionary) === null || _a2 === void 0 ? void 0 : _a2.set(data2.values[index], value2);
};
const setIntervalValue = (data2, index, value2) => {
  switch (data2.type.unit) {
    case IntervalUnit$1.YEAR_MONTH:
      return setIntervalYearMonth(data2, index, value2);
    case IntervalUnit$1.DAY_TIME:
      return setIntervalDayTime(data2, index, value2);
    case IntervalUnit$1.MONTH_DAY_NANO:
      return setIntervalMonthDayNano(data2, index, value2);
  }
};
const setIntervalDayTime = ({ values: values2 }, index, value2) => {
  values2.set(value2.subarray(0, 2), 2 * index);
};
const setIntervalYearMonth = ({ values: values2 }, index, value2) => {
  values2[index] = value2[0] * 12 + value2[1] % 12;
};
const setIntervalMonthDayNano = ({ values: values2, stride }, index, value2) => {
  values2.set(value2.subarray(0, stride), stride * index);
};
const setDurationSecond = ({ values: values2 }, index, value2) => {
  values2[index] = value2;
};
const setDurationMillisecond = ({ values: values2 }, index, value2) => {
  values2[index] = value2;
};
const setDurationMicrosecond = ({ values: values2 }, index, value2) => {
  values2[index] = value2;
};
const setDurationNanosecond = ({ values: values2 }, index, value2) => {
  values2[index] = value2;
};
const setDuration = (data2, index, value2) => {
  switch (data2.type.unit) {
    case TimeUnit$1.SECOND:
      return setDurationSecond(data2, index, value2);
    case TimeUnit$1.MILLISECOND:
      return setDurationMillisecond(data2, index, value2);
    case TimeUnit$1.MICROSECOND:
      return setDurationMicrosecond(data2, index, value2);
    case TimeUnit$1.NANOSECOND:
      return setDurationNanosecond(data2, index, value2);
  }
};
const setFixedSizeList = (data2, index, value2) => {
  const { stride } = data2;
  const child = data2.children[0];
  const set3 = instance$5.getVisitFn(child);
  if (Array.isArray(value2)) {
    for (let idx = -1, offset3 = index * stride; ++idx < stride; ) {
      set3(child, offset3 + idx, value2[idx]);
    }
  } else {
    for (let idx = -1, offset3 = index * stride; ++idx < stride; ) {
      set3(child, offset3 + idx, value2.get(idx));
    }
  }
};
SetVisitor.prototype.visitBool = wrapSet(setBool);
SetVisitor.prototype.visitInt = wrapSet(setInt);
SetVisitor.prototype.visitInt8 = wrapSet(setInt);
SetVisitor.prototype.visitInt16 = wrapSet(setInt);
SetVisitor.prototype.visitInt32 = wrapSet(setInt);
SetVisitor.prototype.visitInt64 = wrapSet(setInt);
SetVisitor.prototype.visitUint8 = wrapSet(setInt);
SetVisitor.prototype.visitUint16 = wrapSet(setInt);
SetVisitor.prototype.visitUint32 = wrapSet(setInt);
SetVisitor.prototype.visitUint64 = wrapSet(setInt);
SetVisitor.prototype.visitFloat = wrapSet(setAnyFloat);
SetVisitor.prototype.visitFloat16 = wrapSet(setFloat16);
SetVisitor.prototype.visitFloat32 = wrapSet(setFloat);
SetVisitor.prototype.visitFloat64 = wrapSet(setFloat);
SetVisitor.prototype.visitUtf8 = wrapSet(setUtf8);
SetVisitor.prototype.visitLargeUtf8 = wrapSet(setUtf8);
SetVisitor.prototype.visitBinary = wrapSet(setBinary);
SetVisitor.prototype.visitLargeBinary = wrapSet(setBinary);
SetVisitor.prototype.visitFixedSizeBinary = wrapSet(setFixedSizeBinary);
SetVisitor.prototype.visitDate = wrapSet(setDate);
SetVisitor.prototype.visitDateDay = wrapSet(setDateDay);
SetVisitor.prototype.visitDateMillisecond = wrapSet(setDateMillisecond);
SetVisitor.prototype.visitTimestamp = wrapSet(setTimestamp);
SetVisitor.prototype.visitTimestampSecond = wrapSet(setTimestampSecond);
SetVisitor.prototype.visitTimestampMillisecond = wrapSet(setTimestampMillisecond);
SetVisitor.prototype.visitTimestampMicrosecond = wrapSet(setTimestampMicrosecond);
SetVisitor.prototype.visitTimestampNanosecond = wrapSet(setTimestampNanosecond);
SetVisitor.prototype.visitTime = wrapSet(setTime);
SetVisitor.prototype.visitTimeSecond = wrapSet(setTimeSecond);
SetVisitor.prototype.visitTimeMillisecond = wrapSet(setTimeMillisecond);
SetVisitor.prototype.visitTimeMicrosecond = wrapSet(setTimeMicrosecond);
SetVisitor.prototype.visitTimeNanosecond = wrapSet(setTimeNanosecond);
SetVisitor.prototype.visitDecimal = wrapSet(setDecimal);
SetVisitor.prototype.visitList = wrapSet(setList);
SetVisitor.prototype.visitStruct = wrapSet(setStruct);
SetVisitor.prototype.visitUnion = wrapSet(setUnion);
SetVisitor.prototype.visitDenseUnion = wrapSet(setDenseUnion);
SetVisitor.prototype.visitSparseUnion = wrapSet(setSparseUnion);
SetVisitor.prototype.visitDictionary = wrapSet(setDictionary);
SetVisitor.prototype.visitInterval = wrapSet(setIntervalValue);
SetVisitor.prototype.visitIntervalDayTime = wrapSet(setIntervalDayTime);
SetVisitor.prototype.visitIntervalYearMonth = wrapSet(setIntervalYearMonth);
SetVisitor.prototype.visitIntervalMonthDayNano = wrapSet(setIntervalMonthDayNano);
SetVisitor.prototype.visitDuration = wrapSet(setDuration);
SetVisitor.prototype.visitDurationSecond = wrapSet(setDurationSecond);
SetVisitor.prototype.visitDurationMillisecond = wrapSet(setDurationMillisecond);
SetVisitor.prototype.visitDurationMicrosecond = wrapSet(setDurationMicrosecond);
SetVisitor.prototype.visitDurationNanosecond = wrapSet(setDurationNanosecond);
SetVisitor.prototype.visitFixedSizeList = wrapSet(setFixedSizeList);
SetVisitor.prototype.visitMap = wrapSet(setMap);
const instance$5 = new SetVisitor();
const kParent = Symbol.for("parent");
const kRowIndex = Symbol.for("rowIndex");
class StructRow {
  constructor(parent, rowIndex) {
    this[kParent] = parent;
    this[kRowIndex] = rowIndex;
    return new Proxy(this, structRowProxyHandler);
  }
  toArray() {
    return Object.values(this.toJSON());
  }
  toJSON() {
    const i2 = this[kRowIndex];
    const parent = this[kParent];
    const keys2 = parent.type.children;
    const json2 = {};
    for (let j2 = -1, n2 = keys2.length; ++j2 < n2; ) {
      json2[keys2[j2].name] = instance$4.visit(parent.children[j2], i2);
    }
    return json2;
  }
  toString() {
    return `{${[...this].map(([key2, val]) => `${valueToString(key2)}: ${valueToString(val)}`).join(", ")}}`;
  }
  [Symbol.for("nodejs.util.inspect.custom")]() {
    return this.toString();
  }
  [Symbol.iterator]() {
    return new StructRowIterator(this[kParent], this[kRowIndex]);
  }
}
class StructRowIterator {
  constructor(data2, rowIndex) {
    this.childIndex = 0;
    this.children = data2.children;
    this.rowIndex = rowIndex;
    this.childFields = data2.type.children;
    this.numChildren = this.childFields.length;
  }
  [Symbol.iterator]() {
    return this;
  }
  next() {
    const i2 = this.childIndex;
    if (i2 < this.numChildren) {
      this.childIndex = i2 + 1;
      return {
        done: false,
        value: [
          this.childFields[i2].name,
          instance$4.visit(this.children[i2], this.rowIndex)
        ]
      };
    }
    return { done: true, value: null };
  }
}
Object.defineProperties(StructRow.prototype, {
  [Symbol.toStringTag]: { enumerable: false, configurable: false, value: "Row" },
  [kParent]: { writable: true, enumerable: false, configurable: false, value: null },
  [kRowIndex]: { writable: true, enumerable: false, configurable: false, value: -1 }
});
class StructRowProxyHandler {
  isExtensible() {
    return false;
  }
  deleteProperty() {
    return false;
  }
  preventExtensions() {
    return true;
  }
  ownKeys(row2) {
    return row2[kParent].type.children.map((f) => f.name);
  }
  has(row2, key2) {
    return row2[kParent].type.children.some((f) => f.name === key2);
  }
  getOwnPropertyDescriptor(row2, key2) {
    if (row2[kParent].type.children.some((f) => f.name === key2)) {
      return { writable: true, enumerable: true, configurable: true };
    }
    return;
  }
  get(row2, key2) {
    if (Reflect.has(row2, key2)) {
      return row2[key2];
    }
    const idx = row2[kParent].type.children.findIndex((f) => f.name === key2);
    if (idx !== -1) {
      const val = instance$4.visit(row2[kParent].children[idx], row2[kRowIndex]);
      Reflect.set(row2, key2, val);
      return val;
    }
  }
  set(row2, key2, val) {
    const idx = row2[kParent].type.children.findIndex((f) => f.name === key2);
    if (idx !== -1) {
      instance$5.visit(row2[kParent].children[idx], row2[kRowIndex], val);
      return Reflect.set(row2, key2, val);
    } else if (Reflect.has(row2, key2) || typeof key2 === "symbol") {
      return Reflect.set(row2, key2, val);
    }
    return false;
  }
}
const structRowProxyHandler = new StructRowProxyHandler();
class GetVisitor extends Visitor {
}
function wrapGet(fn3) {
  return (data2, _1) => data2.getValid(_1) ? fn3(data2, _1) : null;
}
const epochDaysToMs = (data2, index) => 864e5 * data2[index];
const getNull = (_data, _index) => null;
const getVariableWidthBytes = (values2, valueOffsets, index) => {
  if (index + 1 >= valueOffsets.length) {
    return null;
  }
  const x = bigIntToNumber(valueOffsets[index]);
  const y = bigIntToNumber(valueOffsets[index + 1]);
  return values2.subarray(x, y);
};
const getBool$1 = ({ offset: offset3, values: values2 }, index) => {
  const idx = offset3 + index;
  const byte = values2[idx >> 3];
  return (byte & 1 << idx % 8) !== 0;
};
const getDateDay = ({ values: values2 }, index) => epochDaysToMs(values2, index);
const getDateMillisecond = ({ values: values2 }, index) => bigIntToNumber(values2[index]);
const getNumeric = ({ stride, values: values2 }, index) => values2[stride * index];
const getFloat16 = ({ stride, values: values2 }, index) => uint16ToFloat64(values2[stride * index]);
const getBigInts = ({ values: values2 }, index) => values2[index];
const getFixedSizeBinary = ({ stride, values: values2 }, index) => values2.subarray(stride * index, stride * (index + 1));
const getBinary = ({ values: values2, valueOffsets }, index) => getVariableWidthBytes(values2, valueOffsets, index);
const getUtf8 = ({ values: values2, valueOffsets }, index) => {
  const bytes = getVariableWidthBytes(values2, valueOffsets, index);
  return bytes !== null ? decodeUtf8$1(bytes) : null;
};
const getInt = ({ values: values2 }, index) => values2[index];
const getFloat = ({ type, values: values2 }, index) => type.precision !== Precision$1.HALF ? values2[index] : uint16ToFloat64(values2[index]);
const getDate = (data2, index) => data2.type.unit === DateUnit$1.DAY ? getDateDay(data2, index) : getDateMillisecond(data2, index);
const getTimestampSecond = ({ values: values2 }, index) => 1e3 * bigIntToNumber(values2[index]);
const getTimestampMillisecond = ({ values: values2 }, index) => bigIntToNumber(values2[index]);
const getTimestampMicrosecond = ({ values: values2 }, index) => divideBigInts(values2[index], BigInt(1e3));
const getTimestampNanosecond = ({ values: values2 }, index) => divideBigInts(values2[index], BigInt(1e6));
const getTimestamp = (data2, index) => {
  switch (data2.type.unit) {
    case TimeUnit$1.SECOND:
      return getTimestampSecond(data2, index);
    case TimeUnit$1.MILLISECOND:
      return getTimestampMillisecond(data2, index);
    case TimeUnit$1.MICROSECOND:
      return getTimestampMicrosecond(data2, index);
    case TimeUnit$1.NANOSECOND:
      return getTimestampNanosecond(data2, index);
  }
};
const getTimeSecond = ({ values: values2 }, index) => values2[index];
const getTimeMillisecond = ({ values: values2 }, index) => values2[index];
const getTimeMicrosecond = ({ values: values2 }, index) => values2[index];
const getTimeNanosecond = ({ values: values2 }, index) => values2[index];
const getTime = (data2, index) => {
  switch (data2.type.unit) {
    case TimeUnit$1.SECOND:
      return getTimeSecond(data2, index);
    case TimeUnit$1.MILLISECOND:
      return getTimeMillisecond(data2, index);
    case TimeUnit$1.MICROSECOND:
      return getTimeMicrosecond(data2, index);
    case TimeUnit$1.NANOSECOND:
      return getTimeNanosecond(data2, index);
  }
};
const getDecimal = ({ values: values2, stride }, index) => BN.decimal(values2.subarray(stride * index, stride * (index + 1)));
const getList = (data2, index) => {
  const { valueOffsets, stride, children: children2 } = data2;
  const { [index * stride]: begin, [index * stride + 1]: end2 } = valueOffsets;
  const child = children2[0];
  const slice2 = child.slice(begin, end2 - begin);
  return new Vector([slice2]);
};
const getMap = (data2, index) => {
  const { valueOffsets, children: children2 } = data2;
  const { [index]: begin, [index + 1]: end2 } = valueOffsets;
  const child = children2[0];
  return new MapRow(child.slice(begin, end2 - begin));
};
const getStruct = (data2, index) => {
  return new StructRow(data2, index);
};
const getUnion = (data2, index) => {
  return data2.type.mode === UnionMode$1.Dense ? getDenseUnion(data2, index) : getSparseUnion(data2, index);
};
const getDenseUnion = (data2, index) => {
  const childIndex = data2.type.typeIdToChildIndex[data2.typeIds[index]];
  const child = data2.children[childIndex];
  return instance$4.visit(child, data2.valueOffsets[index]);
};
const getSparseUnion = (data2, index) => {
  const childIndex = data2.type.typeIdToChildIndex[data2.typeIds[index]];
  const child = data2.children[childIndex];
  return instance$4.visit(child, index);
};
const getDictionary = (data2, index) => {
  var _a2;
  return (_a2 = data2.dictionary) === null || _a2 === void 0 ? void 0 : _a2.get(data2.values[index]);
};
const getInterval = (data2, index) => data2.type.unit === IntervalUnit$1.MONTH_DAY_NANO ? getIntervalMonthDayNano(data2, index) : data2.type.unit === IntervalUnit$1.DAY_TIME ? getIntervalDayTime(data2, index) : getIntervalYearMonth(data2, index);
const getIntervalDayTime = ({ values: values2 }, index) => values2.subarray(2 * index, 2 * (index + 1));
const getIntervalYearMonth = ({ values: values2 }, index) => {
  const interval2 = values2[index];
  const int32s = new Int32Array(2);
  int32s[0] = Math.trunc(interval2 / 12);
  int32s[1] = Math.trunc(interval2 % 12);
  return int32s;
};
const getIntervalMonthDayNano = ({ values: values2 }, index) => values2.subarray(4 * index, 4 * (index + 1));
const getDurationSecond = ({ values: values2 }, index) => values2[index];
const getDurationMillisecond = ({ values: values2 }, index) => values2[index];
const getDurationMicrosecond = ({ values: values2 }, index) => values2[index];
const getDurationNanosecond = ({ values: values2 }, index) => values2[index];
const getDuration = (data2, index) => {
  switch (data2.type.unit) {
    case TimeUnit$1.SECOND:
      return getDurationSecond(data2, index);
    case TimeUnit$1.MILLISECOND:
      return getDurationMillisecond(data2, index);
    case TimeUnit$1.MICROSECOND:
      return getDurationMicrosecond(data2, index);
    case TimeUnit$1.NANOSECOND:
      return getDurationNanosecond(data2, index);
  }
};
const getFixedSizeList = (data2, index) => {
  const { stride, children: children2 } = data2;
  const child = children2[0];
  const slice2 = child.slice(index * stride, stride);
  return new Vector([slice2]);
};
GetVisitor.prototype.visitNull = wrapGet(getNull);
GetVisitor.prototype.visitBool = wrapGet(getBool$1);
GetVisitor.prototype.visitInt = wrapGet(getInt);
GetVisitor.prototype.visitInt8 = wrapGet(getNumeric);
GetVisitor.prototype.visitInt16 = wrapGet(getNumeric);
GetVisitor.prototype.visitInt32 = wrapGet(getNumeric);
GetVisitor.prototype.visitInt64 = wrapGet(getBigInts);
GetVisitor.prototype.visitUint8 = wrapGet(getNumeric);
GetVisitor.prototype.visitUint16 = wrapGet(getNumeric);
GetVisitor.prototype.visitUint32 = wrapGet(getNumeric);
GetVisitor.prototype.visitUint64 = wrapGet(getBigInts);
GetVisitor.prototype.visitFloat = wrapGet(getFloat);
GetVisitor.prototype.visitFloat16 = wrapGet(getFloat16);
GetVisitor.prototype.visitFloat32 = wrapGet(getNumeric);
GetVisitor.prototype.visitFloat64 = wrapGet(getNumeric);
GetVisitor.prototype.visitUtf8 = wrapGet(getUtf8);
GetVisitor.prototype.visitLargeUtf8 = wrapGet(getUtf8);
GetVisitor.prototype.visitBinary = wrapGet(getBinary);
GetVisitor.prototype.visitLargeBinary = wrapGet(getBinary);
GetVisitor.prototype.visitFixedSizeBinary = wrapGet(getFixedSizeBinary);
GetVisitor.prototype.visitDate = wrapGet(getDate);
GetVisitor.prototype.visitDateDay = wrapGet(getDateDay);
GetVisitor.prototype.visitDateMillisecond = wrapGet(getDateMillisecond);
GetVisitor.prototype.visitTimestamp = wrapGet(getTimestamp);
GetVisitor.prototype.visitTimestampSecond = wrapGet(getTimestampSecond);
GetVisitor.prototype.visitTimestampMillisecond = wrapGet(getTimestampMillisecond);
GetVisitor.prototype.visitTimestampMicrosecond = wrapGet(getTimestampMicrosecond);
GetVisitor.prototype.visitTimestampNanosecond = wrapGet(getTimestampNanosecond);
GetVisitor.prototype.visitTime = wrapGet(getTime);
GetVisitor.prototype.visitTimeSecond = wrapGet(getTimeSecond);
GetVisitor.prototype.visitTimeMillisecond = wrapGet(getTimeMillisecond);
GetVisitor.prototype.visitTimeMicrosecond = wrapGet(getTimeMicrosecond);
GetVisitor.prototype.visitTimeNanosecond = wrapGet(getTimeNanosecond);
GetVisitor.prototype.visitDecimal = wrapGet(getDecimal);
GetVisitor.prototype.visitList = wrapGet(getList);
GetVisitor.prototype.visitStruct = wrapGet(getStruct);
GetVisitor.prototype.visitUnion = wrapGet(getUnion);
GetVisitor.prototype.visitDenseUnion = wrapGet(getDenseUnion);
GetVisitor.prototype.visitSparseUnion = wrapGet(getSparseUnion);
GetVisitor.prototype.visitDictionary = wrapGet(getDictionary);
GetVisitor.prototype.visitInterval = wrapGet(getInterval);
GetVisitor.prototype.visitIntervalDayTime = wrapGet(getIntervalDayTime);
GetVisitor.prototype.visitIntervalYearMonth = wrapGet(getIntervalYearMonth);
GetVisitor.prototype.visitIntervalMonthDayNano = wrapGet(getIntervalMonthDayNano);
GetVisitor.prototype.visitDuration = wrapGet(getDuration);
GetVisitor.prototype.visitDurationSecond = wrapGet(getDurationSecond);
GetVisitor.prototype.visitDurationMillisecond = wrapGet(getDurationMillisecond);
GetVisitor.prototype.visitDurationMicrosecond = wrapGet(getDurationMicrosecond);
GetVisitor.prototype.visitDurationNanosecond = wrapGet(getDurationNanosecond);
GetVisitor.prototype.visitFixedSizeList = wrapGet(getFixedSizeList);
GetVisitor.prototype.visitMap = wrapGet(getMap);
const instance$4 = new GetVisitor();
const kKeys = Symbol.for("keys");
const kVals = Symbol.for("vals");
const kKeysAsStrings = Symbol.for("kKeysAsStrings");
const _kKeysAsStrings = Symbol.for("_kKeysAsStrings");
class MapRow {
  constructor(slice2) {
    this[kKeys] = new Vector([slice2.children[0]]).memoize();
    this[kVals] = slice2.children[1];
    return new Proxy(this, new MapRowProxyHandler());
  }
  /** @ignore */
  get [kKeysAsStrings]() {
    return this[_kKeysAsStrings] || (this[_kKeysAsStrings] = Array.from(this[kKeys].toArray(), String));
  }
  [Symbol.iterator]() {
    return new MapRowIterator(this[kKeys], this[kVals]);
  }
  get size() {
    return this[kKeys].length;
  }
  toArray() {
    return Object.values(this.toJSON());
  }
  toJSON() {
    const keys2 = this[kKeys];
    const vals = this[kVals];
    const json2 = {};
    for (let i2 = -1, n2 = keys2.length; ++i2 < n2; ) {
      json2[keys2.get(i2)] = instance$4.visit(vals, i2);
    }
    return json2;
  }
  toString() {
    return `{${[...this].map(([key2, val]) => `${valueToString(key2)}: ${valueToString(val)}`).join(", ")}}`;
  }
  [Symbol.for("nodejs.util.inspect.custom")]() {
    return this.toString();
  }
}
class MapRowIterator {
  constructor(keys2, vals) {
    this.keys = keys2;
    this.vals = vals;
    this.keyIndex = 0;
    this.numKeys = keys2.length;
  }
  [Symbol.iterator]() {
    return this;
  }
  next() {
    const i2 = this.keyIndex;
    if (i2 === this.numKeys) {
      return { done: true, value: null };
    }
    this.keyIndex++;
    return {
      done: false,
      value: [
        this.keys.get(i2),
        instance$4.visit(this.vals, i2)
      ]
    };
  }
}
class MapRowProxyHandler {
  isExtensible() {
    return false;
  }
  deleteProperty() {
    return false;
  }
  preventExtensions() {
    return true;
  }
  ownKeys(row2) {
    return row2[kKeysAsStrings];
  }
  has(row2, key2) {
    return row2[kKeysAsStrings].includes(key2);
  }
  getOwnPropertyDescriptor(row2, key2) {
    const idx = row2[kKeysAsStrings].indexOf(key2);
    if (idx !== -1) {
      return { writable: true, enumerable: true, configurable: true };
    }
    return;
  }
  get(row2, key2) {
    if (Reflect.has(row2, key2)) {
      return row2[key2];
    }
    const idx = row2[kKeysAsStrings].indexOf(key2);
    if (idx !== -1) {
      const val = instance$4.visit(Reflect.get(row2, kVals), idx);
      Reflect.set(row2, key2, val);
      return val;
    }
  }
  set(row2, key2, val) {
    const idx = row2[kKeysAsStrings].indexOf(key2);
    if (idx !== -1) {
      instance$5.visit(Reflect.get(row2, kVals), idx, val);
      return Reflect.set(row2, key2, val);
    } else if (Reflect.has(row2, key2)) {
      return Reflect.set(row2, key2, val);
    }
    return false;
  }
}
Object.defineProperties(MapRow.prototype, {
  [Symbol.toStringTag]: { enumerable: false, configurable: false, value: "Row" },
  [kKeys]: { writable: true, enumerable: false, configurable: false, value: null },
  [kVals]: { writable: true, enumerable: false, configurable: false, value: null },
  [_kKeysAsStrings]: { writable: true, enumerable: false, configurable: false, value: null }
});
let tmp;
function clampRange(source2, begin, end2, then) {
  const { length: len = 0 } = source2;
  let lhs = typeof begin !== "number" ? 0 : begin;
  let rhs = typeof end2 !== "number" ? len : end2;
  lhs < 0 && (lhs = (lhs % len + len) % len);
  rhs < 0 && (rhs = (rhs % len + len) % len);
  rhs < lhs && (tmp = lhs, lhs = rhs, rhs = tmp);
  rhs > len && (rhs = len);
  return then ? then(source2, lhs, rhs) : [lhs, rhs];
}
const wrapIndex = (index, len) => index < 0 ? len + index : index;
const isNaNFast = (value2) => value2 !== value2;
function createElementComparator(search) {
  const typeofSearch = typeof search;
  if (typeofSearch !== "object" || search === null) {
    if (isNaNFast(search)) {
      return isNaNFast;
    }
    return (value2) => value2 === search;
  }
  if (search instanceof Date) {
    const valueOfSearch = search.valueOf();
    return (value2) => value2 instanceof Date ? value2.valueOf() === valueOfSearch : false;
  }
  if (ArrayBuffer.isView(search)) {
    return (value2) => value2 ? compareArrayLike(search, value2) : false;
  }
  if (search instanceof Map) {
    return createMapComparator(search);
  }
  if (Array.isArray(search)) {
    return createArrayLikeComparator(search);
  }
  if (search instanceof Vector) {
    return createVectorComparator(search);
  }
  return createObjectComparator(search, true);
}
function createArrayLikeComparator(lhs) {
  const comparators = [];
  for (let i2 = -1, n2 = lhs.length; ++i2 < n2; ) {
    comparators[i2] = createElementComparator(lhs[i2]);
  }
  return createSubElementsComparator(comparators);
}
function createMapComparator(lhs) {
  let i2 = -1;
  const comparators = [];
  for (const v of lhs.values())
    comparators[++i2] = createElementComparator(v);
  return createSubElementsComparator(comparators);
}
function createVectorComparator(lhs) {
  const comparators = [];
  for (let i2 = -1, n2 = lhs.length; ++i2 < n2; ) {
    comparators[i2] = createElementComparator(lhs.get(i2));
  }
  return createSubElementsComparator(comparators);
}
function createObjectComparator(lhs, allowEmpty = false) {
  const keys2 = Object.keys(lhs);
  if (!allowEmpty && keys2.length === 0) {
    return () => false;
  }
  const comparators = [];
  for (let i2 = -1, n2 = keys2.length; ++i2 < n2; ) {
    comparators[i2] = createElementComparator(lhs[keys2[i2]]);
  }
  return createSubElementsComparator(comparators, keys2);
}
function createSubElementsComparator(comparators, keys2) {
  return (rhs) => {
    if (!rhs || typeof rhs !== "object") {
      return false;
    }
    switch (rhs.constructor) {
      case Array:
        return compareArray(comparators, rhs);
      case Map:
        return compareObject(comparators, rhs, rhs.keys());
      case MapRow:
      case StructRow:
      case Object:
      case void 0:
        return compareObject(comparators, rhs, keys2 || Object.keys(rhs));
    }
    return rhs instanceof Vector ? compareVector(comparators, rhs) : false;
  };
}
function compareArray(comparators, arr) {
  const n2 = comparators.length;
  if (arr.length !== n2) {
    return false;
  }
  for (let i2 = -1; ++i2 < n2; ) {
    if (!comparators[i2](arr[i2])) {
      return false;
    }
  }
  return true;
}
function compareVector(comparators, vec) {
  const n2 = comparators.length;
  if (vec.length !== n2) {
    return false;
  }
  for (let i2 = -1; ++i2 < n2; ) {
    if (!comparators[i2](vec.get(i2))) {
      return false;
    }
  }
  return true;
}
function compareObject(comparators, obj, keys2) {
  const lKeyItr = keys2[Symbol.iterator]();
  const rKeyItr = obj instanceof Map ? obj.keys() : Object.keys(obj)[Symbol.iterator]();
  const rValItr = obj instanceof Map ? obj.values() : Object.values(obj)[Symbol.iterator]();
  let i2 = 0;
  const n2 = comparators.length;
  let rVal = rValItr.next();
  let lKey = lKeyItr.next();
  let rKey = rKeyItr.next();
  for (; i2 < n2 && !lKey.done && !rKey.done && !rVal.done; ++i2, lKey = lKeyItr.next(), rKey = rKeyItr.next(), rVal = rValItr.next()) {
    if (lKey.value !== rKey.value || !comparators[i2](rVal.value)) {
      break;
    }
  }
  if (i2 === n2 && lKey.done && rKey.done && rVal.done) {
    return true;
  }
  lKeyItr.return && lKeyItr.return();
  rKeyItr.return && rKeyItr.return();
  rValItr.return && rValItr.return();
  return false;
}
function getBool(_data, _index, byte, bit) {
  return (byte & 1 << bit) !== 0;
}
function getBit(_data, _index, byte, bit) {
  return (byte & 1 << bit) >> bit;
}
function truncateBitmap(offset3, length2, bitmap2) {
  const alignedSize = bitmap2.byteLength + 7 & -8;
  if (offset3 > 0 || bitmap2.byteLength < alignedSize) {
    const bytes = new Uint8Array(alignedSize);
    bytes.set(offset3 % 8 === 0 ? bitmap2.subarray(offset3 >> 3) : (
      // Otherwise iterate each bit from the offset and return a new one
      packBools(new BitIterator(bitmap2, offset3, length2, null, getBool)).subarray(0, alignedSize)
    ));
    return bytes;
  }
  return bitmap2;
}
function packBools(values2) {
  const xs = [];
  let i2 = 0, bit = 0, byte = 0;
  for (const value2 of values2) {
    value2 && (byte |= 1 << bit);
    if (++bit === 8) {
      xs[i2++] = byte;
      byte = bit = 0;
    }
  }
  if (i2 === 0 || bit > 0) {
    xs[i2++] = byte;
  }
  const b = new Uint8Array(xs.length + 7 & -8);
  b.set(xs);
  return b;
}
class BitIterator {
  constructor(bytes, begin, length2, context, get2) {
    this.bytes = bytes;
    this.length = length2;
    this.context = context;
    this.get = get2;
    this.bit = begin % 8;
    this.byteIndex = begin >> 3;
    this.byte = bytes[this.byteIndex++];
    this.index = 0;
  }
  next() {
    if (this.index < this.length) {
      if (this.bit === 8) {
        this.bit = 0;
        this.byte = this.bytes[this.byteIndex++];
      }
      return {
        value: this.get(this.context, this.index++, this.byte, this.bit++)
      };
    }
    return { done: true, value: null };
  }
  [Symbol.iterator]() {
    return this;
  }
}
function popcnt_bit_range(data2, lhs, rhs) {
  if (rhs - lhs <= 0) {
    return 0;
  }
  if (rhs - lhs < 8) {
    let sum = 0;
    for (const bit of new BitIterator(data2, lhs, rhs - lhs, data2, getBit)) {
      sum += bit;
    }
    return sum;
  }
  const rhsInside = rhs >> 3 << 3;
  const lhsInside = lhs + (lhs % 8 === 0 ? 0 : 8 - lhs % 8);
  return (
    // Get the popcnt of bits between the left hand side, and the next highest multiple of 8
    popcnt_bit_range(data2, lhs, lhsInside) + // Get the popcnt of bits between the right hand side, and the next lowest multiple of 8
    popcnt_bit_range(data2, rhsInside, rhs) + // Get the popcnt of all bits between the left and right hand sides' multiples of 8
    popcnt_array(data2, lhsInside >> 3, rhsInside - lhsInside >> 3)
  );
}
function popcnt_array(arr, byteOffset, byteLength) {
  let cnt = 0, pos2 = Math.trunc(byteOffset);
  const view = new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
  const len = byteLength === void 0 ? arr.byteLength : pos2 + byteLength;
  while (len - pos2 >= 4) {
    cnt += popcnt_uint32(view.getUint32(pos2));
    pos2 += 4;
  }
  while (len - pos2 >= 2) {
    cnt += popcnt_uint32(view.getUint16(pos2));
    pos2 += 2;
  }
  while (len - pos2 >= 1) {
    cnt += popcnt_uint32(view.getUint8(pos2));
    pos2 += 1;
  }
  return cnt;
}
function popcnt_uint32(uint322) {
  let i2 = Math.trunc(uint322);
  i2 = i2 - (i2 >>> 1 & 1431655765);
  i2 = (i2 & 858993459) + (i2 >>> 2 & 858993459);
  return (i2 + (i2 >>> 4) & 252645135) * 16843009 >>> 24;
}
const kUnknownNullCount = -1;
class Data {
  get typeId() {
    return this.type.typeId;
  }
  get ArrayType() {
    return this.type.ArrayType;
  }
  get buffers() {
    return [this.valueOffsets, this.values, this.nullBitmap, this.typeIds];
  }
  get nullable() {
    if (this._nullCount !== 0) {
      const { type } = this;
      if (DataType.isSparseUnion(type)) {
        return this.children.some((child) => child.nullable);
      } else if (DataType.isDenseUnion(type)) {
        return this.children.some((child) => child.nullable);
      }
      return this.nullBitmap && this.nullBitmap.byteLength > 0;
    }
    return true;
  }
  get byteLength() {
    let byteLength = 0;
    const { valueOffsets, values: values2, nullBitmap, typeIds } = this;
    valueOffsets && (byteLength += valueOffsets.byteLength);
    values2 && (byteLength += values2.byteLength);
    nullBitmap && (byteLength += nullBitmap.byteLength);
    typeIds && (byteLength += typeIds.byteLength);
    return this.children.reduce((byteLength2, child) => byteLength2 + child.byteLength, byteLength);
  }
  get nullCount() {
    if (DataType.isUnion(this.type)) {
      return this.children.reduce((nullCount2, child) => nullCount2 + child.nullCount, 0);
    }
    let nullCount = this._nullCount;
    let nullBitmap;
    if (nullCount <= kUnknownNullCount && (nullBitmap = this.nullBitmap)) {
      this._nullCount = nullCount = nullBitmap.length === 0 ? (
        // no null bitmap, so all values are valid
        0
      ) : this.length - popcnt_bit_range(nullBitmap, this.offset, this.offset + this.length);
    }
    return nullCount;
  }
  constructor(type, offset3, length2, nullCount, buffers, children2 = [], dictionary2) {
    this.type = type;
    this.children = children2;
    this.dictionary = dictionary2;
    this.offset = Math.floor(Math.max(offset3 || 0, 0));
    this.length = Math.floor(Math.max(length2 || 0, 0));
    this._nullCount = Math.floor(Math.max(nullCount || 0, -1));
    let buffer2;
    if (buffers instanceof Data) {
      this.stride = buffers.stride;
      this.values = buffers.values;
      this.typeIds = buffers.typeIds;
      this.nullBitmap = buffers.nullBitmap;
      this.valueOffsets = buffers.valueOffsets;
    } else {
      this.stride = strideForType(type);
      if (buffers) {
        (buffer2 = buffers[0]) && (this.valueOffsets = buffer2);
        (buffer2 = buffers[1]) && (this.values = buffer2);
        (buffer2 = buffers[2]) && (this.nullBitmap = buffer2);
        (buffer2 = buffers[3]) && (this.typeIds = buffer2);
      }
    }
  }
  getValid(index) {
    const { type } = this;
    if (DataType.isUnion(type)) {
      const union2 = type;
      const child = this.children[union2.typeIdToChildIndex[this.typeIds[index]]];
      const indexInChild = union2.mode === UnionMode$1.Dense ? this.valueOffsets[index] : index;
      return child.getValid(indexInChild);
    }
    if (this.nullable && this.nullCount > 0) {
      const pos2 = this.offset + index;
      const val = this.nullBitmap[pos2 >> 3];
      return (val & 1 << pos2 % 8) !== 0;
    }
    return true;
  }
  setValid(index, value2) {
    let prev;
    const { type } = this;
    if (DataType.isUnion(type)) {
      const union2 = type;
      const child = this.children[union2.typeIdToChildIndex[this.typeIds[index]]];
      const indexInChild = union2.mode === UnionMode$1.Dense ? this.valueOffsets[index] : index;
      prev = child.getValid(indexInChild);
      child.setValid(indexInChild, value2);
    } else {
      let { nullBitmap } = this;
      const { offset: offset3, length: length2 } = this;
      const idx = offset3 + index;
      const mask = 1 << idx % 8;
      const byteOffset = idx >> 3;
      if (!nullBitmap || nullBitmap.byteLength <= byteOffset) {
        nullBitmap = new Uint8Array((offset3 + length2 + 63 & -64) >> 3).fill(255);
        if (this.nullCount > 0) {
          nullBitmap.set(truncateBitmap(offset3, length2, this.nullBitmap), 0);
          Object.assign(this, { nullBitmap });
        } else {
          Object.assign(this, { nullBitmap, _nullCount: 0 });
        }
      }
      const byte = nullBitmap[byteOffset];
      prev = (byte & mask) !== 0;
      nullBitmap[byteOffset] = value2 ? byte | mask : byte & ~mask;
    }
    if (prev !== !!value2) {
      this._nullCount = this.nullCount + (value2 ? -1 : 1);
    }
    return value2;
  }
  clone(type = this.type, offset3 = this.offset, length2 = this.length, nullCount = this._nullCount, buffers = this, children2 = this.children) {
    return new Data(type, offset3, length2, nullCount, buffers, children2, this.dictionary);
  }
  slice(offset3, length2) {
    const { stride, typeId, children: children2 } = this;
    const nullCount = +(this._nullCount === 0) - 1;
    const childStride = typeId === 16 ? stride : 1;
    const buffers = this._sliceBuffers(offset3, length2, stride, typeId);
    return this.clone(
      this.type,
      this.offset + offset3,
      length2,
      nullCount,
      buffers,
      // Don't slice children if we have value offsets (the variable-width types)
      children2.length === 0 || this.valueOffsets ? children2 : this._sliceChildren(children2, childStride * offset3, childStride * length2)
    );
  }
  _changeLengthAndBackfillNullBitmap(newLength) {
    if (this.typeId === Type$1.Null) {
      return this.clone(this.type, 0, newLength, 0);
    }
    const { length: length2, nullCount } = this;
    const bitmap2 = new Uint8Array((newLength + 63 & -64) >> 3).fill(255, 0, length2 >> 3);
    bitmap2[length2 >> 3] = (1 << length2 - (length2 & -8)) - 1;
    if (nullCount > 0) {
      bitmap2.set(truncateBitmap(this.offset, length2, this.nullBitmap), 0);
    }
    const buffers = this.buffers;
    buffers[BufferType.VALIDITY] = bitmap2;
    return this.clone(this.type, 0, newLength, nullCount + (newLength - length2), buffers);
  }
  _sliceBuffers(offset3, length2, stride, typeId) {
    let arr;
    const { buffers } = this;
    (arr = buffers[BufferType.TYPE]) && (buffers[BufferType.TYPE] = arr.subarray(offset3, offset3 + length2));
    (arr = buffers[BufferType.OFFSET]) && (buffers[BufferType.OFFSET] = arr.subarray(offset3, offset3 + length2 + 1)) || // Otherwise if no offsets, slice the data buffer. Don't slice the data vector for Booleans, since the offset goes by bits not bytes
    (arr = buffers[BufferType.DATA]) && (buffers[BufferType.DATA] = typeId === 6 ? arr : arr.subarray(stride * offset3, stride * (offset3 + length2)));
    return buffers;
  }
  _sliceChildren(children2, offset3, length2) {
    return children2.map((child) => child.slice(offset3, length2));
  }
}
Data.prototype.children = Object.freeze([]);
class MakeDataVisitor extends Visitor {
  visit(props) {
    return this.getVisitFn(props["type"]).call(this, props);
  }
  visitNull(props) {
    const { ["type"]: type, ["offset"]: offset3 = 0, ["length"]: length2 = 0 } = props;
    return new Data(type, offset3, length2, length2);
  }
  visitBool(props) {
    const { ["type"]: type, ["offset"]: offset3 = 0 } = props;
    const nullBitmap = toUint8Array(props["nullBitmap"]);
    const data2 = toArrayBufferView(type.ArrayType, props["data"]);
    const { ["length"]: length2 = data2.length >> 3, ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props;
    return new Data(type, offset3, length2, nullCount, [void 0, data2, nullBitmap]);
  }
  visitInt(props) {
    const { ["type"]: type, ["offset"]: offset3 = 0 } = props;
    const nullBitmap = toUint8Array(props["nullBitmap"]);
    const data2 = toArrayBufferView(type.ArrayType, props["data"]);
    const { ["length"]: length2 = data2.length, ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props;
    return new Data(type, offset3, length2, nullCount, [void 0, data2, nullBitmap]);
  }
  visitFloat(props) {
    const { ["type"]: type, ["offset"]: offset3 = 0 } = props;
    const nullBitmap = toUint8Array(props["nullBitmap"]);
    const data2 = toArrayBufferView(type.ArrayType, props["data"]);
    const { ["length"]: length2 = data2.length, ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props;
    return new Data(type, offset3, length2, nullCount, [void 0, data2, nullBitmap]);
  }
  visitUtf8(props) {
    const { ["type"]: type, ["offset"]: offset3 = 0 } = props;
    const data2 = toUint8Array(props["data"]);
    const nullBitmap = toUint8Array(props["nullBitmap"]);
    const valueOffsets = toInt32Array(props["valueOffsets"]);
    const { ["length"]: length2 = valueOffsets.length - 1, ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props;
    return new Data(type, offset3, length2, nullCount, [valueOffsets, data2, nullBitmap]);
  }
  visitLargeUtf8(props) {
    const { ["type"]: type, ["offset"]: offset3 = 0 } = props;
    const data2 = toUint8Array(props["data"]);
    const nullBitmap = toUint8Array(props["nullBitmap"]);
    const valueOffsets = toBigInt64Array(props["valueOffsets"]);
    const { ["length"]: length2 = valueOffsets.length - 1, ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props;
    return new Data(type, offset3, length2, nullCount, [valueOffsets, data2, nullBitmap]);
  }
  visitBinary(props) {
    const { ["type"]: type, ["offset"]: offset3 = 0 } = props;
    const data2 = toUint8Array(props["data"]);
    const nullBitmap = toUint8Array(props["nullBitmap"]);
    const valueOffsets = toInt32Array(props["valueOffsets"]);
    const { ["length"]: length2 = valueOffsets.length - 1, ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props;
    return new Data(type, offset3, length2, nullCount, [valueOffsets, data2, nullBitmap]);
  }
  visitLargeBinary(props) {
    const { ["type"]: type, ["offset"]: offset3 = 0 } = props;
    const data2 = toUint8Array(props["data"]);
    const nullBitmap = toUint8Array(props["nullBitmap"]);
    const valueOffsets = toBigInt64Array(props["valueOffsets"]);
    const { ["length"]: length2 = valueOffsets.length - 1, ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props;
    return new Data(type, offset3, length2, nullCount, [valueOffsets, data2, nullBitmap]);
  }
  visitFixedSizeBinary(props) {
    const { ["type"]: type, ["offset"]: offset3 = 0 } = props;
    const nullBitmap = toUint8Array(props["nullBitmap"]);
    const data2 = toArrayBufferView(type.ArrayType, props["data"]);
    const { ["length"]: length2 = data2.length / strideForType(type), ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props;
    return new Data(type, offset3, length2, nullCount, [void 0, data2, nullBitmap]);
  }
  visitDate(props) {
    const { ["type"]: type, ["offset"]: offset3 = 0 } = props;
    const nullBitmap = toUint8Array(props["nullBitmap"]);
    const data2 = toArrayBufferView(type.ArrayType, props["data"]);
    const { ["length"]: length2 = data2.length / strideForType(type), ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props;
    return new Data(type, offset3, length2, nullCount, [void 0, data2, nullBitmap]);
  }
  visitTimestamp(props) {
    const { ["type"]: type, ["offset"]: offset3 = 0 } = props;
    const nullBitmap = toUint8Array(props["nullBitmap"]);
    const data2 = toArrayBufferView(type.ArrayType, props["data"]);
    const { ["length"]: length2 = data2.length / strideForType(type), ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props;
    return new Data(type, offset3, length2, nullCount, [void 0, data2, nullBitmap]);
  }
  visitTime(props) {
    const { ["type"]: type, ["offset"]: offset3 = 0 } = props;
    const nullBitmap = toUint8Array(props["nullBitmap"]);
    const data2 = toArrayBufferView(type.ArrayType, props["data"]);
    const { ["length"]: length2 = data2.length / strideForType(type), ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props;
    return new Data(type, offset3, length2, nullCount, [void 0, data2, nullBitmap]);
  }
  visitDecimal(props) {
    const { ["type"]: type, ["offset"]: offset3 = 0 } = props;
    const nullBitmap = toUint8Array(props["nullBitmap"]);
    const data2 = toArrayBufferView(type.ArrayType, props["data"]);
    const { ["length"]: length2 = data2.length / strideForType(type), ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props;
    return new Data(type, offset3, length2, nullCount, [void 0, data2, nullBitmap]);
  }
  visitList(props) {
    const { ["type"]: type, ["offset"]: offset3 = 0, ["child"]: child } = props;
    const nullBitmap = toUint8Array(props["nullBitmap"]);
    const valueOffsets = toInt32Array(props["valueOffsets"]);
    const { ["length"]: length2 = valueOffsets.length - 1, ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props;
    return new Data(type, offset3, length2, nullCount, [valueOffsets, void 0, nullBitmap], [child]);
  }
  visitStruct(props) {
    const { ["type"]: type, ["offset"]: offset3 = 0, ["children"]: children2 = [] } = props;
    const nullBitmap = toUint8Array(props["nullBitmap"]);
    const { length: length2 = children2.reduce((len, { length: length3 }) => Math.max(len, length3), 0), nullCount = props["nullBitmap"] ? -1 : 0 } = props;
    return new Data(type, offset3, length2, nullCount, [void 0, void 0, nullBitmap], children2);
  }
  visitUnion(props) {
    const { ["type"]: type, ["offset"]: offset3 = 0, ["children"]: children2 = [] } = props;
    const typeIds = toArrayBufferView(type.ArrayType, props["typeIds"]);
    const { ["length"]: length2 = typeIds.length, ["nullCount"]: nullCount = -1 } = props;
    if (DataType.isSparseUnion(type)) {
      return new Data(type, offset3, length2, nullCount, [void 0, void 0, void 0, typeIds], children2);
    }
    const valueOffsets = toInt32Array(props["valueOffsets"]);
    return new Data(type, offset3, length2, nullCount, [valueOffsets, void 0, void 0, typeIds], children2);
  }
  visitDictionary(props) {
    const { ["type"]: type, ["offset"]: offset3 = 0 } = props;
    const nullBitmap = toUint8Array(props["nullBitmap"]);
    const data2 = toArrayBufferView(type.indices.ArrayType, props["data"]);
    const { ["dictionary"]: dictionary2 = new Vector([new MakeDataVisitor().visit({ type: type.dictionary })]) } = props;
    const { ["length"]: length2 = data2.length, ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props;
    return new Data(type, offset3, length2, nullCount, [void 0, data2, nullBitmap], [], dictionary2);
  }
  visitInterval(props) {
    const { ["type"]: type, ["offset"]: offset3 = 0 } = props;
    const nullBitmap = toUint8Array(props["nullBitmap"]);
    const data2 = toArrayBufferView(type.ArrayType, props["data"]);
    const { ["length"]: length2 = data2.length / strideForType(type), ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props;
    return new Data(type, offset3, length2, nullCount, [void 0, data2, nullBitmap]);
  }
  visitDuration(props) {
    const { ["type"]: type, ["offset"]: offset3 = 0 } = props;
    const nullBitmap = toUint8Array(props["nullBitmap"]);
    const data2 = toArrayBufferView(type.ArrayType, props["data"]);
    const { ["length"]: length2 = data2.length, ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props;
    return new Data(type, offset3, length2, nullCount, [void 0, data2, nullBitmap]);
  }
  visitFixedSizeList(props) {
    const { ["type"]: type, ["offset"]: offset3 = 0, ["child"]: child = new MakeDataVisitor().visit({ type: type.valueType }) } = props;
    const nullBitmap = toUint8Array(props["nullBitmap"]);
    const { ["length"]: length2 = child.length / strideForType(type), ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props;
    return new Data(type, offset3, length2, nullCount, [void 0, void 0, nullBitmap], [child]);
  }
  visitMap(props) {
    const { ["type"]: type, ["offset"]: offset3 = 0, ["child"]: child = new MakeDataVisitor().visit({ type: type.childType }) } = props;
    const nullBitmap = toUint8Array(props["nullBitmap"]);
    const valueOffsets = toInt32Array(props["valueOffsets"]);
    const { ["length"]: length2 = valueOffsets.length - 1, ["nullCount"]: nullCount = props["nullBitmap"] ? -1 : 0 } = props;
    return new Data(type, offset3, length2, nullCount, [valueOffsets, void 0, nullBitmap], [child]);
  }
}
const makeDataVisitor = new MakeDataVisitor();
function makeData(props) {
  return makeDataVisitor.visit(props);
}
class ChunkedIterator {
  constructor(numChunks = 0, getChunkIterator) {
    this.numChunks = numChunks;
    this.getChunkIterator = getChunkIterator;
    this.chunkIndex = 0;
    this.chunkIterator = this.getChunkIterator(0);
  }
  next() {
    while (this.chunkIndex < this.numChunks) {
      const next = this.chunkIterator.next();
      if (!next.done) {
        return next;
      }
      if (++this.chunkIndex < this.numChunks) {
        this.chunkIterator = this.getChunkIterator(this.chunkIndex);
      }
    }
    return { done: true, value: null };
  }
  [Symbol.iterator]() {
    return this;
  }
}
function computeChunkNullable(chunks) {
  return chunks.some((chunk) => chunk.nullable);
}
function computeChunkNullCounts(chunks) {
  return chunks.reduce((nullCount, chunk) => nullCount + chunk.nullCount, 0);
}
function computeChunkOffsets(chunks) {
  return chunks.reduce((offsets, chunk, index) => {
    offsets[index + 1] = offsets[index] + chunk.length;
    return offsets;
  }, new Uint32Array(chunks.length + 1));
}
function sliceChunks(chunks, offsets, begin, end2) {
  const slices = [];
  for (let i2 = -1, n2 = chunks.length; ++i2 < n2; ) {
    const chunk = chunks[i2];
    const offset3 = offsets[i2];
    const { length: length2 } = chunk;
    if (offset3 >= end2) {
      break;
    }
    if (begin >= offset3 + length2) {
      continue;
    }
    if (offset3 >= begin && offset3 + length2 <= end2) {
      slices.push(chunk);
      continue;
    }
    const from2 = Math.max(0, begin - offset3);
    const to2 = Math.min(end2 - offset3, length2);
    slices.push(chunk.slice(from2, to2 - from2));
  }
  if (slices.length === 0) {
    slices.push(chunks[0].slice(0, 0));
  }
  return slices;
}
function binarySearch(chunks, offsets, idx, fn3) {
  let lhs = 0, mid = 0, rhs = offsets.length - 1;
  do {
    if (lhs >= rhs - 1) {
      return idx < offsets[rhs] ? fn3(chunks, lhs, idx - offsets[lhs]) : null;
    }
    mid = lhs + Math.trunc((rhs - lhs) * 0.5);
    idx < offsets[mid] ? rhs = mid : lhs = mid;
  } while (lhs < rhs);
}
function isChunkedValid(data2, index) {
  return data2.getValid(index);
}
function wrapChunkedCall1(fn3) {
  function chunkedFn(chunks, i2, j2) {
    return fn3(chunks[i2], j2);
  }
  return function(index) {
    const data2 = this.data;
    return binarySearch(data2, this._offsets, index, chunkedFn);
  };
}
function wrapChunkedCall2(fn3) {
  let _2;
  function chunkedFn(chunks, i2, j2) {
    return fn3(chunks[i2], j2, _2);
  }
  return function(index, value2) {
    const data2 = this.data;
    _2 = value2;
    const result2 = binarySearch(data2, this._offsets, index, chunkedFn);
    _2 = void 0;
    return result2;
  };
}
function wrapChunkedIndexOf(indexOf) {
  let _1;
  function chunkedIndexOf(data2, chunkIndex, fromIndex) {
    let begin = fromIndex, index = 0, total = 0;
    for (let i2 = chunkIndex - 1, n2 = data2.length; ++i2 < n2; ) {
      const chunk = data2[i2];
      if (~(index = indexOf(chunk, _1, begin))) {
        return total + index;
      }
      begin = 0;
      total += chunk.length;
    }
    return -1;
  }
  return function(element, offset3) {
    _1 = element;
    const data2 = this.data;
    const result2 = typeof offset3 !== "number" ? chunkedIndexOf(data2, 0, 0) : binarySearch(data2, this._offsets, offset3, chunkedIndexOf);
    _1 = void 0;
    return result2;
  };
}
class IndexOfVisitor extends Visitor {
}
function nullIndexOf(data2, searchElement) {
  return searchElement === null && data2.length > 0 ? 0 : -1;
}
function indexOfNull(data2, fromIndex) {
  const { nullBitmap } = data2;
  if (!nullBitmap || data2.nullCount <= 0) {
    return -1;
  }
  let i2 = 0;
  for (const isValid2 of new BitIterator(nullBitmap, data2.offset + (fromIndex || 0), data2.length, nullBitmap, getBool)) {
    if (!isValid2) {
      return i2;
    }
    ++i2;
  }
  return -1;
}
function indexOfValue(data2, searchElement, fromIndex) {
  if (searchElement === void 0) {
    return -1;
  }
  if (searchElement === null) {
    switch (data2.typeId) {
      // Unions don't have a nullBitmap of its own, so compare the `searchElement` to `get()`.
      case Type$1.Union:
        break;
      // Dictionaries do have a nullBitmap, but their dictionary could also have null elements.
      case Type$1.Dictionary:
        break;
      // All other types can iterate the null bitmap
      default:
        return indexOfNull(data2, fromIndex);
    }
  }
  const get2 = instance$4.getVisitFn(data2);
  const compare2 = createElementComparator(searchElement);
  for (let i2 = (fromIndex || 0) - 1, n2 = data2.length; ++i2 < n2; ) {
    if (compare2(get2(data2, i2))) {
      return i2;
    }
  }
  return -1;
}
function indexOfUnion(data2, searchElement, fromIndex) {
  const get2 = instance$4.getVisitFn(data2);
  const compare2 = createElementComparator(searchElement);
  for (let i2 = (fromIndex || 0) - 1, n2 = data2.length; ++i2 < n2; ) {
    if (compare2(get2(data2, i2))) {
      return i2;
    }
  }
  return -1;
}
IndexOfVisitor.prototype.visitNull = nullIndexOf;
IndexOfVisitor.prototype.visitBool = indexOfValue;
IndexOfVisitor.prototype.visitInt = indexOfValue;
IndexOfVisitor.prototype.visitInt8 = indexOfValue;
IndexOfVisitor.prototype.visitInt16 = indexOfValue;
IndexOfVisitor.prototype.visitInt32 = indexOfValue;
IndexOfVisitor.prototype.visitInt64 = indexOfValue;
IndexOfVisitor.prototype.visitUint8 = indexOfValue;
IndexOfVisitor.prototype.visitUint16 = indexOfValue;
IndexOfVisitor.prototype.visitUint32 = indexOfValue;
IndexOfVisitor.prototype.visitUint64 = indexOfValue;
IndexOfVisitor.prototype.visitFloat = indexOfValue;
IndexOfVisitor.prototype.visitFloat16 = indexOfValue;
IndexOfVisitor.prototype.visitFloat32 = indexOfValue;
IndexOfVisitor.prototype.visitFloat64 = indexOfValue;
IndexOfVisitor.prototype.visitUtf8 = indexOfValue;
IndexOfVisitor.prototype.visitLargeUtf8 = indexOfValue;
IndexOfVisitor.prototype.visitBinary = indexOfValue;
IndexOfVisitor.prototype.visitLargeBinary = indexOfValue;
IndexOfVisitor.prototype.visitFixedSizeBinary = indexOfValue;
IndexOfVisitor.prototype.visitDate = indexOfValue;
IndexOfVisitor.prototype.visitDateDay = indexOfValue;
IndexOfVisitor.prototype.visitDateMillisecond = indexOfValue;
IndexOfVisitor.prototype.visitTimestamp = indexOfValue;
IndexOfVisitor.prototype.visitTimestampSecond = indexOfValue;
IndexOfVisitor.prototype.visitTimestampMillisecond = indexOfValue;
IndexOfVisitor.prototype.visitTimestampMicrosecond = indexOfValue;
IndexOfVisitor.prototype.visitTimestampNanosecond = indexOfValue;
IndexOfVisitor.prototype.visitTime = indexOfValue;
IndexOfVisitor.prototype.visitTimeSecond = indexOfValue;
IndexOfVisitor.prototype.visitTimeMillisecond = indexOfValue;
IndexOfVisitor.prototype.visitTimeMicrosecond = indexOfValue;
IndexOfVisitor.prototype.visitTimeNanosecond = indexOfValue;
IndexOfVisitor.prototype.visitDecimal = indexOfValue;
IndexOfVisitor.prototype.visitList = indexOfValue;
IndexOfVisitor.prototype.visitStruct = indexOfValue;
IndexOfVisitor.prototype.visitUnion = indexOfValue;
IndexOfVisitor.prototype.visitDenseUnion = indexOfUnion;
IndexOfVisitor.prototype.visitSparseUnion = indexOfUnion;
IndexOfVisitor.prototype.visitDictionary = indexOfValue;
IndexOfVisitor.prototype.visitInterval = indexOfValue;
IndexOfVisitor.prototype.visitIntervalDayTime = indexOfValue;
IndexOfVisitor.prototype.visitIntervalYearMonth = indexOfValue;
IndexOfVisitor.prototype.visitIntervalMonthDayNano = indexOfValue;
IndexOfVisitor.prototype.visitDuration = indexOfValue;
IndexOfVisitor.prototype.visitDurationSecond = indexOfValue;
IndexOfVisitor.prototype.visitDurationMillisecond = indexOfValue;
IndexOfVisitor.prototype.visitDurationMicrosecond = indexOfValue;
IndexOfVisitor.prototype.visitDurationNanosecond = indexOfValue;
IndexOfVisitor.prototype.visitFixedSizeList = indexOfValue;
IndexOfVisitor.prototype.visitMap = indexOfValue;
const instance$3 = new IndexOfVisitor();
class IteratorVisitor extends Visitor {
}
function vectorIterator(vector) {
  const { type } = vector;
  if (vector.nullCount === 0 && vector.stride === 1 && // Don't defer to native iterator for timestamps since Numbers are expected
  // (DataType.isTimestamp(type)) && type.unit === TimeUnit.MILLISECOND ||
  (DataType.isInt(type) && type.bitWidth !== 64 || DataType.isTime(type) && type.bitWidth !== 64 || DataType.isFloat(type) && type.precision !== Precision$1.HALF)) {
    return new ChunkedIterator(vector.data.length, (chunkIndex) => {
      const data2 = vector.data[chunkIndex];
      return data2.values.subarray(0, data2.length)[Symbol.iterator]();
    });
  }
  let offset3 = 0;
  return new ChunkedIterator(vector.data.length, (chunkIndex) => {
    const data2 = vector.data[chunkIndex];
    const length2 = data2.length;
    const inner = vector.slice(offset3, offset3 + length2);
    offset3 += length2;
    return new VectorIterator(inner);
  });
}
class VectorIterator {
  constructor(vector) {
    this.vector = vector;
    this.index = 0;
  }
  next() {
    if (this.index < this.vector.length) {
      return {
        value: this.vector.get(this.index++)
      };
    }
    return { done: true, value: null };
  }
  [Symbol.iterator]() {
    return this;
  }
}
IteratorVisitor.prototype.visitNull = vectorIterator;
IteratorVisitor.prototype.visitBool = vectorIterator;
IteratorVisitor.prototype.visitInt = vectorIterator;
IteratorVisitor.prototype.visitInt8 = vectorIterator;
IteratorVisitor.prototype.visitInt16 = vectorIterator;
IteratorVisitor.prototype.visitInt32 = vectorIterator;
IteratorVisitor.prototype.visitInt64 = vectorIterator;
IteratorVisitor.prototype.visitUint8 = vectorIterator;
IteratorVisitor.prototype.visitUint16 = vectorIterator;
IteratorVisitor.prototype.visitUint32 = vectorIterator;
IteratorVisitor.prototype.visitUint64 = vectorIterator;
IteratorVisitor.prototype.visitFloat = vectorIterator;
IteratorVisitor.prototype.visitFloat16 = vectorIterator;
IteratorVisitor.prototype.visitFloat32 = vectorIterator;
IteratorVisitor.prototype.visitFloat64 = vectorIterator;
IteratorVisitor.prototype.visitUtf8 = vectorIterator;
IteratorVisitor.prototype.visitLargeUtf8 = vectorIterator;
IteratorVisitor.prototype.visitBinary = vectorIterator;
IteratorVisitor.prototype.visitLargeBinary = vectorIterator;
IteratorVisitor.prototype.visitFixedSizeBinary = vectorIterator;
IteratorVisitor.prototype.visitDate = vectorIterator;
IteratorVisitor.prototype.visitDateDay = vectorIterator;
IteratorVisitor.prototype.visitDateMillisecond = vectorIterator;
IteratorVisitor.prototype.visitTimestamp = vectorIterator;
IteratorVisitor.prototype.visitTimestampSecond = vectorIterator;
IteratorVisitor.prototype.visitTimestampMillisecond = vectorIterator;
IteratorVisitor.prototype.visitTimestampMicrosecond = vectorIterator;
IteratorVisitor.prototype.visitTimestampNanosecond = vectorIterator;
IteratorVisitor.prototype.visitTime = vectorIterator;
IteratorVisitor.prototype.visitTimeSecond = vectorIterator;
IteratorVisitor.prototype.visitTimeMillisecond = vectorIterator;
IteratorVisitor.prototype.visitTimeMicrosecond = vectorIterator;
IteratorVisitor.prototype.visitTimeNanosecond = vectorIterator;
IteratorVisitor.prototype.visitDecimal = vectorIterator;
IteratorVisitor.prototype.visitList = vectorIterator;
IteratorVisitor.prototype.visitStruct = vectorIterator;
IteratorVisitor.prototype.visitUnion = vectorIterator;
IteratorVisitor.prototype.visitDenseUnion = vectorIterator;
IteratorVisitor.prototype.visitSparseUnion = vectorIterator;
IteratorVisitor.prototype.visitDictionary = vectorIterator;
IteratorVisitor.prototype.visitInterval = vectorIterator;
IteratorVisitor.prototype.visitIntervalDayTime = vectorIterator;
IteratorVisitor.prototype.visitIntervalYearMonth = vectorIterator;
IteratorVisitor.prototype.visitIntervalMonthDayNano = vectorIterator;
IteratorVisitor.prototype.visitDuration = vectorIterator;
IteratorVisitor.prototype.visitDurationSecond = vectorIterator;
IteratorVisitor.prototype.visitDurationMillisecond = vectorIterator;
IteratorVisitor.prototype.visitDurationMicrosecond = vectorIterator;
IteratorVisitor.prototype.visitDurationNanosecond = vectorIterator;
IteratorVisitor.prototype.visitFixedSizeList = vectorIterator;
IteratorVisitor.prototype.visitMap = vectorIterator;
const instance$2 = new IteratorVisitor();
var _a$4;
const visitorsByTypeId = {};
const vectorPrototypesByTypeId = {};
class Vector {
  constructor(input2) {
    var _b2, _c2, _d2;
    const data2 = input2[0] instanceof Vector ? input2.flatMap((x) => x.data) : input2;
    if (data2.length === 0 || data2.some((x) => !(x instanceof Data))) {
      throw new TypeError("Vector constructor expects an Array of Data instances.");
    }
    const type = (_b2 = data2[0]) === null || _b2 === void 0 ? void 0 : _b2.type;
    switch (data2.length) {
      case 0:
        this._offsets = [0];
        break;
      case 1: {
        const { get: get2, set: set3, indexOf } = visitorsByTypeId[type.typeId];
        const unchunkedData = data2[0];
        this.isValid = (index) => isChunkedValid(unchunkedData, index);
        this.get = (index) => get2(unchunkedData, index);
        this.set = (index, value2) => set3(unchunkedData, index, value2);
        this.indexOf = (index) => indexOf(unchunkedData, index);
        this._offsets = [0, unchunkedData.length];
        break;
      }
      default:
        Object.setPrototypeOf(this, vectorPrototypesByTypeId[type.typeId]);
        this._offsets = computeChunkOffsets(data2);
        break;
    }
    this.data = data2;
    this.type = type;
    this.stride = strideForType(type);
    this.numChildren = (_d2 = (_c2 = type.children) === null || _c2 === void 0 ? void 0 : _c2.length) !== null && _d2 !== void 0 ? _d2 : 0;
    this.length = this._offsets.at(-1);
  }
  /**
   * The aggregate size (in bytes) of this Vector's buffers and/or child Vectors.
   */
  get byteLength() {
    return this.data.reduce((byteLength, data2) => byteLength + data2.byteLength, 0);
  }
  /**
   * Whether this Vector's elements can contain null values.
   */
  get nullable() {
    return computeChunkNullable(this.data);
  }
  /**
   * The number of null elements in this Vector.
   */
  get nullCount() {
    return computeChunkNullCounts(this.data);
  }
  /**
   * The Array or TypedArray constructor used for the JS representation
   *  of the element's values in {@link Vector.prototype.toArray `toArray()`}.
   */
  get ArrayType() {
    return this.type.ArrayType;
  }
  /**
   * The name that should be printed when the Vector is logged in a message.
   */
  get [Symbol.toStringTag]() {
    return `${this.VectorName}<${this.type[Symbol.toStringTag]}>`;
  }
  /**
   * The name of this Vector.
   */
  get VectorName() {
    return `${Type$1[this.type.typeId]}Vector`;
  }
  /**
   * Check whether an element is null.
   * @param index The index at which to read the validity bitmap.
   */
  // @ts-ignore
  isValid(index) {
    return false;
  }
  /**
   * Get an element value by position.
   * @param index The index of the element to read.
   */
  // @ts-ignore
  get(index) {
    return null;
  }
  /**
   * Get an element value by position.
   * @param index The index of the element to read. A negative index will count back from the last element.
   */
  at(index) {
    return this.get(wrapIndex(index, this.length));
  }
  /**
   * Set an element value by position.
   * @param index The index of the element to write.
   * @param value The value to set.
   */
  // @ts-ignore
  set(index, value2) {
    return;
  }
  /**
   * Retrieve the index of the first occurrence of a value in an Vector.
   * @param element The value to locate in the Vector.
   * @param offset The index at which to begin the search. If offset is omitted, the search starts at index 0.
   */
  // @ts-ignore
  indexOf(element, offset3) {
    return -1;
  }
  includes(element, offset3) {
    return this.indexOf(element, offset3) > -1;
  }
  /**
   * Iterator for the Vector's elements.
   */
  [Symbol.iterator]() {
    return instance$2.visit(this);
  }
  /**
   * Combines two or more Vectors of the same type.
   * @param others Additional Vectors to add to the end of this Vector.
   */
  concat(...others) {
    return new Vector(this.data.concat(others.flatMap((x) => x.data).flat(Number.POSITIVE_INFINITY)));
  }
  /**
   * Return a zero-copy sub-section of this Vector.
   * @param start The beginning of the specified portion of the Vector.
   * @param end The end of the specified portion of the Vector. This is exclusive of the element at the index 'end'.
   */
  slice(begin, end2) {
    return new Vector(clampRange(this, begin, end2, ({ data: data2, _offsets }, begin2, end3) => sliceChunks(data2, _offsets, begin2, end3)));
  }
  toJSON() {
    return [...this];
  }
  /**
   * Return a JavaScript Array or TypedArray of the Vector's elements.
   *
   * @note If this Vector contains a single Data chunk and the Vector's type is a
   *  primitive numeric type corresponding to one of the JavaScript TypedArrays, this
   *  method returns a zero-copy slice of the underlying TypedArray values. If there's
   *  more than one chunk, the resulting TypedArray will be a copy of the data from each
   *  chunk's underlying TypedArray values.
   *
   * @returns An Array or TypedArray of the Vector's elements, based on the Vector's DataType.
   */
  toArray() {
    const { type, data: data2, length: length2, stride, ArrayType } = this;
    switch (type.typeId) {
      case Type$1.Int:
      case Type$1.Float:
      case Type$1.Decimal:
      case Type$1.Time:
      case Type$1.Timestamp:
        switch (data2.length) {
          case 0:
            return new ArrayType();
          case 1:
            return data2[0].values.subarray(0, length2 * stride);
          default:
            return data2.reduce((memo2, { values: values2, length: chunk_length }) => {
              memo2.array.set(values2.subarray(0, chunk_length * stride), memo2.offset);
              memo2.offset += chunk_length * stride;
              return memo2;
            }, { array: new ArrayType(length2 * stride), offset: 0 }).array;
        }
    }
    return [...this];
  }
  /**
   * Returns a string representation of the Vector.
   *
   * @returns A string representation of the Vector.
   */
  toString() {
    return `[${[...this].join(",")}]`;
  }
  /**
   * Returns a child Vector by name, or null if this Vector has no child with the given name.
   * @param name The name of the child to retrieve.
   */
  getChild(name2) {
    var _b2;
    return this.getChildAt((_b2 = this.type.children) === null || _b2 === void 0 ? void 0 : _b2.findIndex((f) => f.name === name2));
  }
  /**
   * Returns a child Vector by index, or null if this Vector has no child at the supplied index.
   * @param index The index of the child to retrieve.
   */
  getChildAt(index) {
    if (index > -1 && index < this.numChildren) {
      return new Vector(this.data.map(({ children: children2 }) => children2[index]));
    }
    return null;
  }
  get isMemoized() {
    if (DataType.isDictionary(this.type)) {
      return this.data[0].dictionary.isMemoized;
    }
    return false;
  }
  /**
   * Adds memoization to the Vector's {@link get} method. For dictionary
   * vectors, this method return a vector that memoizes only the dictionary
   * values.
   *
   * Memoization is very useful when decoding a value is expensive such as
   * Utf8. The memoization creates a cache of the size of the Vector and
   * therefore increases memory usage.
   *
   * @returns A new vector that memoizes calls to {@link get}.
   */
  memoize() {
    if (DataType.isDictionary(this.type)) {
      const dictionary2 = new MemoizedVector(this.data[0].dictionary);
      const newData = this.data.map((data2) => {
        const cloned = data2.clone();
        cloned.dictionary = dictionary2;
        return cloned;
      });
      return new Vector(newData);
    }
    return new MemoizedVector(this);
  }
  /**
   * Returns a vector without memoization of the {@link get} method. If this
   * vector is not memoized, this method returns this vector.
   *
   * @returns A new vector without memoization.
   */
  unmemoize() {
    if (DataType.isDictionary(this.type) && this.isMemoized) {
      const dictionary2 = this.data[0].dictionary.unmemoize();
      const newData = this.data.map((data2) => {
        const newData2 = data2.clone();
        newData2.dictionary = dictionary2;
        return newData2;
      });
      return new Vector(newData);
    }
    return this;
  }
}
_a$4 = Symbol.toStringTag;
Vector[_a$4] = ((proto) => {
  proto.type = DataType.prototype;
  proto.data = [];
  proto.length = 0;
  proto.stride = 1;
  proto.numChildren = 0;
  proto._offsets = new Uint32Array([0]);
  proto[Symbol.isConcatSpreadable] = true;
  const typeIds = Object.keys(Type$1).map((T) => Type$1[T]).filter((T) => typeof T === "number" && T !== Type$1.NONE);
  for (const typeId of typeIds) {
    const get2 = instance$4.getVisitFnByTypeId(typeId);
    const set3 = instance$5.getVisitFnByTypeId(typeId);
    const indexOf = instance$3.getVisitFnByTypeId(typeId);
    visitorsByTypeId[typeId] = { get: get2, set: set3, indexOf };
    vectorPrototypesByTypeId[typeId] = Object.create(proto, {
      ["isValid"]: { value: wrapChunkedCall1(isChunkedValid) },
      ["get"]: { value: wrapChunkedCall1(instance$4.getVisitFnByTypeId(typeId)) },
      ["set"]: { value: wrapChunkedCall2(instance$5.getVisitFnByTypeId(typeId)) },
      ["indexOf"]: { value: wrapChunkedIndexOf(instance$3.getVisitFnByTypeId(typeId)) }
    });
  }
  return "Vector";
})(Vector.prototype);
class MemoizedVector extends Vector {
  constructor(vector) {
    super(vector.data);
    const get2 = this.get;
    const set3 = this.set;
    const slice2 = this.slice;
    const cache = new Array(this.length);
    Object.defineProperty(this, "get", {
      value(index) {
        const cachedValue = cache[index];
        if (cachedValue !== void 0) {
          return cachedValue;
        }
        const value2 = get2.call(this, index);
        cache[index] = value2;
        return value2;
      }
    });
    Object.defineProperty(this, "set", {
      value(index, value2) {
        set3.call(this, index, value2);
        cache[index] = value2;
      }
    });
    Object.defineProperty(this, "slice", {
      value: (begin, end2) => new MemoizedVector(slice2.call(this, begin, end2))
    });
    Object.defineProperty(this, "isMemoized", { value: true });
    Object.defineProperty(this, "unmemoize", {
      value: () => new Vector(this.data)
    });
    Object.defineProperty(this, "memoize", {
      value: () => this
    });
  }
}
class Block {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  /**
   * Index to the start of the RecordBlock (note this is past the Message header)
   */
  offset() {
    return this.bb.readInt64(this.bb_pos);
  }
  /**
   * Length of the metadata
   */
  metaDataLength() {
    return this.bb.readInt32(this.bb_pos + 8);
  }
  /**
   * Length of the data (this is aligned so there can be a gap between this and
   * the metadata).
   */
  bodyLength() {
    return this.bb.readInt64(this.bb_pos + 16);
  }
  static sizeOf() {
    return 24;
  }
  static createBlock(builder2, offset3, metaDataLength, bodyLength) {
    builder2.prep(8, 24);
    builder2.writeInt64(BigInt(bodyLength !== null && bodyLength !== void 0 ? bodyLength : 0));
    builder2.pad(4);
    builder2.writeInt32(metaDataLength);
    builder2.writeInt64(BigInt(offset3 !== null && offset3 !== void 0 ? offset3 : 0));
    return builder2.offset();
  }
}
let Footer$1 = class Footer {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  static getRootAsFooter(bb, obj) {
    return (obj || new Footer()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static getSizePrefixedRootAsFooter(bb, obj) {
    bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
    return (obj || new Footer()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  version() {
    const offset3 = this.bb.__offset(this.bb_pos, 4);
    return offset3 ? this.bb.readInt16(this.bb_pos + offset3) : MetadataVersion.V1;
  }
  schema(obj) {
    const offset3 = this.bb.__offset(this.bb_pos, 6);
    return offset3 ? (obj || new Schema$1()).__init(this.bb.__indirect(this.bb_pos + offset3), this.bb) : null;
  }
  dictionaries(index, obj) {
    const offset3 = this.bb.__offset(this.bb_pos, 8);
    return offset3 ? (obj || new Block()).__init(this.bb.__vector(this.bb_pos + offset3) + index * 24, this.bb) : null;
  }
  dictionariesLength() {
    const offset3 = this.bb.__offset(this.bb_pos, 8);
    return offset3 ? this.bb.__vector_len(this.bb_pos + offset3) : 0;
  }
  recordBatches(index, obj) {
    const offset3 = this.bb.__offset(this.bb_pos, 10);
    return offset3 ? (obj || new Block()).__init(this.bb.__vector(this.bb_pos + offset3) + index * 24, this.bb) : null;
  }
  recordBatchesLength() {
    const offset3 = this.bb.__offset(this.bb_pos, 10);
    return offset3 ? this.bb.__vector_len(this.bb_pos + offset3) : 0;
  }
  /**
   * User-defined metadata
   */
  customMetadata(index, obj) {
    const offset3 = this.bb.__offset(this.bb_pos, 12);
    return offset3 ? (obj || new KeyValue()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset3) + index * 4), this.bb) : null;
  }
  customMetadataLength() {
    const offset3 = this.bb.__offset(this.bb_pos, 12);
    return offset3 ? this.bb.__vector_len(this.bb_pos + offset3) : 0;
  }
  static startFooter(builder2) {
    builder2.startObject(5);
  }
  static addVersion(builder2, version2) {
    builder2.addFieldInt16(0, version2, MetadataVersion.V1);
  }
  static addSchema(builder2, schemaOffset) {
    builder2.addFieldOffset(1, schemaOffset, 0);
  }
  static addDictionaries(builder2, dictionariesOffset) {
    builder2.addFieldOffset(2, dictionariesOffset, 0);
  }
  static startDictionariesVector(builder2, numElems) {
    builder2.startVector(24, numElems, 8);
  }
  static addRecordBatches(builder2, recordBatchesOffset) {
    builder2.addFieldOffset(3, recordBatchesOffset, 0);
  }
  static startRecordBatchesVector(builder2, numElems) {
    builder2.startVector(24, numElems, 8);
  }
  static addCustomMetadata(builder2, customMetadataOffset) {
    builder2.addFieldOffset(4, customMetadataOffset, 0);
  }
  static createCustomMetadataVector(builder2, data2) {
    builder2.startVector(4, data2.length, 4);
    for (let i2 = data2.length - 1; i2 >= 0; i2--) {
      builder2.addOffset(data2[i2]);
    }
    return builder2.endVector();
  }
  static startCustomMetadataVector(builder2, numElems) {
    builder2.startVector(4, numElems, 4);
  }
  static endFooter(builder2) {
    const offset3 = builder2.endObject();
    return offset3;
  }
  static finishFooterBuffer(builder2, offset3) {
    builder2.finish(offset3);
  }
  static finishSizePrefixedFooterBuffer(builder2, offset3) {
    builder2.finish(offset3, void 0, true);
  }
};
class Schema2 {
  constructor(fields = [], metadata2, dictionaries, metadataVersion = MetadataVersion.V5) {
    this.fields = fields || [];
    this.metadata = metadata2 || /* @__PURE__ */ new Map();
    if (!dictionaries) {
      dictionaries = generateDictionaryMap(this.fields);
    }
    this.dictionaries = dictionaries;
    this.metadataVersion = metadataVersion;
  }
  get [Symbol.toStringTag]() {
    return "Schema";
  }
  get names() {
    return this.fields.map((f) => f.name);
  }
  toString() {
    return `Schema<{ ${this.fields.map((f, i2) => `${i2}: ${f}`).join(", ")} }>`;
  }
  /**
   * Construct a new Schema containing only specified fields.
   *
   * @param fieldNames Names of fields to keep.
   * @returns A new Schema of fields matching the specified names.
   */
  select(fieldNames) {
    const names = new Set(fieldNames);
    const fields = this.fields.filter((f) => names.has(f.name));
    return new Schema2(fields, this.metadata);
  }
  /**
   * Construct a new Schema containing only fields at the specified indices.
   *
   * @param fieldIndices Indices of fields to keep.
   * @returns A new Schema of fields at the specified indices.
   */
  selectAt(fieldIndices) {
    const fields = fieldIndices.map((i2) => this.fields[i2]).filter(Boolean);
    return new Schema2(fields, this.metadata);
  }
  assign(...args2) {
    const other = args2[0] instanceof Schema2 ? args2[0] : Array.isArray(args2[0]) ? new Schema2(args2[0]) : new Schema2(args2);
    const curFields = [...this.fields];
    const metadata2 = mergeMaps(mergeMaps(/* @__PURE__ */ new Map(), this.metadata), other.metadata);
    const newFields = other.fields.filter((f2) => {
      const i2 = curFields.findIndex((f) => f.name === f2.name);
      return ~i2 ? (curFields[i2] = f2.clone({
        metadata: mergeMaps(mergeMaps(/* @__PURE__ */ new Map(), curFields[i2].metadata), f2.metadata)
      })) && false : true;
    });
    const newDictionaries = generateDictionaryMap(newFields, /* @__PURE__ */ new Map());
    return new Schema2([...curFields, ...newFields], metadata2, new Map([...this.dictionaries, ...newDictionaries]));
  }
}
Schema2.prototype.fields = null;
Schema2.prototype.metadata = null;
Schema2.prototype.dictionaries = null;
class Field2 {
  /** @nocollapse */
  static new(...args2) {
    let [name2, type, nullable, metadata2] = args2;
    if (args2[0] && typeof args2[0] === "object") {
      ({ name: name2 } = args2[0]);
      type === void 0 && (type = args2[0].type);
      nullable === void 0 && (nullable = args2[0].nullable);
      metadata2 === void 0 && (metadata2 = args2[0].metadata);
    }
    return new Field2(`${name2}`, type, nullable, metadata2);
  }
  constructor(name2, type, nullable = false, metadata2) {
    this.name = name2;
    this.type = type;
    this.nullable = nullable;
    this.metadata = metadata2 || /* @__PURE__ */ new Map();
  }
  get typeId() {
    return this.type.typeId;
  }
  get [Symbol.toStringTag]() {
    return "Field";
  }
  toString() {
    return `${this.name}: ${this.type}`;
  }
  clone(...args2) {
    let [name2, type, nullable, metadata2] = args2;
    !args2[0] || typeof args2[0] !== "object" ? [name2 = this.name, type = this.type, nullable = this.nullable, metadata2 = this.metadata] = args2 : { name: name2 = this.name, type = this.type, nullable = this.nullable, metadata: metadata2 = this.metadata } = args2[0];
    return Field2.new(name2, type, nullable, metadata2);
  }
}
Field2.prototype.type = null;
Field2.prototype.name = null;
Field2.prototype.nullable = null;
Field2.prototype.metadata = null;
function mergeMaps(m1, m2) {
  return new Map([...m1 || /* @__PURE__ */ new Map(), ...m2 || /* @__PURE__ */ new Map()]);
}
function generateDictionaryMap(fields, dictionaries = /* @__PURE__ */ new Map()) {
  for (let i2 = -1, n2 = fields.length; ++i2 < n2; ) {
    const field2 = fields[i2];
    const type = field2.type;
    if (DataType.isDictionary(type)) {
      if (!dictionaries.has(type.id)) {
        dictionaries.set(type.id, type.dictionary);
      } else if (dictionaries.get(type.id) !== type.dictionary) {
        throw new Error(`Cannot create Schema containing two different dictionaries with the same Id`);
      }
    }
    if (type.children && type.children.length > 0) {
      generateDictionaryMap(type.children, dictionaries);
    }
  }
  return dictionaries;
}
var Builder$2 = Builder$3;
var ByteBuffer$1 = ByteBuffer$2;
class Footer_ {
  /** @nocollapse */
  static decode(buf2) {
    buf2 = new ByteBuffer$1(toUint8Array(buf2));
    const footer2 = Footer$1.getRootAsFooter(buf2);
    const schema = Schema2.decode(footer2.schema(), /* @__PURE__ */ new Map(), footer2.version());
    return new OffHeapFooter(schema, footer2);
  }
  /** @nocollapse */
  static encode(footer2) {
    const b = new Builder$2();
    const schemaOffset = Schema2.encode(b, footer2.schema);
    Footer$1.startRecordBatchesVector(b, footer2.numRecordBatches);
    for (const rb of [...footer2.recordBatches()].slice().reverse()) {
      FileBlock.encode(b, rb);
    }
    const recordBatchesOffset = b.endVector();
    Footer$1.startDictionariesVector(b, footer2.numDictionaries);
    for (const db of [...footer2.dictionaryBatches()].slice().reverse()) {
      FileBlock.encode(b, db);
    }
    const dictionaryBatchesOffset = b.endVector();
    Footer$1.startFooter(b);
    Footer$1.addSchema(b, schemaOffset);
    Footer$1.addVersion(b, MetadataVersion.V5);
    Footer$1.addRecordBatches(b, recordBatchesOffset);
    Footer$1.addDictionaries(b, dictionaryBatchesOffset);
    Footer$1.finishFooterBuffer(b, Footer$1.endFooter(b));
    return b.asUint8Array();
  }
  get numRecordBatches() {
    return this._recordBatches.length;
  }
  get numDictionaries() {
    return this._dictionaryBatches.length;
  }
  constructor(schema, version2 = MetadataVersion.V5, recordBatches, dictionaryBatches) {
    this.schema = schema;
    this.version = version2;
    recordBatches && (this._recordBatches = recordBatches);
    dictionaryBatches && (this._dictionaryBatches = dictionaryBatches);
  }
  *recordBatches() {
    for (let block2, i2 = -1, n2 = this.numRecordBatches; ++i2 < n2; ) {
      if (block2 = this.getRecordBatch(i2)) {
        yield block2;
      }
    }
  }
  *dictionaryBatches() {
    for (let block2, i2 = -1, n2 = this.numDictionaries; ++i2 < n2; ) {
      if (block2 = this.getDictionaryBatch(i2)) {
        yield block2;
      }
    }
  }
  getRecordBatch(index) {
    return index >= 0 && index < this.numRecordBatches && this._recordBatches[index] || null;
  }
  getDictionaryBatch(index) {
    return index >= 0 && index < this.numDictionaries && this._dictionaryBatches[index] || null;
  }
}
class OffHeapFooter extends Footer_ {
  get numRecordBatches() {
    return this._footer.recordBatchesLength();
  }
  get numDictionaries() {
    return this._footer.dictionariesLength();
  }
  constructor(schema, _footer) {
    super(schema, _footer.version());
    this._footer = _footer;
  }
  getRecordBatch(index) {
    if (index >= 0 && index < this.numRecordBatches) {
      const fileBlock = this._footer.recordBatches(index);
      if (fileBlock) {
        return FileBlock.decode(fileBlock);
      }
    }
    return null;
  }
  getDictionaryBatch(index) {
    if (index >= 0 && index < this.numDictionaries) {
      const fileBlock = this._footer.dictionaries(index);
      if (fileBlock) {
        return FileBlock.decode(fileBlock);
      }
    }
    return null;
  }
}
class FileBlock {
  /** @nocollapse */
  static decode(block2) {
    return new FileBlock(block2.metaDataLength(), block2.bodyLength(), block2.offset());
  }
  /** @nocollapse */
  static encode(b, fileBlock) {
    const { metaDataLength } = fileBlock;
    const offset3 = BigInt(fileBlock.offset);
    const bodyLength = BigInt(fileBlock.bodyLength);
    return Block.createBlock(b, offset3, metaDataLength, bodyLength);
  }
  constructor(metaDataLength, bodyLength, offset3) {
    this.metaDataLength = metaDataLength;
    this.offset = bigIntToNumber(offset3);
    this.bodyLength = bigIntToNumber(bodyLength);
  }
}
let Message$1 = class Message {
  constructor() {
    this.bb = null;
    this.bb_pos = 0;
  }
  __init(i2, bb) {
    this.bb_pos = i2;
    this.bb = bb;
    return this;
  }
  static getRootAsMessage(bb, obj) {
    return (obj || new Message()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  static getSizePrefixedRootAsMessage(bb, obj) {
    bb.setPosition(bb.position() + SIZE_PREFIX_LENGTH);
    return (obj || new Message()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
  }
  version() {
    const offset3 = this.bb.__offset(this.bb_pos, 4);
    return offset3 ? this.bb.readInt16(this.bb_pos + offset3) : MetadataVersion.V1;
  }
  headerType() {
    const offset3 = this.bb.__offset(this.bb_pos, 6);
    return offset3 ? this.bb.readUint8(this.bb_pos + offset3) : MessageHeader$1.NONE;
  }
  header(obj) {
    const offset3 = this.bb.__offset(this.bb_pos, 8);
    return offset3 ? this.bb.__union(obj, this.bb_pos + offset3) : null;
  }
  bodyLength() {
    const offset3 = this.bb.__offset(this.bb_pos, 10);
    return offset3 ? this.bb.readInt64(this.bb_pos + offset3) : BigInt("0");
  }
  customMetadata(index, obj) {
    const offset3 = this.bb.__offset(this.bb_pos, 12);
    return offset3 ? (obj || new KeyValue()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset3) + index * 4), this.bb) : null;
  }
  customMetadataLength() {
    const offset3 = this.bb.__offset(this.bb_pos, 12);
    return offset3 ? this.bb.__vector_len(this.bb_pos + offset3) : 0;
  }
  static startMessage(builder2) {
    builder2.startObject(5);
  }
  static addVersion(builder2, version2) {
    builder2.addFieldInt16(0, version2, MetadataVersion.V1);
  }
  static addHeaderType(builder2, headerType) {
    builder2.addFieldInt8(1, headerType, MessageHeader$1.NONE);
  }
  static addHeader(builder2, headerOffset) {
    builder2.addFieldOffset(2, headerOffset, 0);
  }
  static addBodyLength(builder2, bodyLength) {
    builder2.addFieldInt64(3, bodyLength, BigInt("0"));
  }
  static addCustomMetadata(builder2, customMetadataOffset) {
    builder2.addFieldOffset(4, customMetadataOffset, 0);
  }
  static createCustomMetadataVector(builder2, data2) {
    builder2.startVector(4, data2.length, 4);
    for (let i2 = data2.length - 1; i2 >= 0; i2--) {
      builder2.addOffset(data2[i2]);
    }
    return builder2.endVector();
  }
  static startCustomMetadataVector(builder2, numElems) {
    builder2.startVector(4, numElems, 4);
  }
  static endMessage(builder2) {
    const offset3 = builder2.endObject();
    return offset3;
  }
  static finishMessageBuffer(builder2, offset3) {
    builder2.finish(offset3);
  }
  static finishSizePrefixedMessageBuffer(builder2, offset3) {
    builder2.finish(offset3, void 0, true);
  }
  static createMessage(builder2, version2, headerType, headerOffset, bodyLength, customMetadataOffset) {
    Message.startMessage(builder2);
    Message.addVersion(builder2, version2);
    Message.addHeaderType(builder2, headerType);
    Message.addHeader(builder2, headerOffset);
    Message.addBodyLength(builder2, bodyLength);
    Message.addCustomMetadata(builder2, customMetadataOffset);
    return Message.endMessage(builder2);
  }
};
class TypeAssembler extends Visitor {
  visit(node2, builder2) {
    return node2 == null || builder2 == null ? void 0 : super.visit(node2, builder2);
  }
  visitNull(_node, b) {
    Null$1.startNull(b);
    return Null$1.endNull(b);
  }
  visitInt(node2, b) {
    Int.startInt(b);
    Int.addBitWidth(b, node2.bitWidth);
    Int.addIsSigned(b, node2.isSigned);
    return Int.endInt(b);
  }
  visitFloat(node2, b) {
    FloatingPoint.startFloatingPoint(b);
    FloatingPoint.addPrecision(b, node2.precision);
    return FloatingPoint.endFloatingPoint(b);
  }
  visitBinary(_node, b) {
    Binary$1.startBinary(b);
    return Binary$1.endBinary(b);
  }
  visitLargeBinary(_node, b) {
    LargeBinary$1.startLargeBinary(b);
    return LargeBinary$1.endLargeBinary(b);
  }
  visitBool(_node, b) {
    Bool$1.startBool(b);
    return Bool$1.endBool(b);
  }
  visitUtf8(_node, b) {
    Utf8$1.startUtf8(b);
    return Utf8$1.endUtf8(b);
  }
  visitLargeUtf8(_node, b) {
    LargeUtf8$1.startLargeUtf8(b);
    return LargeUtf8$1.endLargeUtf8(b);
  }
  visitDecimal(node2, b) {
    Decimal$1.startDecimal(b);
    Decimal$1.addScale(b, node2.scale);
    Decimal$1.addPrecision(b, node2.precision);
    Decimal$1.addBitWidth(b, node2.bitWidth);
    return Decimal$1.endDecimal(b);
  }
  visitDate(node2, b) {
    Date$1.startDate(b);
    Date$1.addUnit(b, node2.unit);
    return Date$1.endDate(b);
  }
  visitTime(node2, b) {
    Time.startTime(b);
    Time.addUnit(b, node2.unit);
    Time.addBitWidth(b, node2.bitWidth);
    return Time.endTime(b);
  }
  visitTimestamp(node2, b) {
    const timezone = node2.timezone && b.createString(node2.timezone) || void 0;
    Timestamp.startTimestamp(b);
    Timestamp.addUnit(b, node2.unit);
    if (timezone !== void 0) {
      Timestamp.addTimezone(b, timezone);
    }
    return Timestamp.endTimestamp(b);
  }
  visitInterval(node2, b) {
    Interval.startInterval(b);
    Interval.addUnit(b, node2.unit);
    return Interval.endInterval(b);
  }
  visitDuration(node2, b) {
    Duration$1.startDuration(b);
    Duration$1.addUnit(b, node2.unit);
    return Duration$1.endDuration(b);
  }
  visitList(_node, b) {
    List$1.startList(b);
    return List$1.endList(b);
  }
  visitStruct(_node, b) {
    Struct_.startStruct_(b);
    return Struct_.endStruct_(b);
  }
  visitUnion(node2, b) {
    Union.startTypeIdsVector(b, node2.typeIds.length);
    const typeIds = Union.createTypeIdsVector(b, node2.typeIds);
    Union.startUnion(b);
    Union.addMode(b, node2.mode);
    Union.addTypeIds(b, typeIds);
    return Union.endUnion(b);
  }
  visitDictionary(node2, b) {
    const indexType = this.visit(node2.indices, b);
    DictionaryEncoding.startDictionaryEncoding(b);
    DictionaryEncoding.addId(b, BigInt(node2.id));
    DictionaryEncoding.addIsOrdered(b, node2.isOrdered);
    if (indexType !== void 0) {
      DictionaryEncoding.addIndexType(b, indexType);
    }
    return DictionaryEncoding.endDictionaryEncoding(b);
  }
  visitFixedSizeBinary(node2, b) {
    FixedSizeBinary$1.startFixedSizeBinary(b);
    FixedSizeBinary$1.addByteWidth(b, node2.byteWidth);
    return FixedSizeBinary$1.endFixedSizeBinary(b);
  }
  visitFixedSizeList(node2, b) {
    FixedSizeList$1.startFixedSizeList(b);
    FixedSizeList$1.addListSize(b, node2.listSize);
    return FixedSizeList$1.endFixedSizeList(b);
  }
  visitMap(node2, b) {
    Map$2.startMap(b);
    Map$2.addKeysSorted(b, node2.keysSorted);
    return Map$2.endMap(b);
  }
}
const instance$1 = new TypeAssembler();
function schemaFromJSON(_schema, dictionaries = /* @__PURE__ */ new Map()) {
  return new Schema2(schemaFieldsFromJSON(_schema, dictionaries), customMetadataFromJSON(_schema["metadata"]), dictionaries);
}
function recordBatchFromJSON(b) {
  return new RecordBatch$1(b["count"], fieldNodesFromJSON(b["columns"]), buffersFromJSON(b["columns"]), null);
}
function dictionaryBatchFromJSON(b) {
  return new DictionaryBatch$1(recordBatchFromJSON(b["data"]), b["id"], b["isDelta"]);
}
function schemaFieldsFromJSON(_schema, dictionaries) {
  return (_schema["fields"] || []).filter(Boolean).map((f) => Field2.fromJSON(f, dictionaries));
}
function fieldChildrenFromJSON(_field, dictionaries) {
  return (_field["children"] || []).filter(Boolean).map((f) => Field2.fromJSON(f, dictionaries));
}
function fieldNodesFromJSON(xs) {
  return (xs || []).reduce((fieldNodes, column2) => [
    ...fieldNodes,
    new FieldNode2(column2["count"], nullCountFromJSON(column2["VALIDITY"])),
    ...fieldNodesFromJSON(column2["children"])
  ], []);
}
function buffersFromJSON(xs, buffers = []) {
  for (let i2 = -1, n2 = (xs || []).length; ++i2 < n2; ) {
    const column2 = xs[i2];
    column2["VALIDITY"] && buffers.push(new BufferRegion(buffers.length, column2["VALIDITY"].length));
    column2["TYPE_ID"] && buffers.push(new BufferRegion(buffers.length, column2["TYPE_ID"].length));
    column2["OFFSET"] && buffers.push(new BufferRegion(buffers.length, column2["OFFSET"].length));
    column2["DATA"] && buffers.push(new BufferRegion(buffers.length, column2["DATA"].length));
    buffers = buffersFromJSON(column2["children"], buffers);
  }
  return buffers;
}
function nullCountFromJSON(validity) {
  return (validity || []).reduce((sum, val) => sum + +(val === 0), 0);
}
function fieldFromJSON(_field, dictionaries) {
  let id2;
  let keys2;
  let field2;
  let dictMeta;
  let type;
  let dictType;
  if (!dictionaries || !(dictMeta = _field["dictionary"])) {
    type = typeFromJSON(_field, fieldChildrenFromJSON(_field, dictionaries));
    field2 = new Field2(_field["name"], type, _field["nullable"], customMetadataFromJSON(_field["metadata"]));
  } else if (!dictionaries.has(id2 = dictMeta["id"])) {
    keys2 = (keys2 = dictMeta["indexType"]) ? indexTypeFromJSON(keys2) : new Int32();
    dictionaries.set(id2, type = typeFromJSON(_field, fieldChildrenFromJSON(_field, dictionaries)));
    dictType = new Dictionary$1(type, keys2, id2, dictMeta["isOrdered"]);
    field2 = new Field2(_field["name"], dictType, _field["nullable"], customMetadataFromJSON(_field["metadata"]));
  } else {
    keys2 = (keys2 = dictMeta["indexType"]) ? indexTypeFromJSON(keys2) : new Int32();
    dictType = new Dictionary$1(dictionaries.get(id2), keys2, id2, dictMeta["isOrdered"]);
    field2 = new Field2(_field["name"], dictType, _field["nullable"], customMetadataFromJSON(_field["metadata"]));
  }
  return field2 || null;
}
function customMetadataFromJSON(metadata2 = []) {
  return new Map(metadata2.map(({ key: key2, value: value2 }) => [key2, value2]));
}
function indexTypeFromJSON(_type) {
  return new Int_(_type["isSigned"], _type["bitWidth"]);
}
function typeFromJSON(f, children2) {
  const typeId = f["type"]["name"];
  switch (typeId) {
    case "NONE":
      return new Null2();
    case "null":
      return new Null2();
    case "binary":
      return new Binary2();
    case "largebinary":
      return new LargeBinary2();
    case "utf8":
      return new Utf82();
    case "largeutf8":
      return new LargeUtf82();
    case "bool":
      return new Bool2();
    case "list":
      return new List2((children2 || [])[0]);
    case "struct":
      return new Struct(children2 || []);
    case "struct_":
      return new Struct(children2 || []);
  }
  switch (typeId) {
    case "int": {
      const t2 = f["type"];
      return new Int_(t2["isSigned"], t2["bitWidth"]);
    }
    case "floatingpoint": {
      const t2 = f["type"];
      return new Float(Precision$1[t2["precision"]]);
    }
    case "decimal": {
      const t2 = f["type"];
      return new Decimal2(t2["scale"], t2["precision"], t2["bitWidth"]);
    }
    case "date": {
      const t2 = f["type"];
      return new Date_(DateUnit$1[t2["unit"]]);
    }
    case "time": {
      const t2 = f["type"];
      return new Time_(TimeUnit$1[t2["unit"]], t2["bitWidth"]);
    }
    case "timestamp": {
      const t2 = f["type"];
      return new Timestamp_(TimeUnit$1[t2["unit"]], t2["timezone"]);
    }
    case "interval": {
      const t2 = f["type"];
      return new Interval_(IntervalUnit$1[t2["unit"]]);
    }
    case "duration": {
      const t2 = f["type"];
      return new Duration2(TimeUnit$1[t2["unit"]]);
    }
    case "union": {
      const t2 = f["type"];
      const [m, ...ms] = (t2["mode"] + "").toLowerCase();
      const mode = m.toUpperCase() + ms.join("");
      return new Union_(UnionMode$1[mode], t2["typeIds"] || [], children2 || []);
    }
    case "fixedsizebinary": {
      const t2 = f["type"];
      return new FixedSizeBinary2(t2["byteWidth"]);
    }
    case "fixedsizelist": {
      const t2 = f["type"];
      return new FixedSizeList2(t2["listSize"], (children2 || [])[0]);
    }
    case "map": {
      const t2 = f["type"];
      return new Map_((children2 || [])[0], t2["keysSorted"]);
    }
  }
  throw new Error(`Unrecognized type: "${typeId}"`);
}
var Builder$1 = Builder$3;
var ByteBuffer2 = ByteBuffer$2;
class Message2 {
  /** @nocollapse */
  static fromJSON(msg, headerType) {
    const message2 = new Message2(0, MetadataVersion.V5, headerType);
    message2._createHeader = messageHeaderFromJSON(msg, headerType);
    return message2;
  }
  /** @nocollapse */
  static decode(buf2) {
    buf2 = new ByteBuffer2(toUint8Array(buf2));
    const _message = Message$1.getRootAsMessage(buf2);
    const bodyLength = _message.bodyLength();
    const version2 = _message.version();
    const headerType = _message.headerType();
    const message2 = new Message2(bodyLength, version2, headerType);
    message2._createHeader = decodeMessageHeader(_message, headerType);
    return message2;
  }
  /** @nocollapse */
  static encode(message2) {
    const b = new Builder$1();
    let headerOffset = -1;
    if (message2.isSchema()) {
      headerOffset = Schema2.encode(b, message2.header());
    } else if (message2.isRecordBatch()) {
      headerOffset = RecordBatch$1.encode(b, message2.header());
    } else if (message2.isDictionaryBatch()) {
      headerOffset = DictionaryBatch$1.encode(b, message2.header());
    }
    Message$1.startMessage(b);
    Message$1.addVersion(b, MetadataVersion.V5);
    Message$1.addHeader(b, headerOffset);
    Message$1.addHeaderType(b, message2.headerType);
    Message$1.addBodyLength(b, BigInt(message2.bodyLength));
    Message$1.finishMessageBuffer(b, Message$1.endMessage(b));
    return b.asUint8Array();
  }
  /** @nocollapse */
  static from(header2, bodyLength = 0) {
    if (header2 instanceof Schema2) {
      return new Message2(0, MetadataVersion.V5, MessageHeader$1.Schema, header2);
    }
    if (header2 instanceof RecordBatch$1) {
      return new Message2(bodyLength, MetadataVersion.V5, MessageHeader$1.RecordBatch, header2);
    }
    if (header2 instanceof DictionaryBatch$1) {
      return new Message2(bodyLength, MetadataVersion.V5, MessageHeader$1.DictionaryBatch, header2);
    }
    throw new Error(`Unrecognized Message header: ${header2}`);
  }
  get type() {
    return this.headerType;
  }
  get version() {
    return this._version;
  }
  get headerType() {
    return this._headerType;
  }
  get compression() {
    return this._compression;
  }
  get bodyLength() {
    return this._bodyLength;
  }
  header() {
    return this._createHeader();
  }
  isSchema() {
    return this.headerType === MessageHeader$1.Schema;
  }
  isRecordBatch() {
    return this.headerType === MessageHeader$1.RecordBatch;
  }
  isDictionaryBatch() {
    return this.headerType === MessageHeader$1.DictionaryBatch;
  }
  constructor(bodyLength, version2, headerType, header2) {
    this._version = version2;
    this._headerType = headerType;
    this.body = new Uint8Array(0);
    this._compression = header2 === null || header2 === void 0 ? void 0 : header2.compression;
    header2 && (this._createHeader = () => header2);
    this._bodyLength = bigIntToNumber(bodyLength);
  }
}
let RecordBatch$1 = class RecordBatch2 {
  get nodes() {
    return this._nodes;
  }
  get length() {
    return this._length;
  }
  get buffers() {
    return this._buffers;
  }
  get compression() {
    return this._compression;
  }
  constructor(length2, nodes, buffers, compression) {
    this._nodes = nodes;
    this._buffers = buffers;
    this._length = bigIntToNumber(length2);
    this._compression = compression;
  }
};
let DictionaryBatch$1 = class DictionaryBatch2 {
  get id() {
    return this._id;
  }
  get data() {
    return this._data;
  }
  get isDelta() {
    return this._isDelta;
  }
  get length() {
    return this.data.length;
  }
  get nodes() {
    return this.data.nodes;
  }
  get buffers() {
    return this.data.buffers;
  }
  constructor(data2, id2, isDelta = false) {
    this._data = data2;
    this._isDelta = isDelta;
    this._id = bigIntToNumber(id2);
  }
};
class BufferRegion {
  constructor(offset3, length2) {
    this.offset = bigIntToNumber(offset3);
    this.length = bigIntToNumber(length2);
  }
}
class FieldNode2 {
  constructor(length2, nullCount) {
    this.length = bigIntToNumber(length2);
    this.nullCount = bigIntToNumber(nullCount);
  }
}
class BodyCompression2 {
  constructor(type, method = BodyCompressionMethod.BUFFER) {
    this.type = type;
    this.method = method;
  }
}
function messageHeaderFromJSON(message2, type) {
  return (() => {
    switch (type) {
      case MessageHeader$1.Schema:
        return Schema2.fromJSON(message2);
      case MessageHeader$1.RecordBatch:
        return RecordBatch$1.fromJSON(message2);
      case MessageHeader$1.DictionaryBatch:
        return DictionaryBatch$1.fromJSON(message2);
    }
    throw new Error(`Unrecognized Message type: { name: ${MessageHeader$1[type]}, type: ${type} }`);
  });
}
function decodeMessageHeader(message2, type) {
  return (() => {
    switch (type) {
      case MessageHeader$1.Schema:
        return Schema2.decode(message2.header(new Schema$1()), /* @__PURE__ */ new Map(), message2.version());
      case MessageHeader$1.RecordBatch:
        return RecordBatch$1.decode(message2.header(new RecordBatch$2()), message2.version());
      case MessageHeader$1.DictionaryBatch:
        return DictionaryBatch$1.decode(message2.header(new DictionaryBatch$2()), message2.version());
    }
    throw new Error(`Unrecognized Message type: { name: ${MessageHeader$1[type]}, type: ${type} }`);
  });
}
Field2["encode"] = encodeField$1;
Field2["decode"] = decodeField$1;
Field2["fromJSON"] = fieldFromJSON;
Schema2["encode"] = encodeSchema$1;
Schema2["decode"] = decodeSchema$1;
Schema2["fromJSON"] = schemaFromJSON;
RecordBatch$1["encode"] = encodeRecordBatch$1;
RecordBatch$1["decode"] = decodeRecordBatch$1;
RecordBatch$1["fromJSON"] = recordBatchFromJSON;
DictionaryBatch$1["encode"] = encodeDictionaryBatch$1;
DictionaryBatch$1["decode"] = decodeDictionaryBatch$1;
DictionaryBatch$1["fromJSON"] = dictionaryBatchFromJSON;
FieldNode2["encode"] = encodeFieldNode;
FieldNode2["decode"] = decodeFieldNode;
BufferRegion["encode"] = encodeBufferRegion;
BufferRegion["decode"] = decodeBufferRegion;
BodyCompression2["encode"] = encodeBodyCompression;
BodyCompression2["decode"] = decodeBodyCompression;
function decodeSchema$1(_schema, dictionaries = /* @__PURE__ */ new Map(), version2 = MetadataVersion.V5) {
  const fields = decodeSchemaFields$1(_schema, dictionaries);
  return new Schema2(fields, decodeCustomMetadata(_schema), dictionaries, version2);
}
function decodeRecordBatch$1(batch2, version2 = MetadataVersion.V5) {
  const recordBatch = new RecordBatch$1(batch2.length(), decodeFieldNodes(batch2), decodeBuffers(batch2, version2), decodeBodyCompression(batch2.compression()));
  return recordBatch;
}
function decodeDictionaryBatch$1(batch2, version2 = MetadataVersion.V5) {
  return new DictionaryBatch$1(RecordBatch$1.decode(batch2.data(), version2), batch2.id(), batch2.isDelta());
}
function decodeBufferRegion(b) {
  return new BufferRegion(b.offset(), b.length());
}
function decodeFieldNode(f) {
  return new FieldNode2(f.length(), f.nullCount());
}
function decodeFieldNodes(batch2) {
  const nodes = [];
  for (let f, i2 = -1, j2 = -1, n2 = batch2.nodesLength(); ++i2 < n2; ) {
    if (f = batch2.nodes(i2)) {
      nodes[++j2] = FieldNode2.decode(f);
    }
  }
  return nodes;
}
function decodeBuffers(batch2, version2) {
  const bufferRegions = [];
  for (let b, i2 = -1, j2 = -1, n2 = batch2.buffersLength(); ++i2 < n2; ) {
    if (b = batch2.buffers(i2)) {
      if (version2 < MetadataVersion.V4) {
        b.bb_pos += 8 * (i2 + 1);
      }
      bufferRegions[++j2] = BufferRegion.decode(b);
    }
  }
  return bufferRegions;
}
function decodeSchemaFields$1(schema, dictionaries) {
  const fields = [];
  for (let f, i2 = -1, j2 = -1, n2 = schema.fieldsLength(); ++i2 < n2; ) {
    if (f = schema.fields(i2)) {
      fields[++j2] = Field2.decode(f, dictionaries);
    }
  }
  return fields;
}
function decodeFieldChildren$1(field2, dictionaries) {
  const children2 = [];
  for (let f, i2 = -1, j2 = -1, n2 = field2.childrenLength(); ++i2 < n2; ) {
    if (f = field2.children(i2)) {
      children2[++j2] = Field2.decode(f, dictionaries);
    }
  }
  return children2;
}
function decodeField$1(f, dictionaries) {
  let id2;
  let field2;
  let type;
  let keys2;
  let dictType;
  let dictMeta;
  if (!dictionaries || !(dictMeta = f.dictionary())) {
    type = decodeFieldType(f, decodeFieldChildren$1(f, dictionaries));
    field2 = new Field2(f.name(), type, f.nullable(), decodeCustomMetadata(f));
  } else if (!dictionaries.has(id2 = bigIntToNumber(dictMeta.id()))) {
    keys2 = (keys2 = dictMeta.indexType()) ? decodeIndexType(keys2) : new Int32();
    dictionaries.set(id2, type = decodeFieldType(f, decodeFieldChildren$1(f, dictionaries)));
    dictType = new Dictionary$1(type, keys2, id2, dictMeta.isOrdered());
    field2 = new Field2(f.name(), dictType, f.nullable(), decodeCustomMetadata(f));
  } else {
    keys2 = (keys2 = dictMeta.indexType()) ? decodeIndexType(keys2) : new Int32();
    dictType = new Dictionary$1(dictionaries.get(id2), keys2, id2, dictMeta.isOrdered());
    field2 = new Field2(f.name(), dictType, f.nullable(), decodeCustomMetadata(f));
  }
  return field2 || null;
}
function decodeCustomMetadata(parent) {
  const data2 = /* @__PURE__ */ new Map();
  if (parent) {
    for (let entry2, key2, i2 = -1, n2 = Math.trunc(parent.customMetadataLength()); ++i2 < n2; ) {
      if ((entry2 = parent.customMetadata(i2)) && (key2 = entry2.key()) != null) {
        data2.set(key2, entry2.value());
      }
    }
  }
  return data2;
}
function decodeIndexType(_type) {
  return new Int_(_type.isSigned(), _type.bitWidth());
}
function decodeFieldType(f, children2) {
  const typeId = f.typeType();
  switch (typeId) {
    case Type$2["NONE"]:
      return new Null2();
    case Type$2["Null"]:
      return new Null2();
    case Type$2["Binary"]:
      return new Binary2();
    case Type$2["LargeBinary"]:
      return new LargeBinary2();
    case Type$2["Utf8"]:
      return new Utf82();
    case Type$2["LargeUtf8"]:
      return new LargeUtf82();
    case Type$2["Bool"]:
      return new Bool2();
    case Type$2["List"]:
      return new List2((children2 || [])[0]);
    case Type$2["Struct_"]:
      return new Struct(children2 || []);
  }
  switch (typeId) {
    case Type$2["Int"]: {
      const t2 = f.type(new Int());
      return new Int_(t2.isSigned(), t2.bitWidth());
    }
    case Type$2["FloatingPoint"]: {
      const t2 = f.type(new FloatingPoint());
      return new Float(t2.precision());
    }
    case Type$2["Decimal"]: {
      const t2 = f.type(new Decimal$1());
      return new Decimal2(t2.scale(), t2.precision(), t2.bitWidth());
    }
    case Type$2["Date"]: {
      const t2 = f.type(new Date$1());
      return new Date_(t2.unit());
    }
    case Type$2["Time"]: {
      const t2 = f.type(new Time());
      return new Time_(t2.unit(), t2.bitWidth());
    }
    case Type$2["Timestamp"]: {
      const t2 = f.type(new Timestamp());
      return new Timestamp_(t2.unit(), t2.timezone());
    }
    case Type$2["Interval"]: {
      const t2 = f.type(new Interval());
      return new Interval_(t2.unit());
    }
    case Type$2["Duration"]: {
      const t2 = f.type(new Duration$1());
      return new Duration2(t2.unit());
    }
    case Type$2["Union"]: {
      const t2 = f.type(new Union());
      return new Union_(t2.mode(), t2.typeIdsArray() || [], children2 || []);
    }
    case Type$2["FixedSizeBinary"]: {
      const t2 = f.type(new FixedSizeBinary$1());
      return new FixedSizeBinary2(t2.byteWidth());
    }
    case Type$2["FixedSizeList"]: {
      const t2 = f.type(new FixedSizeList$1());
      return new FixedSizeList2(t2.listSize(), (children2 || [])[0]);
    }
    case Type$2["Map"]: {
      const t2 = f.type(new Map$2());
      return new Map_((children2 || [])[0], t2.keysSorted());
    }
  }
  throw new Error(`Unrecognized type: "${Type$2[typeId]}" (${typeId})`);
}
function decodeBodyCompression(b) {
  return b ? new BodyCompression2(b.codec(), b.method()) : null;
}
function encodeSchema$1(b, schema) {
  const fieldOffsets = schema.fields.map((f) => Field2.encode(b, f));
  Schema$1.startFieldsVector(b, fieldOffsets.length);
  const fieldsVectorOffset = Schema$1.createFieldsVector(b, fieldOffsets);
  const metadataOffset = !(schema.metadata && schema.metadata.size > 0) ? -1 : Schema$1.createCustomMetadataVector(b, [...schema.metadata].map(([k, v]) => {
    const key2 = b.createString(`${k}`);
    const val = b.createString(`${v}`);
    KeyValue.startKeyValue(b);
    KeyValue.addKey(b, key2);
    KeyValue.addValue(b, val);
    return KeyValue.endKeyValue(b);
  }));
  Schema$1.startSchema(b);
  Schema$1.addFields(b, fieldsVectorOffset);
  Schema$1.addEndianness(b, platformIsLittleEndian ? Endianness$1.Little : Endianness$1.Big);
  if (metadataOffset !== -1) {
    Schema$1.addCustomMetadata(b, metadataOffset);
  }
  return Schema$1.endSchema(b);
}
function encodeField$1(b, field2) {
  let nameOffset = -1;
  let typeOffset = -1;
  let dictionaryOffset = -1;
  const type = field2.type;
  let typeId = field2.typeId;
  if (!DataType.isDictionary(type)) {
    typeOffset = instance$1.visit(type, b);
  } else {
    typeId = type.dictionary.typeId;
    dictionaryOffset = instance$1.visit(type, b);
    typeOffset = instance$1.visit(type.dictionary, b);
  }
  const childOffsets = (type.children || []).map((f) => Field2.encode(b, f));
  const childrenVectorOffset = Field$1.createChildrenVector(b, childOffsets);
  const metadataOffset = !(field2.metadata && field2.metadata.size > 0) ? -1 : Field$1.createCustomMetadataVector(b, [...field2.metadata].map(([k, v]) => {
    const key2 = b.createString(`${k}`);
    const val = b.createString(`${v}`);
    KeyValue.startKeyValue(b);
    KeyValue.addKey(b, key2);
    KeyValue.addValue(b, val);
    return KeyValue.endKeyValue(b);
  }));
  if (field2.name) {
    nameOffset = b.createString(field2.name);
  }
  Field$1.startField(b);
  Field$1.addType(b, typeOffset);
  Field$1.addTypeType(b, typeId);
  Field$1.addChildren(b, childrenVectorOffset);
  Field$1.addNullable(b, !!field2.nullable);
  if (nameOffset !== -1) {
    Field$1.addName(b, nameOffset);
  }
  if (dictionaryOffset !== -1) {
    Field$1.addDictionary(b, dictionaryOffset);
  }
  if (metadataOffset !== -1) {
    Field$1.addCustomMetadata(b, metadataOffset);
  }
  return Field$1.endField(b);
}
function encodeRecordBatch$1(b, recordBatch) {
  const nodes = recordBatch.nodes || [];
  const buffers = recordBatch.buffers || [];
  RecordBatch$2.startNodesVector(b, nodes.length);
  for (const n2 of nodes.slice().reverse())
    FieldNode2.encode(b, n2);
  const nodesVectorOffset = b.endVector();
  RecordBatch$2.startBuffersVector(b, buffers.length);
  for (const b_ of buffers.slice().reverse())
    BufferRegion.encode(b, b_);
  const buffersVectorOffset = b.endVector();
  let bodyCompressionOffset = null;
  if (recordBatch.compression !== null) {
    bodyCompressionOffset = encodeBodyCompression(b, recordBatch.compression);
  }
  RecordBatch$2.startRecordBatch(b);
  RecordBatch$2.addLength(b, BigInt(recordBatch.length));
  RecordBatch$2.addNodes(b, nodesVectorOffset);
  RecordBatch$2.addBuffers(b, buffersVectorOffset);
  if (recordBatch.compression !== null && bodyCompressionOffset) {
    RecordBatch$2.addCompression(b, bodyCompressionOffset);
  }
  return RecordBatch$2.endRecordBatch(b);
}
function encodeBodyCompression(b, node2) {
  BodyCompression$1.startBodyCompression(b);
  BodyCompression$1.addCodec(b, node2.type);
  BodyCompression$1.addMethod(b, node2.method);
  return BodyCompression$1.endBodyCompression(b);
}
function encodeDictionaryBatch$1(b, dictionaryBatch) {
  const dataOffset = RecordBatch$1.encode(b, dictionaryBatch.data);
  DictionaryBatch$2.startDictionaryBatch(b);
  DictionaryBatch$2.addId(b, BigInt(dictionaryBatch.id));
  DictionaryBatch$2.addIsDelta(b, dictionaryBatch.isDelta);
  DictionaryBatch$2.addData(b, dataOffset);
  return DictionaryBatch$2.endDictionaryBatch(b);
}
function encodeFieldNode(b, node2) {
  return FieldNode$1.createFieldNode(b, BigInt(node2.length), BigInt(node2.nullCount));
}
function encodeBufferRegion(b, node2) {
  return Buffer$1.createBuffer(b, BigInt(node2.offset), BigInt(node2.length));
}
const platformIsLittleEndian = (() => {
  const buffer2 = new ArrayBuffer(2);
  new DataView(buffer2).setInt16(
    0,
    256,
    true
    /* littleEndian */
  );
  return new Int16Array(buffer2)[0] === 256;
})();
const ITERATOR_DONE = Object.freeze({ done: true, value: void 0 });
class ArrowJSON {
  constructor(_json) {
    this._json = _json;
  }
  get schema() {
    return this._json["schema"];
  }
  get batches() {
    return this._json["batches"] || [];
  }
  get dictionaries() {
    return this._json["dictionaries"] || [];
  }
}
class ReadableInterop {
  tee() {
    return this._getDOMStream().tee();
  }
  pipe(writable, options) {
    return this._getNodeStream().pipe(writable, options);
  }
  pipeTo(writable, options) {
    return this._getDOMStream().pipeTo(writable, options);
  }
  pipeThrough(duplex, options) {
    return this._getDOMStream().pipeThrough(duplex, options);
  }
  _getDOMStream() {
    return this._DOMStream || (this._DOMStream = this.toDOMStream());
  }
  _getNodeStream() {
    return this._nodeStream || (this._nodeStream = this.toNodeStream());
  }
}
class AsyncQueue extends ReadableInterop {
  constructor() {
    super();
    this._values = [];
    this.resolvers = [];
    this._closedPromise = new Promise((r2) => this._closedPromiseResolve = r2);
  }
  get closed() {
    return this._closedPromise;
  }
  cancel(reason) {
    return __awaiter(this, void 0, void 0, function* () {
      yield this.return(reason);
    });
  }
  write(value2) {
    if (this._ensureOpen()) {
      this.resolvers.length <= 0 ? this._values.push(value2) : this.resolvers.shift().resolve({ done: false, value: value2 });
    }
  }
  abort(value2) {
    if (this._closedPromiseResolve) {
      this.resolvers.length <= 0 ? this._error = { error: value2 } : this.resolvers.shift().reject({ done: true, value: value2 });
    }
  }
  close() {
    if (this._closedPromiseResolve) {
      const { resolvers } = this;
      while (resolvers.length > 0) {
        resolvers.shift().resolve(ITERATOR_DONE);
      }
      this._closedPromiseResolve();
      this._closedPromiseResolve = void 0;
    }
  }
  [Symbol.asyncIterator]() {
    return this;
  }
  toDOMStream(options) {
    return streamAdapters.toDOMStream(this._closedPromiseResolve || this._error ? this : this._values, options);
  }
  toNodeStream(options) {
    return streamAdapters.toNodeStream(this._closedPromiseResolve || this._error ? this : this._values, options);
  }
  throw(_) {
    return __awaiter(this, void 0, void 0, function* () {
      yield this.abort(_);
      return ITERATOR_DONE;
    });
  }
  return(_) {
    return __awaiter(this, void 0, void 0, function* () {
      yield this.close();
      return ITERATOR_DONE;
    });
  }
  read(size) {
    return __awaiter(this, void 0, void 0, function* () {
      return (yield this.next(size, "read")).value;
    });
  }
  peek(size) {
    return __awaiter(this, void 0, void 0, function* () {
      return (yield this.next(size, "peek")).value;
    });
  }
  next(..._args) {
    if (this._values.length > 0) {
      return Promise.resolve({ done: false, value: this._values.shift() });
    } else if (this._error) {
      return Promise.reject({ done: true, value: this._error.error });
    } else if (!this._closedPromiseResolve) {
      return Promise.resolve(ITERATOR_DONE);
    } else {
      return new Promise((resolve2, reject) => {
        this.resolvers.push({ resolve: resolve2, reject });
      });
    }
  }
  _ensureOpen() {
    if (this._closedPromiseResolve) {
      return true;
    }
    throw new Error(`AsyncQueue is closed`);
  }
}
class AsyncByteQueue extends AsyncQueue {
  write(value2) {
    if ((value2 = toUint8Array(value2)).byteLength > 0) {
      return super.write(value2);
    }
  }
  toString(sync = false) {
    return sync ? decodeUtf8$1(this.toUint8Array(true)) : this.toUint8Array(false).then(decodeUtf8$1);
  }
  toUint8Array(sync = false) {
    return sync ? joinUint8Arrays(this._values)[0] : (() => __awaiter(this, void 0, void 0, function* () {
      var _a2, e_1, _b2, _c2;
      const buffers = [];
      let byteLength = 0;
      try {
        for (var _d2 = true, _e2 = __asyncValues(this), _f2; _f2 = yield _e2.next(), _a2 = _f2.done, !_a2; _d2 = true) {
          _c2 = _f2.value;
          _d2 = false;
          const chunk = _c2;
          buffers.push(chunk);
          byteLength += chunk.byteLength;
        }
      } catch (e_1_1) {
        e_1 = { error: e_1_1 };
      } finally {
        try {
          if (!_d2 && !_a2 && (_b2 = _e2.return)) yield _b2.call(_e2);
        } finally {
          if (e_1) throw e_1.error;
        }
      }
      return joinUint8Arrays(buffers, byteLength)[0];
    }))();
  }
}
class ByteStream {
  constructor(source2) {
    if (source2) {
      this.source = new ByteStreamSource(streamAdapters.fromIterable(source2));
    }
  }
  [Symbol.iterator]() {
    return this;
  }
  next(value2) {
    return this.source.next(value2);
  }
  throw(value2) {
    return this.source.throw(value2);
  }
  return(value2) {
    return this.source.return(value2);
  }
  peek(size) {
    return this.source.peek(size);
  }
  read(size) {
    return this.source.read(size);
  }
}
class AsyncByteStream {
  constructor(source2) {
    if (source2 instanceof AsyncByteStream) {
      this.source = source2.source;
    } else if (source2 instanceof AsyncByteQueue) {
      this.source = new AsyncByteStreamSource(streamAdapters.fromAsyncIterable(source2));
    } else if (isReadableNodeStream(source2)) {
      this.source = new AsyncByteStreamSource(streamAdapters.fromNodeStream(source2));
    } else if (isReadableDOMStream(source2)) {
      this.source = new AsyncByteStreamSource(streamAdapters.fromDOMStream(source2));
    } else if (isFetchResponse(source2)) {
      this.source = new AsyncByteStreamSource(streamAdapters.fromDOMStream(source2.body));
    } else if (isIterable$1(source2)) {
      this.source = new AsyncByteStreamSource(streamAdapters.fromIterable(source2));
    } else if (isPromise(source2)) {
      this.source = new AsyncByteStreamSource(streamAdapters.fromAsyncIterable(source2));
    } else if (isAsyncIterable(source2)) {
      this.source = new AsyncByteStreamSource(streamAdapters.fromAsyncIterable(source2));
    }
  }
  [Symbol.asyncIterator]() {
    return this;
  }
  next(value2) {
    return this.source.next(value2);
  }
  throw(value2) {
    return this.source.throw(value2);
  }
  return(value2) {
    return this.source.return(value2);
  }
  get closed() {
    return this.source.closed;
  }
  cancel(reason) {
    return this.source.cancel(reason);
  }
  peek(size) {
    return this.source.peek(size);
  }
  read(size) {
    return this.source.read(size);
  }
}
class ByteStreamSource {
  constructor(source2) {
    this.source = source2;
  }
  cancel(reason) {
    this.return(reason);
  }
  peek(size) {
    return this.next(size, "peek").value;
  }
  read(size) {
    return this.next(size, "read").value;
  }
  next(size, cmd = "read") {
    return this.source.next({ cmd, size });
  }
  throw(value2) {
    return Object.create(this.source.throw && this.source.throw(value2) || ITERATOR_DONE);
  }
  return(value2) {
    return Object.create(this.source.return && this.source.return(value2) || ITERATOR_DONE);
  }
}
class AsyncByteStreamSource {
  constructor(source2) {
    this.source = source2;
    this._closedPromise = new Promise((r2) => this._closedPromiseResolve = r2);
  }
  cancel(reason) {
    return __awaiter(this, void 0, void 0, function* () {
      yield this.return(reason);
    });
  }
  get closed() {
    return this._closedPromise;
  }
  read(size) {
    return __awaiter(this, void 0, void 0, function* () {
      return (yield this.next(size, "read")).value;
    });
  }
  peek(size) {
    return __awaiter(this, void 0, void 0, function* () {
      return (yield this.next(size, "peek")).value;
    });
  }
  next(size_1) {
    return __awaiter(this, arguments, void 0, function* (size, cmd = "read") {
      return yield this.source.next({ cmd, size });
    });
  }
  throw(value2) {
    return __awaiter(this, void 0, void 0, function* () {
      const result2 = this.source.throw && (yield this.source.throw(value2)) || ITERATOR_DONE;
      this._closedPromiseResolve && this._closedPromiseResolve();
      this._closedPromiseResolve = void 0;
      return Object.create(result2);
    });
  }
  return(value2) {
    return __awaiter(this, void 0, void 0, function* () {
      const result2 = this.source.return && (yield this.source.return(value2)) || ITERATOR_DONE;
      this._closedPromiseResolve && this._closedPromiseResolve();
      this._closedPromiseResolve = void 0;
      return Object.create(result2);
    });
  }
}
class RandomAccessFile extends ByteStream {
  constructor(buffer2, byteLength) {
    super();
    this.position = 0;
    this.buffer = toUint8Array(buffer2);
    this.size = byteLength === void 0 ? this.buffer.byteLength : byteLength;
  }
  readInt32(position) {
    const { buffer: buffer2, byteOffset } = this.readAt(position, 4);
    return new DataView(buffer2, byteOffset).getInt32(0, true);
  }
  seek(position) {
    this.position = Math.min(position, this.size);
    return position < this.size;
  }
  read(nBytes) {
    const { buffer: buffer2, size, position } = this;
    if (buffer2 && position < size) {
      if (typeof nBytes !== "number") {
        nBytes = Number.POSITIVE_INFINITY;
      }
      this.position = Math.min(size, position + Math.min(size - position, nBytes));
      return buffer2.subarray(position, this.position);
    }
    return null;
  }
  readAt(position, nBytes) {
    const buf2 = this.buffer;
    const end2 = Math.min(this.size, position + nBytes);
    return buf2 ? buf2.subarray(position, end2) : new Uint8Array(nBytes);
  }
  close() {
    this.buffer && (this.buffer = null);
  }
  throw(value2) {
    this.close();
    return { done: true, value: value2 };
  }
  return(value2) {
    this.close();
    return { done: true, value: value2 };
  }
}
class AsyncRandomAccessFile extends AsyncByteStream {
  constructor(file, byteLength) {
    super();
    this.position = 0;
    this._handle = file;
    if (typeof byteLength === "number") {
      this.size = byteLength;
    } else {
      this._pending = (() => __awaiter(this, void 0, void 0, function* () {
        this.size = (yield file.stat()).size;
        delete this._pending;
      }))();
    }
  }
  readInt32(position) {
    return __awaiter(this, void 0, void 0, function* () {
      const { buffer: buffer2, byteOffset } = yield this.readAt(position, 4);
      return new DataView(buffer2, byteOffset).getInt32(0, true);
    });
  }
  seek(position) {
    return __awaiter(this, void 0, void 0, function* () {
      this._pending && (yield this._pending);
      this.position = Math.min(position, this.size);
      return position < this.size;
    });
  }
  read(nBytes) {
    return __awaiter(this, void 0, void 0, function* () {
      this._pending && (yield this._pending);
      const { _handle: file, size, position } = this;
      if (file && position < size) {
        if (typeof nBytes !== "number") {
          nBytes = Number.POSITIVE_INFINITY;
        }
        let pos2 = position, offset3 = 0, bytesRead = 0;
        const end2 = Math.min(size, pos2 + Math.min(size - pos2, nBytes));
        const buffer2 = new Uint8Array(Math.max(0, (this.position = end2) - pos2));
        while ((pos2 += bytesRead) < end2 && (offset3 += bytesRead) < buffer2.byteLength) {
          ({ bytesRead } = yield file.read(buffer2, offset3, buffer2.byteLength - offset3, pos2));
        }
        return buffer2;
      }
      return null;
    });
  }
  readAt(position, nBytes) {
    return __awaiter(this, void 0, void 0, function* () {
      this._pending && (yield this._pending);
      const { _handle: file, size } = this;
      if (file && position + nBytes < size) {
        const end2 = Math.min(size, position + nBytes);
        const buffer2 = new Uint8Array(end2 - position);
        return (yield file.read(buffer2, 0, nBytes, position)).buffer;
      }
      return new Uint8Array(nBytes);
    });
  }
  close() {
    return __awaiter(this, void 0, void 0, function* () {
      const f = this._handle;
      this._handle = null;
      f && (yield f.close());
    });
  }
  throw(value2) {
    return __awaiter(this, void 0, void 0, function* () {
      yield this.close();
      return { done: true, value: value2 };
    });
  }
  return(value2) {
    return __awaiter(this, void 0, void 0, function* () {
      yield this.close();
      return { done: true, value: value2 };
    });
  }
}
const carryBit16 = 1 << 16;
function intAsHex(value2) {
  if (value2 < 0) {
    value2 = 4294967295 + value2 + 1;
  }
  return `0x${value2.toString(16)}`;
}
const kInt32DecimalDigits = 8;
const kPowersOfTen = [
  1,
  10,
  100,
  1e3,
  1e4,
  1e5,
  1e6,
  1e7,
  1e8
];
class BaseInt64 {
  constructor(buffer2) {
    this.buffer = buffer2;
  }
  high() {
    return this.buffer[1];
  }
  low() {
    return this.buffer[0];
  }
  _times(other) {
    const L = new Uint32Array([
      this.buffer[1] >>> 16,
      this.buffer[1] & 65535,
      this.buffer[0] >>> 16,
      this.buffer[0] & 65535
    ]);
    const R = new Uint32Array([
      other.buffer[1] >>> 16,
      other.buffer[1] & 65535,
      other.buffer[0] >>> 16,
      other.buffer[0] & 65535
    ]);
    let product2 = L[3] * R[3];
    this.buffer[0] = product2 & 65535;
    let sum = product2 >>> 16;
    product2 = L[2] * R[3];
    sum += product2;
    product2 = L[3] * R[2] >>> 0;
    sum += product2;
    this.buffer[0] += sum << 16;
    this.buffer[1] = sum >>> 0 < product2 ? carryBit16 : 0;
    this.buffer[1] += sum >>> 16;
    this.buffer[1] += L[1] * R[3] + L[2] * R[2] + L[3] * R[1];
    this.buffer[1] += L[0] * R[3] + L[1] * R[2] + L[2] * R[1] + L[3] * R[0] << 16;
    return this;
  }
  _plus(other) {
    const sum = this.buffer[0] + other.buffer[0] >>> 0;
    this.buffer[1] += other.buffer[1];
    if (sum < this.buffer[0] >>> 0) {
      ++this.buffer[1];
    }
    this.buffer[0] = sum;
  }
  lessThan(other) {
    return this.buffer[1] < other.buffer[1] || this.buffer[1] === other.buffer[1] && this.buffer[0] < other.buffer[0];
  }
  equals(other) {
    return this.buffer[1] === other.buffer[1] && this.buffer[0] == other.buffer[0];
  }
  greaterThan(other) {
    return other.lessThan(this);
  }
  hex() {
    return `${intAsHex(this.buffer[1])} ${intAsHex(this.buffer[0])}`;
  }
}
class Uint64 extends BaseInt64 {
  times(other) {
    this._times(other);
    return this;
  }
  plus(other) {
    this._plus(other);
    return this;
  }
  /** @nocollapse */
  static from(val, out_buffer = new Uint32Array(2)) {
    return Uint64.fromString(typeof val === "string" ? val : val.toString(), out_buffer);
  }
  /** @nocollapse */
  static fromNumber(num, out_buffer = new Uint32Array(2)) {
    return Uint64.fromString(num.toString(), out_buffer);
  }
  /** @nocollapse */
  static fromString(str, out_buffer = new Uint32Array(2)) {
    const length2 = str.length;
    const out = new Uint64(out_buffer);
    for (let posn = 0; posn < length2; ) {
      const group = kInt32DecimalDigits < length2 - posn ? kInt32DecimalDigits : length2 - posn;
      const chunk = new Uint64(new Uint32Array([Number.parseInt(str.slice(posn, posn + group), 10), 0]));
      const multiple = new Uint64(new Uint32Array([kPowersOfTen[group], 0]));
      out.times(multiple);
      out.plus(chunk);
      posn += group;
    }
    return out;
  }
  /** @nocollapse */
  static convertArray(values2) {
    const data2 = new Uint32Array(values2.length * 2);
    for (let i2 = -1, n2 = values2.length; ++i2 < n2; ) {
      Uint64.from(values2[i2], new Uint32Array(data2.buffer, data2.byteOffset + 2 * i2 * 4, 2));
    }
    return data2;
  }
  /** @nocollapse */
  static multiply(left2, right2) {
    const rtrn = new Uint64(new Uint32Array(left2.buffer));
    return rtrn.times(right2);
  }
  /** @nocollapse */
  static add(left2, right2) {
    const rtrn = new Uint64(new Uint32Array(left2.buffer));
    return rtrn.plus(right2);
  }
}
class Int64 extends BaseInt64 {
  negate() {
    this.buffer[0] = ~this.buffer[0] + 1;
    this.buffer[1] = ~this.buffer[1];
    if (this.buffer[0] == 0) {
      ++this.buffer[1];
    }
    return this;
  }
  times(other) {
    this._times(other);
    return this;
  }
  plus(other) {
    this._plus(other);
    return this;
  }
  lessThan(other) {
    const this_high = this.buffer[1] << 0;
    const other_high = other.buffer[1] << 0;
    return this_high < other_high || this_high === other_high && this.buffer[0] < other.buffer[0];
  }
  /** @nocollapse */
  static from(val, out_buffer = new Uint32Array(2)) {
    return Int64.fromString(typeof val === "string" ? val : val.toString(), out_buffer);
  }
  /** @nocollapse */
  static fromNumber(num, out_buffer = new Uint32Array(2)) {
    return Int64.fromString(num.toString(), out_buffer);
  }
  /** @nocollapse */
  static fromString(str, out_buffer = new Uint32Array(2)) {
    const negate = str.startsWith("-");
    const length2 = str.length;
    const out = new Int64(out_buffer);
    for (let posn = negate ? 1 : 0; posn < length2; ) {
      const group = kInt32DecimalDigits < length2 - posn ? kInt32DecimalDigits : length2 - posn;
      const chunk = new Int64(new Uint32Array([Number.parseInt(str.slice(posn, posn + group), 10), 0]));
      const multiple = new Int64(new Uint32Array([kPowersOfTen[group], 0]));
      out.times(multiple);
      out.plus(chunk);
      posn += group;
    }
    return negate ? out.negate() : out;
  }
  /** @nocollapse */
  static convertArray(values2) {
    const data2 = new Uint32Array(values2.length * 2);
    for (let i2 = -1, n2 = values2.length; ++i2 < n2; ) {
      Int64.from(values2[i2], new Uint32Array(data2.buffer, data2.byteOffset + 2 * i2 * 4, 2));
    }
    return data2;
  }
  /** @nocollapse */
  static multiply(left2, right2) {
    const rtrn = new Int64(new Uint32Array(left2.buffer));
    return rtrn.times(right2);
  }
  /** @nocollapse */
  static add(left2, right2) {
    const rtrn = new Int64(new Uint32Array(left2.buffer));
    return rtrn.plus(right2);
  }
}
class Int128 {
  constructor(buffer2) {
    this.buffer = buffer2;
  }
  high() {
    return new Int64(new Uint32Array(this.buffer.buffer, this.buffer.byteOffset + 8, 2));
  }
  low() {
    return new Int64(new Uint32Array(this.buffer.buffer, this.buffer.byteOffset, 2));
  }
  negate() {
    this.buffer[0] = ~this.buffer[0] + 1;
    this.buffer[1] = ~this.buffer[1];
    this.buffer[2] = ~this.buffer[2];
    this.buffer[3] = ~this.buffer[3];
    if (this.buffer[0] == 0) {
      ++this.buffer[1];
    }
    if (this.buffer[1] == 0) {
      ++this.buffer[2];
    }
    if (this.buffer[2] == 0) {
      ++this.buffer[3];
    }
    return this;
  }
  times(other) {
    const L0 = new Uint64(new Uint32Array([this.buffer[3], 0]));
    const L1 = new Uint64(new Uint32Array([this.buffer[2], 0]));
    const L2 = new Uint64(new Uint32Array([this.buffer[1], 0]));
    const L3 = new Uint64(new Uint32Array([this.buffer[0], 0]));
    const R0 = new Uint64(new Uint32Array([other.buffer[3], 0]));
    const R1 = new Uint64(new Uint32Array([other.buffer[2], 0]));
    const R2 = new Uint64(new Uint32Array([other.buffer[1], 0]));
    const R3 = new Uint64(new Uint32Array([other.buffer[0], 0]));
    let product2 = Uint64.multiply(L3, R3);
    this.buffer[0] = product2.low();
    const sum = new Uint64(new Uint32Array([product2.high(), 0]));
    product2 = Uint64.multiply(L2, R3);
    sum.plus(product2);
    product2 = Uint64.multiply(L3, R2);
    sum.plus(product2);
    this.buffer[1] = sum.low();
    this.buffer[3] = sum.lessThan(product2) ? 1 : 0;
    this.buffer[2] = sum.high();
    const high = new Uint64(new Uint32Array(this.buffer.buffer, this.buffer.byteOffset + 8, 2));
    high.plus(Uint64.multiply(L1, R3)).plus(Uint64.multiply(L2, R2)).plus(Uint64.multiply(L3, R1));
    this.buffer[3] += Uint64.multiply(L0, R3).plus(Uint64.multiply(L1, R2)).plus(Uint64.multiply(L2, R1)).plus(Uint64.multiply(L3, R0)).low();
    return this;
  }
  plus(other) {
    const sums = new Uint32Array(4);
    sums[3] = this.buffer[3] + other.buffer[3] >>> 0;
    sums[2] = this.buffer[2] + other.buffer[2] >>> 0;
    sums[1] = this.buffer[1] + other.buffer[1] >>> 0;
    sums[0] = this.buffer[0] + other.buffer[0] >>> 0;
    if (sums[0] < this.buffer[0] >>> 0) {
      ++sums[1];
    }
    if (sums[1] < this.buffer[1] >>> 0) {
      ++sums[2];
    }
    if (sums[2] < this.buffer[2] >>> 0) {
      ++sums[3];
    }
    this.buffer[3] = sums[3];
    this.buffer[2] = sums[2];
    this.buffer[1] = sums[1];
    this.buffer[0] = sums[0];
    return this;
  }
  hex() {
    return `${intAsHex(this.buffer[3])} ${intAsHex(this.buffer[2])} ${intAsHex(this.buffer[1])} ${intAsHex(this.buffer[0])}`;
  }
  /** @nocollapse */
  static multiply(left2, right2) {
    const rtrn = new Int128(new Uint32Array(left2.buffer));
    return rtrn.times(right2);
  }
  /** @nocollapse */
  static add(left2, right2) {
    const rtrn = new Int128(new Uint32Array(left2.buffer));
    return rtrn.plus(right2);
  }
  /** @nocollapse */
  static from(val, out_buffer = new Uint32Array(4)) {
    return Int128.fromString(typeof val === "string" ? val : val.toString(), out_buffer);
  }
  /** @nocollapse */
  static fromNumber(num, out_buffer = new Uint32Array(4)) {
    return Int128.fromString(num.toString(), out_buffer);
  }
  /** @nocollapse */
  static fromString(str, out_buffer = new Uint32Array(4)) {
    const negate = str.startsWith("-");
    const length2 = str.length;
    const out = new Int128(out_buffer);
    for (let posn = negate ? 1 : 0; posn < length2; ) {
      const group = kInt32DecimalDigits < length2 - posn ? kInt32DecimalDigits : length2 - posn;
      const chunk = new Int128(new Uint32Array([Number.parseInt(str.slice(posn, posn + group), 10), 0, 0, 0]));
      const multiple = new Int128(new Uint32Array([kPowersOfTen[group], 0, 0, 0]));
      out.times(multiple);
      out.plus(chunk);
      posn += group;
    }
    return negate ? out.negate() : out;
  }
  /** @nocollapse */
  static convertArray(values2) {
    const data2 = new Uint32Array(values2.length * 4);
    for (let i2 = -1, n2 = values2.length; ++i2 < n2; ) {
      Int128.from(values2[i2], new Uint32Array(data2.buffer, data2.byteOffset + 4 * 4 * i2, 4));
    }
    return data2;
  }
}
function toIntervalDayTimeInt32Array(objects) {
  var _a2, _b2;
  const length2 = objects.length;
  const array2 = new Int32Array(length2 * 2);
  for (let oi = 0, ai = 0; oi < length2; oi++) {
    const interval2 = objects[oi];
    array2[ai++] = (_a2 = interval2["days"]) !== null && _a2 !== void 0 ? _a2 : 0;
    array2[ai++] = (_b2 = interval2["milliseconds"]) !== null && _b2 !== void 0 ? _b2 : 0;
  }
  return array2;
}
function toIntervalMonthDayNanoInt32Array(objects) {
  var _a2, _b2;
  const length2 = objects.length;
  const data2 = new Int32Array(length2 * 4);
  for (let oi = 0, ai = 0; oi < length2; oi++) {
    const interval2 = objects[oi];
    data2[ai++] = (_a2 = interval2["months"]) !== null && _a2 !== void 0 ? _a2 : 0;
    data2[ai++] = (_b2 = interval2["days"]) !== null && _b2 !== void 0 ? _b2 : 0;
    const nanoseconds = interval2["nanoseconds"];
    if (nanoseconds) {
      data2[ai++] = Number(BigInt(nanoseconds) & BigInt(4294967295));
      data2[ai++] = Number(BigInt(nanoseconds) >> BigInt(32));
    } else {
      ai += 2;
    }
  }
  return data2;
}
class VectorLoader extends Visitor {
  constructor(bytes, nodes, buffers, dictionaries, metadataVersion = MetadataVersion.V5) {
    super();
    this.nodesIndex = -1;
    this.buffersIndex = -1;
    this.bytes = bytes;
    this.nodes = nodes;
    this.buffers = buffers;
    this.dictionaries = dictionaries;
    this.metadataVersion = metadataVersion;
  }
  visit(node2) {
    return super.visit(node2 instanceof Field2 ? node2.type : node2);
  }
  visitNull(type, { length: length2 } = this.nextFieldNode()) {
    return makeData({ type, length: length2 });
  }
  visitBool(type, { length: length2, nullCount } = this.nextFieldNode()) {
    return makeData({ type, length: length2, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), data: this.readData(type) });
  }
  visitInt(type, { length: length2, nullCount } = this.nextFieldNode()) {
    return makeData({ type, length: length2, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), data: this.readData(type) });
  }
  visitFloat(type, { length: length2, nullCount } = this.nextFieldNode()) {
    return makeData({ type, length: length2, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), data: this.readData(type) });
  }
  visitUtf8(type, { length: length2, nullCount } = this.nextFieldNode()) {
    return makeData({ type, length: length2, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), valueOffsets: this.readOffsets(type), data: this.readData(type) });
  }
  visitLargeUtf8(type, { length: length2, nullCount } = this.nextFieldNode()) {
    return makeData({ type, length: length2, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), valueOffsets: this.readOffsets(type), data: this.readData(type) });
  }
  visitBinary(type, { length: length2, nullCount } = this.nextFieldNode()) {
    return makeData({ type, length: length2, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), valueOffsets: this.readOffsets(type), data: this.readData(type) });
  }
  visitLargeBinary(type, { length: length2, nullCount } = this.nextFieldNode()) {
    return makeData({ type, length: length2, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), valueOffsets: this.readOffsets(type), data: this.readData(type) });
  }
  visitFixedSizeBinary(type, { length: length2, nullCount } = this.nextFieldNode()) {
    return makeData({ type, length: length2, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), data: this.readData(type) });
  }
  visitDate(type, { length: length2, nullCount } = this.nextFieldNode()) {
    return makeData({ type, length: length2, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), data: this.readData(type) });
  }
  visitTimestamp(type, { length: length2, nullCount } = this.nextFieldNode()) {
    return makeData({ type, length: length2, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), data: this.readData(type) });
  }
  visitTime(type, { length: length2, nullCount } = this.nextFieldNode()) {
    return makeData({ type, length: length2, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), data: this.readData(type) });
  }
  visitDecimal(type, { length: length2, nullCount } = this.nextFieldNode()) {
    return makeData({ type, length: length2, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), data: this.readData(type) });
  }
  visitList(type, { length: length2, nullCount } = this.nextFieldNode()) {
    return makeData({ type, length: length2, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), valueOffsets: this.readOffsets(type), "child": this.visit(type.children[0]) });
  }
  visitStruct(type, { length: length2, nullCount } = this.nextFieldNode()) {
    return makeData({ type, length: length2, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), children: this.visitMany(type.children) });
  }
  visitUnion(type, { length: length2, nullCount } = this.nextFieldNode()) {
    if (this.metadataVersion < MetadataVersion.V5) {
      this.readNullBitmap(type, nullCount);
    }
    return type.mode === UnionMode$1.Sparse ? this.visitSparseUnion(type, { length: length2, nullCount }) : this.visitDenseUnion(type, { length: length2, nullCount });
  }
  visitDenseUnion(type, { length: length2, nullCount } = this.nextFieldNode()) {
    return makeData({ type, length: length2, nullCount, typeIds: this.readTypeIds(type), valueOffsets: this.readOffsets(type), children: this.visitMany(type.children) });
  }
  visitSparseUnion(type, { length: length2, nullCount } = this.nextFieldNode()) {
    return makeData({ type, length: length2, nullCount, typeIds: this.readTypeIds(type), children: this.visitMany(type.children) });
  }
  visitDictionary(type, { length: length2, nullCount } = this.nextFieldNode()) {
    return makeData({ type, length: length2, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), data: this.readData(type.indices), dictionary: this.readDictionary(type) });
  }
  visitInterval(type, { length: length2, nullCount } = this.nextFieldNode()) {
    return makeData({ type, length: length2, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), data: this.readData(type) });
  }
  visitDuration(type, { length: length2, nullCount } = this.nextFieldNode()) {
    return makeData({ type, length: length2, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), data: this.readData(type) });
  }
  visitFixedSizeList(type, { length: length2, nullCount } = this.nextFieldNode()) {
    return makeData({ type, length: length2, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), "child": this.visit(type.children[0]) });
  }
  visitMap(type, { length: length2, nullCount } = this.nextFieldNode()) {
    return makeData({ type, length: length2, nullCount, nullBitmap: this.readNullBitmap(type, nullCount), valueOffsets: this.readOffsets(type), "child": this.visit(type.children[0]) });
  }
  nextFieldNode() {
    return this.nodes[++this.nodesIndex];
  }
  nextBufferRange() {
    return this.buffers[++this.buffersIndex];
  }
  readNullBitmap(type, nullCount, buffer2 = this.nextBufferRange()) {
    return nullCount > 0 && this.readData(type, buffer2) || new Uint8Array(0);
  }
  readOffsets(type, buffer2) {
    return this.readData(type, buffer2);
  }
  readTypeIds(type, buffer2) {
    return this.readData(type, buffer2);
  }
  readData(_type, { length: length2, offset: offset3 } = this.nextBufferRange()) {
    return this.bytes.subarray(offset3, offset3 + length2);
  }
  readDictionary(type) {
    return this.dictionaries.get(type.id);
  }
}
class JSONVectorLoader extends VectorLoader {
  constructor(sources, nodes, buffers, dictionaries, metadataVersion) {
    super(new Uint8Array(0), nodes, buffers, dictionaries, metadataVersion);
    this.sources = sources;
  }
  readNullBitmap(_type, nullCount, { offset: offset3 } = this.nextBufferRange()) {
    return nullCount <= 0 ? new Uint8Array(0) : packBools(this.sources[offset3]);
  }
  readOffsets(_type, { offset: offset3 } = this.nextBufferRange()) {
    return toArrayBufferView(Uint8Array, toArrayBufferView(_type.OffsetArrayType, this.sources[offset3]));
  }
  readTypeIds(type, { offset: offset3 } = this.nextBufferRange()) {
    return toArrayBufferView(Uint8Array, toArrayBufferView(type.ArrayType, this.sources[offset3]));
  }
  readData(type, { offset: offset3 } = this.nextBufferRange()) {
    const { sources } = this;
    if (DataType.isTimestamp(type)) {
      return toArrayBufferView(Uint8Array, Int64.convertArray(sources[offset3]));
    } else if ((DataType.isInt(type) || DataType.isTime(type)) && type.bitWidth === 64 || DataType.isDuration(type)) {
      return toArrayBufferView(Uint8Array, Int64.convertArray(sources[offset3]));
    } else if (DataType.isDate(type) && type.unit === DateUnit$1.MILLISECOND) {
      return toArrayBufferView(Uint8Array, Int64.convertArray(sources[offset3]));
    } else if (DataType.isDecimal(type)) {
      return toArrayBufferView(Uint8Array, Int128.convertArray(sources[offset3]));
    } else if (DataType.isBinary(type) || DataType.isLargeBinary(type) || DataType.isFixedSizeBinary(type)) {
      return binaryDataFromJSON(sources[offset3]);
    } else if (DataType.isBool(type)) {
      return packBools(sources[offset3]);
    } else if (DataType.isUtf8(type) || DataType.isLargeUtf8(type)) {
      return encodeUtf8$1(sources[offset3].join(""));
    } else if (DataType.isInterval(type)) {
      switch (type.unit) {
        case IntervalUnit$1.DAY_TIME:
          return toIntervalDayTimeInt32Array(sources[offset3]);
        case IntervalUnit$1.MONTH_DAY_NANO:
          return toIntervalMonthDayNanoInt32Array(sources[offset3]);
      }
    }
    return toArrayBufferView(Uint8Array, toArrayBufferView(type.ArrayType, sources[offset3].map((x) => +x)));
  }
}
function binaryDataFromJSON(values2) {
  const joined = values2.join("");
  const data2 = new Uint8Array(joined.length / 2);
  for (let i2 = 0; i2 < joined.length; i2 += 2) {
    data2[i2 >> 1] = Number.parseInt(joined.slice(i2, i2 + 2), 16);
  }
  return data2;
}
class CompressedVectorLoader extends VectorLoader {
  constructor(bodyChunks, nodes, buffers, dictionaries, metadataVersion) {
    super(new Uint8Array(0), nodes, buffers, dictionaries, metadataVersion);
    this.bodyChunks = bodyChunks;
  }
  readData(_type, _buffer = this.nextBufferRange()) {
    return this.bodyChunks[this.buffersIndex];
  }
}
class TypeComparator extends Visitor {
  compareSchemas(schema, other) {
    return schema === other || other instanceof schema.constructor && this.compareManyFields(schema.fields, other.fields);
  }
  compareManyFields(fields, others) {
    return fields === others || Array.isArray(fields) && Array.isArray(others) && fields.length === others.length && fields.every((f, i2) => this.compareFields(f, others[i2]));
  }
  compareFields(field2, other) {
    return field2 === other || other instanceof field2.constructor && field2.name === other.name && field2.nullable === other.nullable && this.visit(field2.type, other.type);
  }
}
function compareConstructor(type, other) {
  return other instanceof type.constructor;
}
function compareAny(type, other) {
  return type === other || compareConstructor(type, other);
}
function compareInt(type, other) {
  return type === other || compareConstructor(type, other) && type.bitWidth === other.bitWidth && type.isSigned === other.isSigned;
}
function compareFloat(type, other) {
  return type === other || compareConstructor(type, other) && type.precision === other.precision;
}
function compareFixedSizeBinary(type, other) {
  return type === other || compareConstructor(type, other) && type.byteWidth === other.byteWidth;
}
function compareDate(type, other) {
  return type === other || compareConstructor(type, other) && type.unit === other.unit;
}
function compareTimestamp(type, other) {
  return type === other || compareConstructor(type, other) && type.unit === other.unit && type.timezone === other.timezone;
}
function compareTime(type, other) {
  return type === other || compareConstructor(type, other) && type.unit === other.unit && type.bitWidth === other.bitWidth;
}
function compareList(type, other) {
  return type === other || compareConstructor(type, other) && type.children.length === other.children.length && instance.compareManyFields(type.children, other.children);
}
function compareStruct(type, other) {
  return type === other || compareConstructor(type, other) && type.children.length === other.children.length && instance.compareManyFields(type.children, other.children);
}
function compareUnion(type, other) {
  return type === other || compareConstructor(type, other) && type.mode === other.mode && type.typeIds.every((x, i2) => x === other.typeIds[i2]) && instance.compareManyFields(type.children, other.children);
}
function compareDictionary(type, other) {
  return type === other || compareConstructor(type, other) && type.id === other.id && type.isOrdered === other.isOrdered && instance.visit(type.indices, other.indices) && instance.visit(type.dictionary, other.dictionary);
}
function compareInterval(type, other) {
  return type === other || compareConstructor(type, other) && type.unit === other.unit;
}
function compareDuration(type, other) {
  return type === other || compareConstructor(type, other) && type.unit === other.unit;
}
function compareFixedSizeList(type, other) {
  return type === other || compareConstructor(type, other) && type.listSize === other.listSize && type.children.length === other.children.length && instance.compareManyFields(type.children, other.children);
}
function compareMap(type, other) {
  return type === other || compareConstructor(type, other) && type.keysSorted === other.keysSorted && type.children.length === other.children.length && instance.compareManyFields(type.children, other.children);
}
TypeComparator.prototype.visitNull = compareAny;
TypeComparator.prototype.visitBool = compareAny;
TypeComparator.prototype.visitInt = compareInt;
TypeComparator.prototype.visitInt8 = compareInt;
TypeComparator.prototype.visitInt16 = compareInt;
TypeComparator.prototype.visitInt32 = compareInt;
TypeComparator.prototype.visitInt64 = compareInt;
TypeComparator.prototype.visitUint8 = compareInt;
TypeComparator.prototype.visitUint16 = compareInt;
TypeComparator.prototype.visitUint32 = compareInt;
TypeComparator.prototype.visitUint64 = compareInt;
TypeComparator.prototype.visitFloat = compareFloat;
TypeComparator.prototype.visitFloat16 = compareFloat;
TypeComparator.prototype.visitFloat32 = compareFloat;
TypeComparator.prototype.visitFloat64 = compareFloat;
TypeComparator.prototype.visitUtf8 = compareAny;
TypeComparator.prototype.visitLargeUtf8 = compareAny;
TypeComparator.prototype.visitBinary = compareAny;
TypeComparator.prototype.visitLargeBinary = compareAny;
TypeComparator.prototype.visitFixedSizeBinary = compareFixedSizeBinary;
TypeComparator.prototype.visitDate = compareDate;
TypeComparator.prototype.visitDateDay = compareDate;
TypeComparator.prototype.visitDateMillisecond = compareDate;
TypeComparator.prototype.visitTimestamp = compareTimestamp;
TypeComparator.prototype.visitTimestampSecond = compareTimestamp;
TypeComparator.prototype.visitTimestampMillisecond = compareTimestamp;
TypeComparator.prototype.visitTimestampMicrosecond = compareTimestamp;
TypeComparator.prototype.visitTimestampNanosecond = compareTimestamp;
TypeComparator.prototype.visitTime = compareTime;
TypeComparator.prototype.visitTimeSecond = compareTime;
TypeComparator.prototype.visitTimeMillisecond = compareTime;
TypeComparator.prototype.visitTimeMicrosecond = compareTime;
TypeComparator.prototype.visitTimeNanosecond = compareTime;
TypeComparator.prototype.visitDecimal = compareAny;
TypeComparator.prototype.visitList = compareList;
TypeComparator.prototype.visitStruct = compareStruct;
TypeComparator.prototype.visitUnion = compareUnion;
TypeComparator.prototype.visitDenseUnion = compareUnion;
TypeComparator.prototype.visitSparseUnion = compareUnion;
TypeComparator.prototype.visitDictionary = compareDictionary;
TypeComparator.prototype.visitInterval = compareInterval;
TypeComparator.prototype.visitIntervalDayTime = compareInterval;
TypeComparator.prototype.visitIntervalYearMonth = compareInterval;
TypeComparator.prototype.visitIntervalMonthDayNano = compareInterval;
TypeComparator.prototype.visitDuration = compareDuration;
TypeComparator.prototype.visitDurationSecond = compareDuration;
TypeComparator.prototype.visitDurationMillisecond = compareDuration;
TypeComparator.prototype.visitDurationMicrosecond = compareDuration;
TypeComparator.prototype.visitDurationNanosecond = compareDuration;
TypeComparator.prototype.visitFixedSizeList = compareFixedSizeList;
TypeComparator.prototype.visitMap = compareMap;
const instance = new TypeComparator();
function compareSchemas(schema, other) {
  return instance.compareSchemas(schema, other);
}
function distributeVectorsIntoRecordBatches(schema, vecs) {
  return uniformlyDistributeChunksAcrossRecordBatches(schema, vecs.map((v) => v.data.concat()));
}
function uniformlyDistributeChunksAcrossRecordBatches(schema, cols) {
  const fields = [...schema.fields];
  const batches = [];
  const memo2 = { numBatches: cols.reduce((n2, c2) => Math.max(n2, c2.length), 0) };
  let numBatches = 0, batchLength = 0;
  let i2 = -1;
  const numColumns = cols.length;
  let child, children2 = [];
  while (memo2.numBatches-- > 0) {
    for (batchLength = Number.POSITIVE_INFINITY, i2 = -1; ++i2 < numColumns; ) {
      children2[i2] = child = cols[i2].shift();
      batchLength = Math.min(batchLength, child ? child.length : batchLength);
    }
    if (Number.isFinite(batchLength)) {
      children2 = distributeChildren(fields, batchLength, children2, cols, memo2);
      if (batchLength > 0) {
        batches[numBatches++] = makeData({
          type: new Struct(fields),
          length: batchLength,
          nullCount: 0,
          children: children2.slice()
        });
      }
    }
  }
  return [
    schema = schema.assign(fields),
    batches.map((data2) => new RecordBatch3(schema, data2))
  ];
}
function distributeChildren(fields, batchLength, children2, columns2, memo2) {
  var _a2;
  const nullBitmapSize = (batchLength + 63 & -64) >> 3;
  for (let i2 = -1, n2 = columns2.length; ++i2 < n2; ) {
    const child = children2[i2];
    const length2 = child === null || child === void 0 ? void 0 : child.length;
    if (length2 >= batchLength) {
      if (length2 === batchLength) {
        children2[i2] = child;
      } else {
        children2[i2] = child.slice(0, batchLength);
        memo2.numBatches = Math.max(memo2.numBatches, columns2[i2].unshift(child.slice(batchLength, length2 - batchLength)));
      }
    } else {
      const field2 = fields[i2];
      fields[i2] = field2.clone({ nullable: true });
      children2[i2] = (_a2 = child === null || child === void 0 ? void 0 : child._changeLengthAndBackfillNullBitmap(batchLength)) !== null && _a2 !== void 0 ? _a2 : makeData({
        type: field2.type,
        length: batchLength,
        nullCount: batchLength,
        nullBitmap: new Uint8Array(nullBitmapSize)
      });
    }
  }
  return children2;
}
var _a$3;
let Table$2 = class Table {
  constructor(...args2) {
    var _b2, _c2;
    if (args2.length === 0) {
      this.batches = [];
      this.schema = new Schema2([]);
      this._offsets = [0];
      return this;
    }
    let schema;
    let offsets;
    if (args2[0] instanceof Schema2) {
      schema = args2.shift();
    }
    if (args2.at(-1) instanceof Uint32Array) {
      offsets = args2.pop();
    }
    const unwrap2 = (x) => {
      if (x) {
        if (x instanceof RecordBatch3) {
          return [x];
        } else if (x instanceof Table) {
          return x.batches;
        } else if (x instanceof Data) {
          if (x.type instanceof Struct) {
            return [new RecordBatch3(new Schema2(x.type.children), x)];
          }
        } else if (Array.isArray(x)) {
          return x.flatMap((v) => unwrap2(v));
        } else if (typeof x[Symbol.iterator] === "function") {
          return [...x].flatMap((v) => unwrap2(v));
        } else if (typeof x === "object") {
          const keys2 = Object.keys(x);
          const vecs = keys2.map((k) => new Vector([x[k]]));
          const batchSchema = schema !== null && schema !== void 0 ? schema : new Schema2(keys2.map((k, i2) => new Field2(String(k), vecs[i2].type, vecs[i2].nullable)));
          const [, batches2] = distributeVectorsIntoRecordBatches(batchSchema, vecs);
          return batches2.length === 0 ? [new RecordBatch3(x)] : batches2;
        }
      }
      return [];
    };
    const batches = args2.flatMap((v) => unwrap2(v));
    schema = (_c2 = schema !== null && schema !== void 0 ? schema : (_b2 = batches[0]) === null || _b2 === void 0 ? void 0 : _b2.schema) !== null && _c2 !== void 0 ? _c2 : new Schema2([]);
    if (!(schema instanceof Schema2)) {
      throw new TypeError("Table constructor expects a [Schema, RecordBatch[]] pair.");
    }
    for (const batch2 of batches) {
      if (!(batch2 instanceof RecordBatch3)) {
        throw new TypeError("Table constructor expects a [Schema, RecordBatch[]] pair.");
      }
      if (!compareSchemas(schema, batch2.schema)) {
        throw new TypeError("Table and inner RecordBatch schemas must be equivalent.");
      }
    }
    this.schema = schema;
    this.batches = batches;
    this._offsets = offsets !== null && offsets !== void 0 ? offsets : computeChunkOffsets(this.data);
  }
  /**
   * The contiguous {@link RecordBatch `RecordBatch`} chunks of the Table rows.
   */
  get data() {
    return this.batches.map(({ data: data2 }) => data2);
  }
  /**
   * The number of columns in this Table.
   */
  get numCols() {
    return this.schema.fields.length;
  }
  /**
   * The number of rows in this Table.
   */
  get numRows() {
    return this.data.reduce((numRows, data2) => numRows + data2.length, 0);
  }
  /**
   * The number of null rows in this Table.
   */
  get nullCount() {
    if (this._nullCount === -1) {
      this._nullCount = computeChunkNullCounts(this.data);
    }
    return this._nullCount;
  }
  /**
   * Check whether an element is null.
   *
   * @param index The index at which to read the validity bitmap.
   */
  // @ts-ignore
  isValid(index) {
    return false;
  }
  /**
   * Get an element value by position.
   *
   * @param index The index of the element to read.
   */
  // @ts-ignore
  get(index) {
    return null;
  }
  /**
    * Get an element value by position.
    * @param index The index of the element to read. A negative index will count back from the last element.
    */
  // @ts-ignore
  at(index) {
    return this.get(wrapIndex(index, this.numRows));
  }
  /**
   * Set an element value by position.
   *
   * @param index The index of the element to write.
   * @param value The value to set.
   */
  // @ts-ignore
  set(index, value2) {
    return;
  }
  /**
   * Retrieve the index of the first occurrence of a value in an Vector.
   *
   * @param element The value to locate in the Vector.
   * @param offset The index at which to begin the search. If offset is omitted, the search starts at index 0.
   */
  // @ts-ignore
  indexOf(element, offset3) {
    return -1;
  }
  /**
   * Iterator for rows in this Table.
   */
  [Symbol.iterator]() {
    if (this.batches.length > 0) {
      return instance$2.visit(new Vector(this.data));
    }
    return new Array(0)[Symbol.iterator]();
  }
  /**
   * Return a JavaScript Array of the Table rows.
   *
   * @returns An Array of Table rows.
   */
  toArray() {
    return [...this];
  }
  /**
   * Returns a string representation of the Table rows.
   *
   * @returns A string representation of the Table rows.
   */
  toString() {
    return `[
  ${this.toArray().join(",\n  ")}
]`;
  }
  /**
   * Combines two or more Tables of the same schema.
   *
   * @param others Additional Tables to add to the end of this Tables.
   */
  concat(...others) {
    const schema = this.schema;
    const data2 = this.data.concat(others.flatMap(({ data: data3 }) => data3));
    return new Table(schema, data2.map((data3) => new RecordBatch3(schema, data3)));
  }
  /**
   * Return a zero-copy sub-section of this Table.
   *
   * @param begin The beginning of the specified portion of the Table.
   * @param end The end of the specified portion of the Table. This is exclusive of the element at the index 'end'.
   */
  slice(begin, end2) {
    const schema = this.schema;
    [begin, end2] = clampRange({ length: this.numRows }, begin, end2);
    const data2 = sliceChunks(this.data, this._offsets, begin, end2);
    return new Table(schema, data2.map((chunk) => new RecordBatch3(schema, chunk)));
  }
  /**
   * Returns a child Vector by name, or null if this Vector has no child with the given name.
   *
   * @param name The name of the child to retrieve.
   */
  getChild(name2) {
    return this.getChildAt(this.schema.fields.findIndex((f) => f.name === name2));
  }
  /**
   * Returns a child Vector by index, or null if this Vector has no child at the supplied index.
   *
   * @param index The index of the child to retrieve.
   */
  getChildAt(index) {
    if (index > -1 && index < this.schema.fields.length) {
      const data2 = this.data.map((data3) => data3.children[index]);
      if (data2.length === 0) {
        const { type } = this.schema.fields[index];
        const empty2 = makeData({ type, length: 0, nullCount: 0 });
        data2.push(empty2._changeLengthAndBackfillNullBitmap(this.numRows));
      }
      return new Vector(data2);
    }
    return null;
  }
  /**
   * Sets a child Vector by name.
   *
   * @param name The name of the child to overwrite.
   * @returns A new Table with the supplied child for the specified name.
   */
  setChild(name2, child) {
    var _b2;
    return this.setChildAt((_b2 = this.schema.fields) === null || _b2 === void 0 ? void 0 : _b2.findIndex((f) => f.name === name2), child);
  }
  setChildAt(index, child) {
    let schema = this.schema;
    let batches = [...this.batches];
    if (index > -1 && index < this.numCols) {
      if (!child) {
        child = new Vector([makeData({ type: new Null2(), length: this.numRows })]);
      }
      const fields = schema.fields.slice();
      const field2 = fields[index].clone({ type: child.type });
      const children2 = this.schema.fields.map((_, i2) => this.getChildAt(i2));
      [fields[index], children2[index]] = [field2, child];
      [schema, batches] = distributeVectorsIntoRecordBatches(schema, children2);
    }
    return new Table(schema, batches);
  }
  /**
   * Construct a new Table containing only specified columns.
   *
   * @param columnNames Names of columns to keep.
   * @returns A new Table of columns matching the specified names.
   */
  select(columnNames) {
    const nameToIndex = this.schema.fields.reduce((m, f, i2) => m.set(f.name, i2), /* @__PURE__ */ new Map());
    return this.selectAt(columnNames.map((columnName) => nameToIndex.get(columnName)).filter((x) => x > -1));
  }
  /**
   * Construct a new Table containing only columns at the specified indices.
   *
   * @param columnIndices Indices of columns to keep.
   * @returns A new Table of columns at the specified indices.
   */
  selectAt(columnIndices) {
    const schema = this.schema.selectAt(columnIndices);
    const data2 = this.batches.map((batch2) => batch2.selectAt(columnIndices));
    return new Table(schema, data2);
  }
  assign(other) {
    const fields = this.schema.fields;
    const [indices, oldToNew] = other.schema.fields.reduce((memo2, f2, newIdx) => {
      const [indices2, oldToNew2] = memo2;
      const i2 = fields.findIndex((f) => f.name === f2.name);
      ~i2 ? oldToNew2[i2] = newIdx : indices2.push(newIdx);
      return memo2;
    }, [[], []]);
    const schema = this.schema.assign(other.schema);
    const columns2 = [
      ...fields.map((_, i2) => [i2, oldToNew[i2]]).map(([i2, j2]) => j2 === void 0 ? this.getChildAt(i2) : other.getChildAt(j2)),
      ...indices.map((i2) => other.getChildAt(i2))
    ].filter(Boolean);
    return new Table(...distributeVectorsIntoRecordBatches(schema, columns2));
  }
};
_a$3 = Symbol.toStringTag;
Table$2[_a$3] = ((proto) => {
  proto.schema = null;
  proto.batches = [];
  proto._offsets = new Uint32Array([0]);
  proto._nullCount = -1;
  proto[Symbol.isConcatSpreadable] = true;
  proto["isValid"] = wrapChunkedCall1(isChunkedValid);
  proto["get"] = wrapChunkedCall1(instance$4.getVisitFn(Type$1.Struct));
  proto["set"] = wrapChunkedCall2(instance$5.getVisitFn(Type$1.Struct));
  proto["indexOf"] = wrapChunkedIndexOf(instance$3.getVisitFn(Type$1.Struct));
  return "Table";
})(Table$2.prototype);
var _a$2;
class RecordBatch3 {
  constructor(...args2) {
    switch (args2.length) {
      case 2: {
        [this.schema] = args2;
        if (!(this.schema instanceof Schema2)) {
          throw new TypeError("RecordBatch constructor expects a [Schema, Data] pair.");
        }
        [
          ,
          this.data = makeData({
            nullCount: 0,
            type: new Struct(this.schema.fields),
            children: this.schema.fields.map((f) => makeData({ type: f.type, nullCount: 0 }))
          })
        ] = args2;
        if (!(this.data instanceof Data)) {
          throw new TypeError("RecordBatch constructor expects a [Schema, Data] pair.");
        }
        [this.schema, this.data] = ensureSameLengthData(this.schema, this.data.children);
        break;
      }
      case 1: {
        const [obj] = args2;
        const { fields, children: children2, length: length2 } = Object.keys(obj).reduce((memo2, name2, i2) => {
          memo2.children[i2] = obj[name2];
          memo2.length = Math.max(memo2.length, obj[name2].length);
          memo2.fields[i2] = Field2.new({ name: name2, type: obj[name2].type, nullable: true });
          return memo2;
        }, {
          length: 0,
          fields: new Array(),
          children: new Array()
        });
        const schema = new Schema2(fields);
        const data2 = makeData({ type: new Struct(fields), length: length2, children: children2, nullCount: 0 });
        [this.schema, this.data] = ensureSameLengthData(schema, data2.children, length2);
        break;
      }
      default:
        throw new TypeError("RecordBatch constructor expects an Object mapping names to child Data, or a [Schema, Data] pair.");
    }
  }
  get dictionaries() {
    return this._dictionaries || (this._dictionaries = collectDictionaries(this.schema.fields, this.data.children));
  }
  /**
   * The number of columns in this RecordBatch.
   */
  get numCols() {
    return this.schema.fields.length;
  }
  /**
   * The number of rows in this RecordBatch.
   */
  get numRows() {
    return this.data.length;
  }
  /**
   * The number of null rows in this RecordBatch.
   */
  get nullCount() {
    return this.data.nullCount;
  }
  /**
   * Check whether an row is null.
   * @param index The index at which to read the validity bitmap.
   */
  isValid(index) {
    return this.data.getValid(index);
  }
  /**
   * Get a row by position.
   * @param index The index of the row to read.
   */
  get(index) {
    return instance$4.visit(this.data, index);
  }
  /**
    * Get a row value by position.
    * @param index The index of the row to read. A negative index will count back from the last row.
    */
  at(index) {
    return this.get(wrapIndex(index, this.numRows));
  }
  /**
   * Set a row by position.
   * @param index The index of the row to write.
   * @param value The value to set.
   */
  set(index, value2) {
    return instance$5.visit(this.data, index, value2);
  }
  /**
   * Retrieve the index of the first occurrence of a row in an RecordBatch.
   * @param element The row to locate in the RecordBatch.
   * @param offset The index at which to begin the search. If offset is omitted, the search starts at index 0.
   */
  indexOf(element, offset3) {
    return instance$3.visit(this.data, element, offset3);
  }
  /**
   * Iterator for rows in this RecordBatch.
   */
  [Symbol.iterator]() {
    return instance$2.visit(new Vector([this.data]));
  }
  /**
   * Return a JavaScript Array of the RecordBatch rows.
   * @returns An Array of RecordBatch rows.
   */
  toArray() {
    return [...this];
  }
  /**
   * Combines two or more RecordBatch of the same schema.
   * @param others Additional RecordBatch to add to the end of this RecordBatch.
   */
  concat(...others) {
    return new Table$2(this.schema, [this, ...others]);
  }
  /**
   * Return a zero-copy sub-section of this RecordBatch.
   * @param start The beginning of the specified portion of the RecordBatch.
   * @param end The end of the specified portion of the RecordBatch. This is exclusive of the row at the index 'end'.
   */
  slice(begin, end2) {
    const [slice2] = new Vector([this.data]).slice(begin, end2).data;
    return new RecordBatch3(this.schema, slice2);
  }
  /**
   * Returns a child Vector by name, or null if this Vector has no child with the given name.
   * @param name The name of the child to retrieve.
   */
  getChild(name2) {
    var _b2;
    return this.getChildAt((_b2 = this.schema.fields) === null || _b2 === void 0 ? void 0 : _b2.findIndex((f) => f.name === name2));
  }
  /**
   * Returns a child Vector by index, or null if this Vector has no child at the supplied index.
   * @param index The index of the child to retrieve.
   */
  getChildAt(index) {
    if (index > -1 && index < this.schema.fields.length) {
      return new Vector([this.data.children[index]]);
    }
    return null;
  }
  /**
   * Sets a child Vector by name.
   * @param name The name of the child to overwrite.
   * @returns A new RecordBatch with the new child for the specified name.
   */
  setChild(name2, child) {
    var _b2;
    return this.setChildAt((_b2 = this.schema.fields) === null || _b2 === void 0 ? void 0 : _b2.findIndex((f) => f.name === name2), child);
  }
  setChildAt(index, child) {
    let schema = this.schema;
    let data2 = this.data;
    if (index > -1 && index < this.numCols) {
      if (!child) {
        child = new Vector([makeData({ type: new Null2(), length: this.numRows })]);
      }
      const fields = schema.fields.slice();
      const children2 = data2.children.slice();
      const field2 = fields[index].clone({ type: child.type });
      [fields[index], children2[index]] = [field2, child.data[0]];
      schema = new Schema2(fields, new Map(this.schema.metadata));
      data2 = makeData({ type: new Struct(fields), children: children2 });
    }
    return new RecordBatch3(schema, data2);
  }
  /**
   * Construct a new RecordBatch containing only specified columns.
   *
   * @param columnNames Names of columns to keep.
   * @returns A new RecordBatch of columns matching the specified names.
   */
  select(columnNames) {
    const schema = this.schema.select(columnNames);
    const type = new Struct(schema.fields);
    const children2 = [];
    for (const name2 of columnNames) {
      const index = this.schema.fields.findIndex((f) => f.name === name2);
      if (~index) {
        children2[index] = this.data.children[index];
      }
    }
    return new RecordBatch3(schema, makeData({ type, length: this.numRows, children: children2 }));
  }
  /**
   * Construct a new RecordBatch containing only columns at the specified indices.
   *
   * @param columnIndices Indices of columns to keep.
   * @returns A new RecordBatch of columns matching at the specified indices.
   */
  selectAt(columnIndices) {
    const schema = this.schema.selectAt(columnIndices);
    const children2 = columnIndices.map((i2) => this.data.children[i2]).filter(Boolean);
    const subset = makeData({ type: new Struct(schema.fields), length: this.numRows, children: children2 });
    return new RecordBatch3(schema, subset);
  }
}
_a$2 = Symbol.toStringTag;
RecordBatch3[_a$2] = ((proto) => {
  proto._nullCount = -1;
  proto[Symbol.isConcatSpreadable] = true;
  return "RecordBatch";
})(RecordBatch3.prototype);
function ensureSameLengthData(schema, chunks, maxLength = chunks.reduce((max2, col) => Math.max(max2, col.length), 0)) {
  var _b2;
  const fields = [...schema.fields];
  const children2 = [...chunks];
  const nullBitmapSize = (maxLength + 63 & -64) >> 3;
  for (const [idx, field2] of schema.fields.entries()) {
    const chunk = chunks[idx];
    if (!chunk || chunk.length !== maxLength) {
      fields[idx] = field2.clone({ nullable: true });
      children2[idx] = (_b2 = chunk === null || chunk === void 0 ? void 0 : chunk._changeLengthAndBackfillNullBitmap(maxLength)) !== null && _b2 !== void 0 ? _b2 : makeData({
        type: field2.type,
        length: maxLength,
        nullCount: maxLength,
        nullBitmap: new Uint8Array(nullBitmapSize)
      });
    }
  }
  return [
    schema.assign(fields),
    makeData({ type: new Struct(fields), length: maxLength, children: children2 })
  ];
}
function collectDictionaries(fields, children2, dictionaries = /* @__PURE__ */ new Map()) {
  var _b2, _c2;
  if (((_b2 = fields === null || fields === void 0 ? void 0 : fields.length) !== null && _b2 !== void 0 ? _b2 : 0) > 0 && (fields === null || fields === void 0 ? void 0 : fields.length) === (children2 === null || children2 === void 0 ? void 0 : children2.length)) {
    for (let i2 = -1, n2 = fields.length; ++i2 < n2; ) {
      const { type } = fields[i2];
      const data2 = children2[i2];
      for (const next of [data2, ...((_c2 = data2 === null || data2 === void 0 ? void 0 : data2.dictionary) === null || _c2 === void 0 ? void 0 : _c2.data) || []]) {
        collectDictionaries(type.children, next === null || next === void 0 ? void 0 : next.children, dictionaries);
      }
      if (DataType.isDictionary(type)) {
        const { id: id2 } = type;
        if (!dictionaries.has(id2)) {
          if (data2 === null || data2 === void 0 ? void 0 : data2.dictionary) {
            dictionaries.set(id2, data2.dictionary);
          }
        } else if (dictionaries.get(id2) !== data2.dictionary) {
          throw new Error(`Cannot create Schema containing two different dictionaries with the same Id`);
        }
      }
    }
  }
  return dictionaries;
}
class _InternalEmptyPlaceholderRecordBatch extends RecordBatch3 {
  constructor(schema) {
    const children2 = schema.fields.map((f) => makeData({ type: f.type }));
    const data2 = makeData({ type: new Struct(schema.fields), nullCount: 0, children: children2 });
    super(schema, data2);
  }
}
const invalidMessageType$1 = (type) => `Expected ${MessageHeader$1[type]} Message in stream, but was null or length 0.`;
const nullMessage = (type) => `Header pointer of flatbuffer-encoded ${MessageHeader$1[type]} Message is null or length 0.`;
const invalidMessageMetadata$1 = (expected, actual) => `Expected to read ${expected} metadata bytes, but only read ${actual}.`;
const invalidMessageBodyLength$1 = (expected, actual) => `Expected to read ${expected} bytes for message body, but only read ${actual}.`;
class MessageReader {
  constructor(source2) {
    this.source = source2 instanceof ByteStream ? source2 : new ByteStream(source2);
  }
  [Symbol.iterator]() {
    return this;
  }
  next() {
    let r2;
    if ((r2 = this.readMetadataLength()).done) {
      return ITERATOR_DONE;
    }
    if (r2.value === -1 && (r2 = this.readMetadataLength()).done) {
      return ITERATOR_DONE;
    }
    if ((r2 = this.readMetadata(r2.value)).done) {
      return ITERATOR_DONE;
    }
    return r2;
  }
  throw(value2) {
    return this.source.throw(value2);
  }
  return(value2) {
    return this.source.return(value2);
  }
  readMessage(type) {
    let r2;
    if ((r2 = this.next()).done) {
      return null;
    }
    if (type != null && r2.value.headerType !== type) {
      throw new Error(invalidMessageType$1(type));
    }
    return r2.value;
  }
  readMessageBody(bodyLength) {
    if (bodyLength <= 0) {
      return new Uint8Array(0);
    }
    const buf2 = toUint8Array(this.source.read(bodyLength));
    if (buf2.byteLength < bodyLength) {
      throw new Error(invalidMessageBodyLength$1(bodyLength, buf2.byteLength));
    }
    return (
      /* 1. */
      buf2.byteOffset % 8 === 0 && /* 2. */
      buf2.byteOffset + buf2.byteLength <= buf2.buffer.byteLength ? buf2 : buf2.slice()
    );
  }
  readSchema(throwIfNull = false) {
    const type = MessageHeader$1.Schema;
    const message2 = this.readMessage(type);
    const schema = message2 === null || message2 === void 0 ? void 0 : message2.header();
    if (throwIfNull && !schema) {
      throw new Error(nullMessage(type));
    }
    return schema;
  }
  readMetadataLength() {
    const buf2 = this.source.read(PADDING);
    const bb = buf2 && new ByteBuffer$2(buf2);
    const len = (bb === null || bb === void 0 ? void 0 : bb.readInt32(0)) || 0;
    return { done: len === 0, value: len };
  }
  readMetadata(metadataLength) {
    const buf2 = this.source.read(metadataLength);
    if (!buf2) {
      return ITERATOR_DONE;
    }
    if (buf2.byteLength < metadataLength) {
      throw new Error(invalidMessageMetadata$1(metadataLength, buf2.byteLength));
    }
    return { done: false, value: Message2.decode(buf2) };
  }
}
class AsyncMessageReader {
  constructor(source2, byteLength) {
    this.source = source2 instanceof AsyncByteStream ? source2 : isFileHandle(source2) ? new AsyncRandomAccessFile(source2, byteLength) : new AsyncByteStream(source2);
  }
  [Symbol.asyncIterator]() {
    return this;
  }
  next() {
    return __awaiter(this, void 0, void 0, function* () {
      let r2;
      if ((r2 = yield this.readMetadataLength()).done) {
        return ITERATOR_DONE;
      }
      if (r2.value === -1 && (r2 = yield this.readMetadataLength()).done) {
        return ITERATOR_DONE;
      }
      if ((r2 = yield this.readMetadata(r2.value)).done) {
        return ITERATOR_DONE;
      }
      return r2;
    });
  }
  throw(value2) {
    return __awaiter(this, void 0, void 0, function* () {
      return yield this.source.throw(value2);
    });
  }
  return(value2) {
    return __awaiter(this, void 0, void 0, function* () {
      return yield this.source.return(value2);
    });
  }
  readMessage(type) {
    return __awaiter(this, void 0, void 0, function* () {
      let r2;
      if ((r2 = yield this.next()).done) {
        return null;
      }
      if (type != null && r2.value.headerType !== type) {
        throw new Error(invalidMessageType$1(type));
      }
      return r2.value;
    });
  }
  readMessageBody(bodyLength) {
    return __awaiter(this, void 0, void 0, function* () {
      if (bodyLength <= 0) {
        return new Uint8Array(0);
      }
      const buf2 = toUint8Array(yield this.source.read(bodyLength));
      if (buf2.byteLength < bodyLength) {
        throw new Error(invalidMessageBodyLength$1(bodyLength, buf2.byteLength));
      }
      return (
        /* 1. */
        buf2.byteOffset % 8 === 0 && /* 2. */
        buf2.byteOffset + buf2.byteLength <= buf2.buffer.byteLength ? buf2 : buf2.slice()
      );
    });
  }
  readSchema() {
    return __awaiter(this, arguments, void 0, function* (throwIfNull = false) {
      const type = MessageHeader$1.Schema;
      const message2 = yield this.readMessage(type);
      const schema = message2 === null || message2 === void 0 ? void 0 : message2.header();
      if (throwIfNull && !schema) {
        throw new Error(nullMessage(type));
      }
      return schema;
    });
  }
  readMetadataLength() {
    return __awaiter(this, void 0, void 0, function* () {
      const buf2 = yield this.source.read(PADDING);
      const bb = buf2 && new ByteBuffer$2(buf2);
      const len = (bb === null || bb === void 0 ? void 0 : bb.readInt32(0)) || 0;
      return { done: len === 0, value: len };
    });
  }
  readMetadata(metadataLength) {
    return __awaiter(this, void 0, void 0, function* () {
      const buf2 = yield this.source.read(metadataLength);
      if (!buf2) {
        return ITERATOR_DONE;
      }
      if (buf2.byteLength < metadataLength) {
        throw new Error(invalidMessageMetadata$1(metadataLength, buf2.byteLength));
      }
      return { done: false, value: Message2.decode(buf2) };
    });
  }
}
class JSONMessageReader extends MessageReader {
  constructor(source2) {
    super(new Uint8Array(0));
    this._schema = false;
    this._body = [];
    this._batchIndex = 0;
    this._dictionaryIndex = 0;
    this._json = source2 instanceof ArrowJSON ? source2 : new ArrowJSON(source2);
  }
  next() {
    const { _json } = this;
    if (!this._schema) {
      this._schema = true;
      const message2 = Message2.fromJSON(_json.schema, MessageHeader$1.Schema);
      return { done: false, value: message2 };
    }
    if (this._dictionaryIndex < _json.dictionaries.length) {
      const batch2 = _json.dictionaries[this._dictionaryIndex++];
      this._body = batch2["data"]["columns"];
      const message2 = Message2.fromJSON(batch2, MessageHeader$1.DictionaryBatch);
      return { done: false, value: message2 };
    }
    if (this._batchIndex < _json.batches.length) {
      const batch2 = _json.batches[this._batchIndex++];
      this._body = batch2["columns"];
      const message2 = Message2.fromJSON(batch2, MessageHeader$1.RecordBatch);
      return { done: false, value: message2 };
    }
    this._body = [];
    return ITERATOR_DONE;
  }
  readMessageBody(_bodyLength) {
    return flattenDataSources(this._body);
    function flattenDataSources(xs) {
      return (xs || []).reduce((buffers, column2) => [
        ...buffers,
        ...column2["VALIDITY"] && [column2["VALIDITY"]] || [],
        ...column2["TYPE_ID"] && [column2["TYPE_ID"]] || [],
        ...column2["OFFSET"] && [column2["OFFSET"]] || [],
        ...column2["DATA"] && [column2["DATA"]] || [],
        ...flattenDataSources(column2["children"])
      ], []);
    }
  }
  readMessage(type) {
    let r2;
    if ((r2 = this.next()).done) {
      return null;
    }
    if (type != null && r2.value.headerType !== type) {
      throw new Error(invalidMessageType$1(type));
    }
    return r2.value;
  }
  readSchema() {
    const type = MessageHeader$1.Schema;
    const message2 = this.readMessage(type);
    const schema = message2 === null || message2 === void 0 ? void 0 : message2.header();
    if (!message2 || !schema) {
      throw new Error(nullMessage(type));
    }
    return schema;
  }
}
const PADDING = 4;
const MAGIC_STR = "ARROW1";
const MAGIC$1 = new Uint8Array(MAGIC_STR.length);
for (let i2 = 0; i2 < MAGIC_STR.length; i2 += 1) {
  MAGIC$1[i2] = MAGIC_STR.codePointAt(i2);
}
function checkForMagicArrowString(buffer2, index = 0) {
  for (let i2 = -1, n2 = MAGIC$1.length; ++i2 < n2; ) {
    if (MAGIC$1[i2] !== buffer2[index + i2]) {
      return false;
    }
  }
  return true;
}
const magicLength = MAGIC$1.length;
const magicAndPadding = magicLength + PADDING;
const magicX2AndPadding = magicLength * 2 + PADDING;
class Lz4FrameValidator {
  constructor() {
    this.LZ4_FRAME_MAGIC = new Uint8Array([4, 34, 77, 24]);
    this.MIN_HEADER_LENGTH = 7;
  }
  isValidCodecEncode(codec) {
    const testData = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
    const compressed = codec.encode(testData);
    return this._isValidCompressed(compressed);
  }
  _isValidCompressed(buffer2) {
    return this._hasMinimumLength(buffer2) && this._hasValidMagicNumber(buffer2) && this._hasValidVersion(buffer2);
  }
  _hasMinimumLength(buffer2) {
    return buffer2.length >= this.MIN_HEADER_LENGTH;
  }
  _hasValidMagicNumber(buffer2) {
    return this.LZ4_FRAME_MAGIC.every((byte, i2) => buffer2[i2] === byte);
  }
  _hasValidVersion(buffer2) {
    const flg = buffer2[4];
    const versionBits = (flg & 192) >> 6;
    return versionBits === 1;
  }
}
class ZstdValidator {
  constructor() {
    this.ZSTD_MAGIC = new Uint8Array([40, 181, 47, 253]);
    this.MIN_HEADER_LENGTH = 6;
  }
  isValidCodecEncode(codec) {
    const testData = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
    const compressed = codec.encode(testData);
    return this._isValidCompressed(compressed);
  }
  _isValidCompressed(buffer2) {
    return this._hasMinimumLength(buffer2) && this._hasValidMagicNumber(buffer2);
  }
  _hasMinimumLength(buffer2) {
    return buffer2.length >= this.MIN_HEADER_LENGTH;
  }
  _hasValidMagicNumber(buffer2) {
    return this.ZSTD_MAGIC.every((byte, i2) => buffer2[i2] === byte);
  }
}
const compressionValidators = {
  [CompressionType.LZ4_FRAME]: new Lz4FrameValidator(),
  [CompressionType.ZSTD]: new ZstdValidator()
};
class _CompressionRegistry {
  constructor() {
    this.registry = {};
  }
  set(compression, codec) {
    if ((codec === null || codec === void 0 ? void 0 : codec.encode) && typeof codec.encode === "function" && !compressionValidators[compression].isValidCodecEncode(codec)) {
      throw new Error(`Encoder for ${CompressionType[compression]} is not valid.`);
    }
    this.registry[compression] = codec;
  }
  get(compression) {
    var _a2;
    return ((_a2 = this.registry) === null || _a2 === void 0 ? void 0 : _a2[compression]) || null;
  }
}
const compressionRegistry = new _CompressionRegistry();
const LENGTH_NO_COMPRESSED_DATA = -1;
const COMPRESS_LENGTH_PREFIX = 8;
class RecordBatchReader extends ReadableInterop {
  constructor(impl) {
    super();
    this._impl = impl;
  }
  get closed() {
    return this._impl.closed;
  }
  get schema() {
    return this._impl.schema;
  }
  get autoDestroy() {
    return this._impl.autoDestroy;
  }
  get dictionaries() {
    return this._impl.dictionaries;
  }
  get numDictionaries() {
    return this._impl.numDictionaries;
  }
  get numRecordBatches() {
    return this._impl.numRecordBatches;
  }
  get footer() {
    return this._impl.isFile() ? this._impl.footer : null;
  }
  isSync() {
    return this._impl.isSync();
  }
  isAsync() {
    return this._impl.isAsync();
  }
  isFile() {
    return this._impl.isFile();
  }
  isStream() {
    return this._impl.isStream();
  }
  next() {
    return this._impl.next();
  }
  throw(value2) {
    return this._impl.throw(value2);
  }
  return(value2) {
    return this._impl.return(value2);
  }
  cancel() {
    return this._impl.cancel();
  }
  reset(schema) {
    this._impl.reset(schema);
    this._DOMStream = void 0;
    this._nodeStream = void 0;
    return this;
  }
  open(options) {
    const opening = this._impl.open(options);
    return isPromise(opening) ? opening.then(() => this) : this;
  }
  readRecordBatch(index) {
    return this._impl.isFile() ? this._impl.readRecordBatch(index) : null;
  }
  [Symbol.iterator]() {
    return this._impl[Symbol.iterator]();
  }
  [Symbol.asyncIterator]() {
    return this._impl[Symbol.asyncIterator]();
  }
  toDOMStream() {
    return streamAdapters.toDOMStream(this.isSync() ? { [Symbol.iterator]: () => this } : { [Symbol.asyncIterator]: () => this });
  }
  toNodeStream() {
    return streamAdapters.toNodeStream(this.isSync() ? { [Symbol.iterator]: () => this } : { [Symbol.asyncIterator]: () => this }, { objectMode: true });
  }
  /** @nocollapse */
  // @ts-ignore
  static throughNode(options) {
    throw new Error(`"throughNode" not available in this environment`);
  }
  /** @nocollapse */
  static throughDOM(writableStrategy, readableStrategy) {
    throw new Error(`"throughDOM" not available in this environment`);
  }
  /** @nocollapse */
  static from(source2) {
    if (source2 instanceof RecordBatchReader) {
      return source2;
    } else if (isArrowJSON(source2)) {
      return fromArrowJSON(source2);
    } else if (isFileHandle(source2)) {
      return fromFileHandle(source2);
    } else if (isPromise(source2)) {
      return (() => __awaiter(this, void 0, void 0, function* () {
        return yield RecordBatchReader.from(yield source2);
      }))();
    } else if (isFetchResponse(source2) || isReadableDOMStream(source2) || isReadableNodeStream(source2) || isAsyncIterable(source2)) {
      return fromAsyncByteStream(new AsyncByteStream(source2));
    }
    return fromByteStream(new ByteStream(source2));
  }
  /** @nocollapse */
  static readAll(source2) {
    if (source2 instanceof RecordBatchReader) {
      return source2.isSync() ? readAllSync(source2) : readAllAsync(source2);
    } else if (isArrowJSON(source2) || ArrayBuffer.isView(source2) || isIterable$1(source2) || isIteratorResult(source2)) {
      return readAllSync(source2);
    }
    return readAllAsync(source2);
  }
}
class RecordBatchStreamReader extends RecordBatchReader {
  constructor(_impl) {
    super(_impl);
    this._impl = _impl;
  }
  readAll() {
    return [...this];
  }
  [Symbol.iterator]() {
    return this._impl[Symbol.iterator]();
  }
  [Symbol.asyncIterator]() {
    return __asyncGenerator(this, arguments, function* _a2() {
      yield __await(yield* __asyncDelegator(__asyncValues(this[Symbol.iterator]())));
    });
  }
}
class AsyncRecordBatchStreamReader extends RecordBatchReader {
  constructor(_impl) {
    super(_impl);
    this._impl = _impl;
  }
  readAll() {
    return __awaiter(this, void 0, void 0, function* () {
      var _a2, e_1, _b2, _c2;
      const batches = new Array();
      try {
        for (var _d2 = true, _e2 = __asyncValues(this), _f2; _f2 = yield _e2.next(), _a2 = _f2.done, !_a2; _d2 = true) {
          _c2 = _f2.value;
          _d2 = false;
          const batch2 = _c2;
          batches.push(batch2);
        }
      } catch (e_1_1) {
        e_1 = { error: e_1_1 };
      } finally {
        try {
          if (!_d2 && !_a2 && (_b2 = _e2.return)) yield _b2.call(_e2);
        } finally {
          if (e_1) throw e_1.error;
        }
      }
      return batches;
    });
  }
  [Symbol.iterator]() {
    throw new Error(`AsyncRecordBatchStreamReader is not Iterable`);
  }
  [Symbol.asyncIterator]() {
    return this._impl[Symbol.asyncIterator]();
  }
}
class RecordBatchFileReader extends RecordBatchStreamReader {
  constructor(_impl) {
    super(_impl);
    this._impl = _impl;
  }
}
class AsyncRecordBatchFileReader extends AsyncRecordBatchStreamReader {
  constructor(_impl) {
    super(_impl);
    this._impl = _impl;
  }
}
class RecordBatchReaderImpl {
  get numDictionaries() {
    return this._dictionaryIndex;
  }
  get numRecordBatches() {
    return this._recordBatchIndex;
  }
  constructor(dictionaries = /* @__PURE__ */ new Map()) {
    this.closed = false;
    this.autoDestroy = true;
    this._dictionaryIndex = 0;
    this._recordBatchIndex = 0;
    this.dictionaries = dictionaries;
  }
  isSync() {
    return false;
  }
  isAsync() {
    return false;
  }
  isFile() {
    return false;
  }
  isStream() {
    return false;
  }
  reset(schema) {
    this._dictionaryIndex = 0;
    this._recordBatchIndex = 0;
    this.schema = schema;
    this.dictionaries = /* @__PURE__ */ new Map();
    return this;
  }
  _loadRecordBatch(header2, body) {
    let children2;
    if (header2.compression != null) {
      const codec = compressionRegistry.get(header2.compression.type);
      if ((codec === null || codec === void 0 ? void 0 : codec.decode) && typeof codec.decode === "function") {
        const { decommpressedBody, buffers } = this._decompressBuffers(header2, body, codec);
        children2 = this._loadCompressedVectors(header2, decommpressedBody, this.schema.fields);
        header2 = new RecordBatch$1(header2.length, header2.nodes, buffers, null);
      } else {
        throw new Error("Record batch is compressed but codec not found");
      }
    } else {
      children2 = this._loadVectors(header2, body, this.schema.fields);
    }
    const data2 = makeData({ type: new Struct(this.schema.fields), length: header2.length, children: children2 });
    return new RecordBatch3(this.schema, data2);
  }
  _loadDictionaryBatch(header2, body) {
    const { id: id2, isDelta } = header2;
    const { dictionaries, schema } = this;
    const dictionary2 = dictionaries.get(id2);
    const type = schema.dictionaries.get(id2);
    let data2;
    if (header2.data.compression != null) {
      const codec = compressionRegistry.get(header2.data.compression.type);
      if ((codec === null || codec === void 0 ? void 0 : codec.decode) && typeof codec.decode === "function") {
        const { decommpressedBody, buffers } = this._decompressBuffers(header2.data, body, codec);
        data2 = this._loadCompressedVectors(header2.data, decommpressedBody, [type]);
        header2 = new DictionaryBatch$1(new RecordBatch$1(header2.data.length, header2.data.nodes, buffers, null), id2, isDelta);
      } else {
        throw new Error("Dictionary batch is compressed but codec not found");
      }
    } else {
      data2 = this._loadVectors(header2.data, body, [type]);
    }
    return (dictionary2 && isDelta ? dictionary2.concat(new Vector(data2)) : new Vector(data2)).memoize();
  }
  _loadVectors(header2, body, types2) {
    return new VectorLoader(body, header2.nodes, header2.buffers, this.dictionaries, this.schema.metadataVersion).visitMany(types2);
  }
  _loadCompressedVectors(header2, body, types2) {
    return new CompressedVectorLoader(body, header2.nodes, header2.buffers, this.dictionaries, this.schema.metadataVersion).visitMany(types2);
  }
  _decompressBuffers(header2, body, codec) {
    const decompressedBuffers = [];
    const newBufferRegions = [];
    let currentOffset = 0;
    for (const { offset: offset3, length: length2 } of header2.buffers) {
      if (length2 === 0) {
        decompressedBuffers.push(new Uint8Array(0));
        newBufferRegions.push(new BufferRegion(currentOffset, 0));
        continue;
      }
      const byteBuf = new ByteBuffer$2(body.subarray(offset3, offset3 + length2));
      const uncompressedLenth = bigIntToNumber(byteBuf.readInt64(0));
      const bytes = byteBuf.bytes().subarray(COMPRESS_LENGTH_PREFIX);
      const decompressed = uncompressedLenth === LENGTH_NO_COMPRESSED_DATA ? bytes : codec.decode(bytes);
      decompressedBuffers.push(decompressed);
      const padding = (currentOffset + 7 & -8) - currentOffset;
      currentOffset += padding;
      newBufferRegions.push(new BufferRegion(currentOffset, decompressed.length));
      currentOffset += decompressed.length;
    }
    return {
      decommpressedBody: decompressedBuffers,
      buffers: newBufferRegions
    };
  }
}
class RecordBatchStreamReaderImpl extends RecordBatchReaderImpl {
  constructor(source2, dictionaries) {
    super(dictionaries);
    this._reader = !isArrowJSON(source2) ? new MessageReader(this._handle = source2) : new JSONMessageReader(this._handle = source2);
  }
  isSync() {
    return true;
  }
  isStream() {
    return true;
  }
  [Symbol.iterator]() {
    return this;
  }
  cancel() {
    if (!this.closed && (this.closed = true)) {
      this.reset()._reader.return();
      this._reader = null;
      this.dictionaries = null;
    }
  }
  open(options) {
    if (!this.closed) {
      this.autoDestroy = shouldAutoDestroy(this, options);
      if (!(this.schema || (this.schema = this._reader.readSchema()))) {
        this.cancel();
      }
    }
    return this;
  }
  throw(value2) {
    if (!this.closed && this.autoDestroy && (this.closed = true)) {
      return this.reset()._reader.throw(value2);
    }
    return ITERATOR_DONE;
  }
  return(value2) {
    if (!this.closed && this.autoDestroy && (this.closed = true)) {
      return this.reset()._reader.return(value2);
    }
    return ITERATOR_DONE;
  }
  next() {
    if (this.closed) {
      return ITERATOR_DONE;
    }
    let message2;
    const { _reader: reader } = this;
    while (message2 = this._readNextMessageAndValidate()) {
      if (message2.isSchema()) {
        this.reset(message2.header());
      } else if (message2.isRecordBatch()) {
        this._recordBatchIndex++;
        const header2 = message2.header();
        const buffer2 = reader.readMessageBody(message2.bodyLength);
        const recordBatch = this._loadRecordBatch(header2, buffer2);
        return { done: false, value: recordBatch };
      } else if (message2.isDictionaryBatch()) {
        this._dictionaryIndex++;
        const header2 = message2.header();
        const buffer2 = reader.readMessageBody(message2.bodyLength);
        const vector = this._loadDictionaryBatch(header2, buffer2);
        this.dictionaries.set(header2.id, vector);
      }
    }
    if (this.schema && this._recordBatchIndex === 0) {
      this._recordBatchIndex++;
      return { done: false, value: new _InternalEmptyPlaceholderRecordBatch(this.schema) };
    }
    return this.return();
  }
  _readNextMessageAndValidate(type) {
    return this._reader.readMessage(type);
  }
}
class AsyncRecordBatchStreamReaderImpl extends RecordBatchReaderImpl {
  constructor(source2, dictionaries) {
    super(dictionaries);
    this._reader = new AsyncMessageReader(this._handle = source2);
  }
  isAsync() {
    return true;
  }
  isStream() {
    return true;
  }
  [Symbol.asyncIterator]() {
    return this;
  }
  cancel() {
    return __awaiter(this, void 0, void 0, function* () {
      if (!this.closed && (this.closed = true)) {
        yield this.reset()._reader.return();
        this._reader = null;
        this.dictionaries = null;
      }
    });
  }
  open(options) {
    return __awaiter(this, void 0, void 0, function* () {
      if (!this.closed) {
        this.autoDestroy = shouldAutoDestroy(this, options);
        if (!(this.schema || (this.schema = yield this._reader.readSchema()))) {
          yield this.cancel();
        }
      }
      return this;
    });
  }
  throw(value2) {
    return __awaiter(this, void 0, void 0, function* () {
      if (!this.closed && this.autoDestroy && (this.closed = true)) {
        return yield this.reset()._reader.throw(value2);
      }
      return ITERATOR_DONE;
    });
  }
  return(value2) {
    return __awaiter(this, void 0, void 0, function* () {
      if (!this.closed && this.autoDestroy && (this.closed = true)) {
        return yield this.reset()._reader.return(value2);
      }
      return ITERATOR_DONE;
    });
  }
  next() {
    return __awaiter(this, void 0, void 0, function* () {
      if (this.closed) {
        return ITERATOR_DONE;
      }
      let message2;
      const { _reader: reader } = this;
      while (message2 = yield this._readNextMessageAndValidate()) {
        if (message2.isSchema()) {
          yield this.reset(message2.header());
        } else if (message2.isRecordBatch()) {
          this._recordBatchIndex++;
          const header2 = message2.header();
          const buffer2 = yield reader.readMessageBody(message2.bodyLength);
          const recordBatch = this._loadRecordBatch(header2, buffer2);
          return { done: false, value: recordBatch };
        } else if (message2.isDictionaryBatch()) {
          this._dictionaryIndex++;
          const header2 = message2.header();
          const buffer2 = yield reader.readMessageBody(message2.bodyLength);
          const vector = this._loadDictionaryBatch(header2, buffer2);
          this.dictionaries.set(header2.id, vector);
        }
      }
      if (this.schema && this._recordBatchIndex === 0) {
        this._recordBatchIndex++;
        return { done: false, value: new _InternalEmptyPlaceholderRecordBatch(this.schema) };
      }
      return yield this.return();
    });
  }
  _readNextMessageAndValidate(type) {
    return __awaiter(this, void 0, void 0, function* () {
      return yield this._reader.readMessage(type);
    });
  }
}
class RecordBatchFileReaderImpl extends RecordBatchStreamReaderImpl {
  get footer() {
    return this._footer;
  }
  get numDictionaries() {
    return this._footer ? this._footer.numDictionaries : 0;
  }
  get numRecordBatches() {
    return this._footer ? this._footer.numRecordBatches : 0;
  }
  constructor(source2, dictionaries) {
    super(source2 instanceof RandomAccessFile ? source2 : new RandomAccessFile(source2), dictionaries);
  }
  isSync() {
    return true;
  }
  isFile() {
    return true;
  }
  open(options) {
    if (!this.closed && !this._footer) {
      this.schema = (this._footer = this._readFooter()).schema;
      for (const block2 of this._footer.dictionaryBatches()) {
        block2 && this._readDictionaryBatch(this._dictionaryIndex++);
      }
    }
    return super.open(options);
  }
  readRecordBatch(index) {
    var _a2;
    if (this.closed) {
      return null;
    }
    if (!this._footer) {
      this.open();
    }
    const block2 = (_a2 = this._footer) === null || _a2 === void 0 ? void 0 : _a2.getRecordBatch(index);
    if (block2 && this._handle.seek(block2.offset)) {
      const message2 = this._reader.readMessage(MessageHeader$1.RecordBatch);
      if (message2 === null || message2 === void 0 ? void 0 : message2.isRecordBatch()) {
        const header2 = message2.header();
        const buffer2 = this._reader.readMessageBody(message2.bodyLength);
        const recordBatch = this._loadRecordBatch(header2, buffer2);
        return recordBatch;
      }
    }
    return null;
  }
  _readDictionaryBatch(index) {
    var _a2;
    const block2 = (_a2 = this._footer) === null || _a2 === void 0 ? void 0 : _a2.getDictionaryBatch(index);
    if (block2 && this._handle.seek(block2.offset)) {
      const message2 = this._reader.readMessage(MessageHeader$1.DictionaryBatch);
      if (message2 === null || message2 === void 0 ? void 0 : message2.isDictionaryBatch()) {
        const header2 = message2.header();
        const buffer2 = this._reader.readMessageBody(message2.bodyLength);
        const vector = this._loadDictionaryBatch(header2, buffer2);
        this.dictionaries.set(header2.id, vector);
      }
    }
  }
  _readFooter() {
    const { _handle } = this;
    const offset3 = _handle.size - magicAndPadding;
    const length2 = _handle.readInt32(offset3);
    const buffer2 = _handle.readAt(offset3 - length2, length2);
    return Footer_.decode(buffer2);
  }
  _readNextMessageAndValidate(type) {
    var _a2;
    if (!this._footer) {
      this.open();
    }
    if (this._footer && this._recordBatchIndex < this.numRecordBatches) {
      const block2 = (_a2 = this._footer) === null || _a2 === void 0 ? void 0 : _a2.getRecordBatch(this._recordBatchIndex);
      if (block2 && this._handle.seek(block2.offset)) {
        return this._reader.readMessage(type);
      }
    }
    return null;
  }
}
class AsyncRecordBatchFileReaderImpl extends AsyncRecordBatchStreamReaderImpl {
  get footer() {
    return this._footer;
  }
  get numDictionaries() {
    return this._footer ? this._footer.numDictionaries : 0;
  }
  get numRecordBatches() {
    return this._footer ? this._footer.numRecordBatches : 0;
  }
  constructor(source2, ...rest) {
    const byteLength = typeof rest[0] !== "number" ? rest.shift() : void 0;
    const dictionaries = rest[0] instanceof Map ? rest.shift() : void 0;
    super(source2 instanceof AsyncRandomAccessFile ? source2 : new AsyncRandomAccessFile(source2, byteLength), dictionaries);
  }
  isFile() {
    return true;
  }
  isAsync() {
    return true;
  }
  open(options) {
    const _super = Object.create(null, {
      open: { get: () => super.open }
    });
    return __awaiter(this, void 0, void 0, function* () {
      if (!this.closed && !this._footer) {
        this.schema = (this._footer = yield this._readFooter()).schema;
        for (const block2 of this._footer.dictionaryBatches()) {
          block2 && (yield this._readDictionaryBatch(this._dictionaryIndex++));
        }
      }
      return yield _super.open.call(this, options);
    });
  }
  readRecordBatch(index) {
    return __awaiter(this, void 0, void 0, function* () {
      var _a2;
      if (this.closed) {
        return null;
      }
      if (!this._footer) {
        yield this.open();
      }
      const block2 = (_a2 = this._footer) === null || _a2 === void 0 ? void 0 : _a2.getRecordBatch(index);
      if (block2 && (yield this._handle.seek(block2.offset))) {
        const message2 = yield this._reader.readMessage(MessageHeader$1.RecordBatch);
        if (message2 === null || message2 === void 0 ? void 0 : message2.isRecordBatch()) {
          const header2 = message2.header();
          const buffer2 = yield this._reader.readMessageBody(message2.bodyLength);
          const recordBatch = this._loadRecordBatch(header2, buffer2);
          return recordBatch;
        }
      }
      return null;
    });
  }
  _readDictionaryBatch(index) {
    return __awaiter(this, void 0, void 0, function* () {
      var _a2;
      const block2 = (_a2 = this._footer) === null || _a2 === void 0 ? void 0 : _a2.getDictionaryBatch(index);
      if (block2 && (yield this._handle.seek(block2.offset))) {
        const message2 = yield this._reader.readMessage(MessageHeader$1.DictionaryBatch);
        if (message2 === null || message2 === void 0 ? void 0 : message2.isDictionaryBatch()) {
          const header2 = message2.header();
          const buffer2 = yield this._reader.readMessageBody(message2.bodyLength);
          const vector = this._loadDictionaryBatch(header2, buffer2);
          this.dictionaries.set(header2.id, vector);
        }
      }
    });
  }
  _readFooter() {
    return __awaiter(this, void 0, void 0, function* () {
      const { _handle } = this;
      _handle._pending && (yield _handle._pending);
      const offset3 = _handle.size - magicAndPadding;
      const length2 = yield _handle.readInt32(offset3);
      const buffer2 = yield _handle.readAt(offset3 - length2, length2);
      return Footer_.decode(buffer2);
    });
  }
  _readNextMessageAndValidate(type) {
    return __awaiter(this, void 0, void 0, function* () {
      if (!this._footer) {
        yield this.open();
      }
      if (this._footer && this._recordBatchIndex < this.numRecordBatches) {
        const block2 = this._footer.getRecordBatch(this._recordBatchIndex);
        if (block2 && (yield this._handle.seek(block2.offset))) {
          return yield this._reader.readMessage(type);
        }
      }
      return null;
    });
  }
}
class RecordBatchJSONReaderImpl extends RecordBatchStreamReaderImpl {
  constructor(source2, dictionaries) {
    super(source2, dictionaries);
  }
  _loadVectors(header2, body, types2) {
    return new JSONVectorLoader(body, header2.nodes, header2.buffers, this.dictionaries, this.schema.metadataVersion).visitMany(types2);
  }
}
function shouldAutoDestroy(self2, options) {
  return options && typeof options["autoDestroy"] === "boolean" ? options["autoDestroy"] : self2["autoDestroy"];
}
function* readAllSync(source2) {
  const reader = RecordBatchReader.from(source2);
  try {
    if (!reader.open({ autoDestroy: false }).closed) {
      do {
        yield reader;
      } while (!reader.reset().open().closed);
    }
  } finally {
    reader.cancel();
  }
}
function readAllAsync(source2) {
  return __asyncGenerator(this, arguments, function* readAllAsync_1() {
    const reader = yield __await(RecordBatchReader.from(source2));
    try {
      if (!(yield __await(reader.open({ autoDestroy: false }))).closed) {
        do {
          yield yield __await(reader);
        } while (!(yield __await(reader.reset().open())).closed);
      }
    } finally {
      yield __await(reader.cancel());
    }
  });
}
function fromArrowJSON(source2) {
  return new RecordBatchStreamReader(new RecordBatchJSONReaderImpl(source2));
}
function fromByteStream(source2) {
  const bytes = source2.peek(magicLength + 7 & -8);
  return bytes && bytes.byteLength >= 4 ? !checkForMagicArrowString(bytes) ? new RecordBatchStreamReader(new RecordBatchStreamReaderImpl(source2)) : new RecordBatchFileReader(new RecordBatchFileReaderImpl(source2.read())) : new RecordBatchStreamReader(new RecordBatchStreamReaderImpl((function* () {
  })()));
}
function fromAsyncByteStream(source2) {
  return __awaiter(this, void 0, void 0, function* () {
    const bytes = yield source2.peek(magicLength + 7 & -8);
    return bytes && bytes.byteLength >= 4 ? !checkForMagicArrowString(bytes) ? new AsyncRecordBatchStreamReader(new AsyncRecordBatchStreamReaderImpl(source2)) : new RecordBatchFileReader(new RecordBatchFileReaderImpl(yield source2.read())) : new AsyncRecordBatchStreamReader(new AsyncRecordBatchStreamReaderImpl((function() {
      return __asyncGenerator(this, arguments, function* () {
      });
    })()));
  });
}
function fromFileHandle(source2) {
  return __awaiter(this, void 0, void 0, function* () {
    const { size } = yield source2.stat();
    const file = new AsyncRandomAccessFile(source2, size);
    if (size >= magicX2AndPadding && checkForMagicArrowString(yield file.readAt(0, magicLength + 7 & -8))) {
      return new AsyncRecordBatchFileReader(new AsyncRecordBatchFileReaderImpl(file));
    }
    return new AsyncRecordBatchStreamReader(new AsyncRecordBatchStreamReaderImpl(file));
  });
}
class VectorAssembler extends Visitor {
  /** @nocollapse */
  static assemble(...args2) {
    const unwrap2 = (nodes) => nodes.flatMap((node2) => Array.isArray(node2) ? unwrap2(node2) : node2 instanceof RecordBatch3 ? node2.data.children : node2.data);
    const assembler = new VectorAssembler();
    assembler.visitMany(unwrap2(args2));
    return assembler;
  }
  constructor() {
    super();
    this._byteLength = 0;
    this._nodes = [];
    this._buffers = [];
    this._bufferRegions = [];
  }
  visit(data2) {
    if (data2 instanceof Vector) {
      this.visitMany(data2.data);
      return this;
    }
    const { type } = data2;
    if (!DataType.isDictionary(type)) {
      const { length: length2 } = data2;
      if (length2 > 2147483647) {
        throw new RangeError("Cannot write arrays larger than 2^31 - 1 in length");
      }
      if (DataType.isUnion(type)) {
        this.nodes.push(new FieldNode2(length2, 0));
      } else {
        const { nullCount } = data2;
        if (!DataType.isNull(type)) {
          addBuffer.call(this, nullCount <= 0 ? new Uint8Array(0) : truncateBitmap(data2.offset, length2, data2.nullBitmap));
        }
        this.nodes.push(new FieldNode2(length2, nullCount));
      }
    }
    return super.visit(data2);
  }
  visitNull(_null) {
    return this;
  }
  visitDictionary(data2) {
    return this.visit(data2.clone(data2.type.indices));
  }
  get nodes() {
    return this._nodes;
  }
  get buffers() {
    return this._buffers;
  }
  get byteLength() {
    return this._byteLength;
  }
  get bufferRegions() {
    return this._bufferRegions;
  }
}
function addBuffer(values2) {
  const byteLength = values2.byteLength + 7 & -8;
  this.buffers.push(values2);
  this.bufferRegions.push(new BufferRegion(this._byteLength, byteLength));
  this._byteLength += byteLength;
  return this;
}
function assembleUnion(data2) {
  var _a2;
  const { type, length: length2, typeIds, valueOffsets } = data2;
  addBuffer.call(this, typeIds);
  if (type.mode === UnionMode$1.Sparse) {
    return assembleNestedVector.call(this, data2);
  } else if (type.mode === UnionMode$1.Dense) {
    if (data2.offset <= 0) {
      addBuffer.call(this, valueOffsets);
      return assembleNestedVector.call(this, data2);
    } else {
      const shiftedOffsets = new Int32Array(length2);
      const childOffsets = /* @__PURE__ */ Object.create(null);
      const childLengths = /* @__PURE__ */ Object.create(null);
      for (let typeId, shift, index = -1; ++index < length2; ) {
        if ((typeId = typeIds[index]) === void 0) {
          continue;
        }
        if ((shift = childOffsets[typeId]) === void 0) {
          shift = childOffsets[typeId] = valueOffsets[index];
        }
        shiftedOffsets[index] = valueOffsets[index] - shift;
        childLengths[typeId] = ((_a2 = childLengths[typeId]) !== null && _a2 !== void 0 ? _a2 : 0) + 1;
      }
      addBuffer.call(this, shiftedOffsets);
      this.visitMany(data2.children.map((child, childIndex) => {
        const typeId = type.typeIds[childIndex];
        const childOffset = childOffsets[typeId];
        const childLength = childLengths[typeId];
        return child.slice(childOffset, Math.min(length2, childLength));
      }));
    }
  }
  return this;
}
function assembleBoolVector(data2) {
  let values2;
  if (data2.nullCount >= data2.length) {
    return addBuffer.call(this, new Uint8Array(0));
  } else if ((values2 = data2.values) instanceof Uint8Array) {
    return addBuffer.call(this, truncateBitmap(data2.offset, data2.length, values2));
  }
  return addBuffer.call(this, packBools(data2.values));
}
function assembleFlatVector(data2) {
  return addBuffer.call(this, data2.values.subarray(0, data2.length * data2.stride));
}
function assembleFlatListVector(data2) {
  const { length: length2, values: values2, valueOffsets } = data2;
  const begin = bigIntToNumber(valueOffsets[0]);
  const end2 = bigIntToNumber(valueOffsets[length2]);
  const byteLength = Math.min(end2 - begin, values2.byteLength - begin);
  addBuffer.call(this, rebaseValueOffsets(-begin, length2 + 1, valueOffsets));
  addBuffer.call(this, values2.subarray(begin, begin + byteLength));
  return this;
}
function assembleListVector(data2) {
  const { length: length2, valueOffsets } = data2;
  if (valueOffsets) {
    const { [0]: begin, [length2]: end2 } = valueOffsets;
    addBuffer.call(this, rebaseValueOffsets(-begin, length2 + 1, valueOffsets));
    return this.visit(data2.children[0].slice(begin, end2 - begin));
  }
  return this.visit(data2.children[0]);
}
function assembleNestedVector(data2) {
  return this.visitMany(data2.type.children.map((_, i2) => data2.children[i2]).filter(Boolean))[0];
}
VectorAssembler.prototype.visitBool = assembleBoolVector;
VectorAssembler.prototype.visitInt = assembleFlatVector;
VectorAssembler.prototype.visitFloat = assembleFlatVector;
VectorAssembler.prototype.visitUtf8 = assembleFlatListVector;
VectorAssembler.prototype.visitLargeUtf8 = assembleFlatListVector;
VectorAssembler.prototype.visitBinary = assembleFlatListVector;
VectorAssembler.prototype.visitLargeBinary = assembleFlatListVector;
VectorAssembler.prototype.visitFixedSizeBinary = assembleFlatVector;
VectorAssembler.prototype.visitDate = assembleFlatVector;
VectorAssembler.prototype.visitTimestamp = assembleFlatVector;
VectorAssembler.prototype.visitTime = assembleFlatVector;
VectorAssembler.prototype.visitDecimal = assembleFlatVector;
VectorAssembler.prototype.visitList = assembleListVector;
VectorAssembler.prototype.visitStruct = assembleNestedVector;
VectorAssembler.prototype.visitUnion = assembleUnion;
VectorAssembler.prototype.visitInterval = assembleFlatVector;
VectorAssembler.prototype.visitDuration = assembleFlatVector;
VectorAssembler.prototype.visitFixedSizeList = assembleListVector;
VectorAssembler.prototype.visitMap = assembleListVector;
class RecordBatchWriter extends ReadableInterop {
  /** @nocollapse */
  // @ts-ignore
  static throughNode(options) {
    throw new Error(`"throughNode" not available in this environment`);
  }
  /** @nocollapse */
  static throughDOM(writableStrategy, readableStrategy) {
    throw new Error(`"throughDOM" not available in this environment`);
  }
  constructor(options) {
    super();
    this._position = 0;
    this._started = false;
    this._compression = null;
    this._sink = new AsyncByteQueue();
    this._schema = null;
    this._dictionaryBlocks = [];
    this._recordBatchBlocks = [];
    this._seenDictionaries = /* @__PURE__ */ new Map();
    this._dictionaryDeltaOffsets = /* @__PURE__ */ new Map();
    isObject$2(options) || (options = { autoDestroy: true, writeLegacyIpcFormat: false, compressionType: null });
    this._autoDestroy = typeof options.autoDestroy === "boolean" ? options.autoDestroy : true;
    this._writeLegacyIpcFormat = typeof options.writeLegacyIpcFormat === "boolean" ? options.writeLegacyIpcFormat : false;
    if (options.compressionType != null) {
      if (this._writeLegacyIpcFormat) {
        throw new Error("Legacy IPC format does not support columnar compression. Use modern IPC format (writeLegacyIpcFormat=false).");
      }
      if (Object.values(CompressionType).includes(options.compressionType)) {
        this._compression = new BodyCompression2(options.compressionType);
      } else {
        const validCompressionTypes = Object.values(CompressionType).filter((v) => typeof v === "string");
        throw new Error(`Unsupported compressionType: ${options.compressionType} Available types: ${validCompressionTypes.join(", ")}`);
      }
    } else {
      this._compression = null;
    }
  }
  toString(sync = false) {
    return this._sink.toString(sync);
  }
  toUint8Array(sync = false) {
    return this._sink.toUint8Array(sync);
  }
  writeAll(input2) {
    if (isPromise(input2)) {
      return input2.then((x) => this.writeAll(x));
    } else if (isAsyncIterable(input2)) {
      return writeAllAsync(this, input2);
    }
    return writeAll(this, input2);
  }
  get closed() {
    return this._sink.closed;
  }
  [Symbol.asyncIterator]() {
    return this._sink[Symbol.asyncIterator]();
  }
  toDOMStream(options) {
    return this._sink.toDOMStream(options);
  }
  toNodeStream(options) {
    return this._sink.toNodeStream(options);
  }
  close() {
    return this.reset()._sink.close();
  }
  abort(reason) {
    return this.reset()._sink.abort(reason);
  }
  finish() {
    this._autoDestroy ? this.close() : this.reset(this._sink, this._schema);
    return this;
  }
  reset(sink = this._sink, schema = null) {
    if (sink === this._sink || sink instanceof AsyncByteQueue) {
      this._sink = sink;
    } else {
      this._sink = new AsyncByteQueue();
      if (sink && isWritableDOMStream(sink)) {
        this.toDOMStream({ type: "bytes" }).pipeTo(sink);
      } else if (sink && isWritableNodeStream(sink)) {
        this.toNodeStream({ objectMode: false }).pipe(sink);
      }
    }
    if (this._started && this._schema) {
      this._writeFooter(this._schema);
    }
    this._started = false;
    this._dictionaryBlocks = [];
    this._recordBatchBlocks = [];
    this._seenDictionaries = /* @__PURE__ */ new Map();
    this._dictionaryDeltaOffsets = /* @__PURE__ */ new Map();
    if (!schema || !compareSchemas(schema, this._schema)) {
      if (schema == null) {
        this._position = 0;
        this._schema = null;
      } else {
        this._started = true;
        this._schema = schema;
        this._writeSchema(schema);
      }
    }
    return this;
  }
  write(payload) {
    let schema = null;
    if (!this._sink) {
      throw new Error(`RecordBatchWriter is closed`);
    } else if (payload == null) {
      return this.finish() && void 0;
    } else if (payload instanceof Table$2 && !(schema = payload.schema)) {
      return this.finish() && void 0;
    } else if (payload instanceof RecordBatch3 && !(schema = payload.schema)) {
      return this.finish() && void 0;
    }
    if (schema && !compareSchemas(schema, this._schema)) {
      if (this._started && this._autoDestroy) {
        return this.close();
      }
      this.reset(this._sink, schema);
    }
    if (payload instanceof RecordBatch3) {
      if (!(payload instanceof _InternalEmptyPlaceholderRecordBatch)) {
        this._writeRecordBatch(payload);
      }
    } else if (payload instanceof Table$2) {
      this.writeAll(payload.batches);
    } else if (isIterable$1(payload)) {
      this.writeAll(payload);
    }
  }
  _writeMessage(message2, alignment = 8) {
    const a2 = alignment - 1;
    const buffer2 = Message2.encode(message2);
    const flatbufferSize = buffer2.byteLength;
    const prefixSize = !this._writeLegacyIpcFormat ? 8 : 4;
    const alignedSize = flatbufferSize + prefixSize + a2 & ~a2;
    const nPaddingBytes = alignedSize - flatbufferSize - prefixSize;
    if (message2.headerType === MessageHeader$1.RecordBatch) {
      this._recordBatchBlocks.push(new FileBlock(alignedSize, message2.bodyLength, this._position));
    } else if (message2.headerType === MessageHeader$1.DictionaryBatch) {
      this._dictionaryBlocks.push(new FileBlock(alignedSize, message2.bodyLength, this._position));
    }
    if (!this._writeLegacyIpcFormat) {
      this._write(Int32Array.of(-1));
    }
    this._write(Int32Array.of(alignedSize - prefixSize));
    if (flatbufferSize > 0) {
      this._write(buffer2);
    }
    return this._writePadding(nPaddingBytes);
  }
  _write(chunk) {
    if (this._started) {
      const buffer2 = toUint8Array(chunk);
      if (buffer2 && buffer2.byteLength > 0) {
        this._sink.write(buffer2);
        this._position += buffer2.byteLength;
      }
    }
    return this;
  }
  _writeSchema(schema) {
    return this._writeMessage(Message2.from(schema));
  }
  // @ts-ignore
  _writeFooter(schema) {
    return this._writeLegacyIpcFormat ? this._write(Int32Array.of(0)) : this._write(Int32Array.of(-1, 0));
  }
  _writeMagic() {
    return this._write(MAGIC$1);
  }
  _writePadding(nBytes) {
    return nBytes > 0 ? this._write(new Uint8Array(nBytes)) : this;
  }
  _writeRecordBatch(batch2) {
    const { byteLength, nodes, bufferRegions, buffers } = this._assembleRecordBatch(batch2);
    const recordBatch = new RecordBatch$1(batch2.numRows, nodes, bufferRegions, this._compression);
    const message2 = Message2.from(recordBatch, byteLength);
    return this._writeDictionaries(batch2)._writeMessage(message2)._writeBodyBuffers(buffers);
  }
  _assembleRecordBatch(batch2) {
    let { byteLength, nodes, bufferRegions, buffers } = VectorAssembler.assemble(batch2);
    if (this._compression != null) {
      ({ byteLength, bufferRegions, buffers } = this._compressBodyBuffers(buffers));
    }
    return { byteLength, nodes, bufferRegions, buffers };
  }
  _compressBodyBuffers(buffers) {
    const codec = compressionRegistry.get(this._compression.type);
    if (!(codec === null || codec === void 0 ? void 0 : codec.encode) || typeof codec.encode !== "function") {
      throw new Error(`Codec for compression type "${CompressionType[this._compression.type]}" has invalid encode method`);
    }
    let currentOffset = 0;
    const compressedBuffers = [];
    const bufferRegions = [];
    for (const buffer2 of buffers) {
      const byteBuf = toUint8Array(buffer2);
      if (byteBuf.length === 0) {
        compressedBuffers.push(new Uint8Array(0), new Uint8Array(0));
        bufferRegions.push(new BufferRegion(currentOffset, 0));
        continue;
      }
      const compressed = codec.encode(byteBuf);
      const isCompressionEffective = compressed.length < byteBuf.length;
      const finalBuffer = isCompressionEffective ? compressed : byteBuf;
      const byteLength = isCompressionEffective ? finalBuffer.length : LENGTH_NO_COMPRESSED_DATA;
      const lengthPrefix = new ByteBuffer$2(new Uint8Array(COMPRESS_LENGTH_PREFIX));
      lengthPrefix.writeInt64(0, BigInt(byteLength));
      compressedBuffers.push(lengthPrefix.bytes(), new Uint8Array(finalBuffer));
      const padding = (currentOffset + 7 & -8) - currentOffset;
      currentOffset += padding;
      const fullBodyLength = COMPRESS_LENGTH_PREFIX + finalBuffer.length;
      bufferRegions.push(new BufferRegion(currentOffset, fullBodyLength));
      currentOffset += fullBodyLength;
    }
    const finalPadding = (currentOffset + 7 & -8) - currentOffset;
    currentOffset += finalPadding;
    return { byteLength: currentOffset, bufferRegions, buffers: compressedBuffers };
  }
  _writeDictionaryBatch(dictionary2, id2, isDelta = false) {
    const { byteLength, nodes, bufferRegions, buffers } = this._assembleRecordBatch(new Vector([dictionary2]));
    const recordBatch = new RecordBatch$1(dictionary2.length, nodes, bufferRegions, this._compression);
    const dictionaryBatch = new DictionaryBatch$1(recordBatch, id2, isDelta);
    const message2 = Message2.from(dictionaryBatch, byteLength);
    return this._writeMessage(message2)._writeBodyBuffers(buffers);
  }
  _writeBodyBuffers(buffers) {
    const bufGroupSize = this._compression != null ? 2 : 1;
    const bufs = new Array(bufGroupSize);
    for (let i2 = 0; i2 < buffers.length; i2 += bufGroupSize) {
      let size = 0;
      for (let j2 = -1; ++j2 < bufGroupSize; ) {
        bufs[j2] = buffers[i2 + j2];
        size += bufs[j2].byteLength;
      }
      if (size === 0) {
        continue;
      }
      for (const buf2 of bufs)
        this._write(buf2);
      const padding = (size + 7 & -8) - size;
      if (padding > 0) {
        this._writePadding(padding);
      }
    }
    return this;
  }
  _writeDictionaries(batch2) {
    var _a2, _b2;
    for (const [id2, dictionary2] of batch2.dictionaries) {
      const chunks = (_a2 = dictionary2 === null || dictionary2 === void 0 ? void 0 : dictionary2.data) !== null && _a2 !== void 0 ? _a2 : [];
      const prevDictionary = this._seenDictionaries.get(id2);
      const offset3 = (_b2 = this._dictionaryDeltaOffsets.get(id2)) !== null && _b2 !== void 0 ? _b2 : 0;
      if (!prevDictionary || prevDictionary.data[0] !== chunks[0]) {
        for (const [index, chunk] of chunks.entries())
          this._writeDictionaryBatch(chunk, id2, index > 0);
      } else if (offset3 < chunks.length) {
        for (const chunk of chunks.slice(offset3))
          this._writeDictionaryBatch(chunk, id2, true);
      }
      this._seenDictionaries.set(id2, dictionary2);
      this._dictionaryDeltaOffsets.set(id2, chunks.length);
    }
    return this;
  }
}
class RecordBatchStreamWriter extends RecordBatchWriter {
  /** @nocollapse */
  static writeAll(input2, options) {
    const writer = new RecordBatchStreamWriter(options);
    if (isPromise(input2)) {
      return input2.then((x) => writer.writeAll(x));
    } else if (isAsyncIterable(input2)) {
      return writeAllAsync(writer, input2);
    }
    return writeAll(writer, input2);
  }
}
class RecordBatchFileWriter extends RecordBatchWriter {
  /** @nocollapse */
  static writeAll(input2, options) {
    const writer = new RecordBatchFileWriter(options);
    if (isPromise(input2)) {
      return input2.then((x) => writer.writeAll(x));
    } else if (isAsyncIterable(input2)) {
      return writeAllAsync(writer, input2);
    }
    return writeAll(writer, input2);
  }
  constructor(options) {
    super(options);
    this._autoDestroy = true;
    this._writeLegacyIpcFormat = false;
  }
  // @ts-ignore
  _writeSchema(schema) {
    return this._writeMagic()._writePadding(2);
  }
  _writeDictionaryBatch(dictionary2, id2, isDelta = false) {
    if (!isDelta && this._seenDictionaries.has(id2)) {
      throw new Error("The Arrow File format does not support replacement dictionaries. ");
    }
    return super._writeDictionaryBatch(dictionary2, id2, isDelta);
  }
  _writeFooter(schema) {
    const buffer2 = Footer_.encode(new Footer_(schema, MetadataVersion.V5, this._recordBatchBlocks, this._dictionaryBlocks));
    return super._writeFooter(schema)._write(buffer2)._write(Int32Array.of(buffer2.byteLength))._writeMagic();
  }
}
function writeAll(writer, input2) {
  let chunks = input2;
  if (input2 instanceof Table$2) {
    chunks = input2.batches;
    writer.reset(void 0, input2.schema);
  }
  for (const batch2 of chunks) {
    writer.write(batch2);
  }
  return writer.finish();
}
function writeAllAsync(writer, batches) {
  return __awaiter(this, void 0, void 0, function* () {
    var _a2, batches_1, batches_1_1;
    var _b2, e_1, _c2, _d2;
    try {
      for (_a2 = true, batches_1 = __asyncValues(batches); batches_1_1 = yield batches_1.next(), _b2 = batches_1_1.done, !_b2; _a2 = true) {
        _d2 = batches_1_1.value;
        _a2 = false;
        const batch2 = _d2;
        writer.write(batch2);
      }
    } catch (e_1_1) {
      e_1 = { error: e_1_1 };
    } finally {
      try {
        if (!_a2 && !_b2 && (_c2 = batches_1.return)) yield _c2.call(batches_1);
      } finally {
        if (e_1) throw e_1.error;
      }
    }
    return writer.finish();
  });
}
function tableFromIPC$1(input2) {
  const reader = RecordBatchReader.from(input2);
  if (isPromise(reader)) {
    return reader.then((reader2) => tableFromIPC$1(reader2));
  }
  if (reader.isAsync()) {
    return reader.readAll().then((xs) => new Table$2(xs));
  }
  return new Table$2(reader.readAll());
}
function tableToIPC$1(table2, type = "stream", compressionType = null) {
  const writerOptions = { compressionType };
  return (type === "stream" ? RecordBatchStreamWriter : RecordBatchFileWriter).writeAll(table2, writerOptions).toUint8Array(true);
}
const ONE = 2147483648;
const ALL = 4294967295;
class BitSet {
  /**
   * Instantiate a new BitSet instance.
   * @param {number} size The number of bits.
   */
  constructor(size) {
    this._size = size;
    this._bits = new Uint32Array(Math.ceil(size / 32));
  }
  /**
   * The number of bits.
   * @return {number}
   */
  get length() {
    return this._size;
  }
  /**
   * The number of bits set to one.
   * https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan
   * @return {number}
   */
  count() {
    const n2 = this._bits.length;
    let count2 = 0;
    for (let i2 = 0; i2 < n2; ++i2) {
      for (let b = this._bits[i2]; b; ++count2) {
        b &= b - 1;
      }
    }
    return count2;
  }
  /**
   * Get the bit at a given index.
   * @param {number} i The bit index.
   */
  get(i2) {
    return this._bits[i2 >> 5] & ONE >>> i2;
  }
  /**
   * Set the bit at a given index to one.
   * @param {number} i The bit index.
   */
  set(i2) {
    this._bits[i2 >> 5] |= ONE >>> i2;
  }
  /**
   * Clear the bit at a given index to zero.
   * @param {number} i The bit index.
   */
  clear(i2) {
    this._bits[i2 >> 5] &= ~(ONE >>> i2);
  }
  /**
   * Scan the bits, invoking a callback function with the index of
   * each non-zero bit.
   * @param {(i: number) => void} fn A callback function.
   */
  scan(fn3) {
    for (let i2 = this.next(0); i2 >= 0; i2 = this.next(i2 + 1)) {
      fn3(i2);
    }
  }
  /**
   * Get the next non-zero bit starting from a given index.
   * @param {number} i The bit index.
   */
  next(i2) {
    const bits = this._bits;
    const n2 = bits.length;
    let index = i2 >> 5;
    let curr = bits[index] & ALL >>> i2;
    for (; index < n2; curr = bits[++index]) {
      if (curr !== 0) {
        return (index << 5) + Math.clz32(curr);
      }
    }
    return -1;
  }
  /**
   * Return the index of the nth non-zero bit.
   * @param {number} n The number of non-zero bits to advance.
   * @return {number} The index of the nth non-zero bit.
   */
  nth(n2) {
    let i2 = this.next(0);
    while (n2-- && i2 >= 0) i2 = this.next(i2 + 1);
    return i2;
  }
  /**
   * Negate all bits in this bitset.
   * Modifies this BitSet in place.
   * @return {this}
   */
  not() {
    const bits = this._bits;
    const n2 = bits.length;
    for (let i2 = 0; i2 < n2; ++i2) {
      bits[i2] = ~bits[i2];
    }
    const tail = this._size % 32;
    if (tail) {
      bits[n2 - 1] &= ONE >> tail - 1;
    }
    return this;
  }
  /**
   * Compute the logical AND of this BitSet and another.
   * @param {BitSet} bitset The BitSet to combine with.
   * @return {BitSet} This BitSet updated with the logical AND.
   */
  and(bitset) {
    if (bitset) {
      const a2 = this._bits;
      const b = bitset._bits;
      const n2 = a2.length;
      for (let i2 = 0; i2 < n2; ++i2) {
        a2[i2] &= b[i2];
      }
    }
    return this;
  }
  /**
   * Compute the logical OR of this BitSet and another.
   * @param {BitSet} bitset The BitSet to combine with.
   * @return {BitSet} This BitSet updated with the logical OR.
   */
  or(bitset) {
    if (bitset) {
      const a2 = this._bits;
      const b = bitset._bits;
      const n2 = a2.length;
      for (let i2 = 0; i2 < n2; ++i2) {
        a2[i2] |= b[i2];
      }
    }
    return this;
  }
}
function bin(value2, min2, max2, step, offset3) {
  return value2 == null ? null : value2 < min2 ? -Infinity : value2 > max2 ? Infinity : (value2 = Math.max(min2, Math.min(value2, max2)), min2 + step * Math.floor(1e-14 + (value2 - min2) / step + (offset3 || 0)));
}
function isDate$1(value2) {
  return value2 instanceof Date;
}
function isRegExp$1(value2) {
  return value2 instanceof RegExp;
}
function isObject$1(value2) {
  return value2 === Object(value2);
}
function equal(a2, b) {
  return a2 == null || b == null || a2 !== a2 || b !== b ? false : a2 === b ? true : isDate$1(a2) || isDate$1(b) ? +a2 === +b : isRegExp$1(a2) && isRegExp$1(b) ? a2 + "" === b + "" : isObject$1(a2) && isObject$1(b) ? deepEqual(a2, b) : false;
}
function deepEqual(a2, b) {
  if (Object.getPrototypeOf(a2) !== Object.getPrototypeOf(b)) {
    return false;
  }
  if (a2.length || b.length) {
    return arrayEqual(a2, b);
  }
  const keysA = Object.keys(a2);
  const keysB = Object.keys(b);
  if (keysA.length !== keysB.length) {
    return false;
  }
  keysA.sort();
  keysB.sort();
  if (!arrayEqual(keysA, keysB, (a3, b2) => a3 === b2)) {
    return false;
  }
  const n2 = keysA.length;
  for (let i2 = 0; i2 < n2; ++i2) {
    const k = keysA[i2];
    if (!equal(a2[k], b[k])) {
      return false;
    }
  }
  return true;
}
function arrayEqual(a2, b, test2 = equal) {
  const n2 = a2.length;
  if (n2 !== b.length) return false;
  for (let i2 = 0; i2 < n2; ++i2) {
    if (!test2(a2[i2], b[i2])) {
      return false;
    }
  }
  return true;
}
function recode(value2, map2, fallback) {
  if (map2 instanceof Map) {
    if (map2.has(value2)) return map2.get(value2);
  } else {
    const key2 = `${value2}`;
    if (Object.hasOwn(map2, key2)) return map2[key2];
  }
  return fallback !== void 0 ? fallback : value2;
}
function sequence(start2, stop, step) {
  let n2 = arguments.length;
  start2 = +start2;
  stop = +stop;
  step = n2 < 2 ? (stop = start2, start2 = 0, 1) : n2 < 3 ? 1 : +step;
  n2 = Math.max(0, Math.ceil((stop - start2) / step)) | 0;
  const seq = new Array(n2);
  for (let i2 = 0; i2 < n2; ++i2) {
    seq[i2] = start2 + i2 * step;
  }
  return seq;
}
const NULL = void 0;
function isArray$2(value2) {
  return Array.isArray(value2);
}
const TypedArray$1 = Object.getPrototypeOf(Int8Array);
function isTypedArray$1(value2) {
  return value2 instanceof TypedArray$1;
}
function isArrayType(value2) {
  return isArray$2(value2) || isTypedArray$1(value2);
}
function isString$2(value2) {
  return typeof value2 === "string";
}
function isValid(value2) {
  return value2 != null && value2 === value2;
}
const isSeq = (seq) => isArrayType(seq) || isString$2(seq);
function compact(array2) {
  return isArrayType(array2) ? array2.filter((v) => isValid(v)) : array2;
}
function concat$2(...values2) {
  return [].concat(...values2);
}
function includes(sequence2, value2, index) {
  return isSeq(sequence2) ? sequence2.includes(value2, index) : false;
}
function indexof(sequence2, value2) {
  return isSeq(sequence2) ? sequence2.indexOf(value2) : -1;
}
function join$2(array2, delim) {
  return isArrayType(array2) ? array2.join(delim) : NULL;
}
function lastindexof(sequence2, value2) {
  return isSeq(sequence2) ? sequence2.lastIndexOf(value2) : -1;
}
function length(sequence2) {
  return isSeq(sequence2) ? sequence2.length : 0;
}
function pluck(array2, property) {
  return isArrayType(array2) ? array2.map((v) => isValid(v) ? v[property] : NULL) : NULL;
}
function reverse(sequence2) {
  return isArrayType(sequence2) ? sequence2.slice().reverse() : isString$2(sequence2) ? sequence2.split("").reverse().join("") : NULL;
}
function slice$2(sequence2, start2, end2) {
  return isSeq(sequence2) ? sequence2.slice(start2, end2) : NULL;
}
const array$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  compact,
  concat: concat$2,
  includes,
  indexof,
  join: join$2,
  lastindexof,
  length,
  pluck,
  reverse,
  slice: slice$2
}, Symbol.toStringTag, { value: "Module" }));
function pad(value2, width, char = "0") {
  const s = value2 + "";
  const len = s.length;
  return len < width ? Array(width - len + 1).join(char) + s : s;
}
const pad2 = (v) => (v < 10 ? "0" : "") + v;
const formatYear = (year2) => year2 < 0 ? "-" + pad(-year2, 6) : year2 > 9999 ? "+" + pad(year2, 6) : pad(year2, 4);
function formatISO(year2, month2, date2, hours2, min2, sec, ms, utc, short) {
  const suffix = utc ? "Z" : "";
  return formatYear(year2) + "-" + pad2(month2 + 1) + "-" + pad2(date2) + (!short || ms ? "T" + pad2(hours2) + ":" + pad2(min2) + ":" + pad2(sec) + "." + pad(ms, 3) + suffix : sec ? "T" + pad2(hours2) + ":" + pad2(min2) + ":" + pad2(sec) + suffix : min2 || hours2 || !utc ? "T" + pad2(hours2) + ":" + pad2(min2) + suffix : "");
}
function formatDate(d, short) {
  return isNaN(d) ? "Invalid Date" : formatISO(
    d.getFullYear(),
    d.getMonth(),
    d.getDate(),
    d.getHours(),
    d.getMinutes(),
    d.getSeconds(),
    d.getMilliseconds(),
    false,
    short
  );
}
function formatUTCDate(d, short) {
  return isNaN(d) ? "Invalid Date" : formatISO(
    d.getUTCFullYear(),
    d.getUTCMonth(),
    d.getUTCDate(),
    d.getUTCHours(),
    d.getUTCMinutes(),
    d.getUTCSeconds(),
    d.getUTCMilliseconds(),
    true,
    short
  );
}
const iso_re = /^([-+]\d{2})?\d{4}(-\d{2}(-\d{2})?)?(T\d{2}:\d{2}(:\d{2}(\.\d{3})?)?(Z|[-+]\d{2}:\d{2})?)?$/;
function isISODateString(value2) {
  return value2.match(iso_re) && !isNaN(Date.parse(value2));
}
function parseISODate(value2, parse5 = Date.parse) {
  return isISODateString(value2) ? parse5(value2) : value2;
}
const msMinute = 6e4;
const msDay = 864e5;
const msWeek = 6048e5;
const t0 = /* @__PURE__ */ new Date();
const t1 = /* @__PURE__ */ new Date();
const t$1 = (d) => (t0.setTime(typeof d === "string" ? parseISODate(d) : d), t0);
function format_date(date2, shorten) {
  return formatDate(t$1(date2), !shorten);
}
function format_utcdate(date2, shorten) {
  return formatUTCDate(t$1(date2), !shorten);
}
function now() {
  return Date.now();
}
function timestamp$1(date2) {
  return +t$1(date2);
}
function datetime(year2, month2, date2, hours2, minutes2, seconds2, milliseconds2) {
  return !arguments.length ? new Date(Date.now()) : new Date(
    year2,
    month2 || 0,
    date2 == null ? 1 : date2,
    hours2 || 0,
    minutes2 || 0,
    seconds2 || 0,
    milliseconds2 || 0
  );
}
function year(date2) {
  return t$1(date2).getFullYear();
}
function quarter(date2) {
  return Math.floor(t$1(date2).getMonth() / 3);
}
function month(date2) {
  return t$1(date2).getMonth();
}
function week(date2, firstday) {
  const i2 = firstday || 0;
  t1.setTime(+date2);
  t1.setDate(t1.getDate() - (t1.getDay() + 7 - i2) % 7);
  t1.setHours(0, 0, 0, 0);
  t0.setTime(+date2);
  t0.setMonth(0);
  t0.setDate(1);
  t0.setDate(1 - (t0.getDay() + 7 - i2) % 7);
  t0.setHours(0, 0, 0, 0);
  const tz = (t1.getTimezoneOffset() - t0.getTimezoneOffset()) * msMinute;
  return Math.floor((1 + (+t1 - +t0) - tz) / msWeek);
}
function date$1(date2) {
  return t$1(date2).getDate();
}
function dayofyear(date2) {
  t1.setTime(+date2);
  t1.setHours(0, 0, 0, 0);
  t0.setTime(+t1);
  t0.setMonth(0);
  t0.setDate(1);
  const tz = (t1.getTimezoneOffset() - t0.getTimezoneOffset()) * msMinute;
  return Math.floor(1 + (+t1 - +t0 - tz) / msDay);
}
function dayofweek(date2) {
  return t$1(date2).getDay();
}
function hours(date2) {
  return t$1(date2).getHours();
}
function minutes(date2) {
  return t$1(date2).getMinutes();
}
function seconds(date2) {
  return t$1(date2).getSeconds();
}
function milliseconds(date2) {
  return t$1(date2).getMilliseconds();
}
function utcdatetime(year2, month2, date2, hours2, minutes2, seconds2, milliseconds2) {
  return !arguments.length ? new Date(Date.now()) : new Date(Date.UTC(
    year2,
    month2 || 0,
    date2 == null ? 1 : date2,
    hours2 || 0,
    minutes2 || 0,
    seconds2 || 0,
    milliseconds2 || 0
  ));
}
function utcyear(date2) {
  return t$1(date2).getUTCFullYear();
}
function utcquarter(date2) {
  return Math.floor(t$1(date2).getUTCMonth() / 3);
}
function utcmonth(date2) {
  return t$1(date2).getUTCMonth();
}
function utcweek(date2, firstday) {
  const i2 = firstday || 0;
  t1.setTime(+date2);
  t1.setUTCDate(t1.getUTCDate() - (t1.getUTCDay() + 7 - i2) % 7);
  t1.setUTCHours(0, 0, 0, 0);
  t0.setTime(+date2);
  t0.setUTCMonth(0);
  t0.setUTCDate(1);
  t0.setUTCDate(1 - (t0.getUTCDay() + 7 - i2) % 7);
  t0.setUTCHours(0, 0, 0, 0);
  return Math.floor((1 + (+t1 - +t0)) / msWeek);
}
function utcdate(date2) {
  return t$1(date2).getUTCDate();
}
function utcdayofyear(date2) {
  t1.setTime(+date2);
  t1.setUTCHours(0, 0, 0, 0);
  const t02 = Date.UTC(t1.getUTCFullYear(), 0, 1);
  return Math.floor(1 + (+t1 - t02) / msDay);
}
function utcdayofweek(date2) {
  return t$1(date2).getUTCDay();
}
function utchours(date2) {
  return t$1(date2).getUTCHours();
}
function utcminutes(date2) {
  return t$1(date2).getUTCMinutes();
}
function utcseconds(date2) {
  return t$1(date2).getUTCSeconds();
}
function utcmilliseconds(date2) {
  return t$1(date2).getUTCMilliseconds();
}
const date$2 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  date: date$1,
  datetime,
  dayofweek,
  dayofyear,
  format_date,
  format_utcdate,
  hours,
  milliseconds,
  minutes,
  month,
  now,
  quarter,
  seconds,
  timestamp: timestamp$1,
  utcdate,
  utcdatetime,
  utcdayofweek,
  utcdayofyear,
  utchours,
  utcmilliseconds,
  utcminutes,
  utcmonth,
  utcquarter,
  utcseconds,
  utcweek,
  utcyear,
  week,
  year
}, Symbol.toStringTag, { value: "Module" }));
function parse_json(value2) {
  return JSON.parse(value2);
}
function to_json(value2) {
  return JSON.stringify(value2);
}
const json = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  parse_json,
  to_json
}, Symbol.toStringTag, { value: "Module" }));
let source = Math.random;
function random$2() {
  return source();
}
function random$1() {
  return random$2();
}
function is_nan(value2) {
  return Number.isNaN(value2);
}
function is_finite(value2) {
  return Number.isFinite(value2);
}
function abs(value2) {
  return Math.abs(value2);
}
function cbrt(value2) {
  return Math.cbrt(value2);
}
function ceil(value2) {
  return Math.ceil(value2);
}
function clz32(value2) {
  return Math.clz32(value2);
}
function exp(value2) {
  return Math.exp(value2);
}
function expm1(value2) {
  return Math.expm1(value2);
}
function floor$1(value2) {
  return Math.floor(value2);
}
function fround(value2) {
  return Math.fround(value2);
}
function greatest(...values2) {
  return Math.max(...values2);
}
function least(...values2) {
  return Math.min(...values2);
}
function log(value2) {
  return Math.log(value2);
}
function log10(value2) {
  return Math.log10(value2);
}
function log1p(value2) {
  return Math.log1p(value2);
}
function log2(value2) {
  return Math.log2(value2);
}
function pow(base2, exponent) {
  return Math.pow(base2, exponent);
}
function round$1(value2) {
  return Math.round(value2);
}
function sign(value2) {
  return Math.sign(value2);
}
function sqrt(value2) {
  return Math.sqrt(value2);
}
function trunc(value2) {
  return Math.trunc(value2);
}
function degrees(radians2) {
  return 180 * radians2 / Math.PI;
}
function radians(degrees2) {
  return Math.PI * degrees2 / 180;
}
function acos(value2) {
  return Math.acos(value2);
}
function acosh(value2) {
  return Math.acosh(value2);
}
function asin(value2) {
  return Math.asin(value2);
}
function asinh(value2) {
  return Math.asinh(value2);
}
function atan(value2) {
  return Math.atan(value2);
}
function atan2(y, x) {
  return Math.atan2(y, x);
}
function atanh(value2) {
  return Math.atanh(value2);
}
function cos(value2) {
  return Math.cos(value2);
}
function cosh(value2) {
  return Math.cosh(value2);
}
function sin(value2) {
  return Math.sin(value2);
}
function sinh(value2) {
  return Math.sinh(value2);
}
function tan(value2) {
  return Math.tan(value2);
}
function tanh(value2) {
  return Math.tanh(value2);
}
const math = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  abs,
  acos,
  acosh,
  asin,
  asinh,
  atan,
  atan2,
  atanh,
  cbrt,
  ceil,
  clz32,
  cos,
  cosh,
  degrees,
  exp,
  expm1,
  floor: floor$1,
  fround,
  greatest,
  is_finite,
  is_nan,
  least,
  log,
  log10,
  log1p,
  log2,
  pow,
  radians,
  random: random$1,
  round: round$1,
  sign,
  sin,
  sinh,
  sqrt,
  tan,
  tanh,
  trunc
}, Symbol.toStringTag, { value: "Module" }));
function isMap(value2) {
  return value2 instanceof Map;
}
function isSet(value2) {
  return value2 instanceof Set;
}
function isMapOrSet(value2) {
  return isMap(value2) || isSet(value2);
}
function array(iter) {
  return Array.from(iter);
}
function has$1(object2, key2) {
  return isMapOrSet(object2) ? object2.has(key2) : object2 != null ? Object.hasOwn(object2, `${key2}`) : false;
}
function keys(object2) {
  return isMap(object2) ? array(object2.keys()) : object2 != null ? (
    /** @type {K[]} */
    Object.keys(object2)
  ) : [];
}
function values$2(object2) {
  return isMapOrSet(object2) ? array(object2.values()) : object2 != null ? Object.values(object2) : [];
}
function entries$1(object2) {
  return isMapOrSet(object2) ? array(object2.entries()) : object2 != null ? (
    /** @type {[K, V][]} */
    Object.entries(object2)
  ) : [];
}
function object(entries2) {
  return entries2 ? (
    /** @type {Record<K, V>} */
    Object.fromEntries(entries2)
  ) : NULL;
}
const object$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  entries: entries$1,
  has: has$1,
  keys,
  object,
  values: values$2
}, Symbol.toStringTag, { value: "Module" }));
function parse_date(value2) {
  return value2 == null ? value2 : new Date(value2);
}
function parse_float(value2) {
  return value2 == null ? value2 : Number.parseFloat(value2);
}
function parse_int(value2, radix) {
  return value2 == null ? value2 : Number.parseInt(value2, radix);
}
function endswith(value2, search, length2) {
  return value2 == null ? false : String(value2).endsWith(search, length2);
}
function match(value2, regexp, index) {
  const m = value2 == null ? value2 : String(value2).match(regexp);
  return index == null || m == null ? m : typeof index === "number" ? m[index] : m.groups ? m.groups[index] : null;
}
function normalize$1(value2, form) {
  return value2 == null ? value2 : String(value2).normalize(form);
}
function padend(value2, length2, fill) {
  return value2 == null ? value2 : String(value2).padEnd(length2, fill);
}
function padstart(value2, length2, fill) {
  return value2 == null ? value2 : String(value2).padStart(length2, fill);
}
function upper(value2) {
  return value2 == null ? value2 : String(value2).toUpperCase();
}
function lower(value2) {
  return value2 == null ? value2 : String(value2).toLowerCase();
}
function repeat$1(value2, number2) {
  return value2 == null ? value2 : String(value2).repeat(number2);
}
function replace$1(value2, pattern, replacement) {
  return value2 == null ? value2 : String(value2).replace(pattern, String(replacement));
}
function split(value2, separator2, limit) {
  return value2 == null ? [] : String(value2).split(separator2, limit);
}
function startswith(value2, search, position) {
  return value2 == null ? false : String(value2).startsWith(search, position);
}
function substring(value2, start2, end2) {
  return value2 == null ? value2 : String(value2).substring(start2, end2);
}
function trim(value2) {
  return value2 == null ? value2 : String(value2).trim();
}
const string = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  endswith,
  lower,
  match,
  normalize: normalize$1,
  padend,
  padstart,
  parse_date,
  parse_float,
  parse_int,
  repeat: repeat$1,
  replace: replace$1,
  split,
  startswith,
  substring,
  trim,
  upper
}, Symbol.toStringTag, { value: "Module" }));
const functions = {
  bin,
  equal,
  recode,
  sequence,
  ...array$1,
  ...date$2,
  ...json,
  ...math,
  ...object$1,
  ...string
};
function toArray$1(value2) {
  return value2 != null ? isArray$2(value2) ? value2 : [value2] : [];
}
function isBigInt(value2) {
  return typeof value2 === "bigint";
}
function toString$2(v) {
  return v === void 0 ? v + "" : isBigInt(v) ? v + "n" : JSON.stringify(v);
}
let Op$1 = class Op {
  constructor(name2, fields, params) {
    this.name = name2;
    this.fields = fields;
    this.params = params;
  }
  toString() {
    const args2 = [
      ...this.fields.map((f) => `d[${toString$2(f)}]`),
      ...this.params.map(toString$2)
    ];
    return `d => op.${this.name}(${args2})`;
  }
  toObject() {
    return { expr: this.toString(), func: true };
  }
};
function op(name2, fields = [], params = []) {
  return new Op$1(name2, toArray$1(fields), toArray$1(params));
}
const any = (field2) => op("any", field2);
const count = () => op("count");
const array_agg = (field2) => op("array_agg", field2);
const array_agg_distinct = (field2) => op("array_agg_distinct", field2);
const map_agg = (key2, value2) => op("map_agg", [key2, value2]);
const object_agg = (key2, value2) => op("object_agg", [key2, value2]);
const entries_agg = (key2, value2) => op("entries_agg", [key2, value2]);
({
  ...functions
});
function error$4(message2, cause) {
  throw Error(message2, { cause });
}
function uniqueName(names, name2) {
  names = isMapOrSet(names) ? names : new Set(names);
  let uname = name2;
  let index = 0;
  while (names.has(uname)) {
    uname = name2 + ++index;
  }
  return uname;
}
function isFunction$1(value2) {
  return typeof value2 === "function";
}
function repeat(reps, value2) {
  const result2 = Array(reps);
  if (isFunction$1(value2)) {
    for (let i2 = 0; i2 < reps; ++i2) {
      result2[i2] = value2(i2);
    }
  } else {
    result2.fill(value2);
  }
  return result2;
}
function bins(min2, max2, maxbins = 15, nice = true, minstep = 0, step) {
  const base2 = 10;
  const logb = Math.LN10;
  if (step == null) {
    const level = Math.ceil(Math.log(maxbins) / logb);
    const span = max2 - min2 || Math.abs(min2) || 1;
    const div = [5, 2];
    step = Math.max(
      minstep,
      Math.pow(base2, Math.round(Math.log(span) / logb) - level)
    );
    while (Math.ceil(span / step) > maxbins) {
      step *= base2;
    }
    const n2 = div.length;
    for (let i2 = 0; i2 < n2; ++i2) {
      const v = step / div[i2];
      if (v >= minstep && span / v <= maxbins) {
        step = v;
      }
    }
  }
  if (nice) {
    let v = Math.log(step);
    const precision = v >= 0 ? 0 : ~~(-v / logb) + 1;
    const eps = Math.pow(base2, -precision - 1);
    v = Math.floor(min2 / step + eps) * step;
    min2 = min2 < v ? v - step : v;
    max2 = Math.ceil(max2 / step) * step;
  }
  return [
    min2,
    max2 === min2 ? min2 + step : max2,
    step
  ];
}
function key$1(value2) {
  const type = typeof value2;
  return type === "string" ? `"${value2}"` : type !== "object" || !value2 ? value2 : isDate$1(value2) ? +value2 : isArray$2(value2) || isTypedArray$1(value2) ? `[${value2.map(key$1)}]` : isRegExp$1(value2) ? value2 + "" : objectKey$1(value2);
}
function objectKey$1(value2) {
  let s = "{";
  let i2 = -1;
  for (const k in value2) {
    if (++i2 > 0) s += ",";
    s += `"${k}":${key$1(value2[k])}`;
  }
  s += "}";
  return s;
}
function keyFunction(get2, nulls) {
  const n2 = get2.length;
  return n2 === 1 ? (row2, data2) => key$1(get2[0](row2, data2)) : (row2, data2) => {
    let s = "";
    for (let i2 = 0; i2 < n2; ++i2) {
      if (i2 > 0) s += "|";
      const v = get2[i2](row2, data2);
      if (nulls && (v == null || v !== v)) return null;
      s += key$1(v);
    }
    return s;
  };
}
function distinctMap() {
  const map2 = /* @__PURE__ */ new Map();
  return {
    count() {
      return map2.size;
    },
    values() {
      return Array.from(map2.values(), (_) => _.v);
    },
    increment(v) {
      const k = key$1(v);
      const e = map2.get(k);
      e ? ++e.n : map2.set(k, { v, n: 1 });
    },
    decrement(v) {
      const k = key$1(v);
      const e = map2.get(k);
      e.n === 1 ? map2.delete(k) : --e.n;
    },
    forEach(fn3) {
      map2.forEach(({ v, n: n2 }) => fn3(v, n2));
    }
  };
}
function noop$1() {
}
function product(values2, start2 = 0, stop = values2.length) {
  let prod = values2[start2++];
  for (let i2 = start2; i2 < stop; ++i2) {
    prod *= values2[i2];
  }
  return prod;
}
function initOp(op2) {
  op2.init = op2.init || noop$1;
  op2.add = op2.add || noop$1;
  op2.rem = op2.rem || noop$1;
  return op2;
}
function initProduct(s, value2) {
  s.product_v = false;
  return s.product = value2;
}
const aggregateFunctions = {
  /** @type {AggregateDef} */
  count: {
    create: () => initOp({
      value: (s) => s.count
    }),
    param: []
  },
  /** @type {AggregateDef} */
  array_agg: {
    create: () => initOp({
      init: (s) => s.values = true,
      value: (s) => s.list.values(s.stream)
    }),
    param: [1]
  },
  /** @type {AggregateDef} */
  object_agg: {
    create: () => initOp({
      init: (s) => s.values = true,
      value: (s) => Object.fromEntries(s.list.values())
    }),
    param: [2]
  },
  /** @type {AggregateDef} */
  map_agg: {
    create: () => initOp({
      init: (s) => s.values = true,
      value: (s) => new Map(s.list.values())
    }),
    param: [2]
  },
  /** @type {AggregateDef} */
  entries_agg: {
    create: () => initOp({
      init: (s) => s.values = true,
      value: (s) => s.list.values(s.stream)
    }),
    param: [2]
  },
  /** @type {AggregateDef} */
  any: {
    create: () => initOp({
      add: (s, v) => {
        if (s.any == null) s.any = v;
      },
      value: (s) => s.valid ? s.any : NULL
    }),
    param: [1]
  },
  /** @type {AggregateDef} */
  valid: {
    create: () => initOp({
      value: (s) => s.valid
    }),
    param: [1]
  },
  /** @type {AggregateDef} */
  invalid: {
    create: () => initOp({
      value: (s) => s.count - s.valid
    }),
    param: [1]
  },
  /** @type {AggregateDef} */
  distinct: {
    create: () => ({
      init: (s) => s.distinct = distinctMap(),
      value: (s) => s.distinct.count() + (s.valid === s.count ? 0 : 1),
      add: (s, v) => s.distinct.increment(v),
      rem: (s, v) => s.distinct.decrement(v)
    }),
    param: [1]
  },
  /** @type {AggregateDef} */
  array_agg_distinct: {
    create: () => initOp({
      value: (s) => s.distinct.values()
    }),
    param: [1],
    req: ["distinct"]
  },
  /** @type {AggregateDef} */
  mode: {
    create: () => initOp({
      value: (s) => {
        let mode = NULL;
        let max2 = 0;
        s.distinct.forEach((value2, count2) => {
          if (count2 > max2) {
            max2 = count2;
            mode = value2;
          }
        });
        return mode;
      }
    }),
    param: [1],
    req: ["distinct"]
  },
  /** @type {AggregateDef} */
  sum: {
    create: () => ({
      init: (s) => s.sum = 0,
      value: (s) => s.valid ? s.sum : NULL,
      add: (s, v) => isBigInt(v) ? s.sum === 0 ? s.sum = v : s.sum += v : s.sum += +v,
      rem: (s, v) => s.sum -= v
    }),
    param: [1]
  },
  /** @type {AggregateDef} */
  product: {
    create: () => ({
      init: (s) => initProduct(s, 1),
      value: (s) => s.valid ? s.product_v ? initProduct(s, product(s.list.values())) : s.product : void 0,
      add: (s, v) => isBigInt(v) ? s.product === 1 ? s.product = v : s.product *= v : s.product *= v,
      rem: (s, v) => v == 0 || v === Infinity || v === -Infinity ? s.product_v = true : s.product /= v
    }),
    param: [1],
    stream: ["array_agg"]
  },
  /** @type {AggregateDef} */
  mean: {
    create: () => ({
      init: (s) => s.mean = 0,
      value: (s) => s.valid ? s.mean : NULL,
      add: (s, v) => {
        s.mean_d = v - s.mean;
        s.mean += s.mean_d / s.valid;
      },
      rem: (s, v) => {
        s.mean_d = v - s.mean;
        s.mean -= s.valid ? s.mean_d / s.valid : s.mean;
      }
    }),
    param: [1]
  },
  /** @type {AggregateDef} */
  average: {
    create: () => initOp({
      value: (s) => s.valid ? s.mean : NULL
    }),
    param: [1],
    req: ["mean"]
  },
  /** @type {AggregateDef} */
  variance: {
    create: () => ({
      init: (s) => s.dev = 0,
      value: (s) => s.valid > 1 ? s.dev / (s.valid - 1) : NULL,
      add: (s, v) => s.dev += s.mean_d * (v - s.mean),
      rem: (s, v) => s.dev -= s.mean_d * (v - s.mean)
    }),
    param: [1],
    req: ["mean"]
  },
  /** @type {AggregateDef} */
  variancep: {
    create: () => initOp({
      value: (s) => s.valid > 1 ? s.dev / s.valid : NULL
    }),
    param: [1],
    req: ["variance"]
  },
  /** @type {AggregateDef} */
  stdev: {
    create: () => initOp({
      value: (s) => s.valid > 1 ? Math.sqrt(s.dev / (s.valid - 1)) : NULL
    }),
    param: [1],
    req: ["variance"]
  },
  /** @type {AggregateDef} */
  stdevp: {
    create: () => initOp({
      value: (s) => s.valid > 1 ? Math.sqrt(s.dev / s.valid) : NULL
    }),
    param: [1],
    req: ["variance"]
  },
  /** @type {AggregateDef} */
  min: {
    create: () => ({
      init: (s) => s.min = NULL,
      value: (s) => s.min = Number.isNaN(s.min) ? s.list.min() : s.min,
      add: (s, v) => {
        if (v < s.min || s.min === NULL) s.min = v;
      },
      rem: (s, v) => {
        if (v <= s.min) s.min = NaN;
      }
    }),
    param: [1],
    stream: ["array_agg"]
  },
  /** @type {AggregateDef} */
  max: {
    create: () => ({
      init: (s) => s.max = NULL,
      value: (s) => s.max = Number.isNaN(s.max) ? s.list.max() : s.max,
      add: (s, v) => {
        if (v > s.max || s.max === NULL) s.max = v;
      },
      rem: (s, v) => {
        if (v >= s.max) s.max = NaN;
      }
    }),
    param: [1],
    stream: ["array_agg"]
  },
  /** @type {AggregateDef} */
  quantile: {
    create: (p) => initOp({
      value: (s) => s.list.quantile(p)
    }),
    param: [1, 1],
    req: ["array_agg"]
  },
  /** @type {AggregateDef} */
  median: {
    create: () => initOp({
      value: (s) => s.list.quantile(0.5)
    }),
    param: [1],
    req: ["array_agg"]
  },
  /** @type {AggregateDef} */
  covariance: {
    create: () => ({
      init: (s) => {
        s.cov = s.mean_x = s.mean_y = s.dev_x = s.dev_y = 0;
      },
      value: (s) => s.valid > 1 ? s.cov / (s.valid - 1) : NULL,
      add: (s, x, y) => {
        const dx = x - s.mean_x;
        const dy = y - s.mean_y;
        s.mean_x += dx / s.valid;
        s.mean_y += dy / s.valid;
        const dy2 = y - s.mean_y;
        s.dev_x += dx * (x - s.mean_x);
        s.dev_y += dy * dy2;
        s.cov += dx * dy2;
      },
      rem: (s, x, y) => {
        const dx = x - s.mean_x;
        const dy = y - s.mean_y;
        s.mean_x -= s.valid ? dx / s.valid : s.mean_x;
        s.mean_y -= s.valid ? dy / s.valid : s.mean_y;
        const dy2 = y - s.mean_y;
        s.dev_x -= dx * (x - s.mean_x);
        s.dev_y -= dy * dy2;
        s.cov -= dx * dy2;
      }
    }),
    param: [2]
  },
  /** @type {AggregateDef} */
  covariancep: {
    create: () => initOp({
      value: (s) => s.valid > 1 ? s.cov / s.valid : NULL
    }),
    param: [2],
    req: ["covariance"]
  },
  /** @type {AggregateDef} */
  corr: {
    create: () => initOp({
      value: (s) => s.valid > 1 ? s.cov / (Math.sqrt(s.dev_x) * Math.sqrt(s.dev_y)) : NULL
    }),
    param: [2],
    req: ["covariance"]
  },
  /** @type {AggregateDef} */
  bins: {
    create: (maxbins, nice, minstep, step) => initOp({
      value: (s) => bins(s.min, s.max, maxbins, nice, minstep, step)
    }),
    param: [1, 4],
    req: ["min", "max"]
  }
};
const rank = {
  create() {
    let rank2;
    return {
      init: () => rank2 = 1,
      value: (w2) => {
        const i2 = w2.index;
        return i2 && !w2.peer(i2) ? rank2 = i2 + 1 : rank2;
      }
    };
  },
  param: []
};
const cume_dist = {
  create() {
    let cume;
    return {
      init: () => cume = 0,
      value: (w2) => {
        const { index, peer, size } = w2;
        let i2 = index;
        if (cume < i2) {
          while (i2 + 1 < size && peer(i2 + 1)) ++i2;
          cume = i2;
        }
        return (1 + cume) / size;
      }
    };
  },
  param: []
};
const windowFunctions = {
  /** @type {WindowDef} */
  row_number: {
    create() {
      return {
        init: noop$1,
        value: (w2) => w2.index + 1
      };
    },
    param: []
  },
  /** @type {WindowDef} */
  rank,
  /** @type {WindowDef} */
  avg_rank: {
    create() {
      let j2, rank2;
      return {
        init: () => (j2 = -1, rank2 = 1),
        value: (w2) => {
          const i2 = w2.index;
          if (i2 >= j2) {
            for (rank2 = j2 = i2 + 1; w2.peer(j2); rank2 += ++j2) ;
            rank2 /= j2 - i2;
          }
          return rank2;
        }
      };
    },
    param: []
  },
  /** @type {WindowDef} */
  dense_rank: {
    create() {
      let drank;
      return {
        init: () => drank = 1,
        value: (w2) => {
          const i2 = w2.index;
          return i2 && !w2.peer(i2) ? ++drank : drank;
        }
      };
    },
    param: []
  },
  /** @type {WindowDef} */
  percent_rank: {
    create() {
      const { init, value: value2 } = rank.create();
      return {
        init,
        value: (w2) => (value2(w2) - 1) / (w2.size - 1)
      };
    },
    param: []
  },
  /** @type {WindowDef} */
  cume_dist,
  /** @type {WindowDef} */
  ntile: {
    create(num) {
      num = +num;
      if (!(num > 0)) error$4("ntile num must be greater than zero.");
      const { init, value: value2 } = cume_dist.create();
      return {
        init,
        value: (w2) => Math.ceil(num * value2(w2))
      };
    },
    param: [0, 1]
  },
  /** @type {WindowDef} */
  lag: {
    create(offset3, defaultValue = NULL) {
      offset3 = +offset3 || 1;
      return {
        init: noop$1,
        value: (w2, f) => {
          const i2 = w2.index - offset3;
          return i2 >= 0 ? w2.value(i2, f) : defaultValue;
        }
      };
    },
    param: [1, 2]
  },
  /** @type {WindowDef} */
  lead: {
    create(offset3, defaultValue = NULL) {
      offset3 = +offset3 || 1;
      return {
        init: noop$1,
        value: (w2, f) => {
          const i2 = w2.index + offset3;
          return i2 < w2.size ? w2.value(i2, f) : defaultValue;
        }
      };
    },
    param: [1, 2]
  },
  /** @type {WindowDef} */
  first_value: {
    create() {
      return {
        init: noop$1,
        value: (w2, f) => w2.value(w2.i0, f)
      };
    },
    param: [1]
  },
  /** @type {WindowDef} */
  last_value: {
    create() {
      return {
        init: noop$1,
        value: (w2, f) => w2.value(w2.i1 - 1, f)
      };
    },
    param: [1]
  },
  /** @type {WindowDef} */
  nth_value: {
    create(nth) {
      nth = +nth;
      if (!(nth > 0)) error$4("nth_value nth must be greater than zero.");
      return {
        init: noop$1,
        value: (w2, f) => {
          const i2 = w2.i0 + (nth - 1);
          return i2 < w2.i1 ? w2.value(i2, f) : NULL;
        }
      };
    },
    param: [1, 1]
  },
  /** @type {WindowDef} */
  fill_down: {
    create(defaultValue = NULL) {
      let value2;
      return {
        init: () => value2 = defaultValue,
        value: (w2, f) => {
          const v = w2.value(w2.index, f);
          return isValid(v) ? value2 = v : value2;
        }
      };
    },
    param: [1, 1]
  },
  /** @type {WindowDef} */
  fill_up: {
    create(defaultValue = NULL) {
      let value2, idx;
      return {
        init: () => (value2 = defaultValue, idx = -1),
        value: (w2, f) => w2.index <= idx ? value2 : (idx = find(w2, f, w2.index)) >= 0 ? value2 = w2.value(idx, f) : (idx = w2.size, value2 = defaultValue)
      };
    },
    param: [1, 1]
  }
};
function find(w2, f, i2) {
  for (const n2 = w2.size; i2 < n2; ++i2) {
    if (isValid(w2.value(i2, f))) return i2;
  }
  return -1;
}
function hasAggregate(name2) {
  return Object.hasOwn(aggregateFunctions, name2);
}
function hasWindow(name2) {
  return Object.hasOwn(windowFunctions, name2);
}
function hasFunction(name2) {
  return Object.hasOwn(functions, name2) || name2 === "row_object";
}
function getAggregate(name2) {
  return hasAggregate(name2) && aggregateFunctions[name2];
}
function getWindow$1(name2) {
  return hasWindow(name2) && windowFunctions[name2];
}
function concat$1(list2, fn3 = ((x, i2) => x), delim = "") {
  const n2 = list2.length;
  if (!n2) return "";
  let s = fn3(list2[0], 0);
  for (let i2 = 1; i2 < n2; ++i2) {
    s += delim + fn3(list2[i2], i2);
  }
  return s;
}
function unroll$1(args2, code2, ...lists) {
  const v = ["_", "$"];
  const a2 = v.slice(0, lists.length);
  a2.push(
    '"use strict"; const ' + lists.map((l2, j2) => l2.map((_, i2) => `${v[j2]}${i2} = ${v[j2]}[${i2}]`).join(", ")).join(", ") + `; return (${args2}) => ${code2};`
  );
  return Function(...a2)(...lists);
}
function ascending(a2, b) {
  return a2 < b ? -1 : a2 > b ? 1 : a2 >= b ? 0 : NaN;
}
function max$1(values2, start2 = 0, stop = values2.length) {
  let max2 = stop ? values2[start2++] : NULL;
  for (let i2 = start2; i2 < stop; ++i2) {
    if (max2 < values2[i2]) {
      max2 = values2[i2];
    }
  }
  return max2;
}
function min$1(values2, start2 = 0, stop = values2.length) {
  let min2 = stop ? values2[start2++] : NULL;
  for (let i2 = start2; i2 < stop; ++i2) {
    if (min2 > values2[i2]) {
      min2 = values2[i2];
    }
  }
  return min2;
}
function toNumeric(value2) {
  return isBigInt(value2) ? value2 : +value2;
}
function quantile(values2, p) {
  const n2 = values2.length;
  if (!n2) return NULL;
  if ((p = +p) <= 0 || n2 < 2) return toNumeric(values2[0]);
  if (p >= 1) return toNumeric(values2[n2 - 1]);
  const i2 = (n2 - 1) * p;
  const i0 = Math.floor(i2);
  const v0 = toNumeric(values2[i0]);
  return isBigInt(v0) ? v0 : v0 + (toNumeric(values2[i0 + 1]) - v0) * (i2 - i0);
}
let ValueList$1 = class ValueList {
  constructor(values2) {
    this._values = values2 || [];
    this._sorted = null;
    this._start = 0;
  }
  values(copy) {
    if (this._start) {
      this._values = this._values.slice(this._start);
      this._start = 0;
    }
    return copy ? this._values.slice() : this._values;
  }
  add(value2) {
    this._values.push(value2);
    this._sorted = null;
  }
  rem() {
    this._start += 1;
    this._sorted = null;
  }
  min() {
    return this._sorted && this._sorted.length ? this._sorted[0] : min$1(this._values, this._start);
  }
  max() {
    return this._sorted && this._sorted.length ? this._sorted[this._sorted.length - 1] : max$1(this._values, this._start);
  }
  quantile(p) {
    if (!this._sorted) {
      this._sorted = this.values(true);
      this._sorted.sort(ascending);
    }
    return quantile(this._sorted, p);
  }
};
class Reducer {
  constructor(outputs) {
    this._outputs = outputs;
  }
  size() {
    return this._outputs.length;
  }
  outputs() {
    return this._outputs;
  }
  // eslint-disable-next-line no-unused-vars
  init(columns2) {
    return {};
  }
  // eslint-disable-next-line no-unused-vars
  add(state, row2, data2) {
  }
  // eslint-disable-next-line no-unused-vars
  rem(state, row2, data2) {
  }
  // eslint-disable-next-line no-unused-vars
  write(state, values2, index) {
  }
}
const update = (ops, args2, fn3) => unroll$1(
  args2,
  "{" + concat$1(ops, (_, i2) => `_${i2}.${fn3}(${args2});`) + "}",
  ops
);
function fieldReducer(oplist, stream) {
  const { ops, output: output2 } = expand$1(oplist, stream);
  const fields = oplist[0].fields;
  const n2 = fields.length;
  const cls = n2 === 0 ? FieldReducer : n2 === 1 ? Field1Reducer : n2 === 2 ? Field2Reducer : error$4("Unsupported field count: " + n2);
  return new cls(fields, ops, output2, stream);
}
function expand$1(oplist, stream) {
  const has2 = {};
  const ops = [];
  function add2(name2, params = []) {
    const key2 = name2 + ":" + params;
    if (has2[key2]) return has2[key2];
    const def = getAggregate(name2);
    const op2 = def.create(...params);
    if (stream < 0 && def.stream) {
      def.stream.forEach((name3) => add2(name3, []));
    }
    if (def.req) {
      def.req.forEach((name3) => add2(name3, []));
    }
    has2[key2] = op2;
    ops.push(op2);
    return op2;
  }
  const output2 = oplist.map((item2) => {
    const op2 = add2(item2.name, item2.params);
    op2.output = item2.id;
    return op2;
  });
  return { ops, output: output2 };
}
class FieldReducer extends Reducer {
  constructor(fields, ops, outputs, stream) {
    super(outputs);
    this._op = ops;
    this._fields = fields;
    this._stream = !!stream;
  }
  init() {
    const state = { count: 0, valid: 0, stream: this._stream };
    this._op.forEach((op2) => op2.init(state));
    if (state.values) {
      state.list = new ValueList$1();
    }
    return state;
  }
  write(state, values2, index) {
    const op2 = this._outputs;
    const n2 = op2.length;
    for (let i2 = 0; i2 < n2; ++i2) {
      values2[op2[i2].output][index] = op2[i2].value(state);
    }
    return 1;
  }
  _add() {
  }
  _rem() {
  }
  add(state) {
    ++state.count;
  }
  rem(state) {
    --state.count;
  }
}
class Field1Reducer extends FieldReducer {
  constructor(fields, ops, outputs, stream) {
    super(fields, ops, outputs, stream);
    const args2 = ["state", "v1", "v2"];
    this._add = update(ops, args2, "add");
    this._rem = update(ops, args2, "rem");
  }
  add(state, row2, data2) {
    const value2 = this._fields[0](row2, data2);
    ++state.count;
    if (isValid(value2)) {
      ++state.valid;
      if (state.list) state.list.add(value2);
      this._add(state, value2);
    }
  }
  rem(state, row2, data2) {
    const value2 = this._fields[0](row2, data2);
    --state.count;
    if (isValid(value2)) {
      --state.valid;
      if (state.list) state.list.rem();
      this._rem(state, value2);
    }
  }
}
class Field2Reducer extends FieldReducer {
  constructor(fields, ops, outputs, stream) {
    super(fields, ops, outputs, stream);
    const args2 = ["state", "v1", "v2"];
    this._add = update(ops, args2, "add");
    this._rem = update(ops, args2, "rem");
  }
  add(state, row2, data2) {
    const value1 = this._fields[0](row2, data2);
    const value2 = this._fields[1](row2, data2);
    ++state.count;
    if (isValid(value1) && isValid(value2)) {
      ++state.valid;
      if (state.list) state.list.add([value1, value2]);
      this._add(state, value1, value2);
    }
  }
  rem(state, row2, data2) {
    const value1 = this._fields[0](row2, data2);
    const value2 = this._fields[1](row2, data2);
    --state.count;
    if (isValid(value1) && isValid(value2)) {
      --state.valid;
      if (state.list) state.list.rem();
      this._rem(state, value1, value2);
    }
  }
}
function aggregateGet(table2, ops, get2) {
  if (ops.length) {
    const data2 = table2.data();
    const { keys: keys2 } = table2.groups() || {};
    const result2 = aggregate(table2, ops);
    const op2 = keys2 ? (name2, row2) => result2[name2][keys2[row2]] : (name2) => result2[name2][0];
    get2 = get2.map((f) => (row2) => f(row2, data2, op2));
  }
  return get2;
}
function aggregate(table2, ops, result2) {
  if (!ops.length) return result2;
  const aggrs = reducers(ops);
  const groups = table2.groups();
  const size = groups ? groups.size : 1;
  result2 = result2 || repeat(ops.length, () => Array(size));
  if (size > 1) {
    aggrs.forEach((aggr) => {
      const cells = reduceGroups(table2, aggr, groups);
      for (let i2 = 0; i2 < size; ++i2) {
        aggr.write(cells[i2], result2, i2);
      }
    });
  } else {
    aggrs.forEach((aggr) => {
      const cell2 = reduceFlat(table2, aggr);
      aggr.write(cell2, result2, 0);
    });
  }
  return result2;
}
function reducers(ops, stream) {
  const aggrs = [];
  const fields = {};
  for (const op2 of ops) {
    const key2 = op2.fields.map((f) => f + "").join(",");
    (fields[key2] || (fields[key2] = [])).push(op2);
  }
  for (const key2 in fields) {
    aggrs.push(fieldReducer(fields[key2], stream));
  }
  return aggrs;
}
function reduceFlat(table2, reducer) {
  const cell2 = reducer.init();
  const data2 = table2.data();
  const bits = table2.mask();
  if (table2.isOrdered()) {
    const idx = table2.indices();
    const m = idx.length;
    for (let i2 = 0; i2 < m; ++i2) {
      reducer.add(cell2, idx[i2], data2);
    }
  } else if (bits) {
    for (let i2 = bits.next(0); i2 >= 0; i2 = bits.next(i2 + 1)) {
      reducer.add(cell2, i2, data2);
    }
  } else {
    const n2 = table2.totalRows();
    for (let i2 = 0; i2 < n2; ++i2) {
      reducer.add(cell2, i2, data2);
    }
  }
  return cell2;
}
function reduceGroups(table2, reducer, groups) {
  const { keys: keys2, size } = groups;
  const cells = repeat(size, () => reducer.init());
  const data2 = table2.data();
  if (table2.isOrdered()) {
    const idx = table2.indices();
    const m = idx.length;
    for (let i2 = 0; i2 < m; ++i2) {
      const row2 = idx[i2];
      reducer.add(cells[keys2[row2]], row2, data2);
    }
  } else if (table2.isFiltered()) {
    const bits = table2.mask();
    for (let i2 = bits.next(0); i2 >= 0; i2 = bits.next(i2 + 1)) {
      reducer.add(cells[keys2[i2]], i2, data2);
    }
  } else {
    const n2 = table2.totalRows();
    for (let i2 = 0; i2 < n2; ++i2) {
      reducer.add(cells[keys2[i2]], i2, data2);
    }
  }
  return cells;
}
function groupOutput(cols, groups) {
  const { get: get2, names, rows, size } = groups;
  const m = names.length;
  for (let j2 = 0; j2 < m; ++j2) {
    const col = cols.add(names[j2], Array(size));
    const val = get2[j2];
    for (let i2 = 0; i2 < size; ++i2) {
      col[i2] = val(rows[i2]);
    }
  }
}
function entries(value2) {
  return isArray$2(value2) ? value2 : isMap(value2) ? value2.entries() : value2 ? Object.entries(value2) : [];
}
const ArrayPattern = "ArrayPattern";
const ArrowFunctionExpression = "ArrowFunctionExpression";
const FunctionExpression = "FunctionExpression";
const Identifier$1 = "Identifier";
const Literal = "Literal";
const MemberExpression = "MemberExpression";
const ObjectExpression = "ObjectExpression";
const ObjectPattern = "ObjectPattern";
const Property = "Property";
const Column$1 = "Column";
const Constant = "Constant";
const Dictionary2 = "Dictionary";
const Function$1 = "Function";
const Parameter = "Parameter";
const Op2 = "Op";
function walk(node2, ctx, visitors2, parent) {
  const visit2 = visitors2[node2.type] || visitors2["Default"];
  if (visit2 && visit2(node2, ctx, parent) === false) return;
  const walker = walkers[node2.type];
  if (walker) walker(node2, ctx, visitors2);
}
const unary = (node2, ctx, visitors2) => {
  walk(node2.argument, ctx, visitors2, node2);
};
const binary$2 = (node2, ctx, visitors2) => {
  walk(node2.left, ctx, visitors2, node2);
  walk(node2.right, ctx, visitors2, node2);
};
const ternary = (node2, ctx, visitors2) => {
  walk(node2.test, ctx, visitors2, node2);
  walk(node2.consequent, ctx, visitors2, node2);
  if (node2.alternate) walk(node2.alternate, ctx, visitors2, node2);
};
const func$1 = (node2, ctx, visitors2) => {
  list$4(node2.params, ctx, visitors2, node2);
  walk(node2.body, ctx, visitors2, node2);
};
const call$1 = (node2, ctx, visitors2) => {
  walk(node2.callee, ctx, visitors2, node2);
  list$4(node2.arguments, ctx, visitors2, node2);
};
const list$4 = (nodes, ctx, visitors2, node2) => {
  nodes.forEach((item2) => walk(item2, ctx, visitors2, node2));
};
const walkers = {
  TemplateLiteral: (node2, ctx, visitors2) => {
    list$4(node2.expressions, ctx, visitors2, node2);
    list$4(node2.quasis, ctx, visitors2, node2);
  },
  MemberExpression: (node2, ctx, visitors2) => {
    walk(node2.object, ctx, visitors2, node2);
    walk(node2.property, ctx, visitors2, node2);
  },
  CallExpression: call$1,
  NewExpression: call$1,
  ArrayExpression: (node2, ctx, visitors2) => {
    list$4(node2.elements, ctx, visitors2, node2);
  },
  AssignmentExpression: binary$2,
  AwaitExpression: unary,
  BinaryExpression: binary$2,
  LogicalExpression: binary$2,
  UnaryExpression: unary,
  UpdateExpression: unary,
  ConditionalExpression: ternary,
  ObjectExpression: (node2, ctx, visitors2) => {
    list$4(node2.properties, ctx, visitors2, node2);
  },
  Property: (node2, ctx, visitors2) => {
    walk(node2.key, ctx, visitors2, node2);
    walk(node2.value, ctx, visitors2, node2);
  },
  ArrowFunctionExpression: func$1,
  FunctionExpression: func$1,
  FunctionDeclaration: func$1,
  VariableDeclaration: (node2, ctx, visitors2) => {
    list$4(node2.declarations, ctx, visitors2, node2);
  },
  VariableDeclarator: (node2, ctx, visitors2) => {
    walk(node2.id, ctx, visitors2, node2);
    walk(node2.init, ctx, visitors2, node2);
  },
  SpreadElement: (node2, ctx, visitors2) => {
    walk(node2.argument, ctx, visitors2, node2);
  },
  BlockStatement: (node2, ctx, visitors2) => {
    list$4(node2.body, ctx, visitors2, node2);
  },
  ExpressionStatement: (node2, ctx, visitors2) => {
    walk(node2.expression, ctx, visitors2, node2);
  },
  IfStatement: ternary,
  ForStatement: (node2, ctx, visitors2) => {
    walk(node2.init, ctx, visitors2, node2);
    walk(node2.test, ctx, visitors2, node2);
    walk(node2.update, ctx, visitors2, node2);
    walk(node2.body, ctx, visitors2, node2);
  },
  WhileStatement: (node2, ctx, visitors2) => {
    walk(node2.test, ctx, visitors2, node2);
    walk(node2.body, ctx, visitors2, node2);
  },
  DoWhileStatement: (node2, ctx, visitors2) => {
    walk(node2.body, ctx, visitors2, node2);
    walk(node2.test, ctx, visitors2, node2);
  },
  SwitchStatement: (node2, ctx, visitors2) => {
    walk(node2.discriminant, ctx, visitors2, node2);
    list$4(node2.cases, ctx, visitors2, node2);
  },
  SwitchCase: (node2, ctx, visitors2) => {
    if (node2.test) walk(node2.test, ctx, visitors2, node2);
    list$4(node2.consequent, ctx, visitors2, node2);
  },
  ReturnStatement: unary,
  Program: (node2, ctx, visitors2) => {
    walk(node2.body[0], ctx, visitors2, node2);
  }
};
function strip(node2) {
  delete node2.start;
  delete node2.end;
  delete node2.optional;
}
function stripMember(node2) {
  strip(node2);
  delete node2.object;
  delete node2.property;
  delete node2.computed;
  if (!node2.table) delete node2.table;
}
function clean(ast) {
  walk(ast, null, {
    Column: stripMember,
    Constant: stripMember,
    Default: strip
  });
  return ast;
}
function is(type, node2) {
  return node2 && node2.type === type;
}
function isFunctionExpression(node2) {
  return is(FunctionExpression, node2) || is(ArrowFunctionExpression, node2);
}
const visit$2 = (node2, opt2) => {
  const f = visitors$1[node2.type];
  return f ? f(node2, opt2) : error$4(`Unsupported expression construct: ${node2.type}`);
};
const binary$1 = (node2, opt2) => {
  return "(" + visit$2(node2.left, opt2) + " " + node2.operator + " " + visit$2(node2.right, opt2) + ")";
};
const func = (node2, opt2) => {
  return "(" + list$3(node2.params, opt2) + ")=>" + visit$2(node2.body, opt2);
};
const call = (node2, opt2) => {
  return visit$2(node2.callee, opt2) + "(" + list$3(node2.arguments, opt2) + ")";
};
const list$3 = (array2, opt2, delim = ",") => {
  return array2.map((node2) => visit$2(node2, opt2)).join(delim);
};
const name = (node2) => node2.computed ? `[${toString$2(node2.name)}]` : `.${node2.name}`;
const ref$1 = (node2, opt2, method) => {
  const table2 = node2.table || "";
  return `data${table2}${name(node2)}.${method}(${opt2.index}${table2})`;
};
const get$2 = (node2, opt2) => {
  const table2 = node2.table || "";
  return `data${table2}${name(node2)}[${opt2.index}${table2}]`;
};
const visitors$1 = {
  Constant: (node2) => node2.raw,
  Column: (node2, opt2) => node2.array ? get$2(node2, opt2) : ref$1(node2, opt2, "at"),
  Dictionary: (node2, opt2) => ref$1(node2, opt2, "key"),
  Function: (node2) => `fn.${node2.name}`,
  Parameter: (node2) => `$${name(node2)}`,
  Op: (node2, opt2) => `op(${toString$2(node2.name)},${opt2.op || opt2.index})`,
  Literal: (node2) => node2.raw,
  Identifier: (node2) => node2.name,
  TemplateLiteral: (node2, opt2) => {
    const { quasis, expressions } = node2;
    const n2 = expressions.length;
    let t2 = quasis[0].value.raw;
    for (let i2 = 0; i2 < n2; ) {
      t2 += "${" + visit$2(expressions[i2], opt2) + "}" + quasis[++i2].value.raw;
    }
    return "`" + t2 + "`";
  },
  MemberExpression: (node2, opt2) => {
    const d = !node2.computed;
    const o = visit$2(node2.object, opt2);
    const p = visit$2(node2.property, opt2);
    return o + (d ? "." + p : "[" + p + "]");
  },
  CallExpression: call,
  NewExpression: (node2, opt2) => {
    return "new " + call(node2, opt2);
  },
  ArrayExpression: (node2, opt2) => {
    return "[" + list$3(node2.elements, opt2) + "]";
  },
  AssignmentExpression: binary$1,
  BinaryExpression: binary$1,
  LogicalExpression: binary$1,
  UnaryExpression: (node2, opt2) => {
    return "(" + node2.operator + visit$2(node2.argument, opt2) + ")";
  },
  ConditionalExpression: (node2, opt2) => {
    return "(" + visit$2(node2.test, opt2) + "?" + visit$2(node2.consequent, opt2) + ":" + visit$2(node2.alternate, opt2) + ")";
  },
  ObjectExpression: (node2, opt2) => {
    return "({" + list$3(node2.properties, opt2) + "})";
  },
  Property: (node2, opt2) => {
    const key2 = visit$2(node2.key, opt2);
    return (node2.computed ? `[${key2}]` : key2) + ":" + visit$2(node2.value, opt2);
  },
  ArrowFunctionExpression: func,
  FunctionExpression: func,
  FunctionDeclaration: func,
  ArrayPattern: (node2, opt2) => {
    return "[" + list$3(node2.elements, opt2) + "]";
  },
  ObjectPattern: (node2, opt2) => {
    return "{" + list$3(node2.properties, opt2) + "}";
  },
  VariableDeclaration: (node2, opt2) => {
    return node2.kind + " " + list$3(node2.declarations, opt2, ",");
  },
  VariableDeclarator: (node2, opt2) => {
    return visit$2(node2.id, opt2) + "=" + visit$2(node2.init, opt2);
  },
  SpreadElement: (node2, opt2) => {
    return "..." + visit$2(node2.argument, opt2);
  },
  BlockStatement: (node2, opt2) => {
    return "{" + list$3(node2.body, opt2, ";") + ";}";
  },
  BreakStatement: () => {
    return "break";
  },
  ExpressionStatement: (node2, opt2) => {
    return visit$2(node2.expression, opt2);
  },
  IfStatement: (node2, opt2) => {
    return "if (" + visit$2(node2.test, opt2) + ")" + visit$2(node2.consequent, opt2) + (node2.alternate ? " else " + visit$2(node2.alternate, opt2) : "");
  },
  SwitchStatement: (node2, opt2) => {
    return "switch (" + visit$2(node2.discriminant, opt2) + ") {" + list$3(node2.cases, opt2, "") + "}";
  },
  SwitchCase: (node2, opt2) => {
    return (node2.test ? "case " + visit$2(node2.test, opt2) : "default") + ": " + list$3(node2.consequent, opt2, ";") + ";";
  },
  ReturnStatement: (node2, opt2) => {
    return "return " + visit$2(node2.argument, opt2);
  },
  Program: (node2, opt2) => visit$2(node2.body[0], opt2)
};
function codegen(node2, opt2 = { index: "row" }) {
  return visit$2(node2, opt2);
}
function _compile(code2, fn3, params) {
  code2 = `"use strict"; return ${code2};`;
  return Function("fn", "$", code2)(fn3, params);
}
const compile$1 = {
  escape: (code2, func2, params) => _compile(code2, func2, params),
  expr: (code2, params) => _compile(`(row,data,op)=>${code2}`, functions, params),
  expr2: (code2, params) => _compile(`(row0,data0,row,data)=>${code2}`, functions, params),
  join: (code2, params) => _compile(`(row1,data1,row2,data2)=>${code2}`, functions, params),
  param: (code2, params) => _compile(code2, functions, params)
};
const dictOps = {
  "==": 1,
  "!=": 1,
  "===": 1,
  "!==": 1
};
function rewrite(ref2, name2, index = 0, col = void 0, op2 = void 0) {
  ref2.type = Column$1;
  ref2.name = name2;
  ref2.table = index;
  if (isArrayType(col)) {
    ref2.array = true;
  }
  if (op2 && col && isFunction$1(col.keyFor)) {
    const lit = dictOps[op2.operator] ? op2.left === ref2 ? op2.right : op2.left : op2.callee && op2.callee.name === "equal" ? op2.arguments[op2.arguments[0] === ref2 ? 1 : 0] : null;
    if (lit && lit.type === Literal) {
      rewriteDictionary(op2, ref2, lit, col.keyFor(lit.value));
    }
  }
  return ref2;
}
function rewriteDictionary(op2, ref2, lit, key2) {
  if (key2 < 0) {
    op2.type = Literal;
    op2.value = false;
    op2.raw = "false";
  } else {
    ref2.type = Dictionary2;
    lit.value = key2;
    lit.raw = key2 + "";
  }
  return true;
}
const ROW_OBJECT = "row_object";
function rowObjectExpression(node2, table2, props = table2.columnNames()) {
  node2.type = ObjectExpression;
  const p = node2.properties = [];
  for (const prop of entries(props)) {
    const [name2, key2] = isArray$2(prop) ? prop : [prop, prop];
    p.push({
      type: Property,
      key: { type: Literal, raw: toString$2(key2) },
      value: rewrite({ computed: true }, name2, 0, table2.column(name2))
    });
  }
  return node2;
}
function rowObjectCode(table2, props) {
  return codegen(rowObjectExpression({}, table2, props));
}
function rowObjectBuilder(table2, props) {
  return compile$1.expr(rowObjectCode(table2, props));
}
function toFunction(value2) {
  return isFunction$1(value2) ? value2 : () => value2;
}
const ERROR_ESC_AGGRONLY = "Escaped functions are not valid as rollup or pivot values.";
function parseEscape(ctx, spec, params) {
  if (ctx.aggronly) error$4(ERROR_ESC_AGGRONLY);
  const code2 = `(row,data)=>fn(${rowObjectCode(ctx.table)},$)`;
  return { escape: compile$1.escape(code2, toFunction(spec.expr), params) };
}
var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 7, 9, 32, 4, 318, 1, 80, 3, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 343, 9, 54, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 245, 1, 2, 9, 726, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 4, 51, 13, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 39, 27, 10, 22, 251, 41, 7, 1, 17, 2, 60, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 200, 32, 32, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 42, 9, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 229, 29, 3, 0, 496, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 4191];
var nonASCIIidentifierChars = "‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࢗ-࢟࣊-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄ఼ా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ೳഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-໎໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜕ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠏-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿ-ᫎᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷿‌‍‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯・꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏０-９＿･";
var nonASCIIidentifierStartChars = "ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࡰ-ࢇࢉ-ࢎࢠ-ࣉऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౝౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೝೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜑᜟ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭌᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲊᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꟍꟐꟑꟓꟕ-Ƛꟲ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ﬀ-ﬆﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼＡ-Ｚａ-ｚｦ-ﾾￂ-ￇￊ-ￏￒ-ￗￚ-ￜ";
var reservedWords = {
  3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
  5: "class enum extends super const export import",
  6: "enum",
  strict: "implements interface let package private protected public static yield",
  strictBind: "eval arguments"
};
var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
var keywords$1 = {
  5: ecma5AndLessKeywords,
  "5module": ecma5AndLessKeywords + " export import",
  6: ecma5AndLessKeywords + " const class extends export import super"
};
var keywordRelationalOperator = /^in(stanceof)?$/;
var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
function isInAstralSet(code2, set3) {
  var pos2 = 65536;
  for (var i2 = 0; i2 < set3.length; i2 += 2) {
    pos2 += set3[i2];
    if (pos2 > code2) {
      return false;
    }
    pos2 += set3[i2 + 1];
    if (pos2 >= code2) {
      return true;
    }
  }
  return false;
}
function isIdentifierStart(code2, astral) {
  if (code2 < 65) {
    return code2 === 36;
  }
  if (code2 < 91) {
    return true;
  }
  if (code2 < 97) {
    return code2 === 95;
  }
  if (code2 < 123) {
    return true;
  }
  if (code2 <= 65535) {
    return code2 >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code2));
  }
  if (astral === false) {
    return false;
  }
  return isInAstralSet(code2, astralIdentifierStartCodes);
}
function isIdentifierChar(code2, astral) {
  if (code2 < 48) {
    return code2 === 36;
  }
  if (code2 < 58) {
    return true;
  }
  if (code2 < 65) {
    return false;
  }
  if (code2 < 91) {
    return true;
  }
  if (code2 < 97) {
    return code2 === 95;
  }
  if (code2 < 123) {
    return true;
  }
  if (code2 <= 65535) {
    return code2 >= 170 && nonASCIIidentifier.test(String.fromCharCode(code2));
  }
  if (astral === false) {
    return false;
  }
  return isInAstralSet(code2, astralIdentifierStartCodes) || isInAstralSet(code2, astralIdentifierCodes);
}
var TokenType = function TokenType2(label2, conf) {
  if (conf === void 0) conf = {};
  this.label = label2;
  this.keyword = conf.keyword;
  this.beforeExpr = !!conf.beforeExpr;
  this.startsExpr = !!conf.startsExpr;
  this.isLoop = !!conf.isLoop;
  this.isAssign = !!conf.isAssign;
  this.prefix = !!conf.prefix;
  this.postfix = !!conf.postfix;
  this.binop = conf.binop || null;
  this.updateContext = null;
};
function binop(name2, prec) {
  return new TokenType(name2, { beforeExpr: true, binop: prec });
}
var beforeExpr = { beforeExpr: true }, startsExpr = { startsExpr: true };
var keywords = {};
function kw(name2, options) {
  if (options === void 0) options = {};
  options.keyword = name2;
  return keywords[name2] = new TokenType(name2, options);
}
var types$1 = {
  num: new TokenType("num", startsExpr),
  regexp: new TokenType("regexp", startsExpr),
  string: new TokenType("string", startsExpr),
  name: new TokenType("name", startsExpr),
  privateId: new TokenType("privateId", startsExpr),
  eof: new TokenType("eof"),
  // Punctuation token types.
  bracketL: new TokenType("[", { beforeExpr: true, startsExpr: true }),
  bracketR: new TokenType("]"),
  braceL: new TokenType("{", { beforeExpr: true, startsExpr: true }),
  braceR: new TokenType("}"),
  parenL: new TokenType("(", { beforeExpr: true, startsExpr: true }),
  parenR: new TokenType(")"),
  comma: new TokenType(",", beforeExpr),
  semi: new TokenType(";", beforeExpr),
  colon: new TokenType(":", beforeExpr),
  dot: new TokenType("."),
  question: new TokenType("?", beforeExpr),
  questionDot: new TokenType("?."),
  arrow: new TokenType("=>", beforeExpr),
  template: new TokenType("template"),
  invalidTemplate: new TokenType("invalidTemplate"),
  ellipsis: new TokenType("...", beforeExpr),
  backQuote: new TokenType("`", startsExpr),
  dollarBraceL: new TokenType("${", { beforeExpr: true, startsExpr: true }),
  // Operators. These carry several kinds of properties to help the
  // parser use them properly (the presence of these properties is
  // what categorizes them as operators).
  //
  // `binop`, when present, specifies that this operator is a binary
  // operator, and will refer to its precedence.
  //
  // `prefix` and `postfix` mark the operator as a prefix or postfix
  // unary operator.
  //
  // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
  // binary operators with a very low precedence, that should result
  // in AssignmentExpression nodes.
  eq: new TokenType("=", { beforeExpr: true, isAssign: true }),
  assign: new TokenType("_=", { beforeExpr: true, isAssign: true }),
  incDec: new TokenType("++/--", { prefix: true, postfix: true, startsExpr: true }),
  prefix: new TokenType("!/~", { beforeExpr: true, prefix: true, startsExpr: true }),
  logicalOR: binop("||", 1),
  logicalAND: binop("&&", 2),
  bitwiseOR: binop("|", 3),
  bitwiseXOR: binop("^", 4),
  bitwiseAND: binop("&", 5),
  equality: binop("==/!=/===/!==", 6),
  relational: binop("</>/<=/>=", 7),
  bitShift: binop("<</>>/>>>", 8),
  plusMin: new TokenType("+/-", { beforeExpr: true, binop: 9, prefix: true, startsExpr: true }),
  modulo: binop("%", 10),
  star: binop("*", 10),
  slash: binop("/", 10),
  starstar: new TokenType("**", { beforeExpr: true }),
  coalesce: binop("??", 1),
  // Keyword token types.
  _break: kw("break"),
  _case: kw("case", beforeExpr),
  _catch: kw("catch"),
  _continue: kw("continue"),
  _debugger: kw("debugger"),
  _default: kw("default", beforeExpr),
  _do: kw("do", { isLoop: true, beforeExpr: true }),
  _else: kw("else", beforeExpr),
  _finally: kw("finally"),
  _for: kw("for", { isLoop: true }),
  _function: kw("function", startsExpr),
  _if: kw("if"),
  _return: kw("return", beforeExpr),
  _switch: kw("switch"),
  _throw: kw("throw", beforeExpr),
  _try: kw("try"),
  _var: kw("var"),
  _const: kw("const"),
  _while: kw("while", { isLoop: true }),
  _with: kw("with"),
  _new: kw("new", { beforeExpr: true, startsExpr: true }),
  _this: kw("this", startsExpr),
  _super: kw("super", startsExpr),
  _class: kw("class", startsExpr),
  _extends: kw("extends", beforeExpr),
  _export: kw("export"),
  _import: kw("import", startsExpr),
  _null: kw("null", startsExpr),
  _true: kw("true", startsExpr),
  _false: kw("false", startsExpr),
  _in: kw("in", { beforeExpr: true, binop: 7 }),
  _instanceof: kw("instanceof", { beforeExpr: true, binop: 7 }),
  _typeof: kw("typeof", { beforeExpr: true, prefix: true, startsExpr: true }),
  _void: kw("void", { beforeExpr: true, prefix: true, startsExpr: true }),
  _delete: kw("delete", { beforeExpr: true, prefix: true, startsExpr: true })
};
var lineBreak = /\r\n?|\n|\u2028|\u2029/;
var lineBreakG = new RegExp(lineBreak.source, "g");
function isNewLine(code2) {
  return code2 === 10 || code2 === 13 || code2 === 8232 || code2 === 8233;
}
function nextLineBreak(code2, from2, end2) {
  if (end2 === void 0) end2 = code2.length;
  for (var i2 = from2; i2 < end2; i2++) {
    var next = code2.charCodeAt(i2);
    if (isNewLine(next)) {
      return i2 < end2 - 1 && next === 13 && code2.charCodeAt(i2 + 1) === 10 ? i2 + 2 : i2 + 1;
    }
  }
  return -1;
}
var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
var ref = Object.prototype;
var hasOwnProperty = ref.hasOwnProperty;
var toString$1 = ref.toString;
var hasOwn = Object.hasOwn || (function(obj, propName) {
  return hasOwnProperty.call(obj, propName);
});
var isArray$1 = Array.isArray || (function(obj) {
  return toString$1.call(obj) === "[object Array]";
});
var regexpCache = /* @__PURE__ */ Object.create(null);
function wordsRegexp(words) {
  return regexpCache[words] || (regexpCache[words] = new RegExp("^(?:" + words.replace(/ /g, "|") + ")$"));
}
function codePointToString(code2) {
  if (code2 <= 65535) {
    return String.fromCharCode(code2);
  }
  code2 -= 65536;
  return String.fromCharCode((code2 >> 10) + 55296, (code2 & 1023) + 56320);
}
var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/;
var Position = function Position2(line2, col) {
  this.line = line2;
  this.column = col;
};
Position.prototype.offset = function offset(n2) {
  return new Position(this.line, this.column + n2);
};
var SourceLocation = function SourceLocation2(p, start2, end2) {
  this.start = start2;
  this.end = end2;
  if (p.sourceFile !== null) {
    this.source = p.sourceFile;
  }
};
function getLineInfo(input2, offset3) {
  for (var line2 = 1, cur = 0; ; ) {
    var nextBreak = nextLineBreak(input2, cur, offset3);
    if (nextBreak < 0) {
      return new Position(line2, offset3 - cur);
    }
    ++line2;
    cur = nextBreak;
  }
}
var defaultOptions$1 = {
  // `ecmaVersion` indicates the ECMAScript version to parse. Must be
  // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
  // (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"`
  // (the latest version the library supports). This influences
  // support for strict mode, the set of reserved words, and support
  // for new syntax features.
  ecmaVersion: null,
  // `sourceType` indicates the mode the code should be parsed in.
  // Can be either `"script"` or `"module"`. This influences global
  // strict mode and parsing of `import` and `export` declarations.
  sourceType: "script",
  // `onInsertedSemicolon` can be a callback that will be called when
  // a semicolon is automatically inserted. It will be passed the
  // position of the inserted semicolon as an offset, and if
  // `locations` is enabled, it is given the location as a `{line,
  // column}` object as second argument.
  onInsertedSemicolon: null,
  // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
  // trailing commas.
  onTrailingComma: null,
  // By default, reserved words are only enforced if ecmaVersion >= 5.
  // Set `allowReserved` to a boolean value to explicitly turn this on
  // an off. When this option has the value "never", reserved words
  // and keywords can also not be used as property names.
  allowReserved: null,
  // When enabled, a return at the top level is not considered an
  // error.
  allowReturnOutsideFunction: false,
  // When enabled, import/export statements are not constrained to
  // appearing at the top of the program, and an import.meta expression
  // in a script isn't considered an error.
  allowImportExportEverywhere: false,
  // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
  // When enabled, await identifiers are allowed to appear at the top-level scope,
  // but they are still not allowed in non-async functions.
  allowAwaitOutsideFunction: null,
  // When enabled, super identifiers are not constrained to
  // appearing in methods and do not raise an error when they appear elsewhere.
  allowSuperOutsideMethod: null,
  // When enabled, hashbang directive in the beginning of file is
  // allowed and treated as a line comment. Enabled by default when
  // `ecmaVersion` >= 2023.
  allowHashBang: false,
  // By default, the parser will verify that private properties are
  // only used in places where they are valid and have been declared.
  // Set this to false to turn such checks off.
  checkPrivateFields: true,
  // When `locations` is on, `loc` properties holding objects with
  // `start` and `end` properties in `{line, column}` form (with
  // line being 1-based and column 0-based) will be attached to the
  // nodes.
  locations: false,
  // A function can be passed as `onToken` option, which will
  // cause Acorn to call that function with object in the same
  // format as tokens returned from `tokenizer().getToken()`. Note
  // that you are not allowed to call the parser from the
  // callback—that will corrupt its internal state.
  onToken: null,
  // A function can be passed as `onComment` option, which will
  // cause Acorn to call that function with `(block, text, start,
  // end)` parameters whenever a comment is skipped. `block` is a
  // boolean indicating whether this is a block (`/* */`) comment,
  // `text` is the content of the comment, and `start` and `end` are
  // character offsets that denote the start and end of the comment.
  // When the `locations` option is on, two more parameters are
  // passed, the full `{line, column}` locations of the start and
  // end of the comments. Note that you are not allowed to call the
  // parser from the callback—that will corrupt its internal state.
  // When this option has an array as value, objects representing the
  // comments are pushed to it.
  onComment: null,
  // Nodes have their start and end characters offsets recorded in
  // `start` and `end` properties (directly on the node, rather than
  // the `loc` object, which holds line/column data. To also add a
  // [semi-standardized][range] `range` property holding a `[start,
  // end]` array with the same numbers, set the `ranges` option to
  // `true`.
  //
  // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
  ranges: false,
  // It is possible to parse multiple files into a single AST by
  // passing the tree produced by parsing the first file as
  // `program` option in subsequent parses. This will add the
  // toplevel forms of the parsed file to the `Program` (top) node
  // of an existing parse tree.
  program: null,
  // When `locations` is on, you can pass this to record the source
  // file in every node's `loc` object.
  sourceFile: null,
  // This value, if given, is stored in every node, whether
  // `locations` is on or off.
  directSourceFile: null,
  // When enabled, parenthesized expressions are represented by
  // (non-standard) ParenthesizedExpression nodes
  preserveParens: false
};
var warnedAboutEcmaVersion = false;
function getOptions(opts) {
  var options = {};
  for (var opt2 in defaultOptions$1) {
    options[opt2] = opts && hasOwn(opts, opt2) ? opts[opt2] : defaultOptions$1[opt2];
  }
  if (options.ecmaVersion === "latest") {
    options.ecmaVersion = 1e8;
  } else if (options.ecmaVersion == null) {
    if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
      warnedAboutEcmaVersion = true;
      console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
    }
    options.ecmaVersion = 11;
  } else if (options.ecmaVersion >= 2015) {
    options.ecmaVersion -= 2009;
  }
  if (options.allowReserved == null) {
    options.allowReserved = options.ecmaVersion < 5;
  }
  if (!opts || opts.allowHashBang == null) {
    options.allowHashBang = options.ecmaVersion >= 14;
  }
  if (isArray$1(options.onToken)) {
    var tokens = options.onToken;
    options.onToken = function(token2) {
      return tokens.push(token2);
    };
  }
  if (isArray$1(options.onComment)) {
    options.onComment = pushComment(options, options.onComment);
  }
  return options;
}
function pushComment(options, array2) {
  return function(block2, text2, start2, end2, startLoc, endLoc) {
    var comment2 = {
      type: block2 ? "Block" : "Line",
      value: text2,
      start: start2,
      end: end2
    };
    if (options.locations) {
      comment2.loc = new SourceLocation(this, startLoc, endLoc);
    }
    if (options.ranges) {
      comment2.range = [start2, end2];
    }
    array2.push(comment2);
  };
}
var SCOPE_TOP = 1, SCOPE_FUNCTION = 2, SCOPE_ASYNC = 4, SCOPE_GENERATOR = 8, SCOPE_ARROW = 16, SCOPE_SIMPLE_CATCH = 32, SCOPE_SUPER = 64, SCOPE_DIRECT_SUPER = 128, SCOPE_CLASS_STATIC_BLOCK = 256, SCOPE_CLASS_FIELD_INIT = 512, SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK;
function functionFlags(async, generator) {
  return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0);
}
var BIND_NONE = 0, BIND_VAR = 1, BIND_LEXICAL = 2, BIND_FUNCTION = 3, BIND_SIMPLE_CATCH = 4, BIND_OUTSIDE = 5;
var Parser = function Parser2(options, input2, startPos) {
  this.options = options = getOptions(options);
  this.sourceFile = options.sourceFile;
  this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
  var reserved = "";
  if (options.allowReserved !== true) {
    reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
    if (options.sourceType === "module") {
      reserved += " await";
    }
  }
  this.reservedWords = wordsRegexp(reserved);
  var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
  this.reservedWordsStrict = wordsRegexp(reservedStrict);
  this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
  this.input = String(input2);
  this.containsEsc = false;
  if (startPos) {
    this.pos = startPos;
    this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
    this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
  } else {
    this.pos = this.lineStart = 0;
    this.curLine = 1;
  }
  this.type = types$1.eof;
  this.value = null;
  this.start = this.end = this.pos;
  this.startLoc = this.endLoc = this.curPosition();
  this.lastTokEndLoc = this.lastTokStartLoc = null;
  this.lastTokStart = this.lastTokEnd = this.pos;
  this.context = this.initialContext();
  this.exprAllowed = true;
  this.inModule = options.sourceType === "module";
  this.strict = this.inModule || this.strictDirective(this.pos);
  this.potentialArrowAt = -1;
  this.potentialArrowInForAwait = false;
  this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
  this.labels = [];
  this.undefinedExports = /* @__PURE__ */ Object.create(null);
  if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") {
    this.skipLineComment(2);
  }
  this.scopeStack = [];
  this.enterScope(SCOPE_TOP);
  this.regexpState = null;
  this.privateNameStack = [];
};
var prototypeAccessors = { inFunction: { configurable: true }, inGenerator: { configurable: true }, inAsync: { configurable: true }, canAwait: { configurable: true }, allowSuper: { configurable: true }, allowDirectSuper: { configurable: true }, treatFunctionsAsVar: { configurable: true }, allowNewDotTarget: { configurable: true }, inClassStaticBlock: { configurable: true } };
Parser.prototype.parse = function parse2() {
  var node2 = this.options.program || this.startNode();
  this.nextToken();
  return this.parseTopLevel(node2);
};
prototypeAccessors.inFunction.get = function() {
  return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0;
};
prototypeAccessors.inGenerator.get = function() {
  return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0;
};
prototypeAccessors.inAsync.get = function() {
  return (this.currentVarScope().flags & SCOPE_ASYNC) > 0;
};
prototypeAccessors.canAwait.get = function() {
  for (var i2 = this.scopeStack.length - 1; i2 >= 0; i2--) {
    var ref2 = this.scopeStack[i2];
    var flags = ref2.flags;
    if (flags & (SCOPE_CLASS_STATIC_BLOCK | SCOPE_CLASS_FIELD_INIT)) {
      return false;
    }
    if (flags & SCOPE_FUNCTION) {
      return (flags & SCOPE_ASYNC) > 0;
    }
  }
  return this.inModule && this.options.ecmaVersion >= 13 || this.options.allowAwaitOutsideFunction;
};
prototypeAccessors.allowSuper.get = function() {
  var ref2 = this.currentThisScope();
  var flags = ref2.flags;
  return (flags & SCOPE_SUPER) > 0 || this.options.allowSuperOutsideMethod;
};
prototypeAccessors.allowDirectSuper.get = function() {
  return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0;
};
prototypeAccessors.treatFunctionsAsVar.get = function() {
  return this.treatFunctionsAsVarInScope(this.currentScope());
};
prototypeAccessors.allowNewDotTarget.get = function() {
  for (var i2 = this.scopeStack.length - 1; i2 >= 0; i2--) {
    var ref2 = this.scopeStack[i2];
    var flags = ref2.flags;
    if (flags & (SCOPE_CLASS_STATIC_BLOCK | SCOPE_CLASS_FIELD_INIT) || flags & SCOPE_FUNCTION && !(flags & SCOPE_ARROW)) {
      return true;
    }
  }
  return false;
};
prototypeAccessors.inClassStaticBlock.get = function() {
  return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0;
};
Parser.extend = function extend() {
  var plugins2 = [], len = arguments.length;
  while (len--) plugins2[len] = arguments[len];
  var cls = this;
  for (var i2 = 0; i2 < plugins2.length; i2++) {
    cls = plugins2[i2](cls);
  }
  return cls;
};
Parser.parse = function parse3(input2, options) {
  return new this(options, input2).parse();
};
Parser.parseExpressionAt = function parseExpressionAt(input2, pos2, options) {
  var parser = new this(options, input2, pos2);
  parser.nextToken();
  return parser.parseExpression();
};
Parser.tokenizer = function tokenizer(input2, options) {
  return new this(options, input2);
};
Object.defineProperties(Parser.prototype, prototypeAccessors);
var pp$9 = Parser.prototype;
var literal = /^(?:'((?:\\[^]|[^'\\])*?)'|"((?:\\[^]|[^"\\])*?)")/;
pp$9.strictDirective = function(start2) {
  if (this.options.ecmaVersion < 5) {
    return false;
  }
  for (; ; ) {
    skipWhiteSpace.lastIndex = start2;
    start2 += skipWhiteSpace.exec(this.input)[0].length;
    var match3 = literal.exec(this.input.slice(start2));
    if (!match3) {
      return false;
    }
    if ((match3[1] || match3[2]) === "use strict") {
      skipWhiteSpace.lastIndex = start2 + match3[0].length;
      var spaceAfter = skipWhiteSpace.exec(this.input), end2 = spaceAfter.index + spaceAfter[0].length;
      var next = this.input.charAt(end2);
      return next === ";" || next === "}" || lineBreak.test(spaceAfter[0]) && !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end2 + 1) === "=");
    }
    start2 += match3[0].length;
    skipWhiteSpace.lastIndex = start2;
    start2 += skipWhiteSpace.exec(this.input)[0].length;
    if (this.input[start2] === ";") {
      start2++;
    }
  }
};
pp$9.eat = function(type) {
  if (this.type === type) {
    this.next();
    return true;
  } else {
    return false;
  }
};
pp$9.isContextual = function(name2) {
  return this.type === types$1.name && this.value === name2 && !this.containsEsc;
};
pp$9.eatContextual = function(name2) {
  if (!this.isContextual(name2)) {
    return false;
  }
  this.next();
  return true;
};
pp$9.expectContextual = function(name2) {
  if (!this.eatContextual(name2)) {
    this.unexpected();
  }
};
pp$9.canInsertSemicolon = function() {
  return this.type === types$1.eof || this.type === types$1.braceR || lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
};
pp$9.insertSemicolon = function() {
  if (this.canInsertSemicolon()) {
    if (this.options.onInsertedSemicolon) {
      this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc);
    }
    return true;
  }
};
pp$9.semicolon = function() {
  if (!this.eat(types$1.semi) && !this.insertSemicolon()) {
    this.unexpected();
  }
};
pp$9.afterTrailingComma = function(tokType, notNext) {
  if (this.type === tokType) {
    if (this.options.onTrailingComma) {
      this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc);
    }
    if (!notNext) {
      this.next();
    }
    return true;
  }
};
pp$9.expect = function(type) {
  this.eat(type) || this.unexpected();
};
pp$9.unexpected = function(pos2) {
  this.raise(pos2 != null ? pos2 : this.start, "Unexpected token");
};
var DestructuringErrors = function DestructuringErrors2() {
  this.shorthandAssign = this.trailingComma = this.parenthesizedAssign = this.parenthesizedBind = this.doubleProto = -1;
};
pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) {
  if (!refDestructuringErrors) {
    return;
  }
  if (refDestructuringErrors.trailingComma > -1) {
    this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element");
  }
  var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
  if (parens > -1) {
    this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern");
  }
};
pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
  if (!refDestructuringErrors) {
    return false;
  }
  var shorthandAssign = refDestructuringErrors.shorthandAssign;
  var doubleProto = refDestructuringErrors.doubleProto;
  if (!andThrow) {
    return shorthandAssign >= 0 || doubleProto >= 0;
  }
  if (shorthandAssign >= 0) {
    this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns");
  }
  if (doubleProto >= 0) {
    this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property");
  }
};
pp$9.checkYieldAwaitInDefaultParams = function() {
  if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) {
    this.raise(this.yieldPos, "Yield expression cannot be a default value");
  }
  if (this.awaitPos) {
    this.raise(this.awaitPos, "Await expression cannot be a default value");
  }
};
pp$9.isSimpleAssignTarget = function(expr) {
  if (expr.type === "ParenthesizedExpression") {
    return this.isSimpleAssignTarget(expr.expression);
  }
  return expr.type === "Identifier" || expr.type === "MemberExpression";
};
var pp$8 = Parser.prototype;
pp$8.parseTopLevel = function(node2) {
  var exports2 = /* @__PURE__ */ Object.create(null);
  if (!node2.body) {
    node2.body = [];
  }
  while (this.type !== types$1.eof) {
    var stmt = this.parseStatement(null, true, exports2);
    node2.body.push(stmt);
  }
  if (this.inModule) {
    for (var i2 = 0, list2 = Object.keys(this.undefinedExports); i2 < list2.length; i2 += 1) {
      var name2 = list2[i2];
      this.raiseRecoverable(this.undefinedExports[name2].start, "Export '" + name2 + "' is not defined");
    }
  }
  this.adaptDirectivePrologue(node2.body);
  this.next();
  node2.sourceType = this.options.sourceType;
  return this.finishNode(node2, "Program");
};
var loopLabel = { kind: "loop" }, switchLabel = { kind: "switch" };
pp$8.isLet = function(context) {
  if (this.options.ecmaVersion < 6 || !this.isContextual("let")) {
    return false;
  }
  skipWhiteSpace.lastIndex = this.pos;
  var skip = skipWhiteSpace.exec(this.input);
  var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  if (nextCh === 91 || nextCh === 92) {
    return true;
  }
  if (context) {
    return false;
  }
  if (nextCh === 123 || nextCh > 55295 && nextCh < 56320) {
    return true;
  }
  if (isIdentifierStart(nextCh, true)) {
    var pos2 = next + 1;
    while (isIdentifierChar(nextCh = this.input.charCodeAt(pos2), true)) {
      ++pos2;
    }
    if (nextCh === 92 || nextCh > 55295 && nextCh < 56320) {
      return true;
    }
    var ident = this.input.slice(next, pos2);
    if (!keywordRelationalOperator.test(ident)) {
      return true;
    }
  }
  return false;
};
pp$8.isAsyncFunction = function() {
  if (this.options.ecmaVersion < 8 || !this.isContextual("async")) {
    return false;
  }
  skipWhiteSpace.lastIndex = this.pos;
  var skip = skipWhiteSpace.exec(this.input);
  var next = this.pos + skip[0].length, after;
  return !lineBreak.test(this.input.slice(this.pos, next)) && this.input.slice(next, next + 8) === "function" && (next + 8 === this.input.length || !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 55295 && after < 56320));
};
pp$8.isUsingKeyword = function(isAwaitUsing, isFor) {
  if (this.options.ecmaVersion < 17 || !this.isContextual(isAwaitUsing ? "await" : "using")) {
    return false;
  }
  skipWhiteSpace.lastIndex = this.pos;
  var skip = skipWhiteSpace.exec(this.input);
  var next = this.pos + skip[0].length;
  if (lineBreak.test(this.input.slice(this.pos, next))) {
    return false;
  }
  if (isAwaitUsing) {
    var awaitEndPos = next + 5, after;
    if (this.input.slice(next, awaitEndPos) !== "using" || awaitEndPos === this.input.length || isIdentifierChar(after = this.input.charCodeAt(awaitEndPos)) || after > 55295 && after < 56320) {
      return false;
    }
    skipWhiteSpace.lastIndex = awaitEndPos;
    var skipAfterUsing = skipWhiteSpace.exec(this.input);
    if (skipAfterUsing && lineBreak.test(this.input.slice(awaitEndPos, awaitEndPos + skipAfterUsing[0].length))) {
      return false;
    }
  }
  if (isFor) {
    var ofEndPos = next + 2, after$1;
    if (this.input.slice(next, ofEndPos) === "of") {
      if (ofEndPos === this.input.length || !isIdentifierChar(after$1 = this.input.charCodeAt(ofEndPos)) && !(after$1 > 55295 && after$1 < 56320)) {
        return false;
      }
    }
  }
  var ch = this.input.charCodeAt(next);
  return isIdentifierStart(ch, true) || ch === 92;
};
pp$8.isAwaitUsing = function(isFor) {
  return this.isUsingKeyword(true, isFor);
};
pp$8.isUsing = function(isFor) {
  return this.isUsingKeyword(false, isFor);
};
pp$8.parseStatement = function(context, topLevel, exports2) {
  var starttype = this.type, node2 = this.startNode(), kind;
  if (this.isLet(context)) {
    starttype = types$1._var;
    kind = "let";
  }
  switch (starttype) {
    case types$1._break:
    case types$1._continue:
      return this.parseBreakContinueStatement(node2, starttype.keyword);
    case types$1._debugger:
      return this.parseDebuggerStatement(node2);
    case types$1._do:
      return this.parseDoStatement(node2);
    case types$1._for:
      return this.parseForStatement(node2);
    case types$1._function:
      if (context && (this.strict || context !== "if" && context !== "label") && this.options.ecmaVersion >= 6) {
        this.unexpected();
      }
      return this.parseFunctionStatement(node2, false, !context);
    case types$1._class:
      if (context) {
        this.unexpected();
      }
      return this.parseClass(node2, true);
    case types$1._if:
      return this.parseIfStatement(node2);
    case types$1._return:
      return this.parseReturnStatement(node2);
    case types$1._switch:
      return this.parseSwitchStatement(node2);
    case types$1._throw:
      return this.parseThrowStatement(node2);
    case types$1._try:
      return this.parseTryStatement(node2);
    case types$1._const:
    case types$1._var:
      kind = kind || this.value;
      if (context && kind !== "var") {
        this.unexpected();
      }
      return this.parseVarStatement(node2, kind);
    case types$1._while:
      return this.parseWhileStatement(node2);
    case types$1._with:
      return this.parseWithStatement(node2);
    case types$1.braceL:
      return this.parseBlock(true, node2);
    case types$1.semi:
      return this.parseEmptyStatement(node2);
    case types$1._export:
    case types$1._import:
      if (this.options.ecmaVersion > 10 && starttype === types$1._import) {
        skipWhiteSpace.lastIndex = this.pos;
        var skip = skipWhiteSpace.exec(this.input);
        var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
        if (nextCh === 40 || nextCh === 46) {
          return this.parseExpressionStatement(node2, this.parseExpression());
        }
      }
      if (!this.options.allowImportExportEverywhere) {
        if (!topLevel) {
          this.raise(this.start, "'import' and 'export' may only appear at the top level");
        }
        if (!this.inModule) {
          this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'");
        }
      }
      return starttype === types$1._import ? this.parseImport(node2) : this.parseExport(node2, exports2);
    // If the statement does not start with a statement keyword or a
    // brace, it's an ExpressionStatement or LabeledStatement. We
    // simply start parsing an expression, and afterwards, if the
    // next token is a colon and the expression was a simple
    // Identifier node, we switch to interpreting it as a label.
    default:
      if (this.isAsyncFunction()) {
        if (context) {
          this.unexpected();
        }
        this.next();
        return this.parseFunctionStatement(node2, true, !context);
      }
      var usingKind = this.isAwaitUsing(false) ? "await using" : this.isUsing(false) ? "using" : null;
      if (usingKind) {
        if (topLevel && this.options.sourceType === "script") {
          this.raise(this.start, "Using declaration cannot appear in the top level when source type is `script`");
        }
        if (usingKind === "await using") {
          if (!this.canAwait) {
            this.raise(this.start, "Await using cannot appear outside of async function");
          }
          this.next();
        }
        this.next();
        this.parseVar(node2, false, usingKind);
        this.semicolon();
        return this.finishNode(node2, "VariableDeclaration");
      }
      var maybeName = this.value, expr = this.parseExpression();
      if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon)) {
        return this.parseLabeledStatement(node2, maybeName, expr, context);
      } else {
        return this.parseExpressionStatement(node2, expr);
      }
  }
};
pp$8.parseBreakContinueStatement = function(node2, keyword) {
  var isBreak = keyword === "break";
  this.next();
  if (this.eat(types$1.semi) || this.insertSemicolon()) {
    node2.label = null;
  } else if (this.type !== types$1.name) {
    this.unexpected();
  } else {
    node2.label = this.parseIdent();
    this.semicolon();
  }
  var i2 = 0;
  for (; i2 < this.labels.length; ++i2) {
    var lab = this.labels[i2];
    if (node2.label == null || lab.name === node2.label.name) {
      if (lab.kind != null && (isBreak || lab.kind === "loop")) {
        break;
      }
      if (node2.label && isBreak) {
        break;
      }
    }
  }
  if (i2 === this.labels.length) {
    this.raise(node2.start, "Unsyntactic " + keyword);
  }
  return this.finishNode(node2, isBreak ? "BreakStatement" : "ContinueStatement");
};
pp$8.parseDebuggerStatement = function(node2) {
  this.next();
  this.semicolon();
  return this.finishNode(node2, "DebuggerStatement");
};
pp$8.parseDoStatement = function(node2) {
  this.next();
  this.labels.push(loopLabel);
  node2.body = this.parseStatement("do");
  this.labels.pop();
  this.expect(types$1._while);
  node2.test = this.parseParenExpression();
  if (this.options.ecmaVersion >= 6) {
    this.eat(types$1.semi);
  } else {
    this.semicolon();
  }
  return this.finishNode(node2, "DoWhileStatement");
};
pp$8.parseForStatement = function(node2) {
  this.next();
  var awaitAt = this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await") ? this.lastTokStart : -1;
  this.labels.push(loopLabel);
  this.enterScope(0);
  this.expect(types$1.parenL);
  if (this.type === types$1.semi) {
    if (awaitAt > -1) {
      this.unexpected(awaitAt);
    }
    return this.parseFor(node2, null);
  }
  var isLet = this.isLet();
  if (this.type === types$1._var || this.type === types$1._const || isLet) {
    var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
    this.next();
    this.parseVar(init$1, true, kind);
    this.finishNode(init$1, "VariableDeclaration");
    return this.parseForAfterInit(node2, init$1, awaitAt);
  }
  var startsWithLet = this.isContextual("let"), isForOf = false;
  var usingKind = this.isUsing(true) ? "using" : this.isAwaitUsing(true) ? "await using" : null;
  if (usingKind) {
    var init$2 = this.startNode();
    this.next();
    if (usingKind === "await using") {
      this.next();
    }
    this.parseVar(init$2, true, usingKind);
    this.finishNode(init$2, "VariableDeclaration");
    return this.parseForAfterInit(node2, init$2, awaitAt);
  }
  var containsEsc = this.containsEsc;
  var refDestructuringErrors = new DestructuringErrors();
  var initPos = this.start;
  var init = awaitAt > -1 ? this.parseExprSubscripts(refDestructuringErrors, "await") : this.parseExpression(true, refDestructuringErrors);
  if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
    if (awaitAt > -1) {
      if (this.type === types$1._in) {
        this.unexpected(awaitAt);
      }
      node2.await = true;
    } else if (isForOf && this.options.ecmaVersion >= 8) {
      if (init.start === initPos && !containsEsc && init.type === "Identifier" && init.name === "async") {
        this.unexpected();
      } else if (this.options.ecmaVersion >= 9) {
        node2.await = false;
      }
    }
    if (startsWithLet && isForOf) {
      this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'.");
    }
    this.toAssignable(init, false, refDestructuringErrors);
    this.checkLValPattern(init);
    return this.parseForIn(node2, init);
  } else {
    this.checkExpressionErrors(refDestructuringErrors, true);
  }
  if (awaitAt > -1) {
    this.unexpected(awaitAt);
  }
  return this.parseFor(node2, init);
};
pp$8.parseForAfterInit = function(node2, init, awaitAt) {
  if ((this.type === types$1._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) && init.declarations.length === 1) {
    if (this.options.ecmaVersion >= 9) {
      if (this.type === types$1._in) {
        if (awaitAt > -1) {
          this.unexpected(awaitAt);
        }
      } else {
        node2.await = awaitAt > -1;
      }
    }
    return this.parseForIn(node2, init);
  }
  if (awaitAt > -1) {
    this.unexpected(awaitAt);
  }
  return this.parseFor(node2, init);
};
pp$8.parseFunctionStatement = function(node2, isAsync, declarationPosition) {
  this.next();
  return this.parseFunction(node2, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync);
};
pp$8.parseIfStatement = function(node2) {
  this.next();
  node2.test = this.parseParenExpression();
  node2.consequent = this.parseStatement("if");
  node2.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null;
  return this.finishNode(node2, "IfStatement");
};
pp$8.parseReturnStatement = function(node2) {
  if (!this.inFunction && !this.options.allowReturnOutsideFunction) {
    this.raise(this.start, "'return' outside of function");
  }
  this.next();
  if (this.eat(types$1.semi) || this.insertSemicolon()) {
    node2.argument = null;
  } else {
    node2.argument = this.parseExpression();
    this.semicolon();
  }
  return this.finishNode(node2, "ReturnStatement");
};
pp$8.parseSwitchStatement = function(node2) {
  this.next();
  node2.discriminant = this.parseParenExpression();
  node2.cases = [];
  this.expect(types$1.braceL);
  this.labels.push(switchLabel);
  this.enterScope(0);
  var cur;
  for (var sawDefault = false; this.type !== types$1.braceR; ) {
    if (this.type === types$1._case || this.type === types$1._default) {
      var isCase = this.type === types$1._case;
      if (cur) {
        this.finishNode(cur, "SwitchCase");
      }
      node2.cases.push(cur = this.startNode());
      cur.consequent = [];
      this.next();
      if (isCase) {
        cur.test = this.parseExpression();
      } else {
        if (sawDefault) {
          this.raiseRecoverable(this.lastTokStart, "Multiple default clauses");
        }
        sawDefault = true;
        cur.test = null;
      }
      this.expect(types$1.colon);
    } else {
      if (!cur) {
        this.unexpected();
      }
      cur.consequent.push(this.parseStatement(null));
    }
  }
  this.exitScope();
  if (cur) {
    this.finishNode(cur, "SwitchCase");
  }
  this.next();
  this.labels.pop();
  return this.finishNode(node2, "SwitchStatement");
};
pp$8.parseThrowStatement = function(node2) {
  this.next();
  if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) {
    this.raise(this.lastTokEnd, "Illegal newline after throw");
  }
  node2.argument = this.parseExpression();
  this.semicolon();
  return this.finishNode(node2, "ThrowStatement");
};
var empty$1 = [];
pp$8.parseCatchClauseParam = function() {
  var param = this.parseBindingAtom();
  var simple2 = param.type === "Identifier";
  this.enterScope(simple2 ? SCOPE_SIMPLE_CATCH : 0);
  this.checkLValPattern(param, simple2 ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
  this.expect(types$1.parenR);
  return param;
};
pp$8.parseTryStatement = function(node2) {
  this.next();
  node2.block = this.parseBlock();
  node2.handler = null;
  if (this.type === types$1._catch) {
    var clause = this.startNode();
    this.next();
    if (this.eat(types$1.parenL)) {
      clause.param = this.parseCatchClauseParam();
    } else {
      if (this.options.ecmaVersion < 10) {
        this.unexpected();
      }
      clause.param = null;
      this.enterScope(0);
    }
    clause.body = this.parseBlock(false);
    this.exitScope();
    node2.handler = this.finishNode(clause, "CatchClause");
  }
  node2.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null;
  if (!node2.handler && !node2.finalizer) {
    this.raise(node2.start, "Missing catch or finally clause");
  }
  return this.finishNode(node2, "TryStatement");
};
pp$8.parseVarStatement = function(node2, kind, allowMissingInitializer) {
  this.next();
  this.parseVar(node2, false, kind, allowMissingInitializer);
  this.semicolon();
  return this.finishNode(node2, "VariableDeclaration");
};
pp$8.parseWhileStatement = function(node2) {
  this.next();
  node2.test = this.parseParenExpression();
  this.labels.push(loopLabel);
  node2.body = this.parseStatement("while");
  this.labels.pop();
  return this.finishNode(node2, "WhileStatement");
};
pp$8.parseWithStatement = function(node2) {
  if (this.strict) {
    this.raise(this.start, "'with' in strict mode");
  }
  this.next();
  node2.object = this.parseParenExpression();
  node2.body = this.parseStatement("with");
  return this.finishNode(node2, "WithStatement");
};
pp$8.parseEmptyStatement = function(node2) {
  this.next();
  return this.finishNode(node2, "EmptyStatement");
};
pp$8.parseLabeledStatement = function(node2, maybeName, expr, context) {
  for (var i$1 = 0, list2 = this.labels; i$1 < list2.length; i$1 += 1) {
    var label2 = list2[i$1];
    if (label2.name === maybeName) {
      this.raise(expr.start, "Label '" + maybeName + "' is already declared");
    }
  }
  var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null;
  for (var i2 = this.labels.length - 1; i2 >= 0; i2--) {
    var label$12 = this.labels[i2];
    if (label$12.statementStart === node2.start) {
      label$12.statementStart = this.start;
      label$12.kind = kind;
    } else {
      break;
    }
  }
  this.labels.push({ name: maybeName, kind, statementStart: this.start });
  node2.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  this.labels.pop();
  node2.label = expr;
  return this.finishNode(node2, "LabeledStatement");
};
pp$8.parseExpressionStatement = function(node2, expr) {
  node2.expression = expr;
  this.semicolon();
  return this.finishNode(node2, "ExpressionStatement");
};
pp$8.parseBlock = function(createNewLexicalScope, node2, exitStrict) {
  if (createNewLexicalScope === void 0) createNewLexicalScope = true;
  if (node2 === void 0) node2 = this.startNode();
  node2.body = [];
  this.expect(types$1.braceL);
  if (createNewLexicalScope) {
    this.enterScope(0);
  }
  while (this.type !== types$1.braceR) {
    var stmt = this.parseStatement(null);
    node2.body.push(stmt);
  }
  if (exitStrict) {
    this.strict = false;
  }
  this.next();
  if (createNewLexicalScope) {
    this.exitScope();
  }
  return this.finishNode(node2, "BlockStatement");
};
pp$8.parseFor = function(node2, init) {
  node2.init = init;
  this.expect(types$1.semi);
  node2.test = this.type === types$1.semi ? null : this.parseExpression();
  this.expect(types$1.semi);
  node2.update = this.type === types$1.parenR ? null : this.parseExpression();
  this.expect(types$1.parenR);
  node2.body = this.parseStatement("for");
  this.exitScope();
  this.labels.pop();
  return this.finishNode(node2, "ForStatement");
};
pp$8.parseForIn = function(node2, init) {
  var isForIn = this.type === types$1._in;
  this.next();
  if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.options.ecmaVersion < 8 || this.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) {
    this.raise(
      init.start,
      (isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer"
    );
  }
  node2.left = init;
  node2.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  this.expect(types$1.parenR);
  node2.body = this.parseStatement("for");
  this.exitScope();
  this.labels.pop();
  return this.finishNode(node2, isForIn ? "ForInStatement" : "ForOfStatement");
};
pp$8.parseVar = function(node2, isFor, kind, allowMissingInitializer) {
  node2.declarations = [];
  node2.kind = kind;
  for (; ; ) {
    var decl = this.startNode();
    this.parseVarId(decl, kind);
    if (this.eat(types$1.eq)) {
      decl.init = this.parseMaybeAssign(isFor);
    } else if (!allowMissingInitializer && kind === "const" && !(this.type === types$1._in || this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
      this.unexpected();
    } else if (!allowMissingInitializer && (kind === "using" || kind === "await using") && this.options.ecmaVersion >= 17 && this.type !== types$1._in && !this.isContextual("of")) {
      this.raise(this.lastTokEnd, "Missing initializer in " + kind + " declaration");
    } else if (!allowMissingInitializer && decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) {
      this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
    } else {
      decl.init = null;
    }
    node2.declarations.push(this.finishNode(decl, "VariableDeclarator"));
    if (!this.eat(types$1.comma)) {
      break;
    }
  }
  return node2;
};
pp$8.parseVarId = function(decl, kind) {
  decl.id = kind === "using" || kind === "await using" ? this.parseIdent() : this.parseBindingAtom();
  this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
};
var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
pp$8.parseFunction = function(node2, statement, allowExpressionBody, isAsync, forInit) {
  this.initFunction(node2);
  if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
    if (this.type === types$1.star && statement & FUNC_HANGING_STATEMENT) {
      this.unexpected();
    }
    node2.generator = this.eat(types$1.star);
  }
  if (this.options.ecmaVersion >= 8) {
    node2.async = !!isAsync;
  }
  if (statement & FUNC_STATEMENT) {
    node2.id = statement & FUNC_NULLABLE_ID && this.type !== types$1.name ? null : this.parseIdent();
    if (node2.id && !(statement & FUNC_HANGING_STATEMENT)) {
      this.checkLValSimple(node2.id, this.strict || node2.generator || node2.async ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION);
    }
  }
  var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  this.yieldPos = 0;
  this.awaitPos = 0;
  this.awaitIdentPos = 0;
  this.enterScope(functionFlags(node2.async, node2.generator));
  if (!(statement & FUNC_STATEMENT)) {
    node2.id = this.type === types$1.name ? this.parseIdent() : null;
  }
  this.parseFunctionParams(node2);
  this.parseFunctionBody(node2, allowExpressionBody, false, forInit);
  this.yieldPos = oldYieldPos;
  this.awaitPos = oldAwaitPos;
  this.awaitIdentPos = oldAwaitIdentPos;
  return this.finishNode(node2, statement & FUNC_STATEMENT ? "FunctionDeclaration" : "FunctionExpression");
};
pp$8.parseFunctionParams = function(node2) {
  this.expect(types$1.parenL);
  node2.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  this.checkYieldAwaitInDefaultParams();
};
pp$8.parseClass = function(node2, isStatement) {
  this.next();
  var oldStrict = this.strict;
  this.strict = true;
  this.parseClassId(node2, isStatement);
  this.parseClassSuper(node2);
  var privateNameMap = this.enterClassBody();
  var classBody = this.startNode();
  var hadConstructor = false;
  classBody.body = [];
  this.expect(types$1.braceL);
  while (this.type !== types$1.braceR) {
    var element = this.parseClassElement(node2.superClass !== null);
    if (element) {
      classBody.body.push(element);
      if (element.type === "MethodDefinition" && element.kind === "constructor") {
        if (hadConstructor) {
          this.raiseRecoverable(element.start, "Duplicate constructor in the same class");
        }
        hadConstructor = true;
      } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
        this.raiseRecoverable(element.key.start, "Identifier '#" + element.key.name + "' has already been declared");
      }
    }
  }
  this.strict = oldStrict;
  this.next();
  node2.body = this.finishNode(classBody, "ClassBody");
  this.exitClassBody();
  return this.finishNode(node2, isStatement ? "ClassDeclaration" : "ClassExpression");
};
pp$8.parseClassElement = function(constructorAllowsSuper) {
  if (this.eat(types$1.semi)) {
    return null;
  }
  var ecmaVersion = this.options.ecmaVersion;
  var node2 = this.startNode();
  var keyName = "";
  var isGenerator = false;
  var isAsync = false;
  var kind = "method";
  var isStatic = false;
  if (this.eatContextual("static")) {
    if (ecmaVersion >= 13 && this.eat(types$1.braceL)) {
      this.parseClassStaticBlock(node2);
      return node2;
    }
    if (this.isClassElementNameStart() || this.type === types$1.star) {
      isStatic = true;
    } else {
      keyName = "static";
    }
  }
  node2.static = isStatic;
  if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
    if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) {
      isAsync = true;
    } else {
      keyName = "async";
    }
  }
  if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) {
    isGenerator = true;
  }
  if (!keyName && !isAsync && !isGenerator) {
    var lastValue = this.value;
    if (this.eatContextual("get") || this.eatContextual("set")) {
      if (this.isClassElementNameStart()) {
        kind = lastValue;
      } else {
        keyName = lastValue;
      }
    }
  }
  if (keyName) {
    node2.computed = false;
    node2.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
    node2.key.name = keyName;
    this.finishNode(node2.key, "Identifier");
  } else {
    this.parseClassElementName(node2);
  }
  if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) {
    var isConstructor = !node2.static && checkKeyName(node2, "constructor");
    var allowsDirectSuper = isConstructor && constructorAllowsSuper;
    if (isConstructor && kind !== "method") {
      this.raise(node2.key.start, "Constructor can't have get/set modifier");
    }
    node2.kind = isConstructor ? "constructor" : kind;
    this.parseClassMethod(node2, isGenerator, isAsync, allowsDirectSuper);
  } else {
    this.parseClassField(node2);
  }
  return node2;
};
pp$8.isClassElementNameStart = function() {
  return this.type === types$1.name || this.type === types$1.privateId || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword;
};
pp$8.parseClassElementName = function(element) {
  if (this.type === types$1.privateId) {
    if (this.value === "constructor") {
      this.raise(this.start, "Classes can't have an element named '#constructor'");
    }
    element.computed = false;
    element.key = this.parsePrivateIdent();
  } else {
    this.parsePropertyName(element);
  }
};
pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
  var key2 = method.key;
  if (method.kind === "constructor") {
    if (isGenerator) {
      this.raise(key2.start, "Constructor can't be a generator");
    }
    if (isAsync) {
      this.raise(key2.start, "Constructor can't be an async method");
    }
  } else if (method.static && checkKeyName(method, "prototype")) {
    this.raise(key2.start, "Classes may not have a static property named prototype");
  }
  var value2 = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
  if (method.kind === "get" && value2.params.length !== 0) {
    this.raiseRecoverable(value2.start, "getter should have no params");
  }
  if (method.kind === "set" && value2.params.length !== 1) {
    this.raiseRecoverable(value2.start, "setter should have exactly one param");
  }
  if (method.kind === "set" && value2.params[0].type === "RestElement") {
    this.raiseRecoverable(value2.params[0].start, "Setter cannot use rest params");
  }
  return this.finishNode(method, "MethodDefinition");
};
pp$8.parseClassField = function(field2) {
  if (checkKeyName(field2, "constructor")) {
    this.raise(field2.key.start, "Classes can't have a field named 'constructor'");
  } else if (field2.static && checkKeyName(field2, "prototype")) {
    this.raise(field2.key.start, "Classes can't have a static field named 'prototype'");
  }
  if (this.eat(types$1.eq)) {
    this.enterScope(SCOPE_CLASS_FIELD_INIT | SCOPE_SUPER);
    field2.value = this.parseMaybeAssign();
    this.exitScope();
  } else {
    field2.value = null;
  }
  this.semicolon();
  return this.finishNode(field2, "PropertyDefinition");
};
pp$8.parseClassStaticBlock = function(node2) {
  node2.body = [];
  var oldLabels = this.labels;
  this.labels = [];
  this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER);
  while (this.type !== types$1.braceR) {
    var stmt = this.parseStatement(null);
    node2.body.push(stmt);
  }
  this.next();
  this.exitScope();
  this.labels = oldLabels;
  return this.finishNode(node2, "StaticBlock");
};
pp$8.parseClassId = function(node2, isStatement) {
  if (this.type === types$1.name) {
    node2.id = this.parseIdent();
    if (isStatement) {
      this.checkLValSimple(node2.id, BIND_LEXICAL, false);
    }
  } else {
    if (isStatement === true) {
      this.unexpected();
    }
    node2.id = null;
  }
};
pp$8.parseClassSuper = function(node2) {
  node2.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(null, false) : null;
};
pp$8.enterClassBody = function() {
  var element = { declared: /* @__PURE__ */ Object.create(null), used: [] };
  this.privateNameStack.push(element);
  return element.declared;
};
pp$8.exitClassBody = function() {
  var ref2 = this.privateNameStack.pop();
  var declared = ref2.declared;
  var used = ref2.used;
  if (!this.options.checkPrivateFields) {
    return;
  }
  var len = this.privateNameStack.length;
  var parent = len === 0 ? null : this.privateNameStack[len - 1];
  for (var i2 = 0; i2 < used.length; ++i2) {
    var id2 = used[i2];
    if (!hasOwn(declared, id2.name)) {
      if (parent) {
        parent.used.push(id2);
      } else {
        this.raiseRecoverable(id2.start, "Private field '#" + id2.name + "' must be declared in an enclosing class");
      }
    }
  }
};
function isPrivateNameConflicted(privateNameMap, element) {
  var name2 = element.key.name;
  var curr = privateNameMap[name2];
  var next = "true";
  if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
    next = (element.static ? "s" : "i") + element.kind;
  }
  if (curr === "iget" && next === "iset" || curr === "iset" && next === "iget" || curr === "sget" && next === "sset" || curr === "sset" && next === "sget") {
    privateNameMap[name2] = "true";
    return false;
  } else if (!curr) {
    privateNameMap[name2] = next;
    return false;
  } else {
    return true;
  }
}
function checkKeyName(node2, name2) {
  var computed = node2.computed;
  var key2 = node2.key;
  return !computed && (key2.type === "Identifier" && key2.name === name2 || key2.type === "Literal" && key2.value === name2);
}
pp$8.parseExportAllDeclaration = function(node2, exports2) {
  if (this.options.ecmaVersion >= 11) {
    if (this.eatContextual("as")) {
      node2.exported = this.parseModuleExportName();
      this.checkExport(exports2, node2.exported, this.lastTokStart);
    } else {
      node2.exported = null;
    }
  }
  this.expectContextual("from");
  if (this.type !== types$1.string) {
    this.unexpected();
  }
  node2.source = this.parseExprAtom();
  if (this.options.ecmaVersion >= 16) {
    node2.attributes = this.parseWithClause();
  }
  this.semicolon();
  return this.finishNode(node2, "ExportAllDeclaration");
};
pp$8.parseExport = function(node2, exports2) {
  this.next();
  if (this.eat(types$1.star)) {
    return this.parseExportAllDeclaration(node2, exports2);
  }
  if (this.eat(types$1._default)) {
    this.checkExport(exports2, "default", this.lastTokStart);
    node2.declaration = this.parseExportDefaultDeclaration();
    return this.finishNode(node2, "ExportDefaultDeclaration");
  }
  if (this.shouldParseExportStatement()) {
    node2.declaration = this.parseExportDeclaration(node2);
    if (node2.declaration.type === "VariableDeclaration") {
      this.checkVariableExport(exports2, node2.declaration.declarations);
    } else {
      this.checkExport(exports2, node2.declaration.id, node2.declaration.id.start);
    }
    node2.specifiers = [];
    node2.source = null;
    if (this.options.ecmaVersion >= 16) {
      node2.attributes = [];
    }
  } else {
    node2.declaration = null;
    node2.specifiers = this.parseExportSpecifiers(exports2);
    if (this.eatContextual("from")) {
      if (this.type !== types$1.string) {
        this.unexpected();
      }
      node2.source = this.parseExprAtom();
      if (this.options.ecmaVersion >= 16) {
        node2.attributes = this.parseWithClause();
      }
    } else {
      for (var i2 = 0, list2 = node2.specifiers; i2 < list2.length; i2 += 1) {
        var spec = list2[i2];
        this.checkUnreserved(spec.local);
        this.checkLocalExport(spec.local);
        if (spec.local.type === "Literal") {
          this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`.");
        }
      }
      node2.source = null;
      if (this.options.ecmaVersion >= 16) {
        node2.attributes = [];
      }
    }
    this.semicolon();
  }
  return this.finishNode(node2, "ExportNamedDeclaration");
};
pp$8.parseExportDeclaration = function(node2) {
  return this.parseStatement(null);
};
pp$8.parseExportDefaultDeclaration = function() {
  var isAsync;
  if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) {
    var fNode = this.startNode();
    this.next();
    if (isAsync) {
      this.next();
    }
    return this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
  } else if (this.type === types$1._class) {
    var cNode = this.startNode();
    return this.parseClass(cNode, "nullableID");
  } else {
    var declaration2 = this.parseMaybeAssign();
    this.semicolon();
    return declaration2;
  }
};
pp$8.checkExport = function(exports2, name2, pos2) {
  if (!exports2) {
    return;
  }
  if (typeof name2 !== "string") {
    name2 = name2.type === "Identifier" ? name2.name : name2.value;
  }
  if (hasOwn(exports2, name2)) {
    this.raiseRecoverable(pos2, "Duplicate export '" + name2 + "'");
  }
  exports2[name2] = true;
};
pp$8.checkPatternExport = function(exports2, pat) {
  var type = pat.type;
  if (type === "Identifier") {
    this.checkExport(exports2, pat, pat.start);
  } else if (type === "ObjectPattern") {
    for (var i2 = 0, list2 = pat.properties; i2 < list2.length; i2 += 1) {
      var prop = list2[i2];
      this.checkPatternExport(exports2, prop);
    }
  } else if (type === "ArrayPattern") {
    for (var i$1 = 0, list$12 = pat.elements; i$1 < list$12.length; i$1 += 1) {
      var elt = list$12[i$1];
      if (elt) {
        this.checkPatternExport(exports2, elt);
      }
    }
  } else if (type === "Property") {
    this.checkPatternExport(exports2, pat.value);
  } else if (type === "AssignmentPattern") {
    this.checkPatternExport(exports2, pat.left);
  } else if (type === "RestElement") {
    this.checkPatternExport(exports2, pat.argument);
  }
};
pp$8.checkVariableExport = function(exports2, decls) {
  if (!exports2) {
    return;
  }
  for (var i2 = 0, list2 = decls; i2 < list2.length; i2 += 1) {
    var decl = list2[i2];
    this.checkPatternExport(exports2, decl.id);
  }
};
pp$8.shouldParseExportStatement = function() {
  return this.type.keyword === "var" || this.type.keyword === "const" || this.type.keyword === "class" || this.type.keyword === "function" || this.isLet() || this.isAsyncFunction();
};
pp$8.parseExportSpecifier = function(exports2) {
  var node2 = this.startNode();
  node2.local = this.parseModuleExportName();
  node2.exported = this.eatContextual("as") ? this.parseModuleExportName() : node2.local;
  this.checkExport(
    exports2,
    node2.exported,
    node2.exported.start
  );
  return this.finishNode(node2, "ExportSpecifier");
};
pp$8.parseExportSpecifiers = function(exports2) {
  var nodes = [], first2 = true;
  this.expect(types$1.braceL);
  while (!this.eat(types$1.braceR)) {
    if (!first2) {
      this.expect(types$1.comma);
      if (this.afterTrailingComma(types$1.braceR)) {
        break;
      }
    } else {
      first2 = false;
    }
    nodes.push(this.parseExportSpecifier(exports2));
  }
  return nodes;
};
pp$8.parseImport = function(node2) {
  this.next();
  if (this.type === types$1.string) {
    node2.specifiers = empty$1;
    node2.source = this.parseExprAtom();
  } else {
    node2.specifiers = this.parseImportSpecifiers();
    this.expectContextual("from");
    node2.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected();
  }
  if (this.options.ecmaVersion >= 16) {
    node2.attributes = this.parseWithClause();
  }
  this.semicolon();
  return this.finishNode(node2, "ImportDeclaration");
};
pp$8.parseImportSpecifier = function() {
  var node2 = this.startNode();
  node2.imported = this.parseModuleExportName();
  if (this.eatContextual("as")) {
    node2.local = this.parseIdent();
  } else {
    this.checkUnreserved(node2.imported);
    node2.local = node2.imported;
  }
  this.checkLValSimple(node2.local, BIND_LEXICAL);
  return this.finishNode(node2, "ImportSpecifier");
};
pp$8.parseImportDefaultSpecifier = function() {
  var node2 = this.startNode();
  node2.local = this.parseIdent();
  this.checkLValSimple(node2.local, BIND_LEXICAL);
  return this.finishNode(node2, "ImportDefaultSpecifier");
};
pp$8.parseImportNamespaceSpecifier = function() {
  var node2 = this.startNode();
  this.next();
  this.expectContextual("as");
  node2.local = this.parseIdent();
  this.checkLValSimple(node2.local, BIND_LEXICAL);
  return this.finishNode(node2, "ImportNamespaceSpecifier");
};
pp$8.parseImportSpecifiers = function() {
  var nodes = [], first2 = true;
  if (this.type === types$1.name) {
    nodes.push(this.parseImportDefaultSpecifier());
    if (!this.eat(types$1.comma)) {
      return nodes;
    }
  }
  if (this.type === types$1.star) {
    nodes.push(this.parseImportNamespaceSpecifier());
    return nodes;
  }
  this.expect(types$1.braceL);
  while (!this.eat(types$1.braceR)) {
    if (!first2) {
      this.expect(types$1.comma);
      if (this.afterTrailingComma(types$1.braceR)) {
        break;
      }
    } else {
      first2 = false;
    }
    nodes.push(this.parseImportSpecifier());
  }
  return nodes;
};
pp$8.parseWithClause = function() {
  var nodes = [];
  if (!this.eat(types$1._with)) {
    return nodes;
  }
  this.expect(types$1.braceL);
  var attributeKeys = {};
  var first2 = true;
  while (!this.eat(types$1.braceR)) {
    if (!first2) {
      this.expect(types$1.comma);
      if (this.afterTrailingComma(types$1.braceR)) {
        break;
      }
    } else {
      first2 = false;
    }
    var attr = this.parseImportAttribute();
    var keyName = attr.key.type === "Identifier" ? attr.key.name : attr.key.value;
    if (hasOwn(attributeKeys, keyName)) {
      this.raiseRecoverable(attr.key.start, "Duplicate attribute key '" + keyName + "'");
    }
    attributeKeys[keyName] = true;
    nodes.push(attr);
  }
  return nodes;
};
pp$8.parseImportAttribute = function() {
  var node2 = this.startNode();
  node2.key = this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never");
  this.expect(types$1.colon);
  if (this.type !== types$1.string) {
    this.unexpected();
  }
  node2.value = this.parseExprAtom();
  return this.finishNode(node2, "ImportAttribute");
};
pp$8.parseModuleExportName = function() {
  if (this.options.ecmaVersion >= 13 && this.type === types$1.string) {
    var stringLiteral = this.parseLiteral(this.value);
    if (loneSurrogate.test(stringLiteral.value)) {
      this.raise(stringLiteral.start, "An export name cannot include a lone surrogate.");
    }
    return stringLiteral;
  }
  return this.parseIdent(true);
};
pp$8.adaptDirectivePrologue = function(statements) {
  for (var i2 = 0; i2 < statements.length && this.isDirectiveCandidate(statements[i2]); ++i2) {
    statements[i2].directive = statements[i2].expression.raw.slice(1, -1);
  }
};
pp$8.isDirectiveCandidate = function(statement) {
  return this.options.ecmaVersion >= 5 && statement.type === "ExpressionStatement" && statement.expression.type === "Literal" && typeof statement.expression.value === "string" && // Reject parenthesized strings.
  (this.input[statement.start] === '"' || this.input[statement.start] === "'");
};
var pp$7 = Parser.prototype;
pp$7.toAssignable = function(node2, isBinding, refDestructuringErrors) {
  if (this.options.ecmaVersion >= 6 && node2) {
    switch (node2.type) {
      case "Identifier":
        if (this.inAsync && node2.name === "await") {
          this.raise(node2.start, "Cannot use 'await' as identifier inside an async function");
        }
        break;
      case "ObjectPattern":
      case "ArrayPattern":
      case "AssignmentPattern":
      case "RestElement":
        break;
      case "ObjectExpression":
        node2.type = "ObjectPattern";
        if (refDestructuringErrors) {
          this.checkPatternErrors(refDestructuringErrors, true);
        }
        for (var i2 = 0, list2 = node2.properties; i2 < list2.length; i2 += 1) {
          var prop = list2[i2];
          this.toAssignable(prop, isBinding);
          if (prop.type === "RestElement" && (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")) {
            this.raise(prop.argument.start, "Unexpected token");
          }
        }
        break;
      case "Property":
        if (node2.kind !== "init") {
          this.raise(node2.key.start, "Object pattern can't contain getter or setter");
        }
        this.toAssignable(node2.value, isBinding);
        break;
      case "ArrayExpression":
        node2.type = "ArrayPattern";
        if (refDestructuringErrors) {
          this.checkPatternErrors(refDestructuringErrors, true);
        }
        this.toAssignableList(node2.elements, isBinding);
        break;
      case "SpreadElement":
        node2.type = "RestElement";
        this.toAssignable(node2.argument, isBinding);
        if (node2.argument.type === "AssignmentPattern") {
          this.raise(node2.argument.start, "Rest elements cannot have a default value");
        }
        break;
      case "AssignmentExpression":
        if (node2.operator !== "=") {
          this.raise(node2.left.end, "Only '=' operator can be used for specifying default value.");
        }
        node2.type = "AssignmentPattern";
        delete node2.operator;
        this.toAssignable(node2.left, isBinding);
        break;
      case "ParenthesizedExpression":
        this.toAssignable(node2.expression, isBinding, refDestructuringErrors);
        break;
      case "ChainExpression":
        this.raiseRecoverable(node2.start, "Optional chaining cannot appear in left-hand side");
        break;
      case "MemberExpression":
        if (!isBinding) {
          break;
        }
      default:
        this.raise(node2.start, "Assigning to rvalue");
    }
  } else if (refDestructuringErrors) {
    this.checkPatternErrors(refDestructuringErrors, true);
  }
  return node2;
};
pp$7.toAssignableList = function(exprList, isBinding) {
  var end2 = exprList.length;
  for (var i2 = 0; i2 < end2; i2++) {
    var elt = exprList[i2];
    if (elt) {
      this.toAssignable(elt, isBinding);
    }
  }
  if (end2) {
    var last2 = exprList[end2 - 1];
    if (this.options.ecmaVersion === 6 && isBinding && last2 && last2.type === "RestElement" && last2.argument.type !== "Identifier") {
      this.unexpected(last2.argument.start);
    }
  }
  return exprList;
};
pp$7.parseSpread = function(refDestructuringErrors) {
  var node2 = this.startNode();
  this.next();
  node2.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  return this.finishNode(node2, "SpreadElement");
};
pp$7.parseRestBinding = function() {
  var node2 = this.startNode();
  this.next();
  if (this.options.ecmaVersion === 6 && this.type !== types$1.name) {
    this.unexpected();
  }
  node2.argument = this.parseBindingAtom();
  return this.finishNode(node2, "RestElement");
};
pp$7.parseBindingAtom = function() {
  if (this.options.ecmaVersion >= 6) {
    switch (this.type) {
      case types$1.bracketL:
        var node2 = this.startNode();
        this.next();
        node2.elements = this.parseBindingList(types$1.bracketR, true, true);
        return this.finishNode(node2, "ArrayPattern");
      case types$1.braceL:
        return this.parseObj(true);
    }
  }
  return this.parseIdent();
};
pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowModifiers) {
  var elts = [], first2 = true;
  while (!this.eat(close)) {
    if (first2) {
      first2 = false;
    } else {
      this.expect(types$1.comma);
    }
    if (allowEmpty && this.type === types$1.comma) {
      elts.push(null);
    } else if (allowTrailingComma && this.afterTrailingComma(close)) {
      break;
    } else if (this.type === types$1.ellipsis) {
      var rest = this.parseRestBinding();
      this.parseBindingListItem(rest);
      elts.push(rest);
      if (this.type === types$1.comma) {
        this.raiseRecoverable(this.start, "Comma is not permitted after the rest element");
      }
      this.expect(close);
      break;
    } else {
      elts.push(this.parseAssignableListItem(allowModifiers));
    }
  }
  return elts;
};
pp$7.parseAssignableListItem = function(allowModifiers) {
  var elem = this.parseMaybeDefault(this.start, this.startLoc);
  this.parseBindingListItem(elem);
  return elem;
};
pp$7.parseBindingListItem = function(param) {
  return param;
};
pp$7.parseMaybeDefault = function(startPos, startLoc, left2) {
  left2 = left2 || this.parseBindingAtom();
  if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) {
    return left2;
  }
  var node2 = this.startNodeAt(startPos, startLoc);
  node2.left = left2;
  node2.right = this.parseMaybeAssign();
  return this.finishNode(node2, "AssignmentPattern");
};
pp$7.checkLValSimple = function(expr, bindingType, checkClashes) {
  if (bindingType === void 0) bindingType = BIND_NONE;
  var isBind = bindingType !== BIND_NONE;
  switch (expr.type) {
    case "Identifier":
      if (this.strict && this.reservedWordsStrictBind.test(expr.name)) {
        this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode");
      }
      if (isBind) {
        if (bindingType === BIND_LEXICAL && expr.name === "let") {
          this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name");
        }
        if (checkClashes) {
          if (hasOwn(checkClashes, expr.name)) {
            this.raiseRecoverable(expr.start, "Argument name clash");
          }
          checkClashes[expr.name] = true;
        }
        if (bindingType !== BIND_OUTSIDE) {
          this.declareName(expr.name, bindingType, expr.start);
        }
      }
      break;
    case "ChainExpression":
      this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
      break;
    case "MemberExpression":
      if (isBind) {
        this.raiseRecoverable(expr.start, "Binding member expression");
      }
      break;
    case "ParenthesizedExpression":
      if (isBind) {
        this.raiseRecoverable(expr.start, "Binding parenthesized expression");
      }
      return this.checkLValSimple(expr.expression, bindingType, checkClashes);
    default:
      this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
  }
};
pp$7.checkLValPattern = function(expr, bindingType, checkClashes) {
  if (bindingType === void 0) bindingType = BIND_NONE;
  switch (expr.type) {
    case "ObjectPattern":
      for (var i2 = 0, list2 = expr.properties; i2 < list2.length; i2 += 1) {
        var prop = list2[i2];
        this.checkLValInnerPattern(prop, bindingType, checkClashes);
      }
      break;
    case "ArrayPattern":
      for (var i$1 = 0, list$12 = expr.elements; i$1 < list$12.length; i$1 += 1) {
        var elem = list$12[i$1];
        if (elem) {
          this.checkLValInnerPattern(elem, bindingType, checkClashes);
        }
      }
      break;
    default:
      this.checkLValSimple(expr, bindingType, checkClashes);
  }
};
pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
  if (bindingType === void 0) bindingType = BIND_NONE;
  switch (expr.type) {
    case "Property":
      this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
      break;
    case "AssignmentPattern":
      this.checkLValPattern(expr.left, bindingType, checkClashes);
      break;
    case "RestElement":
      this.checkLValPattern(expr.argument, bindingType, checkClashes);
      break;
    default:
      this.checkLValPattern(expr, bindingType, checkClashes);
  }
};
var TokContext = function TokContext2(token2, isExpr, preserveSpace, override, generator) {
  this.token = token2;
  this.isExpr = !!isExpr;
  this.preserveSpace = !!preserveSpace;
  this.override = override;
  this.generator = !!generator;
};
var types = {
  b_stat: new TokContext("{", false),
  b_expr: new TokContext("{", true),
  b_tmpl: new TokContext("${", false),
  p_stat: new TokContext("(", false),
  p_expr: new TokContext("(", true),
  q_tmpl: new TokContext("`", true, true, function(p) {
    return p.tryReadTemplateToken();
  }),
  f_stat: new TokContext("function", false),
  f_expr: new TokContext("function", true),
  f_expr_gen: new TokContext("function", true, false, null, true),
  f_gen: new TokContext("function", false, false, null, true)
};
var pp$6 = Parser.prototype;
pp$6.initialContext = function() {
  return [types.b_stat];
};
pp$6.curContext = function() {
  return this.context[this.context.length - 1];
};
pp$6.braceIsBlock = function(prevType) {
  var parent = this.curContext();
  if (parent === types.f_expr || parent === types.f_stat) {
    return true;
  }
  if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr)) {
    return !parent.isExpr;
  }
  if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed) {
    return lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
  }
  if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow) {
    return true;
  }
  if (prevType === types$1.braceL) {
    return parent === types.b_stat;
  }
  if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name) {
    return false;
  }
  return !this.exprAllowed;
};
pp$6.inGeneratorContext = function() {
  for (var i2 = this.context.length - 1; i2 >= 1; i2--) {
    var context = this.context[i2];
    if (context.token === "function") {
      return context.generator;
    }
  }
  return false;
};
pp$6.updateContext = function(prevType) {
  var update2, type = this.type;
  if (type.keyword && prevType === types$1.dot) {
    this.exprAllowed = false;
  } else if (update2 = type.updateContext) {
    update2.call(this, prevType);
  } else {
    this.exprAllowed = type.beforeExpr;
  }
};
pp$6.overrideContext = function(tokenCtx) {
  if (this.curContext() !== tokenCtx) {
    this.context[this.context.length - 1] = tokenCtx;
  }
};
types$1.parenR.updateContext = types$1.braceR.updateContext = function() {
  if (this.context.length === 1) {
    this.exprAllowed = true;
    return;
  }
  var out = this.context.pop();
  if (out === types.b_stat && this.curContext().token === "function") {
    out = this.context.pop();
  }
  this.exprAllowed = !out.isExpr;
};
types$1.braceL.updateContext = function(prevType) {
  this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr);
  this.exprAllowed = true;
};
types$1.dollarBraceL.updateContext = function() {
  this.context.push(types.b_tmpl);
  this.exprAllowed = true;
};
types$1.parenL.updateContext = function(prevType) {
  var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while;
  this.context.push(statementParens ? types.p_stat : types.p_expr);
  this.exprAllowed = true;
};
types$1.incDec.updateContext = function() {
};
types$1._function.updateContext = types$1._class.updateContext = function(prevType) {
  if (prevType.beforeExpr && prevType !== types$1._else && !(prevType === types$1.semi && this.curContext() !== types.p_stat) && !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat)) {
    this.context.push(types.f_expr);
  } else {
    this.context.push(types.f_stat);
  }
  this.exprAllowed = false;
};
types$1.colon.updateContext = function() {
  if (this.curContext().token === "function") {
    this.context.pop();
  }
  this.exprAllowed = true;
};
types$1.backQuote.updateContext = function() {
  if (this.curContext() === types.q_tmpl) {
    this.context.pop();
  } else {
    this.context.push(types.q_tmpl);
  }
  this.exprAllowed = false;
};
types$1.star.updateContext = function(prevType) {
  if (prevType === types$1._function) {
    var index = this.context.length - 1;
    if (this.context[index] === types.f_expr) {
      this.context[index] = types.f_expr_gen;
    } else {
      this.context[index] = types.f_gen;
    }
  }
  this.exprAllowed = true;
};
types$1.name.updateContext = function(prevType) {
  var allowed = false;
  if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) {
    if (this.value === "of" && !this.exprAllowed || this.value === "yield" && this.inGeneratorContext()) {
      allowed = true;
    }
  }
  this.exprAllowed = allowed;
};
var pp$5 = Parser.prototype;
pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
  if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") {
    return;
  }
  if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) {
    return;
  }
  var key2 = prop.key;
  var name2;
  switch (key2.type) {
    case "Identifier":
      name2 = key2.name;
      break;
    case "Literal":
      name2 = String(key2.value);
      break;
    default:
      return;
  }
  var kind = prop.kind;
  if (this.options.ecmaVersion >= 6) {
    if (name2 === "__proto__" && kind === "init") {
      if (propHash.proto) {
        if (refDestructuringErrors) {
          if (refDestructuringErrors.doubleProto < 0) {
            refDestructuringErrors.doubleProto = key2.start;
          }
        } else {
          this.raiseRecoverable(key2.start, "Redefinition of __proto__ property");
        }
      }
      propHash.proto = true;
    }
    return;
  }
  name2 = "$" + name2;
  var other = propHash[name2];
  if (other) {
    var redefinition;
    if (kind === "init") {
      redefinition = this.strict && other.init || other.get || other.set;
    } else {
      redefinition = other.init || other[kind];
    }
    if (redefinition) {
      this.raiseRecoverable(key2.start, "Redefinition of property");
    }
  } else {
    other = propHash[name2] = {
      init: false,
      get: false,
      set: false
    };
  }
  other[kind] = true;
};
pp$5.parseExpression = function(forInit, refDestructuringErrors) {
  var startPos = this.start, startLoc = this.startLoc;
  var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
  if (this.type === types$1.comma) {
    var node2 = this.startNodeAt(startPos, startLoc);
    node2.expressions = [expr];
    while (this.eat(types$1.comma)) {
      node2.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors));
    }
    return this.finishNode(node2, "SequenceExpression");
  }
  return expr;
};
pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
  if (this.isContextual("yield")) {
    if (this.inGenerator) {
      return this.parseYield(forInit);
    } else {
      this.exprAllowed = false;
    }
  }
  var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1;
  if (refDestructuringErrors) {
    oldParenAssign = refDestructuringErrors.parenthesizedAssign;
    oldTrailingComma = refDestructuringErrors.trailingComma;
    oldDoubleProto = refDestructuringErrors.doubleProto;
    refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
  } else {
    refDestructuringErrors = new DestructuringErrors();
    ownDestructuringErrors = true;
  }
  var startPos = this.start, startLoc = this.startLoc;
  if (this.type === types$1.parenL || this.type === types$1.name) {
    this.potentialArrowAt = this.start;
    this.potentialArrowInForAwait = forInit === "await";
  }
  var left2 = this.parseMaybeConditional(forInit, refDestructuringErrors);
  if (afterLeftParse) {
    left2 = afterLeftParse.call(this, left2, startPos, startLoc);
  }
  if (this.type.isAssign) {
    var node2 = this.startNodeAt(startPos, startLoc);
    node2.operator = this.value;
    if (this.type === types$1.eq) {
      left2 = this.toAssignable(left2, false, refDestructuringErrors);
    }
    if (!ownDestructuringErrors) {
      refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
    }
    if (refDestructuringErrors.shorthandAssign >= left2.start) {
      refDestructuringErrors.shorthandAssign = -1;
    }
    if (this.type === types$1.eq) {
      this.checkLValPattern(left2);
    } else {
      this.checkLValSimple(left2);
    }
    node2.left = left2;
    this.next();
    node2.right = this.parseMaybeAssign(forInit);
    if (oldDoubleProto > -1) {
      refDestructuringErrors.doubleProto = oldDoubleProto;
    }
    return this.finishNode(node2, "AssignmentExpression");
  } else {
    if (ownDestructuringErrors) {
      this.checkExpressionErrors(refDestructuringErrors, true);
    }
  }
  if (oldParenAssign > -1) {
    refDestructuringErrors.parenthesizedAssign = oldParenAssign;
  }
  if (oldTrailingComma > -1) {
    refDestructuringErrors.trailingComma = oldTrailingComma;
  }
  return left2;
};
pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) {
  var startPos = this.start, startLoc = this.startLoc;
  var expr = this.parseExprOps(forInit, refDestructuringErrors);
  if (this.checkExpressionErrors(refDestructuringErrors)) {
    return expr;
  }
  if (this.eat(types$1.question)) {
    var node2 = this.startNodeAt(startPos, startLoc);
    node2.test = expr;
    node2.consequent = this.parseMaybeAssign();
    this.expect(types$1.colon);
    node2.alternate = this.parseMaybeAssign(forInit);
    return this.finishNode(node2, "ConditionalExpression");
  }
  return expr;
};
pp$5.parseExprOps = function(forInit, refDestructuringErrors) {
  var startPos = this.start, startLoc = this.startLoc;
  var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit);
  if (this.checkExpressionErrors(refDestructuringErrors)) {
    return expr;
  }
  return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit);
};
pp$5.parseExprOp = function(left2, leftStartPos, leftStartLoc, minPrec, forInit) {
  var prec = this.type.binop;
  if (prec != null && (!forInit || this.type !== types$1._in)) {
    if (prec > minPrec) {
      var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND;
      var coalesce = this.type === types$1.coalesce;
      if (coalesce) {
        prec = types$1.logicalAND.binop;
      }
      var op2 = this.value;
      this.next();
      var startPos = this.start, startLoc = this.startLoc;
      var right2 = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit);
      var node2 = this.buildBinary(leftStartPos, leftStartLoc, left2, right2, op2, logical || coalesce);
      if (logical && this.type === types$1.coalesce || coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND)) {
        this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
      }
      return this.parseExprOp(node2, leftStartPos, leftStartLoc, minPrec, forInit);
    }
  }
  return left2;
};
pp$5.buildBinary = function(startPos, startLoc, left2, right2, op2, logical) {
  if (right2.type === "PrivateIdentifier") {
    this.raise(right2.start, "Private identifier can only be left side of binary expression");
  }
  var node2 = this.startNodeAt(startPos, startLoc);
  node2.left = left2;
  node2.operator = op2;
  node2.right = right2;
  return this.finishNode(node2, logical ? "LogicalExpression" : "BinaryExpression");
};
pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) {
  var startPos = this.start, startLoc = this.startLoc, expr;
  if (this.isContextual("await") && this.canAwait) {
    expr = this.parseAwait(forInit);
    sawUnary = true;
  } else if (this.type.prefix) {
    var node2 = this.startNode(), update2 = this.type === types$1.incDec;
    node2.operator = this.value;
    node2.prefix = true;
    this.next();
    node2.argument = this.parseMaybeUnary(null, true, update2, forInit);
    this.checkExpressionErrors(refDestructuringErrors, true);
    if (update2) {
      this.checkLValSimple(node2.argument);
    } else if (this.strict && node2.operator === "delete" && isLocalVariableAccess(node2.argument)) {
      this.raiseRecoverable(node2.start, "Deleting local variable in strict mode");
    } else if (node2.operator === "delete" && isPrivateFieldAccess(node2.argument)) {
      this.raiseRecoverable(node2.start, "Private fields can not be deleted");
    } else {
      sawUnary = true;
    }
    expr = this.finishNode(node2, update2 ? "UpdateExpression" : "UnaryExpression");
  } else if (!sawUnary && this.type === types$1.privateId) {
    if ((forInit || this.privateNameStack.length === 0) && this.options.checkPrivateFields) {
      this.unexpected();
    }
    expr = this.parsePrivateIdent();
    if (this.type !== types$1._in) {
      this.unexpected();
    }
  } else {
    expr = this.parseExprSubscripts(refDestructuringErrors, forInit);
    if (this.checkExpressionErrors(refDestructuringErrors)) {
      return expr;
    }
    while (this.type.postfix && !this.canInsertSemicolon()) {
      var node$1 = this.startNodeAt(startPos, startLoc);
      node$1.operator = this.value;
      node$1.prefix = false;
      node$1.argument = expr;
      this.checkLValSimple(expr);
      this.next();
      expr = this.finishNode(node$1, "UpdateExpression");
    }
  }
  if (!incDec && this.eat(types$1.starstar)) {
    if (sawUnary) {
      this.unexpected(this.lastTokStart);
    } else {
      return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false);
    }
  } else {
    return expr;
  }
};
function isLocalVariableAccess(node2) {
  return node2.type === "Identifier" || node2.type === "ParenthesizedExpression" && isLocalVariableAccess(node2.expression);
}
function isPrivateFieldAccess(node2) {
  return node2.type === "MemberExpression" && node2.property.type === "PrivateIdentifier" || node2.type === "ChainExpression" && isPrivateFieldAccess(node2.expression) || node2.type === "ParenthesizedExpression" && isPrivateFieldAccess(node2.expression);
}
pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) {
  var startPos = this.start, startLoc = this.startLoc;
  var expr = this.parseExprAtom(refDestructuringErrors, forInit);
  if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") {
    return expr;
  }
  var result2 = this.parseSubscripts(expr, startPos, startLoc, false, forInit);
  if (refDestructuringErrors && result2.type === "MemberExpression") {
    if (refDestructuringErrors.parenthesizedAssign >= result2.start) {
      refDestructuringErrors.parenthesizedAssign = -1;
    }
    if (refDestructuringErrors.parenthesizedBind >= result2.start) {
      refDestructuringErrors.parenthesizedBind = -1;
    }
    if (refDestructuringErrors.trailingComma >= result2.start) {
      refDestructuringErrors.trailingComma = -1;
    }
  }
  return result2;
};
pp$5.parseSubscripts = function(base2, startPos, startLoc, noCalls, forInit) {
  var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base2.type === "Identifier" && base2.name === "async" && this.lastTokEnd === base2.end && !this.canInsertSemicolon() && base2.end - base2.start === 5 && this.potentialArrowAt === base2.start;
  var optionalChained = false;
  while (true) {
    var element = this.parseSubscript(base2, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit);
    if (element.optional) {
      optionalChained = true;
    }
    if (element === base2 || element.type === "ArrowFunctionExpression") {
      if (optionalChained) {
        var chainNode = this.startNodeAt(startPos, startLoc);
        chainNode.expression = element;
        element = this.finishNode(chainNode, "ChainExpression");
      }
      return element;
    }
    base2 = element;
  }
};
pp$5.shouldParseAsyncArrow = function() {
  return !this.canInsertSemicolon() && this.eat(types$1.arrow);
};
pp$5.parseSubscriptAsyncArrow = function(startPos, startLoc, exprList, forInit) {
  return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit);
};
pp$5.parseSubscript = function(base2, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {
  var optionalSupported = this.options.ecmaVersion >= 11;
  var optional = optionalSupported && this.eat(types$1.questionDot);
  if (noCalls && optional) {
    this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions");
  }
  var computed = this.eat(types$1.bracketL);
  if (computed || optional && this.type !== types$1.parenL && this.type !== types$1.backQuote || this.eat(types$1.dot)) {
    var node2 = this.startNodeAt(startPos, startLoc);
    node2.object = base2;
    if (computed) {
      node2.property = this.parseExpression();
      this.expect(types$1.bracketR);
    } else if (this.type === types$1.privateId && base2.type !== "Super") {
      node2.property = this.parsePrivateIdent();
    } else {
      node2.property = this.parseIdent(this.options.allowReserved !== "never");
    }
    node2.computed = !!computed;
    if (optionalSupported) {
      node2.optional = optional;
    }
    base2 = this.finishNode(node2, "MemberExpression");
  } else if (!noCalls && this.eat(types$1.parenL)) {
    var refDestructuringErrors = new DestructuringErrors(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
    this.yieldPos = 0;
    this.awaitPos = 0;
    this.awaitIdentPos = 0;
    var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
    if (maybeAsyncArrow && !optional && this.shouldParseAsyncArrow()) {
      this.checkPatternErrors(refDestructuringErrors, false);
      this.checkYieldAwaitInDefaultParams();
      if (this.awaitIdentPos > 0) {
        this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function");
      }
      this.yieldPos = oldYieldPos;
      this.awaitPos = oldAwaitPos;
      this.awaitIdentPos = oldAwaitIdentPos;
      return this.parseSubscriptAsyncArrow(startPos, startLoc, exprList, forInit);
    }
    this.checkExpressionErrors(refDestructuringErrors, true);
    this.yieldPos = oldYieldPos || this.yieldPos;
    this.awaitPos = oldAwaitPos || this.awaitPos;
    this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
    var node$1 = this.startNodeAt(startPos, startLoc);
    node$1.callee = base2;
    node$1.arguments = exprList;
    if (optionalSupported) {
      node$1.optional = optional;
    }
    base2 = this.finishNode(node$1, "CallExpression");
  } else if (this.type === types$1.backQuote) {
    if (optional || optionalChained) {
      this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
    }
    var node$2 = this.startNodeAt(startPos, startLoc);
    node$2.tag = base2;
    node$2.quasi = this.parseTemplate({ isTagged: true });
    base2 = this.finishNode(node$2, "TaggedTemplateExpression");
  }
  return base2;
};
pp$5.parseExprAtom = function(refDestructuringErrors, forInit, forNew) {
  if (this.type === types$1.slash) {
    this.readRegexp();
  }
  var node2, canBeArrow = this.potentialArrowAt === this.start;
  switch (this.type) {
    case types$1._super:
      if (!this.allowSuper) {
        this.raise(this.start, "'super' keyword outside a method");
      }
      node2 = this.startNode();
      this.next();
      if (this.type === types$1.parenL && !this.allowDirectSuper) {
        this.raise(node2.start, "super() call outside constructor of a subclass");
      }
      if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL) {
        this.unexpected();
      }
      return this.finishNode(node2, "Super");
    case types$1._this:
      node2 = this.startNode();
      this.next();
      return this.finishNode(node2, "ThisExpression");
    case types$1.name:
      var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
      var id2 = this.parseIdent(false);
      if (this.options.ecmaVersion >= 8 && !containsEsc && id2.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) {
        this.overrideContext(types.f_expr);
        return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit);
      }
      if (canBeArrow && !this.canInsertSemicolon()) {
        if (this.eat(types$1.arrow)) {
          return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id2], false, forInit);
        }
        if (this.options.ecmaVersion >= 8 && id2.name === "async" && this.type === types$1.name && !containsEsc && (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
          id2 = this.parseIdent(false);
          if (this.canInsertSemicolon() || !this.eat(types$1.arrow)) {
            this.unexpected();
          }
          return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id2], true, forInit);
        }
      }
      return id2;
    case types$1.regexp:
      var value2 = this.value;
      node2 = this.parseLiteral(value2.value);
      node2.regex = { pattern: value2.pattern, flags: value2.flags };
      return node2;
    case types$1.num:
    case types$1.string:
      return this.parseLiteral(this.value);
    case types$1._null:
    case types$1._true:
    case types$1._false:
      node2 = this.startNode();
      node2.value = this.type === types$1._null ? null : this.type === types$1._true;
      node2.raw = this.type.keyword;
      this.next();
      return this.finishNode(node2, "Literal");
    case types$1.parenL:
      var start2 = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit);
      if (refDestructuringErrors) {
        if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) {
          refDestructuringErrors.parenthesizedAssign = start2;
        }
        if (refDestructuringErrors.parenthesizedBind < 0) {
          refDestructuringErrors.parenthesizedBind = start2;
        }
      }
      return expr;
    case types$1.bracketL:
      node2 = this.startNode();
      this.next();
      node2.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors);
      return this.finishNode(node2, "ArrayExpression");
    case types$1.braceL:
      this.overrideContext(types.b_expr);
      return this.parseObj(false, refDestructuringErrors);
    case types$1._function:
      node2 = this.startNode();
      this.next();
      return this.parseFunction(node2, 0);
    case types$1._class:
      return this.parseClass(this.startNode(), false);
    case types$1._new:
      return this.parseNew();
    case types$1.backQuote:
      return this.parseTemplate();
    case types$1._import:
      if (this.options.ecmaVersion >= 11) {
        return this.parseExprImport(forNew);
      } else {
        return this.unexpected();
      }
    default:
      return this.parseExprAtomDefault();
  }
};
pp$5.parseExprAtomDefault = function() {
  this.unexpected();
};
pp$5.parseExprImport = function(forNew) {
  var node2 = this.startNode();
  if (this.containsEsc) {
    this.raiseRecoverable(this.start, "Escape sequence in keyword import");
  }
  this.next();
  if (this.type === types$1.parenL && !forNew) {
    return this.parseDynamicImport(node2);
  } else if (this.type === types$1.dot) {
    var meta = this.startNodeAt(node2.start, node2.loc && node2.loc.start);
    meta.name = "import";
    node2.meta = this.finishNode(meta, "Identifier");
    return this.parseImportMeta(node2);
  } else {
    this.unexpected();
  }
};
pp$5.parseDynamicImport = function(node2) {
  this.next();
  node2.source = this.parseMaybeAssign();
  if (this.options.ecmaVersion >= 16) {
    if (!this.eat(types$1.parenR)) {
      this.expect(types$1.comma);
      if (!this.afterTrailingComma(types$1.parenR)) {
        node2.options = this.parseMaybeAssign();
        if (!this.eat(types$1.parenR)) {
          this.expect(types$1.comma);
          if (!this.afterTrailingComma(types$1.parenR)) {
            this.unexpected();
          }
        }
      } else {
        node2.options = null;
      }
    } else {
      node2.options = null;
    }
  } else {
    if (!this.eat(types$1.parenR)) {
      var errorPos = this.start;
      if (this.eat(types$1.comma) && this.eat(types$1.parenR)) {
        this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
      } else {
        this.unexpected(errorPos);
      }
    }
  }
  return this.finishNode(node2, "ImportExpression");
};
pp$5.parseImportMeta = function(node2) {
  this.next();
  var containsEsc = this.containsEsc;
  node2.property = this.parseIdent(true);
  if (node2.property.name !== "meta") {
    this.raiseRecoverable(node2.property.start, "The only valid meta property for import is 'import.meta'");
  }
  if (containsEsc) {
    this.raiseRecoverable(node2.start, "'import.meta' must not contain escaped characters");
  }
  if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) {
    this.raiseRecoverable(node2.start, "Cannot use 'import.meta' outside a module");
  }
  return this.finishNode(node2, "MetaProperty");
};
pp$5.parseLiteral = function(value2) {
  var node2 = this.startNode();
  node2.value = value2;
  node2.raw = this.input.slice(this.start, this.end);
  if (node2.raw.charCodeAt(node2.raw.length - 1) === 110) {
    node2.bigint = node2.value != null ? node2.value.toString() : node2.raw.slice(0, -1).replace(/_/g, "");
  }
  this.next();
  return this.finishNode(node2, "Literal");
};
pp$5.parseParenExpression = function() {
  this.expect(types$1.parenL);
  var val = this.parseExpression();
  this.expect(types$1.parenR);
  return val;
};
pp$5.shouldParseArrow = function(exprList) {
  return !this.canInsertSemicolon();
};
pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) {
  var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
  if (this.options.ecmaVersion >= 6) {
    this.next();
    var innerStartPos = this.start, innerStartLoc = this.startLoc;
    var exprList = [], first2 = true, lastIsComma = false;
    var refDestructuringErrors = new DestructuringErrors(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
    this.yieldPos = 0;
    this.awaitPos = 0;
    while (this.type !== types$1.parenR) {
      first2 ? first2 = false : this.expect(types$1.comma);
      if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) {
        lastIsComma = true;
        break;
      } else if (this.type === types$1.ellipsis) {
        spreadStart = this.start;
        exprList.push(this.parseParenItem(this.parseRestBinding()));
        if (this.type === types$1.comma) {
          this.raiseRecoverable(
            this.start,
            "Comma is not permitted after the rest element"
          );
        }
        break;
      } else {
        exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
      }
    }
    var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc;
    this.expect(types$1.parenR);
    if (canBeArrow && this.shouldParseArrow(exprList) && this.eat(types$1.arrow)) {
      this.checkPatternErrors(refDestructuringErrors, false);
      this.checkYieldAwaitInDefaultParams();
      this.yieldPos = oldYieldPos;
      this.awaitPos = oldAwaitPos;
      return this.parseParenArrowList(startPos, startLoc, exprList, forInit);
    }
    if (!exprList.length || lastIsComma) {
      this.unexpected(this.lastTokStart);
    }
    if (spreadStart) {
      this.unexpected(spreadStart);
    }
    this.checkExpressionErrors(refDestructuringErrors, true);
    this.yieldPos = oldYieldPos || this.yieldPos;
    this.awaitPos = oldAwaitPos || this.awaitPos;
    if (exprList.length > 1) {
      val = this.startNodeAt(innerStartPos, innerStartLoc);
      val.expressions = exprList;
      this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
    } else {
      val = exprList[0];
    }
  } else {
    val = this.parseParenExpression();
  }
  if (this.options.preserveParens) {
    var par = this.startNodeAt(startPos, startLoc);
    par.expression = val;
    return this.finishNode(par, "ParenthesizedExpression");
  } else {
    return val;
  }
};
pp$5.parseParenItem = function(item2) {
  return item2;
};
pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) {
  return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit);
};
var empty = [];
pp$5.parseNew = function() {
  if (this.containsEsc) {
    this.raiseRecoverable(this.start, "Escape sequence in keyword new");
  }
  var node2 = this.startNode();
  this.next();
  if (this.options.ecmaVersion >= 6 && this.type === types$1.dot) {
    var meta = this.startNodeAt(node2.start, node2.loc && node2.loc.start);
    meta.name = "new";
    node2.meta = this.finishNode(meta, "Identifier");
    this.next();
    var containsEsc = this.containsEsc;
    node2.property = this.parseIdent(true);
    if (node2.property.name !== "target") {
      this.raiseRecoverable(node2.property.start, "The only valid meta property for new is 'new.target'");
    }
    if (containsEsc) {
      this.raiseRecoverable(node2.start, "'new.target' must not contain escaped characters");
    }
    if (!this.allowNewDotTarget) {
      this.raiseRecoverable(node2.start, "'new.target' can only be used in functions and class static block");
    }
    return this.finishNode(node2, "MetaProperty");
  }
  var startPos = this.start, startLoc = this.startLoc;
  node2.callee = this.parseSubscripts(this.parseExprAtom(null, false, true), startPos, startLoc, true, false);
  if (this.eat(types$1.parenL)) {
    node2.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false);
  } else {
    node2.arguments = empty;
  }
  return this.finishNode(node2, "NewExpression");
};
pp$5.parseTemplateElement = function(ref2) {
  var isTagged = ref2.isTagged;
  var elem = this.startNode();
  if (this.type === types$1.invalidTemplate) {
    if (!isTagged) {
      this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
    }
    elem.value = {
      raw: this.value.replace(/\r\n?/g, "\n"),
      cooked: null
    };
  } else {
    elem.value = {
      raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
      cooked: this.value
    };
  }
  this.next();
  elem.tail = this.type === types$1.backQuote;
  return this.finishNode(elem, "TemplateElement");
};
pp$5.parseTemplate = function(ref2) {
  if (ref2 === void 0) ref2 = {};
  var isTagged = ref2.isTagged;
  if (isTagged === void 0) isTagged = false;
  var node2 = this.startNode();
  this.next();
  node2.expressions = [];
  var curElt = this.parseTemplateElement({ isTagged });
  node2.quasis = [curElt];
  while (!curElt.tail) {
    if (this.type === types$1.eof) {
      this.raise(this.pos, "Unterminated template literal");
    }
    this.expect(types$1.dollarBraceL);
    node2.expressions.push(this.parseExpression());
    this.expect(types$1.braceR);
    node2.quasis.push(curElt = this.parseTemplateElement({ isTagged }));
  }
  this.next();
  return this.finishNode(node2, "TemplateLiteral");
};
pp$5.isAsyncProp = function(prop) {
  return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && (this.type === types$1.name || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword || this.options.ecmaVersion >= 9 && this.type === types$1.star) && !lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
};
pp$5.parseObj = function(isPattern, refDestructuringErrors) {
  var node2 = this.startNode(), first2 = true, propHash = {};
  node2.properties = [];
  this.next();
  while (!this.eat(types$1.braceR)) {
    if (!first2) {
      this.expect(types$1.comma);
      if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) {
        break;
      }
    } else {
      first2 = false;
    }
    var prop = this.parseProperty(isPattern, refDestructuringErrors);
    if (!isPattern) {
      this.checkPropClash(prop, propHash, refDestructuringErrors);
    }
    node2.properties.push(prop);
  }
  return this.finishNode(node2, isPattern ? "ObjectPattern" : "ObjectExpression");
};
pp$5.parseProperty = function(isPattern, refDestructuringErrors) {
  var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
  if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) {
    if (isPattern) {
      prop.argument = this.parseIdent(false);
      if (this.type === types$1.comma) {
        this.raiseRecoverable(this.start, "Comma is not permitted after the rest element");
      }
      return this.finishNode(prop, "RestElement");
    }
    prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
    if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
      refDestructuringErrors.trailingComma = this.start;
    }
    return this.finishNode(prop, "SpreadElement");
  }
  if (this.options.ecmaVersion >= 6) {
    prop.method = false;
    prop.shorthand = false;
    if (isPattern || refDestructuringErrors) {
      startPos = this.start;
      startLoc = this.startLoc;
    }
    if (!isPattern) {
      isGenerator = this.eat(types$1.star);
    }
  }
  var containsEsc = this.containsEsc;
  this.parsePropertyName(prop);
  if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
    isAsync = true;
    isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star);
    this.parsePropertyName(prop);
  } else {
    isAsync = false;
  }
  this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
  return this.finishNode(prop, "Property");
};
pp$5.parseGetterSetter = function(prop) {
  var kind = prop.key.name;
  this.parsePropertyName(prop);
  prop.value = this.parseMethod(false);
  prop.kind = kind;
  var paramCount = prop.kind === "get" ? 0 : 1;
  if (prop.value.params.length !== paramCount) {
    var start2 = prop.value.start;
    if (prop.kind === "get") {
      this.raiseRecoverable(start2, "getter should have no params");
    } else {
      this.raiseRecoverable(start2, "setter should have exactly one param");
    }
  } else {
    if (prop.kind === "set" && prop.value.params[0].type === "RestElement") {
      this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params");
    }
  }
};
pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
  if ((isGenerator || isAsync) && this.type === types$1.colon) {
    this.unexpected();
  }
  if (this.eat(types$1.colon)) {
    prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
    prop.kind = "init";
  } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) {
    if (isPattern) {
      this.unexpected();
    }
    prop.method = true;
    prop.value = this.parseMethod(isGenerator, isAsync);
    prop.kind = "init";
  } else if (!isPattern && !containsEsc && this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) {
    if (isGenerator || isAsync) {
      this.unexpected();
    }
    this.parseGetterSetter(prop);
  } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
    if (isGenerator || isAsync) {
      this.unexpected();
    }
    this.checkUnreserved(prop.key);
    if (prop.key.name === "await" && !this.awaitIdentPos) {
      this.awaitIdentPos = startPos;
    }
    if (isPattern) {
      prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
    } else if (this.type === types$1.eq && refDestructuringErrors) {
      if (refDestructuringErrors.shorthandAssign < 0) {
        refDestructuringErrors.shorthandAssign = this.start;
      }
      prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
    } else {
      prop.value = this.copyNode(prop.key);
    }
    prop.kind = "init";
    prop.shorthand = true;
  } else {
    this.unexpected();
  }
};
pp$5.parsePropertyName = function(prop) {
  if (this.options.ecmaVersion >= 6) {
    if (this.eat(types$1.bracketL)) {
      prop.computed = true;
      prop.key = this.parseMaybeAssign();
      this.expect(types$1.bracketR);
      return prop.key;
    } else {
      prop.computed = false;
    }
  }
  return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never");
};
pp$5.initFunction = function(node2) {
  node2.id = null;
  if (this.options.ecmaVersion >= 6) {
    node2.generator = node2.expression = false;
  }
  if (this.options.ecmaVersion >= 8) {
    node2.async = false;
  }
};
pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
  var node2 = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  this.initFunction(node2);
  if (this.options.ecmaVersion >= 6) {
    node2.generator = isGenerator;
  }
  if (this.options.ecmaVersion >= 8) {
    node2.async = !!isAsync;
  }
  this.yieldPos = 0;
  this.awaitPos = 0;
  this.awaitIdentPos = 0;
  this.enterScope(functionFlags(isAsync, node2.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  this.expect(types$1.parenL);
  node2.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  this.checkYieldAwaitInDefaultParams();
  this.parseFunctionBody(node2, false, true, false);
  this.yieldPos = oldYieldPos;
  this.awaitPos = oldAwaitPos;
  this.awaitIdentPos = oldAwaitIdentPos;
  return this.finishNode(node2, "FunctionExpression");
};
pp$5.parseArrowExpression = function(node2, params, isAsync, forInit) {
  var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
  this.initFunction(node2);
  if (this.options.ecmaVersion >= 8) {
    node2.async = !!isAsync;
  }
  this.yieldPos = 0;
  this.awaitPos = 0;
  this.awaitIdentPos = 0;
  node2.params = this.toAssignableList(params, true);
  this.parseFunctionBody(node2, true, false, forInit);
  this.yieldPos = oldYieldPos;
  this.awaitPos = oldAwaitPos;
  this.awaitIdentPos = oldAwaitIdentPos;
  return this.finishNode(node2, "ArrowFunctionExpression");
};
pp$5.parseFunctionBody = function(node2, isArrowFunction, isMethod, forInit) {
  var isExpression = isArrowFunction && this.type !== types$1.braceL;
  var oldStrict = this.strict, useStrict = false;
  if (isExpression) {
    node2.body = this.parseMaybeAssign(forInit);
    node2.expression = true;
    this.checkParams(node2, false);
  } else {
    var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node2.params);
    if (!oldStrict || nonSimple) {
      useStrict = this.strictDirective(this.end);
      if (useStrict && nonSimple) {
        this.raiseRecoverable(node2.start, "Illegal 'use strict' directive in function with non-simple parameter list");
      }
    }
    var oldLabels = this.labels;
    this.labels = [];
    if (useStrict) {
      this.strict = true;
    }
    this.checkParams(node2, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node2.params));
    if (this.strict && node2.id) {
      this.checkLValSimple(node2.id, BIND_OUTSIDE);
    }
    node2.body = this.parseBlock(false, void 0, useStrict && !oldStrict);
    node2.expression = false;
    this.adaptDirectivePrologue(node2.body.body);
    this.labels = oldLabels;
  }
  this.exitScope();
};
pp$5.isSimpleParamList = function(params) {
  for (var i2 = 0, list2 = params; i2 < list2.length; i2 += 1) {
    var param = list2[i2];
    if (param.type !== "Identifier") {
      return false;
    }
  }
  return true;
};
pp$5.checkParams = function(node2, allowDuplicates) {
  var nameHash = /* @__PURE__ */ Object.create(null);
  for (var i2 = 0, list2 = node2.params; i2 < list2.length; i2 += 1) {
    var param = list2[i2];
    this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
  }
};
pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  var elts = [], first2 = true;
  while (!this.eat(close)) {
    if (!first2) {
      this.expect(types$1.comma);
      if (allowTrailingComma && this.afterTrailingComma(close)) {
        break;
      }
    } else {
      first2 = false;
    }
    var elt = void 0;
    if (allowEmpty && this.type === types$1.comma) {
      elt = null;
    } else if (this.type === types$1.ellipsis) {
      elt = this.parseSpread(refDestructuringErrors);
      if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0) {
        refDestructuringErrors.trailingComma = this.start;
      }
    } else {
      elt = this.parseMaybeAssign(false, refDestructuringErrors);
    }
    elts.push(elt);
  }
  return elts;
};
pp$5.checkUnreserved = function(ref2) {
  var start2 = ref2.start;
  var end2 = ref2.end;
  var name2 = ref2.name;
  if (this.inGenerator && name2 === "yield") {
    this.raiseRecoverable(start2, "Cannot use 'yield' as identifier inside a generator");
  }
  if (this.inAsync && name2 === "await") {
    this.raiseRecoverable(start2, "Cannot use 'await' as identifier inside an async function");
  }
  if (!(this.currentThisScope().flags & SCOPE_VAR) && name2 === "arguments") {
    this.raiseRecoverable(start2, "Cannot use 'arguments' in class field initializer");
  }
  if (this.inClassStaticBlock && (name2 === "arguments" || name2 === "await")) {
    this.raise(start2, "Cannot use " + name2 + " in class static initialization block");
  }
  if (this.keywords.test(name2)) {
    this.raise(start2, "Unexpected keyword '" + name2 + "'");
  }
  if (this.options.ecmaVersion < 6 && this.input.slice(start2, end2).indexOf("\\") !== -1) {
    return;
  }
  var re2 = this.strict ? this.reservedWordsStrict : this.reservedWords;
  if (re2.test(name2)) {
    if (!this.inAsync && name2 === "await") {
      this.raiseRecoverable(start2, "Cannot use keyword 'await' outside an async function");
    }
    this.raiseRecoverable(start2, "The keyword '" + name2 + "' is reserved");
  }
};
pp$5.parseIdent = function(liberal) {
  var node2 = this.parseIdentNode();
  this.next(!!liberal);
  this.finishNode(node2, "Identifier");
  if (!liberal) {
    this.checkUnreserved(node2);
    if (node2.name === "await" && !this.awaitIdentPos) {
      this.awaitIdentPos = node2.start;
    }
  }
  return node2;
};
pp$5.parseIdentNode = function() {
  var node2 = this.startNode();
  if (this.type === types$1.name) {
    node2.name = this.value;
  } else if (this.type.keyword) {
    node2.name = this.type.keyword;
    if ((node2.name === "class" || node2.name === "function") && (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
      this.context.pop();
    }
    this.type = types$1.name;
  } else {
    this.unexpected();
  }
  return node2;
};
pp$5.parsePrivateIdent = function() {
  var node2 = this.startNode();
  if (this.type === types$1.privateId) {
    node2.name = this.value;
  } else {
    this.unexpected();
  }
  this.next();
  this.finishNode(node2, "PrivateIdentifier");
  if (this.options.checkPrivateFields) {
    if (this.privateNameStack.length === 0) {
      this.raise(node2.start, "Private field '#" + node2.name + "' must be declared in an enclosing class");
    } else {
      this.privateNameStack[this.privateNameStack.length - 1].used.push(node2);
    }
  }
  return node2;
};
pp$5.parseYield = function(forInit) {
  if (!this.yieldPos) {
    this.yieldPos = this.start;
  }
  var node2 = this.startNode();
  this.next();
  if (this.type === types$1.semi || this.canInsertSemicolon() || this.type !== types$1.star && !this.type.startsExpr) {
    node2.delegate = false;
    node2.argument = null;
  } else {
    node2.delegate = this.eat(types$1.star);
    node2.argument = this.parseMaybeAssign(forInit);
  }
  return this.finishNode(node2, "YieldExpression");
};
pp$5.parseAwait = function(forInit) {
  if (!this.awaitPos) {
    this.awaitPos = this.start;
  }
  var node2 = this.startNode();
  this.next();
  node2.argument = this.parseMaybeUnary(null, true, false, forInit);
  return this.finishNode(node2, "AwaitExpression");
};
var pp$4 = Parser.prototype;
pp$4.raise = function(pos2, message2) {
  var loc = getLineInfo(this.input, pos2);
  message2 += " (" + loc.line + ":" + loc.column + ")";
  if (this.sourceFile) {
    message2 += " in " + this.sourceFile;
  }
  var err = new SyntaxError(message2);
  err.pos = pos2;
  err.loc = loc;
  err.raisedAt = this.pos;
  throw err;
};
pp$4.raiseRecoverable = pp$4.raise;
pp$4.curPosition = function() {
  if (this.options.locations) {
    return new Position(this.curLine, this.pos - this.lineStart);
  }
};
var pp$3 = Parser.prototype;
var Scope = function Scope2(flags) {
  this.flags = flags;
  this.var = [];
  this.lexical = [];
  this.functions = [];
};
pp$3.enterScope = function(flags) {
  this.scopeStack.push(new Scope(flags));
};
pp$3.exitScope = function() {
  this.scopeStack.pop();
};
pp$3.treatFunctionsAsVarInScope = function(scope) {
  return scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_TOP;
};
pp$3.declareName = function(name2, bindingType, pos2) {
  var redeclared = false;
  if (bindingType === BIND_LEXICAL) {
    var scope = this.currentScope();
    redeclared = scope.lexical.indexOf(name2) > -1 || scope.functions.indexOf(name2) > -1 || scope.var.indexOf(name2) > -1;
    scope.lexical.push(name2);
    if (this.inModule && scope.flags & SCOPE_TOP) {
      delete this.undefinedExports[name2];
    }
  } else if (bindingType === BIND_SIMPLE_CATCH) {
    var scope$1 = this.currentScope();
    scope$1.lexical.push(name2);
  } else if (bindingType === BIND_FUNCTION) {
    var scope$2 = this.currentScope();
    if (this.treatFunctionsAsVar) {
      redeclared = scope$2.lexical.indexOf(name2) > -1;
    } else {
      redeclared = scope$2.lexical.indexOf(name2) > -1 || scope$2.var.indexOf(name2) > -1;
    }
    scope$2.functions.push(name2);
  } else {
    for (var i2 = this.scopeStack.length - 1; i2 >= 0; --i2) {
      var scope$3 = this.scopeStack[i2];
      if (scope$3.lexical.indexOf(name2) > -1 && !(scope$3.flags & SCOPE_SIMPLE_CATCH && scope$3.lexical[0] === name2) || !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name2) > -1) {
        redeclared = true;
        break;
      }
      scope$3.var.push(name2);
      if (this.inModule && scope$3.flags & SCOPE_TOP) {
        delete this.undefinedExports[name2];
      }
      if (scope$3.flags & SCOPE_VAR) {
        break;
      }
    }
  }
  if (redeclared) {
    this.raiseRecoverable(pos2, "Identifier '" + name2 + "' has already been declared");
  }
};
pp$3.checkLocalExport = function(id2) {
  if (this.scopeStack[0].lexical.indexOf(id2.name) === -1 && this.scopeStack[0].var.indexOf(id2.name) === -1) {
    this.undefinedExports[id2.name] = id2;
  }
};
pp$3.currentScope = function() {
  return this.scopeStack[this.scopeStack.length - 1];
};
pp$3.currentVarScope = function() {
  for (var i2 = this.scopeStack.length - 1; ; i2--) {
    var scope = this.scopeStack[i2];
    if (scope.flags & (SCOPE_VAR | SCOPE_CLASS_FIELD_INIT | SCOPE_CLASS_STATIC_BLOCK)) {
      return scope;
    }
  }
};
pp$3.currentThisScope = function() {
  for (var i2 = this.scopeStack.length - 1; ; i2--) {
    var scope = this.scopeStack[i2];
    if (scope.flags & (SCOPE_VAR | SCOPE_CLASS_FIELD_INIT | SCOPE_CLASS_STATIC_BLOCK) && !(scope.flags & SCOPE_ARROW)) {
      return scope;
    }
  }
};
var Node$1 = function Node2(parser, pos2, loc) {
  this.type = "";
  this.start = pos2;
  this.end = 0;
  if (parser.options.locations) {
    this.loc = new SourceLocation(parser, loc);
  }
  if (parser.options.directSourceFile) {
    this.sourceFile = parser.options.directSourceFile;
  }
  if (parser.options.ranges) {
    this.range = [pos2, 0];
  }
};
var pp$2 = Parser.prototype;
pp$2.startNode = function() {
  return new Node$1(this, this.start, this.startLoc);
};
pp$2.startNodeAt = function(pos2, loc) {
  return new Node$1(this, pos2, loc);
};
function finishNodeAt(node2, type, pos2, loc) {
  node2.type = type;
  node2.end = pos2;
  if (this.options.locations) {
    node2.loc.end = loc;
  }
  if (this.options.ranges) {
    node2.range[1] = pos2;
  }
  return node2;
}
pp$2.finishNode = function(node2, type) {
  return finishNodeAt.call(this, node2, type, this.lastTokEnd, this.lastTokEndLoc);
};
pp$2.finishNodeAt = function(node2, type, pos2, loc) {
  return finishNodeAt.call(this, node2, type, pos2, loc);
};
pp$2.copyNode = function(node2) {
  var newNode = new Node$1(this, node2.start, this.startLoc);
  for (var prop in node2) {
    newNode[prop] = node2[prop];
  }
  return newNode;
};
var scriptValuesAddedInUnicode = "Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz";
var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";
var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
var ecma11BinaryProperties = ecma10BinaryProperties;
var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
var ecma13BinaryProperties = ecma12BinaryProperties;
var ecma14BinaryProperties = ecma13BinaryProperties;
var unicodeBinaryProperties = {
  9: ecma9BinaryProperties,
  10: ecma10BinaryProperties,
  11: ecma11BinaryProperties,
  12: ecma12BinaryProperties,
  13: ecma13BinaryProperties,
  14: ecma14BinaryProperties
};
var ecma14BinaryPropertiesOfStrings = "Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji";
var unicodeBinaryPropertiesOfStrings = {
  9: "",
  10: "",
  11: "",
  12: "",
  13: "",
  14: ecma14BinaryPropertiesOfStrings
};
var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";
var ecma9ScriptValues = "Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";
var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith";
var ecma14ScriptValues = ecma13ScriptValues + " " + scriptValuesAddedInUnicode;
var unicodeScriptValues = {
  9: ecma9ScriptValues,
  10: ecma10ScriptValues,
  11: ecma11ScriptValues,
  12: ecma12ScriptValues,
  13: ecma13ScriptValues,
  14: ecma14ScriptValues
};
var data = {};
function buildUnicodeData(ecmaVersion) {
  var d = data[ecmaVersion] = {
    binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
    binaryOfStrings: wordsRegexp(unicodeBinaryPropertiesOfStrings[ecmaVersion]),
    nonBinary: {
      General_Category: wordsRegexp(unicodeGeneralCategoryValues),
      Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
    }
  };
  d.nonBinary.Script_Extensions = d.nonBinary.Script;
  d.nonBinary.gc = d.nonBinary.General_Category;
  d.nonBinary.sc = d.nonBinary.Script;
  d.nonBinary.scx = d.nonBinary.Script_Extensions;
}
for (var i$1 = 0, list$2 = [9, 10, 11, 12, 13, 14]; i$1 < list$2.length; i$1 += 1) {
  var ecmaVersion = list$2[i$1];
  buildUnicodeData(ecmaVersion);
}
var pp$1 = Parser.prototype;
var BranchID = function BranchID2(parent, base2) {
  this.parent = parent;
  this.base = base2 || this;
};
BranchID.prototype.separatedFrom = function separatedFrom(alt) {
  for (var self2 = this; self2; self2 = self2.parent) {
    for (var other = alt; other; other = other.parent) {
      if (self2.base === other.base && self2 !== other) {
        return true;
      }
    }
  }
  return false;
};
BranchID.prototype.sibling = function sibling() {
  return new BranchID(this.parent, this.base);
};
var RegExpValidationState = function RegExpValidationState2(parser) {
  this.parser = parser;
  this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "") + (parser.options.ecmaVersion >= 15 ? "v" : "");
  this.unicodeProperties = data[parser.options.ecmaVersion >= 14 ? 14 : parser.options.ecmaVersion];
  this.source = "";
  this.flags = "";
  this.start = 0;
  this.switchU = false;
  this.switchV = false;
  this.switchN = false;
  this.pos = 0;
  this.lastIntValue = 0;
  this.lastStringValue = "";
  this.lastAssertionIsQuantifiable = false;
  this.numCapturingParens = 0;
  this.maxBackReference = 0;
  this.groupNames = /* @__PURE__ */ Object.create(null);
  this.backReferenceNames = [];
  this.branchID = null;
};
RegExpValidationState.prototype.reset = function reset(start2, pattern, flags) {
  var unicodeSets = flags.indexOf("v") !== -1;
  var unicode2 = flags.indexOf("u") !== -1;
  this.start = start2 | 0;
  this.source = pattern + "";
  this.flags = flags;
  if (unicodeSets && this.parser.options.ecmaVersion >= 15) {
    this.switchU = true;
    this.switchV = true;
    this.switchN = true;
  } else {
    this.switchU = unicode2 && this.parser.options.ecmaVersion >= 6;
    this.switchV = false;
    this.switchN = unicode2 && this.parser.options.ecmaVersion >= 9;
  }
};
RegExpValidationState.prototype.raise = function raise(message2) {
  this.parser.raiseRecoverable(this.start, "Invalid regular expression: /" + this.source + "/: " + message2);
};
RegExpValidationState.prototype.at = function at(i2, forceU) {
  if (forceU === void 0) forceU = false;
  var s = this.source;
  var l2 = s.length;
  if (i2 >= l2) {
    return -1;
  }
  var c2 = s.charCodeAt(i2);
  if (!(forceU || this.switchU) || c2 <= 55295 || c2 >= 57344 || i2 + 1 >= l2) {
    return c2;
  }
  var next = s.charCodeAt(i2 + 1);
  return next >= 56320 && next <= 57343 ? (c2 << 10) + next - 56613888 : c2;
};
RegExpValidationState.prototype.nextIndex = function nextIndex(i2, forceU) {
  if (forceU === void 0) forceU = false;
  var s = this.source;
  var l2 = s.length;
  if (i2 >= l2) {
    return l2;
  }
  var c2 = s.charCodeAt(i2), next;
  if (!(forceU || this.switchU) || c2 <= 55295 || c2 >= 57344 || i2 + 1 >= l2 || (next = s.charCodeAt(i2 + 1)) < 56320 || next > 57343) {
    return i2 + 1;
  }
  return i2 + 2;
};
RegExpValidationState.prototype.current = function current2(forceU) {
  if (forceU === void 0) forceU = false;
  return this.at(this.pos, forceU);
};
RegExpValidationState.prototype.lookahead = function lookahead(forceU) {
  if (forceU === void 0) forceU = false;
  return this.at(this.nextIndex(this.pos, forceU), forceU);
};
RegExpValidationState.prototype.advance = function advance(forceU) {
  if (forceU === void 0) forceU = false;
  this.pos = this.nextIndex(this.pos, forceU);
};
RegExpValidationState.prototype.eat = function eat(ch, forceU) {
  if (forceU === void 0) forceU = false;
  if (this.current(forceU) === ch) {
    this.advance(forceU);
    return true;
  }
  return false;
};
RegExpValidationState.prototype.eatChars = function eatChars(chs, forceU) {
  if (forceU === void 0) forceU = false;
  var pos2 = this.pos;
  for (var i2 = 0, list2 = chs; i2 < list2.length; i2 += 1) {
    var ch = list2[i2];
    var current3 = this.at(pos2, forceU);
    if (current3 === -1 || current3 !== ch) {
      return false;
    }
    pos2 = this.nextIndex(pos2, forceU);
  }
  this.pos = pos2;
  return true;
};
pp$1.validateRegExpFlags = function(state) {
  var validFlags = state.validFlags;
  var flags = state.flags;
  var u = false;
  var v = false;
  for (var i2 = 0; i2 < flags.length; i2++) {
    var flag = flags.charAt(i2);
    if (validFlags.indexOf(flag) === -1) {
      this.raise(state.start, "Invalid regular expression flag");
    }
    if (flags.indexOf(flag, i2 + 1) > -1) {
      this.raise(state.start, "Duplicate regular expression flag");
    }
    if (flag === "u") {
      u = true;
    }
    if (flag === "v") {
      v = true;
    }
  }
  if (this.options.ecmaVersion >= 15 && u && v) {
    this.raise(state.start, "Invalid regular expression flag");
  }
};
function hasProp(obj) {
  for (var _ in obj) {
    return true;
  }
  return false;
}
pp$1.validateRegExpPattern = function(state) {
  this.regexp_pattern(state);
  if (!state.switchN && this.options.ecmaVersion >= 9 && hasProp(state.groupNames)) {
    state.switchN = true;
    this.regexp_pattern(state);
  }
};
pp$1.regexp_pattern = function(state) {
  state.pos = 0;
  state.lastIntValue = 0;
  state.lastStringValue = "";
  state.lastAssertionIsQuantifiable = false;
  state.numCapturingParens = 0;
  state.maxBackReference = 0;
  state.groupNames = /* @__PURE__ */ Object.create(null);
  state.backReferenceNames.length = 0;
  state.branchID = null;
  this.regexp_disjunction(state);
  if (state.pos !== state.source.length) {
    if (state.eat(
      41
      /* ) */
    )) {
      state.raise("Unmatched ')'");
    }
    if (state.eat(
      93
      /* ] */
    ) || state.eat(
      125
      /* } */
    )) {
      state.raise("Lone quantifier brackets");
    }
  }
  if (state.maxBackReference > state.numCapturingParens) {
    state.raise("Invalid escape");
  }
  for (var i2 = 0, list2 = state.backReferenceNames; i2 < list2.length; i2 += 1) {
    var name2 = list2[i2];
    if (!state.groupNames[name2]) {
      state.raise("Invalid named capture referenced");
    }
  }
};
pp$1.regexp_disjunction = function(state) {
  var trackDisjunction = this.options.ecmaVersion >= 16;
  if (trackDisjunction) {
    state.branchID = new BranchID(state.branchID, null);
  }
  this.regexp_alternative(state);
  while (state.eat(
    124
    /* | */
  )) {
    if (trackDisjunction) {
      state.branchID = state.branchID.sibling();
    }
    this.regexp_alternative(state);
  }
  if (trackDisjunction) {
    state.branchID = state.branchID.parent;
  }
  if (this.regexp_eatQuantifier(state, true)) {
    state.raise("Nothing to repeat");
  }
  if (state.eat(
    123
    /* { */
  )) {
    state.raise("Lone quantifier brackets");
  }
};
pp$1.regexp_alternative = function(state) {
  while (state.pos < state.source.length && this.regexp_eatTerm(state)) {
  }
};
pp$1.regexp_eatTerm = function(state) {
  if (this.regexp_eatAssertion(state)) {
    if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
      if (state.switchU) {
        state.raise("Invalid quantifier");
      }
    }
    return true;
  }
  if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
    this.regexp_eatQuantifier(state);
    return true;
  }
  return false;
};
pp$1.regexp_eatAssertion = function(state) {
  var start2 = state.pos;
  state.lastAssertionIsQuantifiable = false;
  if (state.eat(
    94
    /* ^ */
  ) || state.eat(
    36
    /* $ */
  )) {
    return true;
  }
  if (state.eat(
    92
    /* \ */
  )) {
    if (state.eat(
      66
      /* B */
    ) || state.eat(
      98
      /* b */
    )) {
      return true;
    }
    state.pos = start2;
  }
  if (state.eat(
    40
    /* ( */
  ) && state.eat(
    63
    /* ? */
  )) {
    var lookbehind = false;
    if (this.options.ecmaVersion >= 9) {
      lookbehind = state.eat(
        60
        /* < */
      );
    }
    if (state.eat(
      61
      /* = */
    ) || state.eat(
      33
      /* ! */
    )) {
      this.regexp_disjunction(state);
      if (!state.eat(
        41
        /* ) */
      )) {
        state.raise("Unterminated group");
      }
      state.lastAssertionIsQuantifiable = !lookbehind;
      return true;
    }
  }
  state.pos = start2;
  return false;
};
pp$1.regexp_eatQuantifier = function(state, noError) {
  if (noError === void 0) noError = false;
  if (this.regexp_eatQuantifierPrefix(state, noError)) {
    state.eat(
      63
      /* ? */
    );
    return true;
  }
  return false;
};
pp$1.regexp_eatQuantifierPrefix = function(state, noError) {
  return state.eat(
    42
    /* * */
  ) || state.eat(
    43
    /* + */
  ) || state.eat(
    63
    /* ? */
  ) || this.regexp_eatBracedQuantifier(state, noError);
};
pp$1.regexp_eatBracedQuantifier = function(state, noError) {
  var start2 = state.pos;
  if (state.eat(
    123
    /* { */
  )) {
    var min2 = 0, max2 = -1;
    if (this.regexp_eatDecimalDigits(state)) {
      min2 = state.lastIntValue;
      if (state.eat(
        44
        /* , */
      ) && this.regexp_eatDecimalDigits(state)) {
        max2 = state.lastIntValue;
      }
      if (state.eat(
        125
        /* } */
      )) {
        if (max2 !== -1 && max2 < min2 && !noError) {
          state.raise("numbers out of order in {} quantifier");
        }
        return true;
      }
    }
    if (state.switchU && !noError) {
      state.raise("Incomplete quantifier");
    }
    state.pos = start2;
  }
  return false;
};
pp$1.regexp_eatAtom = function(state) {
  return this.regexp_eatPatternCharacters(state) || state.eat(
    46
    /* . */
  ) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state);
};
pp$1.regexp_eatReverseSolidusAtomEscape = function(state) {
  var start2 = state.pos;
  if (state.eat(
    92
    /* \ */
  )) {
    if (this.regexp_eatAtomEscape(state)) {
      return true;
    }
    state.pos = start2;
  }
  return false;
};
pp$1.regexp_eatUncapturingGroup = function(state) {
  var start2 = state.pos;
  if (state.eat(
    40
    /* ( */
  )) {
    if (state.eat(
      63
      /* ? */
    )) {
      if (this.options.ecmaVersion >= 16) {
        var addModifiers = this.regexp_eatModifiers(state);
        var hasHyphen = state.eat(
          45
          /* - */
        );
        if (addModifiers || hasHyphen) {
          for (var i2 = 0; i2 < addModifiers.length; i2++) {
            var modifier = addModifiers.charAt(i2);
            if (addModifiers.indexOf(modifier, i2 + 1) > -1) {
              state.raise("Duplicate regular expression modifiers");
            }
          }
          if (hasHyphen) {
            var removeModifiers = this.regexp_eatModifiers(state);
            if (!addModifiers && !removeModifiers && state.current() === 58) {
              state.raise("Invalid regular expression modifiers");
            }
            for (var i$1 = 0; i$1 < removeModifiers.length; i$1++) {
              var modifier$1 = removeModifiers.charAt(i$1);
              if (removeModifiers.indexOf(modifier$1, i$1 + 1) > -1 || addModifiers.indexOf(modifier$1) > -1) {
                state.raise("Duplicate regular expression modifiers");
              }
            }
          }
        }
      }
      if (state.eat(
        58
        /* : */
      )) {
        this.regexp_disjunction(state);
        if (state.eat(
          41
          /* ) */
        )) {
          return true;
        }
        state.raise("Unterminated group");
      }
    }
    state.pos = start2;
  }
  return false;
};
pp$1.regexp_eatCapturingGroup = function(state) {
  if (state.eat(
    40
    /* ( */
  )) {
    if (this.options.ecmaVersion >= 9) {
      this.regexp_groupSpecifier(state);
    } else if (state.current() === 63) {
      state.raise("Invalid group");
    }
    this.regexp_disjunction(state);
    if (state.eat(
      41
      /* ) */
    )) {
      state.numCapturingParens += 1;
      return true;
    }
    state.raise("Unterminated group");
  }
  return false;
};
pp$1.regexp_eatModifiers = function(state) {
  var modifiers = "";
  var ch = 0;
  while ((ch = state.current()) !== -1 && isRegularExpressionModifier(ch)) {
    modifiers += codePointToString(ch);
    state.advance();
  }
  return modifiers;
};
function isRegularExpressionModifier(ch) {
  return ch === 105 || ch === 109 || ch === 115;
}
pp$1.regexp_eatExtendedAtom = function(state) {
  return state.eat(
    46
    /* . */
  ) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state) || this.regexp_eatInvalidBracedQuantifier(state) || this.regexp_eatExtendedPatternCharacter(state);
};
pp$1.regexp_eatInvalidBracedQuantifier = function(state) {
  if (this.regexp_eatBracedQuantifier(state, true)) {
    state.raise("Nothing to repeat");
  }
  return false;
};
pp$1.regexp_eatSyntaxCharacter = function(state) {
  var ch = state.current();
  if (isSyntaxCharacter(ch)) {
    state.lastIntValue = ch;
    state.advance();
    return true;
  }
  return false;
};
function isSyntaxCharacter(ch) {
  return ch === 36 || ch >= 40 && ch <= 43 || ch === 46 || ch === 63 || ch >= 91 && ch <= 94 || ch >= 123 && ch <= 125;
}
pp$1.regexp_eatPatternCharacters = function(state) {
  var start2 = state.pos;
  var ch = 0;
  while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
    state.advance();
  }
  return state.pos !== start2;
};
pp$1.regexp_eatExtendedPatternCharacter = function(state) {
  var ch = state.current();
  if (ch !== -1 && ch !== 36 && !(ch >= 40 && ch <= 43) && ch !== 46 && ch !== 63 && ch !== 91 && ch !== 94 && ch !== 124) {
    state.advance();
    return true;
  }
  return false;
};
pp$1.regexp_groupSpecifier = function(state) {
  if (state.eat(
    63
    /* ? */
  )) {
    if (!this.regexp_eatGroupName(state)) {
      state.raise("Invalid group");
    }
    var trackDisjunction = this.options.ecmaVersion >= 16;
    var known = state.groupNames[state.lastStringValue];
    if (known) {
      if (trackDisjunction) {
        for (var i2 = 0, list2 = known; i2 < list2.length; i2 += 1) {
          var altID = list2[i2];
          if (!altID.separatedFrom(state.branchID)) {
            state.raise("Duplicate capture group name");
          }
        }
      } else {
        state.raise("Duplicate capture group name");
      }
    }
    if (trackDisjunction) {
      (known || (state.groupNames[state.lastStringValue] = [])).push(state.branchID);
    } else {
      state.groupNames[state.lastStringValue] = true;
    }
  }
};
pp$1.regexp_eatGroupName = function(state) {
  state.lastStringValue = "";
  if (state.eat(
    60
    /* < */
  )) {
    if (this.regexp_eatRegExpIdentifierName(state) && state.eat(
      62
      /* > */
    )) {
      return true;
    }
    state.raise("Invalid capture group name");
  }
  return false;
};
pp$1.regexp_eatRegExpIdentifierName = function(state) {
  state.lastStringValue = "";
  if (this.regexp_eatRegExpIdentifierStart(state)) {
    state.lastStringValue += codePointToString(state.lastIntValue);
    while (this.regexp_eatRegExpIdentifierPart(state)) {
      state.lastStringValue += codePointToString(state.lastIntValue);
    }
    return true;
  }
  return false;
};
pp$1.regexp_eatRegExpIdentifierStart = function(state) {
  var start2 = state.pos;
  var forceU = this.options.ecmaVersion >= 11;
  var ch = state.current(forceU);
  state.advance(forceU);
  if (ch === 92 && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
    ch = state.lastIntValue;
  }
  if (isRegExpIdentifierStart(ch)) {
    state.lastIntValue = ch;
    return true;
  }
  state.pos = start2;
  return false;
};
function isRegExpIdentifierStart(ch) {
  return isIdentifierStart(ch, true) || ch === 36 || ch === 95;
}
pp$1.regexp_eatRegExpIdentifierPart = function(state) {
  var start2 = state.pos;
  var forceU = this.options.ecmaVersion >= 11;
  var ch = state.current(forceU);
  state.advance(forceU);
  if (ch === 92 && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
    ch = state.lastIntValue;
  }
  if (isRegExpIdentifierPart(ch)) {
    state.lastIntValue = ch;
    return true;
  }
  state.pos = start2;
  return false;
};
function isRegExpIdentifierPart(ch) {
  return isIdentifierChar(ch, true) || ch === 36 || ch === 95 || ch === 8204 || ch === 8205;
}
pp$1.regexp_eatAtomEscape = function(state) {
  if (this.regexp_eatBackReference(state) || this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) || state.switchN && this.regexp_eatKGroupName(state)) {
    return true;
  }
  if (state.switchU) {
    if (state.current() === 99) {
      state.raise("Invalid unicode escape");
    }
    state.raise("Invalid escape");
  }
  return false;
};
pp$1.regexp_eatBackReference = function(state) {
  var start2 = state.pos;
  if (this.regexp_eatDecimalEscape(state)) {
    var n2 = state.lastIntValue;
    if (state.switchU) {
      if (n2 > state.maxBackReference) {
        state.maxBackReference = n2;
      }
      return true;
    }
    if (n2 <= state.numCapturingParens) {
      return true;
    }
    state.pos = start2;
  }
  return false;
};
pp$1.regexp_eatKGroupName = function(state) {
  if (state.eat(
    107
    /* k */
  )) {
    if (this.regexp_eatGroupName(state)) {
      state.backReferenceNames.push(state.lastStringValue);
      return true;
    }
    state.raise("Invalid named reference");
  }
  return false;
};
pp$1.regexp_eatCharacterEscape = function(state) {
  return this.regexp_eatControlEscape(state) || this.regexp_eatCControlLetter(state) || this.regexp_eatZero(state) || this.regexp_eatHexEscapeSequence(state) || this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || !state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state) || this.regexp_eatIdentityEscape(state);
};
pp$1.regexp_eatCControlLetter = function(state) {
  var start2 = state.pos;
  if (state.eat(
    99
    /* c */
  )) {
    if (this.regexp_eatControlLetter(state)) {
      return true;
    }
    state.pos = start2;
  }
  return false;
};
pp$1.regexp_eatZero = function(state) {
  if (state.current() === 48 && !isDecimalDigit(state.lookahead())) {
    state.lastIntValue = 0;
    state.advance();
    return true;
  }
  return false;
};
pp$1.regexp_eatControlEscape = function(state) {
  var ch = state.current();
  if (ch === 116) {
    state.lastIntValue = 9;
    state.advance();
    return true;
  }
  if (ch === 110) {
    state.lastIntValue = 10;
    state.advance();
    return true;
  }
  if (ch === 118) {
    state.lastIntValue = 11;
    state.advance();
    return true;
  }
  if (ch === 102) {
    state.lastIntValue = 12;
    state.advance();
    return true;
  }
  if (ch === 114) {
    state.lastIntValue = 13;
    state.advance();
    return true;
  }
  return false;
};
pp$1.regexp_eatControlLetter = function(state) {
  var ch = state.current();
  if (isControlLetter(ch)) {
    state.lastIntValue = ch % 32;
    state.advance();
    return true;
  }
  return false;
};
function isControlLetter(ch) {
  return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122;
}
pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
  if (forceU === void 0) forceU = false;
  var start2 = state.pos;
  var switchU = forceU || state.switchU;
  if (state.eat(
    117
    /* u */
  )) {
    if (this.regexp_eatFixedHexDigits(state, 4)) {
      var lead = state.lastIntValue;
      if (switchU && lead >= 55296 && lead <= 56319) {
        var leadSurrogateEnd = state.pos;
        if (state.eat(
          92
          /* \ */
        ) && state.eat(
          117
          /* u */
        ) && this.regexp_eatFixedHexDigits(state, 4)) {
          var trail = state.lastIntValue;
          if (trail >= 56320 && trail <= 57343) {
            state.lastIntValue = (lead - 55296) * 1024 + (trail - 56320) + 65536;
            return true;
          }
        }
        state.pos = leadSurrogateEnd;
        state.lastIntValue = lead;
      }
      return true;
    }
    if (switchU && state.eat(
      123
      /* { */
    ) && this.regexp_eatHexDigits(state) && state.eat(
      125
      /* } */
    ) && isValidUnicode(state.lastIntValue)) {
      return true;
    }
    if (switchU) {
      state.raise("Invalid unicode escape");
    }
    state.pos = start2;
  }
  return false;
};
function isValidUnicode(ch) {
  return ch >= 0 && ch <= 1114111;
}
pp$1.regexp_eatIdentityEscape = function(state) {
  if (state.switchU) {
    if (this.regexp_eatSyntaxCharacter(state)) {
      return true;
    }
    if (state.eat(
      47
      /* / */
    )) {
      state.lastIntValue = 47;
      return true;
    }
    return false;
  }
  var ch = state.current();
  if (ch !== 99 && (!state.switchN || ch !== 107)) {
    state.lastIntValue = ch;
    state.advance();
    return true;
  }
  return false;
};
pp$1.regexp_eatDecimalEscape = function(state) {
  state.lastIntValue = 0;
  var ch = state.current();
  if (ch >= 49 && ch <= 57) {
    do {
      state.lastIntValue = 10 * state.lastIntValue + (ch - 48);
      state.advance();
    } while ((ch = state.current()) >= 48 && ch <= 57);
    return true;
  }
  return false;
};
var CharSetNone = 0;
var CharSetOk = 1;
var CharSetString = 2;
pp$1.regexp_eatCharacterClassEscape = function(state) {
  var ch = state.current();
  if (isCharacterClassEscape(ch)) {
    state.lastIntValue = -1;
    state.advance();
    return CharSetOk;
  }
  var negate = false;
  if (state.switchU && this.options.ecmaVersion >= 9 && ((negate = ch === 80) || ch === 112)) {
    state.lastIntValue = -1;
    state.advance();
    var result2;
    if (state.eat(
      123
      /* { */
    ) && (result2 = this.regexp_eatUnicodePropertyValueExpression(state)) && state.eat(
      125
      /* } */
    )) {
      if (negate && result2 === CharSetString) {
        state.raise("Invalid property name");
      }
      return result2;
    }
    state.raise("Invalid property name");
  }
  return CharSetNone;
};
function isCharacterClassEscape(ch) {
  return ch === 100 || ch === 68 || ch === 115 || ch === 83 || ch === 119 || ch === 87;
}
pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
  var start2 = state.pos;
  if (this.regexp_eatUnicodePropertyName(state) && state.eat(
    61
    /* = */
  )) {
    var name2 = state.lastStringValue;
    if (this.regexp_eatUnicodePropertyValue(state)) {
      var value2 = state.lastStringValue;
      this.regexp_validateUnicodePropertyNameAndValue(state, name2, value2);
      return CharSetOk;
    }
  }
  state.pos = start2;
  if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
    var nameOrValue = state.lastStringValue;
    return this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
  }
  return CharSetNone;
};
pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name2, value2) {
  if (!hasOwn(state.unicodeProperties.nonBinary, name2)) {
    state.raise("Invalid property name");
  }
  if (!state.unicodeProperties.nonBinary[name2].test(value2)) {
    state.raise("Invalid property value");
  }
};
pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
  if (state.unicodeProperties.binary.test(nameOrValue)) {
    return CharSetOk;
  }
  if (state.switchV && state.unicodeProperties.binaryOfStrings.test(nameOrValue)) {
    return CharSetString;
  }
  state.raise("Invalid property name");
};
pp$1.regexp_eatUnicodePropertyName = function(state) {
  var ch = 0;
  state.lastStringValue = "";
  while (isUnicodePropertyNameCharacter(ch = state.current())) {
    state.lastStringValue += codePointToString(ch);
    state.advance();
  }
  return state.lastStringValue !== "";
};
function isUnicodePropertyNameCharacter(ch) {
  return isControlLetter(ch) || ch === 95;
}
pp$1.regexp_eatUnicodePropertyValue = function(state) {
  var ch = 0;
  state.lastStringValue = "";
  while (isUnicodePropertyValueCharacter(ch = state.current())) {
    state.lastStringValue += codePointToString(ch);
    state.advance();
  }
  return state.lastStringValue !== "";
};
function isUnicodePropertyValueCharacter(ch) {
  return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch);
}
pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
  return this.regexp_eatUnicodePropertyValue(state);
};
pp$1.regexp_eatCharacterClass = function(state) {
  if (state.eat(
    91
    /* [ */
  )) {
    var negate = state.eat(
      94
      /* ^ */
    );
    var result2 = this.regexp_classContents(state);
    if (!state.eat(
      93
      /* ] */
    )) {
      state.raise("Unterminated character class");
    }
    if (negate && result2 === CharSetString) {
      state.raise("Negated character class may contain strings");
    }
    return true;
  }
  return false;
};
pp$1.regexp_classContents = function(state) {
  if (state.current() === 93) {
    return CharSetOk;
  }
  if (state.switchV) {
    return this.regexp_classSetExpression(state);
  }
  this.regexp_nonEmptyClassRanges(state);
  return CharSetOk;
};
pp$1.regexp_nonEmptyClassRanges = function(state) {
  while (this.regexp_eatClassAtom(state)) {
    var left2 = state.lastIntValue;
    if (state.eat(
      45
      /* - */
    ) && this.regexp_eatClassAtom(state)) {
      var right2 = state.lastIntValue;
      if (state.switchU && (left2 === -1 || right2 === -1)) {
        state.raise("Invalid character class");
      }
      if (left2 !== -1 && right2 !== -1 && left2 > right2) {
        state.raise("Range out of order in character class");
      }
    }
  }
};
pp$1.regexp_eatClassAtom = function(state) {
  var start2 = state.pos;
  if (state.eat(
    92
    /* \ */
  )) {
    if (this.regexp_eatClassEscape(state)) {
      return true;
    }
    if (state.switchU) {
      var ch$1 = state.current();
      if (ch$1 === 99 || isOctalDigit(ch$1)) {
        state.raise("Invalid class escape");
      }
      state.raise("Invalid escape");
    }
    state.pos = start2;
  }
  var ch = state.current();
  if (ch !== 93) {
    state.lastIntValue = ch;
    state.advance();
    return true;
  }
  return false;
};
pp$1.regexp_eatClassEscape = function(state) {
  var start2 = state.pos;
  if (state.eat(
    98
    /* b */
  )) {
    state.lastIntValue = 8;
    return true;
  }
  if (state.switchU && state.eat(
    45
    /* - */
  )) {
    state.lastIntValue = 45;
    return true;
  }
  if (!state.switchU && state.eat(
    99
    /* c */
  )) {
    if (this.regexp_eatClassControlLetter(state)) {
      return true;
    }
    state.pos = start2;
  }
  return this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state);
};
pp$1.regexp_classSetExpression = function(state) {
  var result2 = CharSetOk, subResult;
  if (this.regexp_eatClassSetRange(state)) ;
  else if (subResult = this.regexp_eatClassSetOperand(state)) {
    if (subResult === CharSetString) {
      result2 = CharSetString;
    }
    var start2 = state.pos;
    while (state.eatChars(
      [38, 38]
      /* && */
    )) {
      if (state.current() !== 38 && (subResult = this.regexp_eatClassSetOperand(state))) {
        if (subResult !== CharSetString) {
          result2 = CharSetOk;
        }
        continue;
      }
      state.raise("Invalid character in character class");
    }
    if (start2 !== state.pos) {
      return result2;
    }
    while (state.eatChars(
      [45, 45]
      /* -- */
    )) {
      if (this.regexp_eatClassSetOperand(state)) {
        continue;
      }
      state.raise("Invalid character in character class");
    }
    if (start2 !== state.pos) {
      return result2;
    }
  } else {
    state.raise("Invalid character in character class");
  }
  for (; ; ) {
    if (this.regexp_eatClassSetRange(state)) {
      continue;
    }
    subResult = this.regexp_eatClassSetOperand(state);
    if (!subResult) {
      return result2;
    }
    if (subResult === CharSetString) {
      result2 = CharSetString;
    }
  }
};
pp$1.regexp_eatClassSetRange = function(state) {
  var start2 = state.pos;
  if (this.regexp_eatClassSetCharacter(state)) {
    var left2 = state.lastIntValue;
    if (state.eat(
      45
      /* - */
    ) && this.regexp_eatClassSetCharacter(state)) {
      var right2 = state.lastIntValue;
      if (left2 !== -1 && right2 !== -1 && left2 > right2) {
        state.raise("Range out of order in character class");
      }
      return true;
    }
    state.pos = start2;
  }
  return false;
};
pp$1.regexp_eatClassSetOperand = function(state) {
  if (this.regexp_eatClassSetCharacter(state)) {
    return CharSetOk;
  }
  return this.regexp_eatClassStringDisjunction(state) || this.regexp_eatNestedClass(state);
};
pp$1.regexp_eatNestedClass = function(state) {
  var start2 = state.pos;
  if (state.eat(
    91
    /* [ */
  )) {
    var negate = state.eat(
      94
      /* ^ */
    );
    var result2 = this.regexp_classContents(state);
    if (state.eat(
      93
      /* ] */
    )) {
      if (negate && result2 === CharSetString) {
        state.raise("Negated character class may contain strings");
      }
      return result2;
    }
    state.pos = start2;
  }
  if (state.eat(
    92
    /* \ */
  )) {
    var result$12 = this.regexp_eatCharacterClassEscape(state);
    if (result$12) {
      return result$12;
    }
    state.pos = start2;
  }
  return null;
};
pp$1.regexp_eatClassStringDisjunction = function(state) {
  var start2 = state.pos;
  if (state.eatChars(
    [92, 113]
    /* \q */
  )) {
    if (state.eat(
      123
      /* { */
    )) {
      var result2 = this.regexp_classStringDisjunctionContents(state);
      if (state.eat(
        125
        /* } */
      )) {
        return result2;
      }
    } else {
      state.raise("Invalid escape");
    }
    state.pos = start2;
  }
  return null;
};
pp$1.regexp_classStringDisjunctionContents = function(state) {
  var result2 = this.regexp_classString(state);
  while (state.eat(
    124
    /* | */
  )) {
    if (this.regexp_classString(state) === CharSetString) {
      result2 = CharSetString;
    }
  }
  return result2;
};
pp$1.regexp_classString = function(state) {
  var count2 = 0;
  while (this.regexp_eatClassSetCharacter(state)) {
    count2++;
  }
  return count2 === 1 ? CharSetOk : CharSetString;
};
pp$1.regexp_eatClassSetCharacter = function(state) {
  var start2 = state.pos;
  if (state.eat(
    92
    /* \ */
  )) {
    if (this.regexp_eatCharacterEscape(state) || this.regexp_eatClassSetReservedPunctuator(state)) {
      return true;
    }
    if (state.eat(
      98
      /* b */
    )) {
      state.lastIntValue = 8;
      return true;
    }
    state.pos = start2;
    return false;
  }
  var ch = state.current();
  if (ch < 0 || ch === state.lookahead() && isClassSetReservedDoublePunctuatorCharacter(ch)) {
    return false;
  }
  if (isClassSetSyntaxCharacter(ch)) {
    return false;
  }
  state.advance();
  state.lastIntValue = ch;
  return true;
};
function isClassSetReservedDoublePunctuatorCharacter(ch) {
  return ch === 33 || ch >= 35 && ch <= 38 || ch >= 42 && ch <= 44 || ch === 46 || ch >= 58 && ch <= 64 || ch === 94 || ch === 96 || ch === 126;
}
function isClassSetSyntaxCharacter(ch) {
  return ch === 40 || ch === 41 || ch === 45 || ch === 47 || ch >= 91 && ch <= 93 || ch >= 123 && ch <= 125;
}
pp$1.regexp_eatClassSetReservedPunctuator = function(state) {
  var ch = state.current();
  if (isClassSetReservedPunctuator(ch)) {
    state.lastIntValue = ch;
    state.advance();
    return true;
  }
  return false;
};
function isClassSetReservedPunctuator(ch) {
  return ch === 33 || ch === 35 || ch === 37 || ch === 38 || ch === 44 || ch === 45 || ch >= 58 && ch <= 62 || ch === 64 || ch === 96 || ch === 126;
}
pp$1.regexp_eatClassControlLetter = function(state) {
  var ch = state.current();
  if (isDecimalDigit(ch) || ch === 95) {
    state.lastIntValue = ch % 32;
    state.advance();
    return true;
  }
  return false;
};
pp$1.regexp_eatHexEscapeSequence = function(state) {
  var start2 = state.pos;
  if (state.eat(
    120
    /* x */
  )) {
    if (this.regexp_eatFixedHexDigits(state, 2)) {
      return true;
    }
    if (state.switchU) {
      state.raise("Invalid escape");
    }
    state.pos = start2;
  }
  return false;
};
pp$1.regexp_eatDecimalDigits = function(state) {
  var start2 = state.pos;
  var ch = 0;
  state.lastIntValue = 0;
  while (isDecimalDigit(ch = state.current())) {
    state.lastIntValue = 10 * state.lastIntValue + (ch - 48);
    state.advance();
  }
  return state.pos !== start2;
};
function isDecimalDigit(ch) {
  return ch >= 48 && ch <= 57;
}
pp$1.regexp_eatHexDigits = function(state) {
  var start2 = state.pos;
  var ch = 0;
  state.lastIntValue = 0;
  while (isHexDigit(ch = state.current())) {
    state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
    state.advance();
  }
  return state.pos !== start2;
};
function isHexDigit(ch) {
  return ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102;
}
function hexToInt(ch) {
  if (ch >= 65 && ch <= 70) {
    return 10 + (ch - 65);
  }
  if (ch >= 97 && ch <= 102) {
    return 10 + (ch - 97);
  }
  return ch - 48;
}
pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) {
  if (this.regexp_eatOctalDigit(state)) {
    var n1 = state.lastIntValue;
    if (this.regexp_eatOctalDigit(state)) {
      var n2 = state.lastIntValue;
      if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
        state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
      } else {
        state.lastIntValue = n1 * 8 + n2;
      }
    } else {
      state.lastIntValue = n1;
    }
    return true;
  }
  return false;
};
pp$1.regexp_eatOctalDigit = function(state) {
  var ch = state.current();
  if (isOctalDigit(ch)) {
    state.lastIntValue = ch - 48;
    state.advance();
    return true;
  }
  state.lastIntValue = 0;
  return false;
};
function isOctalDigit(ch) {
  return ch >= 48 && ch <= 55;
}
pp$1.regexp_eatFixedHexDigits = function(state, length2) {
  var start2 = state.pos;
  state.lastIntValue = 0;
  for (var i2 = 0; i2 < length2; ++i2) {
    var ch = state.current();
    if (!isHexDigit(ch)) {
      state.pos = start2;
      return false;
    }
    state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
    state.advance();
  }
  return true;
};
var Token$1 = function Token(p) {
  this.type = p.type;
  this.value = p.value;
  this.start = p.start;
  this.end = p.end;
  if (p.options.locations) {
    this.loc = new SourceLocation(p, p.startLoc, p.endLoc);
  }
  if (p.options.ranges) {
    this.range = [p.start, p.end];
  }
};
var pp = Parser.prototype;
pp.next = function(ignoreEscapeSequenceInKeyword) {
  if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) {
    this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword);
  }
  if (this.options.onToken) {
    this.options.onToken(new Token$1(this));
  }
  this.lastTokEnd = this.end;
  this.lastTokStart = this.start;
  this.lastTokEndLoc = this.endLoc;
  this.lastTokStartLoc = this.startLoc;
  this.nextToken();
};
pp.getToken = function() {
  this.next();
  return new Token$1(this);
};
if (typeof Symbol !== "undefined") {
  pp[Symbol.iterator] = function() {
    var this$1$1 = this;
    return {
      next: function() {
        var token2 = this$1$1.getToken();
        return {
          done: token2.type === types$1.eof,
          value: token2
        };
      }
    };
  };
}
pp.nextToken = function() {
  var curContext = this.curContext();
  if (!curContext || !curContext.preserveSpace) {
    this.skipSpace();
  }
  this.start = this.pos;
  if (this.options.locations) {
    this.startLoc = this.curPosition();
  }
  if (this.pos >= this.input.length) {
    return this.finishToken(types$1.eof);
  }
  if (curContext.override) {
    return curContext.override(this);
  } else {
    this.readToken(this.fullCharCodeAtPos());
  }
};
pp.readToken = function(code2) {
  if (isIdentifierStart(code2, this.options.ecmaVersion >= 6) || code2 === 92) {
    return this.readWord();
  }
  return this.getTokenFromCode(code2);
};
pp.fullCharCodeAtPos = function() {
  var code2 = this.input.charCodeAt(this.pos);
  if (code2 <= 55295 || code2 >= 56320) {
    return code2;
  }
  var next = this.input.charCodeAt(this.pos + 1);
  return next <= 56319 || next >= 57344 ? code2 : (code2 << 10) + next - 56613888;
};
pp.skipBlockComment = function() {
  var startLoc = this.options.onComment && this.curPosition();
  var start2 = this.pos, end2 = this.input.indexOf("*/", this.pos += 2);
  if (end2 === -1) {
    this.raise(this.pos - 2, "Unterminated comment");
  }
  this.pos = end2 + 2;
  if (this.options.locations) {
    for (var nextBreak = void 0, pos2 = start2; (nextBreak = nextLineBreak(this.input, pos2, this.pos)) > -1; ) {
      ++this.curLine;
      pos2 = this.lineStart = nextBreak;
    }
  }
  if (this.options.onComment) {
    this.options.onComment(
      true,
      this.input.slice(start2 + 2, end2),
      start2,
      this.pos,
      startLoc,
      this.curPosition()
    );
  }
};
pp.skipLineComment = function(startSkip) {
  var start2 = this.pos;
  var startLoc = this.options.onComment && this.curPosition();
  var ch = this.input.charCodeAt(this.pos += startSkip);
  while (this.pos < this.input.length && !isNewLine(ch)) {
    ch = this.input.charCodeAt(++this.pos);
  }
  if (this.options.onComment) {
    this.options.onComment(
      false,
      this.input.slice(start2 + startSkip, this.pos),
      start2,
      this.pos,
      startLoc,
      this.curPosition()
    );
  }
};
pp.skipSpace = function() {
  loop: while (this.pos < this.input.length) {
    var ch = this.input.charCodeAt(this.pos);
    switch (ch) {
      case 32:
      case 160:
        ++this.pos;
        break;
      case 13:
        if (this.input.charCodeAt(this.pos + 1) === 10) {
          ++this.pos;
        }
      case 10:
      case 8232:
      case 8233:
        ++this.pos;
        if (this.options.locations) {
          ++this.curLine;
          this.lineStart = this.pos;
        }
        break;
      case 47:
        switch (this.input.charCodeAt(this.pos + 1)) {
          case 42:
            this.skipBlockComment();
            break;
          case 47:
            this.skipLineComment(2);
            break;
          default:
            break loop;
        }
        break;
      default:
        if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
          ++this.pos;
        } else {
          break loop;
        }
    }
  }
};
pp.finishToken = function(type, val) {
  this.end = this.pos;
  if (this.options.locations) {
    this.endLoc = this.curPosition();
  }
  var prevType = this.type;
  this.type = type;
  this.value = val;
  this.updateContext(prevType);
};
pp.readToken_dot = function() {
  var next = this.input.charCodeAt(this.pos + 1);
  if (next >= 48 && next <= 57) {
    return this.readNumber(true);
  }
  var next2 = this.input.charCodeAt(this.pos + 2);
  if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) {
    this.pos += 3;
    return this.finishToken(types$1.ellipsis);
  } else {
    ++this.pos;
    return this.finishToken(types$1.dot);
  }
};
pp.readToken_slash = function() {
  var next = this.input.charCodeAt(this.pos + 1);
  if (this.exprAllowed) {
    ++this.pos;
    return this.readRegexp();
  }
  if (next === 61) {
    return this.finishOp(types$1.assign, 2);
  }
  return this.finishOp(types$1.slash, 1);
};
pp.readToken_mult_modulo_exp = function(code2) {
  var next = this.input.charCodeAt(this.pos + 1);
  var size = 1;
  var tokentype = code2 === 42 ? types$1.star : types$1.modulo;
  if (this.options.ecmaVersion >= 7 && code2 === 42 && next === 42) {
    ++size;
    tokentype = types$1.starstar;
    next = this.input.charCodeAt(this.pos + 2);
  }
  if (next === 61) {
    return this.finishOp(types$1.assign, size + 1);
  }
  return this.finishOp(tokentype, size);
};
pp.readToken_pipe_amp = function(code2) {
  var next = this.input.charCodeAt(this.pos + 1);
  if (next === code2) {
    if (this.options.ecmaVersion >= 12) {
      var next2 = this.input.charCodeAt(this.pos + 2);
      if (next2 === 61) {
        return this.finishOp(types$1.assign, 3);
      }
    }
    return this.finishOp(code2 === 124 ? types$1.logicalOR : types$1.logicalAND, 2);
  }
  if (next === 61) {
    return this.finishOp(types$1.assign, 2);
  }
  return this.finishOp(code2 === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1);
};
pp.readToken_caret = function() {
  var next = this.input.charCodeAt(this.pos + 1);
  if (next === 61) {
    return this.finishOp(types$1.assign, 2);
  }
  return this.finishOp(types$1.bitwiseXOR, 1);
};
pp.readToken_plus_min = function(code2) {
  var next = this.input.charCodeAt(this.pos + 1);
  if (next === code2) {
    if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
      this.skipLineComment(3);
      this.skipSpace();
      return this.nextToken();
    }
    return this.finishOp(types$1.incDec, 2);
  }
  if (next === 61) {
    return this.finishOp(types$1.assign, 2);
  }
  return this.finishOp(types$1.plusMin, 1);
};
pp.readToken_lt_gt = function(code2) {
  var next = this.input.charCodeAt(this.pos + 1);
  var size = 1;
  if (next === code2) {
    size = code2 === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
    if (this.input.charCodeAt(this.pos + size) === 61) {
      return this.finishOp(types$1.assign, size + 1);
    }
    return this.finishOp(types$1.bitShift, size);
  }
  if (next === 33 && code2 === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && this.input.charCodeAt(this.pos + 3) === 45) {
    this.skipLineComment(4);
    this.skipSpace();
    return this.nextToken();
  }
  if (next === 61) {
    size = 2;
  }
  return this.finishOp(types$1.relational, size);
};
pp.readToken_eq_excl = function(code2) {
  var next = this.input.charCodeAt(this.pos + 1);
  if (next === 61) {
    return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2);
  }
  if (code2 === 61 && next === 62 && this.options.ecmaVersion >= 6) {
    this.pos += 2;
    return this.finishToken(types$1.arrow);
  }
  return this.finishOp(code2 === 61 ? types$1.eq : types$1.prefix, 1);
};
pp.readToken_question = function() {
  var ecmaVersion = this.options.ecmaVersion;
  if (ecmaVersion >= 11) {
    var next = this.input.charCodeAt(this.pos + 1);
    if (next === 46) {
      var next2 = this.input.charCodeAt(this.pos + 2);
      if (next2 < 48 || next2 > 57) {
        return this.finishOp(types$1.questionDot, 2);
      }
    }
    if (next === 63) {
      if (ecmaVersion >= 12) {
        var next2$1 = this.input.charCodeAt(this.pos + 2);
        if (next2$1 === 61) {
          return this.finishOp(types$1.assign, 3);
        }
      }
      return this.finishOp(types$1.coalesce, 2);
    }
  }
  return this.finishOp(types$1.question, 1);
};
pp.readToken_numberSign = function() {
  var ecmaVersion = this.options.ecmaVersion;
  var code2 = 35;
  if (ecmaVersion >= 13) {
    ++this.pos;
    code2 = this.fullCharCodeAtPos();
    if (isIdentifierStart(code2, true) || code2 === 92) {
      return this.finishToken(types$1.privateId, this.readWord1());
    }
  }
  this.raise(this.pos, "Unexpected character '" + codePointToString(code2) + "'");
};
pp.getTokenFromCode = function(code2) {
  switch (code2) {
    // The interpretation of a dot depends on whether it is followed
    // by a digit or another two dots.
    case 46:
      return this.readToken_dot();
    // Punctuation tokens.
    case 40:
      ++this.pos;
      return this.finishToken(types$1.parenL);
    case 41:
      ++this.pos;
      return this.finishToken(types$1.parenR);
    case 59:
      ++this.pos;
      return this.finishToken(types$1.semi);
    case 44:
      ++this.pos;
      return this.finishToken(types$1.comma);
    case 91:
      ++this.pos;
      return this.finishToken(types$1.bracketL);
    case 93:
      ++this.pos;
      return this.finishToken(types$1.bracketR);
    case 123:
      ++this.pos;
      return this.finishToken(types$1.braceL);
    case 125:
      ++this.pos;
      return this.finishToken(types$1.braceR);
    case 58:
      ++this.pos;
      return this.finishToken(types$1.colon);
    case 96:
      if (this.options.ecmaVersion < 6) {
        break;
      }
      ++this.pos;
      return this.finishToken(types$1.backQuote);
    case 48:
      var next = this.input.charCodeAt(this.pos + 1);
      if (next === 120 || next === 88) {
        return this.readRadixNumber(16);
      }
      if (this.options.ecmaVersion >= 6) {
        if (next === 111 || next === 79) {
          return this.readRadixNumber(8);
        }
        if (next === 98 || next === 66) {
          return this.readRadixNumber(2);
        }
      }
    // Anything else beginning with a digit is an integer, octal
    // number, or float.
    case 49:
    case 50:
    case 51:
    case 52:
    case 53:
    case 54:
    case 55:
    case 56:
    case 57:
      return this.readNumber(false);
    // Quotes produce strings.
    case 34:
    case 39:
      return this.readString(code2);
    // Operators are parsed inline in tiny state machines. '=' (61) is
    // often referred to. `finishOp` simply skips the amount of
    // characters it is given as second argument, and returns a token
    // of the type given by its first argument.
    case 47:
      return this.readToken_slash();
    case 37:
    case 42:
      return this.readToken_mult_modulo_exp(code2);
    case 124:
    case 38:
      return this.readToken_pipe_amp(code2);
    case 94:
      return this.readToken_caret();
    case 43:
    case 45:
      return this.readToken_plus_min(code2);
    case 60:
    case 62:
      return this.readToken_lt_gt(code2);
    case 61:
    case 33:
      return this.readToken_eq_excl(code2);
    case 63:
      return this.readToken_question();
    case 126:
      return this.finishOp(types$1.prefix, 1);
    case 35:
      return this.readToken_numberSign();
  }
  this.raise(this.pos, "Unexpected character '" + codePointToString(code2) + "'");
};
pp.finishOp = function(type, size) {
  var str = this.input.slice(this.pos, this.pos + size);
  this.pos += size;
  return this.finishToken(type, str);
};
pp.readRegexp = function() {
  var escaped, inClass, start2 = this.pos;
  for (; ; ) {
    if (this.pos >= this.input.length) {
      this.raise(start2, "Unterminated regular expression");
    }
    var ch = this.input.charAt(this.pos);
    if (lineBreak.test(ch)) {
      this.raise(start2, "Unterminated regular expression");
    }
    if (!escaped) {
      if (ch === "[") {
        inClass = true;
      } else if (ch === "]" && inClass) {
        inClass = false;
      } else if (ch === "/" && !inClass) {
        break;
      }
      escaped = ch === "\\";
    } else {
      escaped = false;
    }
    ++this.pos;
  }
  var pattern = this.input.slice(start2, this.pos);
  ++this.pos;
  var flagsStart = this.pos;
  var flags = this.readWord1();
  if (this.containsEsc) {
    this.unexpected(flagsStart);
  }
  var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
  state.reset(start2, pattern, flags);
  this.validateRegExpFlags(state);
  this.validateRegExpPattern(state);
  var value2 = null;
  try {
    value2 = new RegExp(pattern, flags);
  } catch (e) {
  }
  return this.finishToken(types$1.regexp, { pattern, flags, value: value2 });
};
pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
  var allowSeparators = this.options.ecmaVersion >= 12 && len === void 0;
  var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
  var start2 = this.pos, total = 0, lastCode = 0;
  for (var i2 = 0, e = len == null ? Infinity : len; i2 < e; ++i2, ++this.pos) {
    var code2 = this.input.charCodeAt(this.pos), val = void 0;
    if (allowSeparators && code2 === 95) {
      if (isLegacyOctalNumericLiteral) {
        this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals");
      }
      if (lastCode === 95) {
        this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore");
      }
      if (i2 === 0) {
        this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits");
      }
      lastCode = code2;
      continue;
    }
    if (code2 >= 97) {
      val = code2 - 97 + 10;
    } else if (code2 >= 65) {
      val = code2 - 65 + 10;
    } else if (code2 >= 48 && code2 <= 57) {
      val = code2 - 48;
    } else {
      val = Infinity;
    }
    if (val >= radix) {
      break;
    }
    lastCode = code2;
    total = total * radix + val;
  }
  if (allowSeparators && lastCode === 95) {
    this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits");
  }
  if (this.pos === start2 || len != null && this.pos - start2 !== len) {
    return null;
  }
  return total;
};
function stringToNumber(str, isLegacyOctalNumericLiteral) {
  if (isLegacyOctalNumericLiteral) {
    return parseInt(str, 8);
  }
  return parseFloat(str.replace(/_/g, ""));
}
function stringToBigInt(str) {
  if (typeof BigInt !== "function") {
    return null;
  }
  return BigInt(str.replace(/_/g, ""));
}
pp.readRadixNumber = function(radix) {
  var start2 = this.pos;
  this.pos += 2;
  var val = this.readInt(radix);
  if (val == null) {
    this.raise(this.start + 2, "Expected number in radix " + radix);
  }
  if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
    val = stringToBigInt(this.input.slice(start2, this.pos));
    ++this.pos;
  } else if (isIdentifierStart(this.fullCharCodeAtPos())) {
    this.raise(this.pos, "Identifier directly after number");
  }
  return this.finishToken(types$1.num, val);
};
pp.readNumber = function(startsWithDot) {
  var start2 = this.pos;
  if (!startsWithDot && this.readInt(10, void 0, true) === null) {
    this.raise(start2, "Invalid number");
  }
  var octal = this.pos - start2 >= 2 && this.input.charCodeAt(start2) === 48;
  if (octal && this.strict) {
    this.raise(start2, "Invalid number");
  }
  var next = this.input.charCodeAt(this.pos);
  if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
    var val$1 = stringToBigInt(this.input.slice(start2, this.pos));
    ++this.pos;
    if (isIdentifierStart(this.fullCharCodeAtPos())) {
      this.raise(this.pos, "Identifier directly after number");
    }
    return this.finishToken(types$1.num, val$1);
  }
  if (octal && /[89]/.test(this.input.slice(start2, this.pos))) {
    octal = false;
  }
  if (next === 46 && !octal) {
    ++this.pos;
    this.readInt(10);
    next = this.input.charCodeAt(this.pos);
  }
  if ((next === 69 || next === 101) && !octal) {
    next = this.input.charCodeAt(++this.pos);
    if (next === 43 || next === 45) {
      ++this.pos;
    }
    if (this.readInt(10) === null) {
      this.raise(start2, "Invalid number");
    }
  }
  if (isIdentifierStart(this.fullCharCodeAtPos())) {
    this.raise(this.pos, "Identifier directly after number");
  }
  var val = stringToNumber(this.input.slice(start2, this.pos), octal);
  return this.finishToken(types$1.num, val);
};
pp.readCodePoint = function() {
  var ch = this.input.charCodeAt(this.pos), code2;
  if (ch === 123) {
    if (this.options.ecmaVersion < 6) {
      this.unexpected();
    }
    var codePos = ++this.pos;
    code2 = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
    ++this.pos;
    if (code2 > 1114111) {
      this.invalidStringToken(codePos, "Code point out of bounds");
    }
  } else {
    code2 = this.readHexChar(4);
  }
  return code2;
};
pp.readString = function(quote2) {
  var out = "", chunkStart = ++this.pos;
  for (; ; ) {
    if (this.pos >= this.input.length) {
      this.raise(this.start, "Unterminated string constant");
    }
    var ch = this.input.charCodeAt(this.pos);
    if (ch === quote2) {
      break;
    }
    if (ch === 92) {
      out += this.input.slice(chunkStart, this.pos);
      out += this.readEscapedChar(false);
      chunkStart = this.pos;
    } else if (ch === 8232 || ch === 8233) {
      if (this.options.ecmaVersion < 10) {
        this.raise(this.start, "Unterminated string constant");
      }
      ++this.pos;
      if (this.options.locations) {
        this.curLine++;
        this.lineStart = this.pos;
      }
    } else {
      if (isNewLine(ch)) {
        this.raise(this.start, "Unterminated string constant");
      }
      ++this.pos;
    }
  }
  out += this.input.slice(chunkStart, this.pos++);
  return this.finishToken(types$1.string, out);
};
var INVALID_TEMPLATE_ESCAPE_ERROR = {};
pp.tryReadTemplateToken = function() {
  this.inTemplateElement = true;
  try {
    this.readTmplToken();
  } catch (err) {
    if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
      this.readInvalidTemplateToken();
    } else {
      throw err;
    }
  }
  this.inTemplateElement = false;
};
pp.invalidStringToken = function(position, message2) {
  if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
    throw INVALID_TEMPLATE_ESCAPE_ERROR;
  } else {
    this.raise(position, message2);
  }
};
pp.readTmplToken = function() {
  var out = "", chunkStart = this.pos;
  for (; ; ) {
    if (this.pos >= this.input.length) {
      this.raise(this.start, "Unterminated template");
    }
    var ch = this.input.charCodeAt(this.pos);
    if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) {
      if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) {
        if (ch === 36) {
          this.pos += 2;
          return this.finishToken(types$1.dollarBraceL);
        } else {
          ++this.pos;
          return this.finishToken(types$1.backQuote);
        }
      }
      out += this.input.slice(chunkStart, this.pos);
      return this.finishToken(types$1.template, out);
    }
    if (ch === 92) {
      out += this.input.slice(chunkStart, this.pos);
      out += this.readEscapedChar(true);
      chunkStart = this.pos;
    } else if (isNewLine(ch)) {
      out += this.input.slice(chunkStart, this.pos);
      ++this.pos;
      switch (ch) {
        case 13:
          if (this.input.charCodeAt(this.pos) === 10) {
            ++this.pos;
          }
        case 10:
          out += "\n";
          break;
        default:
          out += String.fromCharCode(ch);
          break;
      }
      if (this.options.locations) {
        ++this.curLine;
        this.lineStart = this.pos;
      }
      chunkStart = this.pos;
    } else {
      ++this.pos;
    }
  }
};
pp.readInvalidTemplateToken = function() {
  for (; this.pos < this.input.length; this.pos++) {
    switch (this.input[this.pos]) {
      case "\\":
        ++this.pos;
        break;
      case "$":
        if (this.input[this.pos + 1] !== "{") {
          break;
        }
      // fall through
      case "`":
        return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos));
      case "\r":
        if (this.input[this.pos + 1] === "\n") {
          ++this.pos;
        }
      // fall through
      case "\n":
      case "\u2028":
      case "\u2029":
        ++this.curLine;
        this.lineStart = this.pos + 1;
        break;
    }
  }
  this.raise(this.start, "Unterminated template");
};
pp.readEscapedChar = function(inTemplate) {
  var ch = this.input.charCodeAt(++this.pos);
  ++this.pos;
  switch (ch) {
    case 110:
      return "\n";
    // 'n' -> '\n'
    case 114:
      return "\r";
    // 'r' -> '\r'
    case 120:
      return String.fromCharCode(this.readHexChar(2));
    // 'x'
    case 117:
      return codePointToString(this.readCodePoint());
    // 'u'
    case 116:
      return "	";
    // 't' -> '\t'
    case 98:
      return "\b";
    // 'b' -> '\b'
    case 118:
      return "\v";
    // 'v' -> '\u000b'
    case 102:
      return "\f";
    // 'f' -> '\f'
    case 13:
      if (this.input.charCodeAt(this.pos) === 10) {
        ++this.pos;
      }
    // '\r\n'
    case 10:
      if (this.options.locations) {
        this.lineStart = this.pos;
        ++this.curLine;
      }
      return "";
    case 56:
    case 57:
      if (this.strict) {
        this.invalidStringToken(
          this.pos - 1,
          "Invalid escape sequence"
        );
      }
      if (inTemplate) {
        var codePos = this.pos - 1;
        this.invalidStringToken(
          codePos,
          "Invalid escape sequence in template string"
        );
      }
    default:
      if (ch >= 48 && ch <= 55) {
        var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
        var octal = parseInt(octalStr, 8);
        if (octal > 255) {
          octalStr = octalStr.slice(0, -1);
          octal = parseInt(octalStr, 8);
        }
        this.pos += octalStr.length - 1;
        ch = this.input.charCodeAt(this.pos);
        if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
          this.invalidStringToken(
            this.pos - 1 - octalStr.length,
            inTemplate ? "Octal literal in template string" : "Octal literal in strict mode"
          );
        }
        return String.fromCharCode(octal);
      }
      if (isNewLine(ch)) {
        if (this.options.locations) {
          this.lineStart = this.pos;
          ++this.curLine;
        }
        return "";
      }
      return String.fromCharCode(ch);
  }
};
pp.readHexChar = function(len) {
  var codePos = this.pos;
  var n2 = this.readInt(16, len);
  if (n2 === null) {
    this.invalidStringToken(codePos, "Bad character escape sequence");
  }
  return n2;
};
pp.readWord1 = function() {
  this.containsEsc = false;
  var word = "", first2 = true, chunkStart = this.pos;
  var astral = this.options.ecmaVersion >= 6;
  while (this.pos < this.input.length) {
    var ch = this.fullCharCodeAtPos();
    if (isIdentifierChar(ch, astral)) {
      this.pos += ch <= 65535 ? 1 : 2;
    } else if (ch === 92) {
      this.containsEsc = true;
      word += this.input.slice(chunkStart, this.pos);
      var escStart = this.pos;
      if (this.input.charCodeAt(++this.pos) !== 117) {
        this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX");
      }
      ++this.pos;
      var esc = this.readCodePoint();
      if (!(first2 ? isIdentifierStart : isIdentifierChar)(esc, astral)) {
        this.invalidStringToken(escStart, "Invalid Unicode escape");
      }
      word += codePointToString(esc);
      chunkStart = this.pos;
    } else {
      break;
    }
    first2 = false;
  }
  return word + this.input.slice(chunkStart, this.pos);
};
pp.readWord = function() {
  var word = this.readWord1();
  var type = types$1.name;
  if (this.keywords.test(word)) {
    type = keywords[word];
  }
  return this.finishToken(type, word);
};
var version = "8.15.0";
Parser.acorn = {
  Parser,
  version,
  defaultOptions: defaultOptions$1,
  Position,
  SourceLocation,
  getLineInfo,
  Node: Node$1,
  TokenType,
  tokTypes: types$1,
  keywordTypes: keywords,
  TokContext,
  tokContexts: types,
  isIdentifierChar,
  isIdentifierStart,
  Token: Token$1,
  isNewLine,
  lineBreak,
  lineBreakG,
  nonASCIIwhitespace
};
function parse$4(input2, options) {
  return Parser.parse(input2, options);
}
const constants = {
  undefined: "void(0)",
  Infinity: "Number.POSITIVE_INFINITY",
  NaN: "Number.NaN",
  E: "Math.E",
  LN2: "Math.LN2",
  LN10: "Math.LN10",
  LOG2E: "Math.LOG2E",
  LOG10E: "Math.LOG10E",
  PI: "Math.PI",
  SQRT1_2: "Math.SQRT1_2",
  SQRT2: "Math.SQRT2"
};
function isNumber$1(value2) {
  return typeof value2 === "number";
}
const PARSER_OPT = { ecmaVersion: 11 };
const DEFAULT_PARAM_ID = "$";
const DEFAULT_TUPLE_ID = "d";
const DEFAULT_TUPLE_ID1 = "d1";
const DEFAULT_TUPLE_ID2 = "d2";
const NO = (msg) => (node2, ctx) => ctx.error(node2, msg + " not allowed");
const ERROR_AGGREGATE = NO("Aggregate function");
const ERROR_WINDOW = NO("Window function");
const ERROR_ARGUMENT = "Invalid argument";
const ERROR_COLUMN = "Invalid column reference";
const ERROR_AGGRONLY = ERROR_COLUMN + " (must be input to an aggregate function)";
const ERROR_FUNCTION = "Invalid function call";
const ERROR_MEMBER = "Invalid member expression";
const ERROR_OP_PARAMETER = "Invalid operator parameter";
const ERROR_PARAM = "Invalid param reference";
const ERROR_VARIABLE = "Invalid variable reference";
const ERROR_VARIABLE_OP = "Variable not accessible in operator call";
const ERROR_DECLARATION = "Unsupported variable declaration";
const ERROR_DESTRUCTURE = "Unsupported destructuring pattern";
const ERROR_CLOSURE = "Table expressions do not support closures";
const ERROR_ESCAPE = "Use aq.escape(fn) to use a function as-is (including closures)";
const ERROR_USE_PARAMS = "use table.params({ name: value }) to define dynamic parameters";
const ERROR_ADD_FUNCTION = "use aq.addFunction(name, fn) to add new op functions";
const ERROR_VARIABLE_NOTE = `
Note: ${ERROR_CLOSURE}. ${ERROR_ESCAPE}, or ${ERROR_USE_PARAMS}.`;
const ERROR_FUNCTION_NOTE = `
Note: ${ERROR_CLOSURE}. ${ERROR_ESCAPE}, or ${ERROR_ADD_FUNCTION}.`;
const ERROR_ROW_OBJECT = `The ${ROW_OBJECT} method is not valid in multi-table expressions.`;
function parseExpression(ctx, spec) {
  const ast = parseAST(spec);
  let node2 = ctx.root = ast;
  ctx.spec = spec;
  ctx.tuple = null;
  ctx.tuple1 = null;
  ctx.tuple2 = null;
  ctx.$param = null;
  ctx.$op = 0;
  ctx.scope = /* @__PURE__ */ new Set();
  ctx.paramsRef = /* @__PURE__ */ new Map();
  ctx.columnRef = /* @__PURE__ */ new Map();
  if (isFunctionExpression(node2)) {
    parseFunction(node2, ctx);
    node2 = node2.body;
  } else if (ctx.join) {
    ctx.scope.add(ctx.tuple1 = DEFAULT_TUPLE_ID1);
    ctx.scope.add(ctx.tuple2 = DEFAULT_TUPLE_ID2);
    ctx.scope.add(ctx.$param = DEFAULT_PARAM_ID);
  } else {
    ctx.scope.add(ctx.tuple = DEFAULT_TUPLE_ID);
    ctx.scope.add(ctx.$param = DEFAULT_PARAM_ID);
  }
  walk(node2, ctx, visitors);
  return ctx.root;
}
function parseAST(expr) {
  try {
    const code2 = expr.field ? fieldRef(expr) : isArray$2(expr) ? toString$2(expr) : expr;
    return parse$4(`expr=(${code2})`, PARSER_OPT).body[0].expression.right;
  } catch (err) {
    error$4(`Expression parse error: ${expr + ""}`);
  }
}
function fieldRef(expr) {
  const col = JSON.stringify(expr + "");
  return !(expr.table || 0) ? `d=>d[${col}]` : `(a,b)=>b[${col}]`;
}
const visitors = {
  FunctionDeclaration: NO("Function definitions"),
  ForStatement: NO("For loops"),
  ForOfStatement: NO("For-of loops"),
  ForInStatement: NO("For-in loops"),
  WhileStatement: NO("While loops"),
  DoWhileStatement: NO("Do-while loops"),
  AwaitExpression: NO("Await expressions"),
  ArrowFunctionExpression: NO("Function definitions"),
  AssignmentExpression: NO("Assignments"),
  FunctionExpression: NO("Function definitions"),
  NewExpression: NO('Use of "new"'),
  UpdateExpression: NO("Update expressions"),
  VariableDeclarator(node2, ctx) {
    handleDeclaration(node2.id, ctx);
  },
  Identifier(node2, ctx, parent) {
    if (handleIdentifier(node2, ctx, parent) && !ctx.scope.has(node2.name)) {
      ctx.error(node2, ERROR_VARIABLE, ERROR_VARIABLE_NOTE);
    }
  },
  CallExpression(node2, ctx) {
    const name2 = functionName(node2.callee);
    const def = getAggregate(name2) || getWindow$1(name2);
    if (def) {
      if ((ctx.join || ctx.aggregate === false) && hasAggregate(name2)) {
        ERROR_AGGREGATE(node2, ctx);
      }
      if ((ctx.join || ctx.window === false) && hasWindow(name2)) {
        ERROR_WINDOW(node2, ctx);
      }
      ctx.$op = 1;
      if (ctx.ast) {
        updateFunctionNode(node2, name2, ctx);
        node2.arguments.forEach((arg) => walk(arg, ctx, opVisitors));
      } else {
        const op2 = ctx.op(parseOperator(ctx, def, name2, node2.arguments));
        Object.assign(node2, { type: Op2, name: op2.id });
      }
      ctx.$op = 0;
      return false;
    } else if (hasFunction(name2)) {
      updateFunctionNode(node2, name2, ctx);
    } else {
      ctx.error(node2, ERROR_FUNCTION, ERROR_FUNCTION_NOTE);
    }
  },
  MemberExpression(node2, ctx, parent) {
    const { object: object2, property } = node2;
    if (!is(Identifier$1, object2)) return;
    const { name: name2 } = object2;
    if (isMath(node2) && is(Identifier$1, property) && Object.hasOwn(constants, property.name)) {
      updateConstantNode(node2, property.name);
      return;
    }
    const index = name2 === ctx.tuple ? 0 : name2 === ctx.tuple1 ? 1 : name2 === ctx.tuple2 ? 2 : -1;
    if (index >= 0) {
      return spliceMember(node2, index, ctx, checkColumn, parent);
    } else if (name2 === ctx.$param) {
      return spliceMember(node2, index, ctx, checkParam);
    } else if (ctx.paramsRef.has(name2)) {
      updateParameterNode(node2, ctx.paramsRef.get(name2));
    } else if (ctx.columnRef.has(name2)) {
      updateColumnNode(object2, name2, ctx, node2);
    } else if (Object.hasOwn(ctx.params, name2)) {
      updateParameterNode(object2, name2);
    }
  }
};
function spliceMember(node2, index, ctx, check2, parent) {
  const { property, computed } = node2;
  let name2;
  if (!computed) {
    name2 = property.name;
  } else if (is(Literal, property)) {
    name2 = property.value;
  } else try {
    walk(property, ctx, visitors, node2);
    name2 = ctx.param(property);
  } catch (e) {
    ctx.error(node2, ERROR_MEMBER);
  }
  check2(node2, name2, index, ctx, parent);
  return false;
}
const opVisitors = {
  ...visitors,
  VariableDeclarator: NO("Variable declaration in operator call"),
  Identifier(node2, ctx, parent) {
    if (handleIdentifier(node2, ctx, parent)) {
      ctx.error(node2, ERROR_VARIABLE_OP);
    }
  },
  CallExpression(node2, ctx) {
    const name2 = functionName(node2.callee);
    if (hasFunction(name2)) {
      updateFunctionNode(node2, name2, ctx);
    } else {
      ctx.error(node2, ERROR_FUNCTION, ERROR_FUNCTION_NOTE);
    }
  }
};
function parseFunction(node2, ctx) {
  if (node2.generator) NO("Generator functions")(node2, ctx);
  if (node2.async) NO("Async functions")(node2, ctx);
  const { params } = node2;
  const len = params.length;
  const setc = (index) => (name2, key2) => ctx.columnRef.set(name2, [key2, index]);
  const setp = (name2, key2) => ctx.paramsRef.set(name2, key2);
  if (!len) ;
  else if (ctx.join) {
    parseRef(ctx, params[0], "tuple1", setc(1));
    if (len > 1) parseRef(ctx, params[1], "tuple2", setc(2));
    if (len > 2) parseRef(ctx, params[2], "$param", setp);
  } else {
    parseRef(ctx, params[0], "tuple", setc(0));
    if (len > 1) parseRef(ctx, params[1], "$param", setp);
  }
  ctx.root = node2.body;
}
function parseRef(ctx, node2, refName, alias) {
  if (is(Identifier$1, node2)) {
    ctx.scope.add(node2.name);
    ctx[refName] = node2.name;
  } else if (is(ObjectPattern, node2)) {
    node2.properties.forEach((p) => {
      const key2 = is(Identifier$1, p.key) ? p.key.name : is(Literal, p.key) ? p.key.value : ctx.error(p, ERROR_ARGUMENT);
      if (!is(Identifier$1, p.value)) {
        ctx.error(p.value, ERROR_DESTRUCTURE);
      }
      alias(p.value.name, key2);
    });
  }
}
function parseOperator(ctx, def, name2, args2) {
  const fields = [];
  const params = [];
  const idxFields = def.param[0] || 0;
  const idxParams = idxFields + (def.param[1] || 0);
  args2.forEach((arg, index) => {
    if (index < idxFields) {
      walk(arg, ctx, opVisitors);
      fields.push(ctx.field(arg));
    } else if (index < idxParams) {
      walk(arg, ctx, opVisitors);
      params.push(ctx.param(arg));
    } else {
      ctx.error(arg, ERROR_OP_PARAMETER);
    }
  });
  return { name: name2, fields, params, ...ctx.spec.window || {} };
}
function functionName(node2) {
  return is(Identifier$1, node2) ? node2.name : !is(MemberExpression, node2) ? null : isMath(node2) ? rewriteMath(node2.property.name) : node2.property.name;
}
function isMath(node2) {
  return is(Identifier$1, node2.object) && node2.object.name === "Math";
}
function rewriteMath(name2) {
  return name2 === "max" ? "greatest" : name2 === "min" ? "least" : name2;
}
function handleIdentifier(node2, ctx, parent) {
  const { name: name2 } = node2;
  if (is(MemberExpression, parent) && parent.property === node2) ;
  else if (is(Property, parent) && parent.key === node2) ;
  else if (ctx.paramsRef.has(name2)) {
    updateParameterNode(node2, ctx.paramsRef.get(name2));
  } else if (ctx.columnRef.has(name2)) {
    updateColumnNode(node2, name2, ctx, parent);
  } else if (Object.hasOwn(ctx.params, name2)) {
    updateParameterNode(node2, name2);
  } else if (Object.hasOwn(constants, name2)) {
    updateConstantNode(node2, name2);
  } else {
    return true;
  }
}
function checkColumn(node2, name2, index, ctx, parent) {
  const table2 = index === 0 ? ctx.table : index > 0 ? ctx.join[index - 1] : null;
  const col = table2 && table2.column(name2);
  if (table2 && !col) {
    ctx.error(node2, ERROR_COLUMN);
  }
  if (ctx.aggronly && !ctx.$op) {
    ctx.error(node2, ERROR_AGGRONLY);
  }
  rewrite(node2, name2, index, col, parent);
}
function updateColumnNode(node2, key2, ctx, parent) {
  const [name2, index] = ctx.columnRef.get(key2);
  checkColumn(node2, name2, index, ctx, parent);
}
function checkParam(node2, name2, index, ctx) {
  if (ctx.params && !Object.hasOwn(ctx.params, name2)) {
    ctx.error(node2, ERROR_PARAM);
  }
  updateParameterNode(node2, name2);
}
function updateParameterNode(node2, name2) {
  node2.type = Parameter;
  node2.name = name2;
}
function updateConstantNode(node2, name2) {
  node2.type = Constant;
  node2.name = name2;
  node2.raw = constants[name2];
}
function updateFunctionNode(node2, name2, ctx) {
  if (name2 === ROW_OBJECT) {
    const t2 = ctx.table;
    if (!t2) ctx.error(node2, ERROR_ROW_OBJECT);
    rowObjectExpression(
      node2,
      t2,
      node2.arguments.length ? node2.arguments.map((node3) => {
        const col = ctx.param(node3);
        const name3 = isNumber$1(col) ? t2.columnName(col) : col;
        if (!t2.column(name3)) ctx.error(node3, ERROR_COLUMN);
        return name3;
      }) : t2.columnNames()
    );
  } else {
    node2.callee = { type: Function$1, name: name2 };
  }
}
function handleDeclaration(node2, ctx) {
  if (is(Identifier$1, node2)) {
    ctx.scope.add(node2.name);
  } else if (is(ArrayPattern, node2)) {
    node2.elements.forEach((elm) => handleDeclaration(elm, ctx));
  } else if (is(ObjectPattern, node2)) {
    node2.properties.forEach((prop) => handleDeclaration(prop.value, ctx));
  } else {
    ctx.error(node2.id, ERROR_DECLARATION);
  }
}
const ANNOTATE = { [Column$1]: 1, [Op2]: 1 };
function parse$3(input2, opt2 = {}) {
  const generate = opt2.generate || codegen;
  const compiler = opt2.compiler || compile$1;
  const params = getParams(opt2);
  const fields = {};
  const opcall = {};
  const names = [];
  const exprs = [];
  let fieldId = 0;
  let opId = -1;
  const compileExpr = opt2.join ? compiler.join : opt2.index == 1 ? compiler.expr2 : compiler.expr;
  const ctx = {
    op(op2) {
      const key2 = opKey(op2);
      return opcall[key2] || (op2.id = ++opId, opcall[key2] = op2);
    },
    field(node2) {
      const code2 = generate(node2);
      return fields[code2] || (fields[code2] = ++fieldId);
    },
    param(node2) {
      return is(Literal, node2) ? node2.value : compiler.param(generate(node2), params);
    },
    value(name2, node2) {
      names.push(name2);
      const e = node2.escape || (opt2.ast ? clean(node2) : compileExpr(generate(node2), params));
      exprs.push(e);
      if (ANNOTATE[node2.type] && e !== node2 && isObject$1(e)) {
        e.field = node2.name;
      }
    },
    error(node2, msg, note = "") {
      const i2 = node2.start - 6;
      const j2 = node2.end - 6;
      const snippet = String(ctx.spec).slice(i2, j2);
      error$4(`${msg}: "${snippet}"${note}`);
    }
  };
  Object.assign(ctx, opt2, { params });
  for (const [name2, value2] of entries(input2)) {
    ctx.value(
      name2 + "",
      value2.escape ? parseEscape(ctx, value2, params) : parseExpression(ctx, value2)
    );
  }
  if (opt2.ast) {
    return { names, exprs };
  }
  const f = [];
  for (const key2 in fields) {
    f[fields[key2]] = compiler.expr(key2, params);
  }
  const ops = Object.values(opcall);
  ops.forEach((op2) => op2.fields = op2.fields.map((id2) => f[id2]));
  return { names, exprs, ops };
}
function opKey(op2) {
  let key2 = `${op2.name}(${op2.fields.concat(op2.params).join(",")})`;
  if (op2.frame) {
    const frame = op2.frame.map((v) => Number.isFinite(v) ? Math.abs(v) : -1);
    key2 += `[${frame},${!!op2.peers}]`;
  }
  return key2;
}
function getParams(opt2) {
  return (opt2.table ? getTableParams(opt2.table) : opt2.join ? {
    ...getTableParams(opt2.join[1]),
    ...getTableParams(opt2.join[0])
  } : {}) || {};
}
function getTableParams(table2) {
  return table2 && isFunction$1(table2.params) ? table2.params() : {};
}
function wrap$2(expr, properties) {
  return expr && expr.expr ? new Wrapper({ ...expr, ...properties }) : new Wrapper(properties, expr);
}
class Wrapper {
  constructor(properties, expr) {
    this.expr = expr;
    Object.assign(this, properties);
  }
  toString() {
    return String(this.expr);
  }
  toObject() {
    return {
      ...this,
      expr: this.toString(),
      ...isFunction$1(this.expr) ? { func: true } : {}
    };
  }
}
function field$1(expr, name2, table2 = 0) {
  const props = table2 ? { field: true, table: table2 } : { field: true };
  return wrap$2(
    expr,
    name2 ? { expr: name2, ...props } : props
  );
}
function assign$3(map2, pairs2) {
  for (const [key2, value2] of entries(pairs2)) {
    map2.set(key2, value2);
  }
  return map2;
}
function resolve(table2, sel, map2 = /* @__PURE__ */ new Map()) {
  sel = isNumber$1(sel) ? table2.columnName(sel) : sel;
  if (isString$2(sel)) {
    map2.set(sel, sel);
  } else if (isArray$2(sel)) {
    sel.forEach((r2) => resolve(table2, r2, map2));
  } else if (isFunction$1(sel)) {
    resolve(table2, sel(table2), map2);
  } else if (isObject$1(sel)) {
    assign$3(map2, sel);
  } else {
    error$4(`Invalid column selection: ${toString$2(sel)}`);
  }
  return map2;
}
function decorate(value2, toObject2) {
  value2.toObject = toObject2;
  return value2;
}
function toObject(value2) {
  return isArray$2(value2) ? value2.map(toObject) : value2 && value2.toObject ? value2.toObject() : value2;
}
function all$1() {
  return decorate(
    (table2) => table2.columnNames(),
    () => ({ all: [] })
  );
}
function not(...selection) {
  selection = selection.flat();
  return decorate(
    (table2) => {
      const drop = resolve(table2, selection);
      return table2.columnNames((name2) => !drop.has(name2));
    },
    () => ({ not: toObject(selection) })
  );
}
function parseValue(name2, table2, params, options = { window: false }) {
  const exprs = /* @__PURE__ */ new Map();
  const marshal = (param) => {
    param = isNumber$1(param) ? table2.columnName(param) : param;
    isString$2(param) ? exprs.set(param, field$1(param)) : isFunction$1(param) ? resolve(table2, param).forEach(marshal) : isObject$1(param) ? assign$3(exprs, param) : error$4(`Invalid ${name2} value: ${param + ""}`);
  };
  toArray$1(params).forEach(marshal);
  if (options.preparse) {
    options.preparse(exprs);
  }
  return parse$3(exprs, { table: table2, ...options });
}
function groupby(table2, ...values2) {
  return _groupby(table2, parseValue("groupby", table2, values2.flat()));
}
function _groupby(table2, exprs) {
  return table2.create({
    groups: createGroups(table2, exprs)
  });
}
function createGroups(table2, { names = [], exprs = [], ops = [] }) {
  const n2 = names.length;
  if (n2 === 0) return null;
  if (n2 === 1 && !table2.isFiltered() && exprs[0].field) {
    const col = table2.column(exprs[0].field);
    if (col.groups) return col.groups(names);
  }
  let get2 = aggregateGet(table2, ops, exprs);
  const getKey = keyFunction(get2);
  const nrows = table2.totalRows();
  const keys2 = new Uint32Array(nrows);
  const index = {};
  const rows = [];
  const data2 = table2.data();
  const bits = table2.mask();
  if (bits) {
    for (let i2 = bits.next(0); i2 >= 0; i2 = bits.next(i2 + 1)) {
      const key2 = getKey(i2, data2) + "";
      keys2[i2] = index[key2] ??= rows.push(i2) - 1;
    }
  } else {
    for (let i2 = 0; i2 < nrows; ++i2) {
      const key2 = getKey(i2, data2) + "";
      keys2[i2] = index[key2] ??= rows.push(i2) - 1;
    }
  }
  if (!ops.length) {
    get2 = get2.map((f) => (row2) => f(row2, data2));
  }
  return { keys: keys2, get: get2, names, rows, size: rows.length };
}
function columnSet(table2) {
  return table2 ? new ColumnSet({ ...table2.data() }, table2.columnNames()) : new ColumnSet();
}
class ColumnSet {
  /**
   * Create a new column set instance.
   * @param {import('./types.js').ColumnData} [data] Initial column data.
   * @param {string[]} [names] Initial column names.
   */
  constructor(data2, names) {
    this.data = data2 || {};
    this.names = names || [];
  }
  /**
   * Add a new column to this set and return the column values.
   * @template {import('./types.js').ColumnType} T
   * @param {string} name The column name.
   * @param {T} values The column values.
   * @return {T} The provided column values.
   */
  add(name2, values2) {
    if (!this.has(name2)) this.names.push(name2 + "");
    return this.data[name2] = values2;
  }
  /**
   * Test if this column set has a columns with the given name.
   * @param {string} name A column name
   * @return {boolean} True if this set contains a column with the given name,
   *  false otherwise.
   */
  has(name2) {
    return Object.hasOwn(this.data, name2);
  }
  /**
   * Add a groupby specification to this column set.
   * @param {import('./types.js').GroupBySpec} groups A groupby specification.
   * @return {this} This column set.
   */
  groupby(groups) {
    this.groups = groups;
    return this;
  }
  /**
   * Create a new table with the contents of this column set, using the same
   * type as a given prototype table. The new table does not inherit the
   * filter, groupby, or orderby state of the prototype.
   * @template {import('./Table.js').Table} T
   * @param {T} proto A prototype table
   * @return {T} The new table.
   */
  new(proto) {
    const { data: data2, names, groups = null } = this;
    return proto.create({ data: data2, names, groups, filter: null, order: null });
  }
  /**
   * Create a derived table with the contents of this column set, using the same
   * type as a given prototype table. The new table will inherit the filter,
   * groupby, and orderby state of the prototype.
   * @template {import('./Table.js').Table} T
   * @param {T} proto A prototype table
   * @return {T} The new table.
   */
  derive(proto) {
    return proto.create(this);
  }
}
function rollup(table2, values2) {
  return _rollup(table2, parse$3(values2, { table: table2, aggronly: true, window: false }));
}
function _rollup(table2, { names, exprs, ops = [] }) {
  const cols = columnSet();
  const groups = table2.groups();
  if (groups) groupOutput(cols, groups);
  output$3(names, exprs, groups, aggregate(table2, ops), cols);
  return cols.new(table2);
}
function output$3(names, exprs, groups, result2 = [], cols) {
  if (!exprs.length) return;
  const size = groups ? groups.size : 1;
  const op2 = (id2, row2) => result2[id2][row2];
  const n2 = names.length;
  for (let i2 = 0; i2 < n2; ++i2) {
    const get2 = exprs[i2];
    if (get2.field != null) {
      cols.add(names[i2], result2[get2.field]);
    } else if (size > 1) {
      const col = cols.add(names[i2], Array(size));
      for (let j2 = 0; j2 < size; ++j2) {
        col[j2] = get2(j2, null, op2);
      }
    } else {
      cols.add(names[i2], [get2(0, null, op2)]);
    }
  }
}
function select(table2, ...columns2) {
  return _select(table2, resolve(table2, columns2.flat()));
}
function _select(table2, columns2) {
  const cols = columnSet();
  columns2.forEach((value2, curr) => {
    const next = isString$2(value2) ? value2 : curr;
    if (next) {
      const col = table2.column(curr) || error$4(`Unrecognized column: ${curr}`);
      cols.add(next, col);
    }
  });
  return cols.derive(table2);
}
function regroup(groups, filter2) {
  if (!groups || !filter2) return groups;
  const { keys: keys2, rows, size } = groups;
  const map2 = new Uint32Array(size);
  filter2.scan((row2) => map2[keys2[row2]] = 1);
  const sum = map2.reduce((sum2, val) => sum2 + val, 0);
  if (sum === size) return groups;
  const _rows = Array(sum);
  let _size = 0;
  for (let i2 = 0; i2 < size; ++i2) {
    if (map2[i2]) _rows[map2[i2] = _size++] = rows[i2];
  }
  const _keys = new Uint32Array(keys2.length);
  filter2.scan((row2) => _keys[row2] = map2[keys2[row2]]);
  return { ...groups, keys: _keys, rows: _rows, size: _size };
}
function reindex(groups, scan2, filter2, nrows) {
  const { keys: keys2, rows, size } = groups;
  let _rows = rows;
  let _size = size;
  let map2 = null;
  if (filter2) {
    map2 = new Int32Array(size);
    scan2((row2) => map2[keys2[row2]] = 1);
    const sum = map2.reduce((sum2, val) => sum2 + val, 0);
    if (sum !== size) {
      _rows = Array(sum);
      _size = 0;
      for (let i2 = 0; i2 < size; ++i2) {
        if (map2[i2]) _rows[map2[i2] = _size++] = rows[i2];
      }
    }
  }
  let r2 = -1;
  const _keys = new Uint32Array(nrows);
  const fn3 = _size !== size ? (row2) => _keys[++r2] = map2[keys2[row2]] : (row2) => _keys[++r2] = keys2[row2];
  scan2(fn3);
  return { ...groups, keys: _keys, rows: _rows, size: _size };
}
function nest(table2, idx, obj, type) {
  const agg = type === "map" || type === true ? map_agg : type === "entries" ? entries_agg : type === "object" ? object_agg : error$4('groups option must be "map", "entries", or "object".');
  const { names } = table2.groups();
  const col = uniqueName(table2.columnNames(), "_");
  let t2 = select(table2, {}).reify(idx).create({ data: { [col]: obj } });
  t2 = rollup(t2, { [col]: array_agg(col) });
  for (let i2 = names.length; --i2 >= 0; ) {
    t2 = rollup(
      groupby(t2, names.slice(0, i2)),
      // @ts-ignore
      { [col]: agg(names[i2], col) }
    );
  }
  return t2.get(col);
}
function arrayType$1(column2) {
  return isTypedArray$1(column2) ? column2.constructor : Array;
}
let Table$1 = class Table2 {
  /**
   * Instantiate a Table instance.
   * @param {import('./types.js').ColumnData} columns
   *  An object mapping column names to values.
   * @param {string[]} [names]
   *  An ordered list of column names.
   * @param {import('./BitSet.js').BitSet} [filter]
   *  A filtering BitSet.
   * @param {import('./types.js').GroupBySpec} [group]
   *  A groupby specification.
   * @param {import('./types.js').RowComparator} [order]
   *  A row comparator function.
   * @param {import('./types.js').Params} [params]
   *  An object mapping parameter names to values.
   */
  constructor(columns2, names, filter2, group, order2, params) {
    const data2 = Object.freeze({ ...columns2 });
    names = names?.slice() ?? Object.keys(data2);
    const nrows = names.length ? data2[names[0]].length : 0;
    this._names = Object.freeze(names);
    this._data = data2;
    this._total = nrows;
    this._nrows = filter2?.count() ?? nrows;
    this._mask = filter2 ?? null;
    this._group = group ?? null;
    this._order = order2 ?? null;
    this._params = params;
    this._index = null;
    this._partitions = null;
  }
  /**
   * Create a new table with the same type as this table.
   * The new table may have different data, filter, grouping, or ordering
   * based on the values of the optional configuration argument. If a
   * setting is not specified, it is inherited from the current table.
   * @param {import('./types.js').CreateOptions} [options]
   *  Creation options for the new table.
   * @return {this} A newly created table.
   */
  create({
    data: data2 = void 0,
    names = void 0,
    filter: filter2 = void 0,
    groups = void 0,
    order: order2 = void 0
  } = {}) {
    const f = filter2 !== void 0 ? filter2 : this.mask();
    return new this.constructor(
      data2 || this._data,
      names || (!data2 ? this._names : null),
      f,
      groups !== void 0 ? groups : regroup(this._group, filter2 && f),
      order2 !== void 0 ? order2 : this._order,
      this._params
    );
  }
  /**
   * Get or set table expression parameter values.
   * If called with no arguments, returns the current parameter values
   * as an object. Otherwise, adds the provided parameters to this
   * table's parameter set and returns the table. Any prior parameters
   * with names matching the input parameters are overridden.
   * @param {import('./types.js').Params} [values]
   *  The parameter values.
   * @return {this|import('./types.js').Params}
   *  The current parameter values (if called with no arguments) or this table.
   */
  params(values2) {
    if (arguments.length) {
      if (values2) {
        this._params = { ...this._params, ...values2 };
      }
      return this;
    } else {
      return this._params;
    }
  }
  /**
   * Provide an informative object string tag.
   */
  get [Symbol.toStringTag]() {
    if (!this._names) return "Object";
    const nr2 = this.numRows();
    const nc = this.numCols();
    const plural = (v) => v !== 1 ? "s" : "";
    return `Table: ${nc} col${plural(nc)} x ${nr2} row${plural(nr2)}` + (this.isFiltered() ? ` (${this.totalRows()} backing)` : "") + (this.isGrouped() ? `, ${this._group.size} groups` : "") + (this.isOrdered() ? ", ordered" : "");
  }
  /**
   * Indicates if the table has a filter applied.
   * @return {boolean} True if filtered, false otherwise.
   */
  isFiltered() {
    return !!this._mask;
  }
  /**
   * Indicates if the table has a groupby specification.
   * @return {boolean} True if grouped, false otherwise.
   */
  isGrouped() {
    return !!this._group;
  }
  /**
   * Indicates if the table has a row order comparator.
   * @return {boolean} True if ordered, false otherwise.
   */
  isOrdered() {
    return !!this._order;
  }
  /**
   * Get the backing column data for this table.
   * @return {import('./types.js').ColumnData}
   *  Object of named column instances.
   */
  data() {
    return this._data;
  }
  /**
   * Returns the filter bitset mask, if defined.
   * @return {import('./BitSet.js').BitSet} The filter bitset mask.
   */
  mask() {
    return this._mask;
  }
  /**
   * Returns the groupby specification, if defined.
   * @return {import('./types.js').GroupBySpec} The groupby specification.
   */
  groups() {
    return this._group;
  }
  /**
   * Returns the row order comparator function, if specified.
   * @return {import('./types.js').RowComparator}
   *  The row order comparator function.
   */
  comparator() {
    return this._order;
  }
  /**
   * The total number of rows in this table, counting both
   * filtered and unfiltered rows.
   * @return {number} The number of total rows.
   */
  totalRows() {
    return this._total;
  }
  /**
   * The number of active rows in this table. This number may be
   * less than the *totalRows* if the table has been filtered.
   * @return {number} The number of rows.
   */
  numRows() {
    return this._nrows;
  }
  /**
   * The number of active rows in this table. This number may be
   * less than the *totalRows* if the table has been filtered.
   * @return {number} The number of rows.
   */
  get size() {
    return this._nrows;
  }
  /**
   * The number of columns in this table.
   * @return {number} The number of columns.
   */
  numCols() {
    return this._names.length;
  }
  /**
   * Filter function invoked for each column name.
   * @callback NameFilter
   * @param {string} name The column name.
   * @param {number} index The column index.
   * @param {string[]} array The array of names.
   * @return {boolean} Returns true to retain the column name.
   */
  /**
   * The table column names, optionally filtered.
   * @param {NameFilter} [filter] An optional filter function.
   *  If unspecified, all column names are returned.
   * @return {string[]} An array of matching column names.
   */
  columnNames(filter2) {
    return filter2 ? this._names.filter(filter2) : this._names.slice();
  }
  /**
   * The column name at the given index.
   * @param {number} index The column index.
   * @return {string} The column name,
   *  or undefined if the index is out of range.
   */
  columnName(index) {
    return this._names[index];
  }
  /**
   * The column index for the given name.
   * @param {string} name The column name.
   * @return {number} The column index, or -1 if the name is not found.
   */
  columnIndex(name2) {
    return this._names.indexOf(name2);
  }
  /**
   * Get the column instance with the given name.
   * @param {string} name The column name.
   * @return {import('./types.js').ColumnType | undefined}
   *  The named column, or undefined if it does not exist.
   */
  column(name2) {
    return this._data[name2];
  }
  /**
   * Get the column instance at the given index position.
   * @param {number} index The zero-based column index.
   * @return {import('./types.js').ColumnType | undefined}
   *  The column, or undefined if it does not exist.
   */
  columnAt(index) {
    return this._data[this._names[index]];
  }
  /**
   * Get an array of values contained in a column. The resulting array
   * respects any table filter or orderby criteria.
   * @param {string} name The column name.
   * @param {ArrayConstructor | import('./types.js').TypedArrayConstructor} [constructor=Array]
   *  The array constructor for instantiating the output array.
   * @return {import('./types.js').DataValue[] | import('./types.js').TypedArray}
   *  The array of column values.
   */
  array(name2, constructor = Array) {
    const column2 = this.column(name2);
    const array2 = new constructor(this.numRows());
    let idx = -1;
    this.scan((row2) => array2[++idx] = column2.at(row2), true);
    return array2;
  }
  /**
   * Get the value for the given column and row.
   * @param {string} name The column name.
   * @param {number} [row=0] The row index, defaults to zero if not specified.
   * @return {import('./types.js').DataValue} The table value at (column, row).
   */
  get(name2, row2 = 0) {
    const column2 = this.column(name2);
    return this.isFiltered() || this.isOrdered() ? column2.at(this.indices()[row2]) : column2.at(row2);
  }
  /**
   * Returns an accessor ("getter") function for a column. The returned
   * function takes a row index as its single argument and returns the
   * corresponding column value.
   * @param {string} name The column name.
   * @return {import('./types.js').ColumnGetter} The column getter function.
   */
  getter(name2) {
    const column2 = this.column(name2);
    const indices = this.isFiltered() || this.isOrdered() ? this.indices() : null;
    if (indices) {
      return (row2) => column2.at(indices[row2]);
    } else if (column2) {
      return (row2) => column2.at(row2);
    } else {
      error$4(`Unrecognized column: ${name2}`);
    }
  }
  /**
   * Returns an object representing a table row.
   * @param {number} [row=0] The row index, defaults to zero if not specified.
   * @return {object} A row object with named properties for each column.
   */
  object(row2 = 0) {
    return objectBuilder$1(this)(row2);
  }
  /**
   * Returns an array of objects representing table rows.
   * @param {import('./types.js').ObjectsOptions} [options]
   *  The options for row object generation.
   * @return {object[]} An array of row objects.
   */
  objects(options = {}) {
    const { grouped, limit, offset: offset3 } = options;
    const names = resolve(this, options.columns || all$1());
    const createRow = rowObjectBuilder(this, names);
    const obj = [];
    this.scan(
      (row2, data2) => obj.push(createRow(row2, data2)),
      true,
      limit,
      offset3
    );
    if (grouped && this.isGrouped()) {
      const idx = [];
      this.scan((row2) => idx.push(row2), true, limit, offset3);
      return nest(this, idx, obj, grouped);
    }
    return obj;
  }
  /**
   * Returns an iterator over objects representing table rows.
   * @return {Iterator<object>} An iterator over row objects.
   */
  *[Symbol.iterator]() {
    const createRow = objectBuilder$1(this);
    const n2 = this.numRows();
    for (let i2 = 0; i2 < n2; ++i2) {
      yield createRow(i2);
    }
  }
  /**
   * Returns an iterator over column values.
   * @return {Iterator<object>} An iterator over row objects.
   */
  *values(name2) {
    const get2 = this.getter(name2);
    const n2 = this.numRows();
    for (let i2 = 0; i2 < n2; ++i2) {
      yield get2(i2);
    }
  }
  /**
   * Print the contents of this table using the console.table() method.
   * @param {import('./types.js').PrintOptions|number} options
   *  The options for row object generation, determining which rows and
   *  columns are printed. If number-valued, specifies the row limit.
   * @return {this} The table instance.
   */
  print(options = {}) {
    const opt2 = isNumber$1(options) ? { limit: +options } : { ...options, limit: 10 };
    const obj = this.objects({ ...opt2, grouped: false });
    const msg = `${this[Symbol.toStringTag]}. Showing ${obj.length} rows.`;
    console.log(msg);
    console.table(obj);
    return this;
  }
  /**
   * Returns an array of indices for all rows passing the table filter.
   * @param {boolean} [order=true] A flag indicating if the returned
   *  indices should be sorted if this table is ordered. If false, the
   *  returned indices may or may not be sorted.
   * @return {Uint32Array} An array of row indices.
   */
  indices(order2 = true) {
    if (this._index) return this._index;
    const n2 = this.numRows();
    const index = new Uint32Array(n2);
    const ordered = this.isOrdered();
    const bits = this.mask();
    let row2 = -1;
    if (bits) {
      for (let i2 = bits.next(0); i2 >= 0; i2 = bits.next(i2 + 1)) {
        index[++row2] = i2;
      }
    } else {
      for (let i2 = 0; i2 < n2; ++i2) {
        index[++row2] = i2;
      }
    }
    if (order2 && ordered) {
      const { _order, _data } = this;
      index.sort((a2, b) => _order(a2, b, _data));
    }
    if (order2 || !ordered) {
      this._index = index;
    }
    return index;
  }
  /**
   * Returns an array of indices for each group in the table.
   * If the table is not grouped, the result is the same as
   * the *indices* method, but wrapped within an array.
   * @param {boolean} [order=true] A flag indicating if the returned
   *  indices should be sorted if this table is ordered. If false, the
   *  returned indices may or may not be sorted.
   * @return {number[][] | Uint32Array[]} An array of row index arrays, one
   *  per group. The indices will be filtered if the table is filtered.
   */
  partitions(order2 = true) {
    if (this._partitions) {
      return this._partitions;
    }
    if (!this.isGrouped()) {
      return [this.indices(order2)];
    }
    const { keys: keys2, size } = this._group;
    const part = repeat(size, () => []);
    const sort = this._index;
    const bits = this.mask();
    const n2 = this.numRows();
    if (sort && this.isOrdered()) {
      for (let i2 = 0, r2; i2 < n2; ++i2) {
        r2 = sort[i2];
        part[keys2[r2]].push(r2);
      }
    } else if (bits) {
      for (let i2 = bits.next(0); i2 >= 0; i2 = bits.next(i2 + 1)) {
        part[keys2[i2]].push(i2);
      }
    } else {
      for (let i2 = 0; i2 < n2; ++i2) {
        part[keys2[i2]].push(i2);
      }
    }
    if (order2 && !sort && this.isOrdered()) {
      const compare2 = this._order;
      const data2 = this._data;
      for (let i2 = 0; i2 < size; ++i2) {
        part[i2].sort((a2, b) => compare2(a2, b, data2));
      }
    }
    if (order2 || !this.isOrdered()) {
      this._partitions = part;
    }
    return part;
  }
  /**
   * Create a new fully-materialized instance of this table.
   * All filter and orderby settings are removed from the new table.
   * Instead, the backing data itself is filtered and ordered as needed.
   * @param {number[]} [indices] Ordered row indices to materialize.
   *  If unspecified, all rows passing the table filter are used.
   * @return {this} A reified table.
   */
  reify(indices) {
    const nrows = indices ? indices.length : this.numRows();
    const names = this._names;
    let data2, groups;
    if (!indices && !this.isOrdered()) {
      if (!this.isFiltered()) {
        return this;
      } else if (nrows === this.totalRows()) {
        data2 = this.data();
      }
    }
    if (!data2) {
      const scan2 = indices ? (f) => indices.forEach(f) : (f) => this.scan(f, true);
      const ncols = names.length;
      data2 = {};
      for (let i2 = 0; i2 < ncols; ++i2) {
        const name2 = names[i2];
        const prev = this.column(name2);
        const curr = data2[name2] = new (arrayType$1(prev))(nrows);
        let r2 = -1;
        isArrayType(prev) ? scan2((row2) => curr[++r2] = prev[row2]) : scan2((row2) => curr[++r2] = prev.at(row2));
      }
      if (this.isGrouped()) {
        groups = reindex(this.groups(), scan2, !!indices, nrows);
      }
    }
    return this.create({ data: data2, names, groups, filter: null, order: null });
  }
  /**
   * Callback function to cancel a table scan.
   * @callback ScanStop
   * @return {void}
   */
  /**
   * Callback function invoked for each row of a table scan.
   * @callback ScanVisitor
   * @param {number} [row] The table row index.
   * @param {import('./types.js').ColumnData} [data]
   *  The backing table data store.
   * @param {ScanStop} [stop] Function to stop the scan early.
   *  Callees can invoke this function to prevent future calls.
   * @return {void}
   */
  /**
   * Perform a table scan, visiting each row of the table.
   * If this table is filtered, only rows passing the filter are visited.
   * @param {ScanVisitor} fn Callback invoked for each row of the table.
   * @param {boolean} [order=false] Indicates if the table should be
   *  scanned in the order determined by *orderby*. This
   *  argument has no effect if the table is unordered.
   * @property {number} [limit=Infinity] The maximum number of rows to scan.
   * @property {number} [offset=0] The row offset indicating how many
   *  initial rows to skip.
   */
  scan(fn3, order2, limit = Infinity, offset3 = 0) {
    const filter2 = this._mask;
    const nrows = this._nrows;
    const data2 = this._data;
    let i2 = offset3 || 0;
    if (i2 > nrows) return;
    const n2 = Math.min(nrows, i2 + limit);
    const stop = () => i2 = this._total;
    if (order2 && this.isOrdered() || filter2 && this._index) {
      const index = this.indices();
      const data3 = this._data;
      for (; i2 < n2; ++i2) {
        fn3(index[i2], data3, stop);
      }
    } else if (filter2) {
      let c2 = n2 - i2 + 1;
      for (i2 = filter2.nth(i2); --c2 && i2 > -1; i2 = filter2.next(i2 + 1)) {
        fn3(i2, data2, stop);
      }
    } else {
      for (; i2 < n2; ++i2) {
        fn3(i2, data2, stop);
      }
    }
  }
};
function objectBuilder$1(table2) {
  let b = table2._builder;
  if (!b) {
    const createRow = rowObjectBuilder(table2);
    const data2 = table2.data();
    if (table2.isOrdered() || table2.isFiltered()) {
      const indices = table2.indices();
      b = (row2) => createRow(indices[row2], data2);
    } else {
      b = (row2) => createRow(row2, data2);
    }
    table2._builder = b;
  }
  return b;
}
function assign$2(table2, ...others) {
  others = others.flat();
  const nrows = table2.numRows();
  const base2 = table2.reify();
  const cols = columnSet(base2).groupby(base2.groups());
  others.forEach((input2) => {
    input2 = input2 instanceof Table$1 ? input2 : new Table$1(input2);
    if (input2.numRows() !== nrows) error$4("Assign row counts do not match");
    input2 = input2.reify();
    input2.columnNames((name2) => cols.add(name2, input2.column(name2)));
  });
  return cols.new(table2);
}
function concat(table2, ...others) {
  others = others.flat();
  const trows = table2.numRows();
  const nrows = trows + others.reduce((n2, t2) => n2 + t2.numRows(), 0);
  if (trows === nrows) return table2;
  const tables = [table2, ...others];
  const cols = columnSet();
  table2.columnNames().forEach((name2) => {
    const arr = Array(nrows);
    let row2 = 0;
    tables.forEach((table3) => {
      const col = table3.column(name2) || { at: () => NULL };
      table3.scan((trow) => arr[row2++] = col.at(trow));
    });
    cols.add(name2, arr);
  });
  return cols.new(table2);
}
function relocate(table2, columns2, {
  before = void 0,
  after = void 0
} = {}) {
  const bef = before != null;
  const aft = after != null;
  if (!(bef || aft)) {
    error$4("relocate requires a before or after option.");
  }
  if (bef && aft) {
    error$4("relocate accepts only one of the before or after options.");
  }
  columns2 = resolve(table2, columns2);
  const anchors = [...resolve(table2, bef ? before : after).keys()];
  const anchor = bef ? anchors[0] : anchors.pop();
  const select2 = /* @__PURE__ */ new Map();
  table2.columnNames().forEach((name2) => {
    const assign2 = !columns2.has(name2);
    if (name2 === anchor) {
      if (aft && assign2) select2.set(name2, name2);
      for (const [key2, value2] of columns2) {
        select2.set(key2, value2);
      }
      if (aft) return;
    }
    if (assign2) select2.set(name2, name2);
  });
  return _select(table2, select2);
}
function bisector(compare2) {
  return {
    left(a2, x, lo, hi) {
      if (lo == null) lo = 0;
      if (hi == null) hi = a2.length;
      while (lo < hi) {
        const mid = lo + hi >>> 1;
        if (compare2(a2[mid], x) < 0) lo = mid + 1;
        else hi = mid;
      }
      return lo;
    },
    right(a2, x, lo, hi) {
      if (lo == null) lo = 0;
      if (hi == null) hi = a2.length;
      while (lo < hi) {
        const mid = lo + hi >>> 1;
        if (compare2(a2[mid], x) > 0) hi = mid;
        else lo = mid + 1;
      }
      return lo;
    }
  };
}
const bisect$1 = bisector(ascending);
function windowState(data2, frame, adjust, ops, aggrs) {
  let rows, peer, cells, result2, key2;
  const isPeer = (index) => peer[index - 1] === peer[index];
  const numOps = ops.length;
  const numAgg = aggrs.length;
  const evaluate = ops.length ? unroll$1(
    ["w", "r", "k"],
    "{" + concat$1(ops, (_, i2) => `r[_${i2}.id][k]=_${i2}.value(w,_${i2}.get);`) + "}",
    ops
  ) : () => {
  };
  const w2 = {
    i0: 0,
    i1: 0,
    index: 0,
    size: 0,
    peer: isPeer,
    init(partition, peers, results, group) {
      w2.index = w2.i0 = w2.i1 = 0;
      w2.size = peers.length;
      rows = partition;
      peer = peers;
      result2 = results;
      key2 = group;
      cells = aggrs ? aggrs.map((aggr) => aggr.init()) : null;
      for (let i2 = 0; i2 < numOps; ++i2) {
        ops[i2].init();
      }
      return w2;
    },
    value(index, get2) {
      return get2(rows[index], data2);
    },
    step(idx) {
      const [f0, f1] = frame;
      const n2 = w2.size;
      const p0 = w2.i0;
      const p1 = w2.i1;
      w2.i0 = f0 != null ? Math.max(0, idx - Math.abs(f0)) : 0;
      w2.i1 = f1 != null ? Math.min(n2, idx + Math.abs(f1) + 1) : n2;
      w2.index = idx;
      if (adjust) {
        if (w2.i0 > 0 && isPeer(w2.i0)) {
          w2.i0 = bisect$1.left(peer, peer[w2.i0]);
        }
        if (w2.i1 < n2 && isPeer(w2.i1)) {
          w2.i1 = bisect$1.right(peer, peer[w2.i1 - 1]);
        }
      }
      for (let i2 = 0; i2 < numAgg; ++i2) {
        const aggr = aggrs[i2];
        const cell2 = cells[i2];
        for (let j2 = p0; j2 < w2.i0; ++j2) {
          aggr.rem(cell2, rows[j2], data2);
        }
        for (let j2 = p1; j2 < w2.i1; ++j2) {
          aggr.add(cell2, rows[j2], data2);
        }
        aggr.write(cell2, result2, key2);
      }
      evaluate(w2, result2, key2);
      return result2;
    }
  };
  return w2;
}
const frameValue = (op2) => (op2.frame || [null, null]).map((v) => Number.isFinite(v) ? Math.abs(v) : null);
const peersValue = (op2) => !!op2.peers;
function windowOp(spec) {
  const { id: id2, name: name2, fields = [], params = [] } = spec;
  return {
    ...getWindow$1(name2).create(...params),
    get: fields.length ? fields[0] : null,
    id: id2
  };
}
function window$1(table2, cols, exprs, result2 = {}, ops) {
  const data2 = table2.data();
  const states = windowStates(ops, data2);
  const nstate = states.length;
  const write2 = unroll$1(
    ["r", "d", "op"],
    "{" + concat$1(cols, (_, i2) => `_${i2}[r] = $${i2}(r, d, op);`) + "}",
    cols,
    exprs
  );
  table2.partitions().forEach((rows, key2) => {
    const size = rows.length;
    const peers = windowPeers(table2, rows);
    for (let i2 = 0; i2 < nstate; ++i2) {
      states[i2].init(rows, peers, result2, key2);
    }
    const op2 = (id2) => result2[id2][key2];
    for (let index = 0; index < size; ++index) {
      for (let i2 = 0; i2 < nstate; ++i2) {
        states[i2].step(index);
      }
      write2(rows[index], data2, op2);
    }
  });
}
function windowStates(ops, data2) {
  const map2 = {};
  ops.forEach((op2) => {
    const frame = frameValue(op2);
    const peers = peersValue(op2);
    const key2 = `${frame},${peers}`;
    const { aggOps, winOps } = map2[key2] || (map2[key2] = {
      frame,
      peers,
      aggOps: [],
      winOps: []
    });
    hasAggregate(op2.name) ? aggOps.push(op2) : winOps.push(windowOp(op2));
  });
  return Object.values(map2).map((_) => windowState(
    data2,
    _.frame,
    _.peers,
    _.winOps,
    reducers(_.aggOps, _.frame[0] != null ? -1 : 1)
  ));
}
function windowPeers(table2, rows) {
  if (table2.isOrdered()) {
    const compare2 = table2.comparator();
    const data2 = table2.data();
    const nrows = rows.length;
    const peers = new Uint32Array(nrows);
    for (let i2 = 1, index = 0; i2 < nrows; ++i2) {
      peers[i2] = compare2(rows[i2 - 1], rows[i2], data2) ? ++index : index;
    }
    return peers;
  } else {
    return rows;
  }
}
function isWindowed(op2) {
  return hasWindow(op2.name) || op2.frame && (Number.isFinite(op2.frame[0]) || Number.isFinite(op2.frame[1]));
}
function derive(table2, values2, options = {}) {
  const dt = _derive(table2, parse$3(values2, { table: table2 }), options);
  return options.drop || options.before == null && options.after == null ? dt : relocate(
    dt,
    Object.keys(values2).filter((name2) => !table2.column(name2)),
    options
  );
}
function _derive(table2, { names, exprs, ops = [] }, options = {}) {
  const total = table2.totalRows();
  const cols = columnSet(options.drop ? null : table2);
  const data2 = names.map((name2) => cols.add(name2, Array(total)));
  const [aggOps, winOps] = segmentOps(ops);
  const size = table2.isGrouped() ? table2.groups().size : 1;
  const result2 = aggregate(
    table2,
    aggOps,
    repeat(ops.length, () => Array(size))
  );
  winOps.length ? window$1(table2, data2, exprs, result2, winOps) : output$2(table2, data2, exprs, result2);
  return cols.derive(table2);
}
function segmentOps(ops) {
  const aggOps = [];
  const winOps = [];
  const n2 = ops.length;
  for (let i2 = 0; i2 < n2; ++i2) {
    const op2 = ops[i2];
    op2.id = i2;
    (isWindowed(op2) ? winOps : aggOps).push(op2);
  }
  return [aggOps, winOps];
}
function output$2(table2, cols, exprs, result2) {
  const bits = table2.mask();
  const data2 = table2.data();
  const { keys: keys2 } = table2.groups() || {};
  const op2 = keys2 ? (id2, row2) => result2[id2][keys2[row2]] : (id2) => result2[id2][0];
  const m = cols.length;
  for (let j2 = 0; j2 < m; ++j2) {
    const get2 = exprs[j2];
    const col = cols[j2];
    if (bits) {
      for (let i2 = bits.next(0); i2 >= 0; i2 = bits.next(i2 + 1)) {
        col[i2] = get2(i2, data2, op2);
      }
    } else {
      const n2 = table2.totalRows();
      for (let i2 = 0; i2 < n2; ++i2) {
        col[i2] = get2(i2, data2, op2);
      }
    }
  }
}
function filter(table2, criteria) {
  const test2 = parse$3({ p: criteria }, { table: table2 });
  let predicate = test2.exprs[0];
  if (test2.ops.length) {
    const data2 = _derive(table2, test2, { drop: true }).column("p");
    predicate = (row2) => data2.at(row2);
  }
  return _filter(table2, predicate);
}
function _filter(table2, predicate) {
  const n2 = table2.totalRows();
  const bits = table2.mask();
  const data2 = table2.data();
  const filter2 = new BitSet(n2);
  if (bits) {
    for (let i2 = bits.next(0); i2 >= 0; i2 = bits.next(i2 + 1)) {
      if (predicate(i2, data2)) filter2.set(i2);
    }
  } else {
    for (let i2 = 0; i2 < n2; ++i2) {
      if (predicate(i2, data2)) filter2.set(i2);
    }
  }
  return table2.create({ filter: filter2 });
}
function dedupe(table2, ...keys2) {
  keys2 = keys2.flat();
  const gt2 = groupby(table2, keys2.length ? keys2 : table2.columnNames());
  return filter(gt2, "row_number() === 1").ungroup().reify();
}
function rowLookup(table2, hash2) {
  const lut = /* @__PURE__ */ new Map();
  table2.scan((row2, data2) => {
    const key2 = hash2(row2, data2);
    if (key2 != null && key2 === key2) {
      lut.set(key2, row2);
    }
  });
  return lut;
}
function indexLookup(idx, data2, hash2) {
  const lut = /* @__PURE__ */ new Map();
  const n2 = idx.length;
  for (let i2 = 0; i2 < n2; ++i2) {
    const row2 = idx[i2];
    const key2 = hash2(row2, data2);
    if (key2 != null && key2 === key2) {
      lut.has(key2) ? lut.get(key2).push(i2) : lut.set(key2, [i2]);
    }
  }
  return lut;
}
function intersect$1(a2, b) {
  const set3 = new Set(b);
  return a2.filter((x) => set3.has(x));
}
function parseKey(name2, table2, params) {
  const exprs = /* @__PURE__ */ new Map();
  toArray$1(params).forEach((param, i2) => {
    param = isNumber$1(param) ? table2.columnName(param) : param;
    isString$2(param) ? exprs.set(i2, field$1(param)) : isFunction$1(param) || isObject$1(param) && param.expr ? exprs.set(i2, param) : error$4(`Invalid ${name2} key value: ${param + ""}`);
  });
  const fn3 = parse$3(exprs, { table: table2, aggregate: false, window: false });
  return keyFunction(fn3.exprs, true);
}
function inferKeys(tableL, tableR, on) {
  if (!on) {
    const isect = intersect$1(tableL.columnNames(), tableR.columnNames());
    if (!isect.length) error$4("Natural join requires shared column names.");
    on = [isect, isect];
  } else if (isString$2(on)) {
    on = [on, on];
  } else if (isArray$2(on) && on.length === 1) {
    on = [on[0], on[0]];
  }
  return on;
}
function keyPredicate(tableL, tableR, onL, onR) {
  if (onL.length !== onR.length) {
    error$4("Mismatched number of join keys");
  }
  return [
    parseKey("join", tableL, onL),
    parseKey("join", tableR, onR)
  ];
}
function semijoin(tableL, tableR, on) {
  return join_filter(tableL, tableR, on, { anti: false });
}
function antijoin(tableL, tableR, on) {
  return join_filter(tableL, tableR, on, { anti: true });
}
function join_filter(tableL, tableR, on, options) {
  on = inferKeys(tableL, tableR, on);
  const predicate = isArray$2(on) ? keyPredicate(tableL, tableR, ...on.map(toArray$1)) : parse$3({ on }, { join: [tableL, tableR] }).exprs[0];
  return _join_filter(tableL, tableR, predicate, options);
}
function _join_filter(tableL, tableR, predicate, options = {}) {
  const filter2 = new BitSet(tableL.totalRows());
  const join2 = isArray$2(predicate) ? hashSemiJoin : loopSemiJoin;
  join2(filter2, tableL, tableR, predicate);
  if (options.anti) {
    filter2.not().and(tableL.mask());
  }
  return tableL.create({ filter: filter2 });
}
function hashSemiJoin(filter2, tableL, tableR, [keyL, keyR]) {
  const lut = rowLookup(tableR, keyR);
  tableL.scan((rowL, data2) => {
    const rowR = lut.get(keyL(rowL, data2));
    if (rowR >= 0) filter2.set(rowL);
  });
}
function loopSemiJoin(filter2, tableL, tableR, predicate) {
  const nL = tableL.numRows();
  const nR = tableR.numRows();
  const dataL = tableL.data();
  const dataR = tableR.data();
  if (tableL.isFiltered() || tableR.isFiltered()) {
    const idxL = tableL.indices(false);
    const idxR = tableR.indices(false);
    for (let i2 = 0; i2 < nL; ++i2) {
      const rowL = idxL[i2];
      for (let j2 = 0; j2 < nR; ++j2) {
        if (predicate(rowL, dataL, idxR[j2], dataR)) {
          filter2.set(rowL);
          break;
        }
      }
    }
  } else {
    for (let i2 = 0; i2 < nL; ++i2) {
      for (let j2 = 0; j2 < nR; ++j2) {
        if (predicate(i2, dataL, j2, dataR)) {
          filter2.set(i2);
          break;
        }
      }
    }
  }
}
function except(table2, ...others) {
  others = others.flat();
  if (others.length === 0) return table2;
  const names = table2.columnNames();
  return dedupe(others.reduce((a2, b) => antijoin(a2, b.select(names)), table2));
}
function unroll(table2, values2, options) {
  return _unroll(
    table2,
    parseValue("unroll", table2, values2),
    options && options.drop ? { ...options, drop: parseValue("unroll", table2, options.drop).names } : options
  );
}
function _unroll(table2, { names = [], exprs = [], ops = [] }, options = {}) {
  if (!names.length) return table2;
  const limit = options.limit > 0 ? +options.limit : Infinity;
  const index = options.index ? options.index === true ? "index" : options.index + "" : null;
  const drop = new Set(options.drop);
  const get2 = aggregateGet(table2, ops, exprs);
  const cols = columnSet();
  const nset = new Set(names);
  const priors = [];
  const copies = [];
  const unroll2 = [];
  table2.columnNames().forEach((name2) => {
    if (!drop.has(name2)) {
      const col = cols.add(name2, []);
      if (!nset.has(name2)) {
        priors.push(table2.column(name2));
        copies.push(col);
      }
    }
  });
  names.forEach((name2) => {
    if (!drop.has(name2)) {
      if (!cols.has(name2)) cols.add(name2, []);
      unroll2.push(cols.data[name2]);
    }
  });
  const icol = index ? cols.add(index, []) : null;
  let start2 = 0;
  const m = priors.length;
  const n2 = unroll2.length;
  const copy = (row2, maxlen) => {
    for (let i2 = 0; i2 < m; ++i2) {
      copies[i2].length = start2 + maxlen;
      copies[i2].fill(priors[i2].at(row2), start2, start2 + maxlen);
    }
  };
  const indices = icol ? (row2, maxlen) => {
    for (let i2 = 0; i2 < maxlen; ++i2) {
      icol[row2 + i2] = i2;
    }
  } : () => {
  };
  if (n2 === 1) {
    const fn3 = get2[0];
    const col = unroll2[0];
    table2.scan((row2, data2) => {
      const array2 = toArray$1(fn3(row2, data2));
      const maxlen = Math.min(array2.length, limit);
      copy(row2, maxlen);
      for (let j2 = 0; j2 < maxlen; ++j2) {
        col[start2 + j2] = array2[j2];
      }
      indices(start2, maxlen);
      start2 += maxlen;
    });
  } else {
    table2.scan((row2, data2) => {
      let maxlen = 0;
      const arrays = get2.map((fn3) => {
        const value2 = toArray$1(fn3(row2, data2));
        maxlen = Math.min(Math.max(maxlen, value2.length), limit);
        return value2;
      });
      copy(row2, maxlen);
      for (let i2 = 0; i2 < n2; ++i2) {
        const col = unroll2[i2];
        const arr = arrays[i2];
        for (let j2 = 0; j2 < maxlen; ++j2) {
          col[start2 + j2] = arr[j2];
        }
      }
      indices(start2, maxlen);
      start2 += maxlen;
    });
  }
  return cols.new(table2);
}
function fold(table2, values2, options) {
  return _fold(table2, parseValue("fold", table2, values2), options);
}
function _fold(table2, { names = [], exprs = [], ops = [] }, options = {}) {
  if (names.length === 0) return table2;
  const [k = "key", v = "value"] = options.as || [];
  const vals = aggregateGet(table2, ops, exprs);
  return _unroll(
    table2,
    {
      names: [k, v],
      exprs: [() => names, (row2, data2) => vals.map((fn3) => fn3(row2, data2))]
    },
    { ...options, drop: names }
  );
}
function ungroup(table2) {
  return table2.isGrouped() ? table2.create({ groups: null }) : table2;
}
function impute(table2, values2, options = {}) {
  values2 = parse$3(values2, { table: table2 });
  values2.names.forEach(
    (name2) => table2.column(name2) ? 0 : error$4(`Invalid impute column ${toString$2(name2)}`)
  );
  if (options.expand) {
    const opt2 = { preparse: preparse$1, window: false, aggronly: true };
    const params = parseValue("impute", table2, options.expand, opt2);
    const result2 = _rollup(ungroup(table2), params);
    return _impute(
      table2,
      values2,
      params.names,
      params.names.map((name2) => result2.get(name2, 0))
    );
  } else {
    return _impute(table2, values2);
  }
}
function preparse$1(map2) {
  map2.forEach(
    (value2, key2) => value2.field ? map2.set(key2, array_agg_distinct(value2 + "")) : 0
  );
}
function _impute(table2, values2, keys2, arrays) {
  const write2 = keys2 && keys2.length;
  table2 = write2 ? expand(table2, keys2, arrays) : table2;
  const { names, exprs, ops } = values2;
  const gets = aggregateGet(table2, ops, exprs);
  const cols = write2 ? null : columnSet(table2);
  const rows = table2.totalRows();
  names.forEach((name2, i2) => {
    const col = table2.column(name2);
    const out = write2 ? col : cols.add(name2, Array(rows));
    const get2 = gets[i2];
    table2.scan((idx) => {
      const v = col.at(idx);
      out[idx] = !isValid(v) ? get2(idx) : v;
    });
  });
  return write2 ? table2 : table2.create(cols);
}
function expand(table2, keys2, values2) {
  const groups = table2.groups();
  const data2 = table2.data();
  const keyNames = (groups ? groups.names : []).concat(keys2);
  const keyGet = (groups ? groups.get : []).concat(keys2.map((key2) => table2.getter(key2)));
  const hash2 = /* @__PURE__ */ new Set();
  const keyTable = keyFunction(keyGet);
  table2.scan((idx, data3) => hash2.add(keyTable(idx, data3)));
  const names = table2.columnNames();
  const cols = columnSet();
  const out = names.map((name2) => cols.add(name2, []));
  names.forEach((name2, i2) => {
    const old = data2[name2];
    const col = out[i2];
    table2.scan((row2) => col.push(old.at(row2)));
  });
  const keyEnum = keyFunction(keyGet.map((k, i2) => (a2) => a2[i2]));
  const set3 = unroll$1(
    "v",
    "{" + out.map((_, i2) => `_${i2}.push(v[$${i2}]);`).join("") + "}",
    out,
    names.map((name2) => keyNames.indexOf(name2))
  );
  if (groups) {
    let row2 = groups.keys.length;
    const prod = values2.reduce((p, a2) => p * a2.length, groups.size);
    const keys3 = new Uint32Array(prod + (row2 - hash2.size));
    keys3.set(groups.keys);
    enumerate(groups, values2, (vec, idx) => {
      if (!hash2.has(keyEnum(vec))) {
        set3(vec);
        keys3[row2++] = idx[0];
      }
    });
    cols.groupby({ ...groups, keys: keys3 });
  } else {
    enumerate(groups, values2, (vec) => {
      if (!hash2.has(keyEnum(vec))) set3(vec);
    });
  }
  return cols.new(table2);
}
function enumerate(groups, values2, callback) {
  const offset3 = groups ? groups.get.length : 0;
  const pad3 = groups ? 1 : 0;
  const len = pad3 + values2.length;
  const lens = new Int32Array(len);
  const idxs = new Int32Array(len);
  const set3 = [];
  if (groups) {
    const { get: get2, rows, size } = groups;
    lens[0] = size;
    set3.push((vec2, idx) => {
      const row2 = rows[idx];
      for (let i2 = 0; i2 < offset3; ++i2) {
        vec2[i2] = get2[i2](row2);
      }
    });
  }
  values2.forEach((a2, i2) => {
    const j2 = i2 + offset3;
    lens[i2 + pad3] = a2.length;
    set3.push((vec2, idx) => vec2[j2] = a2[idx]);
  });
  const vec = Array(offset3 + values2.length);
  for (let i2 = 0; i2 < len; ++i2) {
    set3[i2](vec, 0);
  }
  callback(vec, idxs);
  for (let i2 = len - 1; i2 >= 0; ) {
    const idx = ++idxs[i2];
    if (idx < lens[i2]) {
      set3[i2](vec, idx);
      callback(vec, idxs);
      i2 = len - 1;
    } else {
      idxs[i2] = 0;
      set3[i2](vec, 0);
      --i2;
    }
  }
}
function intersect(table2, ...others) {
  others = others.flat();
  const names = table2.columnNames();
  return others.length ? dedupe(others.reduce((a2, b) => semijoin(a2, b.select(names)), table2)) : table2.reify([]);
}
const OPT_L = { aggregate: false, window: false };
const OPT_R = { ...OPT_L, index: 1 };
const NONE = -Infinity;
function cross(table2, other, values2, options) {
  return join$1(
    table2,
    other,
    () => true,
    values2,
    { ...options, left: true, right: true }
  );
}
function join$1(tableL, tableR, on, values2, options = {}) {
  on = inferKeys(tableL, tableR, on);
  const optParse = { join: [tableL, tableR] };
  let predicate;
  if (isArray$2(on)) {
    const [onL, onR] = on.map(toArray$1);
    predicate = keyPredicate(tableL, tableR, onL, onR);
    if (!values2) {
      values2 = inferValues(tableL, onL, onR, options);
    }
  } else {
    predicate = parse$3({ on }, optParse).exprs[0];
    if (!values2) {
      values2 = [all$1(), all$1()];
    }
  }
  return _join(
    tableL,
    tableR,
    predicate,
    parseValues$1(tableL, tableR, values2, optParse, options && options.suffix),
    options
  );
}
function inferValues(tableL, onL, onR, options) {
  const isect = [];
  onL.forEach((s, i2) => isString$2(s) && s === onR[i2] ? isect.push(s) : 0);
  const vR = not(isect);
  if (options.left && options.right) {
    const shared = new Set(isect);
    return [
      tableL.columnNames().map((s) => {
        const c2 = `[${toString$2(s)}]`;
        return shared.has(s) ? { [s]: `(a, b) => a${c2} == null ? b${c2} : a${c2}` } : s;
      }),
      vR
    ];
  }
  return options.right ? [vR, all$1()] : [all$1(), vR];
}
function parseValues$1(tableL, tableR, values2, optParse, suffix = []) {
  if (isArray$2(values2)) {
    let vL, vR, vJ, n2 = values2.length;
    vL = vR = vJ = { names: [], exprs: [] };
    if (n2--) {
      vL = parseValue("join", tableL, values2[0], optParse);
    }
    if (n2--) {
      vR = parseValue("join", tableR, values2[1], OPT_R);
    }
    if (n2--) {
      vJ = parse$3(values2[2], optParse);
    }
    const rename2 = /* @__PURE__ */ new Set();
    const namesL = new Set(vL.names);
    vR.names.forEach((name2) => {
      if (namesL.has(name2)) {
        rename2.add(name2);
      }
    });
    if (rename2.size) {
      suffix[0] !== "" && rekey(vL.names, rename2, suffix[0] || "_1");
      suffix[1] !== "" && rekey(vR.names, rename2, suffix[1] || "_2");
    }
    return {
      names: vL.names.concat(vR.names, vJ.names),
      exprs: vL.exprs.concat(vR.exprs, vJ.exprs)
    };
  } else {
    return parse$3(values2, optParse);
  }
}
function rekey(names, rename2, suffix) {
  names.forEach((name2, i2) => rename2.has(name2) ? names[i2] = name2 + suffix : 0);
}
function emitter(columns2, getters) {
  const args2 = ["i", "a", "j", "b"];
  return unroll$1(
    args2,
    "{" + concat$1(columns2, (_, i2) => `_${i2}.push($${i2}(${args2}));`) + "}",
    columns2,
    getters
  );
}
function _join(tableL, tableR, predicate, { names, exprs }, options = {}) {
  const dataL = tableL.data();
  const idxL = tableL.indices(false);
  const nL = idxL.length;
  const hitL = new Int32Array(nL);
  const dataR = tableR.data();
  const idxR = tableR.indices(false);
  const nR = idxR.length;
  const hitR = new Int32Array(nR);
  const ncols = names.length;
  const cols = columnSet();
  const columns2 = Array(ncols);
  const getters = Array(ncols);
  for (let i2 = 0; i2 < names.length; ++i2) {
    columns2[i2] = cols.add(names[i2], []);
    getters[i2] = exprs[i2];
  }
  const emit = emitter(columns2, getters);
  const join2 = isArray$2(predicate) ? hashJoin : loopJoin;
  join2(emit, predicate, dataL, dataR, idxL, idxR, hitL, hitR, nL, nR);
  if (options.left) {
    for (let i2 = 0; i2 < nL; ++i2) {
      if (!hitL[i2]) {
        emit(idxL[i2], dataL, NONE, dataR);
      }
    }
  }
  if (options.right) {
    for (let j2 = 0; j2 < nR; ++j2) {
      if (!hitR[j2]) {
        emit(NONE, dataL, idxR[j2], dataR);
      }
    }
  }
  return cols.new(tableL);
}
function loopJoin(emit, predicate, dataL, dataR, idxL, idxR, hitL, hitR, nL, nR) {
  for (let i2 = 0; i2 < nL; ++i2) {
    const rowL = idxL[i2];
    for (let j2 = 0; j2 < nR; ++j2) {
      const rowR = idxR[j2];
      if (predicate(rowL, dataL, rowR, dataR)) {
        emit(rowL, dataL, rowR, dataR);
        hitL[i2] = 1;
        hitR[j2] = 1;
      }
    }
  }
}
function hashJoin(emit, [keyL, keyR], dataL, dataR, idxL, idxR, hitL, hitR, nL, nR) {
  let dataScan, keyScan, hitScan, idxScan;
  let dataHash, keyHash, hitHash, idxHash;
  let emitScan = emit;
  if (nL >= nR) {
    dataScan = dataL;
    keyScan = keyL;
    hitScan = hitL;
    idxScan = idxL;
    dataHash = dataR;
    keyHash = keyR;
    hitHash = hitR;
    idxHash = idxR;
  } else {
    dataScan = dataR;
    keyScan = keyR;
    hitScan = hitR;
    idxScan = idxR;
    dataHash = dataL;
    keyHash = keyL;
    hitHash = hitL;
    idxHash = idxL;
    emitScan = (i2, a2, j2, b) => emit(j2, b, i2, a2);
  }
  const lut = indexLookup(idxHash, dataHash, keyHash);
  const m = idxScan.length;
  for (let j2 = 0; j2 < m; ++j2) {
    const rowScan = idxScan[j2];
    const list2 = lut.get(keyScan(rowScan, dataScan));
    if (list2) {
      const n2 = list2.length;
      for (let k = 0; k < n2; ++k) {
        const i2 = list2[k];
        emitScan(rowScan, dataScan, idxHash[i2], dataHash);
        hitHash[i2] = 1;
      }
      hitScan[j2] = 1;
    }
  }
}
function lookup(tableL, tableR, on, ...values2) {
  on = inferKeys(tableL, tableR, on);
  values2 = values2.length === 0 ? [not(tableL.columnNames())] : values2.flat();
  return _lookup(
    tableL,
    tableR,
    [parseKey("lookup", tableL, on[0]), parseKey("lookup", tableR, on[1])],
    parseValue("lookup", tableR, values2)
  );
}
function _lookup(tableL, tableR, [keyL, keyR], { names, exprs, ops = [] }) {
  const cols = columnSet(tableL);
  const total = tableL.totalRows();
  names.forEach((name2) => cols.add(name2, Array(total).fill(NULL)));
  const lut = rowLookup(tableR, keyR);
  const set3 = unroll$1(
    ["lr", "rr", "data"],
    "{" + concat$1(names, (_, i2) => `_[${i2}][lr] = $[${i2}](rr, data);`) + "}",
    names.map((name2) => cols.data[name2]),
    aggregateGet(tableR, ops, exprs)
  );
  const dataR = tableR.data();
  tableL.scan((lrow, data2) => {
    const rrow = lut.get(keyL(lrow, data2));
    if (rrow >= 0) set3(lrow, rrow, dataR);
  });
  return cols.derive(tableL);
}
const _compare = (u, v, lt, gt2) => `((u = ${u}) < (v = ${v}) || u == null) && v != null ? ${lt} : (u > v || v == null) && u != null ? ${gt2} : ((v = v instanceof Date ? +v : v), (u = u instanceof Date ? +u : u)) !== u && v === v ? ${lt} : v !== v && u === u ? ${gt2} : `;
const _collate = (u, v, lt, gt2, f) => `(v = ${v}, (u = ${u}) == null && v == null) ? 0 : v == null ? ${gt2} : u == null ? ${lt} : (u = ${f}(u,v)) ? u : `;
function compare$1(table2, fields) {
  const names = [];
  const exprs = [];
  const fn3 = [];
  let keys2 = null, opA = "0", opB = "0";
  if (table2.isGrouped()) {
    keys2 = table2.groups().keys;
    opA = "ka";
    opB = "kb";
  }
  const { ops } = parse$3(fields, {
    table: table2,
    value: (name2, node2) => {
      names.push(name2);
      if (node2.escape) {
        const f = (i2) => `fn[${fn3.length}](${i2}, data)`;
        exprs.push([f("a"), f("b")]);
        fn3.push(node2.escape);
      } else {
        exprs.push([
          codegen(node2, { index: "a", op: opA }),
          codegen(node2, { index: "b", op: opB })
        ]);
      }
    },
    window: false
  });
  const result2 = aggregate(table2, ops);
  const op2 = (id2, row2) => result2[id2][row2];
  const n2 = names.length;
  let code2 = "return (a, b) => {" + (op2 && table2.isGrouped() ? "const ka = keys[a], kb = keys[b];" : "") + "let u, v; return ";
  for (let i2 = 0; i2 < n2; ++i2) {
    const field2 = fields.get(names[i2]);
    const o = field2.desc ? -1 : 1;
    const [u, v] = exprs[i2];
    if (field2.collate) {
      code2 += _collate(u, v, -o, o, `${o < 0 ? "-" : ""}fn[${fn3.length}]`);
      fn3.push(field2.collate);
    } else {
      code2 += _compare(u, v, -o, o);
    }
  }
  code2 += "0;};";
  return Function("op", "keys", "fn", "data", code2)(op2, keys2, fn3, table2.data());
}
function orderby(table2, ...values2) {
  return _orderby(table2, parseValues(table2, values2.flat()));
}
function parseValues(table2, params) {
  let index = -1;
  const exprs = /* @__PURE__ */ new Map();
  const add2 = (val) => exprs.set(++index + "", val);
  params.forEach((param) => {
    const expr = param.expr != null ? param.expr : param;
    if (isObject$1(expr) && !isFunction$1(expr)) {
      for (const key2 in expr) add2(expr[key2]);
    } else {
      add2(
        isNumber$1(expr) ? field$1(param, table2.columnName(expr)) : isString$2(expr) ? field$1(param) : isFunction$1(expr) ? param : error$4(`Invalid orderby field: ${param + ""}`)
      );
    }
  });
  return compare$1(table2, exprs);
}
function _orderby(table2, comparator) {
  return table2.create({ order: comparator });
}
function pivot(table2, on, values2, options) {
  return _pivot(
    table2,
    parseValue("fold", table2, on),
    parseValue("fold", table2, values2, { preparse, window: false, aggronly: true }),
    options
  );
}
function preparse(map2) {
  map2.forEach(
    (value2, key2) => value2.field ? map2.set(key2, any(value2 + "")) : 0
  );
}
const opt = (value2, defaultValue) => value2 != null ? value2 : defaultValue;
function _pivot(table2, on, values2, options = {}) {
  const { keys: keys2, keyColumn } = pivotKeys(table2, on, options);
  const vsep = opt(options.valueSeparator, "_");
  const namefn = values2.names.length > 1 ? (i2, name2) => name2 + vsep + keys2[i2] : (i2) => keys2[i2];
  const results = keys2.map(
    (k) => aggregate(table2, values2.ops.map((op2) => {
      if (op2.name === "count") {
        const fn3 = (r2) => k === keyColumn[r2] ? 1 : NaN;
        fn3.toString = () => k + ":1";
        return { ...op2, name: "sum", fields: [fn3] };
      }
      const fields = op2.fields.map((f) => {
        const fn3 = (r2, d) => k === keyColumn[r2] ? f(r2, d) : NaN;
        fn3.toString = () => k + ":" + f;
        return fn3;
      });
      return { ...op2, fields };
    }))
  );
  return output$1(values2, namefn, table2.groups(), results).new(table2);
}
function pivotKeys(table2, on, options) {
  const limit = options.limit > 0 ? +options.limit : Infinity;
  const sort = opt(options.sort, true);
  const ksep = opt(options.keySeparator, "_");
  const get2 = aggregateGet(table2, on.ops, on.exprs);
  const key2 = get2.length === 1 ? get2[0] : (row2, data2) => get2.map((fn3) => fn3(row2, data2)).join(ksep);
  const kcol = Array(table2.totalRows());
  table2.scan((row2, data2) => kcol[row2] = key2(row2, data2));
  const uniq = aggregate(
    ungroup(table2),
    [{
      id: 0,
      name: "array_agg_distinct",
      fields: [((row2) => kcol[row2])],
      params: []
    }]
  )[0][0];
  const keys2 = sort ? uniq.sort() : uniq;
  return {
    keys: Number.isFinite(limit) ? keys2.slice(0, limit) : keys2,
    keyColumn: kcol
  };
}
function output$1({ names, exprs }, namefn, groups, results) {
  const size = groups ? groups.size : 1;
  const cols = columnSet();
  const m = results.length;
  const n2 = names.length;
  let result2;
  const op2 = (id2, row2) => result2[id2][row2];
  if (groups) groupOutput(cols, groups);
  for (let i2 = 0; i2 < n2; ++i2) {
    const get2 = exprs[i2];
    if (get2.field != null) {
      for (let j2 = 0; j2 < m; ++j2) {
        cols.add(namefn(j2, names[i2]), results[j2][get2.field]);
      }
    } else if (size > 1) {
      for (let j2 = 0; j2 < m; ++j2) {
        result2 = results[j2];
        const col = cols.add(namefn(j2, names[i2]), Array(size));
        for (let k = 0; k < size; ++k) {
          col[k] = get2(k, null, op2);
        }
      }
    } else {
      for (let j2 = 0; j2 < m; ++j2) {
        result2 = results[j2];
        cols.add(namefn(j2, names[i2]), [get2(0, null, op2)]);
      }
    }
  }
  return cols;
}
function reduce(table2, reducer) {
  const cols = columnSet();
  const groups = table2.groups();
  const { get: get2, names = [], rows, size = 1 } = groups || {};
  const counts = new Uint32Array(size + 1);
  names.forEach((name2) => cols.add(name2, null));
  const cells = groups ? reduceGroups(table2, reducer, groups) : [reduceFlat(table2, reducer)];
  reducer.outputs().map((name2) => cols.add(name2, []));
  const n2 = counts.length - 1;
  let len = 0;
  for (let i2 = 0; i2 < n2; ++i2) {
    len += counts[i2 + 1] = reducer.write(cells[i2], cols.data, counts[i2]);
  }
  if (groups) {
    const data2 = table2.data();
    names.forEach((name2, index) => {
      const column2 = cols.data[name2] = Array(len);
      const getter = get2[index];
      for (let i2 = 0, j2 = 0; i2 < size; ++i2) {
        column2.fill(getter(rows[i2], data2), j2, j2 += counts[i2 + 1]);
      }
    });
  }
  return cols.new(table2);
}
function rename(table2, ...columns2) {
  const map2 = /* @__PURE__ */ new Map();
  table2.columnNames((x) => (map2.set(x, x), 0));
  return _select(table2, resolve(table2, columns2.flat(), map2));
}
function sample$2(buffer2, replace2, index, weight) {
  return (replace2 ? weight ? sampleRW : sampleRU : weight ? sampleNW : sampleNU)(buffer2.length, buffer2, index, weight);
}
function sampleRU(size, buffer2, index) {
  const n2 = index.length;
  for (let i2 = 0; i2 < size; ++i2) {
    buffer2[i2] = index[n2 * random$2() | 0];
  }
  return buffer2;
}
function sampleRW(size, buffer2, index, weight) {
  const n2 = index.length;
  const w2 = new Float64Array(n2);
  let sum = 0;
  for (let i2 = 0; i2 < n2; ++i2) {
    w2[i2] = sum += weight(index[i2]);
  }
  const bisect2 = bisector(ascending).right;
  for (let i2 = 0; i2 < size; ++i2) {
    buffer2[i2] = index[bisect2(w2, sum * random$2())];
  }
  return buffer2;
}
function sampleNU(size, buffer2, index) {
  const n2 = index.length;
  if (size >= n2) return index;
  for (let i2 = 0; i2 < size; ++i2) {
    buffer2[i2] = index[i2];
  }
  for (let i2 = size; i2 < n2; ++i2) {
    const j2 = i2 * random$2();
    if (j2 < size) {
      buffer2[j2 | 0] = index[i2];
    }
  }
  return buffer2;
}
function sampleNW(size, buffer2, index, weight) {
  const n2 = index.length;
  if (size >= n2) return index;
  const w2 = new Float32Array(n2);
  const k = new Uint32Array(n2);
  for (let i2 = 0; i2 < n2; ++i2) {
    k[i2] = i2;
    w2[i2] = -Math.log(random$2()) / weight(index[i2]);
  }
  k.sort((a2, b) => w2[a2] - w2[b]);
  for (let i2 = 0; i2 < size; ++i2) {
    buffer2[i2] = index[k[i2]];
  }
  return buffer2;
}
function shuffle(array2, lo = 0, hi = array2.length) {
  let n2 = hi - (lo = +lo);
  while (n2) {
    const i2 = random$2() * n2-- | 0;
    const v = array2[n2 + lo];
    array2[n2 + lo] = array2[i2 + lo];
    array2[i2 + lo] = v;
  }
  return array2;
}
function sample$1(table2, size, options = {}) {
  return _sample(
    table2,
    parseSize(table2, size),
    parseWeight(table2, options.weight),
    options
  );
}
const get$1 = (col) => (row2) => col.at(row2) || 0;
function parseSize(table2, size) {
  return isNumber$1(size) ? () => size : get$1(_rollup(table2, parse$3({ size }, { table: table2, window: false })).column("size"));
}
function parseWeight(table2, w2) {
  if (w2 == null) return null;
  w2 = isNumber$1(w2) ? table2.columnName(w2) : w2;
  return get$1(
    isString$2(w2) ? table2.column(w2) : _derive(table2, parse$3({ w: w2 }, { table: table2 }), { drop: true }).column("w")
  );
}
function _sample(table2, size, weight, options = {}) {
  const { replace: replace2, shuffle: shuffle$1 } = options;
  const parts = table2.partitions(false);
  let total = 0;
  size = parts.map((idx, group) => {
    let s = size(group);
    total += s = replace2 ? s : Math.min(idx.length, s);
    return s;
  });
  const samples = new Uint32Array(total);
  let curr = 0;
  parts.forEach((idx, group) => {
    const sz = size[group];
    const buf2 = samples.subarray(curr, curr += sz);
    if (!replace2 && sz === idx.length) {
      buf2.set(idx);
    } else {
      sample$2(buf2, replace2, idx, weight);
    }
  });
  if (shuffle$1 !== false && (parts.length > 1 || !replace2)) {
    shuffle(samples);
  }
  return table2.reify(samples);
}
function slice$1(start2 = 0, end2 = Infinity) {
  return `${prep$1(start2)} < row_number() && row_number() <= ${prep$1(end2)}`;
}
function prep$1(index) {
  return index < 0 ? `count() + ${index}` : index;
}
function slice(table2, start2 = 0, end2 = Infinity) {
  if (table2.isGrouped()) {
    return filter(table2, slice$1(start2, end2)).reify();
  }
  const indices = [];
  const nrows = table2.numRows();
  start2 = Math.max(0, start2 + (start2 < 0 ? nrows : 0));
  end2 = Math.min(nrows, Math.max(0, end2 + (end2 < 0 ? nrows : 0)));
  table2.scan((row2) => indices.push(row2), true, end2 - start2, start2);
  return table2.reify(indices);
}
function spread(table2, values2, options) {
  return _spread(table2, parseValue("spread", table2, values2), options);
}
function _spread(table2, { names, exprs, ops = [] }, options = {}) {
  if (names.length === 0) return table2;
  const as = names.length === 1 && options.as || [];
  const drop = options.drop == null ? true : !!options.drop;
  const limit = options.limit == null ? as.length || Infinity : Math.max(1, +options.limit || 1);
  const get2 = aggregateGet(table2, ops, exprs);
  const cols = columnSet();
  const map2 = names.reduce((map3, name2, i2) => map3.set(name2, i2), /* @__PURE__ */ new Map());
  const add2 = (index, name2) => {
    const columns2 = spreadCols(table2, get2[index], limit);
    const n2 = columns2.length;
    for (let i2 = 0; i2 < n2; ++i2) {
      cols.add(as[i2] || `${name2}_${i2 + 1}`, columns2[i2]);
    }
  };
  table2.columnNames().forEach((name2) => {
    if (map2.has(name2)) {
      if (!drop) cols.add(name2, table2.column(name2));
      add2(map2.get(name2), name2);
      map2.delete(name2);
    } else {
      cols.add(name2, table2.column(name2));
    }
  });
  map2.forEach(add2);
  return cols.derive(table2);
}
function spreadCols(table2, get2, limit) {
  const nrows = table2.totalRows();
  const columns2 = [];
  table2.scan((row2, data2) => {
    const values2 = toArray$1(get2(row2, data2));
    const n2 = Math.min(values2.length, limit);
    while (columns2.length < n2) {
      columns2.push(Array(nrows).fill(NULL));
    }
    for (let i2 = 0; i2 < n2; ++i2) {
      columns2[i2][row2] = values2[i2];
    }
  });
  return columns2;
}
function union$1(table2, ...others) {
  return dedupe(concat(table2, others.flat()));
}
function unorder(table2) {
  return table2.isOrdered() ? table2.create({ order: null }) : table2;
}
const MAGIC = Uint8Array.of(65, 82, 82, 79, 87, 49);
const EOS = Uint8Array.of(255, 255, 255, 255, 0, 0, 0, 0);
const Version = (
  /** @type {const} */
  {
    /** 0.1.0 (October 2016). */
    V1: 0,
    /** >= 0.8.0 (December 2017). Non-backwards compatible with V3. */
    V4: 3,
    /**
     * >= 1.0.0 (July 2020). Backwards compatible with V4 (V5 readers can read V4
     * metadata and IPC messages). Implementations are recommended to provide a
     * V4 compatibility mode with V5 format changes disabled.
     *
     * Incompatible changes between V4 and V5:
     * - Union buffer layout has changed.
     *   In V5, Unions don't have a validity bitmap buffer.
     */
    V5: 4
  }
);
const Endianness = (
  /** @type {const} */
  {
    Little: 0
  }
);
const MessageHeader = (
  /** @type {const} */
  {
    NONE: 0,
    /**
     * A Schema describes the columns in a record batch.
     */
    Schema: 1,
    /**
     * For sending dictionary encoding information. Any Field can be
     * dictionary-encoded, but in this case none of its children may be
     * dictionary-encoded.
     * There is one vector / column per dictionary, but that vector / column
     * may be spread across multiple dictionary batches by using the isDelta
     * flag.
     */
    DictionaryBatch: 2,
    /**
     * A data header describing the shared memory layout of a "record" or "row"
     * batch. Some systems call this a "row batch" internally and others a "record
     * batch".
     */
    RecordBatch: 3,
    /**
     * EXPERIMENTAL: Metadata for n-dimensional arrays, aka "tensors" or
     * "ndarrays". Arrow implementations in general are not required to implement
     * this type.
     *
     * Not currently supported by Flechette.
     */
    Tensor: 4,
    /**
     * EXPERIMENTAL: Metadata for n-dimensional sparse arrays, aka "sparse
     * tensors". Arrow implementations in general are not required to implement
     * this type.
     *
     * Not currently supported by Flechette.
     */
    SparseTensor: 5
  }
);
const Type = (
  /** @type {const} */
  {
    /**
     * Dictionary types compress data by using a set of integer indices to
     * lookup potentially repeated vales in a separate dictionary of values.
     *
     * This type entry is provided for API convenience, it does not occur
     * in actual Arrow IPC binary data.
     */
    Dictionary: -1,
    /** No data type. Included for flatbuffer compatibility. */
    NONE: 0,
    /** Null values only. */
    Null: 1,
    /** Integers, either signed or unsigned, with 8, 16, 32, or 64 bit widths. */
    Int: 2,
    /** Floating point numbers with 16, 32, or 64 bit precision. */
    Float: 3,
    /** Opaque binary data. */
    Binary: 4,
    /** Unicode with UTF-8 encoding. */
    Utf8: 5,
    /** Booleans represented as 8 bit bytes. */
    Bool: 6,
    /**
     * Exact decimal value represented as an integer value in two's complement.
     * Currently only 128-bit (16-byte) and 256-bit (32-byte) integers are used.
     * The representation uses the endianness indicated in the schema.
     */
    Decimal: 7,
    /**
     * Date is either a 32-bit or 64-bit signed integer type representing an
     * elapsed time since UNIX epoch (1970-01-01), stored in either of two units:
     * - Milliseconds (64 bits) indicating UNIX time elapsed since the epoch (no
     * leap seconds), where the values are evenly divisible by 86400000
     * - Days (32 bits) since the UNIX epoch
     */
    Date: 8,
    /**
     * Time is either a 32-bit or 64-bit signed integer type representing an
     * elapsed time since midnight, stored in either of four units: seconds,
     * milliseconds, microseconds or nanoseconds.
     *
     * The integer `bitWidth` depends on the `unit` and must be one of the following:
     * - SECOND and MILLISECOND: 32 bits
     * - MICROSECOND and NANOSECOND: 64 bits
     *
     * The allowed values are between 0 (inclusive) and 86400 (=24*60*60) seconds
     * (exclusive), adjusted for the time unit (for example, up to 86400000
     * exclusive for the MILLISECOND unit).
     * This definition doesn't allow for leap seconds. Time values from
     * measurements with leap seconds will need to be corrected when ingesting
     * into Arrow (for example by replacing the value 86400 with 86399).
     */
    Time: 9,
    /**
     * Timestamp is a 64-bit signed integer representing an elapsed time since a
     * fixed epoch, stored in either of four units: seconds, milliseconds,
     * microseconds or nanoseconds, and is optionally annotated with a timezone.
     *
     * Timestamp values do not include any leap seconds (in other words, all
     * days are considered 86400 seconds long).
     *
     * The timezone is an optional string for the name of a timezone, one of:
     *
     *  - As used in the Olson timezone database (the "tz database" or
     *    "tzdata"), such as "America/New_York".
     *  - An absolute timezone offset of the form "+XX:XX" or "-XX:XX",
     *    such as "+07:30".
     *
     * Whether a timezone string is present indicates different semantics about
     * the data.
     */
    Timestamp: 10,
    /**
     * A "calendar" interval which models types that don't necessarily
     * have a precise duration without the context of a base timestamp (e.g.
     * days can differ in length during day light savings time transitions).
     * All integers in the units below are stored in the endianness indicated
     * by the schema.
     *
     *  - YEAR_MONTH - Indicates the number of elapsed whole months, stored as
     *    4-byte signed integers.
     *  - DAY_TIME - Indicates the number of elapsed days and milliseconds (no
     *    leap seconds), stored as 2 contiguous 32-bit signed integers (8-bytes
     *    in total). Support of this IntervalUnit is not required for full arrow
     *    compatibility.
     *  - MONTH_DAY_NANO - A triple of the number of elapsed months, days, and
     *    nanoseconds. The values are stored contiguously in 16-byte blocks.
     *    Months and days are encoded as 32-bit signed integers and nanoseconds
     *    is encoded as a 64-bit signed integer. Nanoseconds does not allow for
     *    leap seconds. Each field is independent (e.g. there is no constraint
     *    that nanoseconds have the same sign as days or that the quantity of
     *    nanoseconds represents less than a day's worth of time).
     */
    Interval: 11,
    /**
     * List (vector) data supporting variably-sized lists.
     * A list has a single child data type for list entries.
     */
    List: 12,
    /**
     * A struct consisting of multiple named child data types.
     */
    Struct: 13,
    /**
     * A union is a complex type with parallel child data types. By default ids
     * in the type vector refer to the offsets in the children. Optionally
     * typeIds provides an indirection between the child offset and the type id.
     * For each child `typeIds[offset]` is the id used in the type vector.
     */
    Union: 14,
    /**
     * Binary data where each entry has the same fixed size.
     */
    FixedSizeBinary: 15,
    /**
     * List (vector) data where every list has the same fixed size.
     * A list has a single child data type for list entries.
     */
    FixedSizeList: 16,
    /**
     * A Map is a logical nested type that is represented as
     * List<entries: Struct<key: K, value: V>>
     *
     * In this layout, the keys and values are each respectively contiguous. We do
     * not constrain the key and value types, so the application is responsible
     * for ensuring that the keys are hashable and unique. Whether the keys are sorted
     * may be set in the metadata for this field.
     *
     * In a field with Map type, the field has a child Struct field, which then
     * has two children: key type and the second the value type. The names of the
     * child fields may be respectively "entries", "key", and "value", but this is
     * not enforced.
     *
     * Map
     * ```text
     *   - child[0] entries: Struct
     *   - child[0] key: K
     *   - child[1] value: V
     *  ```
     * Neither the "entries" field nor the "key" field may be nullable.
     *
     * The metadata is structured so that Arrow systems without special handling
     * for Map can make Map an alias for List. The "layout" attribute for the Map
     * field must have the same contents as a List.
     */
    Map: 17,
    /**
     * An absolute length of time unrelated to any calendar artifacts. For the
     * purposes of Arrow implementations, adding this value to a Timestamp
     * ("t1") naively (i.e. simply summing the two numbers) is acceptable even
     * though in some cases the resulting Timestamp (t2) would not account for
     * leap-seconds during the elapsed time between "t1" and "t2". Similarly,
     * representing the difference between two Unix timestamp is acceptable, but
     * would yield a value that is possibly a few seconds off from the true
     * elapsed time.
     *
     * The resolution defaults to millisecond, but can be any of the other
     * supported TimeUnit values as with Timestamp and Time types. This type is
     * always represented as an 8-byte integer.
     */
    Duration: 18,
    /**
     * Same as Binary, but with 64-bit offsets, allowing representation of
     * extremely large data values.
     */
    LargeBinary: 19,
    /**
     * Same as Utf8, but with 64-bit offsets, allowing representation of
     * extremely large data values.
     */
    LargeUtf8: 20,
    /**
     * Same as List, but with 64-bit offsets, allowing representation of
     * extremely large data values.
     */
    LargeList: 21,
    /**
     * Contains two child arrays, run_ends and values. The run_ends child array
     * must be a 16/32/64-bit integer array which encodes the indices at which
     * the run with the value in each corresponding index in the values child
     * array ends. Like list/struct types, the value array can be of any type.
     */
    RunEndEncoded: 22,
    /**
     * Logically the same as Binary, but the internal representation uses a view
     * struct that contains the string length and either the string's entire data
     * inline (for small strings) or an inlined prefix, an index of another buffer,
     * and an offset pointing to a slice in that buffer (for non-small strings).
     *
     * Since it uses a variable number of data buffers, each Field with this type
     * must have a corresponding entry in `variadicBufferCounts`.
     */
    BinaryView: 23,
    /**
     * Logically the same as Utf8, but the internal representation uses a view
     * struct that contains the string length and either the string's entire data
     * inline (for small strings) or an inlined prefix, an index of another buffer,
     * and an offset pointing to a slice in that buffer (for non-small strings).
     *
     * Since it uses a variable number of data buffers, each Field with this type
     * must have a corresponding entry in `variadicBufferCounts`.
     */
    Utf8View: 24,
    /**
     * Represents the same logical types that List can, but contains offsets and
     * sizes allowing for writes in any order and sharing of child values among
     * list values.
     */
    ListView: 25,
    /**
     * Same as ListView, but with 64-bit offsets and sizes, allowing to represent
     * extremely large data values.
     */
    LargeListView: 26
  }
);
const Precision = (
  /** @type {const} */
  {
    /** 16-bit floating point number. */
    HALF: 0,
    /** 32-bit floating point number. */
    SINGLE: 1,
    /** 64-bit floating point number. */
    DOUBLE: 2
  }
);
const DateUnit = (
  /** @type {const} */
  {
    /* Days (as 32 bit int) since the UNIX epoch. */
    DAY: 0,
    /**
     * Milliseconds (as 64 bit int) indicating UNIX time elapsed since the epoch
     * (no leap seconds), with values evenly divisible by 86400000.
     */
    MILLISECOND: 1
  }
);
const TimeUnit = (
  /** @type {const} */
  {
    /** Seconds. */
    SECOND: 0,
    /** Milliseconds. */
    MILLISECOND: 1,
    /** Microseconds. */
    MICROSECOND: 2,
    /** Nanoseconds. */
    NANOSECOND: 3
  }
);
const IntervalUnit = (
  /** @type {const} */
  {
    /**
     * Indicates the number of elapsed whole months, stored as 4-byte signed
     * integers.
     */
    YEAR_MONTH: 0,
    /**
     * Indicates the number of elapsed days and milliseconds (no leap seconds),
     * stored as 2 contiguous 32-bit signed integers (8-bytes in total). Support
     * of this IntervalUnit is not required for full arrow compatibility.
     */
    DAY_TIME: 1,
    /**
     * A triple of the number of elapsed months, days, and nanoseconds.
     * The values are stored contiguously in 16-byte blocks. Months and days are
     * encoded as 32-bit signed integers and nanoseconds is encoded as a 64-bit
     * signed integer. Nanoseconds does not allow for leap seconds. Each field is
     * independent (e.g. there is no constraint that nanoseconds have the same
     * sign as days or that the quantity of nanoseconds represents less than a
     * day's worth of time).
     */
    MONTH_DAY_NANO: 2
  }
);
const UnionMode = (
  /** @type {const} */
  {
    /** Sparse union layout with full arrays for each sub-type. */
    Sparse: 0,
    /** Dense union layout with offsets into value arrays. */
    Dense: 1
  }
);
const uint8Array = Uint8Array;
const uint16Array = Uint16Array;
const uint32Array = Uint32Array;
const uint64Array = BigUint64Array;
const int8Array = Int8Array;
const int16Array = Int16Array;
const int32Array = Int32Array;
const int64Array = BigInt64Array;
const float32Array = Float32Array;
const float64Array = Float64Array;
function isArrayBufferLike(data2) {
  return data2 instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && data2 instanceof SharedArrayBuffer;
}
function intArrayType(bitWidth, signed) {
  const i2 = Math.log2(bitWidth) - 3;
  return (signed ? [int8Array, int16Array, int32Array, int64Array] : [uint8Array, uint16Array, uint32Array, uint64Array])[i2];
}
const TypedArray = Object.getPrototypeOf(Int8Array);
function isTypedArray(value2) {
  return value2 instanceof TypedArray;
}
function isArray(value2) {
  return Array.isArray(value2) || isTypedArray(value2);
}
function isInt64ArrayType(value2) {
  return value2 === int64Array || value2 === uint64Array;
}
function bisect(offsets, index) {
  let a2 = 0;
  let b = offsets.length;
  if (b <= 2147483648) {
    do {
      const mid = a2 + b >>> 1;
      if (offsets[mid] <= index) a2 = mid + 1;
      else b = mid;
    } while (a2 < b);
  } else {
    do {
      const mid = Math.trunc((a2 + b) / 2);
      if (offsets[mid] <= index) a2 = mid + 1;
      else b = mid;
    } while (a2 < b);
  }
  return a2;
}
function align64(length2, bpe = 1) {
  return (length2 * bpe + 7 & -8) / bpe;
}
function align(array2, length2 = array2.length) {
  const alignedLength = align64(length2, array2.BYTES_PER_ELEMENT);
  return array2.length > alignedLength ? (
    /** @type {T} */
    array2.subarray(0, alignedLength)
  ) : array2.length < alignedLength ? resize(array2, alignedLength) : array2;
}
function resize(array2, newLength, offset3 = 0) {
  const newArray = new array2.constructor(newLength);
  newArray.set(array2, offset3);
  return newArray;
}
function grow(array2, index, shift) {
  while (array2.length <= index) {
    array2 = resize(array2, array2.length << 1, shift ? array2.length : 0);
  }
  return array2;
}
function isDate(value2) {
  return value2 instanceof Date;
}
function isIterable(value2) {
  return typeof value2[Symbol.iterator] === "function";
}
function check(value2, test2, message2) {
  if (test2(value2)) return value2;
  throw new Error(message2(value2));
}
function checkOneOf(value2, set3, message2) {
  set3 = Array.isArray(set3) ? set3 : Object.values(set3);
  return check(
    value2,
    (value3) => set3.includes(value3),
    message2 ?? (() => `${value2} must be one of ${set3}`)
  );
}
function keyFor(object2, value2) {
  for (const [key2, val] of Object.entries(object2)) {
    if (val === value2) return key2;
  }
  return "<Unknown>";
}
const invalidDataType = (typeId) => `Unsupported data type: "${keyFor(Type, typeId)}" (id ${typeId})`;
const field = (name2, type, nullable = true, metadata2 = null) => ({
  name: name2,
  type,
  nullable,
  metadata: metadata2
});
function isField(value2) {
  return Object.hasOwn(value2, "name") && isDataType(value2.type);
}
function isDataType(value2) {
  return typeof value2?.typeId === "number";
}
function asField(value2, defaultName = "", defaultNullable = true) {
  return isField(value2) ? value2 : field(
    defaultName,
    check(value2, isDataType, () => `Data type expected.`),
    defaultNullable
  );
}
const basicType = (typeId) => ({ typeId });
const dictionary$1 = (type, indexType, ordered = false, id2 = -1) => ({
  typeId: Type.Dictionary,
  id: id2,
  dictionary: type,
  indices: indexType || int32(),
  ordered
});
const nullType = () => basicType(Type.Null);
const int = (bitWidth = 32, signed = true) => ({
  typeId: Type.Int,
  bitWidth: checkOneOf(bitWidth, [8, 16, 32, 64]),
  signed,
  values: intArrayType(bitWidth, signed)
});
const int8 = () => int(8);
const int16 = () => int(16);
const int32 = () => int(32);
const int64 = () => int(64);
const uint8 = () => int(8, false);
const uint16 = () => int(16, false);
const uint32 = () => int(32, false);
const uint64 = () => int(64, false);
const float = (precision = 2) => ({
  typeId: Type.Float,
  precision: checkOneOf(precision, Precision),
  values: [uint16Array, float32Array, float64Array][precision]
});
const float32 = () => float(Precision.SINGLE);
const float64 = () => float(Precision.DOUBLE);
const binary = () => ({
  typeId: Type.Binary,
  offsets: int32Array
});
const utf8 = () => ({
  typeId: Type.Utf8,
  offsets: int32Array
});
const bool = () => basicType(Type.Bool);
const decimal = (precision, scale, bitWidth = 128) => ({
  typeId: Type.Decimal,
  precision,
  scale,
  bitWidth: checkOneOf(bitWidth, [32, 64, 128, 256]),
  values: bitWidth === 32 ? int32Array : uint64Array
});
const date = (unit) => ({
  typeId: Type.Date,
  unit: checkOneOf(unit, DateUnit),
  values: unit === DateUnit.DAY ? int32Array : int64Array
});
const dateDay = () => date(DateUnit.DAY);
const time = (unit = TimeUnit.MILLISECOND) => {
  unit = checkOneOf(unit, TimeUnit);
  const bitWidth = unit === TimeUnit.SECOND || unit === TimeUnit.MILLISECOND ? 32 : 64;
  return {
    typeId: Type.Time,
    unit,
    bitWidth,
    values: bitWidth === 32 ? int32Array : int64Array
  };
};
const timestamp = (unit = TimeUnit.MILLISECOND, timezone = null) => ({
  typeId: Type.Timestamp,
  unit: checkOneOf(unit, TimeUnit),
  timezone,
  values: int64Array
});
const interval = (unit = IntervalUnit.MONTH_DAY_NANO) => ({
  typeId: Type.Interval,
  unit: checkOneOf(unit, IntervalUnit),
  values: unit === IntervalUnit.MONTH_DAY_NANO ? void 0 : int32Array
});
const list$1 = (child) => ({
  typeId: Type.List,
  children: [asField(child)],
  offsets: int32Array
});
const struct = (children2) => ({
  typeId: Type.Struct,
  children: Array.isArray(children2) && isField(children2[0]) ? (
    /** @type {Field[]} */
    children2
  ) : Object.entries(children2).map(([name2, type]) => field(name2, type))
});
const union = (mode, children2, typeIds, typeIdForValue) => {
  typeIds ??= children2.map((v, i2) => i2);
  return {
    typeId: Type.Union,
    mode: checkOneOf(mode, UnionMode),
    typeIds,
    typeMap: typeIds.reduce((m, id2, i2) => (m[id2] = i2, m), {}),
    children: children2.map((v, i2) => asField(v, `_${i2}`)),
    typeIdForValue,
    offsets: int32Array
  };
};
const fixedSizeBinary = (stride) => ({
  typeId: Type.FixedSizeBinary,
  stride
});
const fixedSizeList = (child, stride) => ({
  typeId: Type.FixedSizeList,
  stride,
  children: [asField(child)]
});
const mapType = (keysSorted, child) => ({
  typeId: Type.Map,
  keysSorted,
  children: [child],
  offsets: int32Array
});
const duration = (unit = TimeUnit.MILLISECOND) => ({
  typeId: Type.Duration,
  unit: checkOneOf(unit, TimeUnit),
  values: int64Array
});
const largeBinary = () => ({
  typeId: Type.LargeBinary,
  offsets: int64Array
});
const largeUtf8 = () => ({
  typeId: Type.LargeUtf8,
  offsets: int64Array
});
const largeList = (child) => ({
  typeId: Type.LargeList,
  children: [asField(child)],
  offsets: int64Array
});
const runEndEncoded = (runsField, valuesField) => ({
  typeId: Type.RunEndEncoded,
  children: [
    check(
      asField(runsField, "run_ends"),
      (field2) => field2.type.typeId === Type.Int,
      () => "Run-ends must have an integer type."
    ),
    asField(valuesField, "values")
  ]
});
const listView = (child) => ({
  typeId: Type.ListView,
  children: [asField(child, "value")],
  offsets: int32Array
});
const largeListView = (child) => ({
  typeId: Type.LargeListView,
  children: [asField(child, "value")],
  offsets: int64Array
});
const f64 = new float64Array(2);
const buf = f64.buffer;
const i64 = new int64Array(buf);
const u32 = new uint32Array(buf);
const i32 = new int32Array(buf);
const u8 = new uint8Array(buf);
function identity$1(value2) {
  return value2;
}
function toBigInt(value2) {
  return BigInt(value2);
}
function toOffset(type) {
  return isInt64ArrayType(type) ? toBigInt : identity$1;
}
function toDateDay(value2) {
  return value2 / 864e5 | 0;
}
function toTimestamp(unit) {
  return unit === TimeUnit.SECOND ? (value2) => toBigInt(value2 / 1e3) : unit === TimeUnit.MILLISECOND ? toBigInt : unit === TimeUnit.MICROSECOND ? (value2) => toBigInt(value2 * 1e3) : (value2) => toBigInt(value2 * 1e6);
}
function toMonthDayNanoBytes([m, d, n2]) {
  i32[0] = m;
  i32[1] = d;
  i64[1] = toBigInt(n2);
  return u8;
}
function toNumber(value2) {
  if (value2 > Number.MAX_SAFE_INTEGER || value2 < Number.MIN_SAFE_INTEGER) {
    throw Error(`BigInt exceeds integer number representation: ${value2}`);
  }
  return Number(value2);
}
function divide(num, div) {
  return Number(num / div) + Number(num % div) / Number(div);
}
function toDecimal32(scale) {
  return (value2) => typeof value2 === "bigint" ? Number(value2) : Math.trunc(value2 * scale);
}
function toDecimal(value2, buf2, offset3, stride, scale) {
  const v = typeof value2 === "bigint" ? value2 : toBigInt(Math.trunc(value2 * scale));
  buf2[offset3] = v;
  if (stride > 1) {
    buf2[offset3 + 1] = v >> 64n;
    if (stride > 2) {
      buf2[offset3 + 2] = v >> 128n;
      buf2[offset3 + 3] = v >> 192n;
    }
  }
}
const asUint64 = (v) => BigInt.asUintN(64, v);
function fromDecimal64(buf2, offset3) {
  return BigInt.asIntN(64, buf2[offset3]);
}
function fromDecimal128(buf2, offset3) {
  const i2 = offset3 << 1;
  let x;
  if (BigInt.asIntN(64, buf2[i2 + 1]) < 0) {
    x = asUint64(~buf2[i2]) | asUint64(~buf2[i2 + 1]) << 64n;
    x = -(x + 1n);
  } else {
    x = buf2[i2] | buf2[i2 + 1] << 64n;
  }
  return x;
}
function fromDecimal256(buf2, offset3) {
  const i2 = offset3 << 2;
  let x;
  if (BigInt.asIntN(64, buf2[i2 + 3]) < 0) {
    x = asUint64(~buf2[i2]) | asUint64(~buf2[i2 + 1]) << 64n | asUint64(~buf2[i2 + 2]) << 128n | asUint64(~buf2[i2 + 3]) << 192n;
    x = -(x + 1n);
  } else {
    x = buf2[i2] | buf2[i2 + 1] << 64n | buf2[i2 + 2] << 128n | buf2[i2 + 3] << 192n;
  }
  return x;
}
function toFloat16(value2) {
  if (value2 !== value2) return 32256;
  f64[0] = value2;
  const sign2 = (u32[1] & 2147483648) >> 16 & 65535;
  let expo = u32[1] & 2146435072, sigf = 0;
  if (expo >= 1089470464) {
    if (u32[0] > 0) {
      expo = 31744;
    } else {
      expo = (expo & 2080374784) >> 16;
      sigf = (u32[1] & 1048575) >> 10;
    }
  } else if (expo <= 1056964608) {
    sigf = 1048576 + (u32[1] & 1048575);
    sigf = 1048576 + (sigf << (expo >> 20) - 998) >> 21;
    expo = 0;
  } else {
    expo = expo - 1056964608 >> 10;
    sigf = (u32[1] & 1048575) + 512 >> 10;
  }
  return sign2 | expo | sigf & 65535;
}
const textDecoder = new TextDecoder("utf-8");
const textEncoder = new TextEncoder();
function decodeUtf8(buf2) {
  return textDecoder.decode(buf2);
}
function encodeUtf8(str) {
  return textEncoder.encode(str);
}
function keyString(value2) {
  const val = typeof value2 !== "object" || !value2 ? value2 ?? null : isDate(value2) ? +value2 : isArray(value2) ? `[${value2.map(keyString)}]` : objectKey(value2);
  return `${val}`;
}
function objectKey(value2) {
  let s = "";
  let i2 = -1;
  for (const k in value2) {
    if (++i2 > 0) s += ",";
    s += `"${k}":${keyString(value2[k])}`;
  }
  return `{${s}}`;
}
const SIZEOF_INT = 4;
const SIZEOF_SHORT = 2;
function decodeBit(bitmap2, index) {
  return (bitmap2[index >> 3] & 1 << index % 8) !== 0;
}
function readObject(buf2, index) {
  const pos2 = index + readInt32(buf2, index);
  const vtable = pos2 - readInt32(buf2, pos2);
  const size = readInt16(buf2, vtable);
  return (index2, read2, fallback = null) => {
    if (index2 < size) {
      const off = readInt16(buf2, vtable + index2);
      if (off) return read2(buf2, pos2 + off);
    }
    return fallback;
  };
}
function readOffset(buf2, offset3) {
  return offset3;
}
function readBoolean(buf2, offset3) {
  return !!readInt8(buf2, offset3);
}
function readInt8(buf2, offset3) {
  return readUint8(buf2, offset3) << 24 >> 24;
}
function readUint8(buf2, offset3) {
  return buf2[offset3];
}
function readInt16(buf2, offset3) {
  return readUint16(buf2, offset3) << 16 >> 16;
}
function readUint16(buf2, offset3) {
  return buf2[offset3] | buf2[offset3 + 1] << 8;
}
function readInt32(buf2, offset3) {
  return buf2[offset3] | buf2[offset3 + 1] << 8 | buf2[offset3 + 2] << 16 | buf2[offset3 + 3] << 24;
}
function readUint32(buf2, offset3) {
  return readInt32(buf2, offset3) >>> 0;
}
function readInt64(buf2, offset3) {
  return toNumber(BigInt.asIntN(
    64,
    BigInt(readUint32(buf2, offset3)) + (BigInt(readUint32(buf2, offset3 + SIZEOF_INT)) << 32n)
  ));
}
function readString(buf2, index) {
  let offset3 = index + readInt32(buf2, index);
  const length2 = readInt32(buf2, offset3);
  offset3 += SIZEOF_INT;
  return decodeUtf8(buf2.subarray(offset3, offset3 + length2));
}
function readVector(buf2, offset3, stride, extract) {
  if (!offset3) return [];
  const base2 = offset3 + readInt32(buf2, offset3);
  return Array.from(
    { length: readInt32(buf2, base2) },
    (_, i2) => extract(buf2, base2 + SIZEOF_INT + i2 * stride)
  );
}
const RowIndex = Symbol("rowIndex");
function proxyFactory(names, batches) {
  class RowObject {
    /**
     * Create a new proxy row object representing a struct or table row.
     * @param {number} index The record batch row index.
     */
    constructor(index) {
      this[RowIndex] = index;
    }
    /**
     * Return a JSON-compatible object representation.
     */
    toJSON() {
      return structObject(names, batches, this[RowIndex]);
    }
  }
  const proto = RowObject.prototype;
  for (let i2 = 0; i2 < names.length; ++i2) {
    if (Object.hasOwn(proto, names[i2])) continue;
    const batch2 = batches[i2];
    Object.defineProperty(proto, names[i2], {
      get() {
        return batch2.at(this[RowIndex]);
      },
      enumerable: true
    });
  }
  return (index) => new RowObject(index);
}
function objectFactory(names, batches) {
  return (index) => structObject(names, batches, index);
}
function structObject(names, batches, index) {
  const obj = {};
  for (let i2 = 0; i2 < names.length; ++i2) {
    obj[names[i2]] = batches[i2].at(index);
  }
  return obj;
}
function isDirectBatch(batch2) {
  return batch2 instanceof DirectBatch;
}
class Batch {
  /**
   * The array type to use when extracting data from the batch.
   * A null value indicates that the array type should match
   * the type of the batch's values array.
   * @type {ArrayConstructor | TypedArrayConstructor | null}
   */
  static ArrayType = null;
  /**
   * Create a new column batch.
   * @param {object} options
   * @param {number} options.length The length of the batch
   * @param {number} options.nullCount The null value count
   * @param {DataType} options.type The data type.
   * @param {Uint8Array} [options.validity] Validity bitmap buffer
   * @param {TypedArray} [options.values] Values buffer
   * @param {OffsetArray} [options.offsets] Offsets buffer
   * @param {OffsetArray} [options.sizes] Sizes buffer
   * @param {Batch[]} [options.children] Children batches
   */
  constructor({
    length: length2,
    nullCount,
    type,
    validity,
    values: values2,
    offsets,
    sizes,
    children: children2
  }) {
    this.length = length2;
    this.nullCount = nullCount;
    this.type = type;
    this.validity = validity;
    this.values = values2;
    this.offsets = offsets;
    this.sizes = sizes;
    this.children = children2;
    if (!nullCount || !this.validity) {
      this.at = (index) => this.value(index);
    }
  }
  /**
   * Provide an informative object string tag.
   */
  get [Symbol.toStringTag]() {
    return "Batch";
  }
  /**
   * Return the value at the given index.
   * @param {number} index The value index.
   * @returns {T | null} The value.
   */
  at(index) {
    return this.isValid(index) ? this.value(index) : null;
  }
  /**
   * Check if a value at the given index is valid (non-null).
   * @param {number} index The value index.
   * @returns {boolean} True if valid, false otherwise.
   */
  isValid(index) {
    return decodeBit(this.validity, index);
  }
  /**
   * Return the value at the given index. This method does not check the
   * validity bitmap and is intended primarily for internal use. In most
   * cases, callers should use the `at()` method instead.
   * @param {number} index The value index
   * @returns {T} The value, ignoring the validity bitmap.
   */
  value(index) {
    return (
      /** @type {T} */
      this.values[index]
    );
  }
  /**
   * Extract an array of values within the given index range. Unlike
   * Array.slice, all arguments are required and may not be negative indices.
   * @param {number} start The starting index, inclusive
   * @param {number} end The ending index, exclusive
   * @returns {ValueArray<T?>} The slice of values
   */
  slice(start2, end2) {
    const n2 = end2 - start2;
    const values2 = Array(n2);
    for (let i2 = 0; i2 < n2; ++i2) {
      values2[i2] = this.at(start2 + i2);
    }
    return values2;
  }
  /**
   * Return an iterator over the values in this batch.
   * @returns {Iterator<T?>}
   */
  *[Symbol.iterator]() {
    for (let i2 = 0; i2 < this.length; ++i2) {
      yield this.at(i2);
    }
  }
}
class DirectBatch extends Batch {
  /**
   * Create a new column batch with direct value array access.
   * @param {object} options
   * @param {number} options.length The length of the batch
   * @param {number} options.nullCount The null value count
   * @param {DataType} options.type The data type.
   * @param {Uint8Array} [options.validity] Validity bitmap buffer
   * @param {TypedArray} options.values Values buffer
   */
  constructor(options) {
    super(options);
    const { length: length2, values: values2 } = this;
    this.values = values2.subarray(0, length2);
  }
  /**
   * Extract an array of values within the given index range. Unlike
   * Array.slice, all arguments are required and may not be negative indices.
   * When feasible, a zero-copy subarray of a typed array is returned.
   * @param {number} start The starting index, inclusive
   * @param {number} end The ending index, exclusive
   * @returns {ValueArray<T?>} The slice of values
   */
  slice(start2, end2) {
    return this.nullCount ? super.slice(start2, end2) : this.values.subarray(start2, end2);
  }
  /**
   * Return an iterator over the values in this batch.
   * @returns {Iterator<T?>}
   */
  [Symbol.iterator]() {
    return this.nullCount ? super[Symbol.iterator]() : (
      /** @type {Iterator<T?>} */
      this.values[Symbol.iterator]()
    );
  }
}
class NumberBatch extends Batch {
  static ArrayType = float64Array;
}
class ArrayBatch extends Batch {
  static ArrayType = Array;
}
class NullBatch extends ArrayBatch {
  /**
   * @param {number} index The value index
   * @returns {null}
   */
  value(index) {
    return null;
  }
}
class Int64Batch extends NumberBatch {
  /**
   * @param {number} index The value index
   */
  value(index) {
    return toNumber(
      /** @type {bigint} */
      this.values[index]
    );
  }
}
class Float16Batch extends NumberBatch {
  /**
   * @param {number} index The value index
   */
  value(index) {
    const v = (
      /** @type {number} */
      this.values[index]
    );
    const expo = (v & 31744) >> 10;
    const sigf = (v & 1023) / 1024;
    const sign2 = (-1) ** ((v & 32768) >> 15);
    switch (expo) {
      case 31:
        return sign2 * (sigf ? Number.NaN : 1 / 0);
      case 0:
        return sign2 * (sigf ? 6103515625e-14 * sigf : 0);
    }
    return sign2 * 2 ** (expo - 15) * (1 + sigf);
  }
}
class BoolBatch extends ArrayBatch {
  /**
   * @param {number} index The value index
   */
  value(index) {
    return decodeBit(
      /** @type {Uint8Array} */
      this.values,
      index
    );
  }
}
class Decimal32NumberBatch extends NumberBatch {
  constructor(options) {
    super(options);
    const { scale } = (
      /** @type {DecimalType} */
      this.type
    );
    this.scale = 10 ** scale;
  }
  /**
   * @param {number} index The value index
   */
  value(index) {
    return (
      /** @type {number} */
      this.values[index] / this.scale
    );
  }
}
class DecimalBatch extends Batch {
  constructor(options) {
    super(options);
    const { bitWidth, scale } = (
      /** @type {DecimalType} */
      this.type
    );
    this.decimal = bitWidth === 64 ? fromDecimal64 : bitWidth === 128 ? fromDecimal128 : fromDecimal256;
    this.scale = 10n ** BigInt(scale);
  }
}
class DecimalNumberBatch extends DecimalBatch {
  static ArrayType = float64Array;
  /**
   * @param {number} index The value index
   */
  value(index) {
    return divide(
      this.decimal(
        /** @type {BigUint64Array} */
        this.values,
        index
      ),
      this.scale
    );
  }
}
class DecimalBigIntBatch extends DecimalBatch {
  static ArrayType = Array;
  /**
   * @param {number} index The value index
   */
  value(index) {
    return this.decimal(
      /** @type {BigUint64Array} */
      this.values,
      index
    );
  }
}
class DateBatch extends ArrayBatch {
  /**
   * Create a new date batch.
   * @param {Batch<number>} batch A batch of timestamp values.
   */
  constructor(batch2) {
    super(batch2);
    this.source = batch2;
  }
  /**
   * @param {number} index The value index
   */
  value(index) {
    return new Date(this.source.value(index));
  }
}
class DateDayBatch extends NumberBatch {
  /**
   * @param {number} index The value index
   * @returns {number}
   */
  value(index) {
    return 864e5 * /** @type {number} */
    this.values[index];
  }
}
const DateDayMillisecondBatch = Int64Batch;
class TimestampSecondBatch extends Int64Batch {
  /**
   * @param {number} index The value index
   */
  value(index) {
    return super.value(index) * 1e3;
  }
}
const TimestampMillisecondBatch = Int64Batch;
class TimestampMicrosecondBatch extends Int64Batch {
  /**
   * @param {number} index The value index
   */
  value(index) {
    return divide(
      /** @type {bigint} */
      this.values[index],
      1000n
    );
  }
}
class TimestampNanosecondBatch extends Int64Batch {
  /**
   * @param {number} index The value index
   */
  value(index) {
    return divide(
      /** @type {bigint} */
      this.values[index],
      1000000n
    );
  }
}
class IntervalDayTimeBatch extends ArrayBatch {
  /**
   * @param {number} index The value index
   * @returns {Int32Array}
   */
  value(index) {
    const values2 = (
      /** @type {Int32Array} */
      this.values
    );
    return values2.subarray(index << 1, index + 1 << 1);
  }
}
class IntervalMonthDayNanoBatch extends ArrayBatch {
  /**
   * @param {number} index The value index
   */
  value(index) {
    const values2 = (
      /** @type {Uint8Array} */
      this.values
    );
    const base2 = index << 4;
    return Float64Array.of(
      readInt32(values2, base2),
      readInt32(values2, base2 + 4),
      readInt64(values2, base2 + 8)
    );
  }
}
const offset32 = ({ values: values2, offsets }, index) => values2.subarray(offsets[index], offsets[index + 1]);
const offset64 = ({ values: values2, offsets }, index) => values2.subarray(toNumber(offsets[index]), toNumber(offsets[index + 1]));
class BinaryBatch extends ArrayBatch {
  /**
   * @param {number} index
   * @returns {Uint8Array}
   */
  value(index) {
    return offset32(this, index);
  }
}
class LargeBinaryBatch extends ArrayBatch {
  /**
   * @param {number} index
   * @returns {Uint8Array}
   */
  value(index) {
    return offset64(this, index);
  }
}
class Utf8Batch extends ArrayBatch {
  /**
   * @param {number} index
   */
  value(index) {
    return decodeUtf8(offset32(this, index));
  }
}
class LargeUtf8Batch extends ArrayBatch {
  /**
   * @param {number} index
   */
  value(index) {
    return decodeUtf8(offset64(this, index));
  }
}
class ListBatch extends ArrayBatch {
  /**
   * @param {number} index
   * @returns {ValueArray<V>}
   */
  value(index) {
    const offsets = (
      /** @type {Int32Array} */
      this.offsets
    );
    return this.children[0].slice(offsets[index], offsets[index + 1]);
  }
}
class LargeListBatch extends ArrayBatch {
  /**
   * @param {number} index
   * @returns {ValueArray<V>}
   */
  value(index) {
    const offsets = (
      /** @type {BigInt64Array} */
      this.offsets
    );
    return this.children[0].slice(toNumber(offsets[index]), toNumber(offsets[index + 1]));
  }
}
class ListViewBatch extends ArrayBatch {
  /**
   * @param {number} index
   * @returns {ValueArray<V>}
   */
  value(index) {
    const a2 = (
      /** @type {number} */
      this.offsets[index]
    );
    const b = a2 + /** @type {number} */
    this.sizes[index];
    return this.children[0].slice(a2, b);
  }
}
class LargeListViewBatch extends ArrayBatch {
  /**
   * @param {number} index
   * @returns {ValueArray<V>}
   */
  value(index) {
    const a2 = (
      /** @type {bigint} */
      this.offsets[index]
    );
    const b = a2 + /** @type {bigint} */
    this.sizes[index];
    return this.children[0].slice(toNumber(a2), toNumber(b));
  }
}
class FixedBatch extends ArrayBatch {
  constructor(options) {
    super(options);
    this.stride = this.type.stride;
  }
}
class FixedBinaryBatch extends FixedBatch {
  /**
   * @param {number} index
   * @returns {Uint8Array}
   */
  value(index) {
    const { stride, values: values2 } = this;
    return (
      /** @type {Uint8Array} */
      values2.subarray(index * stride, (index + 1) * stride)
    );
  }
}
class FixedListBatch extends FixedBatch {
  /**
   * @param {number} index
   * @returns {ValueArray<V>}
   */
  value(index) {
    const { children: children2, stride } = this;
    return children2[0].slice(index * stride, (index + 1) * stride);
  }
}
function pairs({ children: children2, offsets }, index) {
  const [keys2, vals] = children2[0].children;
  const start2 = offsets[index];
  const end2 = offsets[index + 1];
  const entries2 = [];
  for (let i2 = start2; i2 < end2; ++i2) {
    entries2.push([keys2.at(i2), vals.at(i2)]);
  }
  return entries2;
}
class MapEntryBatch extends ArrayBatch {
  /**
   * Return the value at the given index.
   * @param {number} index The value index.
   * @returns {[K, V][]} The map entries as an array of [key, value] arrays.
   */
  value(index) {
    return (
      /** @type {[K, V][]} */
      pairs(this, index)
    );
  }
}
class MapBatch extends ArrayBatch {
  /**
   * Return the value at the given index.
   * @param {number} index The value index.
   * @returns {Map<K, V>} The map value.
   */
  value(index) {
    return new Map(
      /** @type {[K, V][]} */
      pairs(this, index)
    );
  }
}
class SparseUnionBatch extends ArrayBatch {
  /**
   * Create a new column batch.
   * @param {object} options
   * @param {number} options.length The length of the batch
   * @param {number} options.nullCount The null value count
   * @param {DataType} options.type The data type.
   * @param {Uint8Array} [options.validity] Validity bitmap buffer
   * @param {Int32Array} [options.offsets] Offsets buffer
   * @param {Batch[]} options.children Children batches
   * @param {Int8Array} options.typeIds Union type ids buffer
   * @param {Record<string, number>} options.map A typeId to children index map
   */
  constructor({ typeIds, ...options }) {
    super(options);
    this.typeIds = typeIds;
    this.typeMap = this.type.typeMap;
  }
  /**
   * @param {number} index The value index.
   */
  value(index, offset3 = index) {
    const { typeIds, children: children2, typeMap } = this;
    return children2[typeMap[typeIds[index]]].at(offset3);
  }
}
class DenseUnionBatch extends SparseUnionBatch {
  /**
   * @param {number} index The value index.
   */
  value(index) {
    return super.value(
      index,
      /** @type {number} */
      this.offsets[index]
    );
  }
}
class StructBatch extends ArrayBatch {
  constructor(options, factory = objectFactory) {
    super(options);
    this.names = this.type.children.map((child) => child.name);
    this.factory = factory(this.names, this.children);
  }
  /**
   * @param {number} index The value index.
   * @returns {Record<string, any>}
   */
  value(index) {
    return this.factory(index);
  }
}
class StructProxyBatch extends StructBatch {
  constructor(options) {
    super(options, proxyFactory);
  }
}
class RunEndEncodedBatch extends ArrayBatch {
  /**
   * @param {number} index The value index.
   */
  value(index) {
    const [{ values: runs }, vals] = this.children;
    return vals.at(
      bisect(
        /** @type {IntegerArray} */
        runs,
        index
      )
    );
  }
}
class DictionaryBatch3 extends ArrayBatch {
  /**
   * Register the backing dictionary. Dictionaries are added
   * after batch creation as the complete dictionary may not
   * be finished across multiple record batches.
   * @param {Column<T>} dictionary
   * The dictionary of column values.
   */
  setDictionary(dictionary2) {
    this.dictionary = dictionary2;
    this.cache = dictionary2.cache();
    return this;
  }
  /**
   * @param {number} index The value index.
   */
  value(index) {
    return this.cache[this.key(index)];
  }
  /**
   * @param {number} index The value index.
   * @returns {number} The dictionary key
   */
  key(index) {
    return (
      /** @type {number} */
      this.values[index]
    );
  }
}
class ViewBatch extends ArrayBatch {
  /**
   * Create a new view batch.
   * @param {object} options Batch options.
   * @param {number} options.length The length of the batch
   * @param {number} options.nullCount The null value count
   * @param {DataType} options.type The data type.
   * @param {Uint8Array} [options.validity] Validity bitmap buffer
   * @param {Uint8Array} options.values Values buffer
   * @param {Uint8Array[]} options.data View data buffers
   */
  constructor({ data: data2, ...options }) {
    super(options);
    this.data = data2;
  }
  /**
   * Get the binary data at the provided index.
   * @param {number} index The value index.
   * @returns {Uint8Array}
   */
  view(index) {
    const { values: values2, data: data2 } = this;
    const offset3 = index << 4;
    let start2 = offset3 + 4;
    let buf2 = (
      /** @type {Uint8Array} */
      values2
    );
    const length2 = readInt32(buf2, offset3);
    if (length2 > 12) {
      start2 = readInt32(buf2, offset3 + 12);
      buf2 = data2[readInt32(buf2, offset3 + 8)];
    }
    return buf2.subarray(start2, start2 + length2);
  }
}
class BinaryViewBatch extends ViewBatch {
  /**
   * @param {number} index The value index.
   */
  value(index) {
    return this.view(index);
  }
}
class Utf8ViewBatch extends ViewBatch {
  /**
   * @param {number} index The value index.
   */
  value(index) {
    return decodeUtf8(this.view(index));
  }
}
function columnBuilder(type) {
  let data2 = [];
  return {
    add(batch2) {
      data2.push(batch2);
      return this;
    },
    clear: () => data2 = [],
    done: () => new Column(data2, type)
  };
}
class Column {
  /**
   * Create a new column instance.
   * @param {Batch<T>[]} data The value batches.
   * @param {DataType} [type] The column data type.
   *  If not specified, the type is extracted from the batches.
   */
  constructor(data2, type = data2[0]?.type) {
    this.type = type;
    this.length = data2.reduce((m, c2) => m + c2.length, 0);
    this.nullCount = data2.reduce((m, c2) => m + c2.nullCount, 0);
    this.data = data2;
    const n2 = data2.length;
    const offsets = new Int32Array(n2 + 1);
    if (n2 === 1) {
      const [batch2] = data2;
      offsets[1] = batch2.length;
      this.at = (index) => batch2.at(index);
    } else {
      for (let i2 = 0, s = 0; i2 < n2; ++i2) {
        offsets[i2 + 1] = s += data2[i2].length;
      }
    }
    this.offsets = offsets;
  }
  /**
   * Provide an informative object string tag.
   */
  get [Symbol.toStringTag]() {
    return "Column";
  }
  /**
   * Return an iterator over the values in this column.
   * @returns {Iterator<T?>}
   */
  [Symbol.iterator]() {
    const data2 = this.data;
    return data2.length === 1 ? data2[0][Symbol.iterator]() : batchedIterator(data2);
  }
  /**
   * Return the column value at the given index. If a column has multiple
   * batches, this method performs binary search over the batch lengths to
   * determine the batch from which to retrieve the value. The search makes
   * lookup less efficient than a standard array access. If making a full
   * scan of a column, consider extracting arrays via `toArray()` or using an
   * iterator (`for (const value of column) {...}`).
   * @param {number} index The row index.
   * @returns {T | null} The value.
   */
  at(index) {
    const { data: data2, offsets } = this;
    const i2 = bisect(offsets, index) - 1;
    return data2[i2]?.at(index - offsets[i2]);
  }
  /**
   * Return the column value at the given index. This method is the same as
   * `at()` and is provided for better compatibility with Apache Arrow JS.
   * @param {number} index The row index.
   * @returns {T | null} The value.
   */
  get(index) {
    return this.at(index);
  }
  /**
   * Extract column values into a single array instance. When possible,
   * a zero-copy subarray of the input Arrow data is returned.
   * @returns {ValueArray<T?>}
   */
  toArray() {
    const { length: length2, nullCount, data: data2 } = this;
    const copy = !nullCount && isDirectBatch(data2[0]);
    const n2 = data2.length;
    if (copy && n2 === 1) {
      return data2[0].values;
    }
    const ArrayType = !n2 || nullCount > 0 ? Array : data2[0].constructor.ArrayType ?? data2[0].values.constructor;
    const array2 = new ArrayType(length2);
    return copy ? copyArray(array2, data2) : extractArray(array2, data2);
  }
  /**
   * Return an array of cached column values.
   * Used internally to accelerate dictionary types.
   */
  cache() {
    return this._cache ?? (this._cache = this.toArray());
  }
}
function* batchedIterator(data2) {
  for (let i2 = 0; i2 < data2.length; ++i2) {
    const iter = data2[i2][Symbol.iterator]();
    for (let next = iter.next(); !next.done; next = iter.next()) {
      yield next.value;
    }
  }
}
function copyArray(array2, data2) {
  for (let i2 = 0, offset3 = 0; i2 < data2.length; ++i2) {
    const { values: values2 } = data2[i2];
    array2.set(values2, offset3);
    offset3 += values2.length;
  }
  return array2;
}
function extractArray(array2, data2) {
  let index = -1;
  for (let i2 = 0; i2 < data2.length; ++i2) {
    const batch2 = data2[i2];
    for (let j2 = 0; j2 < batch2.length; ++j2) {
      array2[++index] = batch2.at(j2);
    }
  }
  return array2;
}
class Table3 {
  /**
   * Create a new table with the given schema and columns (children).
   * @param {Schema} schema The table schema.
   * @param {Column[]} children The table columns.
   * @param {boolean} [useProxy=false] Flag indicating if row proxy
   *  objects should be used to represent table rows (default `false`).
   */
  constructor(schema, children2, useProxy = false) {
    const names = schema.fields.map((f) => f.name);
    this.schema = schema;
    this.names = names;
    this.children = children2;
    this.factory = useProxy ? proxyFactory : objectFactory;
    const gen = [];
    this.getFactory = (b) => gen[b] ?? (gen[b] = this.factory(names, children2.map((c2) => c2.data[b])));
  }
  /**
   * Provide an informative object string tag.
   */
  get [Symbol.toStringTag]() {
    return "Table";
  }
  /**
   * The number of columns in this table.
   * @return {number} The number of columns.
   */
  get numCols() {
    return this.names.length;
  }
  /**
   * The number of rows in this table.
   * @return {number} The number of rows.
   */
  get numRows() {
    return this.children[0]?.length ?? 0;
  }
  /**
   * Return the child column at the given index position.
   * @template {T[keyof T]} R
   * @param {number} index The column index.
   * @returns {Column<R>}
   */
  getChildAt(index) {
    return this.children[index];
  }
  /**
   * Return the first child column with the given name.
   * @template {keyof T} P
   * @param {P} name The column name.
   * @returns {Column<T[P]>}
   */
  getChild(name2) {
    const i2 = this.names.findIndex((x) => x === name2);
    return i2 > -1 ? this.children[i2] : void 0;
  }
  /**
   * Construct a new table containing only columns at the specified indices.
   * The order of columns in the new table matches the order of input indices.
   * @template {T[keyof T]} V
   * @param {number[]} indices The indices of columns to keep.
   * @param {string[]} [as] Optional new names for selected columns.
   * @returns {Table<{ [key: string]: V }>} A new table with selected columns.
   */
  selectAt(indices, as = []) {
    const { children: children2, factory, schema } = this;
    const { fields } = schema;
    return new Table3(
      {
        ...schema,
        fields: indices.map((i2, j2) => renameField(fields[i2], as[j2]))
      },
      indices.map((i2) => children2[i2]),
      factory === proxyFactory
    );
  }
  /**
   * Construct a new table containing only columns with the specified names.
   * If columns have duplicate names, the first (with lowest index) is used.
   * The order of columns in the new table matches the order of input names.
   * @template {keyof T} K
   * @param {K[]} names Names of columns to keep.
   * @param {string[]} [as] Optional new names for selected columns.
   * @returns A new table with columns matching the specified names.
   */
  select(names, as) {
    const all2 = (
      /** @type {K[]} */
      this.names
    );
    const indices = names.map((name2) => all2.indexOf(name2));
    return this.selectAt(indices, as);
  }
  /**
   * Return an object mapping column names to extracted value arrays.
   * @returns {{ [P in keyof T]: ValueArray<T[P]> }}
   */
  toColumns() {
    const { children: children2, names } = this;
    const cols = {};
    names.forEach((name2, i2) => cols[name2] = children2[i2]?.toArray() ?? []);
    return cols;
  }
  /**
   * Return an array of objects representing the rows of this table.
   * @returns {{ [P in keyof T]: T[P] }[]}
   */
  toArray() {
    const { children: children2, getFactory, numRows } = this;
    const data2 = children2[0]?.data ?? [];
    const output2 = Array(numRows);
    for (let b = 0, row2 = -1; b < data2.length; ++b) {
      const f = getFactory(b);
      for (let i2 = 0; i2 < data2[b].length; ++i2) {
        output2[++row2] = f(i2);
      }
    }
    return output2;
  }
  /**
   * Return an iterator over objects representing the rows of this table.
   * @returns {Generator<{ [P in keyof T]: T[P] }, any, any>}
   */
  *[Symbol.iterator]() {
    const { children: children2, getFactory } = this;
    const data2 = children2[0]?.data ?? [];
    for (let b = 0; b < data2.length; ++b) {
      const f = getFactory(b);
      for (let i2 = 0; i2 < data2[b].length; ++i2) {
        yield f(i2);
      }
    }
  }
  /**
   * Return a row object for the given index.
   * @param {number} index The row index.
   * @returns {{ [P in keyof T]: T[P] }} The row object.
   */
  at(index) {
    const { children: children2, getFactory, numRows } = this;
    if (index < 0 || index >= numRows) return null;
    const [{ offsets }] = children2;
    const b = bisect(offsets, index) - 1;
    return getFactory(b)(index - offsets[b]);
  }
  /**
   * Return a row object for the given index. This method is the same as
   * `at()` and is provided for better compatibility with Apache Arrow JS.
   * @param {number} index The row index.
   * @returns {{ [P in keyof T]: T[P] }} The row object.
   */
  get(index) {
    return this.at(index);
  }
}
function renameField(field2, name2) {
  return name2 != null && name2 !== field2.name ? { ...field2, name: name2 } : field2;
}
function batchType(type, options = {}) {
  const { typeId, bitWidth, mode, precision, unit } = (
    /** @type {any} */
    type
  );
  const { useBigInt, useDate, useDecimalInt, useMap, useProxy } = options;
  switch (typeId) {
    case Type.Null:
      return NullBatch;
    case Type.Bool:
      return BoolBatch;
    case Type.Int:
    case Type.Time:
    case Type.Duration:
      return useBigInt || bitWidth < 64 ? DirectBatch : Int64Batch;
    case Type.Float:
      return precision ? DirectBatch : Float16Batch;
    case Type.Date:
      return wrap(
        unit === DateUnit.DAY ? DateDayBatch : DateDayMillisecondBatch,
        useDate && DateBatch
      );
    case Type.Timestamp:
      return wrap(
        unit === TimeUnit.SECOND ? TimestampSecondBatch : unit === TimeUnit.MILLISECOND ? TimestampMillisecondBatch : unit === TimeUnit.MICROSECOND ? TimestampMicrosecondBatch : TimestampNanosecondBatch,
        useDate && DateBatch
      );
    case Type.Decimal:
      return bitWidth === 32 ? useDecimalInt ? DirectBatch : Decimal32NumberBatch : useDecimalInt ? DecimalBigIntBatch : DecimalNumberBatch;
    case Type.Interval:
      return unit === IntervalUnit.DAY_TIME ? IntervalDayTimeBatch : unit === IntervalUnit.YEAR_MONTH ? DirectBatch : IntervalMonthDayNanoBatch;
    case Type.FixedSizeBinary:
      return FixedBinaryBatch;
    case Type.Utf8:
      return Utf8Batch;
    case Type.LargeUtf8:
      return LargeUtf8Batch;
    case Type.Binary:
      return BinaryBatch;
    case Type.LargeBinary:
      return LargeBinaryBatch;
    case Type.BinaryView:
      return BinaryViewBatch;
    case Type.Utf8View:
      return Utf8ViewBatch;
    case Type.List:
      return ListBatch;
    case Type.LargeList:
      return LargeListBatch;
    case Type.Map:
      return useMap ? MapBatch : MapEntryBatch;
    case Type.ListView:
      return ListViewBatch;
    case Type.LargeListView:
      return LargeListViewBatch;
    case Type.FixedSizeList:
      return FixedListBatch;
    case Type.Struct:
      return useProxy ? StructProxyBatch : StructBatch;
    case Type.RunEndEncoded:
      return RunEndEncodedBatch;
    case Type.Dictionary:
      return DictionaryBatch3;
    case Type.Union:
      return mode ? DenseUnionBatch : SparseUnionBatch;
  }
  throw new Error(invalidDataType(typeId));
}
function wrap(BaseClass, WrapperClass) {
  return WrapperClass ? class WrapBatch extends WrapperClass {
    constructor(options) {
      super(new BaseClass(options));
    }
  } : BaseClass;
}
function decodeBlock(buf2, index) {
  return {
    offset: readInt64(buf2, index),
    metadataLength: readInt32(buf2, index + 8),
    bodyLength: readInt64(buf2, index + 16)
  };
}
function decodeBlocks(buf2, index) {
  return readVector(buf2, index, 24, decodeBlock);
}
function decodeRecordBatch(buf2, index, version2) {
  const get2 = readObject(buf2, index);
  if (get2(10, readOffset, 0)) {
    throw new Error("Record batch compression not implemented");
  }
  const offset3 = version2 < Version.V4 ? 8 : 0;
  return {
    length: get2(4, readInt64, 0),
    nodes: readVector(buf2, get2(6, readOffset), 16, (buf3, pos2) => ({
      length: readInt64(buf3, pos2),
      nullCount: readInt64(buf3, pos2 + 8)
    })),
    regions: readVector(buf2, get2(8, readOffset), 16 + offset3, (buf3, pos2) => ({
      offset: readInt64(buf3, pos2 + offset3),
      length: readInt64(buf3, pos2 + offset3 + 8)
    })),
    variadic: readVector(buf2, get2(12, readOffset), 8, readInt64)
  };
}
function decodeDictionaryBatch(buf2, index, version2) {
  const get2 = readObject(buf2, index);
  return {
    id: get2(4, readInt64, 0),
    data: get2(6, (buf3, off) => decodeRecordBatch(buf3, off, version2)),
    /**
     * If isDelta is true the values in the dictionary are to be appended to a
     * dictionary with the indicated id. If isDelta is false this dictionary
     * should replace the existing dictionary.
     */
    isDelta: get2(8, readBoolean, false)
  };
}
function decodeDataType(buf2, index, typeId, children2) {
  checkOneOf(typeId, Type, invalidDataType);
  const get2 = readObject(buf2, index);
  switch (typeId) {
    // types without flatbuffer objects
    case Type.Binary:
      return binary();
    case Type.Utf8:
      return utf8();
    case Type.LargeBinary:
      return largeBinary();
    case Type.LargeUtf8:
      return largeUtf8();
    case Type.List:
      return list$1(children2[0]);
    case Type.ListView:
      return listView(children2[0]);
    case Type.LargeList:
      return largeList(children2[0]);
    case Type.LargeListView:
      return largeListView(children2[0]);
    case Type.Struct:
      return struct(children2);
    case Type.RunEndEncoded:
      return runEndEncoded(children2[0], children2[1]);
    // types with flatbuffer objects
    case Type.Int:
      return int(
        // @ts-ignore
        get2(4, readInt32, 0),
        // bitwidth
        get2(6, readBoolean, false)
        // signed
      );
    case Type.Float:
      return float(
        // @ts-ignore
        get2(4, readInt16, Precision.HALF)
        // precision
      );
    case Type.Decimal:
      return decimal(
        get2(4, readInt32, 0),
        // precision
        get2(6, readInt32, 0),
        // scale
        // @ts-ignore
        get2(8, readInt32, 128)
        // bitwidth
      );
    case Type.Date:
      return date(
        // @ts-ignore
        get2(4, readInt16, DateUnit.MILLISECOND)
        // unit
      );
    case Type.Time:
      return time(
        // @ts-ignore
        get2(4, readInt16, TimeUnit.MILLISECOND)
        // unit
      );
    case Type.Timestamp:
      return timestamp(
        // @ts-ignore
        get2(4, readInt16, TimeUnit.SECOND),
        // unit
        get2(6, readString)
        // timezone
      );
    case Type.Interval:
      return interval(
        // @ts-ignore
        get2(4, readInt16, IntervalUnit.YEAR_MONTH)
        // unit
      );
    case Type.Duration:
      return duration(
        // @ts-ignore
        get2(4, readInt16, TimeUnit.MILLISECOND)
        // unit
      );
    case Type.FixedSizeBinary:
      return fixedSizeBinary(
        get2(4, readInt32, 0)
        // stride
      );
    case Type.FixedSizeList:
      return fixedSizeList(
        children2[0],
        get2(4, readInt32, 0)
        // stride
      );
    case Type.Map:
      return mapType(
        get2(4, readBoolean, false),
        // keysSorted
        children2[0]
      );
    case Type.Union:
      return union(
        // @ts-ignore
        get2(4, readInt16, UnionMode.Sparse),
        // mode
        children2,
        readVector(buf2, get2(6, readOffset), 4, readInt32)
        // type ids
      );
  }
  return { typeId };
}
function decodeMetadata(buf2, index) {
  const entries2 = readVector(buf2, index, 4, (buf3, pos2) => {
    const get2 = readObject(buf3, pos2);
    return (
      /** @type {[string, string]} */
      [
        get2(4, readString),
        // 4: key (string)
        get2(6, readString)
        // 6: key (string)
      ]
    );
  });
  return entries2.length ? new Map(entries2) : null;
}
function decodeSchema(buf2, index, version2) {
  const get2 = readObject(buf2, index);
  return {
    version: version2,
    endianness: (
      /** @type {Endianness_} */
      get2(4, readInt16, 0)
    ),
    fields: get2(6, decodeSchemaFields, []),
    metadata: get2(8, decodeMetadata)
  };
}
function decodeSchemaFields(buf2, fieldsOffset) {
  return readVector(buf2, fieldsOffset, 4, decodeField);
}
function decodeField(buf2, index) {
  const get2 = readObject(buf2, index);
  const typeId = get2(8, readUint8, Type.NONE);
  const typeOffset = get2(10, readOffset, 0);
  const dict = get2(12, decodeDictionary);
  const children2 = get2(14, (buf3, off) => decodeFieldChildren(buf3, off));
  let type = decodeDataType(buf2, typeOffset, typeId, children2);
  if (dict) {
    dict.dictionary = type;
    type = dict;
  }
  return {
    name: get2(4, readString),
    type,
    nullable: get2(6, readBoolean, false),
    metadata: get2(16, decodeMetadata)
  };
}
function decodeFieldChildren(buf2, fieldOffset) {
  const children2 = readVector(buf2, fieldOffset, 4, decodeField);
  return children2.length ? children2 : null;
}
function decodeDictionary(buf2, index) {
  if (!index) return null;
  const get2 = readObject(buf2, index);
  return dictionary$1(
    null,
    // data type will be populated by caller
    get2(6, decodeInt, int32()),
    // index type
    get2(8, readBoolean, false),
    // ordered
    get2(4, readInt64, 0)
    // id
  );
}
function decodeInt(buf2, index) {
  return (
    /** @type {IntType} */
    decodeDataType(buf2, index, Type.Int)
  );
}
const invalidMessageMetadata = (expected, actual) => `Expected to read ${expected} metadata bytes, but only read ${actual}.`;
const invalidMessageBodyLength = (expected, actual) => `Expected to read ${expected} bytes for message body, but only read ${actual}.`;
const invalidMessageType = (type) => `Unsupported message type: ${type} (${keyFor(MessageHeader, type)})`;
function decodeMessage(buf2, index) {
  let metadataLength = readInt32(buf2, index) || 0;
  index += SIZEOF_INT;
  if (metadataLength === -1) {
    metadataLength = readInt32(buf2, index) || 0;
    index += SIZEOF_INT;
  }
  if (metadataLength === 0) return null;
  const head = buf2.subarray(index, index += metadataLength);
  if (head.byteLength < metadataLength) {
    throw new Error(invalidMessageMetadata(metadataLength, head.byteLength));
  }
  const get2 = readObject(head, 0);
  const version2 = (
    /** @type {Version_} */
    get2(4, readInt16, Version.V1)
  );
  const type = (
    /** @type {MessageHeader_} */
    get2(6, readUint8, MessageHeader.NONE)
  );
  const offset3 = get2(8, readOffset, 0);
  const bodyLength = get2(10, readInt64, 0);
  let content2;
  if (offset3) {
    const decoder2 = type === MessageHeader.Schema ? decodeSchema : type === MessageHeader.DictionaryBatch ? decodeDictionaryBatch : type === MessageHeader.RecordBatch ? decodeRecordBatch : null;
    if (!decoder2) throw new Error(invalidMessageType(type));
    content2 = decoder2(head, offset3, version2);
    if (bodyLength > 0) {
      const body = buf2.subarray(index, index += bodyLength);
      if (body.byteLength < bodyLength) {
        throw new Error(invalidMessageBodyLength(bodyLength, body.byteLength));
      }
      content2.body = body;
    } else if (type !== MessageHeader.Schema) {
      content2.body = new Uint8Array(0);
    }
  }
  return { version: version2, type, index, content: content2 };
}
function decodeIPC(data2) {
  const source2 = isArrayBufferLike(data2) ? new Uint8Array(data2) : data2;
  return source2 instanceof Uint8Array && isArrowFileFormat(source2) ? decodeIPCFile(source2) : decodeIPCStream(source2);
}
function isArrowFileFormat(buf2) {
  if (!buf2 || buf2.length < 4) return false;
  for (let i2 = 0; i2 < 6; ++i2) {
    if (MAGIC[i2] !== buf2[i2]) return false;
  }
  return true;
}
function decodeIPCStream(data2) {
  const stream = [data2].flat();
  let schema;
  const records = [];
  const dictionaries = [];
  for (const buf2 of stream) {
    if (!(buf2 instanceof Uint8Array)) {
      throw new Error(`IPC data batch was not a Uint8Array.`);
    }
    let offset3 = 0;
    while (true) {
      const m = decodeMessage(buf2, offset3);
      if (m === null) break;
      offset3 = m.index;
      if (!m.content) continue;
      switch (m.type) {
        case MessageHeader.Schema:
          if (!schema) schema = m.content;
          break;
        case MessageHeader.RecordBatch:
          records.push(m.content);
          break;
        case MessageHeader.DictionaryBatch:
          dictionaries.push(m.content);
          break;
      }
    }
  }
  return (
    /** @type {ArrowData} */
    { schema, dictionaries, records, metadata: null }
  );
}
function decodeIPCFile(data2) {
  const offset3 = data2.byteLength - (MAGIC.length + 4);
  const length2 = readInt32(data2, offset3);
  const get2 = readObject(data2, offset3 - length2);
  const version2 = (
    /** @type {Version_} */
    get2(4, readInt16, Version.V1)
  );
  const dicts = get2(8, decodeBlocks, []);
  const recs = get2(10, decodeBlocks, []);
  return (
    /** @type {ArrowData} */
    {
      schema: get2(6, (buf2, index) => decodeSchema(buf2, index, version2)),
      dictionaries: dicts.map(({ offset: offset4 }) => decodeMessage(data2, offset4).content),
      records: recs.map(({ offset: offset4 }) => decodeMessage(data2, offset4).content),
      metadata: get2(12, decodeMetadata)
    }
  );
}
function tableFromIPC(data2, options) {
  return createTable(decodeIPC(data2), options);
}
function createTable(data2, options = {}) {
  const { schema = { fields: [] }, dictionaries, records } = data2;
  const { version: version2, fields } = schema;
  const dictionaryMap = /* @__PURE__ */ new Map();
  const context = contextGenerator(options, version2, dictionaryMap);
  const dictionaryTypes = /* @__PURE__ */ new Map();
  visitSchemaFields(schema, (field2) => {
    const type = field2.type;
    if (type.typeId === Type.Dictionary) {
      dictionaryTypes.set(type.id, type.dictionary);
    }
  });
  const dicts = /* @__PURE__ */ new Map();
  for (const dict of dictionaries) {
    const { id: id2, data: data3, isDelta, body } = dict;
    const type = dictionaryTypes.get(id2);
    const batch2 = visit$1(type, context({ ...data3, body }));
    if (!dicts.has(id2)) {
      if (isDelta) {
        throw new Error("Delta update can not be first dictionary batch.");
      }
      dicts.set(id2, columnBuilder(type).add(batch2));
    } else {
      const dict2 = dicts.get(id2);
      if (!isDelta) dict2.clear();
      dict2.add(batch2);
    }
  }
  dicts.forEach((value2, key2) => dictionaryMap.set(key2, value2.done()));
  const cols = fields.map((f) => columnBuilder(f.type));
  for (const batch2 of records) {
    const ctx = context(batch2);
    fields.forEach((f, i2) => cols[i2].add(visit$1(f.type, ctx)));
  }
  return new Table3(schema, cols.map((c2) => c2.done()), options.useProxy);
}
function visitSchemaFields(schema, visitor) {
  schema.fields.forEach(function visitField(field2) {
    visitor(field2);
    field2.type.dictionary?.children?.forEach(visitField);
    field2.type.children?.forEach(visitField);
  });
}
function contextGenerator(options, version2, dictionaryMap) {
  const base2 = {
    version: version2,
    options,
    dictionary: (id2) => dictionaryMap.get(id2)
  };
  return (batch2) => {
    const { length: length2, nodes, regions, variadic, body } = batch2;
    let nodeIndex = -1;
    let bufferIndex = -1;
    let variadicIndex = -1;
    return {
      ...base2,
      length: length2,
      node: () => nodes[++nodeIndex],
      buffer: (ArrayType) => {
        const { length: length3, offset: offset3 } = regions[++bufferIndex];
        return ArrayType ? new ArrayType(body.buffer, body.byteOffset + offset3, length3 / ArrayType.BYTES_PER_ELEMENT) : body.subarray(offset3, offset3 + length3);
      },
      variadic: () => variadic[++variadicIndex],
      visit(children2) {
        return children2.map((f) => visit$1(f.type, this));
      }
    };
  };
}
function visit$1(type, ctx) {
  const { typeId } = type;
  const { options, node: node2, buffer: buffer2, variadic, version: version2 } = ctx;
  const BatchType = batchType(type, options);
  const base2 = { ...node2(), type };
  if (typeId === Type.Null) {
    return new BatchType({ ...base2, nullCount: base2.length });
  }
  switch (typeId) {
    // validity and data value buffers
    case Type.Bool:
    case Type.Int:
    case Type.Time:
    case Type.Duration:
    case Type.Float:
    case Type.Decimal:
    case Type.Date:
    case Type.Timestamp:
    case Type.Interval:
    case Type.FixedSizeBinary:
      return new BatchType({
        ...base2,
        validity: buffer2(),
        values: buffer2(type.values)
      });
    // validity, offset, and value buffers
    case Type.Utf8:
    case Type.LargeUtf8:
    case Type.Binary:
    case Type.LargeBinary:
      return new BatchType({
        ...base2,
        validity: buffer2(),
        offsets: buffer2(type.offsets),
        values: buffer2()
      });
    // views with variadic buffers
    case Type.BinaryView:
    case Type.Utf8View:
      return new BatchType({
        ...base2,
        validity: buffer2(),
        values: buffer2(),
        // views buffer
        data: Array.from({ length: variadic() }, () => buffer2())
        // data buffers
      });
    // validity, offset, and list child
    case Type.List:
    case Type.LargeList:
    case Type.Map:
      return new BatchType({
        ...base2,
        validity: buffer2(),
        offsets: buffer2(type.offsets),
        children: ctx.visit(type.children)
      });
    // validity, offset, size, and list child
    case Type.ListView:
    case Type.LargeListView:
      return new BatchType({
        ...base2,
        validity: buffer2(),
        offsets: buffer2(type.offsets),
        sizes: buffer2(type.offsets),
        children: ctx.visit(type.children)
      });
    // validity and children
    case Type.FixedSizeList:
    case Type.Struct:
      return new BatchType({
        ...base2,
        validity: buffer2(),
        children: ctx.visit(type.children)
      });
    // children only
    case Type.RunEndEncoded:
      return new BatchType({
        ...base2,
        children: ctx.visit(type.children)
      });
    // dictionary
    case Type.Dictionary: {
      const { id: id2, indices } = type;
      return new BatchType({
        ...base2,
        validity: buffer2(),
        values: buffer2(indices.values)
      }).setDictionary(ctx.dictionary(id2));
    }
    // union
    case Type.Union: {
      if (version2 < Version.V5) {
        buffer2();
      }
      return new BatchType({
        ...base2,
        typeIds: buffer2(int8Array),
        offsets: type.mode === UnionMode.Sparse ? null : buffer2(type.offsets),
        children: ctx.visit(type.children)
      });
    }
    // unsupported type
    default:
      throw new Error(invalidDataType(typeId));
  }
}
function writeInt32(buf2, index, value2) {
  buf2[index] = value2;
  buf2[index + 1] = value2 >> 8;
  buf2[index + 2] = value2 >> 16;
  buf2[index + 3] = value2 >> 24;
}
const INIT_SIZE = 1024;
class Builder2 {
  /**
   * Create a new builder instance.
   * @param {Sink} sink The byte consumer.
   */
  constructor(sink) {
    this.sink = sink;
    this.minalign = 1;
    this.buf = new Uint8Array(INIT_SIZE);
    this.space = INIT_SIZE;
    this.vtables = [];
    this.outputBytes = 0;
  }
  /**
   * Returns the flatbuffer offset, relative to the end of the current buffer.
   * @returns {number} Offset relative to the end of the buffer.
   */
  offset() {
    return this.buf.length - this.space;
  }
  /**
   * Write a flatbuffer int8 value at the current buffer position
   * and advance the internal cursor.
   * @param {number} value
   */
  writeInt8(value2) {
    this.buf[this.space -= 1] = value2;
  }
  /**
   * Write a flatbuffer int16 value at the current buffer position
   * and advance the internal cursor.
   * @param {number} value
   */
  writeInt16(value2) {
    this.buf[this.space -= 2] = value2;
    this.buf[this.space + 1] = value2 >> 8;
  }
  /**
   * Write a flatbuffer int32 value at the current buffer position
   * and advance the internal cursor.
   * @param {number} value
   */
  writeInt32(value2) {
    writeInt32(this.buf, this.space -= 4, value2);
  }
  /**
   * Write a flatbuffer int64 value at the current buffer position
   * and advance the internal cursor.
   * @param {number} value
   */
  writeInt64(value2) {
    const v = BigInt(value2);
    this.writeInt32(Number(BigInt.asIntN(32, v >> BigInt(32))));
    this.writeInt32(Number(BigInt.asIntN(32, v)));
  }
  /**
   * Add a flatbuffer int8 value, properly aligned,
   * @param value The int8 value to add the buffer.
   */
  addInt8(value2) {
    prep(this, 1, 0);
    this.writeInt8(value2);
  }
  /**
   * Add a flatbuffer int16 value, properly aligned,
   * @param value The int16 value to add the buffer.
   */
  addInt16(value2) {
    prep(this, 2, 0);
    this.writeInt16(value2);
  }
  /**
   * Add a flatbuffer int32 value, properly aligned,
   * @param value The int32 value to add the buffer.
   */
  addInt32(value2) {
    prep(this, 4, 0);
    this.writeInt32(value2);
  }
  /**
   * Add a flatbuffer int64 values, properly aligned.
   * @param value The int64 value to add the buffer.
   */
  addInt64(value2) {
    prep(this, 8, 0);
    this.writeInt64(value2);
  }
  /**
   * Add a flatbuffer offset, relative to where it will be written.
   * @param {number} offset The offset to add.
   */
  addOffset(offset3) {
    prep(this, SIZEOF_INT, 0);
    this.writeInt32(this.offset() - offset3 + SIZEOF_INT);
  }
  /**
   * Add a flatbuffer object (vtable).
   * @param {number} numFields The maximum number of fields
   *  this object may include.
   * @param {(tableBuilder: ReturnType<objectBuilder>) => void} [addFields]
   *  A callback function that writes all fields using an object builder.
   * @returns {number} The object offset.
   */
  addObject(numFields, addFields) {
    const b = objectBuilder(this, numFields);
    addFields?.(b);
    return b.finish();
  }
  /**
   * Add a flatbuffer vector (list).
   * @template T
   * @param {T[]} items An array of items to write.
   * @param {number} itemSize The size in bytes of a serialized item.
   * @param {number} alignment The desired byte alignment value.
   * @param {(builder: this, item: T) => void} writeItem A callback
   *  function that writes a vector item to this builder.
   * @returns {number} The vector offset.
   */
  addVector(items, itemSize, alignment, writeItem) {
    const n2 = items?.length;
    if (!n2) return 0;
    prep(this, SIZEOF_INT, itemSize * n2);
    prep(this, alignment, itemSize * n2);
    for (let i2 = n2; --i2 >= 0; ) {
      writeItem(this, items[i2]);
    }
    this.writeInt32(n2);
    return this.offset();
  }
  /**
   * Convenience method for writing a vector of byte buffer offsets.
   * @param {number[]} offsets
   * @returns {number} The vector offset.
   */
  addOffsetVector(offsets) {
    return this.addVector(offsets, 4, 4, (b, off) => b.addOffset(off));
  }
  /**
   * Add a flatbuffer UTF-8 string.
   * @param {string} s The string to encode.
   * @return {number} The string offset.
   */
  addString(s) {
    if (s == null) return 0;
    const utf82 = encodeUtf8(s);
    const n2 = utf82.length;
    this.addInt8(0);
    prep(this, SIZEOF_INT, n2);
    this.buf.set(utf82, this.space -= n2);
    this.writeInt32(n2);
    return this.offset();
  }
  /**
   * Finish the current flatbuffer by adding a root offset.
   * @param {number} rootOffset The root offset.
   */
  finish(rootOffset) {
    prep(this, this.minalign, SIZEOF_INT);
    this.addOffset(rootOffset);
  }
  /**
   * Flush the current flatbuffer byte buffer content to the sink,
   * and reset the flatbuffer builder state.
   */
  flush() {
    const { buf: buf2, sink } = this;
    const bytes = buf2.subarray(this.space, buf2.length);
    sink.write(bytes);
    this.outputBytes += bytes.byteLength;
    this.minalign = 1;
    this.vtables = [];
    this.buf = new Uint8Array(INIT_SIZE);
    this.space = INIT_SIZE;
  }
  /**
   * Add a byte buffer directly to the builder sink. This method bypasses
   * any unflushed flatbuffer state and leaves it unchanged, writing the
   * buffer to the sink *before* the flatbuffer.
   * The buffer will be padded for 64-bit (8-byte) alignment as needed.
   * @param {Uint8Array} buffer The buffer to add.
   * @returns {number} The total byte count of the buffer and padding.
   */
  addBuffer(buffer2) {
    const size = buffer2.byteLength;
    if (!size) return 0;
    this.sink.write(buffer2);
    this.outputBytes += size;
    const pad3 = (size + 7 & -8) - size;
    this.addPadding(pad3);
    return size + pad3;
  }
  /**
   * Write padding bytes directly to the builder sink. This method bypasses
   * any unflushed flatbuffer state and leaves it unchanged, writing the
   * padding bytes to the sink *before* the flatbuffer.
   * @param {number} byteCount The number of padding bytes.
   */
  addPadding(byteCount) {
    if (byteCount > 0) {
      this.sink.write(new Uint8Array(byteCount));
      this.outputBytes += byteCount;
    }
  }
}
function prep(builder2, size, additionalBytes) {
  let { buf: buf2, space, minalign } = builder2;
  if (size > minalign) {
    builder2.minalign = size;
  }
  const bufSize = buf2.length;
  const used = bufSize - space + additionalBytes;
  const alignSize = ~used + 1 & size - 1;
  buf2 = grow(buf2, used + alignSize + size - 1, true);
  space += buf2.length - bufSize;
  for (let i2 = 0; i2 < alignSize; ++i2) {
    buf2[--space] = 0;
  }
  builder2.buf = buf2;
  builder2.space = space;
}
function objectBuilder(builder2, numFields) {
  const vtable = Array(numFields).fill(0);
  const startOffset = builder2.offset();
  function slot(index) {
    vtable[index] = builder2.offset();
  }
  return {
    /**
     * Add an int8-valued table field.
     * @param {number} index
     * @param {number} value
     * @param {number} defaultValue
     */
    addInt8(index, value2, defaultValue) {
      if (value2 != defaultValue) {
        builder2.addInt8(value2);
        slot(index);
      }
    },
    /**
     * Add an int16-valued table field.
     * @param {number} index
     * @param {number} value
     * @param {number} defaultValue
     */
    addInt16(index, value2, defaultValue) {
      if (value2 != defaultValue) {
        builder2.addInt16(value2);
        slot(index);
      }
    },
    /**
     * Add an int32-valued table field.
     * @param {number} index
     * @param {number} value
     * @param {number} defaultValue
     */
    addInt32(index, value2, defaultValue) {
      if (value2 != defaultValue) {
        builder2.addInt32(value2);
        slot(index);
      }
    },
    /**
     * Add an int64-valued table field.
     * @param {number} index
     * @param {number} value
     * @param {number} defaultValue
     */
    addInt64(index, value2, defaultValue) {
      if (value2 != defaultValue) {
        builder2.addInt64(value2);
        slot(index);
      }
    },
    /**
     * Add a buffer offset-valued table field.
     * @param {number} index
     * @param {number} value
     * @param {number} defaultValue
     */
    addOffset(index, value2, defaultValue) {
      if (value2 != defaultValue) {
        builder2.addOffset(value2);
        slot(index);
      }
    },
    /**
     * Write the vtable to the buffer and return the table offset.
     * @returns {number} The buffer offset to the vtable.
     */
    finish() {
      builder2.addInt32(0);
      const vtableOffset = builder2.offset();
      let i2 = numFields;
      while (--i2 >= 0 && vtable[i2] === 0) {
      }
      const size = i2 + 1;
      for (; i2 >= 0; --i2) {
        builder2.addInt16(vtable[i2] ? vtableOffset - vtable[i2] : 0);
      }
      const standardFields = 2;
      builder2.addInt16(vtableOffset - startOffset);
      const len = (size + standardFields) * SIZEOF_SHORT;
      builder2.addInt16(len);
      let existingTable = 0;
      const { buf: buf2, vtables, space: vt1 } = builder2;
      outer_loop:
        for (i2 = 0; i2 < vtables.length; ++i2) {
          const vt2 = buf2.length - vtables[i2];
          if (len == readInt16(buf2, vt2)) {
            for (let j2 = SIZEOF_SHORT; j2 < len; j2 += SIZEOF_SHORT) {
              if (readInt16(buf2, vt1 + j2) != readInt16(buf2, vt2 + j2)) {
                continue outer_loop;
              }
            }
            existingTable = vtables[i2];
            break;
          }
        }
      if (existingTable) {
        builder2.space = buf2.length - vtableOffset;
        writeInt32(buf2, builder2.space, existingTable - vtableOffset);
      } else {
        const off = builder2.offset();
        vtables.push(off);
        writeInt32(buf2, buf2.length - vtableOffset, off - vtableOffset);
      }
      return vtableOffset;
    }
  };
}
function encodeRecordBatch(builder2, batch2) {
  const { nodes, regions, variadic } = batch2;
  const nodeVector = builder2.addVector(
    nodes,
    16,
    8,
    (builder3, node2) => {
      builder3.writeInt64(node2.nullCount);
      builder3.writeInt64(node2.length);
      return builder3.offset();
    }
  );
  const regionVector = builder2.addVector(
    regions,
    16,
    8,
    (builder3, region) => {
      builder3.writeInt64(region.length);
      builder3.writeInt64(region.offset);
      return builder3.offset();
    }
  );
  const variadicVector = builder2.addVector(
    variadic,
    8,
    8,
    (builder3, count2) => builder3.addInt64(count2)
  );
  return builder2.addObject(5, (b) => {
    b.addInt64(0, nodes[0].length, 0);
    b.addOffset(1, nodeVector, 0);
    b.addOffset(2, regionVector, 0);
    b.addOffset(4, variadicVector, 0);
  });
}
function encodeDictionaryBatch(builder2, dictionaryBatch) {
  const dataOffset = encodeRecordBatch(builder2, dictionaryBatch.data);
  return builder2.addObject(3, (b) => {
    b.addInt64(0, dictionaryBatch.id, 0);
    b.addOffset(1, dataOffset, 0);
    b.addInt8(2, +dictionaryBatch.isDelta, 0);
  });
}
function encodeMetadata(builder2, metadata2) {
  return metadata2?.size > 0 ? builder2.addOffsetVector(Array.from(metadata2, ([k, v]) => {
    const key2 = builder2.addString(`${k}`);
    const val = builder2.addString(`${v}`);
    return builder2.addObject(2, (b) => {
      b.addOffset(0, key2, 0);
      b.addOffset(1, val, 0);
    });
  })) : 0;
}
function encodeDataType(builder2, type) {
  const typeId = checkOneOf(type.typeId, Type, invalidDataType);
  switch (typeId) {
    case Type.Dictionary:
      return encodeDictionary(builder2, type);
    case Type.Int:
      return encodeInt(builder2, type);
    case Type.Float:
      return encodeFloat(builder2, type);
    case Type.Decimal:
      return encodeDecimal(builder2, type);
    case Type.Date:
      return encodeDate(builder2, type);
    case Type.Time:
      return encodeTime(builder2, type);
    case Type.Timestamp:
      return encodeTimestamp(builder2, type);
    case Type.Interval:
      return encodeInterval(builder2, type);
    case Type.Duration:
      return encodeDuration(builder2, type);
    case Type.FixedSizeBinary:
    case Type.FixedSizeList:
      return encodeFixedSize(builder2, type);
    case Type.Map:
      return encodeMap(builder2, type);
    case Type.Union:
      return encodeUnion(builder2, type);
  }
  return builder2.addObject(0);
}
function encodeDate(builder2, type) {
  return builder2.addObject(1, (b) => {
    b.addInt16(0, type.unit, DateUnit.MILLISECOND);
  });
}
function encodeDecimal(builder2, type) {
  return builder2.addObject(3, (b) => {
    b.addInt32(0, type.precision, 0);
    b.addInt32(1, type.scale, 0);
    b.addInt32(2, type.bitWidth, 128);
  });
}
function encodeDuration(builder2, type) {
  return builder2.addObject(1, (b) => {
    b.addInt16(0, type.unit, TimeUnit.MILLISECOND);
  });
}
function encodeFixedSize(builder2, type) {
  return builder2.addObject(1, (b) => {
    b.addInt32(0, type.stride, 0);
  });
}
function encodeFloat(builder2, type) {
  return builder2.addObject(1, (b) => {
    b.addInt16(0, type.precision, Precision.HALF);
  });
}
function encodeInt(builder2, type) {
  return builder2.addObject(2, (b) => {
    b.addInt32(0, type.bitWidth, 0);
    b.addInt8(1, +type.signed, 0);
  });
}
function encodeInterval(builder2, type) {
  return builder2.addObject(1, (b) => {
    b.addInt16(0, type.unit, IntervalUnit.YEAR_MONTH);
  });
}
function encodeMap(builder2, type) {
  return builder2.addObject(1, (b) => {
    b.addInt8(0, +type.keysSorted, 0);
  });
}
function encodeTime(builder2, type) {
  return builder2.addObject(2, (b) => {
    b.addInt16(0, type.unit, TimeUnit.MILLISECOND);
    b.addInt32(1, type.bitWidth, 32);
  });
}
function encodeTimestamp(builder2, type) {
  const timezoneOffset = builder2.addString(type.timezone);
  return builder2.addObject(2, (b) => {
    b.addInt16(0, type.unit, TimeUnit.SECOND);
    b.addOffset(1, timezoneOffset, 0);
  });
}
function encodeUnion(builder2, type) {
  const typeIdsOffset = builder2.addVector(
    type.typeIds,
    4,
    4,
    (builder3, value2) => builder3.addInt32(value2)
  );
  return builder2.addObject(2, (b) => {
    b.addInt16(0, type.mode, UnionMode.Sparse);
    b.addOffset(1, typeIdsOffset, 0);
  });
}
function encodeDictionary(builder2, type) {
  return builder2.addObject(4, (b) => {
    b.addInt64(0, type.id, 0);
    b.addOffset(1, encodeDataType(builder2, type.indices), 0);
    b.addInt8(2, +type.ordered, 0);
  });
}
const isLittleEndian = new Uint16Array(new Uint8Array([1, 0]).buffer)[0] === 1;
function encodeSchema(builder2, schema) {
  const { fields, metadata: metadata2 } = schema;
  const fieldOffsets = fields.map((f) => encodeField(builder2, f));
  const fieldsVectorOffset = builder2.addOffsetVector(fieldOffsets);
  const metadataOffset = encodeMetadata(builder2, metadata2);
  return builder2.addObject(4, (b) => {
    b.addInt16(0, +!isLittleEndian, 0);
    b.addOffset(1, fieldsVectorOffset, 0);
    b.addOffset(2, metadataOffset, 0);
  });
}
function encodeField(builder2, field2) {
  const { name: name2, nullable, type, metadata: metadata2 } = field2;
  let { typeId } = type;
  let typeOffset = 0;
  let dictionaryOffset = 0;
  if (typeId !== Type.Dictionary) {
    typeOffset = encodeDataType(builder2, type);
  } else {
    const dict = (
      /** @type {DictionaryType} */
      type.dictionary
    );
    typeId = dict.typeId;
    dictionaryOffset = encodeDataType(builder2, type);
    typeOffset = encodeDataType(builder2, dict);
  }
  const childOffsets = (type.children || []).map((f) => encodeField(builder2, f));
  const childrenVectorOffset = builder2.addOffsetVector(childOffsets);
  const metadataOffset = encodeMetadata(builder2, metadata2);
  const nameOffset = builder2.addString(name2);
  return builder2.addObject(7, (b) => {
    b.addOffset(0, nameOffset, 0);
    b.addInt8(1, +nullable, 0);
    b.addInt8(2, typeId, Type.NONE);
    b.addOffset(3, typeOffset, 0);
    b.addOffset(4, dictionaryOffset, 0);
    b.addOffset(5, childrenVectorOffset, 0);
    b.addOffset(6, metadataOffset, 0);
  });
}
function writeFooter(builder2, schema, dictBlocks, recordBlocks, metadata2) {
  const metadataOffset = encodeMetadata(builder2, metadata2);
  const recsOffset = builder2.addVector(recordBlocks, 24, 8, encodeBlock);
  const dictsOffset = builder2.addVector(dictBlocks, 24, 8, encodeBlock);
  const schemaOffset = encodeSchema(builder2, schema);
  builder2.finish(
    builder2.addObject(5, (b) => {
      b.addInt16(0, Version.V5, Version.V1);
      b.addOffset(1, schemaOffset, 0);
      b.addOffset(2, dictsOffset, 0);
      b.addOffset(3, recsOffset, 0);
      b.addOffset(4, metadataOffset, 0);
    })
  );
  const size = builder2.offset();
  builder2.addInt32(0);
  builder2.addInt32(-1);
  builder2.flush();
  builder2.sink.write(new Uint8Array(Int32Array.of(size).buffer));
  builder2.sink.write(MAGIC);
}
function encodeBlock(builder2, { offset: offset3, metadataLength, bodyLength }) {
  builder2.writeInt64(bodyLength);
  builder2.writeInt32(0);
  builder2.writeInt32(metadataLength);
  builder2.writeInt64(offset3);
  return builder2.offset();
}
function writeMessage(builder2, headerType, headerOffset, bodyLength, blocks) {
  builder2.finish(
    builder2.addObject(5, (b) => {
      b.addInt16(0, Version.V5, Version.V1);
      b.addInt8(1, headerType, MessageHeader.NONE);
      b.addOffset(2, headerOffset, 0);
      b.addInt64(3, bodyLength, 0);
    })
  );
  const prefixSize = 8;
  const messageSize = builder2.offset();
  const alignedSize = messageSize + prefixSize + 7 & -8;
  blocks?.push({
    offset: builder2.outputBytes,
    metadataLength: alignedSize,
    bodyLength
  });
  builder2.addInt32(alignedSize - prefixSize);
  builder2.addInt32(-1);
  builder2.flush();
  builder2.addPadding(alignedSize - messageSize - prefixSize);
}
class Sink {
  /**
   * Write bytes to this sink.
   * @param {Uint8Array} bytes The byte buffer to write.
   */
  write(bytes) {
  }
  /**
   * Write padding bytes (zeroes) to this sink.
   * @param {number} byteCount The number of padding bytes.
   */
  pad(byteCount) {
    this.write(new Uint8Array(byteCount));
  }
  /**
   * @returns {Uint8Array | null}
   */
  finish() {
    return null;
  }
}
class MemorySink extends Sink {
  /**
   * A sink that collects bytes in memory.
   */
  constructor() {
    super();
    this.buffers = [];
  }
  /**
   * Write bytes
   * @param {Uint8Array} bytes
   */
  write(bytes) {
    this.buffers.push(bytes);
  }
  /**
   * @returns {Uint8Array}
   */
  finish() {
    const bufs = this.buffers;
    const size = bufs.reduce((sum, b) => sum + b.byteLength, 0);
    const buf2 = new Uint8Array(size);
    for (let i2 = 0, off = 0; i2 < bufs.length; ++i2) {
      buf2.set(bufs[i2], off);
      off += bufs[i2].byteLength;
    }
    return buf2;
  }
}
const STREAM = "stream";
const FILE = "file";
function encodeIPC(data2, { sink, format: format2 = STREAM } = {}) {
  if (format2 !== STREAM && format2 !== FILE) {
    throw new Error(`Unrecognized Arrow IPC format: ${format2}`);
  }
  const { schema, dictionaries = [], records = [], metadata: metadata2 } = data2;
  const builder2 = new Builder2(sink || new MemorySink());
  const file = format2 === FILE;
  const dictBlocks = [];
  const recordBlocks = [];
  if (file) {
    builder2.addBuffer(MAGIC);
  }
  if (schema) {
    writeMessage(
      builder2,
      MessageHeader.Schema,
      encodeSchema(builder2, schema),
      0
    );
  }
  for (const dict of dictionaries) {
    const { data: data3 } = dict;
    writeMessage(
      builder2,
      MessageHeader.DictionaryBatch,
      encodeDictionaryBatch(builder2, dict),
      data3.byteLength,
      dictBlocks
    );
    writeBuffers(builder2, data3.buffers);
  }
  for (const batch2 of records) {
    writeMessage(
      builder2,
      MessageHeader.RecordBatch,
      encodeRecordBatch(builder2, batch2),
      batch2.byteLength,
      recordBlocks
    );
    writeBuffers(builder2, batch2.buffers);
  }
  builder2.addBuffer(EOS);
  if (file) {
    writeFooter(builder2, schema, dictBlocks, recordBlocks, metadata2);
  }
  return builder2.sink;
}
function writeBuffers(builder2, buffers) {
  for (let i2 = 0; i2 < buffers.length; ++i2) {
    builder2.addBuffer(buffers[i2]);
  }
}
function tableToIPC(table2, options) {
  if (typeof options === "string") {
    options = { format: options };
  }
  const columns2 = table2.children;
  checkBatchLengths(columns2);
  const { dictionaries, idMap } = assembleDictionaryBatches(columns2);
  const records = assembleRecordBatches(columns2);
  const schema = assembleSchema(table2.schema, idMap);
  const data2 = { schema, dictionaries, records };
  return encodeIPC(data2, options).finish();
}
function checkBatchLengths(columns2) {
  const n2 = columns2[0]?.data.map((d) => d.length);
  columns2.forEach(({ data: data2 }) => {
    if (data2.length !== n2.length || data2.some((b, i2) => b.length !== n2[i2])) {
      throw new Error("Columns have inconsistent batch sizes.");
    }
  });
}
function assembleContext() {
  let byteLength = 0;
  const nodes = [];
  const regions = [];
  const buffers = [];
  const variadic = [];
  return {
    /**
     * @param {number} length
     * @param {number} nullCount
     */
    node(length2, nullCount) {
      nodes.push({ length: length2, nullCount });
    },
    /**
     * @param {TypedArray} b
     */
    buffer(b) {
      const size = b.byteLength;
      const length2 = size + 7 & -8;
      regions.push({ offset: byteLength, length: length2 });
      byteLength += length2;
      buffers.push(new Uint8Array(b.buffer, b.byteOffset, size));
    },
    /**
     * @param {number} length
     */
    variadic(length2) {
      variadic.push(length2);
    },
    /**
     * @param {DataType} type
     * @param {Batch} batch
     */
    children(type, batch2) {
      type.children.forEach((field2, index) => {
        visit(field2.type, batch2.children[index], this);
      });
    },
    /**
     * @returns {RecordBatch}
     */
    done() {
      return { byteLength, nodes, regions, variadic, buffers };
    }
  };
}
function assembleDictionaryBatches(columns2) {
  const dictionaries = [];
  const dictMap = /* @__PURE__ */ new Map();
  const idMap = /* @__PURE__ */ new Map();
  let id2 = -1;
  const visitor = (dictionaryColumn) => {
    if (!dictMap.has(dictionaryColumn)) {
      dictMap.set(dictionaryColumn, ++id2);
      for (let i2 = 0; i2 < dictionaryColumn.data.length; ++i2) {
        dictionaries.push({
          id: id2,
          isDelta: i2 > 0,
          data: assembleRecordBatch([dictionaryColumn], i2)
        });
      }
      idMap.set(dictionaryColumn.type, id2);
    } else {
      idMap.set(dictionaryColumn.type, dictMap.get(dictionaryColumn));
    }
  };
  columns2.forEach((col) => visitDictionaries(col.data[0], visitor));
  return { dictionaries, idMap };
}
function visitDictionaries(batch2, visitor) {
  if (batch2?.type.typeId === Type.Dictionary) {
    const dictionary2 = batch2.dictionary;
    visitor(dictionary2);
    visitDictionaries(dictionary2.data[0], visitor);
  }
  batch2?.children?.forEach((child) => visitDictionaries(child, visitor));
}
function assembleSchema(schema, idMap) {
  if (!idMap.size) return schema;
  const visit2 = (type) => {
    if (type.typeId === Type.Dictionary) {
      type.id = idMap.get(type.dictionary);
      visitDictType(type);
    }
    if (type.children) {
      (type.children = type.children.slice()).forEach(visitFields);
    }
  };
  const visitFields = (field2, index, array2) => {
    const type = { ...field2.type };
    array2[index] = { ...field2, type };
    visit2(type);
  };
  const visitDictType = (parentType) => {
    const type = { ...parentType.dictionary };
    parentType.dictionary = type;
    visit2(type);
  };
  schema = { ...schema, fields: schema.fields.slice() };
  schema.fields.forEach(visitFields);
  return schema;
}
function assembleRecordBatches(columns2) {
  return (columns2[0]?.data || []).map((_, index) => assembleRecordBatch(columns2, index));
}
function assembleRecordBatch(columns2, batchIndex = 0) {
  const ctx = assembleContext();
  columns2.forEach((column2) => {
    visit(column2.type, column2.data[batchIndex], ctx);
  });
  return ctx.done();
}
function visit(type, batch2, ctx) {
  const { typeId } = type;
  ctx.node(batch2.length, batch2.nullCount);
  if (typeId === Type.Null) return;
  switch (typeId) {
    // validity and value buffers
    // backing dictionaries handled elsewhere
    case Type.Bool:
    case Type.Int:
    case Type.Time:
    case Type.Duration:
    case Type.Float:
    case Type.Date:
    case Type.Timestamp:
    case Type.Decimal:
    case Type.Interval:
    case Type.FixedSizeBinary:
    case Type.Dictionary:
      ctx.buffer(batch2.validity);
      ctx.buffer(batch2.values);
      return;
    // validity, offset, and value buffers
    case Type.Utf8:
    case Type.LargeUtf8:
    case Type.Binary:
    case Type.LargeBinary:
      ctx.buffer(batch2.validity);
      ctx.buffer(batch2.offsets);
      ctx.buffer(batch2.values);
      return;
    // views with variadic buffers
    case Type.BinaryView:
    case Type.Utf8View:
      ctx.buffer(batch2.validity);
      ctx.buffer(batch2.values);
      ctx.variadic(batch2.data.length);
      batch2.data.forEach((b) => ctx.buffer(b));
      return;
    // validity, offset, and list child
    case Type.List:
    case Type.LargeList:
    case Type.Map:
      ctx.buffer(batch2.validity);
      ctx.buffer(batch2.offsets);
      ctx.children(type, batch2);
      return;
    // validity, offset, size, and list child
    case Type.ListView:
    case Type.LargeListView:
      ctx.buffer(batch2.validity);
      ctx.buffer(batch2.offsets);
      ctx.buffer(batch2.sizes);
      ctx.children(type, batch2);
      return;
    // validity and children
    case Type.FixedSizeList:
    case Type.Struct:
      ctx.buffer(batch2.validity);
      ctx.children(type, batch2);
      return;
    // children only
    case Type.RunEndEncoded:
      ctx.children(type, batch2);
      return;
    // union
    case Type.Union: {
      ctx.buffer(batch2.typeIds);
      if (type.mode === UnionMode.Dense) {
        ctx.buffer(batch2.offsets);
      }
      ctx.children(type, batch2);
      return;
    }
    // unsupported type
    default:
      throw new Error(invalidDataType(typeId));
  }
}
function buffer$1(arrayType2) {
  return new Buffer2(arrayType2);
}
class Buffer2 {
  /**
   * Create a new resizable buffer instance.
   * @param {TypedArrayConstructor} arrayType
   */
  constructor(arrayType2 = uint8Array) {
    this.buf = new arrayType2(512);
  }
  /**
   * Return the underlying data as a 64-bit aligned array of minimum size.
   * @param {number} size The desired minimum array size.
   * @returns {TypedArray} The 64-bit aligned array.
   */
  array(size) {
    return align(this.buf, size);
  }
  /**
   * Prepare for writes to the given index, resizing as necessary.
   * @param {number} index The array index to prepare to write to.
   */
  prep(index) {
    if (index >= this.buf.length) {
      this.buf = grow(this.buf, index);
    }
  }
  /**
   * Return the value at the given index.
   * @param {number} index The array index.
   */
  get(index) {
    return this.buf[index];
  }
  /**
   * Set a value at the given index.
   * @param {number | bigint} value The value to set.
   * @param {number} index The index to write to.
   */
  set(value2, index) {
    this.prep(index);
    this.buf[index] = value2;
  }
  /**
   * Write a byte array at the given index. The method should be called
   * only when the underlying buffer is of type Uint8Array.
   * @param {Uint8Array} bytes The byte array.
   * @param {number} index The starting index to write to.
   */
  write(bytes, index) {
    this.prep(index + bytes.length);
    this.buf.set(bytes, index);
  }
}
function bitmap() {
  return new Bitmap();
}
class Bitmap extends Buffer2 {
  /**
   * Set a bit to true at the given bitmap index.
   * @param {number} index The index to write to.
   */
  set(index) {
    const i2 = index >> 3;
    this.prep(i2);
    this.buf[i2] |= 1 << index % 8;
  }
}
class BatchBuilder {
  constructor(type, ctx) {
    this.type = type;
    this.ctx = ctx;
    this.batchClass = ctx.batchType(type);
  }
  /**
   * Initialize the builder state.
   * @returns {this} This builder.
   */
  init() {
    this.index = -1;
    return this;
  }
  /**
   * Write a value to the builder.
   * @param {*} value
   * @param {number} index
   * @returns {boolean | void}
   */
  set(value2, index) {
    this.index = index;
    return false;
  }
  /**
   * Returns a batch constructor options object.
   * Used internally to marshal batch data.
   * @returns {Record<string, any>}
   */
  done() {
    return null;
  }
  /**
   * Returns a completed batch and reinitializes the builder state.
   * @returns {Batch}
   */
  batch() {
    const b = new this.batchClass(this.done());
    this.init();
    return b;
  }
}
class ValidityBuilder extends BatchBuilder {
  constructor(type, ctx) {
    super(type, ctx);
  }
  init() {
    this.nullCount = 0;
    this.validity = bitmap();
    return super.init();
  }
  /**
   * @param {*} value
   * @param {number} index
   * @returns {boolean | void}
   */
  set(value2, index) {
    this.index = index;
    const isValid2 = value2 != null;
    if (isValid2) {
      this.validity.set(index);
    } else {
      this.nullCount++;
    }
    return isValid2;
  }
  done() {
    const { index, nullCount, type, validity } = this;
    return {
      length: index + 1,
      nullCount,
      type,
      validity: nullCount ? validity.array((index >> 3) + 1) : new uint8Array(0)
    };
  }
}
function dictionaryContext() {
  const idMap = /* @__PURE__ */ new Map();
  const dicts = /* @__PURE__ */ new Set();
  return {
    /**
     * Get a dictionary values builder for the given dictionary type.
     * @param {DictionaryType} type
     *  The dictionary type.
     * @param {*} ctx The builder context.
     * @returns {ReturnType<dictionaryValues>}
     */
    get(type, ctx) {
      const id2 = type.id;
      if (id2 >= 0 && idMap.has(id2)) {
        return idMap.get(id2);
      } else {
        const dict = dictionaryValues(type, ctx);
        if (id2 >= 0) idMap.set(id2, dict);
        dicts.add(dict);
        return dict;
      }
    },
    /**
     * Finish building dictionary values columns and assign them to
     * their corresponding dictionary batches.
     * @param {ExtractionOptions} options
     */
    finish(options) {
      dicts.forEach((dict) => dict.finish(options));
    }
  };
}
function dictionaryValues(type, ctx) {
  const keys2 = /* @__PURE__ */ Object.create(null);
  const values2 = ctx.builder(type.dictionary);
  const batches = [];
  values2.init();
  let index = -1;
  return {
    type,
    values: values2,
    add(batch2) {
      batches.push(batch2);
      return batch2;
    },
    key(value2) {
      const v = keyString(value2);
      let k = keys2[v];
      if (k === void 0) {
        keys2[v] = k = ++index;
        values2.set(value2, k);
      }
      return k;
    },
    finish(options) {
      const valueType = type.dictionary;
      const batch2 = new (batchType(valueType, options))(values2.done());
      const dictionary2 = new Column([batch2]);
      batches.forEach((batch3) => batch3.setDictionary(dictionary2));
    }
  };
}
class DictionaryBuilder extends ValidityBuilder {
  constructor(type, ctx) {
    super(type, ctx);
    this.dict = ctx.dictionary(type);
  }
  init() {
    this.values = buffer$1(this.type.indices.values);
    return super.init();
  }
  set(value2, index) {
    if (super.set(value2, index)) {
      this.values.set(this.dict.key(value2), index);
    }
  }
  done() {
    return {
      ...super.done(),
      values: this.values.array(this.index + 1)
    };
  }
  batch() {
    return this.dict.add(super.batch());
  }
}
function inferType$1(visit2) {
  const profile = profiler();
  visit2((value2) => profile.add(value2));
  return profile.type();
}
function profiler() {
  let length2 = 0;
  let nullCount = 0;
  let boolCount = 0;
  let numberCount = 0;
  let intCount = 0;
  let bigintCount = 0;
  let dateCount = 0;
  let dayCount = 0;
  let stringCount = 0;
  let arrayCount = 0;
  let structCount = 0;
  let min2 = Infinity;
  let max2 = -Infinity;
  let minLength = Infinity;
  let maxLength = -Infinity;
  let minBigInt;
  let maxBigInt;
  let arrayProfile;
  let structProfiles = {};
  return {
    add(value2) {
      length2++;
      if (value2 == null) {
        nullCount++;
        return;
      }
      switch (typeof value2) {
        case "string":
          stringCount++;
          break;
        case "number":
          numberCount++;
          if (value2 < min2) min2 = value2;
          if (value2 > max2) max2 = value2;
          if (Number.isInteger(value2)) intCount++;
          break;
        case "bigint":
          bigintCount++;
          if (minBigInt === void 0) {
            minBigInt = maxBigInt = value2;
          } else {
            if (value2 < minBigInt) minBigInt = value2;
            if (value2 > maxBigInt) maxBigInt = value2;
          }
          break;
        case "boolean":
          boolCount++;
          break;
        case "object":
          if (value2 instanceof Date) {
            dateCount++;
            if (+value2 % 864e5 === 0) dayCount++;
          } else if (isArray(value2)) {
            arrayCount++;
            const len = value2.length;
            if (len < minLength) minLength = len;
            if (len > maxLength) maxLength = len;
            arrayProfile ??= profiler();
            value2.forEach(arrayProfile.add);
          } else {
            structCount++;
            for (const key2 in value2) {
              const fieldProfiler = structProfiles[key2] ?? (structProfiles[key2] = profiler());
              fieldProfiler.add(value2[key2]);
            }
          }
      }
    },
    type() {
      const valid = length2 - nullCount;
      return valid === 0 ? nullType() : intCount === valid ? intType(min2, max2) : numberCount === valid ? float64() : bigintCount === valid ? bigintType(minBigInt, maxBigInt) : boolCount === valid ? bool() : dayCount === valid ? dateDay() : dateCount === valid ? timestamp() : stringCount === valid ? dictionary$1(utf8()) : arrayCount === valid ? arrayType(arrayProfile.type(), minLength, maxLength) : structCount === valid ? struct(
        Object.entries(structProfiles).map((_) => field(_[0], _[1].type()))
      ) : unionType();
    }
  };
}
function arrayType(type, minLength, maxLength) {
  return maxLength === minLength ? fixedSizeList(type, minLength) : list$1(type);
}
function intType(min2, max2) {
  const v = Math.max(Math.abs(min2) - 1, max2);
  return v < 1 << 7 ? int8() : v < 1 << 15 ? int16() : v < 2 ** 31 ? int32() : float64();
}
function bigintType(min2, max2) {
  const v = -min2 > max2 ? -min2 - 1n : max2;
  if (v >= 2 ** 63) {
    throw new Error(`BigInt exceeds 64 bits: ${v}`);
  }
  return int64();
}
function unionType() {
  throw new Error("Mixed types detected, please define a union type.");
}
class BinaryBuilder extends ValidityBuilder {
  constructor(type, ctx) {
    super(type, ctx);
    this.toOffset = toOffset(type.offsets);
  }
  init() {
    this.offsets = buffer$1(this.type.offsets);
    this.values = buffer$1();
    this.pos = 0;
    return super.init();
  }
  set(value2, index) {
    const { offsets, values: values2, toOffset: toOffset2 } = this;
    if (super.set(value2, index)) {
      values2.write(value2, this.pos);
      this.pos += value2.length;
    }
    offsets.set(toOffset2(this.pos), index + 1);
  }
  done() {
    return {
      ...super.done(),
      offsets: this.offsets.array(this.index + 2),
      values: this.values.array(this.pos + 1)
    };
  }
}
class BoolBuilder extends ValidityBuilder {
  constructor(type, ctx) {
    super(type, ctx);
  }
  init() {
    this.values = bitmap();
    return super.init();
  }
  set(value2, index) {
    super.set(value2, index);
    if (value2) this.values.set(index);
  }
  done() {
    return {
      ...super.done(),
      values: this.values.array((this.index >> 3) + 1)
    };
  }
}
class DecimalBuilder extends ValidityBuilder {
  constructor(type, ctx) {
    super(type, ctx);
    this.scale = 10 ** type.scale;
    this.stride = type.bitWidth >> 6;
  }
  init() {
    this.values = buffer$1(this.type.values);
    return super.init();
  }
  set(value2, index) {
    const { scale, stride, values: values2 } = this;
    if (super.set(value2, index)) {
      values2.prep((index + 1) * stride);
      toDecimal(value2, values2.buf, index * stride, stride, scale);
    }
  }
  done() {
    const { index, stride, values: values2 } = this;
    return {
      ...super.done(),
      values: values2.array((index + 1) * stride)
    };
  }
}
class FixedSizeBinaryBuilder extends ValidityBuilder {
  constructor(type, ctx) {
    super(type, ctx);
    this.stride = type.stride;
  }
  init() {
    this.values = buffer$1();
    return super.init();
  }
  set(value2, index) {
    if (super.set(value2, index)) {
      this.values.write(value2, index * this.stride);
    }
  }
  done() {
    const { stride, values: values2 } = this;
    return {
      ...super.done(),
      values: values2.array(stride * (this.index + 1))
    };
  }
}
class FixedSizeListBuilder extends ValidityBuilder {
  constructor(type, ctx) {
    super(type, ctx);
    this.child = ctx.builder(this.type.children[0].type);
    this.stride = type.stride;
  }
  init() {
    this.child.init();
    return super.init();
  }
  set(value2, index) {
    const { child, stride } = this;
    const base2 = index * stride;
    if (super.set(value2, index)) {
      for (let i2 = 0; i2 < stride; ++i2) {
        child.set(value2[i2], base2 + i2);
      }
    } else {
      child.index = base2 + stride;
    }
  }
  done() {
    const { child } = this;
    return {
      ...super.done(),
      children: [child.batch()]
    };
  }
}
class IntervalDayTimeBuilder extends ValidityBuilder {
  init() {
    this.values = buffer$1(this.type.values);
    return super.init();
  }
  set(value2, index) {
    if (super.set(value2, index)) {
      const i2 = index << 1;
      this.values.set(value2[0], i2);
      this.values.set(value2[1], i2 + 1);
    }
  }
  done() {
    return {
      ...super.done(),
      values: this.values.array(this.index + 1 << 1)
    };
  }
}
class IntervalMonthDayNanoBuilder extends ValidityBuilder {
  init() {
    this.values = buffer$1();
    return super.init();
  }
  set(value2, index) {
    if (super.set(value2, index)) {
      this.values.write(toMonthDayNanoBytes(value2), index << 4);
    }
  }
  done() {
    return {
      ...super.done(),
      values: this.values.array(this.index + 1 << 4)
    };
  }
}
class AbstractListBuilder extends ValidityBuilder {
  constructor(type, ctx, child) {
    super(type, ctx);
    this.child = child;
  }
  init() {
    this.child.init();
    const offsetType = this.type.offsets;
    this.offsets = buffer$1(offsetType);
    this.toOffset = toOffset(offsetType);
    this.pos = 0;
    return super.init();
  }
  done() {
    return {
      ...super.done(),
      offsets: this.offsets.array(this.index + 2),
      children: [this.child.batch()]
    };
  }
}
class ListBuilder extends AbstractListBuilder {
  constructor(type, ctx) {
    super(type, ctx, ctx.builder(type.children[0].type));
  }
  set(value2, index) {
    const { child, offsets, toOffset: toOffset2 } = this;
    if (super.set(value2, index)) {
      value2.forEach((v) => child.set(v, this.pos++));
    }
    offsets.set(toOffset2(this.pos), index + 1);
  }
}
class AbstractStructBuilder extends ValidityBuilder {
  constructor(type, ctx) {
    super(type, ctx);
    this.children = type.children.map((c2) => ctx.builder(c2.type));
  }
  init() {
    this.children.forEach((c2) => c2.init());
    return super.init();
  }
  done() {
    const { children: children2 } = this;
    children2.forEach((c2) => c2.index = this.index);
    return {
      ...super.done(),
      children: children2.map((c2) => c2.batch())
    };
  }
}
class StructBuilder extends AbstractStructBuilder {
  constructor(type, ctx) {
    super(type, ctx);
    this.setters = this.children.map((child, i2) => {
      const name2 = type.children[i2].name;
      return (value2, index) => child.set(value2?.[name2], index);
    });
  }
  set(value2, index) {
    super.set(value2, index);
    const setters = this.setters;
    for (let i2 = 0; i2 < setters.length; ++i2) {
      setters[i2](value2, index);
    }
  }
}
class MapBuilder extends AbstractListBuilder {
  constructor(type, ctx) {
    super(type, ctx, new MapStructBuilder(type.children[0].type, ctx));
  }
  set(value2, index) {
    const { child, offsets, toOffset: toOffset2 } = this;
    if (super.set(value2, index)) {
      for (const keyValuePair of value2) {
        child.set(keyValuePair, this.pos++);
      }
    }
    offsets.set(toOffset2(this.pos), index + 1);
  }
}
class MapStructBuilder extends AbstractStructBuilder {
  set(value2, index) {
    super.set(value2, index);
    const [key2, val] = this.children;
    key2.set(value2[0], index);
    val.set(value2[1], index);
  }
}
const NO_VALUE = {};
class RunEndEncodedBuilder extends BatchBuilder {
  constructor(type, ctx) {
    super(type, ctx);
    this.children = type.children.map((c2) => ctx.builder(c2.type));
  }
  init() {
    this.pos = 0;
    this.key = null;
    this.value = NO_VALUE;
    this.children.forEach((c2) => c2.init());
    return super.init();
  }
  next() {
    const [runs, vals] = this.children;
    runs.set(this.index + 1, this.pos);
    vals.set(this.value, this.pos++);
  }
  set(value2, index) {
    if (value2 !== this.value) {
      const key2 = keyString(value2);
      if (key2 !== this.key) {
        if (this.key) this.next();
        this.key = key2;
        this.value = value2;
      }
    }
    this.index = index;
  }
  done() {
    this.next();
    const { children: children2, index, type } = this;
    return {
      length: index + 1,
      nullCount: 0,
      type,
      children: children2.map((c2) => c2.batch())
    };
  }
}
class AbstractUnionBuilder extends BatchBuilder {
  constructor(type, ctx) {
    super(type, ctx);
    this.children = type.children.map((c2) => ctx.builder(c2.type));
    this.typeMap = type.typeMap;
    this.lookup = type.typeIdForValue;
  }
  init() {
    this.nullCount = 0;
    this.typeIds = buffer$1(int8Array);
    this.children.forEach((c2) => c2.init());
    return super.init();
  }
  set(value2, index) {
    const { children: children2, lookup: lookup2, typeMap, typeIds } = this;
    this.index = index;
    const typeId = lookup2(value2, index);
    const child = children2[typeMap[typeId]];
    typeIds.set(typeId, index);
    if (value2 == null) ++this.nullCount;
    this.update(value2, index, child);
  }
  done() {
    const { children: children2, nullCount, type, typeIds } = this;
    const length2 = this.index + 1;
    return {
      length: length2,
      nullCount,
      type,
      typeIds: typeIds.array(length2),
      children: children2.map((c2) => c2.batch())
    };
  }
}
class SparseUnionBuilder extends AbstractUnionBuilder {
  update(value2, index, child) {
    child.set(value2, index);
    this.children.forEach((c2) => {
      if (c2 !== child) c2.set(null, index);
    });
  }
}
class DenseUnionBuilder extends AbstractUnionBuilder {
  init() {
    this.offsets = buffer$1(this.type.offsets);
    return super.init();
  }
  update(value2, index, child) {
    const offset3 = child.index + 1;
    child.set(value2, offset3);
    this.offsets.set(offset3, index);
  }
  done() {
    return {
      ...super.done(),
      offsets: this.offsets.array(this.index + 1)
    };
  }
}
class Utf8Builder extends BinaryBuilder {
  set(value2, index) {
    super.set(value2 && encodeUtf8(value2), index);
  }
}
class DirectBuilder extends ValidityBuilder {
  constructor(type, ctx) {
    super(type, ctx);
    this.values = buffer$1(type.values);
  }
  init() {
    this.values = buffer$1(this.type.values);
    return super.init();
  }
  /**
   * @param {*} value
   * @param {number} index
   * @returns {boolean | void}
   */
  set(value2, index) {
    if (super.set(value2, index)) {
      this.values.set(value2, index);
    }
  }
  done() {
    return {
      ...super.done(),
      values: this.values.array(this.index + 1)
    };
  }
}
class Int64Builder extends DirectBuilder {
  set(value2, index) {
    super.set(value2 == null ? value2 : toBigInt(value2), index);
  }
}
class TransformBuilder extends DirectBuilder {
  constructor(type, ctx, transform) {
    super(type, ctx);
    this.transform = transform;
  }
  set(value2, index) {
    super.set(value2 == null ? value2 : this.transform(value2), index);
  }
}
function builderContext(options = {}, dictionaries = dictionaryContext()) {
  return {
    batchType: (type) => batchType(type, options),
    builder(type) {
      return builder(type, this);
    },
    dictionary(type) {
      return dictionaries.get(type, this);
    },
    finish: () => dictionaries.finish(options)
  };
}
function builder(type, ctx = builderContext()) {
  const { typeId } = type;
  switch (typeId) {
    case Type.Int:
    case Type.Time:
    case Type.Duration:
      return isInt64ArrayType(type.values) ? new Int64Builder(type, ctx) : new DirectBuilder(type, ctx);
    case Type.Float:
      return type.precision ? new DirectBuilder(type, ctx) : new TransformBuilder(type, ctx, toFloat16);
    case Type.Binary:
    case Type.LargeBinary:
      return new BinaryBuilder(type, ctx);
    case Type.Utf8:
    case Type.LargeUtf8:
      return new Utf8Builder(type, ctx);
    case Type.Bool:
      return new BoolBuilder(type, ctx);
    case Type.Decimal:
      return type.bitWidth === 32 ? new TransformBuilder(type, ctx, toDecimal32(type.scale)) : new DecimalBuilder(type, ctx);
    case Type.Date:
      return new TransformBuilder(type, ctx, type.unit ? toBigInt : toDateDay);
    case Type.Timestamp:
      return new TransformBuilder(type, ctx, toTimestamp(type.unit));
    case Type.Interval:
      switch (type.unit) {
        case IntervalUnit.DAY_TIME:
          return new IntervalDayTimeBuilder(type, ctx);
        case IntervalUnit.MONTH_DAY_NANO:
          return new IntervalMonthDayNanoBuilder(type, ctx);
      }
      return new DirectBuilder(type, ctx);
    case Type.List:
    case Type.LargeList:
      return new ListBuilder(type, ctx);
    case Type.Struct:
      return new StructBuilder(type, ctx);
    case Type.Union:
      return type.mode ? new DenseUnionBuilder(type, ctx) : new SparseUnionBuilder(type, ctx);
    case Type.FixedSizeBinary:
      return new FixedSizeBinaryBuilder(type, ctx);
    case Type.FixedSizeList:
      return new FixedSizeListBuilder(type, ctx);
    case Type.Map:
      return new MapBuilder(type, ctx);
    case Type.RunEndEncoded:
      return new RunEndEncodedBuilder(type, ctx);
    case Type.Dictionary:
      return new DictionaryBuilder(type, ctx);
  }
  throw new Error(invalidDataType(typeId));
}
function columnFromValues(values2, type, options = {}, dicts) {
  const visit2 = isIterable(values2) ? (callback) => {
    for (const value2 of values2) callback(value2);
  } : values2;
  type ??= inferType$1(visit2);
  const { maxBatchRows = Infinity, ...opt2 } = options;
  let data2;
  if (type.typeId === Type.Null) {
    let length2 = 0;
    visit2(() => ++length2);
    data2 = nullBatches(type, length2, maxBatchRows);
  } else {
    const ctx = builderContext(opt2, dicts);
    const b = builder(type, ctx).init();
    const next = (b2) => data2.push(b2.batch());
    data2 = [];
    let row2 = 0;
    visit2((value2) => {
      b.set(value2, row2++);
      if (row2 >= maxBatchRows) {
        next(b);
        row2 = 0;
      }
    });
    if (row2) next(b);
    ctx.finish();
  }
  return new Column(data2, type);
}
function nullBatches(type, length2, limit) {
  const data2 = [];
  const batch2 = (length3) => new NullBatch({ length: length3, nullCount: length3, type });
  const numBatches = Math.floor(length2 / limit);
  for (let i2 = 0; i2 < numBatches; ++i2) {
    data2.push(batch2(limit));
  }
  const rem = length2 % limit;
  if (rem) data2.push(batch2(rem));
  return data2;
}
function columnFromArray(array2, type, options = {}, dicts) {
  return !type && isTypedArray(array2) ? columnFromTypedArray(array2, options) : columnFromValues((v) => array2.forEach(v), type, options, dicts);
}
function columnFromTypedArray(values2, { maxBatchRows, useBigInt }) {
  const arrayType2 = (
    /** @type {TypedArrayConstructor} */
    values2.constructor
  );
  const type = typeForTypedArray(arrayType2);
  const length2 = values2.length;
  const limit = Math.min(maxBatchRows || Infinity, length2);
  const numBatches = Math.floor(length2 / limit);
  const batches = [];
  const batchType2 = isInt64ArrayType(arrayType2) && !useBigInt ? Int64Batch : DirectBatch;
  const add2 = (start2, end2) => batches.push(new batchType2({
    length: end2 - start2,
    nullCount: 0,
    type,
    validity: new uint8Array(0),
    values: values2.subarray(start2, end2)
  }));
  let idx = 0;
  for (let i2 = 0; i2 < numBatches; ++i2) add2(idx, idx += limit);
  if (idx < length2) add2(idx, length2);
  return new Column(batches);
}
function typeForTypedArray(arrayType2) {
  switch (arrayType2) {
    case float32Array:
      return float32();
    case float64Array:
      return float64();
    case int8Array:
      return int8();
    case int16Array:
      return int16();
    case int32Array:
      return int32();
    case int64Array:
      return int64();
    case uint8Array:
      return uint8();
    case uint16Array:
      return uint16();
    case uint32Array:
      return uint32();
    case uint64Array:
      return uint64();
  }
}
function tableFromColumns(data2, useProxy) {
  const fields = [];
  const entries2 = Array.isArray(data2) ? data2 : Object.entries(data2);
  const length2 = entries2[0]?.[1].length;
  const columns2 = entries2.map(([name2, col]) => {
    if (col.length !== length2) {
      throw new Error("All columns must have the same length.");
    }
    fields.push(field(name2, col.type));
    return col;
  });
  const schema = {
    version: Version.V5,
    endianness: Endianness.Little,
    fields,
    metadata: null
  };
  return new Table3(schema, columns2, useProxy);
}
function columns(table2, names) {
  return isFunction$1(names) ? names(table2) : names || table2.columnNames();
}
function toArrow(table2, options = {}) {
  const { columns: columns$1, limit = Infinity, offset: offset3 = 0, types: types2 = {}, ...opt2 } = options;
  const names = columns(table2, columns$1);
  const data2 = table2.data();
  const fullScan = offset3 === 0 && table2.numRows() <= limit && !table2.isFiltered() && !table2.isOrdered();
  return tableFromColumns(names.map((name2) => {
    const values2 = data2[name2];
    const type = types2[name2];
    const isArray2 = isArrayType(values2);
    let col;
    if (fullScan && (isArray2 || isFunction$1(values2.toArray))) {
      col = columnFromArray(isArray2 ? values2 : values2.toArray(), type, opt2);
    } else {
      const get2 = isArray2 ? (row2) => values2[row2] : (row2) => values2.at(row2);
      col = columnFromValues(
        (visit2) => table2.scan((row2) => visit2(get2(row2)), true, limit, offset3),
        type,
        opt2
      );
    }
    return [name2, col];
  }));
}
function toArrowIPC(data2, options = {}) {
  const { format: format2 = "stream", ...toArrowOptions } = options;
  return tableToIPC(toArrow(data2, toArrowOptions), { format: format2 });
}
function identity(x) {
  return x;
}
function scan(table2, names, limit = 100, offset3, ctx) {
  const { start: start2 = identity, cell: cell2, end: end2 = identity } = ctx;
  const data2 = table2.data();
  const n2 = names.length;
  table2.scan((row2) => {
    start2(row2);
    for (let i2 = 0; i2 < n2; ++i2) {
      const name2 = names[i2];
      cell2(data2[name2].at(row2), name2, i2);
    }
    end2(row2);
  }, true, limit, offset3);
}
function toCSV(table2, options = {}) {
  const names = columns(table2, options.columns);
  const format2 = options.format || {};
  const delim = options.delimiter || ",";
  const header2 = options.header ?? true;
  const reFormat = new RegExp(`["${delim}
\r]`);
  const formatValue2 = (value2) => value2 == null ? "" : isDate$1(value2) ? formatUTCDate(value2, true) : reFormat.test(value2 += "") ? '"' + value2.replace(/"/g, '""') + '"' : value2;
  const vals = names.map(formatValue2);
  let text2 = header2 ? vals.join(delim) + "\n" : "";
  scan(table2, names, options.limit || Infinity, options.offset, {
    cell(value2, name2, index) {
      vals[index] = formatValue2(format2[name2] ? format2[name2](value2) : value2);
    },
    end() {
      text2 += vals.join(delim) + "\n";
    }
  });
  return text2;
}
function mapObject(obj, fn3, output2 = {}) {
  for (const key2 in obj) {
    output2[key2] = fn3(obj[key2], key2);
  }
  return output2;
}
function isExactDateUTC(d) {
  return d.getUTCHours() === 0 && d.getUTCMinutes() === 0 && d.getUTCSeconds() === 0 && d.getUTCMilliseconds() === 0;
}
function inferFormat(scan2, options = {}) {
  let count2 = 0;
  let nulls = 0;
  let dates = 0;
  let dutcs = 0;
  let nums = 0;
  let digits = 0;
  scan2((value2) => {
    ++count2;
    if (value2 == null) {
      ++nulls;
      return;
    }
    const type = typeof value2;
    if (type === "object" && isDate$1(value2)) {
      ++dates;
      if (isExactDateUTC(value2)) ++dutcs;
    } else if (type === "number") {
      ++nums;
      if (value2 === value2 && (value2 | 0) !== value2) {
        const s = value2 + "";
        const p = s.indexOf(".");
        if (p >= 0) {
          const e = s.indexOf("e");
          const l2 = e > 0 ? e : s.length;
          digits = Math.max(digits, l2 - p - 1);
        }
      }
    }
  });
  return {
    align: (nulls + nums + dates) / count2 > 0.5 ? "r" : "l",
    format: {
      utc: dates === dutcs,
      digits: Math.min(digits, options.maxdigits || 6)
    }
  };
}
function formats(table2, names, options) {
  const formatOpt = options.format || {};
  const alignOpt = options.align || {};
  const format2 = {};
  const align2 = {};
  names.forEach((name2) => {
    const auto2 = inferFormat(values$1(table2, name2), options);
    align2[name2] = alignOpt[name2] || auto2.align;
    format2[name2] = formatOpt[name2] || auto2.format;
  });
  return { align: align2, format: format2 };
}
function values$1(table2, columnName) {
  const column2 = table2.column(columnName);
  return (fn3) => table2.scan((row2) => fn3(column2.at(row2)));
}
function formatValue(v, options = {}) {
  if (isFunction$1(options)) {
    return options(v) + "";
  }
  const type = typeof v;
  if (type === "object") {
    if (isDate$1(v)) {
      return options.utc ? formatUTCDate(v) : formatDate(v);
    } else {
      const s = JSON.stringify(
        v,
        // @ts-ignore
        (k, v2) => isTypedArray$1(v2) ? Array.from(v2) : v2
      );
      const maxlen = options.maxlen || 30;
      return s.length > maxlen ? s.slice(0, 28) + "…" + (s[0] === "[" ? "]" : "}") : s;
    }
  } else if (type === "number") {
    const digits = options.digits || 0;
    let a2;
    return v !== 0 && ((a2 = Math.abs(v)) >= 1e18 || a2 < Math.pow(10, -digits)) ? v.toExponential(digits) : v.toFixed(digits);
  } else {
    return v + "";
  }
}
function toHTML(table2, options = {}) {
  const names = columns(table2, options.columns);
  const { align: align2, format: format2 } = formats(table2, names, options);
  const style2 = styles$1l(options);
  const nullish = options.null;
  const alignValue = (a2) => a2 === "c" ? "center" : a2 === "r" ? "right" : "left";
  const escape2 = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
  const baseFormat = (value2, opt2) => escape2(formatValue(value2, opt2));
  const formatter = nullish ? (value2, opt2) => value2 == null ? nullish(value2) : baseFormat(value2, opt2) : baseFormat;
  let r2 = -1;
  let idx = -1;
  const tag = (tag2, name2, shouldAlign) => {
    const a2 = shouldAlign ? alignValue(align2[name2]) : "";
    const s = style2[tag2] ? style2[tag2](name2, idx, r2) || "" : "";
    const css = (a2 ? `text-align: ${a2};` + (s ? " " : "") : "") + s;
    return `<${tag2}${css ? ` style="${css}"` : ""}>`;
  };
  let text2 = tag("table") + tag("thead") + tag("tr", r2) + names.map((name2) => `${tag("th", name2, 1)}${name2}</th>`).join("") + "</tr></thead>" + tag("tbody");
  scan(table2, names, options.limit, options.offset, {
    start(row2) {
      r2 = row2;
      ++idx;
      text2 += tag("tr");
    },
    cell(value2, name2) {
      text2 += tag("td", name2, 1) + formatter(value2, format2[name2]) + "</td>";
    },
    end() {
      text2 += "</tr>";
    }
  });
  return text2 + "</tbody></table>";
}
function styles$1l(options) {
  return mapObject(
    options.style,
    (value2) => isFunction$1(value2) ? value2 : () => value2
  );
}
const COLUMNS = "columns";
const NDJSON = "ndjson";
const defaultFormatter$1 = (value2) => isDate$1(value2) ? formatUTCDate(value2, true) : value2;
function toJSON(table2, {
  type,
  columns: cols,
  format: format2 = {},
  limit,
  offset: offset3
} = {}) {
  const names = columns(table2, cols);
  const fmt = names.map((name2) => format2[name2] || defaultFormatter$1);
  const scan2 = (fn3) => table2.scan(fn3, true, limit, offset3);
  return type === COLUMNS ? toColumns(table2, names, fmt, scan2) : toRows(table2, names, fmt, scan2, type === NDJSON);
}
function toColumns(table2, names, format2, scan2) {
  let text2 = "{";
  names.forEach((name2, i2) => {
    text2 += (i2 ? "," : "") + JSON.stringify(name2) + ":[";
    const column2 = table2.column(name2);
    const formatter = format2[i2];
    let r2 = -1;
    scan2((row2) => {
      const value2 = column2.at(row2);
      text2 += (++r2 ? "," : "") + JSON.stringify(formatter(value2));
    });
    text2 += "]";
  });
  return text2 + "}";
}
function toRows(table2, names, format2, scan2, nd = false) {
  const n2 = names.length;
  const keys2 = names.map((name2) => `"${name2}":`);
  const cols = names.map((name2) => table2.column(name2));
  const finish = nd ? (o) => o.replaceAll("\n", "") : identity;
  const sep = nd ? "\n" : ",";
  let text2 = nd ? "" : "[";
  let r2 = -1;
  scan2((row2) => {
    const props = [];
    for (let i2 = 0; i2 < n2; ++i2) {
      props.push(keys2[i2] + JSON.stringify(format2[i2](cols[i2].at(row2))));
    }
    text2 += (++r2 ? sep : "") + finish(`{${props.join(",")}}`);
  });
  return text2 + (nd ? "" : "]");
}
function toMarkdown(table2, options = {}) {
  const names = columns(table2, options.columns);
  const { align: align2, format: format2 } = formats(table2, names, options);
  const alignValue = (a2) => a2 === "c" ? ":-:" : a2 === "r" ? "-:" : ":-";
  const escape2 = (s) => s.replace(/\|/g, "\\|");
  let text2 = "|" + names.map(escape2).join("|") + "|\n|" + names.map((name2) => alignValue(align2[name2])).join("|") + "|\n";
  scan(table2, names, options.limit, options.offset, {
    start() {
      text2 += "|";
    },
    cell(value2, name2) {
      text2 += escape2(formatValue(value2, format2[name2])) + "|";
    },
    end() {
      text2 += "\n";
    }
  });
  return text2;
}
class ColumnTable extends Table$1 {
  /**
   * Create a new table with additional columns drawn from one or more input
   * tables. All tables must have the same numer of rows and are reified
   * prior to assignment. In the case of repeated column names, input table
   * columns overwrite existing columns.
   * @param {...(Table|import('./types.js').ColumnData)} tables
   *  The tables to merge with this table.
   * @return {this} A new table with merged columns.
   * @example table.assign(table1, table2)
   */
  assign(...tables) {
    return assign$2(this, ...tables);
  }
  /**
   * Count the number of values in a group. This method is a shorthand
   * for *rollup* with a count aggregate function.
   * @param {import('./types.js').CountOptions} [options]
   *  Options for the count.
   * @return {this} A new table with groupby and count columns.
   * @example table.groupby('colA').count()
   * @example table.groupby('colA').count({ as: 'num' })
   */
  count(options = {}) {
    const { as = "count" } = options;
    return rollup(this, { [as]: count() });
  }
  /**
   * Derive new column values based on the provided expressions. By default,
   * new columns are added after (higher indices than) existing columns. Use
   * the before or after options to place new columns elsewhere.
   * @param {import('./types.js').ExprObject} values
   *  Object of name-value pairs defining the columns to derive. The input
   *  object should have output column names for keys and table expressions
   *  for values.
   * @param {import('./types.js').DeriveOptions} [options]
   *  Options for dropping or relocating derived columns. Use either a before
   *  or after property to indicate where to place derived columns. Specifying
   *  both before and after is an error. Unlike the *relocate* verb, this
   *  option affects only new columns; updated columns with existing names
   *  are excluded from relocation.
   * @return {this} A new table with derived columns added.
   * @example table.derive({ sumXY: d => d.x + d.y })
   * @example table.derive({ z: d => d.x * d.y }, { before: 'x' })
   */
  derive(values2, options) {
    return derive(this, values2, options);
  }
  /**
   * Filter a table to a subset of rows based on the input criteria.
   * The resulting table provides a filtered view over the original data; no
   * data copy is made. To create a table that copies only filtered data to
   * new data structures, call *reify* on the output table.
   * @param {import('./types.js').TableExpr} criteria
   *  Filter criteria as a table expression. Both aggregate and window
   *  functions are permitted, taking into account *groupby* or *orderby*
   *  settings.
   * @return {this} A new table with filtered rows.
   * @example table.filter(d => abs(d.value) < 5)
   */
  filter(criteria) {
    return filter(this, criteria);
  }
  /**
   * Extract rows with indices from start to end (end not included), where
   * start and end represent per-group ordered row numbers in the table.
   * @param {number} [start] Zero-based index at which to start extraction.
   *  A negative index indicates an offset from the end of the group.
   *  If start is undefined, slice starts from the index 0.
   * @param {number} [end] Zero-based index before which to end extraction.
   *  A negative index indicates an offset from the end of the group.
   *  If end is omitted, slice extracts through the end of the group.
   * @return {this} A new table with sliced rows.
   * @example table.slice(1, -1)
   */
  slice(start2, end2) {
    return slice(this, start2, end2);
  }
  /**
   * Group table rows based on a set of column values.
   * Subsequent operations that are sensitive to grouping (such as
   * aggregate functions) will operate over the grouped rows.
   * To undo grouping, use *ungroup*.
   * @param  {...import('./types.js').ExprList} keys
   *  Key column values to group by. The keys may be specified using column
   *  name strings, column index numbers, value objects with output column
   *  names for keys and table expressions for values, or selection helper
   *  functions.
   * @return {this} A new table with grouped rows.
   * @example table.groupby('colA', 'colB')
   * @example table.groupby({ key: d => d.colA + d.colB })
   */
  groupby(...keys2) {
    return groupby(this, ...keys2);
  }
  /**
   * Order table rows based on a set of column values. Subsequent operations
   * sensitive to ordering (such as window functions) will operate over sorted
   * values. The resulting table provides an view over the original data,
   * without any copying. To create a table with sorted data copied to new
   * data strucures, call *reify* on the result of this method. To undo
   * ordering, use *unorder*.
   * @param  {...import('./types.js').OrderKeys} keys
   *  Key values to sort by, in precedence order.
   *  By default, sorting is done in ascending order.
   *  To sort in descending order, wrap values using *desc*.
   *  If a string, order by the column with that name.
   *  If a number, order by the column with that index.
   *  If a function, must be a valid table expression; aggregate functions
   *  are permitted, but window functions are not.
   *  If an object, object values must be valid values parameters
   *  with output column names for keys and table expressions
   *  for values (the output names will be ignored).
   *  If an array, array values must be valid key parameters.
   * @return {this} A new ordered table.
   * @example table.orderby('a', desc('b'))
   * @example table.orderby({ a: 'a', b: desc('b') )})
   * @example table.orderby(desc(d => d.a))
   */
  orderby(...keys2) {
    return orderby(this, ...keys2);
  }
  /**
   * Relocate a subset of columns to change their positions, also
   * potentially renaming them.
   * @param {import('./types.js').Select} columns
   *  An ordered selection of columns to relocate.
   *  The input may consist of column name strings, column integer indices,
   *  rename objects with current column names as keys and new column names
   *  as values, or functions that take a table as input and returns a valid
   *  selection parameter (typically the output of selection helper functions
   *  such as *all*, *not*, or *range*).
   * @param {import('./types.js').RelocateOptions} options
   *  Options for relocating. Must include either the before or after property
   *  to indicate where to place the relocated columns. Specifying both before
   *  and after is an error.
   * @return {this} A new table with relocated columns.
   * @example table.relocate(['colY', 'colZ'], { after: 'colX' })
   * @example table.relocate(not('colB', 'colC'), { before: 'colA' })
   * @example table.relocate({ colA: 'newA', colB: 'newB' }, { after: 'colC' })
   */
  relocate(columns2, options) {
    return relocate(this, toArray$1(columns2), options);
  }
  /**
   * Rename one or more columns, preserving column order.
   * @param {...import('./types.js').Select} columns
   *  One or more rename objects with current column names as keys and new
   *  column names as values.
   * @return {this} A new table with renamed columns.
   * @example table.rename({ oldName: 'newName' })
   * @example table.rename({ a: 'a2', b: 'b2' })
   */
  rename(...columns2) {
    return rename(this, ...columns2);
  }
  /**
   * Reduce a table, processing all rows to produce a new table.
   * To produce standard aggregate summaries, use the rollup verb.
   * This method allows the use of custom reducer implementations,
   * for example to produce multiple rows for an aggregate.
   * @param {import('../verbs/reduce/reducer.js').Reducer} reducer
   *  The reducer to apply.
   * @return {this} A new table of reducer outputs.
   */
  reduce(reducer) {
    return reduce(this, reducer);
  }
  /**
   * Rollup a table to produce an aggregate summary.
   * Often used in conjunction with *groupby*.
   * To produce counts only, *count* is a shortcut.
   * @param {import('./types.js').ExprObject} [values]
   *  Object of name-value pairs defining aggregate output columns. The input
   *  object should have output column names for keys and table expressions
   *  for values. The expressions must be valid aggregate expressions: window
   *  functions are not allowed and column references must be arguments to
   *  aggregate functions.
   * @return {this} A new table of aggregate summary values.
   * @example table.groupby('colA').rollup({ mean: d => mean(d.colB) })
   * @example table.groupby('colA').rollup({ mean: op.median('colB') })
   */
  rollup(values2) {
    return rollup(this, values2);
  }
  /**
   * Generate a table from a random sample of rows.
   * If the table is grouped, performs a stratified sample by
   * sampling from each group separately.
   * @param {number | import('./types.js').TableExpr} size
   *  The number of samples to draw per group.
   *  If number-valued, the same sample size is used for each group.
   *  If function-valued, the input should be an aggregate table
   *  expression compatible with *rollup*.
   * @param {import('./types.js').SampleOptions} [options]
   *  Options for sampling.
   * @return {this} A new table with sampled rows.
   * @example table.sample(50)
   * @example table.sample(100, { replace: true })
   * @example table.groupby('colA').sample(() => op.floor(0.5 * op.count()))
   */
  sample(size, options) {
    return sample$1(this, size, options);
  }
  /**
   * Select a subset of columns into a new table, potentially renaming them.
   * @param {...import('./types.js').Select} columns
   *  An ordered selection of columns.
   *  The input may consist of column name strings, column integer indices,
   *  rename objects with current column names as keys and new column names
   *  as values, or functions that take a table as input and returns a valid
   *  selection parameter (typically the output of selection helper functions
   *  such as *all*, *not*, or *range*.).
   * @return {this} A new table of selected columns.
   * @example table.select('colA', 'colB')
   * @example table.select(not('colB', 'colC'))
   * @example table.select({ colA: 'newA', colB: 'newB' })
   */
  select(...columns2) {
    return select(this, ...columns2);
  }
  /**
   * Ungroup a table, removing any grouping criteria.
   * Undoes the effects of *groupby*.
   * @return {this} A new ungrouped table, or this table if not grouped.
   * @example table.ungroup()
   */
  ungroup() {
    return ungroup(this);
  }
  /**
   * Unorder a table, removing any sorting criteria.
   * Undoes the effects of *orderby*.
   * @return {this} A new unordered table, or this table if not ordered.
   * @example table.unorder()
   */
  unorder() {
    return unorder(this);
  }
  // -- Cleaning Verbs ------------------------------------------------------
  /**
   * De-duplicate table rows by removing repeated row values.
   * @param {...import('./types.js').ExprList} keys
   *  Key columns to check for duplicates.
   *  Two rows are considered duplicates if they have matching values for
   *  all keys. If keys are unspecified, all columns are used.
   *  The keys may be specified using column name strings, column index
   *  numbers, value objects with output column names for keys and table
   *  expressions for values, or selection helper functions.
   * @return {this} A new de-duplicated table.
   * @example table.dedupe()
   * @example table.dedupe('a', 'b')
   * @example table.dedupe({ abs: d => op.abs(d.a) })
   */
  dedupe(...keys2) {
    return dedupe(this, ...keys2);
  }
  /**
   * Impute missing values or rows. Accepts a set of column-expression pairs
   * and evaluates the expressions to replace any missing (null, undefined,
   * or NaN) values in the original column.
   * If the expand option is specified, imputes new rows for missing
   * combinations of values. All combinations of key values (a full cross
   * product) are considered for each level of grouping (specified by
   * *groupby*). New rows will be added for any combination
   * of key and groupby values not already contained in the table. For all
   * non-key and non-group columns the new rows are populated with imputation
   * values (first argument) if specified, otherwise undefined.
   * If the expand option is specified, any filter or orderby settings are
   * removed from the output table, but groupby settings persist.
   * @param {import('./types.js').ExprObject} values
   *  Object of name-value pairs for the column values to impute. The input
   *  object should have existing column names for keys and table expressions
   *  for values. The expressions will be evaluated to determine replacements
   *  for any missing values.
   * @param {import('./types.js').ImputeOptions} [options] Imputation options.
   *  The expand property specifies a set of column values to consider for
   *  imputing missing rows. All combinations of expanded values are
   *  considered, and new rows are added for each combination that does not
   *  appear in the input table.
   * @return {this} A new table with imputed values and/or rows.
   * @example table.impute({ v: () => 0 })
   * @example table.impute({ v: d => op.mean(d.v) })
   * @example table.impute({ v: () => 0 }, { expand: ['x', 'y'] })
   */
  impute(values2, options) {
    return impute(this, values2, options);
  }
  // -- Reshaping Verbs -----------------------------------------------------
  /**
   * Fold one or more columns into two key-value pair columns.
   * The fold transform is an inverse of the *pivot* transform.
   * The resulting table has two new columns, one containing the column
   * names (named "key") and the other the column values (named "value").
   * The number of output rows equals the original row count multiplied
   * by the number of folded columns.
   * @param {import('./types.js').ExprList} values The columns to fold.
   *  The columns may be specified using column name strings, column index
   *  numbers, value objects with output column names for keys and table
   *  expressions for values, or selection helper functions.
   * @param {import('./types.js').FoldOptions} [options] Options for folding.
   * @return {this} A new folded table.
   * @example table.fold('colA')
   * @example table.fold(['colA', 'colB'])
   * @example table.fold(range(5, 8))
   */
  fold(values2, options) {
    return fold(this, values2, options);
  }
  /**
   * Pivot columns into a cross-tabulation.
   * The pivot transform is an inverse of the *fold* transform.
   * The resulting table has new columns for each unique combination
   * of the provided *keys*, populated with the provided *values*.
   * The provided *values* must be aggregates, as a single set of keys may
   * include more than one row. If string-valued, the *any* aggregate is used.
   * If only one *values* column is defined, the new pivoted columns will
   * be named using key values directly. Otherwise, input value column names
   * will be included as a component of the output column names.
   * @param {import('./types.js').ExprList} keys
   *  Key values to map to new column names. The keys may be specified using
   *  column name strings, column index numbers, value objects with output
   *  column names for keys and table expressions for values, or selection
   *  helper functions.
   * @param {import('./types.js').ExprList} values Output values for pivoted
   *  columns. Column references will be wrapped in an *any* aggregate. If
   *  object-valued, the input object should have output value names for keys
   *  and aggregate table expressions for values.
   * @param {import('./types.js').PivotOptions} [options]
   *  Options for pivoting.
   * @return {this} A new pivoted table.
   * @example table.pivot('key', 'value')
   * @example table.pivot(['keyA', 'keyB'], ['valueA', 'valueB'])
   * @example table.pivot({ key: d => d.key }, { value: d => op.sum(d.value) })
   */
  pivot(keys2, values2, options) {
    return pivot(this, keys2, values2, options);
  }
  /**
   * Spread array elements into a set of new columns.
   * Output columns are named based on the value key and array index.
   * @param {import('./types.js').ExprList} values
   *  The column values to spread. The values may be specified using column
   *  name strings, column index numbers, value objects with output column
   *  names for keys and table expressions for values, or selection helper
   *  functions.
   * @param {import('./types.js').SpreadOptions } [options]
   *  Options for spreading.
   * @return {this} A new table with the spread columns added.
   * @example table.spread({ a: d => op.split(d.text, '') })
   * @example table.spread('arrayCol', { limit: 100 })
   */
  spread(values2, options) {
    return spread(this, values2, options);
  }
  /**
   * Unroll one or more array-valued columns into new rows.
   * If more than one array value is used, the number of new rows
   * is the smaller of the limit and the largest length.
   * Values for all other columns are copied over.
   * @param {import('./types.js').ExprList} values
   *  The column values to unroll. The values may be specified using column
   *  name strings, column index numbers, value objects with output column
   *  names for keys and table expressions for values, or selection helper
   *  functions.
   * @param {import('./types.js').UnrollOptions} [options]
   *  Options for unrolling.
   * @return {this} A new unrolled table.
   * @example table.unroll('colA', { limit: 1000 })
   */
  unroll(values2, options) {
    return unroll(this, values2, options);
  }
  // -- Joins ---------------------------------------------------------------
  /**
   * Lookup values from a secondary table and add them as new columns.
   * A lookup occurs upon matching key values for rows in both tables.
   * If the secondary table has multiple rows with the same key, only
   * the last observed instance will be considered in the lookup.
   * Lookup is similar to *join_left*, but with a simpler
   * syntax and the added constraint of allowing at most one match only.
   * @param {import('./types.js').TableRef} other
   *  The secondary table to look up values from.
   * @param {import('./types.js').JoinKeys} [on]
   *  Lookup keys (column name strings or table expressions) for this table
   *  and the secondary table, respectively. If unspecified, the values of
   *  all columns with matching names are compared.
   * @param {...import('./types.js').ExprList} [values]
   *  The column values to add from the secondary table. Can be column name
   *  strings or objects with column names as keys and table expressions as
   *  values. If unspecified, includes all columns from the secondary table
   *  whose names do no match any column in the primary table.
   * @return {this} A new table with lookup values added.
   * @example table.lookup(other, ['key1', 'key2'], 'value1', 'value2')
   */
  lookup(other, on, ...values2) {
    return lookup(this, other, on, ...values2);
  }
  /**
   * Join two tables, extending the columns of one table with
   * values from the other table. The current table is considered
   * the "left" table in the join, and the new table input is
   * considered the "right" table in the join. By default an inner
   * join is performed, removing all rows that do not match the
   * join criteria. To perform left, right, or full outer joins, use
   * the *join_left*, *join_right*, or *join_full* methods, or provide
   * an options argument.
   * @param {import('./types.js').TableRef} other
   *  The other (right) table to join with.
   * @param {import('./types.js').JoinPredicate} [on]
   *  The join criteria for matching table rows. If unspecified, the values of
   *  all columns with matching names are compared.
   *  If array-valued, a two-element array should be provided, containing
   *  the columns to compare for the left and right tables, respectively.
   *  If a one-element array or a string value is provided, the same
   *  column names will be drawn from both tables.
   *  If function-valued, should be a two-table table expression that
   *  returns a boolean value. When providing a custom predicate, note that
   *  join key values can be arrays or objects, and that normal join
   *  semantics do not consider null or undefined values to be equal (that is,
   *  null !== null). Use the op.equal function to handle these cases.
   * @param {import('./types.js').JoinValues} [values]
   *  The columns to include in the join output.
   *  If unspecified, all columns from both tables are included; paired
   *  join keys sharing the same column name are included only once.
   *  If array-valued, a two element array should be provided, containing
   *  the columns to include for the left and right tables, respectively.
   *  Array input may consist of column name strings, objects with output
   *  names as keys and single-table table expressions as values, or the
   *  selection helper functions *all*, *not*, or *range*.
   *  If object-valued, specifies the key-value pairs for each output,
   *  defined using two-table table expressions.
   * @param {import('./types.js').JoinOptions} [options]
   *  Options for the join.
   * @return {this} A new joined table.
   * @example table.join(other, ['keyL', 'keyR'])
   * @example table.join(other, (a, b) => op.equal(a.keyL, b.keyR))
   */
  join(other, on, values2, options) {
    return join$1(this, other, on, values2, options);
  }
  /**
   * Perform a left outer join on two tables. Rows in the left table
   * that do not match a row in the right table will be preserved.
   * This is a convenience method with fixed options for *join*.
   * @param {import('./types.js').TableRef} other
   *  The other (right) table to join with.
   * @param {import('./types.js').JoinPredicate} [on]
   *  The join criteria for matching table rows.
   *  If unspecified, the values of all columns with matching names
   *  are compared.
   *  If array-valued, a two-element array should be provided, containing
   *  the columns to compare for the left and right tables, respectively.
   *  If a one-element array or a string value is provided, the same
   *  column names will be drawn from both tables.
   *  If function-valued, should be a two-table table expression that
   *  returns a boolean value. When providing a custom predicate, note that
   *  join key values can be arrays or objects, and that normal join
   *  semantics do not consider null or undefined values to be equal (that is,
   *  null !== null). Use the op.equal function to handle these cases.
   * @param {import('./types.js').JoinValues} [values]
   *  he columns to include in the join output.
   *  If unspecified, all columns from both tables are included; paired
   *  join keys sharing the same column name are included only once.
   *  If array-valued, a two element array should be provided, containing
   *  the columns to include for the left and right tables, respectively.
   *  Array input may consist of column name strings, objects with output
   *  names as keys and single-table table expressions as values, or the
   *  selection helper functions *all*, *not*, or *range*.
   *  If object-valued, specifies the key-value pairs for each output,
   *  defined using two-table table expressions.
   * @param {import('./types.js').JoinOptions} [options]
   *  Options for the join. With this method, any options will be
   *  overridden with `{left: true, right: false}`.
   * @return {this} A new joined table.
   * @example table.join_left(other, ['keyL', 'keyR'])
   * @example table.join_left(other, (a, b) => op.equal(a.keyL, b.keyR))
   */
  join_left(other, on, values2, options) {
    const opt2 = { ...options, left: true, right: false };
    return join$1(this, other, on, values2, opt2);
  }
  /**
   * Perform a right outer join on two tables. Rows in the right table
   * that do not match a row in the left table will be preserved.
   * This is a convenience method with fixed options for *join*.
   * @param {import('./types.js').TableRef} other
   *  The other (right) table to join with.
   * @param {import('./types.js').JoinPredicate} [on]
   *  The join criteria for matching table rows.
   *  If unspecified, the values of all columns with matching names
   *  are compared.
   *  If array-valued, a two-element array should be provided, containing
   *  the columns to compare for the left and right tables, respectively.
   *  If a one-element array or a string value is provided, the same
   *  column names will be drawn from both tables.
   *  If function-valued, should be a two-table table expression that
   *  returns a boolean value. When providing a custom predicate, note that
   *  join key values can be arrays or objects, and that normal join
   *  semantics do not consider null or undefined values to be equal (that is,
   *  null !== null). Use the op.equal function to handle these cases.
   * @param {import('./types.js').JoinValues} [values]
   *  The columns to include in the join output.
   *  If unspecified, all columns from both tables are included; paired
   *  join keys sharing the same column name are included only once.
   *  If array-valued, a two element array should be provided, containing
   *  the columns to include for the left and right tables, respectively.
   *  Array input may consist of column name strings, objects with output
   *  names as keys and single-table table expressions as values, or the
   *  selection helper functions *all*, *not*, or *range*.
   *  If object-valued, specifies the key-value pairs for each output,
   *  defined using two-table table expressions.
   * @param {import('./types.js').JoinOptions} [options]
   *  Options for the join. With this method, any options will be overridden
   *  with `{left: false, right: true}`.
   * @return {this} A new joined table.
   * @example table.join_right(other, ['keyL', 'keyR'])
   * @example table.join_right(other, (a, b) => op.equal(a.keyL, b.keyR))
   */
  join_right(other, on, values2, options) {
    const opt2 = { ...options, left: false, right: true };
    return join$1(this, other, on, values2, opt2);
  }
  /**
   * Perform a full outer join on two tables. Rows in either the left or
   * right table that do not match a row in the other will be preserved.
   * This is a convenience method with fixed options for *join*.
   * @param {import('./types.js').TableRef} other
   *  The other (right) table to join with.
   * @param {import('./types.js').JoinPredicate} [on]
   *  The join criteria for matching table rows.
   *  If unspecified, the values of all columns with matching names
   *  are compared.
   *  If array-valued, a two-element array should be provided, containing
   *  the columns to compare for the left and right tables, respectively.
   *  If a one-element array or a string value is provided, the same
   *  column names will be drawn from both tables.
   *  If function-valued, should be a two-table table expression that
   *  returns a boolean value. When providing a custom predicate, note that
   *  join key values can be arrays or objects, and that normal join
   *  semantics do not consider null or undefined values to be equal (that is,
   *  null !== null). Use the op.equal function to handle these cases.
   * @param {import('./types.js').JoinValues} [values]
   *  The columns to include in the join output.
   *  If unspecified, all columns from both tables are included; paired
   *  join keys sharing the same column name are included only once.
   *  If array-valued, a two element array should be provided, containing
   *  the columns to include for the left and right tables, respectively.
   *  Array input may consist of column name strings, objects with output
   *  names as keys and single-table table expressions as values, or the
   *  selection helper functions *all*, *not*, or *range*.
   *  If object-valued, specifies the key-value pairs for each output,
   *  defined using two-table table expressions.
   * @param {import('./types.js').JoinOptions} [options]
   *  Options for the join. With this method, any options will be overridden
   *  with `{left: true, right: true}`.
   * @return {this} A new joined table.
   * @example table.join_full(other, ['keyL', 'keyR'])
   * @example table.join_full(other, (a, b) => op.equal(a.keyL, b.keyR))
   */
  join_full(other, on, values2, options) {
    const opt2 = { ...options, left: true, right: true };
    return join$1(this, other, on, values2, opt2);
  }
  /**
   * Produce the Cartesian cross product of two tables. The output table
   * has one row for every pair of input table rows. Beware that outputs
   * may be quite large, as the number of output rows is the product of
   * the input row counts.
   * This is a convenience method for *join* in which the
   * join criteria is always true.
   * @param {import('./types.js').TableRef} other
   *  The other (right) table to join with.
   * @param {import('./types.js').JoinValues} [values]
   *  The columns to include in the output.
   *  If unspecified, all columns from both tables are included.
   *  If array-valued, a two element array should be provided, containing
   *  the columns to include for the left and right tables, respectively.
   *  Array input may consist of column name strings, objects with output
   *  names as keys and single-table table expressions as values, or the
   *  selection helper functions *all*, *not*, or *range*.
   *  If object-valued, specifies the key-value pairs for each output,
   *  defined using two-table table expressions.
   * @param {import('./types.js').JoinOptions} [options]
   *  Options for the join.
   * @return {this} A new joined table.
   * @example table.cross(other)
   * @example table.cross(other, [['leftKey', 'leftVal'], ['rightVal']])
   */
  cross(other, values2, options) {
    return cross(this, other, values2, options);
  }
  /**
   * Perform a semi-join, filtering the left table to only rows that
   * match a row in the right table.
   * @param {import('./types.js').TableRef} other
   *  The other (right) table to join with.
   * @param {import('./types.js').JoinPredicate} [on]
   *  The join criteria for matching table rows.
   *  If unspecified, the values of all columns with matching names
   *  are compared.
   *  If array-valued, a two-element array should be provided, containing
   *  the columns to compare for the left and right tables, respectively.
   *  If a one-element array or a string value is provided, the same
   *  column names will be drawn from both tables.
   *  If function-valued, should be a two-table table expression that
   *  returns a boolean value. When providing a custom predicate, note that
   *  join key values can be arrays or objects, and that normal join
   *  semantics do not consider null or undefined values to be equal (that is,
   *  null !== null). Use the op.equal function to handle these cases.
   * @return {this} A new filtered table.
   * @example table.semijoin(other)
   * @example table.semijoin(other, ['keyL', 'keyR'])
   * @example table.semijoin(other, (a, b) => op.equal(a.keyL, b.keyR))
   */
  semijoin(other, on) {
    return semijoin(this, other, on);
  }
  /**
   * Perform an anti-join, filtering the left table to only rows that
   * do *not* match a row in the right table.
   * @param {import('./types.js').TableRef} other
   *  The other (right) table to join with.
   * @param {import('./types.js').JoinPredicate} [on]
   *  The join criteria for matching table rows.
   *  If unspecified, the values of all columns with matching names
   *  are compared.
   *  If array-valued, a two-element array should be provided, containing
   *  the columns to compare for the left and right tables, respectively.
   *  If a one-element array or a string value is provided, the same
   *  column names will be drawn from both tables.
   *  If function-valued, should be a two-table table expression that
   *  returns a boolean value. When providing a custom predicate, note that
   *  join key values can be arrays or objects, and that normal join
   *  semantics do not consider null or undefined values to be equal (that is,
   *  null !== null). Use the op.equal function to handle these cases.
   * @return {this} A new filtered table.
   * @example table.antijoin(other)
   * @example table.antijoin(other, ['keyL', 'keyR'])
   * @example table.antijoin(other, (a, b) => op.equal(a.keyL, b.keyR))
   */
  antijoin(other, on) {
    return antijoin(this, other, on);
  }
  // -- Set Operations ------------------------------------------------------
  /**
   * Concatenate multiple tables into a single table, preserving all rows.
   * This transformation mirrors the UNION_ALL operation in SQL.
   * Only named columns in this table are included in the output.
   * @param  {...import('./types.js').TableRefList} tables
   *  A list of tables to concatenate.
   * @return {this} A new concatenated table.
   * @example table.concat(other)
   * @example table.concat(other1, other2)
   * @example table.concat([other1, other2])
   */
  concat(...tables) {
    return concat(this, ...tables);
  }
  /**
   * Union multiple tables into a single table, deduplicating all rows.
   * This transformation mirrors the UNION operation in SQL. It is
   * similar to *concat* but suppresses duplicate rows with
   * values identical to another row.
   * Only named columns in this table are included in the output.
   * @param  {...import('./types.js').TableRefList} tables
   *  A list of tables to union.
   * @return {this} A new unioned table.
   * @example table.union(other)
   * @example table.union(other1, other2)
   * @example table.union([other1, other2])
   */
  union(...tables) {
    return union$1(this, ...tables);
  }
  /**
   * Intersect multiple tables, keeping only rows whose with identical
   * values for all columns in all tables, and deduplicates the rows.
   * This transformation is similar to a series of *semijoin*.
   * calls, but additionally suppresses duplicate rows.
   * @param  {...import('./types.js').TableRefList} tables
   *  A list of tables to intersect.
   * @return {this} A new filtered table.
   * @example table.intersect(other)
   * @example table.intersect(other1, other2)
   * @example table.intersect([other1, other2])
   */
  intersect(...tables) {
    return intersect(this, ...tables);
  }
  /**
   * Compute the set difference with multiple tables, keeping only rows in
   * this table that whose values do not occur in the other tables.
   * This transformation is similar to a series of *anitjoin*
   * calls, but additionally suppresses duplicate rows.
   * @param  {...import('./types.js').TableRefList} tables
   *  A list of tables to difference.
   * @return {this} A new filtered table.
   * @example table.except(other)
   * @example table.except(other1, other2)
   * @example table.except([other1, other2])
   */
  except(...tables) {
    return except(this, ...tables);
  }
  // -- Table Output Formats ------------------------------------------------
  /**
   * Format this table as a Flechette Arrow table.
   * @param {import('../format/types.js').ArrowFormatOptions} [options]
   *  The Arrow formatting options.
   * @return {import('@uwdata/flechette').Table} A Flechette Arrow table.
   */
  toArrow(options) {
    return toArrow(this, options);
  }
  /**
   * Format this table as binary data in the Apache Arrow IPC format.
   * @param {import('../format/types.js').ArrowIPCFormatOptions} [options]
   *  The Arrow IPC formatting options.
   * @return {Uint8Array} A new Uint8Array of Arrow-encoded binary data.
   */
  toArrowIPC(options) {
    return toArrowIPC(this, options);
  }
  /**
   * Format this table as a comma-separated values (CSV) string. Other
   * delimiters, such as tabs or pipes ('|'), can be specified using
   * the options argument.
   * @param {import('../format/to-csv.js').CSVFormatOptions} [options]
   *   The CSV formatting options.
   * @return {string} A delimited value string.
   */
  toCSV(options) {
    return toCSV(this, options);
  }
  /**
   * Format this table as an HTML table string.
   * @param {import('../format/to-html.js').HTMLFormatOptions} [options]
   *  The HTML formatting options.
   * @return {string} An HTML table string.
   */
  toHTML(options) {
    return toHTML(this, options);
  }
  /**
   * Format this table as a JavaScript Object Notation (JSON) string.
   * @param {import('../format/to-json.js').JSONFormatOptions} [options]
   *  The JSON formatting options.
   * @return {string} A JSON string.
   */
  toJSON(options) {
    return toJSON(this, options);
  }
  /**
   * Format this table as a GitHub-Flavored Markdown table string.
   * @param {import('../format/to-markdown.js').MarkdownFormatOptions} [options]
   *  The Markdown formatting options.
   * @return {string} A GitHub-Flavored Markdown table string.
   */
  toMarkdown(options) {
    return toMarkdown(this, options);
  }
}
function fromArrow(input2, options) {
  const { columns: columns2 = all$1(), ...rest } = {};
  const arrow2 = input2 instanceof ArrayBuffer || input2 instanceof Uint8Array ? tableFromIPC(input2, { useDate: true, ...rest }) : input2;
  const { fields } = arrow2.schema;
  const names = fields.map((f) => f.name);
  const sel = resolve({
    columnNames: (test2) => test2 ? names.filter(test2) : names.slice(),
    columnIndex: (name2) => names.indexOf(name2)
  }, columns2);
  const cols = columnSet();
  sel.forEach((name2, key2) => {
    const col = (
      /** @type {import('./types.js').ArrowColumn} */
      arrow2.getChild(key2)
    );
    cols.add(name2, col.type.typeId === -1 ? dictionary(col) : col);
  });
  return new ColumnTable(cols.data, cols.names);
}
function dictionary(column2) {
  const { data: data2, length: length2, nullCount } = column2;
  const batch2 = data2[data2.length - 1];
  const cache = batch2.cache ?? batch2.dictionary.toArray();
  const size = cache.length;
  const keys2 = dictKeys(data2, length2, nullCount, size);
  const get2 = nullCount ? ((k) => k === size ? null : cache[k]) : ((k) => cache[k]);
  return {
    length: length2,
    nullCount,
    at: (row2) => get2(keys2[row2]),
    key: (row2) => keys2[row2],
    keyFor(value2) {
      if (value2 === null) return nullCount ? size : -1;
      for (let i2 = 0; i2 < size; ++i2) {
        if (cache[i2] === value2) return i2;
      }
      return -1;
    },
    groups(names) {
      const s = size + (nullCount ? 1 : 0);
      return {
        keys: keys2,
        get: [get2],
        names,
        rows: sequence(0, s),
        size: s
      };
    },
    [Symbol.iterator]: () => column2[Symbol.iterator](),
    toArray: () => column2.toArray()
  };
}
function dictKeys(data2, length2, nulls, size) {
  const v = data2.length > 1 || nulls ? flatten(data2, length2) : data2[0].values;
  return nulls ? nullKeys(data2, v, size) : v;
}
function flatten(data2, length2) {
  const type = data2[0].values.constructor;
  const array2 = new type(length2);
  const n2 = data2.length;
  for (let i2 = 0, idx = 0, len; i2 < n2; ++i2) {
    len = data2[i2].length;
    array2.set(data2[i2].values.subarray(0, len), idx);
    idx += len;
  }
  return array2;
}
function nullKeys(data2, keys2, key2) {
  const n2 = data2.length;
  for (let i2 = 0, idx = 0, byte; i2 < n2; ++i2) {
    const batch2 = data2[i2];
    const { length: length2 } = batch2;
    const validity = batch2.validity ?? batch2.nullBitmap;
    const m = length2 >> 3;
    if (validity && validity.length) {
      for (let j2 = 0; j2 <= m; ++j2) {
        if ((byte = validity[j2]) !== 255) {
          const base2 = idx + (j2 << 3);
          if ((byte & 1 << 0) === 0) keys2[base2 + 0] = key2;
          if ((byte & 1 << 1) === 0) keys2[base2 + 1] = key2;
          if ((byte & 1 << 2) === 0) keys2[base2 + 2] = key2;
          if ((byte & 1 << 3) === 0) keys2[base2 + 3] = key2;
          if ((byte & 1 << 4) === 0) keys2[base2 + 4] = key2;
          if ((byte & 1 << 5) === 0) keys2[base2 + 5] = key2;
          if ((byte & 1 << 6) === 0) keys2[base2 + 6] = key2;
          if ((byte & 1 << 7) === 0) keys2[base2 + 7] = key2;
        }
      }
    }
    idx += length2;
  }
  return keys2;
}
function escape$1(value2) {
  return wrap$2(value2, {
    escape: true,
    toString() {
      error$4("Escaped values can not be serialized.");
    }
  });
}
function columnsFrom(values2, names) {
  const raise2 = (type) => {
    error$4(`Illegal argument type: ${type || typeof values2}`);
    return (
      /** @type {import('./types.js').ColumnData} */
      {}
    );
  };
  return values2 instanceof Map ? fromKeyValuePairs(values2.entries(), names) : isDate$1(values2) ? raise2("Date") : isRegExp$1(values2) ? raise2("RegExp") : isString$2(values2) ? raise2() : isArray$2(values2) ? fromArray(values2, names) : isFunction$1(values2[Symbol.iterator]) ? fromIterable(values2, names) : isObject$1(values2) ? fromKeyValuePairs(Object.entries(values2), names) : raise2();
}
function fromKeyValuePairs(entries2, names = ["key", "value"]) {
  const keys2 = [];
  const vals = [];
  for (const [key2, val] of entries2) {
    keys2.push(key2);
    vals.push(val);
  }
  const columns2 = {};
  if (names[0]) columns2[names[0]] = keys2;
  if (names[1]) columns2[names[1]] = vals;
  return columns2;
}
function fromArray(values2, names) {
  const len = values2.length;
  const columns2 = {};
  const add2 = (name2) => columns2[name2] = Array(len);
  if (len) {
    names = names || Object.keys(values2[0]);
    const cols = names.map(add2);
    const n2 = cols.length;
    for (let idx = 0; idx < len; ++idx) {
      const row2 = values2[idx];
      for (let i2 = 0; i2 < n2; ++i2) {
        cols[i2][idx] = row2[names[i2]];
      }
    }
  } else if (names) {
    names.forEach(add2);
  }
  return columns2;
}
function fromIterable(values2, names) {
  const columns2 = {};
  const add2 = (name2) => columns2[name2] = [];
  let cols;
  let n2;
  for (const row2 of values2) {
    if (!cols) {
      names = names || Object.keys(row2);
      cols = names.map(add2);
      n2 = cols.length;
    }
    for (let i2 = 0; i2 < n2; ++i2) {
      cols[i2].push(row2[names[i2]]);
    }
  }
  if (!cols && names) {
    names.forEach(add2);
  }
  return columns2;
}
function table$2(columns2, names) {
  if (columns2 instanceof ColumnTable) return columns2;
  const data2 = {};
  const keys2 = [];
  for (const [key2, value2] of entries(columns2)) {
    data2[key2] = value2;
    keys2.push(key2);
  }
  return new ColumnTable(data2, keys2);
}
function from(values2, names) {
  return new ColumnTable(columnsFrom(values2, names), names);
}
var lz4 = {};
var xxh32 = {};
var util = {};
var hasRequiredUtil;
function requireUtil() {
  if (hasRequiredUtil) return util;
  hasRequiredUtil = 1;
  util.hashU32 = function hashU32(a2) {
    a2 = a2 | 0;
    a2 = a2 + 2127912214 + (a2 << 12) | 0;
    a2 = a2 ^ -949894596 ^ a2 >>> 19;
    a2 = a2 + 374761393 + (a2 << 5) | 0;
    a2 = a2 + -744332180 ^ a2 << 9;
    a2 = a2 + -42973499 + (a2 << 3) | 0;
    return a2 ^ -1252372727 ^ a2 >>> 16 | 0;
  };
  util.readU64 = function readU64(b, n2) {
    var x = 0;
    x |= b[n2++] << 0;
    x |= b[n2++] << 8;
    x |= b[n2++] << 16;
    x |= b[n2++] << 24;
    x |= b[n2++] << 32;
    x |= b[n2++] << 40;
    x |= b[n2++] << 48;
    x |= b[n2++] << 56;
    return x;
  };
  util.readU32 = function readU32(b, n2) {
    var x = 0;
    x |= b[n2++] << 0;
    x |= b[n2++] << 8;
    x |= b[n2++] << 16;
    x |= b[n2++] << 24;
    return x;
  };
  util.writeU32 = function writeU32(b, n2, x) {
    b[n2++] = x >> 0 & 255;
    b[n2++] = x >> 8 & 255;
    b[n2++] = x >> 16 & 255;
    b[n2++] = x >> 24 & 255;
  };
  util.imul = function imul(a2, b) {
    var ah = a2 >>> 16;
    var al = a2 & 65535;
    var bh = b >>> 16;
    var bl = b & 65535;
    return al * bl + (ah * bl + al * bh << 16) | 0;
  };
  return util;
}
var hasRequiredXxh32;
function requireXxh32() {
  if (hasRequiredXxh32) return xxh32;
  hasRequiredXxh32 = 1;
  var util2 = requireUtil();
  var prime1 = 2654435761;
  var prime2 = 2246822519;
  var prime3 = 3266489917;
  var prime4 = 668265263;
  var prime5 = 374761393;
  function rotl32(x, r2) {
    x = x | 0;
    r2 = r2 | 0;
    return x >>> (32 - r2 | 0) | x << r2 | 0;
  }
  function rotmul32(h, r2, m) {
    h = h | 0;
    r2 = r2 | 0;
    m = m | 0;
    return util2.imul(h >>> (32 - r2 | 0) | h << r2, m) | 0;
  }
  function shiftxor32(h, s) {
    h = h | 0;
    s = s | 0;
    return h >>> s ^ h | 0;
  }
  function xxhapply(h, src, m0, s, m1) {
    return rotmul32(util2.imul(src, m0) + h, s, m1);
  }
  function xxh1(h, src, index) {
    return rotmul32(h + util2.imul(src[index], prime5), 11, prime1);
  }
  function xxh4(h, src, index) {
    return xxhapply(h, util2.readU32(src, index), prime3, 17, prime4);
  }
  function xxh16(h, src, index) {
    return [
      xxhapply(h[0], util2.readU32(src, index + 0), prime2, 13, prime1),
      xxhapply(h[1], util2.readU32(src, index + 4), prime2, 13, prime1),
      xxhapply(h[2], util2.readU32(src, index + 8), prime2, 13, prime1),
      xxhapply(h[3], util2.readU32(src, index + 12), prime2, 13, prime1)
    ];
  }
  function xxh32$1(seed, src, index, len) {
    var h, l2;
    l2 = len;
    if (len >= 16) {
      h = [
        seed + prime1 + prime2,
        seed + prime2,
        seed,
        seed - prime1
      ];
      while (len >= 16) {
        h = xxh16(h, src, index);
        index += 16;
        len -= 16;
      }
      h = rotl32(h[0], 1) + rotl32(h[1], 7) + rotl32(h[2], 12) + rotl32(h[3], 18) + l2;
    } else {
      h = seed + prime5 + len >>> 0;
    }
    while (len >= 4) {
      h = xxh4(h, src, index);
      index += 4;
      len -= 4;
    }
    while (len > 0) {
      h = xxh1(h, src, index);
      index++;
      len--;
    }
    h = shiftxor32(util2.imul(shiftxor32(util2.imul(shiftxor32(h, 15), prime2), 13), prime3), 16);
    return h >>> 0;
  }
  xxh32.hash = xxh32$1;
  return xxh32;
}
var hasRequiredLz4;
function requireLz4() {
  if (hasRequiredLz4) return lz4;
  hasRequiredLz4 = 1;
  (function(exports2) {
    var xxhash = requireXxh32();
    var util2 = requireUtil();
    var minMatch = 4;
    var minLength = 13;
    var searchLimit = 5;
    var skipTrigger = 6;
    var hashSize = 1 << 16;
    var mlBits = 4;
    var mlMask = (1 << mlBits) - 1;
    var runBits = 4;
    var runMask = (1 << runBits) - 1;
    var blockBuf = makeBuffer(5 << 20);
    var hashTable = makeHashTable();
    var magicNum = 407708164;
    var fdContentChksum = 4;
    var fdContentSize = 8;
    var fdBlockChksum = 16;
    var fdVersion = 64;
    var fdVersionMask = 192;
    var bsUncompressed = 2147483648;
    var bsDefault = 7;
    var bsShift = 4;
    var bsMask = 7;
    var bsMap = {
      4: 65536,
      5: 262144,
      6: 1048576,
      7: 4194304
    };
    function makeHashTable() {
      try {
        return new Uint32Array(hashSize);
      } catch (error2) {
        var hashTable2 = new Array(hashSize);
        for (var i2 = 0; i2 < hashSize; i2++) {
          hashTable2[i2] = 0;
        }
        return hashTable2;
      }
    }
    function clearHashTable(table2) {
      for (var i2 = 0; i2 < hashSize; i2++) {
        hashTable[i2] = 0;
      }
    }
    function makeBuffer(size) {
      try {
        return new Uint8Array(size);
      } catch (error2) {
        var buf2 = new Array(size);
        for (var i2 = 0; i2 < size; i2++) {
          buf2[i2] = 0;
        }
        return buf2;
      }
    }
    function sliceArray(array2, start2, end2) {
      if (typeof array2.buffer !== void 0) {
        if (Uint8Array.prototype.slice) {
          return array2.slice(start2, end2);
        } else {
          var len = array2.length;
          start2 = start2 | 0;
          start2 = start2 < 0 ? Math.max(len + start2, 0) : Math.min(start2, len);
          end2 = end2 === void 0 ? len : end2 | 0;
          end2 = end2 < 0 ? Math.max(len + end2, 0) : Math.min(end2, len);
          var arraySlice = new Uint8Array(end2 - start2);
          for (var i2 = start2, n2 = 0; i2 < end2; ) {
            arraySlice[n2++] = array2[i2++];
          }
          return arraySlice;
        }
      } else {
        return array2.slice(start2, end2);
      }
    }
    exports2.compressBound = function compressBound(n2) {
      return n2 + n2 / 255 + 16 | 0;
    };
    exports2.decompressBound = function decompressBound(src) {
      var sIndex = 0;
      if (util2.readU32(src, sIndex) !== magicNum) {
        throw new Error("invalid magic number");
      }
      sIndex += 4;
      var descriptor = src[sIndex++];
      if ((descriptor & fdVersionMask) !== fdVersion) {
        throw new Error("incompatible descriptor version " + (descriptor & fdVersionMask));
      }
      var useBlockSum = (descriptor & fdBlockChksum) !== 0;
      var useContentSize = (descriptor & fdContentSize) !== 0;
      var bsIdx = src[sIndex++] >> bsShift & bsMask;
      if (bsMap[bsIdx] === void 0) {
        throw new Error("invalid block size " + bsIdx);
      }
      var maxBlockSize = bsMap[bsIdx];
      if (useContentSize) {
        return util2.readU64(src, sIndex);
      }
      sIndex++;
      var maxSize = 0;
      while (true) {
        var blockSize = util2.readU32(src, sIndex);
        sIndex += 4;
        if (blockSize & bsUncompressed) {
          blockSize &= ~bsUncompressed;
          maxSize += blockSize;
        } else {
          maxSize += maxBlockSize;
        }
        if (blockSize === 0) {
          return maxSize;
        }
        if (useBlockSum) {
          sIndex += 4;
        }
        sIndex += blockSize;
      }
    };
    exports2.makeBuffer = makeBuffer;
    exports2.decompressBlock = function decompressBlock(src, dst, sIndex, sLength, dIndex) {
      var mLength, mOffset, sEnd, n2, i2;
      sEnd = sIndex + sLength;
      while (sIndex < sEnd) {
        var token2 = src[sIndex++];
        var literalCount = token2 >> 4;
        if (literalCount > 0) {
          if (literalCount === 15) {
            while (true) {
              literalCount += src[sIndex];
              if (src[sIndex++] !== 255) {
                break;
              }
            }
          }
          for (n2 = sIndex + literalCount; sIndex < n2; ) {
            dst[dIndex++] = src[sIndex++];
          }
        }
        if (sIndex >= sEnd) {
          break;
        }
        mLength = token2 & 15;
        mOffset = src[sIndex++] | src[sIndex++] << 8;
        if (mLength === 15) {
          while (true) {
            mLength += src[sIndex];
            if (src[sIndex++] !== 255) {
              break;
            }
          }
        }
        mLength += minMatch;
        for (i2 = dIndex - mOffset, n2 = i2 + mLength; i2 < n2; ) {
          dst[dIndex++] = dst[i2++] | 0;
        }
      }
      return dIndex;
    };
    exports2.compressBlock = function compressBlock(src, dst, sIndex, sLength, hashTable2) {
      var mIndex, mAnchor, mLength, mOffset, mStep;
      var literalCount, dIndex, sEnd, n2;
      dIndex = 0;
      sEnd = sLength + sIndex;
      mAnchor = sIndex;
      if (sLength >= minLength) {
        var searchMatchCount = (1 << skipTrigger) + 3;
        while (sIndex + minMatch < sEnd - searchLimit) {
          var seq = util2.readU32(src, sIndex);
          var hash2 = util2.hashU32(seq) >>> 0;
          hash2 = (hash2 >> 16 ^ hash2) >>> 0 & 65535;
          mIndex = hashTable2[hash2] - 1;
          hashTable2[hash2] = sIndex + 1;
          if (mIndex < 0 || sIndex - mIndex >>> 16 > 0 || util2.readU32(src, mIndex) !== seq) {
            mStep = searchMatchCount++ >> skipTrigger;
            sIndex += mStep;
            continue;
          }
          searchMatchCount = (1 << skipTrigger) + 3;
          literalCount = sIndex - mAnchor;
          mOffset = sIndex - mIndex;
          sIndex += minMatch;
          mIndex += minMatch;
          mLength = sIndex;
          while (sIndex < sEnd - searchLimit && src[sIndex] === src[mIndex]) {
            sIndex++;
            mIndex++;
          }
          mLength = sIndex - mLength;
          var token2 = mLength < mlMask ? mLength : mlMask;
          if (literalCount >= runMask) {
            dst[dIndex++] = (runMask << mlBits) + token2;
            for (n2 = literalCount - runMask; n2 >= 255; n2 -= 255) {
              dst[dIndex++] = 255;
            }
            dst[dIndex++] = n2;
          } else {
            dst[dIndex++] = (literalCount << mlBits) + token2;
          }
          for (var i2 = 0; i2 < literalCount; i2++) {
            dst[dIndex++] = src[mAnchor + i2];
          }
          dst[dIndex++] = mOffset;
          dst[dIndex++] = mOffset >> 8;
          if (mLength >= mlMask) {
            for (n2 = mLength - mlMask; n2 >= 255; n2 -= 255) {
              dst[dIndex++] = 255;
            }
            dst[dIndex++] = n2;
          }
          mAnchor = sIndex;
        }
      }
      if (mAnchor === 0) {
        return 0;
      }
      literalCount = sEnd - mAnchor;
      if (literalCount >= runMask) {
        dst[dIndex++] = runMask << mlBits;
        for (n2 = literalCount - runMask; n2 >= 255; n2 -= 255) {
          dst[dIndex++] = 255;
        }
        dst[dIndex++] = n2;
      } else {
        dst[dIndex++] = literalCount << mlBits;
      }
      sIndex = mAnchor;
      while (sIndex < sEnd) {
        dst[dIndex++] = src[sIndex++];
      }
      return dIndex;
    };
    exports2.decompressFrame = function decompressFrame(src, dst) {
      var useBlockSum, useContentSum, useContentSize, descriptor;
      var sIndex = 0;
      var dIndex = 0;
      if (util2.readU32(src, sIndex) !== magicNum) {
        throw new Error("invalid magic number");
      }
      sIndex += 4;
      descriptor = src[sIndex++];
      if ((descriptor & fdVersionMask) !== fdVersion) {
        throw new Error("incompatible descriptor version");
      }
      useBlockSum = (descriptor & fdBlockChksum) !== 0;
      useContentSum = (descriptor & fdContentChksum) !== 0;
      useContentSize = (descriptor & fdContentSize) !== 0;
      var bsIdx = src[sIndex++] >> bsShift & bsMask;
      if (bsMap[bsIdx] === void 0) {
        throw new Error("invalid block size");
      }
      if (useContentSize) {
        sIndex += 8;
      }
      sIndex++;
      while (true) {
        var compSize;
        compSize = util2.readU32(src, sIndex);
        sIndex += 4;
        if (compSize === 0) {
          break;
        }
        if (useBlockSum) {
          sIndex += 4;
        }
        if ((compSize & bsUncompressed) !== 0) {
          compSize &= ~bsUncompressed;
          for (var j2 = 0; j2 < compSize; j2++) {
            dst[dIndex++] = src[sIndex++];
          }
        } else {
          dIndex = exports2.decompressBlock(src, dst, sIndex, compSize, dIndex);
          sIndex += compSize;
        }
      }
      if (useContentSum) {
        sIndex += 4;
      }
      return dIndex;
    };
    exports2.compressFrame = function compressFrame(src, dst) {
      var dIndex = 0;
      util2.writeU32(dst, dIndex, magicNum);
      dIndex += 4;
      dst[dIndex++] = fdVersion;
      dst[dIndex++] = bsDefault << bsShift;
      dst[dIndex] = xxhash.hash(0, dst, 4, dIndex - 4) >> 8;
      dIndex++;
      var maxBlockSize = bsMap[bsDefault];
      var remaining = src.length;
      var sIndex = 0;
      clearHashTable();
      while (remaining > 0) {
        var compSize = 0;
        var blockSize = remaining > maxBlockSize ? maxBlockSize : remaining;
        compSize = exports2.compressBlock(src, blockBuf, sIndex, blockSize, hashTable);
        if (compSize > blockSize || compSize === 0) {
          util2.writeU32(dst, dIndex, 2147483648 | blockSize);
          dIndex += 4;
          for (var z = sIndex + blockSize; sIndex < z; ) {
            dst[dIndex++] = src[sIndex++];
          }
          remaining -= blockSize;
        } else {
          util2.writeU32(dst, dIndex, compSize);
          dIndex += 4;
          for (var j2 = 0; j2 < compSize; ) {
            dst[dIndex++] = blockBuf[j2++];
          }
          sIndex += blockSize;
          remaining -= blockSize;
        }
      }
      util2.writeU32(dst, dIndex, 0);
      dIndex += 4;
      return dIndex;
    };
    exports2.decompress = function decompress(src, maxSize) {
      var dst, size;
      if (maxSize === void 0) {
        maxSize = exports2.decompressBound(src);
      }
      dst = exports2.makeBuffer(maxSize);
      size = exports2.decompressFrame(src, dst);
      if (size !== maxSize) {
        dst = sliceArray(dst, 0, size);
      }
      return dst;
    };
    exports2.compress = function compress(src, maxSize) {
      var dst, size;
      if (maxSize === void 0) {
        maxSize = exports2.compressBound(src.length);
      }
      dst = exports2.makeBuffer(maxSize);
      size = exports2.compressFrame(src, dst);
      if (size !== maxSize) {
        dst = sliceArray(dst, 0, size);
      }
      return dst;
    };
  })(lz4);
  return lz4;
}
var lz4Exports = requireLz4();
const decodeArrowBytes = (bytes) => {
  ensureLZ4CodecRegistered();
  const arrowTable = tableFromIPC$1(bytes);
  const uncompressedBytes = tableToIPC$1(arrowTable);
  let table2 = fromArrow(uncompressedBytes);
  table2 = castColumns(table2);
  const columns2 = {};
  const columnNames = table2.columnNames();
  for (const colName of columnNames) {
    const colData = table2.array(colName);
    columns2[colName] = Array.isArray(colData) ? colData : Array.from(colData);
  }
  return table$2(columns2);
};
let codecRegistered = false;
function ensureLZ4CodecRegistered() {
  if (!codecRegistered) {
    const lz4Codec = {
      encode(data2) {
        return lz4Exports.compress(data2);
      },
      decode(data2) {
        return lz4Exports.decompress(data2);
      }
    };
    compressionRegistry.set(CompressionType.LZ4_FRAME, lz4Codec);
    codecRegistered = true;
  }
}
function castColumns(table2) {
  const columnNames = table2.columnNames();
  const hasValue = columnNames.includes("value") && columnNames.includes("value_type");
  const hasScanRefusal = columnNames.includes("scan_error_refusal");
  if (!hasValue && !hasScanRefusal) {
    return table2;
  }
  const castValue = (value2, valueType) => {
    if (value2 === null || value2 === void 0) {
      return null;
    }
    if (valueType === "boolean") {
      if (typeof value2 === "boolean") {
        return value2;
      }
      const strVal = String(value2).toLowerCase();
      if (strVal === "true") {
        return true;
      }
      if (strVal === "false") {
        return false;
      }
      return null;
    } else if (valueType === "number") {
      if (typeof value2 === "number") {
        return value2;
      }
      const strVal = String(value2).trim();
      if (strVal === "") {
        return null;
      }
      const num = Number(strVal);
      return isNaN(num) ? null : num;
    } else {
      return value2;
    }
  };
  const derivations = {};
  if (hasValue) {
    derivations.value = escape$1((d) => {
      return castValue(d.value, d.value_type);
    });
  }
  if (hasScanRefusal) {
    derivations.scan_error_refusal = escape$1(
      (d) => {
        return d.scan_error_refusal?.toLowerCase() === "true";
      }
    );
  }
  return table2.derive(derivations);
}
const join = (file, dir) => {
  if (!dir) {
    return file;
  }
  const normalizedFile = file.replace(/\\/g, "/");
  const normalizedLogDir = dir.replace(/\\/g, "/");
  const dirWithSlash = normalizedLogDir.endsWith("/") ? normalizedLogDir : normalizedLogDir + "/";
  return dirWithSlash + normalizedFile;
};
const prettyDirUri = (uri) => {
  if (uri.startsWith("file://")) {
    return uri.replace("file://", "");
  } else {
    return uri;
  }
};
async function expandResultsetRows(columnTable) {
  const colNames = columnTable.columnNames();
  if (!colNames.includes("value_type") || !colNames.includes("value") || columnTable.numRows() === 0) {
    return columnTable;
  }
  const resultsetCount = columnTable.filter((d) => d.value_type === "resultset").numRows();
  if (resultsetCount === 0) {
    return columnTable;
  }
  const resultsetRows = columnTable.filter(
    (d) => d.value_type === "resultset"
  );
  const otherRows = columnTable.filter(
    (d) => d.value_type !== "resultset"
  );
  const resultObjs = resultsetRows.objects();
  const explodedResultsetRows = [];
  for (const row2 of resultObjs) {
    try {
      const valueStr = row2.value;
      const results = valueStr ? lib$1.parse(valueStr) : [];
      if (!results || results.length === 0) {
        const expandedRow = { ...row2 };
        expandedRow.value = null;
        expandedRow.value_type = "null";
        explodedResultsetRows.push(expandedRow);
        continue;
      }
      for (const result2 of results) {
        const expandedRow = { ...row2 };
        expandedRow.uuid = result2.uuid ?? null;
        expandedRow.label = result2.label ?? null;
        expandedRow.answer = result2.answer ?? null;
        expandedRow.explanation = result2.explanation ?? null;
        if (row2.validation_result && typeof row2.validation_result === "string") {
          expandedRow.validation_result = await extractLabelValidation(
            expandedRow,
            row2.validation_result
          );
        }
        const metadata2 = result2.metadata ?? {};
        expandedRow.metadata = maybeSerializeValue(metadata2);
        const valueType = result2.type ?? inferType(result2.value);
        expandedRow.value_type = valueType;
        const value2 = maybeSerializeValue(result2.value);
        expandedRow.value = value2;
        const references = result2.references ?? [];
        const messageRefs = references.filter((ref2) => ref2.type === "message");
        const eventRefs = references.filter((ref2) => ref2.type === "event");
        expandedRow.message_references = maybeSerializeValue(messageRefs);
        expandedRow.event_references = maybeSerializeValue(eventRefs);
        explodedResultsetRows.push(expandedRow);
      }
    } catch (error2) {
      console.error("Failed to parse resultset value:", error2);
      continue;
    }
  }
  const syntheticRows = await createSyntheticRows(
    explodedResultsetRows,
    resultObjs
  );
  if (explodedResultsetRows.length === 0) {
    return otherRows;
  } else {
    const otherRowsArray = otherRows.objects();
    const allRowsArray = [
      ...otherRowsArray,
      ...explodedResultsetRows,
      ...syntheticRows
    ];
    return from(allRowsArray);
  }
}
async function extractLabelValidation(row2, validationResultStr) {
  if (!row2.label || typeof row2.label !== "string") {
    return validationResultStr;
  }
  try {
    const parsedValidation = await asyncJsonParse(validationResultStr);
    if (typeof parsedValidation === "object" && parsedValidation !== null && !Array.isArray(parsedValidation)) {
      const validationDict = parsedValidation;
      const labelValidation = validationDict[row2.label];
      return labelValidation ?? null;
    }
    return parsedValidation;
  } catch (error2) {
    return validationResultStr;
  }
}
async function createSyntheticRows(expandedRows, resultsetRows) {
  if (resultsetRows.length === 0 || expandedRows.length === 0) {
    return [];
  }
  const firstRow = expandedRows[0];
  if (!firstRow || !firstRow.validation_target || typeof firstRow.validation_target !== "string") {
    return [];
  }
  try {
    const parsedTarget = await asyncJsonParse(
      firstRow.validation_target
    );
    if (typeof parsedTarget !== "object" || parsedTarget === null || Array.isArray(parsedTarget)) {
      return [];
    }
    const validationTarget = parsedTarget;
    const parsedResult = firstRow.validation_result ? await asyncJsonParse(
      typeof firstRow.validation_result === "string" ? firstRow.validation_result : JSON.stringify(firstRow.validation_result)
    ) : {};
    const validationResults = typeof parsedResult === "object" && !Array.isArray(parsedResult) ? parsedResult : {};
    const presentLabels = new Set(
      expandedRows.map((row2) => row2.label).filter((label2) => label2 !== null && label2 !== void 0)
    );
    const expectedLabels = Object.keys(validationTarget);
    const missingLabels = expectedLabels.filter(
      (label2) => !presentLabels.has(label2)
    );
    const syntheticRows = [];
    const negativeValues = [false, null, "NONE", "none", 0, ""];
    for (const label2 of missingLabels) {
      const expectedValue = validationTarget[label2];
      if (!negativeValues.includes(expectedValue)) {
        continue;
      }
      const templateRow = { ...resultsetRows[0] };
      templateRow.label = label2;
      templateRow.value = expectedValue;
      templateRow.value_type = typeof expectedValue === "boolean" ? "boolean" : "null";
      templateRow.answer = null;
      templateRow.explanation = null;
      templateRow.metadata = maybeSerializeValue({});
      templateRow.message_references = maybeSerializeValue([]);
      templateRow.event_references = maybeSerializeValue([]);
      templateRow.uuid = null;
      templateRow.validation_result = validationResults[label2] ?? null;
      templateRow.scan_error = null;
      templateRow.scan_error_traceback = null;
      templateRow.scan_error_type = null;
      templateRow.scan_total_tokens = null;
      templateRow.scan_model_usage = null;
      syntheticRows.push(templateRow);
    }
    return syntheticRows;
  } catch (error2) {
    return [];
  }
}
function inferType(value2) {
  if (typeof value2 === "boolean") {
    return "boolean";
  } else if (typeof value2 === "number") {
    return "number";
  } else if (typeof value2 === "string") {
    return "string";
  } else if (Array.isArray(value2)) {
    return "array";
  } else if (value2 !== null && typeof value2 === "object") {
    return "object";
  }
  return "null";
}
const maybeSerializeValue = (value2) => {
  if (value2 === void 0 || value2 === null) {
    return null;
  }
  if (typeof value2 === "string" || typeof value2 === "number" || typeof value2 === "boolean") {
    return value2;
  }
  return lib$1.stringify(value2);
};
const useSelectedScanner = () => {
  const selectedScanner = useStore((state) => state.selectedScanner);
  const selectedStatus = useStore((state) => state.selectedScanStatus);
  const defaultScanner = reactExports.useMemo(() => {
    if (selectedStatus) {
      const scanners = Object.keys(selectedStatus.summary.scanners);
      return scanners.length > 0 ? scanners[0] : void 0;
    }
  }, [selectedStatus, selectedStatus?.summary.scanners]);
  return selectedScanner || defaultScanner;
};
const useServerScans = () => {
  const api2 = useApi();
  const resultsDir = useStore((state) => state.resultsDir);
  const setScans = useStore((state) => state.setScans);
  const setResultsDir = useStore((state) => state.setResultsDir);
  const setLoading = useStore((state) => state.setLoading);
  const setError = useStore((state) => state.setError);
  const clearError = useStore((state) => state.clearError);
  reactExports.useEffect(() => {
    const fetchScans = async () => {
      clearError("scanjobs");
      setLoading(true);
      try {
        const scansInfo = await api2.getScans();
        if (scansInfo) {
          setResultsDir(scansInfo.results_dir);
          setScans(scansInfo.scans);
        }
      } catch (e) {
        setError("scanjobs", e?.toString());
      } finally {
        setLoading(false);
      }
    };
    if (!resultsDir) {
      void fetchScans();
    }
  }, [api2, resultsDir, setScans, setResultsDir]);
};
const useServerScannerDataframe = () => {
  const api2 = useApi();
  const params = useParams();
  const relativePath = getRelativePathFromParams(params);
  const { scanPath } = parseScanResultPath(relativePath);
  const singleFileMode = useStore((state) => state.singleFileMode);
  const resultsDir = useStore((state) => state.resultsDir);
  const selectedScanner = useSelectedScanner();
  const setLoadingData = useStore((state) => state.setLoadingData);
  const setSelectedScanResultData = useStore(
    (state) => state.setSelectedScanResultData
  );
  const getSelectedScanResultData = useStore(
    (state) => state.getSelectedScanResultData
  );
  const setError = useStore((state) => state.setError);
  const clearError = useStore((state) => state.clearError);
  reactExports.useEffect(() => {
    const fetchScannerDataframe = async () => {
      clearError("dataframe");
      const existingData = getSelectedScanResultData(selectedScanner);
      if (!scanPath || !selectedScanner || existingData) {
        return;
      }
      setLoadingData(true);
      try {
        let location = scanPath;
        if (resultsDir) {
          location = join(scanPath, resultsDir);
        }
        const arrayBuffer = await api2.getScannerDataframe(
          location,
          selectedScanner
        );
        const table2 = decodeArrowBytes(arrayBuffer);
        const expandedTable = await expandResultsetRows(table2);
        setSelectedScanResultData(selectedScanner, expandedTable);
      } catch (e) {
        setError("dataframe", e?.toString());
      } finally {
        setLoadingData(false);
      }
    };
    void fetchScannerDataframe();
  }, [
    api2,
    scanPath,
    selectedScanner,
    resultsDir,
    singleFileMode,
    setLoadingData,
    setSelectedScanResultData,
    getSelectedScanResultData
  ]);
};
const useServerScanner = () => {
  const api2 = useApi();
  const params = useParams();
  const relativePath = getRelativePathFromParams(params);
  const { scanPath } = parseScanResultPath(relativePath);
  const resultsDir = useStore((state) => state.resultsDir);
  const selectedStatus = useStore((state) => state.selectedScanStatus);
  const scans = useStore((state) => state.scans);
  const setSelectedScanLocation = useStore(
    (state) => state.setSelectedScanLocation
  );
  const setSelectedScanStatus = useStore(
    (state) => state.setSelectedScanStatus
  );
  const setLoading = useStore((state) => state.setLoading);
  const setError = useStore((state) => state.setError);
  const clearError = useStore((state) => state.clearError);
  reactExports.useEffect(() => {
    if (scanPath && !selectedStatus) {
      clearError("scanner");
      const location = join(scanPath, resultsDir);
      const scansInfo = scans.find((s) => s.location === location);
      if (scansInfo) {
        setSelectedScanStatus(scansInfo);
      } else {
        const fetchScan = async () => {
          setLoading(true);
          try {
            const status = await api2.getScan(location);
            setSelectedScanStatus(status);
          } catch (e) {
            setError("scanner", e?.toString());
          } finally {
            setLoading(false);
          }
        };
        void fetchScan();
      }
      setSelectedScanLocation(scanPath);
    }
  }, [
    relativePath,
    api2,
    setSelectedScanStatus,
    scanPath,
    selectedStatus,
    scans,
    resultsDir
  ]);
};
const useScannerData = (columnTable, scanResultUuid) => {
  const [scannerData, setScannerData] = reactExports.useState(
    void 0
  );
  const [isLoading, setIsLoading] = reactExports.useState(false);
  const filtered = reactExports.useMemo(() => {
    if (!scanResultUuid || !columnTable) {
      return void 0;
    }
    if (columnTable.columnNames().length === 0) {
      return void 0;
    }
    const filtered2 = columnTable.params({ targetUuid: scanResultUuid }).filter(
      (d, $2) => d.uuid === $2.targetUuid
    );
    if (filtered2.numRows() === 0) {
      return void 0;
    }
    return filtered2;
  }, [columnTable, scanResultUuid]);
  reactExports.useEffect(() => {
    if (!filtered) {
      setScannerData(void 0);
      setIsLoading(false);
      return;
    }
    let cancelled = false;
    setIsLoading(true);
    const parse5 = async (text2) => {
      return text2 !== null ? asyncJsonParse(text2) : void 0;
    };
    const parseData = async () => {
      try {
        const valueType = filtered.get("value_type", 0);
        const simpleValue = (val, valueType2) => {
          if (valueType2 === "object" || valueType2 === "array") {
            return parse5(val);
          } else {
            return Promise.resolve(val);
          }
        };
        const [
          eventReferences,
          input2,
          inputIds,
          messageReferences,
          metadata2,
          scanEvents,
          scanMetadata,
          scanModelUsage,
          scanTags,
          scannerParams,
          transcriptMetadata,
          validationResult,
          validationTarget,
          value2
        ] = await Promise.all([
          parse5(filtered.get("event_references", 0)),
          parse5(filtered.get("input", 0)),
          parse5(filtered.get("input_ids", 0)),
          parse5(filtered.get("message_references", 0)),
          parse5(filtered.get("metadata", 0)),
          parse5(filtered.get("scan_events", 0)),
          parse5(filtered.get("scan_metadata", 0)),
          parse5(filtered.get("scan_model_usage", 0)),
          parse5(filtered.get("scan_tags", 0)),
          parse5(filtered.get("scanner_params", 0)),
          parse5(filtered.get("transcript_metadata", 0)),
          parse5(filtered.get("validation_result", 0)),
          parse5(filtered.get("validation_target", 0)),
          simpleValue(filtered.get("value", 0), valueType)
        ]);
        if (cancelled) return;
        const uuid = filtered.get("uuid", 0);
        const answer = filtered.get("answer", 0);
        const label2 = filtered.columnNames().includes("label") ? filtered.get("label", 0) : void 0;
        const explanation2 = filtered.get("explanation", 0);
        const inputType = filtered.get("input_type", 0);
        const scanError = filtered.get("scan_error", 0);
        const scanErrorTraceback = filtered.get("scan_error_traceback", 0);
        const scanErrorRefusal = filtered.columnNames().includes("scan_error_refusal") ? filtered.get("scan_error_refusal", void 0) : false;
        const scanId = filtered.get("scan_id", 0);
        const scanTotalTokens = filtered.get("scan_total_tokens", 0);
        const scannerFile = filtered.get("scanner_file", 0);
        const scannerKey = filtered.get("scanner_key", 0);
        const scannerName = filtered.get("scanner_name", 0);
        const transcriptId = filtered.get("transcript_id", 0);
        const transcriptSourceId = filtered.get(
          "transcript_source_id",
          0
        );
        const transcriptSourceUri = filtered.get(
          "transcript_source_uri",
          0
        );
        const baseData = {
          uuid,
          answer,
          label: label2,
          eventReferences,
          explanation: explanation2,
          inputIds,
          messageReferences,
          metadata: metadata2,
          scanError,
          scanErrorTraceback,
          scanErrorRefusal,
          scanEvents,
          scanId,
          scanMetadata,
          scanModelUsage,
          scanTags,
          scanTotalTokens,
          scannerFile,
          scannerKey,
          scannerName,
          scannerParams,
          transcriptId,
          transcriptMetadata,
          transcriptSourceId,
          transcriptSourceUri,
          validationResult,
          validationTarget,
          value: value2 || null,
          valueType
        };
        let typedData;
        switch (inputType) {
          case "transcript":
            typedData = {
              ...baseData,
              inputType: "transcript",
              input: input2
            };
            break;
          case "message":
            typedData = {
              ...baseData,
              inputType: "message",
              input: input2
            };
            break;
          case "messages":
            typedData = {
              ...baseData,
              inputType: "messages",
              input: input2
            };
            break;
          case "event":
            typedData = {
              ...baseData,
              inputType: "event",
              input: input2
            };
            break;
          case "events":
            typedData = {
              ...baseData,
              inputType: "events",
              input: input2
            };
            break;
        }
        setScannerData(typedData);
        setIsLoading(false);
      } catch (error2) {
        if (!cancelled) {
          console.error("Error parsing scanner data:", error2);
          setScannerData(void 0);
          setIsLoading(false);
        }
      }
    };
    void parseData();
    return () => {
      cancelled = true;
    };
  }, [filtered]);
  return { data: scannerData, isLoading };
};
const useSelectedResultsRow = (scanResultUuid) => {
  const getSelectedScanResultData = useStore(
    (state) => state.getSelectedScanResultData
  );
  const selectedScanner = useSelectedScanner();
  const selectedScanResultData = getSelectedScanResultData(selectedScanner);
  const { data: scanData, isLoading } = useScannerData(
    selectedScanResultData,
    scanResultUuid
  );
  return { data: scanData, isLoading };
};
const useScannerPreviews = (columnTable) => {
  const selectedScanner = useSelectedScanner();
  const getSelectedScanResultPreviews = useStore(
    (state) => state.getSelectedScanResultPreviews
  );
  const setSelectedScanResultPreviews = useStore(
    (state) => state.setSelectedScanResultPreviews
  );
  const [scannerPreviews, setScannerPreviews] = reactExports.useState([]);
  const [isLoading, setIsLoading] = reactExports.useState(false);
  const rowData = reactExports.useMemo(() => columnTable?.objects(), [columnTable]);
  reactExports.useEffect(() => {
    if (rowData?.length === 0) {
      setScannerPreviews([]);
      setSelectedScanResultPreviews(selectedScanner, []);
      setIsLoading(false);
      return;
    }
    const existingPreviews = getSelectedScanResultPreviews(selectedScanner);
    if (existingPreviews) {
      setScannerPreviews(existingPreviews);
      setIsLoading(false);
      return;
    }
    let cancelled = false;
    setIsLoading(true);
    const parse5 = async (text2) => {
      return text2 !== null ? asyncJsonParse(text2) : void 0;
    };
    const parsePreviews = async () => {
      try {
        const parsedPreviews = await Promise.all(
          (rowData || []).map(async (row2) => {
            const r2 = row2;
            const valueType = r2.value_type;
            const simpleValue = async (val, valueType2) => {
              if (valueType2 === "object" || valueType2 === "array") {
                return await parse5(val) || null;
              } else {
                return Promise.resolve(val);
              }
            };
            const [
              validationResult,
              validationTarget,
              transcriptMetadata,
              eventReferences,
              messageReferences,
              input2,
              value2
            ] = await Promise.all([
              parse5(r2.validation_result),
              parse5(r2.validation_target),
              parse5(r2.transcript_metadata),
              parse5(r2.event_references),
              parse5(r2.message_references),
              parse5(r2.input),
              simpleValue(r2.value, valueType)
            ]);
            const explanation2 = r2.explanation;
            const transcriptSourceId = r2.transcript_source_id;
            const inputType = r2.input_type;
            const scanError = r2.scan_error;
            const scanErrorRefusal = r2.scan_error_refusal;
            const basePreview = {
              uuid: r2.uuid,
              label: r2.label,
              explanation: explanation2,
              eventReferences,
              messageReferences,
              validationResult,
              validationTarget,
              value: value2,
              valueType,
              transcriptMetadata: transcriptMetadata || {},
              transcriptSourceId,
              scanError,
              scanErrorRefusal
            };
            let typedPreview;
            switch (inputType) {
              case "transcript":
                typedPreview = {
                  ...basePreview,
                  inputType: "transcript",
                  input: input2
                };
                break;
              case "message":
                typedPreview = {
                  ...basePreview,
                  inputType: "message",
                  input: input2
                };
                break;
              case "messages":
                typedPreview = {
                  ...basePreview,
                  inputType: "messages",
                  input: input2
                };
                break;
              case "event":
                typedPreview = {
                  ...basePreview,
                  inputType: "event",
                  input: input2
                };
                break;
              case "events":
                typedPreview = {
                  ...basePreview,
                  inputType: "events",
                  input: input2
                };
                break;
            }
            return typedPreview;
          })
        );
        if (!cancelled) {
          setScannerPreviews(parsedPreviews);
          setSelectedScanResultPreviews(selectedScanner, parsedPreviews);
          setIsLoading(false);
        }
      } catch (error2) {
        if (!cancelled) {
          console.error("Error parsing scanner previews:", error2);
          setScannerPreviews([]);
          setSelectedScanResultPreviews(selectedScanner, []);
          setIsLoading(false);
        }
      }
    };
    void parsePreviews();
    return () => {
      cancelled = true;
    };
  }, [
    rowData,
    selectedScanner,
    getSelectedScanResultPreviews,
    setSelectedScanResultPreviews
  ]);
  return { data: scannerPreviews, isLoading };
};
const filename = (path) => {
  if (!path) {
    return "";
  }
  path = path.endsWith("/") ? path.slice(0, -1) : path;
  const pathparts = path.split("/");
  const basename2 = pathparts.slice(-1)[0];
  if (!basename2) {
    return "";
  }
  if (basename2.startsWith(".") && !basename2.substring(1).includes(".")) {
    return basename2;
  }
  const match3 = basename2.match(/(.*)\.\S+$/);
  if (match3) {
    return match3[1] ?? "";
  } else {
    return path;
  }
};
const basename = (path) => {
  if (!path) {
    return "";
  }
  path = path.endsWith("/") ? path.slice(0, -1) : path;
  const pathparts = path.split("/");
  return pathparts.slice(-1)[0] ?? "";
};
const dirname = (path) => {
  path = path.endsWith("/") ? path.slice(0, -1) : path;
  const pathparts = path.split("/");
  if (pathparts.length > 1) {
    pathparts.pop();
    return pathparts.join("/");
  }
  return "";
};
const ensureTrailingSlash = (path) => {
  if (!path) {
    return "";
  }
  return path.endsWith("/") ? path : path + "/";
};
const toRelativePath = (absolutePath, basePath) => {
  const normalizedResultsDir = ensureTrailingSlash(basePath).replace(
    "file://",
    ""
  );
  const normalizedPath = absolutePath.startsWith("file://") ? decodeURIComponent(absolutePath.replace("file://", "")) : absolutePath;
  if (normalizedPath.startsWith(normalizedResultsDir)) {
    return normalizedPath.substring(normalizedResultsDir.length);
  }
  return normalizedPath;
};
const header$2 = "_header_oy6cz_1";
const bordered$1 = "_bordered_oy6cz_11";
const breadcrumbs = "_breadcrumbs_oy6cz_15";
const ellipsis = "_ellipsis_oy6cz_26";
const left$2 = "_left_oy6cz_31";
const right$2 = "_right_oy6cz_41";
const toolbarButton = "_toolbarButton_oy6cz_50";
const pathContainer = "_pathContainer_oy6cz_58";
const hasChildren = "_hasChildren_oy6cz_62";
const styles$1k = {
  header: header$2,
  bordered: bordered$1,
  breadcrumbs,
  ellipsis,
  left: left$2,
  right: right$2,
  toolbarButton,
  pathContainer,
  hasChildren
};
const useBreadcrumbTruncation = (segments, containerRef) => {
  const [truncatedData, setTruncatedData] = reactExports.useState({
    visibleSegments: segments,
    hiddenCount: 0,
    showEllipsis: false
  });
  reactExports.useEffect(() => {
    const measureAndTruncate = () => {
      if (!containerRef.current || segments.length <= 3) {
        setTruncatedData({
          visibleSegments: segments,
          hiddenCount: 0,
          showEllipsis: false
        });
        return;
      }
      const container2 = containerRef.current;
      const containerWidth = container2.offsetWidth;
      const testElement = document.createElement("ol");
      testElement.className = "breadcrumb";
      testElement.style.position = "absolute";
      testElement.style.visibility = "hidden";
      testElement.style.whiteSpace = "nowrap";
      testElement.style.margin = "0";
      testElement.style.padding = "0";
      container2.appendChild(testElement);
      testElement.innerHTML = segments.map((segment2) => `<li class="breadcrumb-item">${segment2.text}</li>`).join("");
      if (testElement.scrollWidth <= containerWidth) {
        container2.removeChild(testElement);
        setTruncatedData({
          visibleSegments: segments,
          hiddenCount: 0,
          showEllipsis: false
        });
        return;
      }
      const firstSegment = segments[0];
      const lastSegment = segments[segments.length - 1];
      if (!firstSegment || !lastSegment) {
        container2.removeChild(testElement);
        return;
      }
      let maxVisible = 2;
      for (let endCount = 1; endCount < segments.length - 1; endCount++) {
        const candidateSegments = [
          firstSegment,
          ...segments.slice(segments.length - 1 - endCount, -1),
          lastSegment
        ];
        const testHTML = [
          `<li class="breadcrumb-item">${firstSegment.text}</li>`,
          `<li class="breadcrumb-item">...</li>`,
          ...segments.slice(segments.length - 1 - endCount, -1).map((s) => `<li class="breadcrumb-item">${s.text}</li>`),
          `<li class="breadcrumb-item">${lastSegment.text}</li>`
        ].join("");
        testElement.innerHTML = testHTML;
        if (testElement.scrollWidth <= containerWidth) {
          maxVisible = candidateSegments.length;
          setTruncatedData({
            visibleSegments: candidateSegments,
            hiddenCount: segments.length - candidateSegments.length,
            showEllipsis: true
          });
        } else {
          break;
        }
      }
      if (maxVisible === 2) {
        setTruncatedData({
          visibleSegments: [firstSegment, lastSegment],
          hiddenCount: segments.length - 2,
          showEllipsis: true
        });
      }
      container2.removeChild(testElement);
    };
    measureAndTruncate();
    const resizeObserver = new ResizeObserver(measureAndTruncate);
    if (containerRef.current) {
      resizeObserver.observe(containerRef.current);
    }
    return () => {
      resizeObserver.disconnect();
    };
  }, [segments, containerRef]);
  return truncatedData;
};
const Navbar = ({ bordered: bordered2 = true, children: children2 }) => {
  const resultsDir = useStore((state) => state.resultsDir);
  const baseResultsDir = dirname(resultsDir || "");
  const baseResultsName = basename(resultsDir || "");
  const params = useParams();
  const currentPath = getRelativePathFromParams(params);
  const singleFileMode = useStore((state) => state.singleFileMode);
  const [searchParams] = useSearchParams();
  const pathContainerRef = reactExports.useRef(null);
  const { scanPath, scanResultUuid } = parseScanResultPath(currentPath);
  const backUrl = scanResultUuid ? scanRoute(scanPath, searchParams) : !singleFileMode ? scansRoute(dirname(currentPath || "")) : void 0;
  const segments = reactExports.useMemo(() => {
    const pathSegments = currentPath ? currentPath.split("/") : [];
    const dirSegments = [];
    const currentSegment = [];
    for (const pathSegment of pathSegments) {
      currentSegment.push(pathSegment);
      const fullSegmentPath = currentSegment.join("/");
      const segmentUrl = isValidScanPath(fullSegmentPath) ? scanRoute(fullSegmentPath, searchParams) : scansRoute(fullSegmentPath);
      dirSegments.push({
        text: pathSegment,
        url: segmentUrl
      });
    }
    return [
      { text: prettyDirUri(baseResultsDir) },
      { text: baseResultsName, url: scansRoute() },
      ...dirSegments
    ];
  }, [baseResultsDir, baseResultsName, currentPath, searchParams]);
  const { visibleSegments, showEllipsis } = useBreadcrumbTruncation(
    segments,
    pathContainerRef
  );
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "nav",
    {
      className: clsx(
        "text-size-smaller",
        "header-nav",
        styles$1k.header,
        bordered2 ? styles$1k.bordered : void 0
      ),
      "aria-label": "breadcrumb",
      "data-unsearchable": true,
      children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$1k.left), children: [
          backUrl && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Link, { to: backUrl, className: clsx(styles$1k.toolbarButton), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("i", { className: clsx(ApplicationIcons.navbar.back) }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/navbar/Navbar.tsx",
            lineNumber: 89,
            columnNumber: 13
          }, void 0) }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/navbar/Navbar.tsx",
            lineNumber: 88,
            columnNumber: 11
          }, void 0),
          !singleFileMode && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            Link,
            {
              to: scansRoute(),
              className: clsx(styles$1k.toolbarButton),
              onClick: () => {
              },
              children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("i", { className: clsx(ApplicationIcons.navbar.home) }, void 0, false, {
                fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/navbar/Navbar.tsx",
                lineNumber: 100,
                columnNumber: 13
              }, void 0)
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/navbar/Navbar.tsx",
              lineNumber: 93,
              columnNumber: 11
            },
            void 0
          ),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$1k.pathContainer), ref: pathContainerRef, children: resultsDir ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("ol", { className: clsx("breadcrumb", styles$1k.breadcrumbs), children: visibleSegments.map((segment2, index) => {
            const isLast = index === visibleSegments.length - 1;
            const shouldShowEllipsis = showEllipsis && index === 1 && visibleSegments.length >= 2;
            return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(reactExports.Fragment, { children: [
              shouldShowEllipsis && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("li", { className: clsx("breadcrumb-item", styles$1k.ellipsis), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("span", { children: "..." }, void 0, false, {
                fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/navbar/Navbar.tsx",
                lineNumber: 115,
                columnNumber: 25
              }, void 0) }, void 0, false, {
                fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/navbar/Navbar.tsx",
                lineNumber: 114,
                columnNumber: 23
              }, void 0),
              /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
                "li",
                {
                  className: clsx(
                    styles$1k.pathLink,
                    "breadcrumb-item",
                    isLast && !singleFileMode ? "active" : void 0
                  ),
                  children: segment2.url && !singleFileMode && !isLast ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Link, { to: segment2.url, children: segment2.text }, void 0, false, {
                    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/navbar/Navbar.tsx",
                    lineNumber: 126,
                    columnNumber: 25
                  }, void 0) : /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("span", { className: clsx(styles$1k.pathSegment), children: segment2.text }, void 0, false, {
                    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/navbar/Navbar.tsx",
                    lineNumber: 128,
                    columnNumber: 25
                  }, void 0)
                },
                void 0,
                false,
                {
                  fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/navbar/Navbar.tsx",
                  lineNumber: 118,
                  columnNumber: 21
                },
                void 0
              )
            ] }, index, true, {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/navbar/Navbar.tsx",
              lineNumber: 112,
              columnNumber: 19
            }, void 0);
          }) }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/navbar/Navbar.tsx",
            lineNumber: 105,
            columnNumber: 13
          }, void 0) : "" }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/navbar/Navbar.tsx",
            lineNumber: 103,
            columnNumber: 9
          }, void 0)
        ] }, void 0, true, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/navbar/Navbar.tsx",
          lineNumber: 86,
          columnNumber: 7
        }, void 0),
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "div",
          {
            className: clsx(
              styles$1k.right,
              children2 ? styles$1k.hasChildren : void 0
            ),
            children: children2
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/navbar/Navbar.tsx",
            lineNumber: 142,
            columnNumber: 7
          },
          void 0
        )
      ]
    },
    void 0,
    true,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/navbar/Navbar.tsx",
      lineNumber: 76,
      columnNumber: 5
    },
    void 0
  );
};
function commonjsRequire(path) {
  throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
}
var ansiOutput = { exports: {} };
var hasRequiredAnsiOutput;
function requireAnsiOutput() {
  if (hasRequiredAnsiOutput) return ansiOutput.exports;
  hasRequiredAnsiOutput = 1;
  (function(module, exports2) {
    (function(factory) {
      {
        var v = factory(commonjsRequire, exports2);
        if (v !== void 0) module.exports = v;
      }
    })(function(require2, exports3) {
      Object.defineProperty(exports3, "__esModule", { value: true });
      exports3.ANSIOutput = exports3.ANSIColor = exports3.ANSIFont = exports3.ANSIStyle = void 0;
      let counter2 = 0;
      const generateId = () => {
        return `${++counter2}`.padStart(16, "0");
      };
      var ANSIStyle;
      (function(ANSIStyle2) {
        ANSIStyle2["Bold"] = "ansiBold";
        ANSIStyle2["Dim"] = "ansiDim";
        ANSIStyle2["Italic"] = "ansiItalic";
        ANSIStyle2["Underlined"] = "ansiUnderlined";
        ANSIStyle2["SlowBlink"] = "ansiSlowBlink";
        ANSIStyle2["RapidBlink"] = "ansiRapidBlink";
        ANSIStyle2["Hidden"] = "ansiHidden";
        ANSIStyle2["CrossedOut"] = "ansiCrossedOut";
        ANSIStyle2["Fraktur"] = "ansiFraktur";
        ANSIStyle2["DoubleUnderlined"] = "ansiDoubleUnderlined";
        ANSIStyle2["Framed"] = "ansiFramed";
        ANSIStyle2["Encircled"] = "ansiEncircled";
        ANSIStyle2["Overlined"] = "ansiOverlined";
        ANSIStyle2["Superscript"] = "ansiSuperscript";
        ANSIStyle2["Subscript"] = "ansiSubscript";
      })(ANSIStyle || (exports3.ANSIStyle = ANSIStyle = {}));
      var ANSIFont;
      (function(ANSIFont2) {
        ANSIFont2["AlternativeFont1"] = "ansiAlternativeFont1";
        ANSIFont2["AlternativeFont2"] = "ansiAlternativeFont2";
        ANSIFont2["AlternativeFont3"] = "ansiAlternativeFont3";
        ANSIFont2["AlternativeFont4"] = "ansiAlternativeFont4";
        ANSIFont2["AlternativeFont5"] = "ansiAlternativeFont5";
        ANSIFont2["AlternativeFont6"] = "ansiAlternativeFont6";
        ANSIFont2["AlternativeFont7"] = "ansiAlternativeFont7";
        ANSIFont2["AlternativeFont8"] = "ansiAlternativeFont8";
        ANSIFont2["AlternativeFont9"] = "ansiAlternativeFont9";
      })(ANSIFont || (exports3.ANSIFont = ANSIFont = {}));
      var ANSIColor;
      (function(ANSIColor2) {
        ANSIColor2["Black"] = "ansiBlack";
        ANSIColor2["Red"] = "ansiRed";
        ANSIColor2["Green"] = "ansiGreen";
        ANSIColor2["Yellow"] = "ansiYellow";
        ANSIColor2["Blue"] = "ansiBlue";
        ANSIColor2["Magenta"] = "ansiMagenta";
        ANSIColor2["Cyan"] = "ansiCyan";
        ANSIColor2["White"] = "ansiWhite";
        ANSIColor2["BrightBlack"] = "ansiBrightBlack";
        ANSIColor2["BrightRed"] = "ansiBrightRed";
        ANSIColor2["BrightGreen"] = "ansiBrightGreen";
        ANSIColor2["BrightYellow"] = "ansiBrightYellow";
        ANSIColor2["BrightBlue"] = "ansiBrightBlue";
        ANSIColor2["BrightMagenta"] = "ansiBrightMagenta";
        ANSIColor2["BrightCyan"] = "ansiBrightCyan";
        ANSIColor2["BrightWhite"] = "ansiBrightWhite";
      })(ANSIColor || (exports3.ANSIColor = ANSIColor = {}));
      class ANSIOutput {
        //#region Private Properties
        /**
         * Gets or sets the parser state.
         */
        _parserState = ParserState.BufferingOutput;
        /**
         * Gets or sets the control sequence that's being parsed.
         */
        _controlSequence = "";
        /**
         * Gets or sets the SGR state.
         */
        _sgrState = void 0;
        /**
         * Gets or sets the current set of output lines.
         */
        _outputLines = [];
        /**
         * Gets or sets the output line.
         */
        _outputLine = 0;
        /**
         * Gets or sets the output column.
         */
        _outputColumn = 0;
        /**
         * Gets or sets the buffer.
         */
        _buffer = "";
        /**
         * Gets or sets a value which indicates whether there is a pending newline.
         */
        _pendingNewline = false;
        //#endregion Private Properties
        //#region Public Properties
        /**
         * Gets the output lines.
         */
        get outputLines() {
          this.flushBuffer();
          return this._outputLines;
        }
        //#endregion Public Properties
        //#region Public Static Methods
        /**
         * Processes output and returns the ANSIOutput lines of the output.
         * @param output The output to process.
         * @returns The ANSIOutput lines of the output.
         */
        static processOutput(output2) {
          const ansiOutput2 = new ANSIOutput();
          ansiOutput2.processOutput(output2);
          return ansiOutput2.outputLines;
        }
        //#endregion Public Static Methods
        //#region Public Methods
        /**
         * Processes output.
         * @param output The output to process.
         */
        processOutput(output2) {
          for (let i2 = 0; i2 < output2.length; i2++) {
            if (this._pendingNewline) {
              this.flushBuffer();
              this._outputLine++;
              this._outputColumn = 0;
              this._pendingNewline = false;
            }
            const char = output2.charAt(i2);
            if (this._parserState === ParserState.BufferingOutput) {
              if (char === "\x1B") {
                this.flushBuffer();
                this._parserState = ParserState.ControlSequenceStarted;
              } else if (char === "") {
                this.flushBuffer();
                this._parserState = ParserState.ParsingControlSequence;
              } else {
                this.processCharacter(char);
              }
            } else if (this._parserState === ParserState.ControlSequenceStarted) {
              if (char === "[") {
                this._parserState = ParserState.ParsingControlSequence;
              } else {
                this._parserState = ParserState.BufferingOutput;
                this.processCharacter(char);
              }
            } else if (this._parserState === ParserState.ParsingControlSequence) {
              this._controlSequence += char;
              if (char.match(/^[A-Za-z]$/)) {
                this.processControlSequence();
              }
            }
          }
          this.flushBuffer();
        }
        //#endregion Public Methods
        //#region Private Methods
        /**
         * Flushes the buffer to the output line.
         */
        flushBuffer() {
          for (let i2 = this._outputLines.length; i2 < this._outputLine + 1; i2++) {
            this._outputLines.push(new OutputLine());
          }
          if (this._buffer) {
            const outputLine = this._outputLines[this._outputLine];
            outputLine.insert(this._buffer, this._outputColumn, this._sgrState);
            this._outputColumn += this._buffer.length;
            this._buffer = "";
          }
        }
        /**
         * Processes a character.
         * @param char The character.
         */
        processCharacter(char) {
          switch (char) {
            // LF sets the pending newline flag.
            case "\n":
              this._pendingNewline = true;
              break;
            // CR flushes the buffer and sets the output column to 0.
            case "\r":
              this.flushBuffer();
              this._outputColumn = 0;
              break;
            // Buffer the character.
            default:
              this._buffer += char;
              break;
          }
        }
        /**
         * Processes a control sequence.
         */
        processControlSequence() {
          switch (this._controlSequence.charAt(this._controlSequence.length - 1)) {
            // CUU (Cursor Up).
            case "A":
              this.processCUU();
              break;
            // CUD (Cursor Down).
            case "B":
              this.processCUD();
              break;
            // CUF (Cursor Forward).
            case "C":
              this.processCUF();
              break;
            // CUB (Cursor Backward).
            case "D":
              this.processCUB();
              break;
            // CUP (Cursor Position).
            case "H":
              this.processCUP();
              break;
            // ED (Erase in Display).
            case "J":
              this.processED();
              break;
            // EL (Erase in Line).
            case "K":
              this.processEL();
              break;
            // SGR (Select Graphic Rendition).
            case "m":
              this.processSGR();
              break;
          }
          this._controlSequence = "";
          this._parserState = ParserState.BufferingOutput;
        }
        /**
         * Processes a CUU (Cursor Up) control sequence.
         */
        processCUU() {
          const match3 = this._controlSequence.match(/^([0-9]*)A$/);
          if (match3) {
            this._outputLine = Math.max(this._outputLine - rangeParam(match3[1], 1, 1), 0);
          }
        }
        /**
         * Processes a CUD (Cursor Down) control sequence.
         */
        processCUD() {
          const match3 = this._controlSequence.match(/^([0-9]*)B$/);
          if (match3) {
            this._outputLine = this._outputLine + rangeParam(match3[1], 1, 1);
          }
        }
        /**
         * Processes a CUF (Cursor Forward) control sequence.
         */
        processCUF() {
          const match3 = this._controlSequence.match(/^([0-9]*)C$/);
          if (match3) {
            this._outputColumn = this._outputColumn + rangeParam(match3[1], 1, 1);
          }
        }
        /**
         * Processes a CUB (Cursor Backward) control sequence.
         */
        processCUB() {
          const match3 = this._controlSequence.match(/^([0-9]*)D$/);
          if (match3) {
            this._outputColumn = Math.max(this._outputColumn - rangeParam(match3[1], 1, 1), 0);
          }
        }
        /**
         * Processes a CUP (Cursor Position) control sequence.
         */
        processCUP() {
          const match3 = this._controlSequence.match(/^([0-9]*)(?:;?([0-9]*))H$/);
          if (match3) {
            this._outputLine = rangeParam(match3[1], 1, 1) - 1;
            this._outputColumn = rangeParam(match3[2], 1, 1) - 1;
          }
        }
        /**
         * Processes an ED (Erase in Display) control sequence.
         */
        processED() {
          const match3 = this._controlSequence.match(/^([0-9]*)J$/);
          if (match3) {
            switch (getParam(match3[1], 0)) {
              // Clear from cursor to the end of the screen.
              case 0:
                this._outputLines[this._outputLine].clearToEndOfLine(this._outputColumn);
                for (let i2 = this._outputLine + 1; i2 < this._outputLines.length; i2++) {
                  this._outputLines[i2].clearEntireLine();
                }
                break;
              // Clear from cursor to the beginning of the screen.
              case 1:
                this._outputLines[this._outputLine].clearToBeginningOfLine(this._outputColumn);
                for (let i2 = 0; i2 < this._outputLine; i2++) {
                  this._outputLines[i2].clearEntireLine();
                }
                break;
              // Clear the entire screen.
              case 2:
                for (let i2 = 0; i2 < this._outputLines.length; i2++) {
                  this._outputLines[i2].clearEntireLine();
                }
                break;
            }
          }
        }
        /**
         * Processes an EL (Erase in Line) control sequence.
         */
        processEL() {
          const match3 = this._controlSequence.match(/^([0-9]*)K$/);
          if (match3) {
            const outputLine = this._outputLines[this._outputLine];
            switch (getParam(match3[1], 0)) {
              // Clear from cursor to the end of the line.
              case 0:
                outputLine.clearToEndOfLine(this._outputColumn);
                break;
              // Clear from cursor to the beginning of the line.
              case 1:
                outputLine.clearToBeginningOfLine(this._outputColumn);
                break;
              // Clear the entire line.
              case 2:
                outputLine.clearEntireLine();
                break;
            }
          }
        }
        /**
         * Processes an SGR (Select Graphic Rendition) control sequence.
         */
        processSGR() {
          const sgrState = this._sgrState ? this._sgrState.copy() : new SGRState();
          const sgrParams = this._controlSequence.slice(0, -1).split(";").map((sgrParam) => sgrParam === "" ? SGRParam.Reset : parseInt(sgrParam, 10));
          for (let index = 0; index < sgrParams.length; index++) {
            const sgrParam = sgrParams[index];
            const processSetColor = () => {
              if (index + 1 === sgrParams.length) {
                return void 0;
              }
              switch (sgrParams[++index]) {
                // SGRColorParam.Color256 is an indexed color.
                case SGRParamColor.Color256: {
                  if (index + 1 === sgrParams.length) {
                    return void 0;
                  }
                  const colorIndex = sgrParams[++index];
                  switch (colorIndex) {
                    case SGRParamIndexedColor.Black:
                      return ANSIColor.Black;
                    case SGRParamIndexedColor.Red:
                      return ANSIColor.Red;
                    case SGRParamIndexedColor.Green:
                      return ANSIColor.Green;
                    case SGRParamIndexedColor.Yellow:
                      return ANSIColor.Yellow;
                    case SGRParamIndexedColor.Blue:
                      return ANSIColor.Blue;
                    case SGRParamIndexedColor.Magenta:
                      return ANSIColor.Magenta;
                    case SGRParamIndexedColor.Cyan:
                      return ANSIColor.Cyan;
                    case SGRParamIndexedColor.White:
                      return ANSIColor.White;
                    case SGRParamIndexedColor.BrightBlack:
                      return ANSIColor.BrightBlack;
                    case SGRParamIndexedColor.BrightRed:
                      return ANSIColor.BrightRed;
                    case SGRParamIndexedColor.BrightGreen:
                      return ANSIColor.BrightGreen;
                    case SGRParamIndexedColor.BrightYellow:
                      return ANSIColor.BrightYellow;
                    case SGRParamIndexedColor.BrightBlue:
                      return ANSIColor.BrightBlue;
                    case SGRParamIndexedColor.BrightMagenta:
                      return ANSIColor.BrightMagenta;
                    case SGRParamIndexedColor.BrightCyan:
                      return ANSIColor.BrightCyan;
                    case SGRParamIndexedColor.BrightWhite:
                      return ANSIColor.BrightWhite;
                    // Process other color indexes.
                    default:
                      if (colorIndex % 1 !== 0) {
                        return void 0;
                      }
                      if (colorIndex >= 16 && colorIndex <= 231) {
                        let colorNumber = colorIndex - 16;
                        let blue2 = colorNumber % 6;
                        colorNumber = (colorNumber - blue2) / 6;
                        let green2 = colorNumber % 6;
                        colorNumber = (colorNumber - green2) / 6;
                        let red2 = colorNumber;
                        blue2 = Math.round(blue2 * 255 / 5);
                        green2 = Math.round(green2 * 255 / 5);
                        red2 = Math.round(red2 * 255 / 5);
                        return "#" + twoDigitHex(red2) + twoDigitHex(green2) + twoDigitHex(blue2);
                      } else if (colorIndex >= 232 && colorIndex <= 255) {
                        const rgb = Math.round((colorIndex - 232) / 23 * 255);
                        const grayscale = twoDigitHex(rgb);
                        return "#" + grayscale + grayscale + grayscale;
                      } else {
                        return void 0;
                      }
                  }
                }
                // SGRParamColor.ColorRGB is an r;g;b color.
                case SGRParamColor.ColorRGB: {
                  const rgb = [0, 0, 0];
                  for (let i2 = 0; i2 < 3 && index + 1 < sgrParams.length; i2++) {
                    rgb[i2] = sgrParams[++index];
                  }
                  return "#" + twoDigitHex(rgb[0]) + twoDigitHex(rgb[1]) + twoDigitHex(rgb[2]);
                }
              }
              return void 0;
            };
            switch (sgrParam) {
              case SGRParam.Reset:
                sgrState.reset();
                break;
              case SGRParam.Bold:
                sgrState.setStyle(ANSIStyle.Bold);
                break;
              case SGRParam.Dim:
                sgrState.setStyle(ANSIStyle.Dim);
                break;
              case SGRParam.Italic:
                sgrState.setStyle(ANSIStyle.Italic);
                break;
              case SGRParam.Underlined:
                sgrState.setStyle(ANSIStyle.Underlined, ANSIStyle.DoubleUnderlined);
                break;
              case SGRParam.SlowBlink:
                sgrState.setStyle(ANSIStyle.SlowBlink, ANSIStyle.RapidBlink);
                break;
              case SGRParam.RapidBlink:
                sgrState.setStyle(ANSIStyle.RapidBlink, ANSIStyle.SlowBlink);
                break;
              case SGRParam.Reversed:
                sgrState.setReversed(true);
                break;
              case SGRParam.Hidden:
                sgrState.setStyle(ANSIStyle.Hidden);
                break;
              case SGRParam.CrossedOut:
                sgrState.setStyle(ANSIStyle.CrossedOut);
                break;
              case SGRParam.PrimaryFont:
                sgrState.setFont();
                break;
              case SGRParam.AlternativeFont1:
                sgrState.setFont(ANSIFont.AlternativeFont1);
                break;
              case SGRParam.AlternativeFont2:
                sgrState.setFont(ANSIFont.AlternativeFont2);
                break;
              case SGRParam.AlternativeFont3:
                sgrState.setFont(ANSIFont.AlternativeFont3);
                break;
              case SGRParam.AlternativeFont4:
                sgrState.setFont(ANSIFont.AlternativeFont4);
                break;
              case SGRParam.AlternativeFont5:
                sgrState.setFont(ANSIFont.AlternativeFont5);
                break;
              case SGRParam.AlternativeFont6:
                sgrState.setFont(ANSIFont.AlternativeFont6);
                break;
              case SGRParam.AlternativeFont7:
                sgrState.setFont(ANSIFont.AlternativeFont7);
                break;
              case SGRParam.AlternativeFont8:
                sgrState.setFont(ANSIFont.AlternativeFont8);
                break;
              case SGRParam.AlternativeFont9:
                sgrState.setFont(ANSIFont.AlternativeFont9);
                break;
              case SGRParam.Fraktur:
                sgrState.setStyle(ANSIStyle.Fraktur);
                break;
              case SGRParam.DoubleUnderlined:
                sgrState.setStyle(ANSIStyle.DoubleUnderlined, ANSIStyle.Underlined);
                break;
              case SGRParam.NormalIntensity:
                sgrState.deleteStyles(ANSIStyle.Bold, ANSIStyle.Dim);
                break;
              case SGRParam.NotItalicNotFraktur:
                sgrState.deleteStyles(ANSIStyle.Italic, ANSIStyle.Fraktur);
                break;
              case SGRParam.NotUnderlined:
                sgrState.deleteStyles(ANSIStyle.Underlined, ANSIStyle.DoubleUnderlined);
                break;
              case SGRParam.NotBlinking:
                sgrState.deleteStyles(ANSIStyle.SlowBlink, ANSIStyle.RapidBlink);
                break;
              case SGRParam.ProportionalSpacing:
                break;
              case SGRParam.NotReversed:
                sgrState.setReversed(false);
                break;
              case SGRParam.Reveal:
                sgrState.deleteStyles(ANSIStyle.Hidden);
                break;
              case SGRParam.NotCrossedOut:
                sgrState.deleteStyles(ANSIStyle.CrossedOut);
                break;
              case SGRParam.ForegroundBlack:
                sgrState.setForegroundColor(ANSIColor.Black);
                break;
              case SGRParam.ForegroundRed:
                sgrState.setForegroundColor(ANSIColor.Red);
                break;
              case SGRParam.ForegroundGreen:
                sgrState.setForegroundColor(ANSIColor.Green);
                break;
              case SGRParam.ForegroundYellow:
                sgrState.setForegroundColor(ANSIColor.Yellow);
                break;
              case SGRParam.ForegroundBlue:
                sgrState.setForegroundColor(ANSIColor.Blue);
                break;
              case SGRParam.ForegroundMagenta:
                sgrState.setForegroundColor(ANSIColor.Magenta);
                break;
              case SGRParam.ForegroundCyan:
                sgrState.setForegroundColor(ANSIColor.Cyan);
                break;
              case SGRParam.ForegroundWhite:
                sgrState.setForegroundColor(ANSIColor.White);
                break;
              case SGRParam.SetForeground: {
                const foregroundColor2 = processSetColor();
                if (foregroundColor2) {
                  sgrState.setForegroundColor(foregroundColor2);
                }
                break;
              }
              case SGRParam.DefaultForeground:
                sgrState.setForegroundColor();
                break;
              case SGRParam.BackgroundBlack:
                sgrState.setBackgroundColor(ANSIColor.Black);
                break;
              case SGRParam.BackgroundRed:
                sgrState.setBackgroundColor(ANSIColor.Red);
                break;
              case SGRParam.BackgroundGreen:
                sgrState.setBackgroundColor(ANSIColor.Green);
                break;
              case SGRParam.BackgroundYellow:
                sgrState.setBackgroundColor(ANSIColor.Yellow);
                break;
              case SGRParam.BackgroundBlue:
                sgrState.setBackgroundColor(ANSIColor.Blue);
                break;
              case SGRParam.BackgroundMagenta:
                sgrState.setBackgroundColor(ANSIColor.Magenta);
                break;
              case SGRParam.BackgroundCyan:
                sgrState.setBackgroundColor(ANSIColor.Cyan);
                break;
              case SGRParam.BackgroundWhite:
                sgrState.setBackgroundColor(ANSIColor.White);
                break;
              case SGRParam.SetBackground: {
                const backgroundColor2 = processSetColor();
                if (backgroundColor2) {
                  sgrState.setBackgroundColor(backgroundColor2);
                }
                break;
              }
              case SGRParam.DefaultBackground:
                sgrState.setBackgroundColor();
                break;
              case SGRParam.ForegroundBrightBlack:
                sgrState.setForegroundColor(ANSIColor.BrightBlack);
                break;
              case SGRParam.ForegroundBrightRed:
                sgrState.setForegroundColor(ANSIColor.BrightRed);
                break;
              case SGRParam.ForegroundBrightGreen:
                sgrState.setForegroundColor(ANSIColor.BrightGreen);
                break;
              case SGRParam.ForegroundBrightYellow:
                sgrState.setForegroundColor(ANSIColor.BrightYellow);
                break;
              case SGRParam.ForegroundBrightBlue:
                sgrState.setForegroundColor(ANSIColor.BrightBlue);
                break;
              case SGRParam.ForegroundBrightMagenta:
                sgrState.setForegroundColor(ANSIColor.BrightMagenta);
                break;
              case SGRParam.ForegroundBrightCyan:
                sgrState.setForegroundColor(ANSIColor.BrightCyan);
                break;
              case SGRParam.ForegroundBrightWhite:
                sgrState.setForegroundColor(ANSIColor.BrightWhite);
                break;
              case SGRParam.BackgroundBrightBlack:
                sgrState.setBackgroundColor(ANSIColor.BrightBlack);
                break;
              case SGRParam.BackgroundBrightRed:
                sgrState.setBackgroundColor(ANSIColor.BrightRed);
                break;
              case SGRParam.BackgroundBrightGreen:
                sgrState.setBackgroundColor(ANSIColor.BrightGreen);
                break;
              case SGRParam.BackgroundBrightYellow:
                sgrState.setBackgroundColor(ANSIColor.BrightYellow);
                break;
              case SGRParam.BackgroundBrightBlue:
                sgrState.setBackgroundColor(ANSIColor.BrightBlue);
                break;
              case SGRParam.BackgroundBrightMagenta:
                sgrState.setBackgroundColor(ANSIColor.BrightMagenta);
                break;
              case SGRParam.BackgroundBrightCyan:
                sgrState.setBackgroundColor(ANSIColor.BrightCyan);
                break;
              case SGRParam.BackgroundBrightWhite:
                sgrState.setBackgroundColor(ANSIColor.BrightWhite);
                break;
            }
          }
          if (!SGRState.equivalent(sgrState, this._sgrState)) {
            this._sgrState = sgrState;
          }
        }
      }
      exports3.ANSIOutput = ANSIOutput;
      var SGRParam;
      (function(SGRParam2) {
        SGRParam2[SGRParam2["Reset"] = 0] = "Reset";
        SGRParam2[SGRParam2["Bold"] = 1] = "Bold";
        SGRParam2[SGRParam2["Dim"] = 2] = "Dim";
        SGRParam2[SGRParam2["Italic"] = 3] = "Italic";
        SGRParam2[SGRParam2["Underlined"] = 4] = "Underlined";
        SGRParam2[SGRParam2["SlowBlink"] = 5] = "SlowBlink";
        SGRParam2[SGRParam2["RapidBlink"] = 6] = "RapidBlink";
        SGRParam2[SGRParam2["Reversed"] = 7] = "Reversed";
        SGRParam2[SGRParam2["Hidden"] = 8] = "Hidden";
        SGRParam2[SGRParam2["CrossedOut"] = 9] = "CrossedOut";
        SGRParam2[SGRParam2["PrimaryFont"] = 10] = "PrimaryFont";
        SGRParam2[SGRParam2["AlternativeFont1"] = 11] = "AlternativeFont1";
        SGRParam2[SGRParam2["AlternativeFont2"] = 12] = "AlternativeFont2";
        SGRParam2[SGRParam2["AlternativeFont3"] = 13] = "AlternativeFont3";
        SGRParam2[SGRParam2["AlternativeFont4"] = 14] = "AlternativeFont4";
        SGRParam2[SGRParam2["AlternativeFont5"] = 15] = "AlternativeFont5";
        SGRParam2[SGRParam2["AlternativeFont6"] = 16] = "AlternativeFont6";
        SGRParam2[SGRParam2["AlternativeFont7"] = 17] = "AlternativeFont7";
        SGRParam2[SGRParam2["AlternativeFont8"] = 18] = "AlternativeFont8";
        SGRParam2[SGRParam2["AlternativeFont9"] = 19] = "AlternativeFont9";
        SGRParam2[SGRParam2["Fraktur"] = 20] = "Fraktur";
        SGRParam2[SGRParam2["DoubleUnderlined"] = 21] = "DoubleUnderlined";
        SGRParam2[SGRParam2["NormalIntensity"] = 22] = "NormalIntensity";
        SGRParam2[SGRParam2["NotItalicNotFraktur"] = 23] = "NotItalicNotFraktur";
        SGRParam2[SGRParam2["NotUnderlined"] = 24] = "NotUnderlined";
        SGRParam2[SGRParam2["NotBlinking"] = 25] = "NotBlinking";
        SGRParam2[SGRParam2["ProportionalSpacing"] = 26] = "ProportionalSpacing";
        SGRParam2[SGRParam2["NotReversed"] = 27] = "NotReversed";
        SGRParam2[SGRParam2["Reveal"] = 28] = "Reveal";
        SGRParam2[SGRParam2["NotCrossedOut"] = 29] = "NotCrossedOut";
        SGRParam2[SGRParam2["ForegroundBlack"] = 30] = "ForegroundBlack";
        SGRParam2[SGRParam2["ForegroundRed"] = 31] = "ForegroundRed";
        SGRParam2[SGRParam2["ForegroundGreen"] = 32] = "ForegroundGreen";
        SGRParam2[SGRParam2["ForegroundYellow"] = 33] = "ForegroundYellow";
        SGRParam2[SGRParam2["ForegroundBlue"] = 34] = "ForegroundBlue";
        SGRParam2[SGRParam2["ForegroundMagenta"] = 35] = "ForegroundMagenta";
        SGRParam2[SGRParam2["ForegroundCyan"] = 36] = "ForegroundCyan";
        SGRParam2[SGRParam2["ForegroundWhite"] = 37] = "ForegroundWhite";
        SGRParam2[SGRParam2["SetForeground"] = 38] = "SetForeground";
        SGRParam2[SGRParam2["DefaultForeground"] = 39] = "DefaultForeground";
        SGRParam2[SGRParam2["BackgroundBlack"] = 40] = "BackgroundBlack";
        SGRParam2[SGRParam2["BackgroundRed"] = 41] = "BackgroundRed";
        SGRParam2[SGRParam2["BackgroundGreen"] = 42] = "BackgroundGreen";
        SGRParam2[SGRParam2["BackgroundYellow"] = 43] = "BackgroundYellow";
        SGRParam2[SGRParam2["BackgroundBlue"] = 44] = "BackgroundBlue";
        SGRParam2[SGRParam2["BackgroundMagenta"] = 45] = "BackgroundMagenta";
        SGRParam2[SGRParam2["BackgroundCyan"] = 46] = "BackgroundCyan";
        SGRParam2[SGRParam2["BackgroundWhite"] = 47] = "BackgroundWhite";
        SGRParam2[SGRParam2["SetBackground"] = 48] = "SetBackground";
        SGRParam2[SGRParam2["DefaultBackground"] = 49] = "DefaultBackground";
        SGRParam2[SGRParam2["DisableProportionalSpacing"] = 50] = "DisableProportionalSpacing";
        SGRParam2[SGRParam2["Framed"] = 51] = "Framed";
        SGRParam2[SGRParam2["Encircled"] = 52] = "Encircled";
        SGRParam2[SGRParam2["Overlined"] = 53] = "Overlined";
        SGRParam2[SGRParam2["NotFramedNotEncircled"] = 54] = "NotFramedNotEncircled";
        SGRParam2[SGRParam2["NotOverlined"] = 55] = "NotOverlined";
        SGRParam2[SGRParam2["SetUnderline"] = 58] = "SetUnderline";
        SGRParam2[SGRParam2["DefaultUnderline"] = 59] = "DefaultUnderline";
        SGRParam2[SGRParam2["IdeogramUnderlineOrRightSideLine"] = 60] = "IdeogramUnderlineOrRightSideLine";
        SGRParam2[SGRParam2["IdeogramDoubleUnderlineOrDoubleRightSideLine"] = 61] = "IdeogramDoubleUnderlineOrDoubleRightSideLine";
        SGRParam2[SGRParam2["IdeogramOverlineOrLeftSideLine"] = 62] = "IdeogramOverlineOrLeftSideLine";
        SGRParam2[SGRParam2["IdeogramDoubleOverlineOrDoubleLeftSideLine"] = 63] = "IdeogramDoubleOverlineOrDoubleLeftSideLine";
        SGRParam2[SGRParam2["IdeogramStressMarking"] = 64] = "IdeogramStressMarking";
        SGRParam2[SGRParam2["NoIdeogramAttributes"] = 65] = "NoIdeogramAttributes";
        SGRParam2[SGRParam2["Superscript"] = 73] = "Superscript";
        SGRParam2[SGRParam2["Subscript"] = 74] = "Subscript";
        SGRParam2[SGRParam2["NotSuperscriptNotSubscript"] = 75] = "NotSuperscriptNotSubscript";
        SGRParam2[SGRParam2["ForegroundBrightBlack"] = 90] = "ForegroundBrightBlack";
        SGRParam2[SGRParam2["ForegroundBrightRed"] = 91] = "ForegroundBrightRed";
        SGRParam2[SGRParam2["ForegroundBrightGreen"] = 92] = "ForegroundBrightGreen";
        SGRParam2[SGRParam2["ForegroundBrightYellow"] = 93] = "ForegroundBrightYellow";
        SGRParam2[SGRParam2["ForegroundBrightBlue"] = 94] = "ForegroundBrightBlue";
        SGRParam2[SGRParam2["ForegroundBrightMagenta"] = 95] = "ForegroundBrightMagenta";
        SGRParam2[SGRParam2["ForegroundBrightCyan"] = 96] = "ForegroundBrightCyan";
        SGRParam2[SGRParam2["ForegroundBrightWhite"] = 97] = "ForegroundBrightWhite";
        SGRParam2[SGRParam2["BackgroundBrightBlack"] = 100] = "BackgroundBrightBlack";
        SGRParam2[SGRParam2["BackgroundBrightRed"] = 101] = "BackgroundBrightRed";
        SGRParam2[SGRParam2["BackgroundBrightGreen"] = 102] = "BackgroundBrightGreen";
        SGRParam2[SGRParam2["BackgroundBrightYellow"] = 103] = "BackgroundBrightYellow";
        SGRParam2[SGRParam2["BackgroundBrightBlue"] = 104] = "BackgroundBrightBlue";
        SGRParam2[SGRParam2["BackgroundBrightMagenta"] = 105] = "BackgroundBrightMagenta";
        SGRParam2[SGRParam2["BackgroundBrightCyan"] = 106] = "BackgroundBrightCyan";
        SGRParam2[SGRParam2["BackgroundBrightWhite"] = 107] = "BackgroundBrightWhite";
      })(SGRParam || (SGRParam = {}));
      var SGRParamColor;
      (function(SGRParamColor2) {
        SGRParamColor2[SGRParamColor2["Color256"] = 5] = "Color256";
        SGRParamColor2[SGRParamColor2["ColorRGB"] = 2] = "ColorRGB";
      })(SGRParamColor || (SGRParamColor = {}));
      var SGRParamIndexedColor;
      (function(SGRParamIndexedColor2) {
        SGRParamIndexedColor2[SGRParamIndexedColor2["Black"] = 0] = "Black";
        SGRParamIndexedColor2[SGRParamIndexedColor2["Red"] = 1] = "Red";
        SGRParamIndexedColor2[SGRParamIndexedColor2["Green"] = 2] = "Green";
        SGRParamIndexedColor2[SGRParamIndexedColor2["Yellow"] = 3] = "Yellow";
        SGRParamIndexedColor2[SGRParamIndexedColor2["Blue"] = 4] = "Blue";
        SGRParamIndexedColor2[SGRParamIndexedColor2["Magenta"] = 5] = "Magenta";
        SGRParamIndexedColor2[SGRParamIndexedColor2["Cyan"] = 6] = "Cyan";
        SGRParamIndexedColor2[SGRParamIndexedColor2["White"] = 7] = "White";
        SGRParamIndexedColor2[SGRParamIndexedColor2["BrightBlack"] = 8] = "BrightBlack";
        SGRParamIndexedColor2[SGRParamIndexedColor2["BrightRed"] = 9] = "BrightRed";
        SGRParamIndexedColor2[SGRParamIndexedColor2["BrightGreen"] = 10] = "BrightGreen";
        SGRParamIndexedColor2[SGRParamIndexedColor2["BrightYellow"] = 11] = "BrightYellow";
        SGRParamIndexedColor2[SGRParamIndexedColor2["BrightBlue"] = 12] = "BrightBlue";
        SGRParamIndexedColor2[SGRParamIndexedColor2["BrightMagenta"] = 13] = "BrightMagenta";
        SGRParamIndexedColor2[SGRParamIndexedColor2["BrightCyan"] = 14] = "BrightCyan";
        SGRParamIndexedColor2[SGRParamIndexedColor2["BrightWhite"] = 15] = "BrightWhite";
      })(SGRParamIndexedColor || (SGRParamIndexedColor = {}));
      var ParserState;
      (function(ParserState2) {
        ParserState2[ParserState2["BufferingOutput"] = 0] = "BufferingOutput";
        ParserState2[ParserState2["ControlSequenceStarted"] = 1] = "ControlSequenceStarted";
        ParserState2[ParserState2["ParsingControlSequence"] = 2] = "ParsingControlSequence";
      })(ParserState || (ParserState = {}));
      class SGRState {
        //#region Private Properties.
        /**
         * Gets or sets the styles.
         */
        _styles;
        /**
         * Gets or sets the foreground color.
         */
        _foregroundColor;
        /**
         * Gets or sets the background color.
         */
        _backgroundColor;
        /**
         * Gets or sets the underlined color.
         */
        _underlinedColor;
        /**
         * Gets or sets a value which indicates whether the foreground and background colors are
         * reversed.
         */
        _reversed;
        /**
         * Gets or sets the font.
         */
        _font;
        //#endregion Private Properties.
        //#region Public Methods
        /**
         * Resets the SGRState.
         */
        reset() {
          this._styles = void 0;
          this._foregroundColor = void 0;
          this._backgroundColor = void 0;
          this._underlinedColor = void 0;
          this._reversed = void 0;
          this._font = void 0;
        }
        /**
         * Creates a copy of the SGRState.
         * @returns The copy of the SGRState.
         */
        copy() {
          const copy = new SGRState();
          if (this._styles && this._styles.size) {
            const styles2 = /* @__PURE__ */ new Set();
            this._styles.forEach((style2) => styles2.add(style2));
            copy._styles = styles2;
          }
          copy._foregroundColor = this._foregroundColor;
          copy._backgroundColor = this._backgroundColor;
          copy._underlinedColor = this._underlinedColor;
          copy._reversed = this._reversed;
          copy._font = this._font;
          return copy;
        }
        /**
         * Sets a style.
         * @param style The style to set.
         * @param stylesToDelete The styles to delete.
         */
        setStyle(style2, ...stylesToDelete) {
          if (this._styles) {
            for (const style3 of stylesToDelete) {
              this._styles.delete(style3);
            }
          } else {
            this._styles = /* @__PURE__ */ new Set();
          }
          this._styles.add(style2);
        }
        /**
         * Deletes styles.
         * @param stylesToDelete The styles to delete.
         */
        deleteStyles(...stylesToDelete) {
          if (this._styles) {
            for (const style2 of stylesToDelete) {
              this._styles.delete(style2);
            }
            if (!this._styles.size) {
              this._styles = void 0;
            }
          }
        }
        /**
         * Sets the foreground color.
         * @param color The foreground color.
         */
        setForegroundColor(color) {
          if (!this._reversed) {
            this._foregroundColor = color;
          } else {
            this._backgroundColor = color;
          }
        }
        /**
         * Sets the background color.
         * @param color The background color.
         */
        setBackgroundColor(color) {
          if (!this._reversed) {
            this._backgroundColor = color;
          } else {
            this._foregroundColor = color;
          }
        }
        /**
         * Sets reversed.
         * @param reversed A value which indicates whether the foreground and background colors are
         * reversed.
         */
        setReversed(reversed) {
          if (reversed) {
            if (!this._reversed) {
              this._reversed = true;
              this.reverseForegroundAndBackgroundColors();
            }
          } else {
            if (this._reversed) {
              this._reversed = void 0;
              this.reverseForegroundAndBackgroundColors();
            }
          }
        }
        /**
         * Sets the font.
         * @param font The font.
         */
        setFont(font) {
          this._font = font;
        }
        /**
         *
         * @param left
         * @param right
         * @returns
         */
        static equivalent(left2, right2) {
          const setReplacer = (_, value2) => value2 instanceof Set ? !value2.size ? void 0 : [...value2] : value2;
          return left2 === right2 || JSON.stringify(left2, setReplacer) === JSON.stringify(right2, setReplacer);
        }
        //#endregion Public Methods
        //#region ANSIFormat Implementation
        /**
         * Gets the styles.
         */
        get styles() {
          return !this._styles ? void 0 : [...this._styles];
        }
        /**
         * Gets the foreground color.
         */
        get foregroundColor() {
          if (this._backgroundColor && !this._foregroundColor) {
            switch (this._backgroundColor) {
              case ANSIColor.Black:
              case ANSIColor.BrightBlack:
              case ANSIColor.Red:
              case ANSIColor.BrightRed:
                return ANSIColor.White;
              case ANSIColor.Green:
              case ANSIColor.BrightGreen:
              case ANSIColor.Yellow:
              case ANSIColor.BrightYellow:
              case ANSIColor.Blue:
              case ANSIColor.BrightBlue:
              case ANSIColor.Magenta:
              case ANSIColor.BrightMagenta:
              case ANSIColor.Cyan:
              case ANSIColor.BrightCyan:
              case ANSIColor.White:
              case ANSIColor.BrightWhite:
                return ANSIColor.Black;
            }
          }
          return this._foregroundColor;
        }
        /**
         * Gets the background color.
         */
        get backgroundColor() {
          return this._backgroundColor;
        }
        /**
         * Gets the underlined color.
         */
        get underlinedColor() {
          return this._underlinedColor;
        }
        /**
         * Gets the font.
         */
        get font() {
          return this._font;
        }
        //#endregion ANSIFormat Implementation
        //#region Private Methods
        /**
         * Reverses the foreground and background colors.
         */
        reverseForegroundAndBackgroundColors() {
          const foregroundColor2 = this._foregroundColor;
          this._foregroundColor = this._backgroundColor;
          this._backgroundColor = foregroundColor2;
        }
      }
      class OutputLine {
        //#region Private Properties
        /**
         * Gets the identifier.
         */
        _id = generateId();
        /**
         * Gets or sets the output runs.
         */
        _outputRuns = [];
        /**
         * Gets or sets the total length.
         */
        _totalLength = 0;
        //#endregion Private Properties
        //#region Public Methods
        /**
         * Clears the entire output line.
         */
        clearEntireLine() {
          if (this._totalLength) {
            this._outputRuns = [new OutputRun2(" ".repeat(this._totalLength))];
          }
        }
        /**
         * Clears to the end of the output line.
         * @param column The column at which to clear from.
         */
        clearToEndOfLine(column2) {
          column2 = Math.max(column2, 0);
          if (column2 >= this._totalLength) {
            return;
          }
          if (column2 === 0) {
            this.clearEntireLine();
            return;
          }
          let leftOffset = 0;
          let leftOutputRun;
          let leftOutputRunIndex = void 0;
          for (let index = 0; index < this._outputRuns.length; index++) {
            const outputRun = this._outputRuns[index];
            if (column2 < leftOffset + outputRun.text.length) {
              leftOutputRun = outputRun;
              leftOutputRunIndex = index;
              break;
            }
            leftOffset += outputRun.text.length;
          }
          if (leftOutputRun === void 0 || leftOutputRunIndex === void 0) {
            return;
          }
          const leftTextLength = column2 - leftOffset;
          const erasureText = " ".repeat(this._totalLength - column2);
          const outputRuns = [];
          if (!leftTextLength) {
            outputRuns.push(new OutputRun2(erasureText));
          } else {
            const leftText = leftOutputRun.text.slice(0, leftTextLength);
            outputRuns.push(new OutputRun2(leftText, leftOutputRun.sgrState));
            outputRuns.push(new OutputRun2(erasureText));
          }
          this.outputRuns.splice(leftOutputRunIndex, this._outputRuns.length - leftOutputRunIndex, ...outputRuns);
        }
        /**
         * Clears to the beginning of the output line.
         * @param column The column at which to clear from.
         */
        clearToBeginningOfLine(column2) {
          column2 = Math.max(column2, 0);
          if (column2 === 0) {
            return;
          }
          if (column2 >= this._totalLength) {
            this.clearEntireLine();
            return;
          }
          let rightOffset = 0;
          let rightOutputRun;
          let rightOutputRunIndex = void 0;
          for (let index = this._outputRuns.length - 1; index >= 0; index--) {
            const outputRun = this._outputRuns[index];
            if (column2 >= rightOffset - outputRun.text.length) {
              rightOutputRun = outputRun;
              rightOutputRunIndex = index;
              break;
            }
            rightOffset -= outputRun.text.length;
          }
          if (rightOutputRun === void 0 || rightOutputRunIndex === void 0) {
            return;
          }
          const rightTextLength = rightOffset - column2;
          const erasureText = " ".repeat(column2);
          const outputRuns = [new OutputRun2(erasureText)];
          if (rightTextLength) {
            const rightOutputRunText = rightOutputRun.text.slice(-rightTextLength);
            outputRuns.push(new OutputRun2(rightOutputRunText, rightOutputRun.sgrState));
          }
          this.outputRuns.splice(0, this._outputRuns.length - rightOutputRunIndex, ...outputRuns);
        }
        /**
         * Inserts text into the output line.
         * @param text The text to insert.
         * @param column The column at which to insert the text.
         * @param sgrState The SGR state.
         */
        insert(text2, column2, sgrState) {
          if (!text2.length) {
            return;
          }
          if (column2 === this._totalLength) {
            this._totalLength += text2.length;
            if (this._outputRuns.length) {
              const lastOutputRun = this._outputRuns[this._outputRuns.length - 1];
              if (SGRState.equivalent(lastOutputRun.sgrState, sgrState)) {
                lastOutputRun.appendText(text2);
                return;
              }
            }
            this._outputRuns.push(new OutputRun2(text2, sgrState));
            return;
          }
          if (column2 > this._totalLength) {
            const spacer2 = " ".repeat(column2 - this._totalLength);
            this._totalLength += spacer2.length + text2.length;
            if (!sgrState && this._outputRuns.length) {
              const lastOutputRun = this._outputRuns[this._outputRuns.length - 1];
              if (!lastOutputRun.sgrState) {
                lastOutputRun.appendText(spacer2);
                lastOutputRun.appendText(text2);
                return;
              }
            }
            if (!sgrState) {
              this._outputRuns.push(new OutputRun2(spacer2 + text2));
            } else {
              this._outputRuns.push(new OutputRun2(spacer2));
              this._outputRuns.push(new OutputRun2(text2, sgrState));
            }
          }
          let leftOffset = 0;
          let leftOutputRunIndex = void 0;
          for (let index = 0; index < this._outputRuns.length; index++) {
            const outputRun = this._outputRuns[index];
            if (column2 < leftOffset + outputRun.text.length) {
              leftOutputRunIndex = index;
              break;
            }
            leftOffset += outputRun.text.length;
          }
          if (leftOutputRunIndex === void 0) {
            this._outputRuns.push(new OutputRun2(text2, sgrState));
            return;
          }
          if (column2 + text2.length >= this._totalLength) {
            const leftTextLength = column2 - leftOffset;
            const outputRuns2 = [];
            if (!leftTextLength) {
              outputRuns2.push(new OutputRun2(text2, sgrState));
            } else {
              const leftOutputRun = this._outputRuns[leftOutputRunIndex];
              const leftText = leftOutputRun.text.slice(0, leftTextLength);
              if (SGRState.equivalent(leftOutputRun.sgrState, sgrState)) {
                outputRuns2.push(new OutputRun2(leftText + text2, sgrState));
              } else {
                outputRuns2.push(new OutputRun2(leftText, leftOutputRun.sgrState));
                outputRuns2.push(new OutputRun2(text2, sgrState));
              }
            }
            this.outputRuns.splice(leftOutputRunIndex, 1, ...outputRuns2);
            this._totalLength = leftOffset + leftTextLength + text2.length;
            return;
          }
          let rightOffset = this._totalLength;
          let rightOutputRunIndex = void 0;
          for (let index = this._outputRuns.length - 1; index >= 0; index--) {
            const outputRun = this._outputRuns[index];
            if (column2 + text2.length > rightOffset - outputRun.text.length) {
              rightOutputRunIndex = index;
              break;
            }
            rightOffset -= outputRun.text.length;
          }
          if (rightOutputRunIndex === void 0) {
            this._outputRuns.push(new OutputRun2(text2, sgrState));
            return;
          }
          const outputRuns = [];
          const leftOutputRunTextLength = column2 - leftOffset;
          if (leftOutputRunTextLength) {
            const leftOutputRun = this._outputRuns[leftOutputRunIndex];
            const leftOutputRunText = leftOutputRun.text.slice(0, leftOutputRunTextLength);
            outputRuns.push(new OutputRun2(leftOutputRunText, leftOutputRun.sgrState));
          }
          outputRuns.push(new OutputRun2(text2, sgrState));
          const rightOutputRunTextLength = rightOffset - (column2 + text2.length);
          if (rightOutputRunTextLength) {
            const rightOutputRun = this._outputRuns[rightOutputRunIndex];
            const rightOutputRunText = rightOutputRun.text.slice(-rightOutputRunTextLength);
            outputRuns.push(new OutputRun2(rightOutputRunText, rightOutputRun.sgrState));
          }
          this._outputRuns.splice(leftOutputRunIndex, rightOutputRunIndex - leftOutputRunIndex + 1, ...outputRuns);
          if (this._outputRuns.length > 1) {
            this._outputRuns = OutputRun2.optimizeOutputRuns(this._outputRuns);
          }
          this._totalLength = this._outputRuns.reduce((totalLength, outputRun) => totalLength + outputRun.text.length, 0);
        }
        //#endregion Public Methods
        //#region ANSIOutputLine Implementation
        /**
         * Gets the identifier.
         */
        get id() {
          return this._id;
        }
        /**
         * Gets the output runs.
         */
        get outputRuns() {
          return this._outputRuns;
        }
      }
      class OutputRun2 {
        //#region Private Properties
        /**
         * Gets the identifier.
         */
        _id = generateId();
        /**
         * Gets the SGR state.
         */
        _sgrState;
        /**
         * Gets or sets the text.
         */
        _text;
        //#endregion Private Properties
        //#region Public Properties
        get sgrState() {
          return this._sgrState;
        }
        //#endregion Public Properties
        //#region Constructor
        /**
         * Constructor.
         * @param text The text.
         * @param sgrState The SGR state.
         */
        constructor(text2, sgrState) {
          this._sgrState = sgrState;
          this._text = text2;
        }
        //#endregion Constructor
        //#region Public Methods
        /**
         * Optimizes a an array of output runs by combining adjacent output runs with equivalent SGR
         * states.
         * @param outputRunsIn The output runs to optimize.
         * @returns The optimized output runs.
         */
        static optimizeOutputRuns(outputRunsIn) {
          const outputRunsOut = [outputRunsIn[0]];
          for (let i2 = 1, o = 0; i2 < outputRunsIn.length; i2++) {
            const outputRun = outputRunsIn[i2];
            if (SGRState.equivalent(outputRunsOut[o].sgrState, outputRun.sgrState)) {
              outputRunsOut[o]._text += outputRun.text;
            } else {
              outputRunsOut[++o] = outputRun;
            }
          }
          return outputRunsOut;
        }
        /**
         * Appends text to the end of the output run.
         * @param text The text to append.
         */
        appendText(text2) {
          this._text += text2;
        }
        //#endregion Public Methods
        //#region ANSIOutputRun Implementation
        /**
         * Gets the identifier.
         */
        get id() {
          return this._id;
        }
        /**
         * Gets the format.
         */
        get format() {
          return this._sgrState;
        }
        /**
         * Gets the text.
         */
        get text() {
          return this._text;
        }
      }
      const rangeParam = (value2, defaultValue, minValue) => {
        const param = getParam(value2, defaultValue);
        return Math.max(param, minValue);
      };
      const getParam = (value2, defaultValue) => {
        const param = parseInt(value2);
        return Number.isNaN(param) ? defaultValue : param;
      };
      const twoDigitHex = (value2) => {
        const hex = Math.max(Math.min(255, value2), 0).toString(16);
        return hex.length === 2 ? hex : "0" + hex;
      };
    });
  })(ansiOutput, ansiOutput.exports);
  return ansiOutput.exports;
}
var ansiOutputExports = requireAnsiOutput();
const ANSIDisplay = ({
  output: output2,
  style: style2,
  className: className2
}) => {
  const ansiOutput2 = new ansiOutputExports.ANSIOutput();
  ansiOutput2.processOutput(output2);
  const firstOutputIndex = ansiOutput2.outputLines.findIndex(
    (line2) => line2.outputRuns.length > 0
  );
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("ansi-display", className2), style: { ...style2 }, children: ansiOutput2.outputLines.map((line2, index) => {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "ansi-display-line", children: !line2.outputRuns.length ? index >= firstOutputIndex ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("br", {}, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/AnsiDisplay.tsx",
      lineNumber: 32,
      columnNumber: 17
    }, void 0) : null : line2.outputRuns.map((outputRun) => /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(OutputRun, { run: outputRun }, outputRun.id, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/AnsiDisplay.tsx",
      lineNumber: 36,
      columnNumber: 17
    }, void 0)) }, index, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/AnsiDisplay.tsx",
      lineNumber: 29,
      columnNumber: 11
    }, void 0);
  }) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/AnsiDisplay.tsx",
    lineNumber: 26,
    columnNumber: 5
  }, void 0);
};
const kForeground = 0;
const kBackground = 1;
const OutputRun = ({ run }) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("span", { style: computeCSSProperties(run), children: run.text }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/AnsiDisplay.tsx",
    lineNumber: 55,
    columnNumber: 10
  }, void 0);
};
const computeCSSProperties = (outputRun) => {
  return !outputRun.format ? {} : {
    ...computeStyles$2(outputRun.format.styles || []),
    ...computeForegroundBackgroundColor(
      kForeground,
      outputRun.format.foregroundColor
    ),
    ...computeForegroundBackgroundColor(
      kBackground,
      outputRun.format.backgroundColor
    )
  };
};
const computeStyles$2 = (styles2) => {
  let cssProperties = {};
  styles2.forEach((style2) => {
    switch (style2) {
      // Bold.
      case ansiOutputExports.ANSIStyle.Bold:
        cssProperties = { ...cssProperties, ...{ fontWeight: "bold" } };
        break;
      // Dim.
      case ansiOutputExports.ANSIStyle.Dim:
        cssProperties = { ...cssProperties, ...{ fontWeight: "lighter" } };
        break;
      // Italic.
      case ansiOutputExports.ANSIStyle.Italic:
        cssProperties = { ...cssProperties, ...{ fontStyle: "italic" } };
        break;
      // Underlined.
      case ansiOutputExports.ANSIStyle.Underlined:
        cssProperties = {
          ...cssProperties,
          ...{
            textDecorationLine: "underline",
            textDecorationStyle: "solid"
          }
        };
        break;
      // Slow blink.
      case ansiOutputExports.ANSIStyle.SlowBlink:
        cssProperties = {
          ...cssProperties,
          ...{ animation: "ansi-display-run-blink 1s linear infinite" }
        };
        break;
      // Rapid blink.
      case ansiOutputExports.ANSIStyle.RapidBlink:
        cssProperties = {
          ...cssProperties,
          ...{ animation: "ansi-display-run-blink 0.5s linear infinite" }
        };
        break;
      // Hidden.
      case ansiOutputExports.ANSIStyle.Hidden:
        cssProperties = { ...cssProperties, ...{ visibility: "hidden" } };
        break;
      // CrossedOut.
      case ansiOutputExports.ANSIStyle.CrossedOut:
        cssProperties = {
          ...cssProperties,
          ...{
            textDecorationLine: "line-through",
            textDecorationStyle: "solid"
          }
        };
        break;
      // TODO Fraktur
      // DoubleUnderlined.
      case ansiOutputExports.ANSIStyle.DoubleUnderlined:
        cssProperties = {
          ...cssProperties,
          ...{
            textDecorationLine: "underline",
            textDecorationStyle: "double"
          }
        };
        break;
    }
  });
  return cssProperties;
};
const isStandardANSIColor = (color) => {
  return Object.values(ansiOutputExports.ANSIColor).includes(color);
};
const computeForegroundBackgroundColor = (colorType, color) => {
  if (!color) {
    return {};
  }
  if (isStandardANSIColor(color)) {
    if (colorType === kForeground) {
      return { color: `var(--${color})` };
    } else {
      return { background: `var(--${color})` };
    }
  }
  if (colorType === kForeground) {
    return { color };
  } else {
    return { background: color };
  }
};
const CardHeader = ({
  id: id2,
  icon: icon2,
  type,
  label: label2,
  className: className2,
  children: children2
}) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "div",
    {
      className: clsx(
        "card-header-container",
        "text-style-label",
        className2,
        type === "modern" ? "card-header-modern" : ""
      ),
      id: id2 || "",
      children: [
        icon2 ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("i", { className: clsx("card-header-icon", icon2) }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/Card.tsx",
          lineNumber: 56,
          columnNumber: 9
        }, void 0) : /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "span",
          {
            className: clsx("card-header-icon", "card-header-icon-empty")
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/Card.tsx",
            lineNumber: 58,
            columnNumber: 9
          },
          void 0
        ),
        label2 ? label2 : "",
        " ",
        children2
      ]
    },
    void 0,
    true,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/Card.tsx",
      lineNumber: 46,
      columnNumber: 5
    },
    void 0
  );
};
const CardBody = ({
  id: id2,
  children: children2,
  className: className2,
  padded: padded2 = true
}) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "div",
    {
      className: clsx(
        "card-body",
        className2,
        !padded2 ? "card-no-padding" : void 0
      ),
      id: id2 || "",
      children: children2
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/Card.tsx",
      lineNumber: 74,
      columnNumber: 5
    },
    void 0
  );
};
const Card = ({ id: id2, children: children2, className: className2 }) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("card", className2), id: id2, children: children2 }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/Card.tsx",
    lineNumber: 89,
    columnNumber: 5
  }, void 0);
};
const container$h = "_container_1cz5u_1";
const traceback = "_traceback_1cz5u_5";
const styles$1j = {
  container: container$h,
  traceback
};
const ErrorPanel$1 = ({ error: error2, traceback: traceback2 }) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Card, { className: clsx(styles$1j.container), children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(CardHeader, { type: "modern", children: "Error" }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/error/ErrorPanel.tsx",
      lineNumber: 17,
      columnNumber: 7
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(CardBody, { children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("text-size-smaller"), children: error2 }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/error/ErrorPanel.tsx",
        lineNumber: 19,
        columnNumber: 9
      }, void 0),
      traceback2 && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        ANSIDisplay,
        {
          className: clsx(styles$1j.traceback, "text-size-smaller"),
          output: traceback2
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/error/ErrorPanel.tsx",
          lineNumber: 22,
          columnNumber: 11
        },
        void 0
      )
    ] }, void 0, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/error/ErrorPanel.tsx",
      lineNumber: 18,
      columnNumber: 7
    }, void 0)
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/error/ErrorPanel.tsx",
    lineNumber: 16,
    columnNumber: 5
  }, void 0);
};
const labeledValue = "_labeledValue_6obbb_1";
const row$4 = "_row_6obbb_6";
const column = "_column_6obbb_10";
const labeledValueLabel = "_labeledValueLabel_6obbb_14";
const styles$1i = {
  labeledValue,
  row: row$4,
  column,
  labeledValueLabel
};
const LabeledValue = ({
  layout = "column",
  style: style2,
  label: label2,
  children: children2,
  valueStyle,
  className: className2
}) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "div",
    {
      className: clsx(
        styles$1i.labeledValue,
        layout === "column" ? styles$1i.column : styles$1i.row,
        className2
      ),
      style: {
        ...style2
      },
      children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "div",
          {
            className: clsx(
              styles$1i.labeledValueLabel,
              "text-style-label",
              "text-style-secondary"
            ),
            children: label2
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/LabeledValue.tsx",
            lineNumber: 34,
            columnNumber: 7
          },
          void 0
        ),
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$1i.labeledValueValue), style: { ...valueStyle }, children: children2 }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/LabeledValue.tsx",
          lineNumber: 43,
          columnNumber: 7
        }, void 0)
      ]
    },
    void 0,
    true,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/LabeledValue.tsx",
      lineNumber: 24,
      columnNumber: 5
    },
    void 0
  );
};
var jsxRuntime = { exports: {} };
var reactJsxRuntime_development = {};
var hasRequiredReactJsxRuntime_development;
function requireReactJsxRuntime_development() {
  if (hasRequiredReactJsxRuntime_development) return reactJsxRuntime_development;
  hasRequiredReactJsxRuntime_development = 1;
  /**
   * @license React
   * react-jsx-runtime.development.js
   *
   * Copyright (c) Meta Platforms, Inc. and affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   */
  (function() {
    function getComponentNameFromType(type) {
      if (null == type) return null;
      if ("function" === typeof type)
        return type.$$typeof === REACT_CLIENT_REFERENCE ? null : type.displayName || type.name || null;
      if ("string" === typeof type) return type;
      switch (type) {
        case REACT_FRAGMENT_TYPE:
          return "Fragment";
        case REACT_PROFILER_TYPE:
          return "Profiler";
        case REACT_STRICT_MODE_TYPE:
          return "StrictMode";
        case REACT_SUSPENSE_TYPE:
          return "Suspense";
        case REACT_SUSPENSE_LIST_TYPE:
          return "SuspenseList";
        case REACT_ACTIVITY_TYPE:
          return "Activity";
      }
      if ("object" === typeof type)
        switch ("number" === typeof type.tag && console.error(
          "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."
        ), type.$$typeof) {
          case REACT_PORTAL_TYPE:
            return "Portal";
          case REACT_CONTEXT_TYPE:
            return type.displayName || "Context";
          case REACT_CONSUMER_TYPE:
            return (type._context.displayName || "Context") + ".Consumer";
          case REACT_FORWARD_REF_TYPE:
            var innerType = type.render;
            type = type.displayName;
            type || (type = innerType.displayName || innerType.name || "", type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef");
            return type;
          case REACT_MEMO_TYPE:
            return innerType = type.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type.type) || "Memo";
          case REACT_LAZY_TYPE:
            innerType = type._payload;
            type = type._init;
            try {
              return getComponentNameFromType(type(innerType));
            } catch (x) {
            }
        }
      return null;
    }
    function testStringCoercion(value2) {
      return "" + value2;
    }
    function checkKeyStringCoercion(value2) {
      try {
        testStringCoercion(value2);
        var JSCompiler_inline_result = false;
      } catch (e) {
        JSCompiler_inline_result = true;
      }
      if (JSCompiler_inline_result) {
        JSCompiler_inline_result = console;
        var JSCompiler_temp_const = JSCompiler_inline_result.error;
        var JSCompiler_inline_result$jscomp$0 = "function" === typeof Symbol && Symbol.toStringTag && value2[Symbol.toStringTag] || value2.constructor.name || "Object";
        JSCompiler_temp_const.call(
          JSCompiler_inline_result,
          "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",
          JSCompiler_inline_result$jscomp$0
        );
        return testStringCoercion(value2);
      }
    }
    function getTaskName(type) {
      if (type === REACT_FRAGMENT_TYPE) return "<>";
      if ("object" === typeof type && null !== type && type.$$typeof === REACT_LAZY_TYPE)
        return "<...>";
      try {
        var name2 = getComponentNameFromType(type);
        return name2 ? "<" + name2 + ">" : "<...>";
      } catch (x) {
        return "<...>";
      }
    }
    function getOwner() {
      var dispatcher = ReactSharedInternals.A;
      return null === dispatcher ? null : dispatcher.getOwner();
    }
    function UnknownOwner() {
      return Error("react-stack-top-frame");
    }
    function hasValidKey(config2) {
      if (hasOwnProperty2.call(config2, "key")) {
        var getter = Object.getOwnPropertyDescriptor(config2, "key").get;
        if (getter && getter.isReactWarning) return false;
      }
      return void 0 !== config2.key;
    }
    function defineKeyPropWarningGetter(props, displayName) {
      function warnAboutAccessingKey() {
        specialPropKeyWarningShown || (specialPropKeyWarningShown = true, console.error(
          "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",
          displayName
        ));
      }
      warnAboutAccessingKey.isReactWarning = true;
      Object.defineProperty(props, "key", {
        get: warnAboutAccessingKey,
        configurable: true
      });
    }
    function elementRefGetterWithDeprecationWarning() {
      var componentName = getComponentNameFromType(this.type);
      didWarnAboutElementRef[componentName] || (didWarnAboutElementRef[componentName] = true, console.error(
        "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."
      ));
      componentName = this.props.ref;
      return void 0 !== componentName ? componentName : null;
    }
    function ReactElement(type, key2, props, owner, debugStack, debugTask) {
      var refProp = props.ref;
      type = {
        $$typeof: REACT_ELEMENT_TYPE,
        type,
        key: key2,
        props,
        _owner: owner
      };
      null !== (void 0 !== refProp ? refProp : null) ? Object.defineProperty(type, "ref", {
        enumerable: false,
        get: elementRefGetterWithDeprecationWarning
      }) : Object.defineProperty(type, "ref", { enumerable: false, value: null });
      type._store = {};
      Object.defineProperty(type._store, "validated", {
        configurable: false,
        enumerable: false,
        writable: true,
        value: 0
      });
      Object.defineProperty(type, "_debugInfo", {
        configurable: false,
        enumerable: false,
        writable: true,
        value: null
      });
      Object.defineProperty(type, "_debugStack", {
        configurable: false,
        enumerable: false,
        writable: true,
        value: debugStack
      });
      Object.defineProperty(type, "_debugTask", {
        configurable: false,
        enumerable: false,
        writable: true,
        value: debugTask
      });
      Object.freeze && (Object.freeze(type.props), Object.freeze(type));
      return type;
    }
    function jsxDEVImpl(type, config2, maybeKey, isStaticChildren, debugStack, debugTask) {
      var children2 = config2.children;
      if (void 0 !== children2)
        if (isStaticChildren)
          if (isArrayImpl(children2)) {
            for (isStaticChildren = 0; isStaticChildren < children2.length; isStaticChildren++)
              validateChildKeys(children2[isStaticChildren]);
            Object.freeze && Object.freeze(children2);
          } else
            console.error(
              "React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead."
            );
        else validateChildKeys(children2);
      if (hasOwnProperty2.call(config2, "key")) {
        children2 = getComponentNameFromType(type);
        var keys2 = Object.keys(config2).filter(function(k) {
          return "key" !== k;
        });
        isStaticChildren = 0 < keys2.length ? "{key: someKey, " + keys2.join(": ..., ") + ": ...}" : "{key: someKey}";
        didWarnAboutKeySpread[children2 + isStaticChildren] || (keys2 = 0 < keys2.length ? "{" + keys2.join(": ..., ") + ": ...}" : "{}", console.error(
          'A props object containing a "key" prop is being spread into JSX:\n  let props = %s;\n  <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n  let props = %s;\n  <%s key={someKey} {...props} />',
          isStaticChildren,
          children2,
          keys2,
          children2
        ), didWarnAboutKeySpread[children2 + isStaticChildren] = true);
      }
      children2 = null;
      void 0 !== maybeKey && (checkKeyStringCoercion(maybeKey), children2 = "" + maybeKey);
      hasValidKey(config2) && (checkKeyStringCoercion(config2.key), children2 = "" + config2.key);
      if ("key" in config2) {
        maybeKey = {};
        for (var propName in config2)
          "key" !== propName && (maybeKey[propName] = config2[propName]);
      } else maybeKey = config2;
      children2 && defineKeyPropWarningGetter(
        maybeKey,
        "function" === typeof type ? type.displayName || type.name || "Unknown" : type
      );
      return ReactElement(
        type,
        children2,
        maybeKey,
        getOwner(),
        debugStack,
        debugTask
      );
    }
    function validateChildKeys(node2) {
      isValidElement(node2) ? node2._store && (node2._store.validated = 1) : "object" === typeof node2 && null !== node2 && node2.$$typeof === REACT_LAZY_TYPE && ("fulfilled" === node2._payload.status ? isValidElement(node2._payload.value) && node2._payload.value._store && (node2._payload.value._store.validated = 1) : node2._store && (node2._store.validated = 1));
    }
    function isValidElement(object2) {
      return "object" === typeof object2 && null !== object2 && object2.$$typeof === REACT_ELEMENT_TYPE;
    }
    var React = requireReact(), REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = Symbol.for("react.memo"), REACT_LAZY_TYPE = Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = Symbol.for("react.activity"), REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"), ReactSharedInternals = React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, hasOwnProperty2 = Object.prototype.hasOwnProperty, isArrayImpl = Array.isArray, createTask = console.createTask ? console.createTask : function() {
      return null;
    };
    React = {
      react_stack_bottom_frame: function(callStackForError) {
        return callStackForError();
      }
    };
    var specialPropKeyWarningShown;
    var didWarnAboutElementRef = {};
    var unknownOwnerDebugStack = React.react_stack_bottom_frame.bind(
      React,
      UnknownOwner
    )();
    var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));
    var didWarnAboutKeySpread = {};
    reactJsxRuntime_development.Fragment = REACT_FRAGMENT_TYPE;
    reactJsxRuntime_development.jsx = function(type, config2, maybeKey) {
      var trackActualOwner = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
      return jsxDEVImpl(
        type,
        config2,
        maybeKey,
        false,
        trackActualOwner ? Error("react-stack-top-frame") : unknownOwnerDebugStack,
        trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask
      );
    };
    reactJsxRuntime_development.jsxs = function(type, config2, maybeKey) {
      var trackActualOwner = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
      return jsxDEVImpl(
        type,
        config2,
        maybeKey,
        true,
        trackActualOwner ? Error("react-stack-top-frame") : unknownOwnerDebugStack,
        trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask
      );
    };
  })();
  return reactJsxRuntime_development;
}
var hasRequiredJsxRuntime;
function requireJsxRuntime() {
  if (hasRequiredJsxRuntime) return jsxRuntime.exports;
  hasRequiredJsxRuntime = 1;
  {
    jsxRuntime.exports = requireReactJsxRuntime_development();
  }
  return jsxRuntime.exports;
}
var jsxRuntimeExports = requireJsxRuntime();
const we = 0, zt = 1, qt = 2, kn = 4;
function un(t2) {
  return () => t2;
}
function fo(t2) {
  t2();
}
function ne(t2, e) {
  return (n2) => t2(e(n2));
}
function an(t2, e) {
  return () => t2(e);
}
function mo(t2, e) {
  return (n2) => t2(e, n2);
}
function We(t2) {
  return t2 !== void 0;
}
function po(...t2) {
  return () => {
    t2.map(fo);
  };
}
function Yt() {
}
function ve(t2, e) {
  return e(t2), t2;
}
function ho(t2, e) {
  return e(t2);
}
function X(...t2) {
  return t2;
}
function K(t2, e) {
  return t2(zt, e);
}
function G(t2, e) {
  t2(we, e);
}
function Ge(t2) {
  t2(qt);
}
function ot(t2) {
  return t2(kn);
}
function O(t2, e) {
  return K(t2, mo(e, we));
}
function Tt(t2, e) {
  const n2 = t2(zt, (o) => {
    n2(), e(o);
  });
  return n2;
}
function dn(t2) {
  let e, n2;
  return (o) => (r2) => {
    e = r2, n2 && clearTimeout(n2), n2 = setTimeout(() => {
      o(e);
    }, t2);
  };
}
function Fn(t2, e) {
  return t2 === e;
}
function Y(t2 = Fn) {
  let e;
  return (n2) => (o) => {
    t2(e, o) || (e = o, n2(o));
  };
}
function A(t2) {
  return (e) => (n2) => {
    t2(n2) && e(n2);
  };
}
function E(t2) {
  return (e) => ne(e, t2);
}
function Rt(t2) {
  return (e) => () => {
    e(t2);
  };
}
function S(t2, ...e) {
  const n2 = go(...e);
  return (o, r2) => {
    switch (o) {
      case qt:
        Ge(t2);
        return;
      case zt:
        return K(t2, n2(r2));
    }
  };
}
function bt(t2, e) {
  return (n2) => (o) => {
    n2(e = t2(e, o));
  };
}
function Dt(t2) {
  return (e) => (n2) => {
    t2 > 0 ? t2-- : e(n2);
  };
}
function kt(t2) {
  let e = null, n2;
  return (o) => (r2) => {
    e = r2, !n2 && (n2 = setTimeout(() => {
      n2 = void 0, o(e);
    }, t2));
  };
}
function N(...t2) {
  const e = new Array(t2.length);
  let n2 = 0, o = null;
  const r2 = Math.pow(2, t2.length) - 1;
  return t2.forEach((s, i2) => {
    const l2 = Math.pow(2, i2);
    K(s, (c2) => {
      const a2 = n2;
      n2 = n2 | l2, e[i2] = c2, a2 !== r2 && n2 === r2 && o && (o(), o = null);
    });
  }), (s) => (i2) => {
    const l2 = () => {
      s([i2].concat(e));
    };
    n2 === r2 ? l2() : o = l2;
  };
}
function go(...t2) {
  return (e) => t2.reduceRight(ho, e);
}
function Io(t2) {
  let e, n2;
  const o = () => e == null ? void 0 : e();
  return function(r2, s) {
    switch (r2) {
      case zt:
        return s ? n2 === s ? void 0 : (o(), n2 = s, e = K(t2, s), e) : (o(), Yt);
      case qt:
        o(), n2 = null;
        return;
    }
  };
}
function w(t2) {
  let e = t2;
  const n2 = $();
  return (o, r2) => {
    switch (o) {
      case we:
        e = r2;
        break;
      case zt: {
        r2(e);
        break;
      }
      case kn:
        return e;
    }
    return n2(o, r2);
  };
}
function ct(t2, e) {
  return ve(w(e), (n2) => O(t2, n2));
}
function $() {
  const t2 = [];
  return (e, n2) => {
    switch (e) {
      case we:
        t2.slice().forEach((o) => {
          o(n2);
        });
        return;
      case qt:
        t2.splice(0, t2.length);
        return;
      case zt:
        return t2.push(n2), () => {
          const o = t2.indexOf(n2);
          o > -1 && t2.splice(o, 1);
        };
    }
  };
}
function ht(t2) {
  return ve($(), (e) => O(t2, e));
}
function U(t2, e = [], { singleton: n2 } = { singleton: true }) {
  return {
    constructor: t2,
    dependencies: e,
    id: So(),
    singleton: n2
  };
}
const So = () => Symbol();
function xo(t2) {
  const e = /* @__PURE__ */ new Map(), n2 = ({ constructor: o, dependencies: r2, id: s, singleton: i2 }) => {
    if (i2 && e.has(s))
      return e.get(s);
    const l2 = o(r2.map((c2) => n2(c2)));
    return i2 && e.set(s, l2), l2;
  };
  return n2(t2);
}
function rt(...t2) {
  const e = $(), n2 = new Array(t2.length);
  let o = 0;
  const r2 = Math.pow(2, t2.length) - 1;
  return t2.forEach((s, i2) => {
    const l2 = Math.pow(2, i2);
    K(s, (c2) => {
      n2[i2] = c2, o = o | l2, o === r2 && G(e, n2);
    });
  }), function(s, i2) {
    switch (s) {
      case qt: {
        Ge(e);
        return;
      }
      case zt:
        return o === r2 && i2(n2), K(e, i2);
    }
  };
}
function V(t2, e = Fn) {
  return S(t2, Y(e));
}
function Le(...t2) {
  return function(e, n2) {
    switch (e) {
      case qt:
        return;
      case zt:
        return po(...t2.map((o) => K(o, n2)));
    }
  };
}
var mt = /* @__PURE__ */ ((t2) => (t2[t2.DEBUG = 0] = "DEBUG", t2[t2.INFO = 1] = "INFO", t2[t2.WARN = 2] = "WARN", t2[t2.ERROR = 3] = "ERROR", t2))(mt || {});
const To = {
  0: "debug",
  3: "error",
  1: "log",
  2: "warn"
}, Co = () => typeof globalThis > "u" ? window : globalThis, Vt$1 = U(
  () => {
    const t2 = w(
      3
      /* ERROR */
    );
    return {
      log: w((n2, o, r2 = 1) => {
        var i2;
        const s = (i2 = Co().VIRTUOSO_LOG_LEVEL) != null ? i2 : ot(t2);
        r2 >= s && console[To[r2]](
          "%creact-virtuoso: %c%s %o",
          "color: #0253b3; font-weight: bold",
          "color: initial",
          n2,
          o
        );
      }),
      logLevel: t2
    };
  },
  [],
  { singleton: true }
);
function Ht(t2, e, n2) {
  return _e(t2, e, n2).callbackRef;
}
function _e(t2, e, n2) {
  const o = React20.useRef(null);
  let r2 = (i2) => {
  };
  const s = React20.useMemo(() => typeof ResizeObserver < "u" ? new ResizeObserver((i2) => {
    const l2 = () => {
      const c2 = i2[0].target;
      c2.offsetParent !== null && t2(c2);
    };
    n2 ? l2() : requestAnimationFrame(l2);
  }) : null, [t2, n2]);
  return r2 = (i2) => {
    i2 && e ? (s == null || s.observe(i2), o.current = i2) : (o.current && (s == null || s.unobserve(o.current)), o.current = null);
  }, { callbackRef: r2, ref: o };
}
function On(t2, e, n2, o, r2, s, i2, l2, c2) {
  const a2 = React20.useCallback(
    (m) => {
      const x = wo(m.children, e, l2 ? "offsetWidth" : "offsetHeight", r2);
      let h = m.parentElement;
      for (; !h.dataset.virtuosoScroller; )
        h = h.parentElement;
      const I = h.lastElementChild.dataset.viewportType === "window";
      let C;
      I && (C = h.ownerDocument.defaultView);
      const v = i2 ? l2 ? i2.scrollLeft : i2.scrollTop : I ? l2 ? C.scrollX || C.document.documentElement.scrollLeft : C.scrollY || C.document.documentElement.scrollTop : l2 ? h.scrollLeft : h.scrollTop, g = i2 ? l2 ? i2.scrollWidth : i2.scrollHeight : I ? l2 ? C.document.documentElement.scrollWidth : C.document.documentElement.scrollHeight : l2 ? h.scrollWidth : h.scrollHeight, p = i2 ? l2 ? i2.offsetWidth : i2.offsetHeight : I ? l2 ? C.innerWidth : C.innerHeight : l2 ? h.offsetWidth : h.offsetHeight;
      o({
        scrollHeight: g,
        scrollTop: Math.max(v, 0),
        viewportHeight: p
      }), s == null || s(
        l2 ? fn("column-gap", getComputedStyle(m).columnGap, r2) : fn("row-gap", getComputedStyle(m).rowGap, r2)
      ), x !== null && t2(x);
    },
    [t2, e, r2, s, i2, o, l2]
  );
  return _e(a2, n2, c2);
}
function wo(t2, e, n2, o) {
  const r2 = t2.length;
  if (r2 === 0)
    return null;
  const s = [];
  for (let i2 = 0; i2 < r2; i2++) {
    const l2 = t2.item(i2);
    if (l2.dataset.index === void 0)
      continue;
    const c2 = parseInt(l2.dataset.index), a2 = parseFloat(l2.dataset.knownSize), m = e(l2, n2);
    if (m === 0 && o("Zero-sized element, this should not happen", { child: l2 }, mt.ERROR), m === a2)
      continue;
    const x = s[s.length - 1];
    s.length === 0 || x.size !== m || x.endIndex !== c2 - 1 ? s.push({ endIndex: c2, size: m, startIndex: c2 }) : s[s.length - 1].endIndex++;
  }
  return s;
}
function fn(t2, e, n2) {
  return e !== "normal" && !(e != null && e.endsWith("px")) && n2(`${t2} was not resolved to pixel value correctly`, e, mt.WARN), e === "normal" ? 0 : parseInt(e != null ? e : "0", 10);
}
function Ne(t2, e, n2) {
  const o = React20.useRef(null), r2 = React20.useCallback(
    (c2) => {
      if (!(c2 != null && c2.offsetParent))
        return;
      const a2 = c2.getBoundingClientRect(), m = a2.width;
      let x, h;
      if (e) {
        const I = e.getBoundingClientRect(), C = a2.top - I.top;
        h = I.height - Math.max(0, C), x = C + e.scrollTop;
      } else {
        const I = i2.current.ownerDocument.defaultView;
        h = I.innerHeight - Math.max(0, a2.top), x = a2.top + I.scrollY;
      }
      o.current = {
        offsetTop: x,
        visibleHeight: h,
        visibleWidth: m
      }, t2(o.current);
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [t2, e]
  ), { callbackRef: s, ref: i2 } = _e(r2, true, n2), l2 = React20.useCallback(() => {
    r2(i2.current);
  }, [r2, i2]);
  return React20.useEffect(() => {
    var c2;
    if (e) {
      e.addEventListener("scroll", l2);
      const a2 = new ResizeObserver(() => {
        requestAnimationFrame(l2);
      });
      return a2.observe(e), () => {
        e.removeEventListener("scroll", l2), a2.unobserve(e);
      };
    } else {
      const a2 = (c2 = i2.current) == null ? void 0 : c2.ownerDocument.defaultView;
      return a2 == null || a2.addEventListener("scroll", l2), a2 == null || a2.addEventListener("resize", l2), () => {
        a2 == null || a2.removeEventListener("scroll", l2), a2 == null || a2.removeEventListener("resize", l2);
      };
    }
  }, [l2, e, i2]), s;
}
const at2 = U(
  () => {
    const t2 = $(), e = $(), n2 = w(0), o = $(), r2 = w(0), s = $(), i2 = $(), l2 = w(0), c2 = w(0), a2 = w(0), m = w(0), x = $(), h = $(), I = w(false), C = w(false), v = w(false);
    return O(
      S(
        t2,
        E(({ scrollTop: g }) => g)
      ),
      e
    ), O(
      S(
        t2,
        E(({ scrollHeight: g }) => g)
      ),
      i2
    ), O(e, r2), {
      deviation: n2,
      fixedFooterHeight: a2,
      fixedHeaderHeight: c2,
      footerHeight: m,
      headerHeight: l2,
      horizontalDirection: C,
      scrollBy: h,
      // input
      scrollContainerState: t2,
      scrollHeight: i2,
      scrollingInProgress: I,
      // signals
      scrollTo: x,
      scrollTop: e,
      skipAnimationFrameInResizeObserver: v,
      smoothScrollTargetReached: o,
      // state
      statefulScrollTop: r2,
      viewportHeight: s
    };
  },
  [],
  { singleton: true }
), oe = { lvl: 0 };
function Ln(t2, e) {
  const n2 = t2.length;
  if (n2 === 0)
    return [];
  let { index: o, value: r2 } = e(t2[0]);
  const s = [];
  for (let i2 = 1; i2 < n2; i2++) {
    const { index: l2, value: c2 } = e(t2[i2]);
    s.push({ end: l2 - 1, start: o, value: r2 }), o = l2, r2 = c2;
  }
  return s.push({ end: 1 / 0, start: o, value: r2 }), s;
}
function j(t2) {
  return t2 === oe;
}
function re(t2, e) {
  if (!j(t2))
    return e === t2.k ? t2.v : e < t2.k ? re(t2.l, e) : re(t2.r, e);
}
function wt(t2, e, n2 = "k") {
  if (j(t2))
    return [-1 / 0, void 0];
  if (Number(t2[n2]) === e)
    return [t2.k, t2.v];
  if (Number(t2[n2]) < e) {
    const o = wt(t2.r, e, n2);
    return o[0] === -1 / 0 ? [t2.k, t2.v] : o;
  }
  return wt(t2.l, e, n2);
}
function pt(t2, e, n2) {
  return j(t2) ? Pn(e, n2, 1) : e === t2.k ? st(t2, { k: e, v: n2 }) : e < t2.k ? mn(st(t2, { l: pt(t2.l, e, n2) })) : mn(st(t2, { r: pt(t2.r, e, n2) }));
}
function jt() {
  return oe;
}
function ye(t2, e, n2) {
  if (j(t2))
    return [];
  const o = wt(t2, e)[0];
  return vo(Ve(t2, o, n2));
}
function ze(t2, e) {
  if (j(t2)) return oe;
  const { k: n2, l: o, r: r2 } = t2;
  if (e === n2) {
    if (j(o))
      return r2;
    if (j(r2))
      return o;
    {
      const [s, i2] = Vn(o);
      return ge(st(t2, { k: s, l: zn(o), v: i2 }));
    }
  } else return e < n2 ? ge(st(t2, { l: ze(o, e) })) : ge(st(t2, { r: ze(r2, e) }));
}
function Gt(t2) {
  return j(t2) ? [] : [...Gt(t2.l), { k: t2.k, v: t2.v }, ...Gt(t2.r)];
}
function Ve(t2, e, n2) {
  if (j(t2))
    return [];
  const { k: o, l: r2, r: s, v: i2 } = t2;
  let l2 = [];
  return o > e && (l2 = l2.concat(Ve(r2, e, n2))), o >= e && o <= n2 && l2.push({ k: o, v: i2 }), o <= n2 && (l2 = l2.concat(Ve(s, e, n2))), l2;
}
function ge(t2) {
  const { l: e, lvl: n2, r: o } = t2;
  if (o.lvl >= n2 - 1 && e.lvl >= n2 - 1)
    return t2;
  if (n2 > o.lvl + 1) {
    if (Ee(e))
      return An(st(t2, { lvl: n2 - 1 }));
    if (!j(e) && !j(e.r))
      return st(e.r, {
        l: st(e, { r: e.r.l }),
        lvl: n2,
        r: st(t2, {
          l: e.r.r,
          lvl: n2 - 1
        })
      });
    throw new Error("Unexpected empty nodes");
  } else {
    if (Ee(t2))
      return Pe(st(t2, { lvl: n2 - 1 }));
    if (!j(o) && !j(o.l)) {
      const r2 = o.l, s = Ee(r2) ? o.lvl - 1 : o.lvl;
      return st(r2, {
        l: st(t2, {
          lvl: n2 - 1,
          r: r2.l
        }),
        lvl: r2.lvl + 1,
        r: Pe(st(o, { l: r2.r, lvl: s }))
      });
    } else
      throw new Error("Unexpected empty nodes");
  }
}
function st(t2, e) {
  return Pn(
    e.k !== void 0 ? e.k : t2.k,
    e.v !== void 0 ? e.v : t2.v,
    e.lvl !== void 0 ? e.lvl : t2.lvl,
    e.l !== void 0 ? e.l : t2.l,
    e.r !== void 0 ? e.r : t2.r
  );
}
function zn(t2) {
  return j(t2.r) ? t2.l : ge(st(t2, { r: zn(t2.r) }));
}
function Ee(t2) {
  return j(t2) || t2.lvl > t2.r.lvl;
}
function Vn(t2) {
  return j(t2.r) ? [t2.k, t2.v] : Vn(t2.r);
}
function Pn(t2, e, n2, o = oe, r2 = oe) {
  return { k: t2, l: o, lvl: n2, r: r2, v: e };
}
function mn(t2) {
  return Pe(An(t2));
}
function An(t2) {
  const { l: e } = t2;
  return !j(e) && e.lvl === t2.lvl ? st(e, { r: st(t2, { l: e.r }) }) : t2;
}
function Pe(t2) {
  const { lvl: e, r: n2 } = t2;
  return !j(n2) && !j(n2.r) && n2.lvl === e && n2.r.lvl === e ? st(n2, { l: st(t2, { r: n2.l }), lvl: e + 1 }) : t2;
}
function vo(t2) {
  return Ln(t2, ({ k: e, v: n2 }) => ({ index: e, value: n2 }));
}
function Mn(t2, e) {
  return !!(t2 && t2.startIndex === e.startIndex && t2.endIndex === e.endIndex);
}
function se(t2, e) {
  return !!(t2 && t2[0] === e[0] && t2[1] === e[1]);
}
const De = U(
  () => ({ recalcInProgress: w(false) }),
  [],
  { singleton: true }
);
function Wn(t2, e, n2) {
  return t2[Se(t2, e, n2)];
}
function Se(t2, e, n2, o = 0) {
  let r2 = t2.length - 1;
  for (; o <= r2; ) {
    const s = Math.floor((o + r2) / 2), i2 = t2[s], l2 = n2(i2, e);
    if (l2 === 0)
      return s;
    if (l2 === -1) {
      if (r2 - o < 2)
        return s - 1;
      r2 = s - 1;
    } else {
      if (r2 === o)
        return s;
      o = s + 1;
    }
  }
  throw new Error(`Failed binary finding record in array - ${t2.join(",")}, searched for ${e}`);
}
function yo(t2, e, n2, o) {
  const r2 = Se(t2, e, o), s = Se(t2, n2, o, r2);
  return t2.slice(r2, s + 1);
}
function vt$1(t2, e) {
  return Math.round(t2.getBoundingClientRect()[e]);
}
function Re(t2) {
  return !j(t2.groupOffsetTree);
}
function $e({ index: t2 }, e) {
  return e === t2 ? 0 : e < t2 ? -1 : 1;
}
function Ro() {
  return {
    groupIndices: [],
    groupOffsetTree: jt(),
    lastIndex: 0,
    lastOffset: 0,
    lastSize: 0,
    offsetTree: [],
    sizeTree: jt()
  };
}
function bo(t2, e) {
  let n2 = j(t2) ? 0 : 1 / 0;
  for (const o of e) {
    const { endIndex: r2, size: s, startIndex: i2 } = o;
    if (n2 = Math.min(n2, i2), j(t2)) {
      t2 = pt(t2, 0, s);
      continue;
    }
    const l2 = ye(t2, i2 - 1, r2 + 1);
    if (l2.some(Lo(o)))
      continue;
    let c2 = false, a2 = false;
    for (const { end: m, start: x, value: h } of l2)
      c2 ? (r2 >= x || s === h) && (t2 = ze(t2, x)) : (a2 = h !== s, c2 = true), m > r2 && r2 >= x && h !== s && (t2 = pt(t2, r2 + 1, h));
    a2 && (t2 = pt(t2, i2, s));
  }
  return [t2, n2];
}
function Ho(t2) {
  return typeof t2.groupIndex < "u";
}
function Eo({ offset: t2 }, e) {
  return e === t2 ? 0 : e < t2 ? -1 : 1;
}
function ie(t2, e, n2) {
  if (e.length === 0)
    return 0;
  const { index: o, offset: r2, size: s } = Wn(e, t2, $e), i2 = t2 - o, l2 = s * i2 + (i2 - 1) * n2 + r2;
  return l2 > 0 ? l2 + n2 : l2;
}
function Gn(t2, e) {
  if (!Re(e))
    return t2;
  let n2 = 0;
  for (; e.groupIndices[n2] <= t2 + n2; )
    n2++;
  return t2 + n2;
}
function _n(t2, e, n2) {
  if (Ho(t2))
    return e.groupIndices[t2.groupIndex] + 1;
  {
    const o = t2.index === "LAST" ? n2 : t2.index;
    let r2 = Gn(o, e);
    return r2 = Math.max(0, r2, Math.min(n2, r2)), r2;
  }
}
function Bo(t2, e, n2, o = 0) {
  return o > 0 && (e = Math.max(e, Wn(t2, o, $e).offset)), Ln(yo(t2, e, n2, Eo), Oo);
}
function ko(t2, [e, n2, o, r2]) {
  e.length > 0 && o("received item sizes", e, mt.DEBUG);
  const s = t2.sizeTree;
  let i2 = s, l2 = 0;
  if (n2.length > 0 && j(s) && e.length === 2) {
    const h = e[0].size, I = e[1].size;
    i2 = n2.reduce((C, v) => pt(pt(C, v, h), v + 1, I), i2);
  } else
    [i2, l2] = bo(i2, e);
  if (i2 === s)
    return t2;
  const { lastIndex: c2, lastOffset: a2, lastSize: m, offsetTree: x } = Ae(t2.offsetTree, l2, i2, r2);
  return {
    groupIndices: n2,
    groupOffsetTree: n2.reduce((h, I) => pt(h, I, ie(I, x, r2)), jt()),
    lastIndex: c2,
    lastOffset: a2,
    lastSize: m,
    offsetTree: x,
    sizeTree: i2
  };
}
function Fo(t2) {
  return Gt(t2).map(({ k: e, v: n2 }, o, r2) => {
    const s = r2[o + 1];
    return { endIndex: s ? s.k - 1 : 1 / 0, size: n2, startIndex: e };
  });
}
function pn(t2, e) {
  let n2 = 0, o = 0;
  for (; n2 < t2; )
    n2 += e[o + 1] - e[o] - 1, o++;
  return o - (n2 === t2 ? 0 : 1);
}
function Ae(t2, e, n2, o) {
  let r2 = t2, s = 0, i2 = 0, l2 = 0, c2 = 0;
  if (e !== 0) {
    c2 = Se(r2, e - 1, $e), l2 = r2[c2].offset;
    const m = wt(n2, e - 1);
    s = m[0], i2 = m[1], r2.length && r2[c2].size === wt(n2, e)[1] && (c2 -= 1), r2 = r2.slice(0, c2 + 1);
  } else
    r2 = [];
  for (const { start: a2, value: m } of ye(n2, e, 1 / 0)) {
    const x = a2 - s, h = x * i2 + l2 + x * o;
    r2.push({
      index: a2,
      offset: h,
      size: m
    }), s = a2, l2 = h, i2 = m;
  }
  return {
    lastIndex: s,
    lastOffset: l2,
    lastSize: i2,
    offsetTree: r2
  };
}
function Oo(t2) {
  return { index: t2.index, value: t2 };
}
function Lo(t2) {
  const { endIndex: e, size: n2, startIndex: o } = t2;
  return (r2) => r2.start === o && (r2.end === e || r2.end === 1 / 0) && r2.value === n2;
}
const zo = {
  offsetHeight: "height",
  offsetWidth: "width"
}, Et = U(
  ([{ log: t2 }, { recalcInProgress: e }]) => {
    const n2 = $(), o = $(), r2 = ct(o, 0), s = $(), i2 = $(), l2 = w(0), c2 = w([]), a2 = w(void 0), m = w(void 0), x = w((f, d) => vt$1(f, zo[d])), h = w(void 0), I = w(0), C = Ro(), v = ct(
      S(n2, N(c2, t2, I), bt(ko, C), Y()),
      C
    ), g = ct(
      S(
        c2,
        Y(),
        bt((f, d) => ({ current: d, prev: f.current }), {
          current: [],
          prev: []
        }),
        E(({ prev: f }) => f)
      ),
      []
    );
    O(
      S(
        c2,
        A((f) => f.length > 0),
        N(v, I),
        E(([f, d, y]) => {
          const B = f.reduce((k, L, z) => pt(k, L, ie(L, d.offsetTree, y) || z), jt());
          return {
            ...d,
            groupIndices: f,
            groupOffsetTree: B
          };
        })
      ),
      v
    ), O(
      S(
        o,
        N(v),
        A(([f, { lastIndex: d }]) => f < d),
        E(([f, { lastIndex: d, lastSize: y }]) => [
          {
            endIndex: d,
            size: y,
            startIndex: f
          }
        ])
      ),
      n2
    ), O(a2, m);
    const p = ct(
      S(
        a2,
        E((f) => f === void 0)
      ),
      true
    );
    O(
      S(
        m,
        A((f) => f !== void 0 && j(ot(v).sizeTree)),
        E((f) => [{ endIndex: 0, size: f, startIndex: 0 }])
      ),
      n2
    );
    const u = ht(
      S(
        n2,
        N(v),
        bt(
          ({ sizes: f }, [d, y]) => ({
            changed: y !== f,
            sizes: y
          }),
          { changed: false, sizes: C }
        ),
        E((f) => f.changed)
      )
    );
    K(
      S(
        l2,
        bt(
          (f, d) => ({ diff: f.prev - d, prev: d }),
          { diff: 0, prev: 0 }
        ),
        E((f) => f.diff)
      ),
      (f) => {
        const { groupIndices: d } = ot(v);
        if (f > 0)
          G(e, true), G(s, f + pn(f, d));
        else if (f < 0) {
          const y = ot(g);
          y.length > 0 && (f -= pn(-f, y)), G(i2, f);
        }
      }
    ), K(S(l2, N(t2)), ([f, d]) => {
      f < 0 && d(
        "`firstItemIndex` prop should not be set to less than zero. If you don't know the total count, just use a very high value",
        { firstItemIndex: l2 },
        mt.ERROR
      );
    });
    const T = ht(s);
    O(
      S(
        s,
        N(v),
        E(([f, d]) => {
          const y = d.groupIndices.length > 0, B = [], k = d.lastSize;
          if (y) {
            const L = re(d.sizeTree, 0);
            let z = 0, _ = 0;
            for (; z < f; ) {
              const F = d.groupIndices[_], q = d.groupIndices.length === _ + 1 ? 1 / 0 : d.groupIndices[_ + 1] - F - 1;
              B.push({
                endIndex: F,
                size: L,
                startIndex: F
              }), B.push({
                endIndex: F + 1 + q - 1,
                size: k,
                startIndex: F + 1
              }), _++, z += q + 1;
            }
            const J = Gt(d.sizeTree);
            return z !== f && J.shift(), J.reduce(
              (F, { k: q, v: it }) => {
                let dt = F.ranges;
                return F.prevSize !== 0 && (dt = [
                  ...F.ranges,
                  {
                    endIndex: q + f - 1,
                    size: F.prevSize,
                    startIndex: F.prevIndex
                  }
                ]), {
                  prevIndex: q + f,
                  prevSize: it,
                  ranges: dt
                };
              },
              {
                prevIndex: f,
                prevSize: 0,
                ranges: B
              }
            ).ranges;
          }
          return Gt(d.sizeTree).reduce(
            (L, { k: z, v: _ }) => ({
              prevIndex: z + f,
              prevSize: _,
              ranges: [...L.ranges, { endIndex: z + f - 1, size: L.prevSize, startIndex: L.prevIndex }]
            }),
            {
              prevIndex: 0,
              prevSize: k,
              ranges: []
            }
          ).ranges;
        })
      ),
      n2
    );
    const b = ht(
      S(
        i2,
        N(v, I),
        E(([f, { offsetTree: d }, y]) => {
          const B = -f;
          return ie(B, d, y);
        })
      )
    );
    return O(
      S(
        i2,
        N(v, I),
        E(([f, d, y]) => {
          if (d.groupIndices.length > 0) {
            if (j(d.sizeTree))
              return d;
            let k = jt();
            const L = ot(g);
            let z = 0, _ = 0, J = 0;
            for (; z < -f; ) {
              J = L[_];
              const F = L[_ + 1] - J - 1;
              _++, z += F + 1;
            }
            if (k = Gt(d.sizeTree).reduce((F, { k: q, v: it }) => pt(F, Math.max(0, q + f), it), k), z !== -f) {
              const F = re(d.sizeTree, J);
              k = pt(k, 0, F);
              const q = wt(d.sizeTree, -f + 1)[1];
              k = pt(k, 1, q);
            }
            return {
              ...d,
              sizeTree: k,
              ...Ae(d.offsetTree, 0, k, y)
            };
          } else {
            const k = Gt(d.sizeTree).reduce((L, { k: z, v: _ }) => pt(L, Math.max(0, z + f), _), jt());
            return {
              ...d,
              sizeTree: k,
              ...Ae(d.offsetTree, 0, k, y)
            };
          }
        })
      ),
      v
    ), {
      beforeUnshiftWith: T,
      // input
      data: h,
      defaultItemSize: m,
      firstItemIndex: l2,
      fixedItemSize: a2,
      gap: I,
      groupIndices: c2,
      itemSize: x,
      listRefresh: u,
      shiftWith: i2,
      shiftWithOffset: b,
      sizeRanges: n2,
      // output
      sizes: v,
      statefulTotalCount: r2,
      totalCount: o,
      trackItemSizes: p,
      unshiftWith: s
    };
  },
  X(Vt$1, De),
  { singleton: true }
);
function Vo(t2) {
  return t2.reduce(
    (e, n2) => (e.groupIndices.push(e.totalCount), e.totalCount += n2 + 1, e),
    {
      groupIndices: [],
      totalCount: 0
    }
  );
}
const Nn = U(
  ([{ groupIndices: t2, sizes: e, totalCount: n2 }, { headerHeight: o, scrollTop: r2 }]) => {
    const s = $(), i2 = $(), l2 = ht(S(s, E(Vo)));
    return O(
      S(
        l2,
        E((c2) => c2.totalCount)
      ),
      n2
    ), O(
      S(
        l2,
        E((c2) => c2.groupIndices)
      ),
      t2
    ), O(
      S(
        rt(r2, e, o),
        A(([c2, a2]) => Re(a2)),
        E(([c2, a2, m]) => wt(a2.groupOffsetTree, Math.max(c2 - m, 0), "v")[0]),
        Y(),
        E((c2) => [c2])
      ),
      i2
    ), { groupCounts: s, topItemsIndexes: i2 };
  },
  X(Et, at2)
), Pt = U(
  ([{ log: t2 }]) => {
    const e = w(false), n2 = ht(
      S(
        e,
        A((o) => o),
        Y()
      )
    );
    return K(e, (o) => {
      o && ot(t2)("props updated", {}, mt.DEBUG);
    }), { didMount: n2, propsReady: e };
  },
  X(Vt$1),
  { singleton: true }
), Po = typeof document < "u" && "scrollBehavior" in document.documentElement.style;
function Dn(t2) {
  const e = typeof t2 == "number" ? { index: t2 } : t2;
  return e.align || (e.align = "start"), (!e.behavior || !Po) && (e.behavior = "auto"), e.offset || (e.offset = 0), e;
}
const ce = U(
  ([
    { gap: t2, listRefresh: e, sizes: n2, totalCount: o },
    {
      fixedFooterHeight: r2,
      fixedHeaderHeight: s,
      footerHeight: i2,
      headerHeight: l2,
      scrollingInProgress: c2,
      scrollTo: a2,
      smoothScrollTargetReached: m,
      viewportHeight: x
    },
    { log: h }
  ]) => {
    const I = $(), C = $(), v = w(0);
    let g = null, p = null, u = null;
    function T() {
      g && (g(), g = null), u && (u(), u = null), p && (clearTimeout(p), p = null), G(c2, false);
    }
    return O(
      S(
        I,
        N(n2, x, o, v, l2, i2, h),
        N(t2, s, r2),
        E(
          ([
            [b, f, d, y, B, k, L, z],
            _,
            J,
            nt
          ]) => {
            const F = Dn(b), { align: q, behavior: it, offset: dt } = F, St = y - 1, ft = _n(F, f, St);
            let ut = ie(ft, f.offsetTree, _) + k;
            q === "end" ? (ut += J + wt(f.sizeTree, ft)[1] - d + nt, ft === St && (ut += L)) : q === "center" ? ut += (J + wt(f.sizeTree, ft)[1] - d + nt) / 2 : ut -= B, dt && (ut += dt);
            const At = (xt) => {
              T(), xt ? (z("retrying to scroll to", { location: b }, mt.DEBUG), G(I, b)) : (G(C, true), z("list did not change, scroll successful", {}, mt.DEBUG));
            };
            if (T(), it === "smooth") {
              let xt = false;
              u = K(e, (Xt) => {
                xt = xt || Xt;
              }), g = Tt(m, () => {
                At(xt);
              });
            } else
              g = Tt(S(e, Ao(150)), At);
            return p = setTimeout(() => {
              T();
            }, 1200), G(c2, true), z("scrolling from index to", { behavior: it, index: ft, top: ut }, mt.DEBUG), { behavior: it, top: ut };
          }
        )
      ),
      a2
    ), {
      scrollTargetReached: C,
      scrollToIndex: I,
      topListHeight: v
    };
  },
  X(Et, at2, Vt$1),
  { singleton: true }
);
function Ao(t2) {
  return (e) => {
    const n2 = setTimeout(() => {
      e(false);
    }, t2);
    return (o) => {
      o && (e(true), clearTimeout(n2));
    };
  };
}
function Ue(t2, e) {
  t2 == 0 ? e() : requestAnimationFrame(() => {
    Ue(t2 - 1, e);
  });
}
function Ke(t2, e) {
  const n2 = e - 1;
  return typeof t2 == "number" ? t2 : t2.index === "LAST" ? n2 : t2.index;
}
const ue = U(
  ([{ defaultItemSize: t2, listRefresh: e, sizes: n2 }, { scrollTop: o }, { scrollTargetReached: r2, scrollToIndex: s }, { didMount: i2 }]) => {
    const l2 = w(true), c2 = w(0), a2 = w(true);
    return O(
      S(
        i2,
        N(c2),
        A(([m, x]) => !!x),
        Rt(false)
      ),
      l2
    ), O(
      S(
        i2,
        N(c2),
        A(([m, x]) => !!x),
        Rt(false)
      ),
      a2
    ), K(
      S(
        rt(e, i2),
        N(l2, n2, t2, a2),
        A(([[, m], x, { sizeTree: h }, I, C]) => m && (!j(h) || We(I)) && !x && !C),
        N(c2)
      ),
      ([, m]) => {
        Tt(r2, () => {
          G(a2, true);
        }), Ue(4, () => {
          Tt(o, () => {
            G(l2, true);
          }), G(s, m);
        });
      }
    ), {
      initialItemFinalLocationReached: a2,
      initialTopMostItemIndex: c2,
      scrolledToInitialItem: l2
    };
  },
  X(Et, at2, ce, Pt),
  { singleton: true }
);
function $n(t2, e) {
  return Math.abs(t2 - e) < 1.01;
}
const le = "up", te = "down", Mo = "none", Wo = {
  atBottom: false,
  notAtBottomBecause: "NOT_SHOWING_LAST_ITEM",
  state: {
    offsetBottom: 0,
    scrollHeight: 0,
    scrollTop: 0,
    viewportHeight: 0
  }
}, Go = 0, ae = U(([{ footerHeight: t2, headerHeight: e, scrollBy: n2, scrollContainerState: o, scrollTop: r2, viewportHeight: s }]) => {
  const i2 = w(false), l2 = w(true), c2 = $(), a2 = $(), m = w(4), x = w(Go), h = ct(
    S(
      Le(S(V(r2), Dt(1), Rt(true)), S(V(r2), Dt(1), Rt(false), dn(100))),
      Y()
    ),
    false
  ), I = ct(
    S(Le(S(n2, Rt(true)), S(n2, Rt(false), dn(200))), Y()),
    false
  );
  O(
    S(
      rt(V(r2), V(x)),
      E(([u, T]) => u <= T),
      Y()
    ),
    l2
  ), O(S(l2, kt(50)), a2);
  const C = ht(
    S(
      rt(o, V(s), V(e), V(t2), V(m)),
      bt((u, [{ scrollHeight: T, scrollTop: b }, f, d, y, B]) => {
        const k = b + f - T > -B, L = {
          scrollHeight: T,
          scrollTop: b,
          viewportHeight: f
        };
        if (k) {
          let _, J;
          return b > u.state.scrollTop ? (_ = "SCROLLED_DOWN", J = u.state.scrollTop - b) : (_ = "SIZE_DECREASED", J = u.state.scrollTop - b || u.scrollTopDelta), {
            atBottom: true,
            atBottomBecause: _,
            scrollTopDelta: J,
            state: L
          };
        }
        let z;
        return L.scrollHeight > u.state.scrollHeight ? z = "SIZE_INCREASED" : f < u.state.viewportHeight ? z = "VIEWPORT_HEIGHT_DECREASING" : b < u.state.scrollTop ? z = "SCROLLING_UPWARDS" : z = "NOT_FULLY_SCROLLED_TO_LAST_ITEM_BOTTOM", {
          atBottom: false,
          notAtBottomBecause: z,
          state: L
        };
      }, Wo),
      Y((u, T) => u && u.atBottom === T.atBottom)
    )
  ), v = ct(
    S(
      o,
      bt(
        (u, { scrollHeight: T, scrollTop: b, viewportHeight: f }) => {
          if ($n(u.scrollHeight, T))
            return {
              changed: false,
              jump: 0,
              scrollHeight: T,
              scrollTop: b
            };
          {
            const d = T - (b + f) < 1;
            return u.scrollTop !== b && d ? {
              changed: true,
              jump: u.scrollTop - b,
              scrollHeight: T,
              scrollTop: b
            } : {
              changed: true,
              jump: 0,
              scrollHeight: T,
              scrollTop: b
            };
          }
        },
        { changed: false, jump: 0, scrollHeight: 0, scrollTop: 0 }
      ),
      A((u) => u.changed),
      E((u) => u.jump)
    ),
    0
  );
  O(
    S(
      C,
      E((u) => u.atBottom)
    ),
    i2
  ), O(S(i2, kt(50)), c2);
  const g = w(te);
  O(
    S(
      o,
      E(({ scrollTop: u }) => u),
      Y(),
      bt(
        (u, T) => ot(I) ? { direction: u.direction, prevScrollTop: T } : { direction: T < u.prevScrollTop ? le : te, prevScrollTop: T },
        { direction: te, prevScrollTop: 0 }
      ),
      E((u) => u.direction)
    ),
    g
  ), O(S(o, kt(50), Rt(Mo)), g);
  const p = w(0);
  return O(
    S(
      h,
      A((u) => !u),
      Rt(0)
    ),
    p
  ), O(
    S(
      r2,
      kt(100),
      N(h),
      A(([u, T]) => !!T),
      bt(([u, T], [b]) => [T, b], [0, 0]),
      E(([u, T]) => T - u)
    ),
    p
  ), {
    atBottomState: C,
    atBottomStateChange: c2,
    atBottomThreshold: m,
    atTopStateChange: a2,
    atTopThreshold: x,
    isAtBottom: i2,
    isAtTop: l2,
    isScrolling: h,
    lastJumpDueToItemResize: v,
    scrollDirection: g,
    scrollVelocity: p
  };
}, X(at2)), xe = "top", Te = "bottom", hn = "none";
function gn(t2, e, n2) {
  return typeof t2 == "number" ? n2 === le && e === xe || n2 === te && e === Te ? t2 : 0 : n2 === le ? e === xe ? t2.main : t2.reverse : e === Te ? t2.main : t2.reverse;
}
function In(t2, e) {
  var n2;
  return typeof t2 == "number" ? t2 : (n2 = t2[e]) != null ? n2 : 0;
}
const je = U(
  ([{ deviation: t2, fixedHeaderHeight: e, headerHeight: n2, scrollTop: o, viewportHeight: r2 }]) => {
    const s = $(), i2 = w(0), l2 = w(0), c2 = w(0), a2 = ct(
      S(
        rt(
          V(o),
          V(r2),
          V(n2),
          V(s, se),
          V(c2),
          V(i2),
          V(e),
          V(t2),
          V(l2)
        ),
        E(
          ([
            m,
            x,
            h,
            [I, C],
            v,
            g,
            p,
            u,
            T
          ]) => {
            const b = m - u, f = g + p, d = Math.max(h - b, 0);
            let y = hn;
            const B = In(T, xe), k = In(T, Te);
            return I -= u, I += h + p, C += h + p, C -= u, I > m + f - B && (y = le), C < m - d + x + k && (y = te), y !== hn ? [
              Math.max(b - h - gn(v, xe, y) - B, 0),
              b - d - p + x + gn(v, Te, y) + k
            ] : null;
          }
        ),
        A((m) => m != null),
        Y(se)
      ),
      [0, 0]
    );
    return {
      increaseViewportBy: l2,
      // input
      listBoundary: s,
      overscan: c2,
      topListHeight: i2,
      // output
      visibleRange: a2
    };
  },
  X(at2),
  { singleton: true }
);
function _o(t2, e, n2) {
  if (Re(e)) {
    const o = Gn(t2, e);
    return [
      { index: wt(e.groupOffsetTree, o)[0], offset: 0, size: 0 },
      { data: n2 == null ? void 0 : n2[0], index: o, offset: 0, size: 0 }
    ];
  }
  return [{ data: n2 == null ? void 0 : n2[0], index: t2, offset: 0, size: 0 }];
}
const Be = {
  bottom: 0,
  firstItemIndex: 0,
  items: [],
  offsetBottom: 0,
  offsetTop: 0,
  top: 0,
  topItems: [],
  topListHeight: 0,
  totalCount: 0
};
function Ie(t2, e, n2, o, r2, s) {
  const { lastIndex: i2, lastOffset: l2, lastSize: c2 } = r2;
  let a2 = 0, m = 0;
  if (t2.length > 0) {
    a2 = t2[0].offset;
    const v = t2[t2.length - 1];
    m = v.offset + v.size;
  }
  const x = n2 - i2, h = l2 + x * c2 + (x - 1) * o, I = a2, C = h - m;
  return {
    bottom: m,
    firstItemIndex: s,
    items: Sn(t2, r2, s),
    offsetBottom: C,
    offsetTop: a2,
    top: I,
    topItems: Sn(e, r2, s),
    topListHeight: e.reduce((v, g) => g.size + v, 0),
    totalCount: n2
  };
}
function Un(t2, e, n2, o, r2, s) {
  let i2 = 0;
  if (n2.groupIndices.length > 0)
    for (const m of n2.groupIndices) {
      if (m - i2 >= t2)
        break;
      i2++;
    }
  const l2 = t2 + i2, c2 = Ke(e, l2), a2 = Array.from({ length: l2 }).map((m, x) => ({
    data: s[x + c2],
    index: x + c2,
    offset: 0,
    size: 0
  }));
  return Ie(a2, [], l2, r2, n2, o);
}
function Sn(t2, e, n2) {
  if (t2.length === 0)
    return [];
  if (!Re(e))
    return t2.map((a2) => ({ ...a2, index: a2.index + n2, originalIndex: a2.index }));
  const o = t2[0].index, r2 = t2[t2.length - 1].index, s = [], i2 = ye(e.groupOffsetTree, o, r2);
  let l2, c2 = 0;
  for (const a2 of t2) {
    (!l2 || l2.end < a2.index) && (l2 = i2.shift(), c2 = e.groupIndices.indexOf(l2.start));
    let m;
    a2.index === l2.start ? m = {
      index: c2,
      type: "group"
    } : m = {
      groupIndex: c2,
      index: a2.index - (c2 + 1) + n2
    }, s.push({
      ...m,
      data: a2.data,
      offset: a2.offset,
      originalIndex: a2.index,
      size: a2.size
    });
  }
  return s;
}
const $t = U(
  ([
    { data: t2, firstItemIndex: e, gap: n2, sizes: o, totalCount: r2 },
    s,
    { listBoundary: i2, topListHeight: l2, visibleRange: c2 },
    { initialTopMostItemIndex: a2, scrolledToInitialItem: m },
    { topListHeight: x },
    h,
    { didMount: I },
    { recalcInProgress: C }
  ]) => {
    const v = w([]), g = w(0), p = $();
    O(s.topItemsIndexes, v);
    const u = ct(
      S(
        rt(
          I,
          C,
          V(c2, se),
          V(r2),
          V(o),
          V(a2),
          m,
          V(v),
          V(e),
          V(n2),
          t2
        ),
        A(([d, y, , B, , , , , , , k]) => {
          const L = k && k.length !== B;
          return d && !y && !L;
        }),
        E(
          ([
            ,
            ,
            [d, y],
            B,
            k,
            L,
            z,
            _,
            J,
            nt,
            F
          ]) => {
            const q = k, { offsetTree: it, sizeTree: dt } = q, St = ot(g);
            if (B === 0)
              return { ...Be, totalCount: B };
            if (d === 0 && y === 0)
              return St === 0 ? { ...Be, totalCount: B } : Un(St, L, k, J, nt, F || []);
            if (j(dt))
              return St > 0 ? null : Ie(
                _o(Ke(L, B), q, F),
                [],
                B,
                nt,
                q,
                J
              );
            const ft = [];
            if (_.length > 0) {
              const Mt = _[0], yt = _[_.length - 1];
              let Bt = 0;
              for (const R of ye(dt, Mt, yt)) {
                const D = R.value, Q = Math.max(R.start, Mt), lt = Math.min(R.end, yt);
                for (let tt = Q; tt <= lt; tt++)
                  ft.push({ data: F == null ? void 0 : F[tt], index: tt, offset: Bt, size: D }), Bt += D;
              }
            }
            if (!z)
              return Ie([], ft, B, nt, q, J);
            const ut = _.length > 0 ? _[_.length - 1] + 1 : 0, At = Bo(it, d, y, ut);
            if (At.length === 0)
              return null;
            const xt = B - 1, Xt = ve([], (Mt) => {
              for (const yt of At) {
                const Bt = yt.value;
                let R = Bt.offset, D = yt.start;
                const Q = Bt.size;
                if (Bt.offset < d) {
                  D += Math.floor((d - Bt.offset + nt) / (Q + nt));
                  const tt = D - yt.start;
                  R += tt * Q + tt * nt;
                }
                D < ut && (R += (ut - D) * Q, D = ut);
                const lt = Math.min(yt.end, xt);
                for (let tt = D; tt <= lt && !(R >= y); tt++)
                  Mt.push({ data: F == null ? void 0 : F[tt], index: tt, offset: R, size: Q }), R += Q + nt;
              }
            });
            return Ie(Xt, ft, B, nt, q, J);
          }
        ),
        //@ts-expect-error filter needs to be fixed
        A((d) => d !== null),
        Y()
      ),
      Be
    );
    O(
      S(
        t2,
        A(We),
        E((d) => d == null ? void 0 : d.length)
      ),
      r2
    ), O(
      S(
        u,
        E((d) => d.topListHeight)
      ),
      x
    ), O(x, l2), O(
      S(
        u,
        E((d) => [d.top, d.bottom])
      ),
      i2
    ), O(
      S(
        u,
        E((d) => d.items)
      ),
      p
    );
    const T = ht(
      S(
        u,
        A(({ items: d }) => d.length > 0),
        N(r2, t2),
        A(([{ items: d }, y]) => d[d.length - 1].originalIndex === y - 1),
        E(([, d, y]) => [d - 1, y]),
        Y(se),
        E(([d]) => d)
      )
    ), b = ht(
      S(
        u,
        kt(200),
        A(({ items: d, topItems: y }) => d.length > 0 && d[0].originalIndex === y.length),
        E(({ items: d }) => d[0].index),
        Y()
      )
    ), f = ht(
      S(
        u,
        A(({ items: d }) => d.length > 0),
        E(({ items: d }) => {
          let y = 0, B = d.length - 1;
          for (; d[y].type === "group" && y < B; )
            y++;
          for (; d[B].type === "group" && B > y; )
            B--;
          return {
            endIndex: d[B].index,
            startIndex: d[y].index
          };
        }),
        Y(Mn)
      )
    );
    return { endReached: T, initialItemCount: g, itemsRendered: p, listState: u, rangeChanged: f, startReached: b, topItemsIndexes: v, ...h };
  },
  X(
    Et,
    Nn,
    je,
    ue,
    ce,
    ae,
    Pt,
    De
  ),
  { singleton: true }
), Kn = U(
  ([{ fixedFooterHeight: t2, fixedHeaderHeight: e, footerHeight: n2, headerHeight: o }, { listState: r2 }]) => {
    const s = $(), i2 = ct(
      S(
        rt(n2, t2, o, e, r2),
        E(([l2, c2, a2, m, x]) => l2 + c2 + a2 + m + x.offsetBottom + x.bottom)
      ),
      0
    );
    return O(V(i2), s), { totalListHeight: i2, totalListHeightChanged: s };
  },
  X(at2, $t),
  { singleton: true }
), No = U(
  ([{ viewportHeight: t2 }, { totalListHeight: e }]) => {
    const n2 = w(false), o = ct(
      S(
        rt(n2, t2, e),
        A(([r2]) => r2),
        E(([, r2, s]) => Math.max(0, r2 - s)),
        kt(0),
        Y()
      ),
      0
    );
    return { alignToBottom: n2, paddingTopAddition: o };
  },
  X(at2, Kn),
  { singleton: true }
), jn = U(() => ({
  context: w(null)
})), Do = ({
  itemBottom: t2,
  itemTop: e,
  locationParams: { align: n2, behavior: o, ...r2 },
  viewportBottom: s,
  viewportTop: i2
}) => e < i2 ? { ...r2, align: n2 != null ? n2 : "start", behavior: o } : t2 > s ? { ...r2, align: n2 != null ? n2 : "end", behavior: o } : null, qn = U(
  ([
    { gap: t2, sizes: e, totalCount: n2 },
    { fixedFooterHeight: o, fixedHeaderHeight: r2, headerHeight: s, scrollingInProgress: i2, scrollTop: l2, viewportHeight: c2 },
    { scrollToIndex: a2 }
  ]) => {
    const m = $();
    return O(
      S(
        m,
        N(e, c2, n2, s, r2, o, l2),
        N(t2),
        E(([[x, h, I, C, v, g, p, u], T]) => {
          const { align: b, behavior: f, calculateViewLocation: d = Do, done: y, ...B } = x, k = _n(x, h, C - 1), L = ie(k, h.offsetTree, T) + v + g, z = L + wt(h.sizeTree, k)[1], _ = u + g, J = u + I - p, nt = d({
            itemBottom: z,
            itemTop: L,
            locationParams: { align: b, behavior: f, ...B },
            viewportBottom: J,
            viewportTop: _
          });
          return nt ? y && Tt(
            S(
              i2,
              A((F) => !F),
              // skips the initial publish of false, and the cleanup call.
              // but if scrollingInProgress is true, we skip the initial publish.
              Dt(ot(i2) ? 1 : 2)
            ),
            y
          ) : y && y(), nt;
        }),
        A((x) => x !== null)
      ),
      a2
    ), {
      scrollIntoView: m
    };
  },
  X(Et, at2, ce, $t, Vt$1),
  { singleton: true }
);
function xn(t2) {
  return t2 ? t2 === "smooth" ? "smooth" : "auto" : false;
}
const $o = (t2, e) => typeof t2 == "function" ? xn(t2(e)) : e && xn(t2), Uo = U(
  ([
    { listRefresh: t2, totalCount: e, fixedItemSize: n2, data: o },
    { atBottomState: r2, isAtBottom: s },
    { scrollToIndex: i2 },
    { scrolledToInitialItem: l2 },
    { didMount: c2, propsReady: a2 },
    { log: m },
    { scrollingInProgress: x },
    { context: h },
    { scrollIntoView: I }
  ]) => {
    const C = w(false), v = $();
    let g = null;
    function p(f) {
      G(i2, {
        align: "end",
        behavior: f,
        index: "LAST"
      });
    }
    K(
      S(
        rt(S(V(e), Dt(1)), c2),
        N(V(C), s, l2, x),
        E(([[f, d], y, B, k, L]) => {
          let z = d && k, _ = "auto";
          return z && (_ = $o(y, B || L), z = z && !!_), { followOutputBehavior: _, shouldFollow: z, totalCount: f };
        }),
        A(({ shouldFollow: f }) => f)
      ),
      ({ followOutputBehavior: f, totalCount: d }) => {
        g && (g(), g = null), ot(n2) ? requestAnimationFrame(() => {
          ot(m)("following output to ", { totalCount: d }, mt.DEBUG), p(f);
        }) : g = Tt(t2, () => {
          ot(m)("following output to ", { totalCount: d }, mt.DEBUG), p(f), g = null;
        });
      }
    );
    function u(f) {
      const d = Tt(r2, (y) => {
        f && !y.atBottom && y.notAtBottomBecause === "SIZE_INCREASED" && !g && (ot(m)("scrolling to bottom due to increased size", {}, mt.DEBUG), p("auto"));
      });
      setTimeout(d, 100);
    }
    K(
      S(
        rt(V(C), e, a2),
        A(([f, , d]) => f && d),
        bt(
          ({ value: f }, [, d]) => ({ refreshed: f === d, value: d }),
          { refreshed: false, value: 0 }
        ),
        A(({ refreshed: f }) => f),
        N(C, e)
      ),
      ([, f]) => {
        ot(l2) && u(f !== false);
      }
    ), K(v, () => {
      u(ot(C) !== false);
    }), K(rt(V(C), r2), ([f, d]) => {
      f && !d.atBottom && d.notAtBottomBecause === "VIEWPORT_HEIGHT_DECREASING" && p("auto");
    });
    const T = w(null), b = $();
    return O(
      Le(
        S(
          V(o),
          E((f) => {
            var d;
            return (d = f == null ? void 0 : f.length) != null ? d : 0;
          })
        ),
        S(V(e))
      ),
      b
    ), K(
      S(
        rt(S(b, Dt(1)), c2),
        N(V(T), l2, x, h),
        E(([[f, d], y, B, k, L]) => d && B && (y == null ? void 0 : y({ context: L, totalCount: f, scrollingInProgress: k }))),
        A((f) => !!f),
        kt(0)
      ),
      (f) => {
        g && (g(), g = null), ot(n2) ? requestAnimationFrame(() => {
          ot(m)("scrolling into view", {}), G(I, f);
        }) : g = Tt(t2, () => {
          ot(m)("scrolling into view", {}), G(I, f), g = null;
        });
      }
    ), { autoscrollToBottom: v, followOutput: C, scrollIntoViewOnChange: T };
  },
  X(
    Et,
    ae,
    ce,
    ue,
    Pt,
    Vt$1,
    at2,
    jn,
    qn
  )
), Ko = U(
  ([{ data: t2, firstItemIndex: e, gap: n2, sizes: o }, { initialTopMostItemIndex: r2 }, { initialItemCount: s, listState: i2 }, { didMount: l2 }]) => (O(
    S(
      l2,
      N(s),
      A(([, c2]) => c2 !== 0),
      N(r2, o, e, n2, t2),
      E(([[, c2], a2, m, x, h, I = []]) => Un(c2, a2, m, x, h, I))
    ),
    i2
  ), {}),
  X(Et, ue, $t, Pt),
  { singleton: true }
), jo = U(
  ([{ didMount: t2 }, { scrollTo: e }, { listState: n2 }]) => {
    const o = w(0);
    return K(
      S(
        t2,
        N(o),
        A(([, r2]) => r2 !== 0),
        E(([, r2]) => ({ top: r2 }))
      ),
      (r2) => {
        Tt(
          S(
            n2,
            Dt(1),
            A((s) => s.items.length > 1)
          ),
          () => {
            requestAnimationFrame(() => {
              G(e, r2);
            });
          }
        );
      }
    ), {
      initialScrollTop: o
    };
  },
  X(Pt, at2, $t),
  { singleton: true }
), Yn = U(
  ([{ scrollVelocity: t2 }]) => {
    const e = w(false), n2 = $(), o = w(false);
    return O(
      S(
        t2,
        N(o, e, n2),
        A(([r2, s]) => !!s),
        E(([r2, s, i2, l2]) => {
          const { enter: c2, exit: a2 } = s;
          if (i2) {
            if (a2(r2, l2))
              return false;
          } else if (c2(r2, l2))
            return true;
          return i2;
        }),
        Y()
      ),
      e
    ), K(
      S(rt(e, t2, n2), N(o)),
      ([[r2, s, i2], l2]) => {
        r2 && l2 && l2.change && l2.change(s, i2);
      }
    ), { isSeeking: e, scrollSeekConfiguration: o, scrollSeekRangeChanged: n2, scrollVelocity: t2 };
  },
  X(ae),
  { singleton: true }
), qe = U(([{ scrollContainerState: t2, scrollTo: e }]) => {
  const n2 = $(), o = $(), r2 = $(), s = w(false), i2 = w(void 0);
  return O(
    S(
      rt(n2, o),
      E(([{ scrollHeight: l2, scrollTop: c2, viewportHeight: a2 }, { offsetTop: m }]) => ({
        scrollHeight: l2,
        scrollTop: Math.max(0, c2 - m),
        viewportHeight: a2
      }))
    ),
    t2
  ), O(
    S(
      e,
      N(o),
      E(([l2, { offsetTop: c2 }]) => ({
        ...l2,
        top: l2.top + c2
      }))
    ),
    r2
  ), {
    customScrollParent: i2,
    // config
    useWindowScroll: s,
    // input
    windowScrollContainerState: n2,
    // signals
    windowScrollTo: r2,
    windowViewportRect: o
  };
}, X(at2)), qo = U(
  ([
    { sizeRanges: t2, sizes: e },
    { headerHeight: n2, scrollTop: o },
    { initialTopMostItemIndex: r2 },
    { didMount: s },
    { useWindowScroll: i2, windowScrollContainerState: l2, windowViewportRect: c2 }
  ]) => {
    const a2 = $(), m = w(void 0), x = w(null), h = w(null);
    return O(l2, x), O(c2, h), K(
      S(
        a2,
        N(e, o, i2, x, h, n2)
      ),
      ([I, C, v, g, p, u, T]) => {
        const b = Fo(C.sizeTree);
        g && p !== null && u !== null && (v = p.scrollTop - u.offsetTop), v -= T, I({ ranges: b, scrollTop: v });
      }
    ), O(S(m, A(We), E(Yo)), r2), O(
      S(
        s,
        N(m),
        A(([, I]) => I !== void 0),
        Y(),
        E(([, I]) => I.ranges)
      ),
      t2
    ), {
      getState: a2,
      restoreStateFrom: m
    };
  },
  X(Et, at2, ue, Pt, qe)
);
function Yo(t2) {
  return { align: "start", index: 0, offset: t2.scrollTop };
}
const Zo = U(([{ topItemsIndexes: t2 }]) => {
  const e = w(0);
  return O(
    S(
      e,
      A((n2) => n2 >= 0),
      E((n2) => Array.from({ length: n2 }).map((o, r2) => r2))
    ),
    t2
  ), { topItemCount: e };
}, X($t));
function Zn(t2) {
  let e = false, n2;
  return () => (e || (e = true, n2 = t2()), n2);
}
const Xo = Zn(() => /iP(ad|od|hone)/i.test(navigator.userAgent) && /WebKit/i.test(navigator.userAgent)), Jo = U(
  ([
    { deviation: t2, scrollBy: e, scrollingInProgress: n2, scrollTop: o },
    { isAtBottom: r2, isScrolling: s, lastJumpDueToItemResize: i2, scrollDirection: l2 },
    { listState: c2 },
    { beforeUnshiftWith: a2, gap: m, shiftWithOffset: x, sizes: h },
    { log: I },
    { recalcInProgress: C }
  ]) => {
    const v = ht(
      S(
        c2,
        N(i2),
        bt(
          ([, p, u, T], [{ bottom: b, items: f, offsetBottom: d, totalCount: y }, B]) => {
            const k = b + d;
            let L = 0;
            return u === y && p.length > 0 && f.length > 0 && (f[0].originalIndex === 0 && p[0].originalIndex === 0 || (L = k - T, L !== 0 && (L += B))), [L, f, y, k];
          },
          [0, [], 0, 0]
        ),
        A(([p]) => p !== 0),
        N(o, l2, n2, r2, I, C),
        A(([, p, u, T, , , b]) => !b && !T && p !== 0 && u === le),
        E(([[p], , , , , u]) => (u("Upward scrolling compensation", { amount: p }, mt.DEBUG), p))
      )
    );
    function g(p) {
      p > 0 ? (G(e, { behavior: "auto", top: -p }), G(t2, 0)) : (G(t2, 0), G(e, { behavior: "auto", top: -p }));
    }
    return K(S(v, N(t2, s)), ([p, u, T]) => {
      T && Xo() ? G(t2, u - p) : g(-p);
    }), K(
      S(
        rt(ct(s, false), t2, C),
        A(([p, u, T]) => !p && !T && u !== 0),
        E(([p, u]) => u),
        kt(1)
      ),
      g
    ), O(
      S(
        x,
        E((p) => ({ top: -p }))
      ),
      e
    ), K(
      S(
        a2,
        N(h, m),
        E(([p, { groupIndices: u, lastSize: T, sizeTree: b }, f]) => {
          function d(y) {
            return y * (T + f);
          }
          if (u.length === 0)
            return d(p);
          {
            let y = 0;
            const B = re(b, 0);
            let k = 0, L = 0;
            for (; k < p; ) {
              k++, y += B;
              let z = u.length === L + 1 ? 1 / 0 : u[L + 1] - u[L] - 1;
              k + z > p && (y -= B, z = p - k + 1), k += z, y += d(z), L++;
            }
            return y;
          }
        })
      ),
      (p) => {
        G(t2, p), requestAnimationFrame(() => {
          G(e, { top: p }), requestAnimationFrame(() => {
            G(t2, 0), G(C, false);
          });
        });
      }
    ), { deviation: t2 };
  },
  X(at2, ae, $t, Et, Vt$1, De)
), Qo = U(
  ([
    t2,
    e,
    n2,
    o,
    r2,
    s,
    i2,
    l2,
    c2,
    a2,
    m
  ]) => ({
    ...t2,
    ...e,
    ...n2,
    ...o,
    ...r2,
    ...s,
    ...i2,
    ...l2,
    ...c2,
    ...a2,
    ...m
  }),
  X(
    je,
    Ko,
    Pt,
    Yn,
    Kn,
    jo,
    No,
    qe,
    qn,
    Vt$1,
    jn
  )
), Xn = U(
  ([
    {
      data: t2,
      defaultItemSize: e,
      firstItemIndex: n2,
      fixedItemSize: o,
      gap: r2,
      groupIndices: s,
      itemSize: i2,
      sizeRanges: l2,
      sizes: c2,
      statefulTotalCount: a2,
      totalCount: m,
      trackItemSizes: x
    },
    { initialItemFinalLocationReached: h, initialTopMostItemIndex: I, scrolledToInitialItem: C },
    v,
    g,
    p,
    { listState: u, topItemsIndexes: T, ...b },
    { scrollToIndex: f },
    d,
    { topItemCount: y },
    { groupCounts: B },
    k
  ]) => (O(b.rangeChanged, k.scrollSeekRangeChanged), O(
    S(
      k.windowViewportRect,
      E((L) => L.visibleHeight)
    ),
    v.viewportHeight
  ), {
    data: t2,
    defaultItemHeight: e,
    firstItemIndex: n2,
    fixedItemHeight: o,
    gap: r2,
    groupCounts: B,
    initialItemFinalLocationReached: h,
    initialTopMostItemIndex: I,
    scrolledToInitialItem: C,
    sizeRanges: l2,
    topItemCount: y,
    topItemsIndexes: T,
    // input
    totalCount: m,
    ...p,
    groupIndices: s,
    itemSize: i2,
    listState: u,
    scrollToIndex: f,
    // output
    statefulTotalCount: a2,
    trackItemSizes: x,
    // exported from stateFlagsSystem
    ...b,
    // the bag of IO from featureGroup1System
    ...k,
    ...v,
    sizes: c2,
    ...g
  }),
  X(
    Et,
    ue,
    at2,
    qo,
    Uo,
    $t,
    ce,
    Jo,
    Zo,
    Nn,
    Qo
  )
);
function tr(t2, e) {
  const n2 = {}, o = {};
  let r2 = 0;
  const s = t2.length;
  for (; r2 < s; )
    o[t2[r2]] = 1, r2 += 1;
  for (const i2 in e)
    Object.hasOwn(o, i2) || (n2[i2] = e[i2]);
  return n2;
}
const pe = typeof document < "u" ? React20.useLayoutEffect : React20.useEffect;
function Ye(t2, e, n2) {
  const o = Object.keys(e.required || {}), r2 = Object.keys(e.optional || {}), s = Object.keys(e.methods || {}), i2 = Object.keys(e.events || {}), l2 = React20.createContext({});
  function c2(p, u) {
    p.propsReady && G(p.propsReady, false);
    for (const T of o) {
      const b = p[e.required[T]];
      G(b, u[T]);
    }
    for (const T of r2)
      if (T in u) {
        const b = p[e.optional[T]];
        G(b, u[T]);
      }
    p.propsReady && G(p.propsReady, true);
  }
  function a2(p) {
    return s.reduce((u, T) => (u[T] = (b) => {
      const f = p[e.methods[T]];
      G(f, b);
    }, u), {});
  }
  function m(p) {
    return i2.reduce((u, T) => (u[T] = Io(p[e.events[T]]), u), {});
  }
  const x = React20.forwardRef((p, u) => {
    const { children: T, ...b } = p, [f] = React20.useState(() => ve(xo(t2), (B) => {
      c2(B, b);
    })), [d] = React20.useState(an(m, f));
    pe(() => {
      for (const B of i2)
        B in b && K(d[B], b[B]);
      return () => {
        Object.values(d).map(Ge);
      };
    }, [b, d, f]), pe(() => {
      c2(f, b);
    }), React20.useImperativeHandle(u, un(a2(f)));
    const y = n2;
    return /* @__PURE__ */ jsxRuntimeExports.jsx(l2.Provider, { value: f, children: n2 ? /* @__PURE__ */ jsxRuntimeExports.jsx(y, { ...tr([...o, ...r2, ...i2], b), children: T }) : T });
  }), h = (p) => {
    const u = React20.useContext(l2);
    return React20.useCallback(
      (T) => {
        G(u[p], T);
      },
      [u, p]
    );
  }, I = (p) => {
    const T = React20.useContext(l2)[p], b = React20.useCallback(
      (f) => K(T, f),
      [T]
    );
    return React20.useSyncExternalStore(
      b,
      () => ot(T),
      () => ot(T)
    );
  }, C = (p) => {
    const T = React20.useContext(l2)[p], [b, f] = React20.useState(an(ot, T));
    return pe(
      () => K(T, (d) => {
        d !== b && f(un(d));
      }),
      [T, b]
    ), b;
  }, v = React20.version.startsWith("18") ? I : C;
  return {
    Component: x,
    useEmitter: (p, u) => {
      const b = React20.useContext(l2)[p];
      pe(() => K(b, u), [u, b]);
    },
    useEmitterValue: v,
    usePublisher: h
  };
}
const be = React20.createContext(void 0), Jn = React20.createContext(void 0), Qn = typeof document < "u" ? React20.useLayoutEffect : React20.useEffect;
function ke(t2) {
  return "self" in t2;
}
function er(t2) {
  return "body" in t2;
}
function to(t2, e, n2, o = Yt, r2, s) {
  const i2 = React20.useRef(null), l2 = React20.useRef(null), c2 = React20.useRef(null), a2 = React20.useCallback(
    (h) => {
      let I, C, v;
      const g = h.target;
      if (er(g) || ke(g)) {
        const u = ke(g) ? g : g.defaultView;
        v = s ? u.scrollX : u.scrollY, I = s ? u.document.documentElement.scrollWidth : u.document.documentElement.scrollHeight, C = s ? u.innerWidth : u.innerHeight;
      } else
        v = s ? g.scrollLeft : g.scrollTop, I = s ? g.scrollWidth : g.scrollHeight, C = s ? g.offsetWidth : g.offsetHeight;
      const p = () => {
        t2({
          scrollHeight: I,
          scrollTop: Math.max(v, 0),
          viewportHeight: C
        });
      };
      h.suppressFlushSync ? p() : ReactDOM.flushSync(p), l2.current !== null && (v === l2.current || v <= 0 || v === I - C) && (l2.current = null, e(true), c2.current && (clearTimeout(c2.current), c2.current = null));
    },
    [t2, e, s]
  );
  React20.useEffect(() => {
    const h = r2 || i2.current;
    return o(r2 || i2.current), a2({ suppressFlushSync: true, target: h }), h.addEventListener("scroll", a2, { passive: true }), () => {
      o(null), h.removeEventListener("scroll", a2);
    };
  }, [i2, a2, n2, o, r2]);
  function m(h) {
    const I = i2.current;
    if (!I || (s ? "offsetWidth" in I && I.offsetWidth === 0 : "offsetHeight" in I && I.offsetHeight === 0))
      return;
    const C = h.behavior === "smooth";
    let v, g, p;
    ke(I) ? (g = Math.max(
      vt$1(I.document.documentElement, s ? "width" : "height"),
      s ? I.document.documentElement.scrollWidth : I.document.documentElement.scrollHeight
    ), v = s ? I.innerWidth : I.innerHeight, p = s ? window.scrollX : window.scrollY) : (g = I[s ? "scrollWidth" : "scrollHeight"], v = vt$1(I, s ? "width" : "height"), p = I[s ? "scrollLeft" : "scrollTop"]);
    const u = g - v;
    if (h.top = Math.ceil(Math.max(Math.min(u, h.top), 0)), $n(v, g) || h.top === p) {
      t2({ scrollHeight: g, scrollTop: p, viewportHeight: v }), C && e(true);
      return;
    }
    C ? (l2.current = h.top, c2.current && clearTimeout(c2.current), c2.current = setTimeout(() => {
      c2.current = null, l2.current = null, e(true);
    }, 1e3)) : l2.current = null, s && (h = { behavior: h.behavior, left: h.top }), I.scrollTo(h);
  }
  function x(h) {
    s && (h = { behavior: h.behavior, left: h.top }), i2.current.scrollBy(h);
  }
  return { scrollByCallback: x, scrollerRef: i2, scrollToCallback: m };
}
const Fe = "-webkit-sticky", Tn = "sticky", Ze = Zn(() => {
  if (typeof document > "u")
    return Tn;
  const t2 = document.createElement("div");
  return t2.style.position = Fe, t2.style.position === Fe ? Fe : Tn;
});
function Xe(t2) {
  return t2;
}
const nr = /* @__PURE__ */ U(() => {
  const t2 = w((l2) => `Item ${l2}`), e = w((l2) => `Group ${l2}`), n2 = w({}), o = w(Xe), r2 = w("div"), s = w(Yt), i2 = (l2, c2 = null) => ct(
    S(
      n2,
      E((a2) => a2[l2]),
      Y()
    ),
    c2
  );
  return {
    components: n2,
    computeItemKey: o,
    EmptyPlaceholder: i2("EmptyPlaceholder"),
    FooterComponent: i2("Footer"),
    GroupComponent: i2("Group", "div"),
    groupContent: e,
    HeaderComponent: i2("Header"),
    HeaderFooterTag: r2,
    ItemComponent: i2("Item", "div"),
    itemContent: t2,
    ListComponent: i2("List", "div"),
    ScrollerComponent: i2("Scroller", "div"),
    scrollerRef: s,
    ScrollSeekPlaceholder: i2("ScrollSeekPlaceholder"),
    TopItemListComponent: i2("TopItemList")
  };
}), or = /* @__PURE__ */ U(
  ([t2, e]) => ({ ...t2, ...e }),
  X(Xn, nr)
), rr = ({ height: t2 }) => /* @__PURE__ */ jsxRuntimeExports.jsx("div", { style: { height: t2 } }), sr = { overflowAnchor: "none", position: Ze(), zIndex: 1 }, eo = { overflowAnchor: "none" }, ir = { ...eo, display: "inline-block", height: "100%" }, Cn = /* @__PURE__ */ React20.memo(function({ showTopList: e = false }) {
  const n2 = M("listState"), o = gt("sizeRanges"), r2 = M("useWindowScroll"), s = M("customScrollParent"), i2 = gt("windowScrollContainerState"), l2 = gt("scrollContainerState"), c2 = s || r2 ? i2 : l2, a2 = M("itemContent"), m = M("context"), x = M("groupContent"), h = M("trackItemSizes"), I = M("itemSize"), C = M("log"), v = gt("gap"), g = M("horizontalDirection"), { callbackRef: p } = On(
    o,
    I,
    h,
    e ? Yt : c2,
    C,
    v,
    s,
    g,
    M("skipAnimationFrameInResizeObserver")
  ), [u, T] = React20.useState(0);
  tn("deviation", (F) => {
    u !== F && T(F);
  });
  const b = M("EmptyPlaceholder"), f = M("ScrollSeekPlaceholder") || rr, d = M("ListComponent"), y = M("ItemComponent"), B = M("GroupComponent"), k = M("computeItemKey"), L = M("isSeeking"), z = M("groupIndices").length > 0, _ = M("alignToBottom"), J = M("initialItemFinalLocationReached"), nt = e ? {} : {
    boxSizing: "border-box",
    ...g ? {
      display: "inline-block",
      height: "100%",
      marginLeft: u !== 0 ? u : _ ? "auto" : 0,
      paddingLeft: n2.offsetTop,
      paddingRight: n2.offsetBottom,
      whiteSpace: "nowrap"
    } : {
      marginTop: u !== 0 ? u : _ ? "auto" : 0,
      paddingBottom: n2.offsetBottom,
      paddingTop: n2.offsetTop
    },
    ...J ? {} : { visibility: "hidden" }
  };
  return !e && n2.totalCount === 0 && b ? /* @__PURE__ */ jsxRuntimeExports.jsx(b, { ...Z$1(b, m) }) : /* @__PURE__ */ jsxRuntimeExports.jsx(
    d,
    {
      ...Z$1(d, m),
      "data-testid": e ? "virtuoso-top-item-list" : "virtuoso-item-list",
      ref: p,
      style: nt,
      children: (e ? n2.topItems : n2.items).map((F) => {
        const q = F.originalIndex, it = k(q + n2.firstItemIndex, F.data, m);
        return L ? /* @__PURE__ */ reactExports.createElement(
          f,
          {
            ...Z$1(f, m),
            height: F.size,
            index: F.index,
            key: it,
            type: F.type || "item",
            ...F.type === "group" ? {} : { groupIndex: F.groupIndex }
          }
        ) : F.type === "group" ? /* @__PURE__ */ reactExports.createElement(
          B,
          {
            ...Z$1(B, m),
            "data-index": q,
            "data-item-index": F.index,
            "data-known-size": F.size,
            key: it,
            style: sr
          },
          x(F.index, m)
        ) : /* @__PURE__ */ reactExports.createElement(
          y,
          {
            ...Z$1(y, m),
            ...no(y, F.data),
            "data-index": q,
            "data-item-group-index": F.groupIndex,
            "data-item-index": F.index,
            "data-known-size": F.size,
            key: it,
            style: g ? ir : eo
          },
          z ? a2(F.index, F.groupIndex, F.data, m) : a2(F.index, F.data, m)
        );
      })
    }
  );
}), lr = {
  height: "100%",
  outline: "none",
  overflowY: "auto",
  position: "relative",
  WebkitOverflowScrolling: "touch"
}, cr = {
  outline: "none",
  overflowX: "auto",
  position: "relative"
}, Zt = (t2) => ({
  height: "100%",
  position: "absolute",
  top: 0,
  width: "100%",
  ...t2 ? { display: "flex", flexDirection: "column" } : {}
}), ur = {
  position: Ze(),
  top: 0,
  width: "100%",
  zIndex: 1
};
function Z$1(t2, e) {
  if (typeof t2 != "string")
    return { context: e };
}
function no(t2, e) {
  return { item: typeof t2 == "string" ? void 0 : e };
}
const ar = /* @__PURE__ */ React20.memo(function() {
  const e = M("HeaderComponent"), n2 = gt("headerHeight"), o = M("HeaderFooterTag"), r2 = Ht(
    React20.useMemo(
      () => (i2) => {
        n2(vt$1(i2, "height"));
      },
      [n2]
    ),
    true,
    M("skipAnimationFrameInResizeObserver")
  ), s = M("context");
  return e ? /* @__PURE__ */ jsxRuntimeExports.jsx(o, { ref: r2, children: /* @__PURE__ */ jsxRuntimeExports.jsx(e, { ...Z$1(e, s) }) }) : null;
}), dr = /* @__PURE__ */ React20.memo(function() {
  const e = M("FooterComponent"), n2 = gt("footerHeight"), o = M("HeaderFooterTag"), r2 = Ht(
    React20.useMemo(
      () => (i2) => {
        n2(vt$1(i2, "height"));
      },
      [n2]
    ),
    true,
    M("skipAnimationFrameInResizeObserver")
  ), s = M("context");
  return e ? /* @__PURE__ */ jsxRuntimeExports.jsx(o, { ref: r2, children: /* @__PURE__ */ jsxRuntimeExports.jsx(e, { ...Z$1(e, s) }) }) : null;
});
function Je({ useEmitter: t2, useEmitterValue: e, usePublisher: n2 }) {
  return React20.memo(function({ children: s, style: i2, context: l2, ...c2 }) {
    const a2 = n2("scrollContainerState"), m = e("ScrollerComponent"), x = n2("smoothScrollTargetReached"), h = e("scrollerRef"), I = e("horizontalDirection") || false, { scrollByCallback: C, scrollerRef: v, scrollToCallback: g } = to(
      a2,
      x,
      m,
      h,
      void 0,
      I
    );
    return t2("scrollTo", g), t2("scrollBy", C), /* @__PURE__ */ jsxRuntimeExports.jsx(
      m,
      {
        "data-testid": "virtuoso-scroller",
        "data-virtuoso-scroller": true,
        ref: v,
        style: { ...I ? cr : lr, ...i2 },
        tabIndex: 0,
        ...c2,
        ...Z$1(m, l2),
        children: s
      }
    );
  });
}
function Qe({ useEmitter: t2, useEmitterValue: e, usePublisher: n2 }) {
  return React20.memo(function({ children: s, style: i2, context: l2, ...c2 }) {
    const a2 = n2("windowScrollContainerState"), m = e("ScrollerComponent"), x = n2("smoothScrollTargetReached"), h = e("totalListHeight"), I = e("deviation"), C = e("customScrollParent"), v = React20.useRef(null), g = e("scrollerRef"), { scrollByCallback: p, scrollerRef: u, scrollToCallback: T } = to(
      a2,
      x,
      m,
      g,
      C
    );
    return Qn(() => {
      var b;
      return u.current = C || ((b = v.current) == null ? void 0 : b.ownerDocument.defaultView), () => {
        u.current = null;
      };
    }, [u, C]), t2("windowScrollTo", T), t2("scrollBy", p), /* @__PURE__ */ jsxRuntimeExports.jsx(
      m,
      {
        ref: v,
        "data-virtuoso-scroller": true,
        style: { position: "relative", ...i2, ...h !== 0 ? { height: h + I } : {} },
        ...c2,
        ...Z$1(m, l2),
        children: s
      }
    );
  });
}
const fr = ({ children: t2 }) => {
  const e = React20.useContext(be), n2 = gt("viewportHeight"), o = gt("fixedItemHeight"), r2 = M("alignToBottom"), s = M("horizontalDirection"), i2 = React20.useMemo(
    () => ne(n2, (c2) => vt$1(c2, s ? "width" : "height")),
    [n2, s]
  ), l2 = Ht(i2, true, M("skipAnimationFrameInResizeObserver"));
  return React20.useEffect(() => {
    e && (n2(e.viewportHeight), o(e.itemHeight));
  }, [e, n2, o]), /* @__PURE__ */ jsxRuntimeExports.jsx("div", { "data-viewport-type": "element", ref: l2, style: Zt(r2), children: t2 });
}, mr = ({ children: t2 }) => {
  const e = React20.useContext(be), n2 = gt("windowViewportRect"), o = gt("fixedItemHeight"), r2 = M("customScrollParent"), s = Ne(
    n2,
    r2,
    M("skipAnimationFrameInResizeObserver")
  ), i2 = M("alignToBottom");
  return React20.useEffect(() => {
    e && (o(e.itemHeight), n2({ offsetTop: 0, visibleHeight: e.viewportHeight, visibleWidth: 100 }));
  }, [e, n2, o]), /* @__PURE__ */ jsxRuntimeExports.jsx("div", { "data-viewport-type": "window", ref: s, style: Zt(i2), children: t2 });
}, pr = ({ children: t2 }) => {
  const e = M("TopItemListComponent") || "div", n2 = M("headerHeight"), o = { ...ur, marginTop: `${n2}px` }, r2 = M("context");
  return /* @__PURE__ */ jsxRuntimeExports.jsx(e, { style: o, ...Z$1(e, r2), children: t2 });
}, hr$1 = /* @__PURE__ */ React20.memo(function(e) {
  const n2 = M("useWindowScroll"), o = M("topItemsIndexes").length > 0, r2 = M("customScrollParent"), s = M("context");
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(r2 || n2 ? Ir : gr, { ...e, context: s, children: [
    o && /* @__PURE__ */ jsxRuntimeExports.jsx(pr, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(Cn, { showTopList: true }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(r2 || n2 ? mr : fr, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(ar, {}),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Cn, {}),
      /* @__PURE__ */ jsxRuntimeExports.jsx(dr, {})
    ] })
  ] });
}), {
  Component: oo,
  useEmitter: tn,
  useEmitterValue: M,
  usePublisher: gt
} = /* @__PURE__ */ Ye(
  or,
  {
    required: {},
    optional: {
      restoreStateFrom: "restoreStateFrom",
      context: "context",
      followOutput: "followOutput",
      scrollIntoViewOnChange: "scrollIntoViewOnChange",
      itemContent: "itemContent",
      groupContent: "groupContent",
      overscan: "overscan",
      increaseViewportBy: "increaseViewportBy",
      totalCount: "totalCount",
      groupCounts: "groupCounts",
      topItemCount: "topItemCount",
      firstItemIndex: "firstItemIndex",
      initialTopMostItemIndex: "initialTopMostItemIndex",
      components: "components",
      atBottomThreshold: "atBottomThreshold",
      atTopThreshold: "atTopThreshold",
      computeItemKey: "computeItemKey",
      defaultItemHeight: "defaultItemHeight",
      fixedItemHeight: "fixedItemHeight",
      itemSize: "itemSize",
      scrollSeekConfiguration: "scrollSeekConfiguration",
      headerFooterTag: "HeaderFooterTag",
      data: "data",
      initialItemCount: "initialItemCount",
      initialScrollTop: "initialScrollTop",
      alignToBottom: "alignToBottom",
      useWindowScroll: "useWindowScroll",
      customScrollParent: "customScrollParent",
      scrollerRef: "scrollerRef",
      logLevel: "logLevel",
      horizontalDirection: "horizontalDirection",
      skipAnimationFrameInResizeObserver: "skipAnimationFrameInResizeObserver"
    },
    methods: {
      scrollToIndex: "scrollToIndex",
      scrollIntoView: "scrollIntoView",
      scrollTo: "scrollTo",
      scrollBy: "scrollBy",
      autoscrollToBottom: "autoscrollToBottom",
      getState: "getState"
    },
    events: {
      isScrolling: "isScrolling",
      endReached: "endReached",
      startReached: "startReached",
      rangeChanged: "rangeChanged",
      atBottomStateChange: "atBottomStateChange",
      atTopStateChange: "atTopStateChange",
      totalListHeightChanged: "totalListHeightChanged",
      itemsRendered: "itemsRendered",
      groupIndices: "groupIndices"
    }
  },
  hr$1
), gr = /* @__PURE__ */ Je({ useEmitter: tn, useEmitterValue: M, usePublisher: gt }), Ir = /* @__PURE__ */ Qe({ useEmitter: tn, useEmitterValue: M, usePublisher: gt }), qr = oo, Sr = /* @__PURE__ */ U(() => {
  const t2 = w((a2) => /* @__PURE__ */ jsxRuntimeExports.jsxs("td", { children: [
    "Item $",
    a2
  ] })), e = w(null), n2 = w((a2) => /* @__PURE__ */ jsxRuntimeExports.jsxs("td", { colSpan: 1e3, children: [
    "Group ",
    a2
  ] })), o = w(null), r2 = w(null), s = w({}), i2 = w(Xe), l2 = w(Yt), c2 = (a2, m = null) => ct(
    S(
      s,
      E((x) => x[a2]),
      Y()
    ),
    m
  );
  return {
    components: s,
    computeItemKey: i2,
    context: e,
    EmptyPlaceholder: c2("EmptyPlaceholder"),
    FillerRow: c2("FillerRow"),
    fixedFooterContent: r2,
    fixedHeaderContent: o,
    itemContent: t2,
    groupContent: n2,
    ScrollerComponent: c2("Scroller", "div"),
    scrollerRef: l2,
    ScrollSeekPlaceholder: c2("ScrollSeekPlaceholder"),
    TableBodyComponent: c2("TableBody", "tbody"),
    TableComponent: c2("Table", "table"),
    TableFooterComponent: c2("TableFoot", "tfoot"),
    TableHeadComponent: c2("TableHead", "thead"),
    TableRowComponent: c2("TableRow", "tr"),
    GroupComponent: c2("Group", "tr")
  };
});
/* @__PURE__ */ U(
  ([t2, e]) => ({ ...t2, ...e }),
  X(Xn, Sr)
);
({ position: Ze() });
const yn = {
  bottom: 0,
  itemHeight: 0,
  items: [],
  itemWidth: 0,
  offsetBottom: 0,
  offsetTop: 0,
  top: 0
}, Br = {
  bottom: 0,
  itemHeight: 0,
  items: [{ index: 0 }],
  itemWidth: 0,
  offsetBottom: 0,
  offsetTop: 0,
  top: 0
}, { ceil: Rn, floor: Ce, max: ee, min: Oe, round: bn } = Math;
function Hn(t2, e, n2) {
  return Array.from({ length: e - t2 + 1 }).map((o, r2) => ({ data: n2 === null ? null : n2[r2 + t2], index: r2 + t2 }));
}
function kr(t2) {
  return {
    ...Br,
    items: t2
  };
}
function he(t2, e) {
  return t2 && t2.width === e.width && t2.height === e.height;
}
function Fr(t2, e) {
  return t2 && t2.column === e.column && t2.row === e.row;
}
const Or = /* @__PURE__ */ U(
  ([
    { increaseViewportBy: t2, listBoundary: e, overscan: n2, visibleRange: o },
    { footerHeight: r2, headerHeight: s, scrollBy: i2, scrollContainerState: l2, scrollTo: c2, scrollTop: a2, smoothScrollTargetReached: m, viewportHeight: x },
    h,
    I,
    { didMount: C, propsReady: v },
    { customScrollParent: g, useWindowScroll: p, windowScrollContainerState: u, windowScrollTo: T, windowViewportRect: b },
    f
  ]) => {
    const d = w(0), y = w(0), B = w(yn), k = w({ height: 0, width: 0 }), L = w({ height: 0, width: 0 }), z = $(), _ = $(), J = w(0), nt = w(null), F = w({ column: 0, row: 0 }), q = $(), it = $(), dt = w(false), St = w(0), ft = w(true), ut = w(false), At = w(false);
    K(
      S(
        C,
        N(St),
        A(([R, D]) => !!D)
      ),
      () => {
        G(ft, false);
      }
    ), K(
      S(
        rt(C, ft, L, k, St, ut),
        A(([R, D, Q, lt, , tt]) => R && !D && Q.height !== 0 && lt.height !== 0 && !tt)
      ),
      ([, , , , R]) => {
        G(ut, true), Ue(1, () => {
          G(z, R);
        }), Tt(S(a2), () => {
          G(e, [0, 0]), G(ft, true);
        });
      }
    ), O(
      S(
        it,
        A((R) => R != null && R.scrollTop > 0),
        Rt(0)
      ),
      y
    ), K(
      S(
        C,
        N(it),
        A(([, R]) => R != null)
      ),
      ([, R]) => {
        R && (G(k, R.viewport), G(L, R.item), G(F, R.gap), R.scrollTop > 0 && (G(dt, true), Tt(S(a2, Dt(1)), (D) => {
          G(dt, false);
        }), G(c2, { top: R.scrollTop })));
      }
    ), O(
      S(
        k,
        E(({ height: R }) => R)
      ),
      x
    ), O(
      S(
        rt(
          V(k, he),
          V(L, he),
          V(F, (R, D) => R && R.column === D.column && R.row === D.row),
          V(a2)
        ),
        E(([R, D, Q, lt]) => ({
          gap: Q,
          item: D,
          scrollTop: lt,
          viewport: R
        }))
      ),
      q
    ), O(
      S(
        rt(
          V(d),
          o,
          V(F, Fr),
          V(L, he),
          V(k, he),
          V(nt),
          V(y),
          V(dt),
          V(ft),
          V(St)
        ),
        A(([, , , , , , , R]) => !R),
        E(
          ([
            R,
            [D, Q],
            lt,
            tt,
            Ft,
            Jt,
            Ut,
            ,
            de,
            Ot
          ]) => {
            const { column: Lt, row: Qt } = lt, { height: fe, width: He } = tt, { width: nn } = Ft;
            if (Ut === 0 && (R === 0 || nn === 0))
              return yn;
            if (He === 0) {
              const cn = Ke(Ot, R), co = cn + Math.max(Ut - 1, 0);
              return kr(Hn(cn, co, Jt));
            }
            const me = so(nn, He, Lt);
            let Kt, Wt;
            de ? D === 0 && Q === 0 && Ut > 0 ? (Kt = 0, Wt = Ut - 1) : (Kt = me * Ce((D + Qt) / (fe + Qt)), Wt = me * Rn((Q + Qt) / (fe + Qt)) - 1, Wt = Oe(R - 1, ee(Wt, me - 1)), Kt = Oe(Wt, ee(0, Kt))) : (Kt = 0, Wt = -1);
            const on = Hn(Kt, Wt, Jt), { bottom: rn, top: sn } = En(Ft, lt, tt, on), ln = Rn(R / me), lo = ln * fe + (ln - 1) * Qt - rn;
            return { bottom: rn, itemHeight: fe, items: on, itemWidth: He, offsetBottom: lo, offsetTop: sn, top: sn };
          }
        )
      ),
      B
    ), O(
      S(
        nt,
        A((R) => R !== null),
        E((R) => R.length)
      ),
      d
    ), O(
      S(
        rt(k, L, B, F),
        A(([R, D, { items: Q }]) => Q.length > 0 && D.height !== 0 && R.height !== 0),
        E(([R, D, { items: Q }, lt]) => {
          const { bottom: tt, top: Ft } = En(R, lt, D, Q);
          return [Ft, tt];
        }),
        Y(se)
      ),
      e
    );
    const xt = w(false);
    O(
      S(
        a2,
        N(xt),
        E(([R, D]) => D || R !== 0)
      ),
      xt
    );
    const Xt = ht(
      S(
        rt(B, d),
        A(([{ items: R }]) => R.length > 0),
        N(xt),
        A(([[R, D], Q]) => {
          const tt = R.items[R.items.length - 1].index === D - 1;
          return (Q || R.bottom > 0 && R.itemHeight > 0 && R.offsetBottom === 0 && R.items.length === D) && tt;
        }),
        E(([[, R]]) => R - 1),
        Y()
      )
    ), Mt = ht(
      S(
        V(B),
        A(({ items: R }) => R.length > 0 && R[0].index === 0),
        Rt(0),
        Y()
      )
    ), yt = ht(
      S(
        V(B),
        N(dt),
        A(([{ items: R }, D]) => R.length > 0 && !D),
        E(([{ items: R }]) => ({
          endIndex: R[R.length - 1].index,
          startIndex: R[0].index
        })),
        Y(Mn),
        kt(0)
      )
    );
    O(yt, I.scrollSeekRangeChanged), O(
      S(
        z,
        N(k, L, d, F),
        E(([R, D, Q, lt, tt]) => {
          const Ft = Dn(R), { align: Jt, behavior: Ut, offset: de } = Ft;
          let Ot = Ft.index;
          Ot === "LAST" && (Ot = lt - 1), Ot = ee(0, Ot, Oe(lt - 1, Ot));
          let Lt = Me(D, tt, Q, Ot);
          return Jt === "end" ? Lt = bn(Lt - D.height + Q.height) : Jt === "center" && (Lt = bn(Lt - D.height / 2 + Q.height / 2)), de && (Lt += de), { behavior: Ut, top: Lt };
        })
      ),
      c2
    );
    const Bt = ct(
      S(
        B,
        E((R) => R.offsetBottom + R.bottom)
      ),
      0
    );
    return O(
      S(
        b,
        E((R) => ({ height: R.visibleHeight, width: R.visibleWidth }))
      ),
      k
    ), {
      customScrollParent: g,
      // input
      data: nt,
      deviation: J,
      footerHeight: r2,
      gap: F,
      headerHeight: s,
      increaseViewportBy: t2,
      initialItemCount: y,
      itemDimensions: L,
      overscan: n2,
      restoreStateFrom: it,
      scrollBy: i2,
      scrollContainerState: l2,
      scrollHeight: _,
      scrollTo: c2,
      scrollToIndex: z,
      scrollTop: a2,
      smoothScrollTargetReached: m,
      totalCount: d,
      useWindowScroll: p,
      viewportDimensions: k,
      windowScrollContainerState: u,
      windowScrollTo: T,
      windowViewportRect: b,
      ...I,
      // output
      gridState: B,
      horizontalDirection: At,
      initialTopMostItemIndex: St,
      totalListHeight: Bt,
      ...h,
      endReached: Xt,
      propsReady: v,
      rangeChanged: yt,
      startReached: Mt,
      stateChanged: q,
      stateRestoreInProgress: dt,
      ...f
    };
  },
  X(je, at2, ae, Yn, Pt, qe, Vt$1)
);
function so(t2, e, n2) {
  return ee(1, Ce((t2 + n2) / (Ce(e) + n2)));
}
function En(t2, e, n2, o) {
  const { height: r2 } = n2;
  if (r2 === void 0 || o.length === 0)
    return { bottom: 0, top: 0 };
  const s = Me(t2, e, n2, o[0].index);
  return { bottom: Me(t2, e, n2, o[o.length - 1].index) + r2, top: s };
}
function Me(t2, e, n2, o) {
  const r2 = so(t2.width, n2.width, e.column), s = Ce(o / r2), i2 = s * n2.height + ee(0, s - 1) * e.row;
  return i2 > 0 ? i2 + e.row : i2;
}
const Lr = /* @__PURE__ */ U(() => {
  const t2 = w((x) => `Item ${x}`), e = w({}), n2 = w(null), o = w("virtuoso-grid-item"), r2 = w("virtuoso-grid-list"), s = w(Xe), i2 = w("div"), l2 = w(Yt), c2 = (x, h = null) => ct(
    S(
      e,
      E((I) => I[x]),
      Y()
    ),
    h
  ), a2 = w(false), m = w(false);
  return O(V(m), a2), {
    components: e,
    computeItemKey: s,
    context: n2,
    FooterComponent: c2("Footer"),
    HeaderComponent: c2("Header"),
    headerFooterTag: i2,
    itemClassName: o,
    ItemComponent: c2("Item", "div"),
    itemContent: t2,
    listClassName: r2,
    ListComponent: c2("List", "div"),
    readyStateChanged: a2,
    reportReadyState: m,
    ScrollerComponent: c2("Scroller", "div"),
    scrollerRef: l2,
    ScrollSeekPlaceholder: c2("ScrollSeekPlaceholder", "div")
  };
}), zr = /* @__PURE__ */ U(
  ([t2, e]) => ({ ...t2, ...e }),
  X(Or, Lr)
), Vr = /* @__PURE__ */ React20.memo(function() {
  const e = et("gridState"), n2 = et("listClassName"), o = et("itemClassName"), r2 = et("itemContent"), s = et("computeItemKey"), i2 = et("isSeeking"), l2 = It("scrollHeight"), c2 = et("ItemComponent"), a2 = et("ListComponent"), m = et("ScrollSeekPlaceholder"), x = et("context"), h = It("itemDimensions"), I = It("gap"), C = et("log"), v = et("stateRestoreInProgress"), g = It("reportReadyState"), p = Ht(
    React20.useMemo(
      () => (u) => {
        const T = u.parentElement.parentElement.scrollHeight;
        l2(T);
        const b = u.firstChild;
        if (b) {
          const { height: f, width: d } = b.getBoundingClientRect();
          h({ height: f, width: d });
        }
        I({
          column: Bn("column-gap", getComputedStyle(u).columnGap, C),
          row: Bn("row-gap", getComputedStyle(u).rowGap, C)
        });
      },
      [l2, h, I, C]
    ),
    true,
    false
  );
  return Qn(() => {
    e.itemHeight > 0 && e.itemWidth > 0 && g(true);
  }, [e]), v ? null : /* @__PURE__ */ jsxRuntimeExports.jsx(
    a2,
    {
      className: n2,
      ref: p,
      ...Z$1(a2, x),
      "data-testid": "virtuoso-item-list",
      style: { paddingBottom: e.offsetBottom, paddingTop: e.offsetTop },
      children: e.items.map((u) => {
        const T = s(u.index, u.data, x);
        return i2 ? /* @__PURE__ */ jsxRuntimeExports.jsx(
          m,
          {
            ...Z$1(m, x),
            height: e.itemHeight,
            index: u.index,
            width: e.itemWidth
          },
          T
        ) : /* @__PURE__ */ reactExports.createElement(
          c2,
          {
            ...Z$1(c2, x),
            className: o,
            "data-index": u.index,
            key: T
          },
          r2(u.index, u.data, x)
        );
      })
    }
  );
}), Pr = React20.memo(function() {
  const e = et("HeaderComponent"), n2 = It("headerHeight"), o = et("headerFooterTag"), r2 = Ht(
    React20.useMemo(
      () => (i2) => {
        n2(vt$1(i2, "height"));
      },
      [n2]
    ),
    true,
    false
  ), s = et("context");
  return e ? /* @__PURE__ */ jsxRuntimeExports.jsx(o, { ref: r2, children: /* @__PURE__ */ jsxRuntimeExports.jsx(e, { ...Z$1(e, s) }) }) : null;
}), Ar = React20.memo(function() {
  const e = et("FooterComponent"), n2 = It("footerHeight"), o = et("headerFooterTag"), r2 = Ht(
    React20.useMemo(
      () => (i2) => {
        n2(vt$1(i2, "height"));
      },
      [n2]
    ),
    true,
    false
  ), s = et("context");
  return e ? /* @__PURE__ */ jsxRuntimeExports.jsx(o, { ref: r2, children: /* @__PURE__ */ jsxRuntimeExports.jsx(e, { ...Z$1(e, s) }) }) : null;
}), Mr = ({ children: t2 }) => {
  const e = React20.useContext(Jn), n2 = It("itemDimensions"), o = It("viewportDimensions"), r2 = Ht(
    React20.useMemo(
      () => (s) => {
        o(s.getBoundingClientRect());
      },
      [o]
    ),
    true,
    false
  );
  return React20.useEffect(() => {
    e && (o({ height: e.viewportHeight, width: e.viewportWidth }), n2({ height: e.itemHeight, width: e.itemWidth }));
  }, [e, o, n2]), /* @__PURE__ */ jsxRuntimeExports.jsx("div", { ref: r2, style: Zt(false), children: t2 });
}, Wr = ({ children: t2 }) => {
  const e = React20.useContext(Jn), n2 = It("windowViewportRect"), o = It("itemDimensions"), r2 = et("customScrollParent"), s = Ne(n2, r2, false);
  return React20.useEffect(() => {
    e && (o({ height: e.itemHeight, width: e.itemWidth }), n2({ offsetTop: 0, visibleHeight: e.viewportHeight, visibleWidth: e.viewportWidth }));
  }, [e, n2, o]), /* @__PURE__ */ jsxRuntimeExports.jsx("div", { ref: s, style: Zt(false), children: t2 });
}, Gr = /* @__PURE__ */ React20.memo(function({ ...e }) {
  const n2 = et("useWindowScroll"), o = et("customScrollParent"), r2 = o || n2 ? Dr : Nr, s = o || n2 ? Wr : Mr, i2 = et("context");
  return /* @__PURE__ */ jsxRuntimeExports.jsx(r2, { ...e, ...Z$1(r2, i2), children: /* @__PURE__ */ jsxRuntimeExports.jsxs(s, { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(Pr, {}),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Vr, {}),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Ar, {})
  ] }) });
}), {
  useEmitter: io,
  useEmitterValue: et,
  usePublisher: It
} = /* @__PURE__ */ Ye(
  zr,
  {
    optional: {
      context: "context",
      totalCount: "totalCount",
      overscan: "overscan",
      itemContent: "itemContent",
      components: "components",
      computeItemKey: "computeItemKey",
      data: "data",
      initialItemCount: "initialItemCount",
      scrollSeekConfiguration: "scrollSeekConfiguration",
      headerFooterTag: "headerFooterTag",
      listClassName: "listClassName",
      itemClassName: "itemClassName",
      useWindowScroll: "useWindowScroll",
      customScrollParent: "customScrollParent",
      scrollerRef: "scrollerRef",
      logLevel: "logLevel",
      restoreStateFrom: "restoreStateFrom",
      initialTopMostItemIndex: "initialTopMostItemIndex",
      increaseViewportBy: "increaseViewportBy"
    },
    methods: {
      scrollTo: "scrollTo",
      scrollBy: "scrollBy",
      scrollToIndex: "scrollToIndex"
    },
    events: {
      isScrolling: "isScrolling",
      endReached: "endReached",
      startReached: "startReached",
      rangeChanged: "rangeChanged",
      atBottomStateChange: "atBottomStateChange",
      atTopStateChange: "atTopStateChange",
      stateChanged: "stateChanged",
      readyStateChanged: "readyStateChanged"
    }
  },
  Gr
), Nr = /* @__PURE__ */ Je({ useEmitter: io, useEmitterValue: et, usePublisher: It }), Dr = /* @__PURE__ */ Qe({ useEmitter: io, useEmitterValue: et, usePublisher: It });
function Bn(t2, e, n2) {
  return e !== "normal" && !(e != null && e.endsWith("px")) && n2(`${t2} was not resolved to pixel value correctly`, e, mt.WARN), e === "normal" ? 0 : parseInt(e != null ? e : "0", 10);
}
function useProperty(id2, propertyName, options) {
  const defaultValue = options?.defaultValue;
  const cleanup = options?.cleanup ?? true;
  const setPropertyValue = useStore((state) => state.setPropertyValue);
  const removePropertyValue = useStore((state) => state.removePropertyValue);
  const propertyValue = useStore(
    reactExports.useCallback(
      (state) => state.getPropertyValue(id2, propertyName, defaultValue),
      [id2, propertyName, defaultValue]
    )
  );
  const setValue = reactExports.useCallback(
    (value2) => {
      setPropertyValue(id2, propertyName, value2);
    },
    [id2, propertyName, setPropertyValue]
  );
  const removeValue = reactExports.useCallback(() => {
    removePropertyValue(id2, propertyName);
  }, [id2, propertyName, removePropertyValue]);
  reactExports.useEffect(() => {
    return () => {
      if (cleanup) {
        removePropertyValue(id2, propertyName);
      }
    };
  }, [id2, propertyName, removePropertyValue, cleanup]);
  return [propertyValue, setValue, removeValue];
}
const usePrevious = (value2) => {
  const [current3, setCurrent] = reactExports.useState(value2);
  const [previous, setPrevious] = reactExports.useState(void 0);
  if (value2 !== current3) {
    setPrevious(current3);
    setCurrent(value2);
  }
  return previous;
};
const useCollapsibleIds = (key2) => {
  const collapsedIds = useStore((state) => state.collapsedBuckets[key2]);
  const setCollapsed = useStore((state) => state.setCollapsed);
  const collapseId = reactExports.useCallback(
    (id2, value2) => {
      setCollapsed(key2, id2, value2);
    },
    [key2, setCollapsed]
  );
  const clearCollapsedIds = useStore((state) => state.clearCollapsed);
  const clearIds = reactExports.useCallback(() => {
    clearCollapsedIds(key2);
  }, [clearCollapsedIds, key2]);
  return reactExports.useMemo(() => {
    return [collapsedIds || {}, collapseId, clearIds];
  }, [collapsedIds, collapseId, clearIds]);
};
const useCollapsedState = (id2, defaultValue, scope) => {
  const resolvedScope = "collapse-state-scope";
  const collapsed = useStore(
    (state) => state.collapsedBuckets[resolvedScope]?.[id2]
  );
  const setCollapsed = useStore((state) => state.setCollapsed);
  return reactExports.useMemo(() => {
    const set3 = (value2) => {
      setCollapsed(resolvedScope, id2, value2);
    };
    return [collapsed ?? defaultValue ?? false, set3];
  }, [collapsed, resolvedScope, defaultValue, setCollapsed, id2]);
};
const useResizeObserver = (callback) => {
  const elementRef = reactExports.useRef(null);
  const observerRef = reactExports.useRef(null);
  reactExports.useEffect(() => {
    const element = elementRef.current;
    if (!element) return;
    observerRef.current = new ResizeObserver((entries2) => {
      if (entries2[0]) {
        callback(entries2[0]);
      }
    });
    observerRef.current.observe(element);
    return () => {
      if (observerRef.current) {
        observerRef.current.disconnect();
      }
    };
  }, [callback]);
  return elementRef;
};
const expandablePanel = "_expandablePanel_1ka1g_1";
const expandableBordered = "_expandableBordered_1ka1g_5";
const expandableCollapsed = "_expandableCollapsed_1ka1g_18";
const moreToggle = "_moreToggle_1ka1g_22";
const bordered = "_bordered_1ka1g_32";
const moreToggleButton = "_moreToggleButton_1ka1g_36";
const separator$4 = "_separator_1ka1g_44";
const inlineRight = "_inlineRight_1ka1g_50";
const blockLeft = "_blockLeft_1ka1g_56";
const styles$1h = {
  expandablePanel,
  expandableBordered,
  expandableCollapsed,
  moreToggle,
  bordered,
  moreToggleButton,
  separator: separator$4,
  inlineRight,
  blockLeft
};
const ExpandablePanel = reactExports.memo(
  ({
    id: id2,
    collapse,
    border,
    lines = 15,
    children: children2,
    className: className2,
    togglePosition: layout = "inline-right"
  }) => {
    const [collapsed, setCollapsed] = useCollapsedState(id2, collapse);
    const [showToggle, setShowToggle] = reactExports.useState(false);
    const baseFontSizeRef = reactExports.useRef(0);
    const checkOverflow = reactExports.useCallback(
      (entry2) => {
        const element = entry2.target;
        if (baseFontSizeRef.current === 0) {
          const computedStyle = window.getComputedStyle(element);
          const rootFontSize = parseFloat(computedStyle.fontSize);
          baseFontSizeRef.current = rootFontSize;
        }
        const maxCollapsedHeight = baseFontSizeRef.current * lines;
        const contentHeight = element.scrollHeight;
        setShowToggle(contentHeight > maxCollapsedHeight);
      },
      [lines]
    );
    const contentRef = useResizeObserver(checkOverflow);
    const baseStyles = {
      overflow: "hidden",
      ...collapsed && {
        maxHeight: `${lines}rem`
      }
    };
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(className2), children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "div",
        {
          style: baseStyles,
          ref: contentRef,
          className: clsx(
            styles$1h.expandablePanel,
            collapsed ? styles$1h.expandableCollapsed : void 0,
            border ? styles$1h.expandableBordered : void 0,
            showToggle ? styles$1h.padBottom : void 0,
            className2
          ),
          children: [
            children2,
            showToggle && layout === "inline-right" && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(jsxDevRuntimeExports.Fragment, { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
              MoreToggle,
              {
                collapsed,
                setCollapsed,
                border: !border,
                position: "inline-right"
              },
              void 0,
              false,
              {
                fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/ExpandablePanel.tsx",
                lineNumber: 84,
                columnNumber: 15
              },
              void 0
            ) }, void 0, false, {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/ExpandablePanel.tsx",
              lineNumber: 83,
              columnNumber: 13
            }, void 0)
          ]
        },
        void 0,
        true,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/ExpandablePanel.tsx",
          lineNumber: 70,
          columnNumber: 9
        },
        void 0
      ),
      showToggle && layout === "block-left" && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(jsxDevRuntimeExports.Fragment, { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        MoreToggle,
        {
          collapsed,
          setCollapsed,
          border: !border,
          position: "block-left"
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/ExpandablePanel.tsx",
          lineNumber: 95,
          columnNumber: 13
        },
        void 0
      ) }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/ExpandablePanel.tsx",
        lineNumber: 94,
        columnNumber: 11
      }, void 0),
      showToggle && layout === "inline-right" && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$1h.separator) }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/ExpandablePanel.tsx",
        lineNumber: 105,
        columnNumber: 11
      }, void 0)
    ] }, void 0, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/ExpandablePanel.tsx",
      lineNumber: 69,
      columnNumber: 7
    }, void 0);
  }
);
const MoreToggle = ({
  collapsed,
  border,
  setCollapsed,
  style: style2,
  position
}) => {
  const text2 = collapsed ? "more" : "less";
  const handleClick = reactExports.useCallback(() => {
    setCollapsed(!collapsed);
  }, [setCollapsed, collapsed]);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "div",
    {
      className: clsx(
        styles$1h.moreToggle,
        border ? styles$1h.bordered : void 0,
        position === "inline-right" ? styles$1h.inlineRight : styles$1h.blockLeft
      ),
      style: style2,
      children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "button",
        {
          className: clsx(styles$1h.moreToggleButton, "text-size-smallest"),
          onClick: handleClick,
          children: [
            text2,
            "..."
          ]
        },
        void 0,
        true,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/ExpandablePanel.tsx",
          lineNumber: 141,
          columnNumber: 7
        },
        void 0
      )
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/ExpandablePanel.tsx",
      lineNumber: 133,
      columnNumber: 5
    },
    void 0
  );
};
ExpandablePanel.displayName = "ExpandablePanel";
const kStoreInstanceKey = /^(.+)?:([a-zA-Z0-9]{22}):instance$/;
const kStoreKey = /^(.+)?:([a-zA-Z0-9]{22}):(.+)$/;
const resolveStoreKeys = (record) => {
  const result2 = {};
  const storeInstances = {};
  const instanceKeys = /* @__PURE__ */ new Set();
  const entries2 = Object.entries(record);
  for (let i2 = 0; i2 < entries2.length; i2++) {
    const entry2 = entries2[i2];
    if (!entry2) continue;
    const [key2, value2] = entry2;
    const instanceInfo = parseStoreInstanceKey(key2, value2);
    if (instanceInfo) {
      const { storeName, instanceId } = instanceInfo;
      if (!storeName) {
        continue;
      }
      const instanceKey = storeKey(storeName, instanceId);
      if (!storeInstances[instanceKey]) {
        storeInstances[instanceKey] = {};
      }
      instanceKeys.add(key2);
      continue;
    } else {
      const storeKeyInfo = parseStoreKey(key2);
      if (storeKeyInfo) {
        const { storeName, instanceId, keyName } = storeKeyInfo;
        if (!storeName || !instanceId || !keyName) {
          continue;
        }
        const instanceKey = storeKey(storeName, instanceId);
        if (storeInstances[instanceKey]) {
          storeInstances[instanceKey][keyName] = value2;
          continue;
        }
      } else {
        result2[key2] = value2;
      }
    }
  }
  for (const [instanceKey, children2] of Object.entries(storeInstances)) {
    result2[instanceKey] = resolveStoreKeys(children2);
  }
  for (const [key2, value2] of Object.entries(result2)) {
    if (typeof value2 === "object" && value2 !== null && !Array.isArray(value2)) {
      result2[key2] = resolveStoreKeys(value2);
    }
  }
  return result2;
};
const parseStoreInstanceKey = (key2, value2) => {
  const match3 = key2.match(kStoreInstanceKey);
  if (match3) {
    const [, storeName, instanceId] = match3;
    if (typeof value2 === "string" && instanceId === value2) {
      return {
        storeName,
        instanceId
      };
    }
  }
  return null;
};
const parseStoreKey = (key2) => {
  const match3 = key2.match(kStoreKey);
  if (match3) {
    const [, storeName, instanceId, keyName] = match3;
    if (keyName !== "instance") {
      return {
        storeName,
        instanceId,
        keyName
      };
    }
  }
  return null;
};
const storeKey = (storeName, instanceId) => {
  return `${storeName || ""} (${instanceId})`;
};
const keyPairContainer = "_keyPairContainer_qjlxf_1";
const keyPairBordered = "_keyPairBordered_qjlxf_9";
const key = "_key_qjlxf_1";
const pre = "_pre_qjlxf_19";
const treeIcon = "_treeIcon_qjlxf_23";
const styles$1g = {
  keyPairContainer,
  keyPairBordered,
  key,
  pre,
  treeIcon
};
const visible = "_visible_tm52u_1";
const hidden$2 = "_hidden_tm52u_5";
const pills = "_pills_tm52u_9";
const pill = "_pill_tm52u_9";
const styles$1f = {
  visible,
  hidden: hidden$2,
  pills,
  pill
};
const NavPills = ({ id: id2, children: children2 }) => {
  const defaultNav = children2 ? children2?.[0]?.props["title"] : "";
  const [activeItem, setActiveItem] = useProperty(id2, "active", {
    defaultValue: defaultNav
  });
  if (!activeItem || !children2) {
    return void 0;
  }
  const navPills = children2.map((nav2, idx) => {
    const title2 = typeof nav2 === "object" ? nav2["props"]?.title || `Tab ${idx}` : `Tab ${idx}`;
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      NavPill,
      {
        title: title2,
        activeItem,
        setActiveItem
      },
      `nav-pill-contents-${idx}`,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/NavPills.tsx",
        lineNumber: 35,
        columnNumber: 7
      },
      void 0
    );
  });
  const navBodies = children2.map((child, idx) => {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "div",
      {
        className: child["props"]?.title === activeItem ? styles$1f.visible : styles$1f.hidden,
        children: child
      },
      `nav-pill-container-${idx}`,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/NavPills.tsx",
        lineNumber: 47,
        columnNumber: 7
      },
      void 0
    );
  });
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "ul",
      {
        className: clsx("nav", "nav-pills", styles$1f.pills),
        role: "tablist",
        "aria-orientation": "horizontal",
        children: navPills
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/NavPills.tsx",
        lineNumber: 60,
        columnNumber: 7
      },
      void 0
    ),
    navBodies
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/NavPills.tsx",
    lineNumber: 59,
    columnNumber: 5
  }, void 0);
};
const NavPill = ({
  title: title2,
  activeItem,
  setActiveItem,
  children: children2
}) => {
  const active = activeItem === title2;
  const handleClick = reactExports.useCallback(
    (e) => {
      const target = e.currentTarget.dataset.target;
      if (target) {
        setActiveItem(target);
      }
    },
    [setActiveItem]
  );
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("li", { className: "nav-item", children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "button",
      {
        type: "button",
        role: "tab",
        "aria-selected": active,
        className: clsx(
          "nav-link",
          "text-style-label",
          active ? "active " : "",
          styles$1f.pill
        ),
        "data-target": title2,
        onClick: handleClick,
        children: title2
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/NavPills.tsx",
        lineNumber: 98,
        columnNumber: 7
      },
      void 0
    ),
    children2
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/NavPills.tsx",
    lineNumber: 97,
    columnNumber: 5
  }, void 0);
};
const Buckets = {
  first: 0,
  intermediate: 10,
  final: 1e3
};
const copyButton = "_copyButton_1goi8_1";
const styles$1e = {
  copyButton
};
const CopyButton = ({
  icon: icon2 = ApplicationIcons.copy,
  value: value2,
  onCopySuccess,
  onCopyError,
  className: className2 = "",
  ariaLabel = "Copy to clipboard"
}) => {
  const [isCopied, setIsCopied] = reactExports.useState(false);
  const handleClick = async () => {
    try {
      await navigator.clipboard.writeText(value2);
      setIsCopied(true);
      onCopySuccess?.();
      setTimeout(() => {
        setIsCopied(false);
      }, 1250);
    } catch (error2) {
      onCopyError?.(
        error2 instanceof Error ? error2 : new Error("Failed to copy")
      );
    }
  };
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "button",
    {
      type: "button",
      className: clsx("copy-button", styles$1e.copyButton, className2),
      onClick: () => {
        void handleClick();
      },
      "aria-label": ariaLabel,
      disabled: isCopied,
      children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "i",
        {
          className: isCopied ? `${ApplicationIcons.confirm} primary` : icon2,
          "aria-hidden": "true"
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/CopyButton.tsx",
          lineNumber: 54,
          columnNumber: 7
        },
        void 0
      )
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/CopyButton.tsx",
      lineNumber: 45,
      columnNumber: 5
    },
    void 0
  );
};
const message = "_message_b8oe1_1";
const systemRole = "_systemRole_b8oe1_8";
const messageGrid = "_messageGrid_b8oe1_12";
const toolMessageGrid = "_toolMessageGrid_b8oe1_20";
const messageContents = "_messageContents_b8oe1_24";
const indented = "_indented_b8oe1_29";
const copyLink = "_copyLink_b8oe1_33";
const metadataLabel = "_metadataLabel_b8oe1_43";
const hover$1 = "_hover_b8oe1_47";
const styles$1d = {
  message,
  systemRole,
  messageGrid,
  toolMessageGrid,
  messageContents,
  indented,
  copyLink,
  metadataLabel,
  hover: hover$1
};
const decodeCache = {};
function getDecodeCache(exclude) {
  let cache = decodeCache[exclude];
  if (cache) {
    return cache;
  }
  cache = decodeCache[exclude] = [];
  for (let i2 = 0; i2 < 128; i2++) {
    const ch = String.fromCharCode(i2);
    cache.push(ch);
  }
  for (let i2 = 0; i2 < exclude.length; i2++) {
    const ch = exclude.charCodeAt(i2);
    cache[ch] = "%" + ("0" + ch.toString(16).toUpperCase()).slice(-2);
  }
  return cache;
}
function decode$1(string2, exclude) {
  if (typeof exclude !== "string") {
    exclude = decode$1.defaultChars;
  }
  const cache = getDecodeCache(exclude);
  return string2.replace(/(%[a-f0-9]{2})+/gi, function(seq) {
    let result2 = "";
    for (let i2 = 0, l2 = seq.length; i2 < l2; i2 += 3) {
      const b1 = parseInt(seq.slice(i2 + 1, i2 + 3), 16);
      if (b1 < 128) {
        result2 += cache[b1];
        continue;
      }
      if ((b1 & 224) === 192 && i2 + 3 < l2) {
        const b2 = parseInt(seq.slice(i2 + 4, i2 + 6), 16);
        if ((b2 & 192) === 128) {
          const chr = b1 << 6 & 1984 | b2 & 63;
          if (chr < 128) {
            result2 += "��";
          } else {
            result2 += String.fromCharCode(chr);
          }
          i2 += 3;
          continue;
        }
      }
      if ((b1 & 240) === 224 && i2 + 6 < l2) {
        const b2 = parseInt(seq.slice(i2 + 4, i2 + 6), 16);
        const b3 = parseInt(seq.slice(i2 + 7, i2 + 9), 16);
        if ((b2 & 192) === 128 && (b3 & 192) === 128) {
          const chr = b1 << 12 & 61440 | b2 << 6 & 4032 | b3 & 63;
          if (chr < 2048 || chr >= 55296 && chr <= 57343) {
            result2 += "���";
          } else {
            result2 += String.fromCharCode(chr);
          }
          i2 += 6;
          continue;
        }
      }
      if ((b1 & 248) === 240 && i2 + 9 < l2) {
        const b2 = parseInt(seq.slice(i2 + 4, i2 + 6), 16);
        const b3 = parseInt(seq.slice(i2 + 7, i2 + 9), 16);
        const b4 = parseInt(seq.slice(i2 + 10, i2 + 12), 16);
        if ((b2 & 192) === 128 && (b3 & 192) === 128 && (b4 & 192) === 128) {
          let chr = b1 << 18 & 1835008 | b2 << 12 & 258048 | b3 << 6 & 4032 | b4 & 63;
          if (chr < 65536 || chr > 1114111) {
            result2 += "����";
          } else {
            chr -= 65536;
            result2 += String.fromCharCode(55296 + (chr >> 10), 56320 + (chr & 1023));
          }
          i2 += 9;
          continue;
        }
      }
      result2 += "�";
    }
    return result2;
  });
}
decode$1.defaultChars = ";/?:@&=+$,#";
decode$1.componentChars = "";
const encodeCache = {};
function getEncodeCache(exclude) {
  let cache = encodeCache[exclude];
  if (cache) {
    return cache;
  }
  cache = encodeCache[exclude] = [];
  for (let i2 = 0; i2 < 128; i2++) {
    const ch = String.fromCharCode(i2);
    if (/^[0-9a-z]$/i.test(ch)) {
      cache.push(ch);
    } else {
      cache.push("%" + ("0" + i2.toString(16).toUpperCase()).slice(-2));
    }
  }
  for (let i2 = 0; i2 < exclude.length; i2++) {
    cache[exclude.charCodeAt(i2)] = exclude[i2];
  }
  return cache;
}
function encode$1(string2, exclude, keepEscaped) {
  if (typeof exclude !== "string") {
    keepEscaped = exclude;
    exclude = encode$1.defaultChars;
  }
  if (typeof keepEscaped === "undefined") {
    keepEscaped = true;
  }
  const cache = getEncodeCache(exclude);
  let result2 = "";
  for (let i2 = 0, l2 = string2.length; i2 < l2; i2++) {
    const code2 = string2.charCodeAt(i2);
    if (keepEscaped && code2 === 37 && i2 + 2 < l2) {
      if (/^[0-9a-f]{2}$/i.test(string2.slice(i2 + 1, i2 + 3))) {
        result2 += string2.slice(i2, i2 + 3);
        i2 += 2;
        continue;
      }
    }
    if (code2 < 128) {
      result2 += cache[code2];
      continue;
    }
    if (code2 >= 55296 && code2 <= 57343) {
      if (code2 >= 55296 && code2 <= 56319 && i2 + 1 < l2) {
        const nextCode = string2.charCodeAt(i2 + 1);
        if (nextCode >= 56320 && nextCode <= 57343) {
          result2 += encodeURIComponent(string2[i2] + string2[i2 + 1]);
          i2++;
          continue;
        }
      }
      result2 += "%EF%BF%BD";
      continue;
    }
    result2 += encodeURIComponent(string2[i2]);
  }
  return result2;
}
encode$1.defaultChars = ";/?:@&=+$,-_.!~*'()#";
encode$1.componentChars = "-_.!~*'()";
function format$1(url) {
  let result2 = "";
  result2 += url.protocol || "";
  result2 += url.slashes ? "//" : "";
  result2 += url.auth ? url.auth + "@" : "";
  if (url.hostname && url.hostname.indexOf(":") !== -1) {
    result2 += "[" + url.hostname + "]";
  } else {
    result2 += url.hostname || "";
  }
  result2 += url.port ? ":" + url.port : "";
  result2 += url.pathname || "";
  result2 += url.search || "";
  result2 += url.hash || "";
  return result2;
}
function Url() {
  this.protocol = null;
  this.slashes = null;
  this.auth = null;
  this.port = null;
  this.hostname = null;
  this.hash = null;
  this.search = null;
  this.pathname = null;
}
const protocolPattern = /^([a-z0-9.+-]+:)/i;
const portPattern = /:[0-9]*$/;
const simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/;
const delims = ["<", ">", '"', "`", " ", "\r", "\n", "	"];
const unwise = ["{", "}", "|", "\\", "^", "`"].concat(delims);
const autoEscape = ["'"].concat(unwise);
const nonHostChars = ["%", "/", "?", ";", "#"].concat(autoEscape);
const hostEndingChars = ["/", "?", "#"];
const hostnameMaxLen = 255;
const hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/;
const hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/;
const hostlessProtocol = {
  javascript: true,
  "javascript:": true
};
const slashedProtocol = {
  http: true,
  https: true,
  ftp: true,
  gopher: true,
  file: true,
  "http:": true,
  "https:": true,
  "ftp:": true,
  "gopher:": true,
  "file:": true
};
function urlParse(url, slashesDenoteHost) {
  if (url && url instanceof Url) return url;
  const u = new Url();
  u.parse(url, slashesDenoteHost);
  return u;
}
Url.prototype.parse = function(url, slashesDenoteHost) {
  let lowerProto, hec, slashes;
  let rest = url;
  rest = rest.trim();
  if (!slashesDenoteHost && url.split("#").length === 1) {
    const simplePath = simplePathPattern.exec(rest);
    if (simplePath) {
      this.pathname = simplePath[1];
      if (simplePath[2]) {
        this.search = simplePath[2];
      }
      return this;
    }
  }
  let proto = protocolPattern.exec(rest);
  if (proto) {
    proto = proto[0];
    lowerProto = proto.toLowerCase();
    this.protocol = proto;
    rest = rest.substr(proto.length);
  }
  if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
    slashes = rest.substr(0, 2) === "//";
    if (slashes && !(proto && hostlessProtocol[proto])) {
      rest = rest.substr(2);
      this.slashes = true;
    }
  }
  if (!hostlessProtocol[proto] && (slashes || proto && !slashedProtocol[proto])) {
    let hostEnd = -1;
    for (let i2 = 0; i2 < hostEndingChars.length; i2++) {
      hec = rest.indexOf(hostEndingChars[i2]);
      if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) {
        hostEnd = hec;
      }
    }
    let auth, atSign;
    if (hostEnd === -1) {
      atSign = rest.lastIndexOf("@");
    } else {
      atSign = rest.lastIndexOf("@", hostEnd);
    }
    if (atSign !== -1) {
      auth = rest.slice(0, atSign);
      rest = rest.slice(atSign + 1);
      this.auth = auth;
    }
    hostEnd = -1;
    for (let i2 = 0; i2 < nonHostChars.length; i2++) {
      hec = rest.indexOf(nonHostChars[i2]);
      if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) {
        hostEnd = hec;
      }
    }
    if (hostEnd === -1) {
      hostEnd = rest.length;
    }
    if (rest[hostEnd - 1] === ":") {
      hostEnd--;
    }
    const host = rest.slice(0, hostEnd);
    rest = rest.slice(hostEnd);
    this.parseHost(host);
    this.hostname = this.hostname || "";
    const ipv6Hostname = this.hostname[0] === "[" && this.hostname[this.hostname.length - 1] === "]";
    if (!ipv6Hostname) {
      const hostparts = this.hostname.split(/\./);
      for (let i2 = 0, l2 = hostparts.length; i2 < l2; i2++) {
        const part = hostparts[i2];
        if (!part) {
          continue;
        }
        if (!part.match(hostnamePartPattern)) {
          let newpart = "";
          for (let j2 = 0, k = part.length; j2 < k; j2++) {
            if (part.charCodeAt(j2) > 127) {
              newpart += "x";
            } else {
              newpart += part[j2];
            }
          }
          if (!newpart.match(hostnamePartPattern)) {
            const validParts = hostparts.slice(0, i2);
            const notHost = hostparts.slice(i2 + 1);
            const bit = part.match(hostnamePartStart);
            if (bit) {
              validParts.push(bit[1]);
              notHost.unshift(bit[2]);
            }
            if (notHost.length) {
              rest = notHost.join(".") + rest;
            }
            this.hostname = validParts.join(".");
            break;
          }
        }
      }
    }
    if (this.hostname.length > hostnameMaxLen) {
      this.hostname = "";
    }
    if (ipv6Hostname) {
      this.hostname = this.hostname.substr(1, this.hostname.length - 2);
    }
  }
  const hash2 = rest.indexOf("#");
  if (hash2 !== -1) {
    this.hash = rest.substr(hash2);
    rest = rest.slice(0, hash2);
  }
  const qm = rest.indexOf("?");
  if (qm !== -1) {
    this.search = rest.substr(qm);
    rest = rest.slice(0, qm);
  }
  if (rest) {
    this.pathname = rest;
  }
  if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) {
    this.pathname = "";
  }
  return this;
};
Url.prototype.parseHost = function(host) {
  let port = portPattern.exec(host);
  if (port) {
    port = port[0];
    if (port !== ":") {
      this.port = port.substr(1);
    }
    host = host.substr(0, host.length - port.length);
  }
  if (host) {
    this.hostname = host;
  }
};
const mdurl = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  decode: decode$1,
  encode: encode$1,
  format: format$1,
  parse: urlParse
}, Symbol.toStringTag, { value: "Module" }));
const Any = /[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
const Cc = /[\0-\x1F\x7F-\x9F]/;
const regex$1 = /[\xAD\u0600-\u0605\u061C\u06DD\u070F\u0890\u0891\u08E2\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF\uFFF9-\uFFFB]|\uD804[\uDCBD\uDCCD]|\uD80D[\uDC30-\uDC3F]|\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|\uDB40[\uDC01\uDC20-\uDC7F]/;
const P = /[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061D-\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1B7D\u1B7E\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u2E52-\u2E5D\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDEAD\uDF55-\uDF59\uDF86-\uDF89]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5A\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDEB9\uDF3C-\uDF3E]|\uD806[\uDC3B\uDD44-\uDD46\uDDE2\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2\uDF00-\uDF09]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8\uDF43-\uDF4F\uDFFF]|\uD809[\uDC70-\uDC74]|\uD80B[\uDFF1\uDFF2]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDE97-\uDE9A\uDFE2]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/;
const regex = /[\$\+<->\^`\|~\xA2-\xA6\xA8\xA9\xAC\xAE-\xB1\xB4\xB8\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0384\u0385\u03F6\u0482\u058D-\u058F\u0606-\u0608\u060B\u060E\u060F\u06DE\u06E9\u06FD\u06FE\u07F6\u07FE\u07FF\u0888\u09F2\u09F3\u09FA\u09FB\u0AF1\u0B70\u0BF3-\u0BFA\u0C7F\u0D4F\u0D79\u0E3F\u0F01-\u0F03\u0F13\u0F15-\u0F17\u0F1A-\u0F1F\u0F34\u0F36\u0F38\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE\u0FCF\u0FD5-\u0FD8\u109E\u109F\u1390-\u1399\u166D\u17DB\u1940\u19DE-\u19FF\u1B61-\u1B6A\u1B74-\u1B7C\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u2044\u2052\u207A-\u207C\u208A-\u208C\u20A0-\u20C0\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A\u218B\u2190-\u2307\u230C-\u2328\u232B-\u2426\u2440-\u244A\u249C-\u24E9\u2500-\u2767\u2794-\u27C4\u27C7-\u27E5\u27F0-\u2982\u2999-\u29D7\u29DC-\u29FB\u29FE-\u2B73\u2B76-\u2B95\u2B97-\u2BFF\u2CE5-\u2CEA\u2E50\u2E51\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFF\u3004\u3012\u3013\u3020\u3036\u3037\u303E\u303F\u309B\u309C\u3190\u3191\u3196-\u319F\u31C0-\u31E3\u31EF\u3200-\u321E\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA700-\uA716\uA720\uA721\uA789\uA78A\uA828-\uA82B\uA836-\uA839\uAA77-\uAA79\uAB5B\uAB6A\uAB6B\uFB29\uFBB2-\uFBC2\uFD40-\uFD4F\uFDCF\uFDFC-\uFDFF\uFE62\uFE64-\uFE66\uFE69\uFF04\uFF0B\uFF1C-\uFF1E\uFF3E\uFF40\uFF5C\uFF5E\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFFC\uFFFD]|\uD800[\uDD37-\uDD3F\uDD79-\uDD89\uDD8C-\uDD8E\uDD90-\uDD9C\uDDA0\uDDD0-\uDDFC]|\uD802[\uDC77\uDC78\uDEC8]|\uD805\uDF3F|\uD807[\uDFD5-\uDFF1]|\uD81A[\uDF3C-\uDF3F\uDF45]|\uD82F\uDC9C|\uD833[\uDF50-\uDFC3]|\uD834[\uDC00-\uDCF5\uDD00-\uDD26\uDD29-\uDD64\uDD6A-\uDD6C\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDDEA\uDE00-\uDE41\uDE45\uDF00-\uDF56]|\uD835[\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85\uDE86]|\uD838[\uDD4F\uDEFF]|\uD83B[\uDCAC\uDCB0\uDD2E\uDEF0\uDEF1]|\uD83C[\uDC00-\uDC2B\uDC30-\uDC93\uDCA0-\uDCAE\uDCB1-\uDCBF\uDCC1-\uDCCF\uDCD1-\uDCF5\uDD0D-\uDDAD\uDDE6-\uDE02\uDE10-\uDE3B\uDE40-\uDE48\uDE50\uDE51\uDE60-\uDE65\uDF00-\uDFFF]|\uD83D[\uDC00-\uDED7\uDEDC-\uDEEC\uDEF0-\uDEFC\uDF00-\uDF76\uDF7B-\uDFD9\uDFE0-\uDFEB\uDFF0]|\uD83E[\uDC00-\uDC0B\uDC10-\uDC47\uDC50-\uDC59\uDC60-\uDC87\uDC90-\uDCAD\uDCB0\uDCB1\uDD00-\uDE53\uDE60-\uDE6D\uDE70-\uDE7C\uDE80-\uDE88\uDE90-\uDEBD\uDEBF-\uDEC5\uDECE-\uDEDB\uDEE0-\uDEE8\uDEF0-\uDEF8\uDF00-\uDF92\uDF94-\uDFCA]/;
const Z = /[ \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/;
const ucmicro = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  Any,
  Cc,
  Cf: regex$1,
  P,
  S: regex,
  Z
}, Symbol.toStringTag, { value: "Module" }));
const htmlDecodeTree = new Uint16Array(
  // prettier-ignore
  'ᵁ<Õıʊҝջאٵ۞ޢߖࠏ੊ઑඡ๭༉༦჊ረዡᐕᒝᓃᓟᔥ\0\0\0\0\0\0ᕫᛍᦍᰒᷝ὾⁠↰⊍⏀⏻⑂⠤⤒ⴈ⹈⿎〖㊺㘹㞬㣾㨨㩱㫠㬮ࠀEMabcfglmnoprstu\\bfms¦³¹ÈÏlig耻Æ䃆P耻&䀦cute耻Á䃁reve;䄂Āiyx}rc耻Â䃂;䐐r;쀀𝔄rave耻À䃀pha;䎑acr;䄀d;橓Āgp¡on;䄄f;쀀𝔸plyFunction;恡ing耻Å䃅Ācs¾Ãr;쀀𝒜ign;扔ilde耻Ã䃃ml耻Ä䃄ЀaceforsuåûþėĜĢħĪĀcrêòkslash;或Ŷöø;櫧ed;挆y;䐑ƀcrtąċĔause;戵noullis;愬a;䎒r;쀀𝔅pf;쀀𝔹eve;䋘còēmpeq;扎܀HOacdefhilorsuōőŖƀƞƢƵƷƺǜȕɳɸɾcy;䐧PY耻©䂩ƀcpyŝŢźute;䄆Ā;iŧŨ拒talDifferentialD;慅leys;愭ȀaeioƉƎƔƘron;䄌dil耻Ç䃇rc;䄈nint;戰ot;䄊ĀdnƧƭilla;䂸terDot;䂷òſi;䎧rcleȀDMPTǇǋǑǖot;抙inus;抖lus;投imes;抗oĀcsǢǸkwiseContourIntegral;戲eCurlyĀDQȃȏoubleQuote;思uote;怙ȀlnpuȞȨɇɕonĀ;eȥȦ户;橴ƀgitȯȶȺruent;扡nt;戯ourIntegral;戮ĀfrɌɎ;愂oduct;成nterClockwiseContourIntegral;戳oss;樯cr;쀀𝒞pĀ;Cʄʅ拓ap;才րDJSZacefiosʠʬʰʴʸˋ˗ˡ˦̳ҍĀ;oŹʥtrahd;椑cy;䐂cy;䐅cy;䐏ƀgrsʿ˄ˇger;怡r;憡hv;櫤Āayː˕ron;䄎;䐔lĀ;t˝˞戇a;䎔r;쀀𝔇Āaf˫̧Ācm˰̢riticalȀADGT̖̜̀̆cute;䂴oŴ̋̍;䋙bleAcute;䋝rave;䁠ilde;䋜ond;拄ferentialD;慆Ѱ̽\0\0\0͔͂\0Ѕf;쀀𝔻ƀ;DE͈͉͍䂨ot;惜qual;扐blèCDLRUVͣͲ΂ϏϢϸontourIntegraìȹoɴ͹\0\0ͻ»͉nArrow;懓Āeo·ΤftƀARTΐΖΡrrow;懐ightArrow;懔eåˊngĀLRΫτeftĀARγιrrow;柸ightArrow;柺ightArrow;柹ightĀATϘϞrrow;懒ee;抨pɁϩ\0\0ϯrrow;懑ownArrow;懕erticalBar;戥ǹABLRTaВЪаўѿͼrrowƀ;BUНОТ憓ar;椓pArrow;懵reve;䌑eft˒к\0ц\0ѐightVector;楐eeVector;楞ectorĀ;Bљњ憽ar;楖ightǔѧ\0ѱeeVector;楟ectorĀ;BѺѻ懁ar;楗eeĀ;A҆҇护rrow;憧ĀctҒҗr;쀀𝒟rok;䄐ࠀNTacdfglmopqstuxҽӀӄӋӞӢӧӮӵԡԯԶՒ՝ՠեG;䅊H耻Ð䃐cute耻É䃉ƀaiyӒӗӜron;䄚rc耻Ê䃊;䐭ot;䄖r;쀀𝔈rave耻È䃈ement;戈ĀapӺӾcr;䄒tyɓԆ\0\0ԒmallSquare;旻erySmallSquare;斫ĀgpԦԪon;䄘f;쀀𝔼silon;䎕uĀaiԼՉlĀ;TՂՃ橵ilde;扂librium;懌Āci՗՚r;愰m;橳a;䎗ml耻Ë䃋Āipժկsts;戃onentialE;慇ʀcfiosօֈ֍ֲ׌y;䐤r;쀀𝔉lledɓ֗\0\0֣mallSquare;旼erySmallSquare;斪Ͱֺ\0ֿ\0\0ׄf;쀀𝔽All;戀riertrf;愱cò׋؀JTabcdfgorstר׬ׯ׺؀ؒؖ؛؝أ٬ٲcy;䐃耻>䀾mmaĀ;d׷׸䎓;䏜reve;䄞ƀeiy؇،ؐdil;䄢rc;䄜;䐓ot;䄠r;쀀𝔊;拙pf;쀀𝔾eater̀EFGLSTصلَٖٛ٦qualĀ;Lؾؿ扥ess;招ullEqual;执reater;檢ess;扷lantEqual;橾ilde;扳cr;쀀𝒢;扫ЀAacfiosuڅڋږڛڞڪھۊRDcy;䐪Āctڐڔek;䋇;䁞irc;䄤r;愌lbertSpace;愋ǰگ\0ڲf;愍izontalLine;攀Āctۃۅòکrok;䄦mpńېۘownHumðįqual;扏܀EJOacdfgmnostuۺ۾܃܇܎ܚܞܡܨ݄ݸދޏޕcy;䐕lig;䄲cy;䐁cute耻Í䃍Āiyܓܘrc耻Î䃎;䐘ot;䄰r;愑rave耻Ì䃌ƀ;apܠܯܿĀcgܴܷr;䄪inaryI;慈lieóϝǴ݉\0ݢĀ;eݍݎ戬Āgrݓݘral;戫section;拂isibleĀCTݬݲomma;恣imes;恢ƀgptݿރވon;䄮f;쀀𝕀a;䎙cr;愐ilde;䄨ǫޚ\0ޞcy;䐆l耻Ï䃏ʀcfosuެ޷޼߂ߐĀiyޱ޵rc;䄴;䐙r;쀀𝔍pf;쀀𝕁ǣ߇\0ߌr;쀀𝒥rcy;䐈kcy;䐄΀HJacfosߤߨ߽߬߱ࠂࠈcy;䐥cy;䐌ppa;䎚Āey߶߻dil;䄶;䐚r;쀀𝔎pf;쀀𝕂cr;쀀𝒦րJTaceflmostࠥࠩࠬࡐࡣ঳সে্਷ੇcy;䐉耻<䀼ʀcmnpr࠷࠼ࡁࡄࡍute;䄹bda;䎛g;柪lacetrf;愒r;憞ƀaeyࡗ࡜ࡡron;䄽dil;䄻;䐛Āfsࡨ॰tԀACDFRTUVarࡾࢩࢱࣦ࣠ࣼयज़ΐ४Ānrࢃ࢏gleBracket;柨rowƀ;BR࢙࢚࢞憐ar;懤ightArrow;懆eiling;挈oǵࢷ\0ࣃbleBracket;柦nǔࣈ\0࣒eeVector;楡ectorĀ;Bࣛࣜ懃ar;楙loor;挊ightĀAV࣯ࣵrrow;憔ector;楎Āerँगeƀ;AVउऊऐ抣rrow;憤ector;楚iangleƀ;BEतथऩ抲ar;槏qual;抴pƀDTVषूौownVector;楑eeVector;楠ectorĀ;Bॖॗ憿ar;楘ectorĀ;B॥०憼ar;楒ightáΜs̀EFGLSTॾঋকঝঢভqualGreater;拚ullEqual;扦reater;扶ess;檡lantEqual;橽ilde;扲r;쀀𝔏Ā;eঽা拘ftarrow;懚idot;䄿ƀnpw৔ਖਛgȀLRlr৞৷ਂਐeftĀAR০৬rrow;柵ightArrow;柷ightArrow;柶eftĀarγਊightáοightáϊf;쀀𝕃erĀLRਢਬeftArrow;憙ightArrow;憘ƀchtਾੀੂòࡌ;憰rok;䅁;扪Ѐacefiosuਗ਼੝੠੷੼અઋ઎p;椅y;䐜Ādl੥੯iumSpace;恟lintrf;愳r;쀀𝔐nusPlus;戓pf;쀀𝕄cò੶;䎜ҀJacefostuણધભીଔଙඑ඗ඞcy;䐊cute;䅃ƀaey઴હાron;䅇dil;䅅;䐝ƀgswે૰଎ativeƀMTV૓૟૨ediumSpace;怋hiĀcn૦૘ë૙eryThiî૙tedĀGL૸ଆreaterGreateòٳessLesóੈLine;䀊r;쀀𝔑ȀBnptଢନଷ଺reak;恠BreakingSpace;䂠f;愕ڀ;CDEGHLNPRSTV୕ୖ୪୼஡௫ఄ౞಄ದ೘ൡඅ櫬Āou୛୤ngruent;扢pCap;扭oubleVerticalBar;戦ƀlqxஃஊ஛ement;戉ualĀ;Tஒஓ扠ilde;쀀≂̸ists;戄reater΀;EFGLSTஶஷ஽௉௓௘௥扯qual;扱ullEqual;쀀≧̸reater;쀀≫̸ess;批lantEqual;쀀⩾̸ilde;扵umpń௲௽ownHump;쀀≎̸qual;쀀≏̸eĀfsఊధtTriangleƀ;BEచఛడ拪ar;쀀⧏̸qual;括s̀;EGLSTవశ఼ౄోౘ扮qual;扰reater;扸ess;쀀≪̸lantEqual;쀀⩽̸ilde;扴estedĀGL౨౹reaterGreater;쀀⪢̸essLess;쀀⪡̸recedesƀ;ESಒಓಛ技qual;쀀⪯̸lantEqual;拠ĀeiಫಹverseElement;戌ghtTriangleƀ;BEೋೌ೒拫ar;쀀⧐̸qual;拭ĀquೝഌuareSuĀbp೨೹setĀ;E೰ೳ쀀⊏̸qual;拢ersetĀ;Eഃആ쀀⊐̸qual;拣ƀbcpഓതൎsetĀ;Eഛഞ쀀⊂⃒qual;抈ceedsȀ;ESTലള഻െ抁qual;쀀⪰̸lantEqual;拡ilde;쀀≿̸ersetĀ;E൘൛쀀⊃⃒qual;抉ildeȀ;EFT൮൯൵ൿ扁qual;扄ullEqual;扇ilde;扉erticalBar;戤cr;쀀𝒩ilde耻Ñ䃑;䎝܀Eacdfgmoprstuvලෂ෉෕ෛ෠෧෼ขภยา฿ไlig;䅒cute耻Ó䃓Āiy෎ීrc耻Ô䃔;䐞blac;䅐r;쀀𝔒rave耻Ò䃒ƀaei෮ෲ෶cr;䅌ga;䎩cron;䎟pf;쀀𝕆enCurlyĀDQฎบoubleQuote;怜uote;怘;橔Āclวฬr;쀀𝒪ash耻Ø䃘iŬื฼de耻Õ䃕es;樷ml耻Ö䃖erĀBP๋๠Āar๐๓r;怾acĀek๚๜;揞et;掴arenthesis;揜Ҁacfhilors๿ງຊຏຒດຝະ໼rtialD;戂y;䐟r;쀀𝔓i;䎦;䎠usMinus;䂱Āipຢອncareplanåڝf;愙Ȁ;eio຺ູ໠໤檻cedesȀ;EST່້໏໚扺qual;檯lantEqual;扼ilde;找me;怳Ādp໩໮uct;戏ortionĀ;aȥ໹l;戝Āci༁༆r;쀀𝒫;䎨ȀUfos༑༖༛༟OT耻"䀢r;쀀𝔔pf;愚cr;쀀𝒬؀BEacefhiorsu༾གྷཇའཱིྦྷྪྭ႖ႩႴႾarr;椐G耻®䂮ƀcnrཎནབute;䅔g;柫rĀ;tཛྷཝ憠l;椖ƀaeyཧཬཱron;䅘dil;䅖;䐠Ā;vླྀཹ愜erseĀEUྂྙĀlq྇ྎement;戋uilibrium;懋pEquilibrium;楯r»ཹo;䎡ghtЀACDFTUVa࿁࿫࿳ဢဨၛႇϘĀnr࿆࿒gleBracket;柩rowƀ;BL࿜࿝࿡憒ar;懥eftArrow;懄eiling;按oǵ࿹\0စbleBracket;柧nǔည\0နeeVector;楝ectorĀ;Bဝသ懂ar;楕loor;挋Āerိ၃eƀ;AVဵံြ抢rrow;憦ector;楛iangleƀ;BEၐၑၕ抳ar;槐qual;抵pƀDTVၣၮၸownVector;楏eeVector;楜ectorĀ;Bႂႃ憾ar;楔ectorĀ;B႑႒懀ar;楓Āpuႛ႞f;愝ndImplies;楰ightarrow;懛ĀchႹႼr;愛;憱leDelayed;槴ڀHOacfhimoqstuფჱჷჽᄙᄞᅑᅖᅡᅧᆵᆻᆿĀCcჩხHcy;䐩y;䐨FTcy;䐬cute;䅚ʀ;aeiyᄈᄉᄎᄓᄗ檼ron;䅠dil;䅞rc;䅜;䐡r;쀀𝔖ortȀDLRUᄪᄴᄾᅉownArrow»ОeftArrow»࢚ightArrow»࿝pArrow;憑gma;䎣allCircle;战pf;쀀𝕊ɲᅭ\0\0ᅰt;戚areȀ;ISUᅻᅼᆉᆯ斡ntersection;抓uĀbpᆏᆞsetĀ;Eᆗᆘ抏qual;抑ersetĀ;Eᆨᆩ抐qual;抒nion;抔cr;쀀𝒮ar;拆ȀbcmpᇈᇛሉላĀ;sᇍᇎ拐etĀ;Eᇍᇕqual;抆ĀchᇠህeedsȀ;ESTᇭᇮᇴᇿ扻qual;檰lantEqual;扽ilde;承Tháྌ;我ƀ;esሒሓሣ拑rsetĀ;Eሜም抃qual;抇et»ሓրHRSacfhiorsሾቄ቉ቕ቞ቱቶኟዂወዑORN耻Þ䃞ADE;愢ĀHc቎ቒcy;䐋y;䐦Ābuቚቜ;䀉;䎤ƀaeyብቪቯron;䅤dil;䅢;䐢r;쀀𝔗Āeiቻ኉ǲኀ\0ኇefore;戴a;䎘Ācn኎ኘkSpace;쀀  Space;怉ldeȀ;EFTካኬኲኼ戼qual;扃ullEqual;扅ilde;扈pf;쀀𝕋ipleDot;惛Āctዖዛr;쀀𝒯rok;䅦ૡዷጎጚጦ\0ጬጱ\0\0\0\0\0ጸጽ፷ᎅ\0᏿ᐄᐊᐐĀcrዻጁute耻Ú䃚rĀ;oጇገ憟cir;楉rǣጓ\0጖y;䐎ve;䅬Āiyጞጣrc耻Û䃛;䐣blac;䅰r;쀀𝔘rave耻Ù䃙acr;䅪Ādiፁ፩erĀBPፈ፝Āarፍፐr;䁟acĀekፗፙ;揟et;掵arenthesis;揝onĀ;P፰፱拃lus;抎Āgp፻፿on;䅲f;쀀𝕌ЀADETadps᎕ᎮᎸᏄϨᏒᏗᏳrrowƀ;BDᅐᎠᎤar;椒ownArrow;懅ownArrow;憕quilibrium;楮eeĀ;AᏋᏌ报rrow;憥ownáϳerĀLRᏞᏨeftArrow;憖ightArrow;憗iĀ;lᏹᏺ䏒on;䎥ing;䅮cr;쀀𝒰ilde;䅨ml耻Ü䃜ҀDbcdefosvᐧᐬᐰᐳᐾᒅᒊᒐᒖash;披ar;櫫y;䐒ashĀ;lᐻᐼ抩;櫦Āerᑃᑅ;拁ƀbtyᑌᑐᑺar;怖Ā;iᑏᑕcalȀBLSTᑡᑥᑪᑴar;戣ine;䁼eparator;杘ilde;所ThinSpace;怊r;쀀𝔙pf;쀀𝕍cr;쀀𝒱dash;抪ʀcefosᒧᒬᒱᒶᒼirc;䅴dge;拀r;쀀𝔚pf;쀀𝕎cr;쀀𝒲Ȁfiosᓋᓐᓒᓘr;쀀𝔛;䎞pf;쀀𝕏cr;쀀𝒳ҀAIUacfosuᓱᓵᓹᓽᔄᔏᔔᔚᔠcy;䐯cy;䐇cy;䐮cute耻Ý䃝Āiyᔉᔍrc;䅶;䐫r;쀀𝔜pf;쀀𝕐cr;쀀𝒴ml;䅸ЀHacdefosᔵᔹᔿᕋᕏᕝᕠᕤcy;䐖cute;䅹Āayᕄᕉron;䅽;䐗ot;䅻ǲᕔ\0ᕛoWidtè૙a;䎖r;愨pf;愤cr;쀀𝒵௡ᖃᖊᖐ\0ᖰᖶᖿ\0\0\0\0ᗆᗛᗫᙟ᙭\0ᚕ᚛ᚲᚹ\0ᚾcute耻á䃡reve;䄃̀;Ediuyᖜᖝᖡᖣᖨᖭ戾;쀀∾̳;房rc耻â䃢te肻´̆;䐰lig耻æ䃦Ā;r²ᖺ;쀀𝔞rave耻à䃠ĀepᗊᗖĀfpᗏᗔsym;愵èᗓha;䎱ĀapᗟcĀclᗤᗧr;䄁g;樿ɤᗰ\0\0ᘊʀ;adsvᗺᗻᗿᘁᘇ戧nd;橕;橜lope;橘;橚΀;elmrszᘘᘙᘛᘞᘿᙏᙙ戠;榤e»ᘙsdĀ;aᘥᘦ戡ѡᘰᘲᘴᘶᘸᘺᘼᘾ;榨;榩;榪;榫;榬;榭;榮;榯tĀ;vᙅᙆ戟bĀ;dᙌᙍ抾;榝Āptᙔᙗh;戢»¹arr;捼Āgpᙣᙧon;䄅f;쀀𝕒΀;Eaeiop዁ᙻᙽᚂᚄᚇᚊ;橰cir;橯;扊d;手s;䀧roxĀ;e዁ᚒñᚃing耻å䃥ƀctyᚡᚦᚨr;쀀𝒶;䀪mpĀ;e዁ᚯñʈilde耻ã䃣ml耻ä䃤Āciᛂᛈoninôɲnt;樑ࠀNabcdefiklnoprsu᛭ᛱᜰ᜼ᝃᝈ᝸᝽០៦ᠹᡐᜍ᤽᥈ᥰot;櫭Ācrᛶ᜞kȀcepsᜀᜅᜍᜓong;扌psilon;䏶rime;怵imĀ;e᜚᜛戽q;拍Ŷᜢᜦee;抽edĀ;gᜬᜭ挅e»ᜭrkĀ;t፜᜷brk;掶Āoyᜁᝁ;䐱quo;怞ʀcmprtᝓ᝛ᝡᝤᝨausĀ;eĊĉptyv;榰séᜌnoõēƀahwᝯ᝱ᝳ;䎲;愶een;扬r;쀀𝔟g΀costuvwឍឝឳេ៕៛៞ƀaiuបពរðݠrc;旯p»፱ƀdptឤឨឭot;樀lus;樁imes;樂ɱឹ\0\0ើcup;樆ar;昅riangleĀdu៍្own;施p;斳plus;樄eåᑄåᒭarow;植ƀako៭ᠦᠵĀcn៲ᠣkƀlst៺֫᠂ozenge;槫riangleȀ;dlr᠒᠓᠘᠝斴own;斾eft;旂ight;斸k;搣Ʊᠫ\0ᠳƲᠯ\0ᠱ;斒;斑4;斓ck;斈ĀeoᠾᡍĀ;qᡃᡆ쀀=⃥uiv;쀀≡⃥t;挐Ȁptwxᡙᡞᡧᡬf;쀀𝕓Ā;tᏋᡣom»Ꮜtie;拈؀DHUVbdhmptuvᢅᢖᢪᢻᣗᣛᣬ᣿ᤅᤊᤐᤡȀLRlrᢎᢐᢒᢔ;敗;敔;敖;敓ʀ;DUduᢡᢢᢤᢦᢨ敐;敦;敩;敤;敧ȀLRlrᢳᢵᢷᢹ;敝;敚;敜;教΀;HLRhlrᣊᣋᣍᣏᣑᣓᣕ救;敬;散;敠;敫;敢;敟ox;槉ȀLRlrᣤᣦᣨᣪ;敕;敒;攐;攌ʀ;DUduڽ᣷᣹᣻᣽;敥;敨;攬;攴inus;抟lus;択imes;抠ȀLRlrᤙᤛᤝ᤟;敛;敘;攘;攔΀;HLRhlrᤰᤱᤳᤵᤷ᤻᤹攂;敪;敡;敞;攼;攤;攜Āevģ᥂bar耻¦䂦Ȁceioᥑᥖᥚᥠr;쀀𝒷mi;恏mĀ;e᜚᜜lƀ;bhᥨᥩᥫ䁜;槅sub;柈Ŭᥴ᥾lĀ;e᥹᥺怢t»᥺pƀ;Eeįᦅᦇ;檮Ā;qۜۛೡᦧ\0᧨ᨑᨕᨲ\0ᨷᩐ\0\0᪴\0\0᫁\0\0ᬡᬮ᭍᭒\0᯽\0ᰌƀcpr᦭ᦲ᧝ute;䄇̀;abcdsᦿᧀᧄ᧊᧕᧙戩nd;橄rcup;橉Āau᧏᧒p;橋p;橇ot;橀;쀀∩︀Āeo᧢᧥t;恁îړȀaeiu᧰᧻ᨁᨅǰ᧵\0᧸s;橍on;䄍dil耻ç䃧rc;䄉psĀ;sᨌᨍ橌m;橐ot;䄋ƀdmnᨛᨠᨦil肻¸ƭptyv;榲t脀¢;eᨭᨮ䂢räƲr;쀀𝔠ƀceiᨽᩀᩍy;䑇ckĀ;mᩇᩈ朓ark»ᩈ;䏇r΀;Ecefms᩟᩠ᩢᩫ᪤᪪᪮旋;槃ƀ;elᩩᩪᩭ䋆q;扗eɡᩴ\0\0᪈rrowĀlr᩼᪁eft;憺ight;憻ʀRSacd᪒᪔᪖᪚᪟»ཇ;擈st;抛irc;抚ash;抝nint;樐id;櫯cir;槂ubsĀ;u᪻᪼晣it»᪼ˬ᫇᫔᫺\0ᬊonĀ;eᫍᫎ䀺Ā;qÇÆɭ᫙\0\0᫢aĀ;t᫞᫟䀬;䁀ƀ;fl᫨᫩᫫戁îᅠeĀmx᫱᫶ent»᫩eóɍǧ᫾\0ᬇĀ;dኻᬂot;橭nôɆƀfryᬐᬔᬗ;쀀𝕔oäɔ脀©;sŕᬝr;愗Āaoᬥᬩrr;憵ss;朗Ācuᬲᬷr;쀀𝒸Ābpᬼ᭄Ā;eᭁᭂ櫏;櫑Ā;eᭉᭊ櫐;櫒dot;拯΀delprvw᭠᭬᭷ᮂᮬᯔ᯹arrĀlr᭨᭪;椸;椵ɰ᭲\0\0᭵r;拞c;拟arrĀ;p᭿ᮀ憶;椽̀;bcdosᮏᮐᮖᮡᮥᮨ截rcap;橈Āauᮛᮞp;橆p;橊ot;抍r;橅;쀀∪︀Ȁalrv᮵ᮿᯞᯣrrĀ;mᮼᮽ憷;椼yƀevwᯇᯔᯘqɰᯎ\0\0ᯒreã᭳uã᭵ee;拎edge;拏en耻¤䂤earrowĀlrᯮ᯳eft»ᮀight»ᮽeäᯝĀciᰁᰇoninôǷnt;戱lcty;挭ঀAHabcdefhijlorstuwz᰸᰻᰿ᱝᱩᱵᲊᲞᲬᲷ᳻᳿ᴍᵻᶑᶫᶻ᷆᷍rò΁ar;楥Ȁglrs᱈ᱍ᱒᱔ger;怠eth;愸òᄳhĀ;vᱚᱛ怐»ऊūᱡᱧarow;椏aã̕Āayᱮᱳron;䄏;䐴ƀ;ao̲ᱼᲄĀgrʿᲁr;懊tseq;橷ƀglmᲑᲔᲘ耻°䂰ta;䎴ptyv;榱ĀirᲣᲨsht;楿;쀀𝔡arĀlrᲳᲵ»ࣜ»သʀaegsv᳂͸᳖᳜᳠mƀ;oș᳊᳔ndĀ;ș᳑uit;晦amma;䏝in;拲ƀ;io᳧᳨᳸䃷de脀÷;o᳧ᳰntimes;拇nø᳷cy;䑒cɯᴆ\0\0ᴊrn;挞op;挍ʀlptuwᴘᴝᴢᵉᵕlar;䀤f;쀀𝕕ʀ;emps̋ᴭᴷᴽᵂqĀ;d͒ᴳot;扑inus;戸lus;戔quare;抡blebarwedgåúnƀadhᄮᵝᵧownarrowóᲃarpoonĀlrᵲᵶefôᲴighôᲶŢᵿᶅkaro÷གɯᶊ\0\0ᶎrn;挟op;挌ƀcotᶘᶣᶦĀryᶝᶡ;쀀𝒹;䑕l;槶rok;䄑Ādrᶰᶴot;拱iĀ;fᶺ᠖斿Āah᷀᷃ròЩaòྦangle;榦Āci᷒ᷕy;䑟grarr;柿ऀDacdefglmnopqrstuxḁḉḙḸոḼṉṡṾấắẽỡἪἷὄ὎὚ĀDoḆᴴoôᲉĀcsḎḔute耻é䃩ter;橮ȀaioyḢḧḱḶron;䄛rĀ;cḭḮ扖耻ê䃪lon;払;䑍ot;䄗ĀDrṁṅot;扒;쀀𝔢ƀ;rsṐṑṗ檚ave耻è䃨Ā;dṜṝ檖ot;檘Ȁ;ilsṪṫṲṴ檙nters;揧;愓Ā;dṹṺ檕ot;檗ƀapsẅẉẗcr;䄓tyƀ;svẒẓẕ戅et»ẓpĀ1;ẝẤĳạả;怄;怅怃ĀgsẪẬ;䅋p;怂ĀgpẴẸon;䄙f;쀀𝕖ƀalsỄỎỒrĀ;sỊị拕l;槣us;橱iƀ;lvỚớở䎵on»ớ;䏵ȀcsuvỪỳἋἣĀioữḱrc»Ḯɩỹ\0\0ỻíՈantĀglἂἆtr»ṝess»Ṻƀaeiἒ἖Ἒls;䀽st;扟vĀ;DȵἠD;橸parsl;槥ĀDaἯἳot;打rr;楱ƀcdiἾὁỸr;愯oô͒ĀahὉὋ;䎷耻ð䃰Āmrὓὗl耻ë䃫o;悬ƀcipὡὤὧl;䀡sôծĀeoὬὴctatioîՙnentialåչৡᾒ\0ᾞ\0ᾡᾧ\0\0ῆῌ\0ΐ\0ῦῪ \0 ⁚llingdotseñṄy;䑄male;晀ƀilrᾭᾳ῁lig;耀ﬃɩᾹ\0\0᾽g;耀ﬀig;耀ﬄ;쀀𝔣lig;耀ﬁlig;쀀fjƀaltῙ῜ῡt;晭ig;耀ﬂns;斱of;䆒ǰ΅\0ῳf;쀀𝕗ĀakֿῷĀ;vῼ´拔;櫙artint;樍Āao‌⁕Ācs‑⁒α‚‰‸⁅⁈\0⁐β•‥‧‪‬\0‮耻½䂽;慓耻¼䂼;慕;慙;慛Ƴ‴\0‶;慔;慖ʴ‾⁁\0\0⁃耻¾䂾;慗;慜5;慘ƶ⁌\0⁎;慚;慝8;慞l;恄wn;挢cr;쀀𝒻ࢀEabcdefgijlnorstv₂₉₟₥₰₴⃰⃵⃺⃿℃ℒℸ̗ℾ⅒↞Ā;lٍ₇;檌ƀcmpₐₕ₝ute;䇵maĀ;dₜ᳚䎳;檆reve;䄟Āiy₪₮rc;䄝;䐳ot;䄡Ȁ;lqsؾق₽⃉ƀ;qsؾٌ⃄lanô٥Ȁ;cdl٥⃒⃥⃕c;檩otĀ;o⃜⃝檀Ā;l⃢⃣檂;檄Ā;e⃪⃭쀀⋛︀s;檔r;쀀𝔤Ā;gٳ؛mel;愷cy;䑓Ȁ;Eajٚℌℎℐ;檒;檥;檤ȀEaesℛℝ℩ℴ;扩pĀ;p℣ℤ檊rox»ℤĀ;q℮ℯ檈Ā;q℮ℛim;拧pf;쀀𝕘Āci⅃ⅆr;愊mƀ;el٫ⅎ⅐;檎;檐茀>;cdlqr׮ⅠⅪⅮⅳⅹĀciⅥⅧ;檧r;橺ot;拗Par;榕uest;橼ʀadelsↄⅪ←ٖ↛ǰ↉\0↎proø₞r;楸qĀlqؿ↖lesó₈ií٫Āen↣↭rtneqq;쀀≩︀Å↪ԀAabcefkosy⇄⇇⇱⇵⇺∘∝∯≨≽ròΠȀilmr⇐⇔⇗⇛rsðᒄf»․ilôکĀdr⇠⇤cy;䑊ƀ;cwࣴ⇫⇯ir;楈;憭ar;意irc;䄥ƀalr∁∎∓rtsĀ;u∉∊晥it»∊lip;怦con;抹r;쀀𝔥sĀew∣∩arow;椥arow;椦ʀamopr∺∾≃≞≣rr;懿tht;戻kĀlr≉≓eftarrow;憩ightarrow;憪f;쀀𝕙bar;怕ƀclt≯≴≸r;쀀𝒽asè⇴rok;䄧Ābp⊂⊇ull;恃hen»ᱛૡ⊣\0⊪\0⊸⋅⋎\0⋕⋳\0\0⋸⌢⍧⍢⍿\0⎆⎪⎴cute耻í䃭ƀ;iyݱ⊰⊵rc耻î䃮;䐸Ācx⊼⊿y;䐵cl耻¡䂡ĀfrΟ⋉;쀀𝔦rave耻ì䃬Ȁ;inoܾ⋝⋩⋮Āin⋢⋦nt;樌t;戭fin;槜ta;愩lig;䄳ƀaop⋾⌚⌝ƀcgt⌅⌈⌗r;䄫ƀelpܟ⌏⌓inåގarôܠh;䄱f;抷ed;䆵ʀ;cfotӴ⌬⌱⌽⍁are;愅inĀ;t⌸⌹戞ie;槝doô⌙ʀ;celpݗ⍌⍐⍛⍡al;抺Āgr⍕⍙eróᕣã⍍arhk;樗rod;樼Ȁcgpt⍯⍲⍶⍻y;䑑on;䄯f;쀀𝕚a;䎹uest耻¿䂿Āci⎊⎏r;쀀𝒾nʀ;EdsvӴ⎛⎝⎡ӳ;拹ot;拵Ā;v⎦⎧拴;拳Ā;iݷ⎮lde;䄩ǫ⎸\0⎼cy;䑖l耻ï䃯̀cfmosu⏌⏗⏜⏡⏧⏵Āiy⏑⏕rc;䄵;䐹r;쀀𝔧ath;䈷pf;쀀𝕛ǣ⏬\0⏱r;쀀𝒿rcy;䑘kcy;䑔Ѐacfghjos␋␖␢␧␭␱␵␻ppaĀ;v␓␔䎺;䏰Āey␛␠dil;䄷;䐺r;쀀𝔨reen;䄸cy;䑅cy;䑜pf;쀀𝕜cr;쀀𝓀஀ABEHabcdefghjlmnoprstuv⑰⒁⒆⒍⒑┎┽╚▀♎♞♥♹♽⚚⚲⛘❝❨➋⟀⠁⠒ƀart⑷⑺⑼rò৆òΕail;椛arr;椎Ā;gঔ⒋;檋ar;楢ॣ⒥\0⒪\0⒱\0\0\0\0\0⒵Ⓔ\0ⓆⓈⓍ\0⓹ute;䄺mptyv;榴raîࡌbda;䎻gƀ;dlࢎⓁⓃ;榑åࢎ;檅uo耻«䂫rЀ;bfhlpst࢙ⓞⓦⓩ⓫⓮⓱⓵Ā;f࢝ⓣs;椟s;椝ë≒p;憫l;椹im;楳l;憢ƀ;ae⓿─┄檫il;椙Ā;s┉┊檭;쀀⪭︀ƀabr┕┙┝rr;椌rk;杲Āak┢┬cĀek┨┪;䁻;䁛Āes┱┳;榋lĀdu┹┻;榏;榍Ȁaeuy╆╋╖╘ron;䄾Ādi═╔il;䄼ìࢰâ┩;䐻Ȁcqrs╣╦╭╽a;椶uoĀ;rนᝆĀdu╲╷har;楧shar;楋h;憲ʀ;fgqs▋▌উ◳◿扤tʀahlrt▘▤▷◂◨rrowĀ;t࢙□aé⓶arpoonĀdu▯▴own»њp»०eftarrows;懇ightƀahs◍◖◞rrowĀ;sࣴࢧarpoonó྘quigarro÷⇰hreetimes;拋ƀ;qs▋ও◺lanôবʀ;cdgsব☊☍☝☨c;檨otĀ;o☔☕橿Ā;r☚☛檁;檃Ā;e☢☥쀀⋚︀s;檓ʀadegs☳☹☽♉♋pproøⓆot;拖qĀgq♃♅ôউgtò⒌ôছiíলƀilr♕࣡♚sht;楼;쀀𝔩Ā;Eজ♣;檑š♩♶rĀdu▲♮Ā;l॥♳;楪lk;斄cy;䑙ʀ;achtੈ⚈⚋⚑⚖rò◁orneòᴈard;楫ri;旺Āio⚟⚤dot;䅀ustĀ;a⚬⚭掰che»⚭ȀEaes⚻⚽⛉⛔;扨pĀ;p⛃⛄檉rox»⛄Ā;q⛎⛏檇Ā;q⛎⚻im;拦Ѐabnoptwz⛩⛴⛷✚✯❁❇❐Ānr⛮⛱g;柬r;懽rëࣁgƀlmr⛿✍✔eftĀar০✇ightá৲apsto;柼ightá৽parrowĀlr✥✩efô⓭ight;憬ƀafl✶✹✽r;榅;쀀𝕝us;樭imes;樴š❋❏st;戗áፎƀ;ef❗❘᠀旊nge»❘arĀ;l❤❥䀨t;榓ʀachmt❳❶❼➅➇ròࢨorneòᶌarĀ;d྘➃;業;怎ri;抿̀achiqt➘➝ੀ➢➮➻quo;怹r;쀀𝓁mƀ;egল➪➬;檍;檏Ābu┪➳oĀ;rฟ➹;怚rok;䅂萀<;cdhilqrࠫ⟒☹⟜⟠⟥⟪⟰Āci⟗⟙;檦r;橹reå◲mes;拉arr;楶uest;橻ĀPi⟵⟹ar;榖ƀ;ef⠀भ᠛旃rĀdu⠇⠍shar;楊har;楦Āen⠗⠡rtneqq;쀀≨︀Å⠞܀Dacdefhilnopsu⡀⡅⢂⢎⢓⢠⢥⢨⣚⣢⣤ઃ⣳⤂Dot;戺Ȁclpr⡎⡒⡣⡽r耻¯䂯Āet⡗⡙;時Ā;e⡞⡟朠se»⡟Ā;sျ⡨toȀ;dluျ⡳⡷⡻owîҌefôएðᏑker;斮Āoy⢇⢌mma;権;䐼ash;怔asuredangle»ᘦr;쀀𝔪o;愧ƀcdn⢯⢴⣉ro耻µ䂵Ȁ;acdᑤ⢽⣀⣄sôᚧir;櫰ot肻·Ƶusƀ;bd⣒ᤃ⣓戒Ā;uᴼ⣘;横ţ⣞⣡p;櫛ò−ðઁĀdp⣩⣮els;抧f;쀀𝕞Āct⣸⣽r;쀀𝓂pos»ᖝƀ;lm⤉⤊⤍䎼timap;抸ఀGLRVabcdefghijlmoprstuvw⥂⥓⥾⦉⦘⧚⧩⨕⨚⩘⩝⪃⪕⪤⪨⬄⬇⭄⭿⮮ⰴⱧⱼ⳩Āgt⥇⥋;쀀⋙̸Ā;v⥐௏쀀≫⃒ƀelt⥚⥲⥶ftĀar⥡⥧rrow;懍ightarrow;懎;쀀⋘̸Ā;v⥻ే쀀≪⃒ightarrow;懏ĀDd⦎⦓ash;抯ash;抮ʀbcnpt⦣⦧⦬⦱⧌la»˞ute;䅄g;쀀∠⃒ʀ;Eiop඄⦼⧀⧅⧈;쀀⩰̸d;쀀≋̸s;䅉roø඄urĀ;a⧓⧔普lĀ;s⧓ସǳ⧟\0⧣p肻 ଷmpĀ;e௹ఀʀaeouy⧴⧾⨃⨐⨓ǰ⧹\0⧻;橃on;䅈dil;䅆ngĀ;dൾ⨊ot;쀀⩭̸p;橂;䐽ash;怓΀;Aadqsxஒ⨩⨭⨻⩁⩅⩐rr;懗rĀhr⨳⨶k;椤Ā;oᏲᏰot;쀀≐̸uiöୣĀei⩊⩎ar;椨í஘istĀ;s஠டr;쀀𝔫ȀEest௅⩦⩹⩼ƀ;qs஼⩭௡ƀ;qs஼௅⩴lanô௢ií௪Ā;rஶ⪁»ஷƀAap⪊⪍⪑rò⥱rr;憮ar;櫲ƀ;svྍ⪜ྌĀ;d⪡⪢拼;拺cy;䑚΀AEadest⪷⪺⪾⫂⫅⫶⫹rò⥦;쀀≦̸rr;憚r;急Ȁ;fqs఻⫎⫣⫯tĀar⫔⫙rro÷⫁ightarro÷⪐ƀ;qs఻⪺⫪lanôౕĀ;sౕ⫴»శiíౝĀ;rవ⫾iĀ;eచథiäඐĀpt⬌⬑f;쀀𝕟膀¬;in⬙⬚⬶䂬nȀ;Edvஉ⬤⬨⬮;쀀⋹̸ot;쀀⋵̸ǡஉ⬳⬵;拷;拶iĀ;vಸ⬼ǡಸ⭁⭃;拾;拽ƀaor⭋⭣⭩rȀ;ast୻⭕⭚⭟lleì୻l;쀀⫽⃥;쀀∂̸lint;樔ƀ;ceಒ⭰⭳uåಥĀ;cಘ⭸Ā;eಒ⭽ñಘȀAait⮈⮋⮝⮧rò⦈rrƀ;cw⮔⮕⮙憛;쀀⤳̸;쀀↝̸ghtarrow»⮕riĀ;eೋೖ΀chimpqu⮽⯍⯙⬄୸⯤⯯Ȁ;cerല⯆ഷ⯉uå൅;쀀𝓃ortɭ⬅\0\0⯖ará⭖mĀ;e൮⯟Ā;q൴൳suĀbp⯫⯭å೸åഋƀbcp⯶ⰑⰙȀ;Ees⯿ⰀഢⰄ抄;쀀⫅̸etĀ;eഛⰋqĀ;qണⰀcĀ;eലⰗñസȀ;EesⰢⰣൟⰧ抅;쀀⫆̸etĀ;e൘ⰮqĀ;qൠⰣȀgilrⰽⰿⱅⱇìௗlde耻ñ䃱çృiangleĀlrⱒⱜeftĀ;eచⱚñదightĀ;eೋⱥñ೗Ā;mⱬⱭ䎽ƀ;esⱴⱵⱹ䀣ro;愖p;怇ҀDHadgilrsⲏⲔⲙⲞⲣⲰⲶⳓⳣash;抭arr;椄p;쀀≍⃒ash;抬ĀetⲨⲬ;쀀≥⃒;쀀>⃒nfin;槞ƀAetⲽⳁⳅrr;椂;쀀≤⃒Ā;rⳊⳍ쀀<⃒ie;쀀⊴⃒ĀAtⳘⳜrr;椃rie;쀀⊵⃒im;쀀∼⃒ƀAan⳰⳴ⴂrr;懖rĀhr⳺⳽k;椣Ā;oᏧᏥear;椧ቓ᪕\0\0\0\0\0\0\0\0\0\0\0\0\0ⴭ\0ⴸⵈⵠⵥ⵲ⶄᬇ\0\0ⶍⶫ\0ⷈⷎ\0ⷜ⸙⸫⸾⹃Ācsⴱ᪗ute耻ó䃳ĀiyⴼⵅrĀ;c᪞ⵂ耻ô䃴;䐾ʀabios᪠ⵒⵗǈⵚlac;䅑v;樸old;榼lig;䅓Ācr⵩⵭ir;榿;쀀𝔬ͯ⵹\0\0⵼\0ⶂn;䋛ave耻ò䃲;槁Ābmⶈ෴ar;榵Ȁacitⶕ⶘ⶥⶨrò᪀Āir⶝ⶠr;榾oss;榻nå๒;槀ƀaeiⶱⶵⶹcr;䅍ga;䏉ƀcdnⷀⷅǍron;䎿;榶pf;쀀𝕠ƀaelⷔ⷗ǒr;榷rp;榹΀;adiosvⷪⷫⷮ⸈⸍⸐⸖戨rò᪆Ȁ;efmⷷⷸ⸂⸅橝rĀ;oⷾⷿ愴f»ⷿ耻ª䂪耻º䂺gof;抶r;橖lope;橗;橛ƀclo⸟⸡⸧ò⸁ash耻ø䃸l;折iŬⸯ⸴de耻õ䃵esĀ;aǛ⸺s;樶ml耻ö䃶bar;挽ૡ⹞\0⹽\0⺀⺝\0⺢⺹\0\0⻋ຜ\0⼓\0\0⼫⾼\0⿈rȀ;astЃ⹧⹲຅脀¶;l⹭⹮䂶leìЃɩ⹸\0\0⹻m;櫳;櫽y;䐿rʀcimpt⺋⺏⺓ᡥ⺗nt;䀥od;䀮il;怰enk;怱r;쀀𝔭ƀimo⺨⺰⺴Ā;v⺭⺮䏆;䏕maô੶ne;明ƀ;tv⺿⻀⻈䏀chfork»´;䏖Āau⻏⻟nĀck⻕⻝kĀ;h⇴⻛;愎ö⇴sҀ;abcdemst⻳⻴ᤈ⻹⻽⼄⼆⼊⼎䀫cir;樣ir;樢Āouᵀ⼂;樥;橲n肻±ຝim;樦wo;樧ƀipu⼙⼠⼥ntint;樕f;쀀𝕡nd耻£䂣Ԁ;Eaceinosu່⼿⽁⽄⽇⾁⾉⾒⽾⾶;檳p;檷uå໙Ā;c໎⽌̀;acens່⽙⽟⽦⽨⽾pproø⽃urlyeñ໙ñ໎ƀaes⽯⽶⽺pprox;檹qq;檵im;拨iíໟmeĀ;s⾈ຮ怲ƀEas⽸⾐⽺ð⽵ƀdfp໬⾙⾯ƀals⾠⾥⾪lar;挮ine;挒urf;挓Ā;t໻⾴ï໻rel;抰Āci⿀⿅r;쀀𝓅;䏈ncsp;怈̀fiopsu⿚⋢⿟⿥⿫⿱r;쀀𝔮pf;쀀𝕢rime;恗cr;쀀𝓆ƀaeo⿸〉〓tĀei⿾々rnionóڰnt;樖stĀ;e【】䀿ñἙô༔઀ABHabcdefhilmnoprstux぀けさすムㄎㄫㅇㅢㅲㆎ㈆㈕㈤㈩㉘㉮㉲㊐㊰㊷ƀartぇおがròႳòϝail;検aròᱥar;楤΀cdenqrtとふへみわゔヌĀeuねぱ;쀀∽̱te;䅕iãᅮmptyv;榳gȀ;del࿑らるろ;榒;榥å࿑uo耻»䂻rր;abcfhlpstw࿜ガクシスゼゾダッデナp;極Ā;f࿠ゴs;椠;椳s;椞ë≝ð✮l;楅im;楴l;憣;憝Āaiパフil;椚oĀ;nホボ戶aló༞ƀabrョリヮrò៥rk;杳ĀakンヽcĀekヹ・;䁽;䁝Āes㄂㄄;榌lĀduㄊㄌ;榎;榐Ȁaeuyㄗㄜㄧㄩron;䅙Ādiㄡㄥil;䅗ì࿲âヺ;䑀Ȁclqsㄴㄷㄽㅄa;椷dhar;楩uoĀ;rȎȍh;憳ƀacgㅎㅟངlȀ;ipsླྀㅘㅛႜnåႻarôྩt;断ƀilrㅩဣㅮsht;楽;쀀𝔯ĀaoㅷㆆrĀduㅽㅿ»ѻĀ;l႑ㆄ;楬Ā;vㆋㆌ䏁;䏱ƀgns㆕ㇹㇼht̀ahlrstㆤㆰ㇂㇘㇤㇮rrowĀ;t࿜ㆭaéトarpoonĀduㆻㆿowîㅾp»႒eftĀah㇊㇐rrowó࿪arpoonóՑightarrows;應quigarro÷ニhreetimes;拌g;䋚ingdotseñἲƀahm㈍㈐㈓rò࿪aòՑ;怏oustĀ;a㈞㈟掱che»㈟mid;櫮Ȁabpt㈲㈽㉀㉒Ānr㈷㈺g;柭r;懾rëဃƀafl㉇㉊㉎r;榆;쀀𝕣us;樮imes;樵Āap㉝㉧rĀ;g㉣㉤䀩t;榔olint;樒arò㇣Ȁachq㉻㊀Ⴜ㊅quo;怺r;쀀𝓇Ābu・㊊oĀ;rȔȓƀhir㊗㊛㊠reåㇸmes;拊iȀ;efl㊪ၙᠡ㊫方tri;槎luhar;楨;愞ൡ㋕㋛㋟㌬㌸㍱\0㍺㎤\0\0㏬㏰\0㐨㑈㑚㒭㒱㓊㓱\0㘖\0\0㘳cute;䅛quï➺Ԁ;Eaceinpsyᇭ㋳㋵㋿㌂㌋㌏㌟㌦㌩;檴ǰ㋺\0㋼;檸on;䅡uåᇾĀ;dᇳ㌇il;䅟rc;䅝ƀEas㌖㌘㌛;檶p;檺im;择olint;樓iíሄ;䑁otƀ;be㌴ᵇ㌵担;橦΀Aacmstx㍆㍊㍗㍛㍞㍣㍭rr;懘rĀhr㍐㍒ë∨Ā;oਸ਼਴t耻§䂧i;䀻war;椩mĀin㍩ðnuóñt;朶rĀ;o㍶⁕쀀𝔰Ȁacoy㎂㎆㎑㎠rp;景Āhy㎋㎏cy;䑉;䑈rtɭ㎙\0\0㎜iäᑤaraì⹯耻­䂭Āgm㎨㎴maƀ;fv㎱㎲㎲䏃;䏂Ѐ;deglnprካ㏅㏉㏎㏖㏞㏡㏦ot;橪Ā;q኱ኰĀ;E㏓㏔檞;檠Ā;E㏛㏜檝;檟e;扆lus;樤arr;楲aròᄽȀaeit㏸㐈㐏㐗Āls㏽㐄lsetmé㍪hp;樳parsl;槤Ādlᑣ㐔e;挣Ā;e㐜㐝檪Ā;s㐢㐣檬;쀀⪬︀ƀflp㐮㐳㑂tcy;䑌Ā;b㐸㐹䀯Ā;a㐾㐿槄r;挿f;쀀𝕤aĀdr㑍ЂesĀ;u㑔㑕晠it»㑕ƀcsu㑠㑹㒟Āau㑥㑯pĀ;sᆈ㑫;쀀⊓︀pĀ;sᆴ㑵;쀀⊔︀uĀbp㑿㒏ƀ;esᆗᆜ㒆etĀ;eᆗ㒍ñᆝƀ;esᆨᆭ㒖etĀ;eᆨ㒝ñᆮƀ;afᅻ㒦ְrť㒫ֱ»ᅼaròᅈȀcemt㒹㒾㓂㓅r;쀀𝓈tmîñiì㐕aræᆾĀar㓎㓕rĀ;f㓔ឿ昆Āan㓚㓭ightĀep㓣㓪psiloîỠhé⺯s»⡒ʀbcmnp㓻㕞ሉ㖋㖎Ҁ;Edemnprs㔎㔏㔑㔕㔞㔣㔬㔱㔶抂;櫅ot;檽Ā;dᇚ㔚ot;櫃ult;櫁ĀEe㔨㔪;櫋;把lus;檿arr;楹ƀeiu㔽㕒㕕tƀ;en㔎㕅㕋qĀ;qᇚ㔏eqĀ;q㔫㔨m;櫇Ābp㕚㕜;櫕;櫓c̀;acensᇭ㕬㕲㕹㕻㌦pproø㋺urlyeñᇾñᇳƀaes㖂㖈㌛pproø㌚qñ㌗g;晪ڀ123;Edehlmnps㖩㖬㖯ሜ㖲㖴㗀㗉㗕㗚㗟㗨㗭耻¹䂹耻²䂲耻³䂳;櫆Āos㖹㖼t;檾ub;櫘Ā;dሢ㗅ot;櫄sĀou㗏㗒l;柉b;櫗arr;楻ult;櫂ĀEe㗤㗦;櫌;抋lus;櫀ƀeiu㗴㘉㘌tƀ;enሜ㗼㘂qĀ;qሢ㖲eqĀ;q㗧㗤m;櫈Ābp㘑㘓;櫔;櫖ƀAan㘜㘠㘭rr;懙rĀhr㘦㘨ë∮Ā;oਫ਩war;椪lig耻ß䃟௡㙑㙝㙠ዎ㙳㙹\0㙾㛂\0\0\0\0\0㛛㜃\0㜉㝬\0\0\0㞇ɲ㙖\0\0㙛get;挖;䏄rë๟ƀaey㙦㙫㙰ron;䅥dil;䅣;䑂lrec;挕r;쀀𝔱Ȁeiko㚆㚝㚵㚼ǲ㚋\0㚑eĀ4fኄኁaƀ;sv㚘㚙㚛䎸ym;䏑Ācn㚢㚲kĀas㚨㚮pproø዁im»ኬsðኞĀas㚺㚮ð዁rn耻þ䃾Ǭ̟㛆⋧es膀×;bd㛏㛐㛘䃗Ā;aᤏ㛕r;樱;樰ƀeps㛡㛣㜀á⩍Ȁ;bcf҆㛬㛰㛴ot;挶ir;櫱Ā;o㛹㛼쀀𝕥rk;櫚á㍢rime;怴ƀaip㜏㜒㝤dåቈ΀adempst㜡㝍㝀㝑㝗㝜㝟ngleʀ;dlqr㜰㜱㜶㝀㝂斵own»ᶻeftĀ;e⠀㜾ñम;扜ightĀ;e㊪㝋ñၚot;旬inus;樺lus;樹b;槍ime;樻ezium;揢ƀcht㝲㝽㞁Āry㝷㝻;쀀𝓉;䑆cy;䑛rok;䅧Āio㞋㞎xô᝷headĀlr㞗㞠eftarro÷ࡏightarrow»ཝऀAHabcdfghlmoprstuw㟐㟓㟗㟤㟰㟼㠎㠜㠣㠴㡑㡝㡫㢩㣌㣒㣪㣶ròϭar;楣Ācr㟜㟢ute耻ú䃺òᅐrǣ㟪\0㟭y;䑞ve;䅭Āiy㟵㟺rc耻û䃻;䑃ƀabh㠃㠆㠋ròᎭlac;䅱aòᏃĀir㠓㠘sht;楾;쀀𝔲rave耻ù䃹š㠧㠱rĀlr㠬㠮»ॗ»ႃlk;斀Āct㠹㡍ɯ㠿\0\0㡊rnĀ;e㡅㡆挜r»㡆op;挏ri;旸Āal㡖㡚cr;䅫肻¨͉Āgp㡢㡦on;䅳f;쀀𝕦̀adhlsuᅋ㡸㡽፲㢑㢠ownáᎳarpoonĀlr㢈㢌efô㠭ighô㠯iƀ;hl㢙㢚㢜䏅»ᏺon»㢚parrows;懈ƀcit㢰㣄㣈ɯ㢶\0\0㣁rnĀ;e㢼㢽挝r»㢽op;挎ng;䅯ri;旹cr;쀀𝓊ƀdir㣙㣝㣢ot;拰lde;䅩iĀ;f㜰㣨»᠓Āam㣯㣲rò㢨l耻ü䃼angle;榧ހABDacdeflnoprsz㤜㤟㤩㤭㦵㦸㦽㧟㧤㧨㧳㧹㧽㨁㨠ròϷarĀ;v㤦㤧櫨;櫩asèϡĀnr㤲㤷grt;榜΀eknprst㓣㥆㥋㥒㥝㥤㦖appá␕othinçẖƀhir㓫⻈㥙opô⾵Ā;hᎷ㥢ïㆍĀiu㥩㥭gmá㎳Ābp㥲㦄setneqĀ;q㥽㦀쀀⊊︀;쀀⫋︀setneqĀ;q㦏㦒쀀⊋︀;쀀⫌︀Āhr㦛㦟etá㚜iangleĀlr㦪㦯eft»थight»ၑy;䐲ash»ံƀelr㧄㧒㧗ƀ;beⷪ㧋㧏ar;抻q;扚lip;拮Ābt㧜ᑨaòᑩr;쀀𝔳tré㦮suĀbp㧯㧱»ജ»൙pf;쀀𝕧roð໻tré㦴Ācu㨆㨋r;쀀𝓋Ābp㨐㨘nĀEe㦀㨖»㥾nĀEe㦒㨞»㦐igzag;榚΀cefoprs㨶㨻㩖㩛㩔㩡㩪irc;䅵Ādi㩀㩑Ābg㩅㩉ar;機eĀ;qᗺ㩏;扙erp;愘r;쀀𝔴pf;쀀𝕨Ā;eᑹ㩦atèᑹcr;쀀𝓌ૣណ㪇\0㪋\0㪐㪛\0\0㪝㪨㪫㪯\0\0㫃㫎\0㫘ៜ៟tré៑r;쀀𝔵ĀAa㪔㪗ròσrò৶;䎾ĀAa㪡㪤ròθrò৫að✓is;拻ƀdptឤ㪵㪾Āfl㪺ឩ;쀀𝕩imåឲĀAa㫇㫊ròώròਁĀcq㫒ីr;쀀𝓍Āpt៖㫜ré។Ѐacefiosu㫰㫽㬈㬌㬑㬕㬛㬡cĀuy㫶㫻te耻ý䃽;䑏Āiy㬂㬆rc;䅷;䑋n耻¥䂥r;쀀𝔶cy;䑗pf;쀀𝕪cr;쀀𝓎Ācm㬦㬩y;䑎l耻ÿ䃿Ԁacdefhiosw㭂㭈㭔㭘㭤㭩㭭㭴㭺㮀cute;䅺Āay㭍㭒ron;䅾;䐷ot;䅼Āet㭝㭡træᕟa;䎶r;쀀𝔷cy;䐶grarr;懝pf;쀀𝕫cr;쀀𝓏Ājn㮅㮇;怍j;怌'.split("").map((c2) => c2.charCodeAt(0))
);
const xmlDecodeTree = new Uint16Array(
  // prettier-ignore
  "Ȁaglq	\x1Bɭ\0\0p;䀦os;䀧t;䀾t;䀼uot;䀢".split("").map((c2) => c2.charCodeAt(0))
);
var _a$1;
const decodeMap = /* @__PURE__ */ new Map([
  [0, 65533],
  // C1 Unicode control character reference replacements
  [128, 8364],
  [130, 8218],
  [131, 402],
  [132, 8222],
  [133, 8230],
  [134, 8224],
  [135, 8225],
  [136, 710],
  [137, 8240],
  [138, 352],
  [139, 8249],
  [140, 338],
  [142, 381],
  [145, 8216],
  [146, 8217],
  [147, 8220],
  [148, 8221],
  [149, 8226],
  [150, 8211],
  [151, 8212],
  [152, 732],
  [153, 8482],
  [154, 353],
  [155, 8250],
  [156, 339],
  [158, 382],
  [159, 376]
]);
const fromCodePoint$1 = (
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, node/no-unsupported-features/es-builtins
  (_a$1 = String.fromCodePoint) !== null && _a$1 !== void 0 ? _a$1 : function(codePoint) {
    let output2 = "";
    if (codePoint > 65535) {
      codePoint -= 65536;
      output2 += String.fromCharCode(codePoint >>> 10 & 1023 | 55296);
      codePoint = 56320 | codePoint & 1023;
    }
    output2 += String.fromCharCode(codePoint);
    return output2;
  }
);
function replaceCodePoint(codePoint) {
  var _a2;
  if (codePoint >= 55296 && codePoint <= 57343 || codePoint > 1114111) {
    return 65533;
  }
  return (_a2 = decodeMap.get(codePoint)) !== null && _a2 !== void 0 ? _a2 : codePoint;
}
var CharCodes;
(function(CharCodes2) {
  CharCodes2[CharCodes2["NUM"] = 35] = "NUM";
  CharCodes2[CharCodes2["SEMI"] = 59] = "SEMI";
  CharCodes2[CharCodes2["EQUALS"] = 61] = "EQUALS";
  CharCodes2[CharCodes2["ZERO"] = 48] = "ZERO";
  CharCodes2[CharCodes2["NINE"] = 57] = "NINE";
  CharCodes2[CharCodes2["LOWER_A"] = 97] = "LOWER_A";
  CharCodes2[CharCodes2["LOWER_F"] = 102] = "LOWER_F";
  CharCodes2[CharCodes2["LOWER_X"] = 120] = "LOWER_X";
  CharCodes2[CharCodes2["LOWER_Z"] = 122] = "LOWER_Z";
  CharCodes2[CharCodes2["UPPER_A"] = 65] = "UPPER_A";
  CharCodes2[CharCodes2["UPPER_F"] = 70] = "UPPER_F";
  CharCodes2[CharCodes2["UPPER_Z"] = 90] = "UPPER_Z";
})(CharCodes || (CharCodes = {}));
const TO_LOWER_BIT = 32;
var BinTrieFlags;
(function(BinTrieFlags2) {
  BinTrieFlags2[BinTrieFlags2["VALUE_LENGTH"] = 49152] = "VALUE_LENGTH";
  BinTrieFlags2[BinTrieFlags2["BRANCH_LENGTH"] = 16256] = "BRANCH_LENGTH";
  BinTrieFlags2[BinTrieFlags2["JUMP_TABLE"] = 127] = "JUMP_TABLE";
})(BinTrieFlags || (BinTrieFlags = {}));
function isNumber(code2) {
  return code2 >= CharCodes.ZERO && code2 <= CharCodes.NINE;
}
function isHexadecimalCharacter(code2) {
  return code2 >= CharCodes.UPPER_A && code2 <= CharCodes.UPPER_F || code2 >= CharCodes.LOWER_A && code2 <= CharCodes.LOWER_F;
}
function isAsciiAlphaNumeric(code2) {
  return code2 >= CharCodes.UPPER_A && code2 <= CharCodes.UPPER_Z || code2 >= CharCodes.LOWER_A && code2 <= CharCodes.LOWER_Z || isNumber(code2);
}
function isEntityInAttributeInvalidEnd(code2) {
  return code2 === CharCodes.EQUALS || isAsciiAlphaNumeric(code2);
}
var EntityDecoderState;
(function(EntityDecoderState2) {
  EntityDecoderState2[EntityDecoderState2["EntityStart"] = 0] = "EntityStart";
  EntityDecoderState2[EntityDecoderState2["NumericStart"] = 1] = "NumericStart";
  EntityDecoderState2[EntityDecoderState2["NumericDecimal"] = 2] = "NumericDecimal";
  EntityDecoderState2[EntityDecoderState2["NumericHex"] = 3] = "NumericHex";
  EntityDecoderState2[EntityDecoderState2["NamedEntity"] = 4] = "NamedEntity";
})(EntityDecoderState || (EntityDecoderState = {}));
var DecodingMode;
(function(DecodingMode2) {
  DecodingMode2[DecodingMode2["Legacy"] = 0] = "Legacy";
  DecodingMode2[DecodingMode2["Strict"] = 1] = "Strict";
  DecodingMode2[DecodingMode2["Attribute"] = 2] = "Attribute";
})(DecodingMode || (DecodingMode = {}));
class EntityDecoder {
  constructor(decodeTree, emitCodePoint, errors2) {
    this.decodeTree = decodeTree;
    this.emitCodePoint = emitCodePoint;
    this.errors = errors2;
    this.state = EntityDecoderState.EntityStart;
    this.consumed = 1;
    this.result = 0;
    this.treeIndex = 0;
    this.excess = 1;
    this.decodeMode = DecodingMode.Strict;
  }
  /** Resets the instance to make it reusable. */
  startEntity(decodeMode) {
    this.decodeMode = decodeMode;
    this.state = EntityDecoderState.EntityStart;
    this.result = 0;
    this.treeIndex = 0;
    this.excess = 1;
    this.consumed = 1;
  }
  /**
   * Write an entity to the decoder. This can be called multiple times with partial entities.
   * If the entity is incomplete, the decoder will return -1.
   *
   * Mirrors the implementation of `getDecoder`, but with the ability to stop decoding if the
   * entity is incomplete, and resume when the next string is written.
   *
   * @param string The string containing the entity (or a continuation of the entity).
   * @param offset The offset at which the entity begins. Should be 0 if this is not the first call.
   * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
   */
  write(str, offset3) {
    switch (this.state) {
      case EntityDecoderState.EntityStart: {
        if (str.charCodeAt(offset3) === CharCodes.NUM) {
          this.state = EntityDecoderState.NumericStart;
          this.consumed += 1;
          return this.stateNumericStart(str, offset3 + 1);
        }
        this.state = EntityDecoderState.NamedEntity;
        return this.stateNamedEntity(str, offset3);
      }
      case EntityDecoderState.NumericStart: {
        return this.stateNumericStart(str, offset3);
      }
      case EntityDecoderState.NumericDecimal: {
        return this.stateNumericDecimal(str, offset3);
      }
      case EntityDecoderState.NumericHex: {
        return this.stateNumericHex(str, offset3);
      }
      case EntityDecoderState.NamedEntity: {
        return this.stateNamedEntity(str, offset3);
      }
    }
  }
  /**
   * Switches between the numeric decimal and hexadecimal states.
   *
   * Equivalent to the `Numeric character reference state` in the HTML spec.
   *
   * @param str The string containing the entity (or a continuation of the entity).
   * @param offset The current offset.
   * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
   */
  stateNumericStart(str, offset3) {
    if (offset3 >= str.length) {
      return -1;
    }
    if ((str.charCodeAt(offset3) | TO_LOWER_BIT) === CharCodes.LOWER_X) {
      this.state = EntityDecoderState.NumericHex;
      this.consumed += 1;
      return this.stateNumericHex(str, offset3 + 1);
    }
    this.state = EntityDecoderState.NumericDecimal;
    return this.stateNumericDecimal(str, offset3);
  }
  addToNumericResult(str, start2, end2, base2) {
    if (start2 !== end2) {
      const digitCount = end2 - start2;
      this.result = this.result * Math.pow(base2, digitCount) + parseInt(str.substr(start2, digitCount), base2);
      this.consumed += digitCount;
    }
  }
  /**
   * Parses a hexadecimal numeric entity.
   *
   * Equivalent to the `Hexademical character reference state` in the HTML spec.
   *
   * @param str The string containing the entity (or a continuation of the entity).
   * @param offset The current offset.
   * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
   */
  stateNumericHex(str, offset3) {
    const startIdx = offset3;
    while (offset3 < str.length) {
      const char = str.charCodeAt(offset3);
      if (isNumber(char) || isHexadecimalCharacter(char)) {
        offset3 += 1;
      } else {
        this.addToNumericResult(str, startIdx, offset3, 16);
        return this.emitNumericEntity(char, 3);
      }
    }
    this.addToNumericResult(str, startIdx, offset3, 16);
    return -1;
  }
  /**
   * Parses a decimal numeric entity.
   *
   * Equivalent to the `Decimal character reference state` in the HTML spec.
   *
   * @param str The string containing the entity (or a continuation of the entity).
   * @param offset The current offset.
   * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
   */
  stateNumericDecimal(str, offset3) {
    const startIdx = offset3;
    while (offset3 < str.length) {
      const char = str.charCodeAt(offset3);
      if (isNumber(char)) {
        offset3 += 1;
      } else {
        this.addToNumericResult(str, startIdx, offset3, 10);
        return this.emitNumericEntity(char, 2);
      }
    }
    this.addToNumericResult(str, startIdx, offset3, 10);
    return -1;
  }
  /**
   * Validate and emit a numeric entity.
   *
   * Implements the logic from the `Hexademical character reference start
   * state` and `Numeric character reference end state` in the HTML spec.
   *
   * @param lastCp The last code point of the entity. Used to see if the
   *               entity was terminated with a semicolon.
   * @param expectedLength The minimum number of characters that should be
   *                       consumed. Used to validate that at least one digit
   *                       was consumed.
   * @returns The number of characters that were consumed.
   */
  emitNumericEntity(lastCp, expectedLength) {
    var _a2;
    if (this.consumed <= expectedLength) {
      (_a2 = this.errors) === null || _a2 === void 0 ? void 0 : _a2.absenceOfDigitsInNumericCharacterReference(this.consumed);
      return 0;
    }
    if (lastCp === CharCodes.SEMI) {
      this.consumed += 1;
    } else if (this.decodeMode === DecodingMode.Strict) {
      return 0;
    }
    this.emitCodePoint(replaceCodePoint(this.result), this.consumed);
    if (this.errors) {
      if (lastCp !== CharCodes.SEMI) {
        this.errors.missingSemicolonAfterCharacterReference();
      }
      this.errors.validateNumericCharacterReference(this.result);
    }
    return this.consumed;
  }
  /**
   * Parses a named entity.
   *
   * Equivalent to the `Named character reference state` in the HTML spec.
   *
   * @param str The string containing the entity (or a continuation of the entity).
   * @param offset The current offset.
   * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
   */
  stateNamedEntity(str, offset3) {
    const { decodeTree } = this;
    let current3 = decodeTree[this.treeIndex];
    let valueLength = (current3 & BinTrieFlags.VALUE_LENGTH) >> 14;
    for (; offset3 < str.length; offset3++, this.excess++) {
      const char = str.charCodeAt(offset3);
      this.treeIndex = determineBranch(decodeTree, current3, this.treeIndex + Math.max(1, valueLength), char);
      if (this.treeIndex < 0) {
        return this.result === 0 || // If we are parsing an attribute
        this.decodeMode === DecodingMode.Attribute && // We shouldn't have consumed any characters after the entity,
        (valueLength === 0 || // And there should be no invalid characters.
        isEntityInAttributeInvalidEnd(char)) ? 0 : this.emitNotTerminatedNamedEntity();
      }
      current3 = decodeTree[this.treeIndex];
      valueLength = (current3 & BinTrieFlags.VALUE_LENGTH) >> 14;
      if (valueLength !== 0) {
        if (char === CharCodes.SEMI) {
          return this.emitNamedEntityData(this.treeIndex, valueLength, this.consumed + this.excess);
        }
        if (this.decodeMode !== DecodingMode.Strict) {
          this.result = this.treeIndex;
          this.consumed += this.excess;
          this.excess = 0;
        }
      }
    }
    return -1;
  }
  /**
   * Emit a named entity that was not terminated with a semicolon.
   *
   * @returns The number of characters consumed.
   */
  emitNotTerminatedNamedEntity() {
    var _a2;
    const { result: result2, decodeTree } = this;
    const valueLength = (decodeTree[result2] & BinTrieFlags.VALUE_LENGTH) >> 14;
    this.emitNamedEntityData(result2, valueLength, this.consumed);
    (_a2 = this.errors) === null || _a2 === void 0 ? void 0 : _a2.missingSemicolonAfterCharacterReference();
    return this.consumed;
  }
  /**
   * Emit a named entity.
   *
   * @param result The index of the entity in the decode tree.
   * @param valueLength The number of bytes in the entity.
   * @param consumed The number of characters consumed.
   *
   * @returns The number of characters consumed.
   */
  emitNamedEntityData(result2, valueLength, consumed) {
    const { decodeTree } = this;
    this.emitCodePoint(valueLength === 1 ? decodeTree[result2] & ~BinTrieFlags.VALUE_LENGTH : decodeTree[result2 + 1], consumed);
    if (valueLength === 3) {
      this.emitCodePoint(decodeTree[result2 + 2], consumed);
    }
    return consumed;
  }
  /**
   * Signal to the parser that the end of the input was reached.
   *
   * Remaining data will be emitted and relevant errors will be produced.
   *
   * @returns The number of characters consumed.
   */
  end() {
    var _a2;
    switch (this.state) {
      case EntityDecoderState.NamedEntity: {
        return this.result !== 0 && (this.decodeMode !== DecodingMode.Attribute || this.result === this.treeIndex) ? this.emitNotTerminatedNamedEntity() : 0;
      }
      // Otherwise, emit a numeric entity if we have one.
      case EntityDecoderState.NumericDecimal: {
        return this.emitNumericEntity(0, 2);
      }
      case EntityDecoderState.NumericHex: {
        return this.emitNumericEntity(0, 3);
      }
      case EntityDecoderState.NumericStart: {
        (_a2 = this.errors) === null || _a2 === void 0 ? void 0 : _a2.absenceOfDigitsInNumericCharacterReference(this.consumed);
        return 0;
      }
      case EntityDecoderState.EntityStart: {
        return 0;
      }
    }
  }
}
function getDecoder(decodeTree) {
  let ret = "";
  const decoder2 = new EntityDecoder(decodeTree, (str) => ret += fromCodePoint$1(str));
  return function decodeWithTrie(str, decodeMode) {
    let lastIndex = 0;
    let offset3 = 0;
    while ((offset3 = str.indexOf("&", offset3)) >= 0) {
      ret += str.slice(lastIndex, offset3);
      decoder2.startEntity(decodeMode);
      const len = decoder2.write(
        str,
        // Skip the "&"
        offset3 + 1
      );
      if (len < 0) {
        lastIndex = offset3 + decoder2.end();
        break;
      }
      lastIndex = offset3 + len;
      offset3 = len === 0 ? lastIndex + 1 : lastIndex;
    }
    const result2 = ret + str.slice(lastIndex);
    ret = "";
    return result2;
  };
}
function determineBranch(decodeTree, current3, nodeIdx, char) {
  const branchCount = (current3 & BinTrieFlags.BRANCH_LENGTH) >> 7;
  const jumpOffset = current3 & BinTrieFlags.JUMP_TABLE;
  if (branchCount === 0) {
    return jumpOffset !== 0 && char === jumpOffset ? nodeIdx : -1;
  }
  if (jumpOffset) {
    const value2 = char - jumpOffset;
    return value2 < 0 || value2 >= branchCount ? -1 : decodeTree[nodeIdx + value2] - 1;
  }
  let lo = nodeIdx;
  let hi = lo + branchCount - 1;
  while (lo <= hi) {
    const mid = lo + hi >>> 1;
    const midVal = decodeTree[mid];
    if (midVal < char) {
      lo = mid + 1;
    } else if (midVal > char) {
      hi = mid - 1;
    } else {
      return decodeTree[mid + branchCount];
    }
  }
  return -1;
}
const htmlDecoder = getDecoder(htmlDecodeTree);
getDecoder(xmlDecodeTree);
function decodeHTML(str, mode = DecodingMode.Legacy) {
  return htmlDecoder(str, mode);
}
function _class$1(obj) {
  return Object.prototype.toString.call(obj);
}
function isString$1(obj) {
  return _class$1(obj) === "[object String]";
}
const _hasOwnProperty = Object.prototype.hasOwnProperty;
function has(object2, key2) {
  return _hasOwnProperty.call(object2, key2);
}
function assign$1(obj) {
  const sources = Array.prototype.slice.call(arguments, 1);
  sources.forEach(function(source2) {
    if (!source2) {
      return;
    }
    if (typeof source2 !== "object") {
      throw new TypeError(source2 + "must be object");
    }
    Object.keys(source2).forEach(function(key2) {
      obj[key2] = source2[key2];
    });
  });
  return obj;
}
function arrayReplaceAt(src, pos2, newElements) {
  return [].concat(src.slice(0, pos2), newElements, src.slice(pos2 + 1));
}
function isValidEntityCode(c2) {
  if (c2 >= 55296 && c2 <= 57343) {
    return false;
  }
  if (c2 >= 64976 && c2 <= 65007) {
    return false;
  }
  if ((c2 & 65535) === 65535 || (c2 & 65535) === 65534) {
    return false;
  }
  if (c2 >= 0 && c2 <= 8) {
    return false;
  }
  if (c2 === 11) {
    return false;
  }
  if (c2 >= 14 && c2 <= 31) {
    return false;
  }
  if (c2 >= 127 && c2 <= 159) {
    return false;
  }
  if (c2 > 1114111) {
    return false;
  }
  return true;
}
function fromCodePoint(c2) {
  if (c2 > 65535) {
    c2 -= 65536;
    const surrogate1 = 55296 + (c2 >> 10);
    const surrogate2 = 56320 + (c2 & 1023);
    return String.fromCharCode(surrogate1, surrogate2);
  }
  return String.fromCharCode(c2);
}
const UNESCAPE_MD_RE = /\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/g;
const ENTITY_RE = /&([a-z#][a-z0-9]{1,31});/gi;
const UNESCAPE_ALL_RE = new RegExp(UNESCAPE_MD_RE.source + "|" + ENTITY_RE.source, "gi");
const DIGITAL_ENTITY_TEST_RE = /^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))$/i;
function replaceEntityPattern(match3, name2) {
  if (name2.charCodeAt(0) === 35 && DIGITAL_ENTITY_TEST_RE.test(name2)) {
    const code2 = name2[1].toLowerCase() === "x" ? parseInt(name2.slice(2), 16) : parseInt(name2.slice(1), 10);
    if (isValidEntityCode(code2)) {
      return fromCodePoint(code2);
    }
    return match3;
  }
  const decoded = decodeHTML(match3);
  if (decoded !== match3) {
    return decoded;
  }
  return match3;
}
function unescapeMd(str) {
  if (str.indexOf("\\") < 0) {
    return str;
  }
  return str.replace(UNESCAPE_MD_RE, "$1");
}
function unescapeAll(str) {
  if (str.indexOf("\\") < 0 && str.indexOf("&") < 0) {
    return str;
  }
  return str.replace(UNESCAPE_ALL_RE, function(match3, escaped, entity2) {
    if (escaped) {
      return escaped;
    }
    return replaceEntityPattern(match3, entity2);
  });
}
const HTML_ESCAPE_TEST_RE = /[&<>"]/;
const HTML_ESCAPE_REPLACE_RE = /[&<>"]/g;
const HTML_REPLACEMENTS = {
  "&": "&amp;",
  "<": "&lt;",
  ">": "&gt;",
  '"': "&quot;"
};
function replaceUnsafeChar(ch) {
  return HTML_REPLACEMENTS[ch];
}
function escapeHtml(str) {
  if (HTML_ESCAPE_TEST_RE.test(str)) {
    return str.replace(HTML_ESCAPE_REPLACE_RE, replaceUnsafeChar);
  }
  return str;
}
const REGEXP_ESCAPE_RE = /[.?*+^$[\]\\(){}|-]/g;
function escapeRE$1(str) {
  return str.replace(REGEXP_ESCAPE_RE, "\\$&");
}
function isSpace(code2) {
  switch (code2) {
    case 9:
    case 32:
      return true;
  }
  return false;
}
function isWhiteSpace(code2) {
  if (code2 >= 8192 && code2 <= 8202) {
    return true;
  }
  switch (code2) {
    case 9:
    // \t
    case 10:
    // \n
    case 11:
    // \v
    case 12:
    // \f
    case 13:
    // \r
    case 32:
    case 160:
    case 5760:
    case 8239:
    case 8287:
    case 12288:
      return true;
  }
  return false;
}
function isPunctChar(ch) {
  return P.test(ch) || regex.test(ch);
}
function isMdAsciiPunct(ch) {
  switch (ch) {
    case 33:
    case 34:
    case 35:
    case 36:
    case 37:
    case 38:
    case 39:
    case 40:
    case 41:
    case 42:
    case 43:
    case 44:
    case 45:
    case 46:
    case 47:
    case 58:
    case 59:
    case 60:
    case 61:
    case 62:
    case 63:
    case 64:
    case 91:
    case 92:
    case 93:
    case 94:
    case 95:
    case 96:
    case 123:
    case 124:
    case 125:
    case 126:
      return true;
    default:
      return false;
  }
}
function normalizeReference(str) {
  str = str.trim().replace(/\s+/g, " ");
  if ("ẞ".toLowerCase() === "Ṿ") {
    str = str.replace(/ẞ/g, "ß");
  }
  return str.toLowerCase().toUpperCase();
}
const lib = { mdurl, ucmicro };
const utils = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  arrayReplaceAt,
  assign: assign$1,
  escapeHtml,
  escapeRE: escapeRE$1,
  fromCodePoint,
  has,
  isMdAsciiPunct,
  isPunctChar,
  isSpace,
  isString: isString$1,
  isValidEntityCode,
  isWhiteSpace,
  lib,
  normalizeReference,
  unescapeAll,
  unescapeMd
}, Symbol.toStringTag, { value: "Module" }));
function parseLinkLabel(state, start2, disableNested) {
  let level, found, marker, prevPos;
  const max2 = state.posMax;
  const oldPos = state.pos;
  state.pos = start2 + 1;
  level = 1;
  while (state.pos < max2) {
    marker = state.src.charCodeAt(state.pos);
    if (marker === 93) {
      level--;
      if (level === 0) {
        found = true;
        break;
      }
    }
    prevPos = state.pos;
    state.md.inline.skipToken(state);
    if (marker === 91) {
      if (prevPos === state.pos - 1) {
        level++;
      } else if (disableNested) {
        state.pos = oldPos;
        return -1;
      }
    }
  }
  let labelEnd = -1;
  if (found) {
    labelEnd = state.pos;
  }
  state.pos = oldPos;
  return labelEnd;
}
function parseLinkDestination(str, start2, max2) {
  let code2;
  let pos2 = start2;
  const result2 = {
    ok: false,
    pos: 0,
    str: ""
  };
  if (str.charCodeAt(pos2) === 60) {
    pos2++;
    while (pos2 < max2) {
      code2 = str.charCodeAt(pos2);
      if (code2 === 10) {
        return result2;
      }
      if (code2 === 60) {
        return result2;
      }
      if (code2 === 62) {
        result2.pos = pos2 + 1;
        result2.str = unescapeAll(str.slice(start2 + 1, pos2));
        result2.ok = true;
        return result2;
      }
      if (code2 === 92 && pos2 + 1 < max2) {
        pos2 += 2;
        continue;
      }
      pos2++;
    }
    return result2;
  }
  let level = 0;
  while (pos2 < max2) {
    code2 = str.charCodeAt(pos2);
    if (code2 === 32) {
      break;
    }
    if (code2 < 32 || code2 === 127) {
      break;
    }
    if (code2 === 92 && pos2 + 1 < max2) {
      if (str.charCodeAt(pos2 + 1) === 32) {
        break;
      }
      pos2 += 2;
      continue;
    }
    if (code2 === 40) {
      level++;
      if (level > 32) {
        return result2;
      }
    }
    if (code2 === 41) {
      if (level === 0) {
        break;
      }
      level--;
    }
    pos2++;
  }
  if (start2 === pos2) {
    return result2;
  }
  if (level !== 0) {
    return result2;
  }
  result2.str = unescapeAll(str.slice(start2, pos2));
  result2.pos = pos2;
  result2.ok = true;
  return result2;
}
function parseLinkTitle(str, start2, max2, prev_state) {
  let code2;
  let pos2 = start2;
  const state = {
    // if `true`, this is a valid link title
    ok: false,
    // if `true`, this link can be continued on the next line
    can_continue: false,
    // if `ok`, it's the position of the first character after the closing marker
    pos: 0,
    // if `ok`, it's the unescaped title
    str: "",
    // expected closing marker character code
    marker: 0
  };
  if (prev_state) {
    state.str = prev_state.str;
    state.marker = prev_state.marker;
  } else {
    if (pos2 >= max2) {
      return state;
    }
    let marker = str.charCodeAt(pos2);
    if (marker !== 34 && marker !== 39 && marker !== 40) {
      return state;
    }
    start2++;
    pos2++;
    if (marker === 40) {
      marker = 41;
    }
    state.marker = marker;
  }
  while (pos2 < max2) {
    code2 = str.charCodeAt(pos2);
    if (code2 === state.marker) {
      state.pos = pos2 + 1;
      state.str += unescapeAll(str.slice(start2, pos2));
      state.ok = true;
      return state;
    } else if (code2 === 40 && state.marker === 41) {
      return state;
    } else if (code2 === 92 && pos2 + 1 < max2) {
      pos2++;
    }
    pos2++;
  }
  state.can_continue = true;
  state.str += unescapeAll(str.slice(start2, pos2));
  return state;
}
const helpers = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  parseLinkDestination,
  parseLinkLabel,
  parseLinkTitle
}, Symbol.toStringTag, { value: "Module" }));
const default_rules = {};
default_rules.code_inline = function(tokens, idx, options, env, slf) {
  const token2 = tokens[idx];
  return "<code" + slf.renderAttrs(token2) + ">" + escapeHtml(token2.content) + "</code>";
};
default_rules.code_block = function(tokens, idx, options, env, slf) {
  const token2 = tokens[idx];
  return "<pre" + slf.renderAttrs(token2) + "><code>" + escapeHtml(tokens[idx].content) + "</code></pre>\n";
};
default_rules.fence = function(tokens, idx, options, env, slf) {
  const token2 = tokens[idx];
  const info = token2.info ? unescapeAll(token2.info).trim() : "";
  let langName = "";
  let langAttrs = "";
  if (info) {
    const arr = info.split(/(\s+)/g);
    langName = arr[0];
    langAttrs = arr.slice(2).join("");
  }
  let highlighted;
  if (options.highlight) {
    highlighted = options.highlight(token2.content, langName, langAttrs) || escapeHtml(token2.content);
  } else {
    highlighted = escapeHtml(token2.content);
  }
  if (highlighted.indexOf("<pre") === 0) {
    return highlighted + "\n";
  }
  if (info) {
    const i2 = token2.attrIndex("class");
    const tmpAttrs = token2.attrs ? token2.attrs.slice() : [];
    if (i2 < 0) {
      tmpAttrs.push(["class", options.langPrefix + langName]);
    } else {
      tmpAttrs[i2] = tmpAttrs[i2].slice();
      tmpAttrs[i2][1] += " " + options.langPrefix + langName;
    }
    const tmpToken = {
      attrs: tmpAttrs
    };
    return `<pre><code${slf.renderAttrs(tmpToken)}>${highlighted}</code></pre>
`;
  }
  return `<pre><code${slf.renderAttrs(token2)}>${highlighted}</code></pre>
`;
};
default_rules.image = function(tokens, idx, options, env, slf) {
  const token2 = tokens[idx];
  token2.attrs[token2.attrIndex("alt")][1] = slf.renderInlineAsText(token2.children, options, env);
  return slf.renderToken(tokens, idx, options);
};
default_rules.hardbreak = function(tokens, idx, options) {
  return options.xhtmlOut ? "<br />\n" : "<br>\n";
};
default_rules.softbreak = function(tokens, idx, options) {
  return options.breaks ? options.xhtmlOut ? "<br />\n" : "<br>\n" : "\n";
};
default_rules.text = function(tokens, idx) {
  return escapeHtml(tokens[idx].content);
};
default_rules.html_block = function(tokens, idx) {
  return tokens[idx].content;
};
default_rules.html_inline = function(tokens, idx) {
  return tokens[idx].content;
};
function Renderer() {
  this.rules = assign$1({}, default_rules);
}
Renderer.prototype.renderAttrs = function renderAttrs(token2) {
  let i2, l2, result2;
  if (!token2.attrs) {
    return "";
  }
  result2 = "";
  for (i2 = 0, l2 = token2.attrs.length; i2 < l2; i2++) {
    result2 += " " + escapeHtml(token2.attrs[i2][0]) + '="' + escapeHtml(token2.attrs[i2][1]) + '"';
  }
  return result2;
};
Renderer.prototype.renderToken = function renderToken(tokens, idx, options) {
  const token2 = tokens[idx];
  let result2 = "";
  if (token2.hidden) {
    return "";
  }
  if (token2.block && token2.nesting !== -1 && idx && tokens[idx - 1].hidden) {
    result2 += "\n";
  }
  result2 += (token2.nesting === -1 ? "</" : "<") + token2.tag;
  result2 += this.renderAttrs(token2);
  if (token2.nesting === 0 && options.xhtmlOut) {
    result2 += " /";
  }
  let needLf = false;
  if (token2.block) {
    needLf = true;
    if (token2.nesting === 1) {
      if (idx + 1 < tokens.length) {
        const nextToken = tokens[idx + 1];
        if (nextToken.type === "inline" || nextToken.hidden) {
          needLf = false;
        } else if (nextToken.nesting === -1 && nextToken.tag === token2.tag) {
          needLf = false;
        }
      }
    }
  }
  result2 += needLf ? ">\n" : ">";
  return result2;
};
Renderer.prototype.renderInline = function(tokens, options, env) {
  let result2 = "";
  const rules = this.rules;
  for (let i2 = 0, len = tokens.length; i2 < len; i2++) {
    const type = tokens[i2].type;
    if (typeof rules[type] !== "undefined") {
      result2 += rules[type](tokens, i2, options, env, this);
    } else {
      result2 += this.renderToken(tokens, i2, options);
    }
  }
  return result2;
};
Renderer.prototype.renderInlineAsText = function(tokens, options, env) {
  let result2 = "";
  for (let i2 = 0, len = tokens.length; i2 < len; i2++) {
    switch (tokens[i2].type) {
      case "text":
        result2 += tokens[i2].content;
        break;
      case "image":
        result2 += this.renderInlineAsText(tokens[i2].children, options, env);
        break;
      case "html_inline":
      case "html_block":
        result2 += tokens[i2].content;
        break;
      case "softbreak":
      case "hardbreak":
        result2 += "\n";
        break;
    }
  }
  return result2;
};
Renderer.prototype.render = function(tokens, options, env) {
  let result2 = "";
  const rules = this.rules;
  for (let i2 = 0, len = tokens.length; i2 < len; i2++) {
    const type = tokens[i2].type;
    if (type === "inline") {
      result2 += this.renderInline(tokens[i2].children, options, env);
    } else if (typeof rules[type] !== "undefined") {
      result2 += rules[type](tokens, i2, options, env, this);
    } else {
      result2 += this.renderToken(tokens, i2, options, env);
    }
  }
  return result2;
};
function Ruler() {
  this.__rules__ = [];
  this.__cache__ = null;
}
Ruler.prototype.__find__ = function(name2) {
  for (let i2 = 0; i2 < this.__rules__.length; i2++) {
    if (this.__rules__[i2].name === name2) {
      return i2;
    }
  }
  return -1;
};
Ruler.prototype.__compile__ = function() {
  const self2 = this;
  const chains = [""];
  self2.__rules__.forEach(function(rule) {
    if (!rule.enabled) {
      return;
    }
    rule.alt.forEach(function(altName) {
      if (chains.indexOf(altName) < 0) {
        chains.push(altName);
      }
    });
  });
  self2.__cache__ = {};
  chains.forEach(function(chain) {
    self2.__cache__[chain] = [];
    self2.__rules__.forEach(function(rule) {
      if (!rule.enabled) {
        return;
      }
      if (chain && rule.alt.indexOf(chain) < 0) {
        return;
      }
      self2.__cache__[chain].push(rule.fn);
    });
  });
};
Ruler.prototype.at = function(name2, fn3, options) {
  const index = this.__find__(name2);
  const opt2 = options || {};
  if (index === -1) {
    throw new Error("Parser rule not found: " + name2);
  }
  this.__rules__[index].fn = fn3;
  this.__rules__[index].alt = opt2.alt || [];
  this.__cache__ = null;
};
Ruler.prototype.before = function(beforeName, ruleName, fn3, options) {
  const index = this.__find__(beforeName);
  const opt2 = options || {};
  if (index === -1) {
    throw new Error("Parser rule not found: " + beforeName);
  }
  this.__rules__.splice(index, 0, {
    name: ruleName,
    enabled: true,
    fn: fn3,
    alt: opt2.alt || []
  });
  this.__cache__ = null;
};
Ruler.prototype.after = function(afterName, ruleName, fn3, options) {
  const index = this.__find__(afterName);
  const opt2 = options || {};
  if (index === -1) {
    throw new Error("Parser rule not found: " + afterName);
  }
  this.__rules__.splice(index + 1, 0, {
    name: ruleName,
    enabled: true,
    fn: fn3,
    alt: opt2.alt || []
  });
  this.__cache__ = null;
};
Ruler.prototype.push = function(ruleName, fn3, options) {
  const opt2 = options || {};
  this.__rules__.push({
    name: ruleName,
    enabled: true,
    fn: fn3,
    alt: opt2.alt || []
  });
  this.__cache__ = null;
};
Ruler.prototype.enable = function(list2, ignoreInvalid) {
  if (!Array.isArray(list2)) {
    list2 = [list2];
  }
  const result2 = [];
  list2.forEach(function(name2) {
    const idx = this.__find__(name2);
    if (idx < 0) {
      if (ignoreInvalid) {
        return;
      }
      throw new Error("Rules manager: invalid rule name " + name2);
    }
    this.__rules__[idx].enabled = true;
    result2.push(name2);
  }, this);
  this.__cache__ = null;
  return result2;
};
Ruler.prototype.enableOnly = function(list2, ignoreInvalid) {
  if (!Array.isArray(list2)) {
    list2 = [list2];
  }
  this.__rules__.forEach(function(rule) {
    rule.enabled = false;
  });
  this.enable(list2, ignoreInvalid);
};
Ruler.prototype.disable = function(list2, ignoreInvalid) {
  if (!Array.isArray(list2)) {
    list2 = [list2];
  }
  const result2 = [];
  list2.forEach(function(name2) {
    const idx = this.__find__(name2);
    if (idx < 0) {
      if (ignoreInvalid) {
        return;
      }
      throw new Error("Rules manager: invalid rule name " + name2);
    }
    this.__rules__[idx].enabled = false;
    result2.push(name2);
  }, this);
  this.__cache__ = null;
  return result2;
};
Ruler.prototype.getRules = function(chainName) {
  if (this.__cache__ === null) {
    this.__compile__();
  }
  return this.__cache__[chainName] || [];
};
function Token2(type, tag, nesting) {
  this.type = type;
  this.tag = tag;
  this.attrs = null;
  this.map = null;
  this.nesting = nesting;
  this.level = 0;
  this.children = null;
  this.content = "";
  this.markup = "";
  this.info = "";
  this.meta = null;
  this.block = false;
  this.hidden = false;
}
Token2.prototype.attrIndex = function attrIndex(name2) {
  if (!this.attrs) {
    return -1;
  }
  const attrs = this.attrs;
  for (let i2 = 0, len = attrs.length; i2 < len; i2++) {
    if (attrs[i2][0] === name2) {
      return i2;
    }
  }
  return -1;
};
Token2.prototype.attrPush = function attrPush(attrData) {
  if (this.attrs) {
    this.attrs.push(attrData);
  } else {
    this.attrs = [attrData];
  }
};
Token2.prototype.attrSet = function attrSet(name2, value2) {
  const idx = this.attrIndex(name2);
  const attrData = [name2, value2];
  if (idx < 0) {
    this.attrPush(attrData);
  } else {
    this.attrs[idx] = attrData;
  }
};
Token2.prototype.attrGet = function attrGet(name2) {
  const idx = this.attrIndex(name2);
  let value2 = null;
  if (idx >= 0) {
    value2 = this.attrs[idx][1];
  }
  return value2;
};
Token2.prototype.attrJoin = function attrJoin(name2, value2) {
  const idx = this.attrIndex(name2);
  if (idx < 0) {
    this.attrPush([name2, value2]);
  } else {
    this.attrs[idx][1] = this.attrs[idx][1] + " " + value2;
  }
};
function StateCore(src, md, env) {
  this.src = src;
  this.env = env;
  this.tokens = [];
  this.inlineMode = false;
  this.md = md;
}
StateCore.prototype.Token = Token2;
const NEWLINES_RE = /\r\n?|\n/g;
const NULL_RE = /\0/g;
function normalize(state) {
  let str;
  str = state.src.replace(NEWLINES_RE, "\n");
  str = str.replace(NULL_RE, "�");
  state.src = str;
}
function block(state) {
  let token2;
  if (state.inlineMode) {
    token2 = new state.Token("inline", "", 0);
    token2.content = state.src;
    token2.map = [0, 1];
    token2.children = [];
    state.tokens.push(token2);
  } else {
    state.md.block.parse(state.src, state.md, state.env, state.tokens);
  }
}
function inline$1(state) {
  const tokens = state.tokens;
  for (let i2 = 0, l2 = tokens.length; i2 < l2; i2++) {
    const tok = tokens[i2];
    if (tok.type === "inline") {
      state.md.inline.parse(tok.content, state.md, state.env, tok.children);
    }
  }
}
function isLinkOpen$1(str) {
  return /^<a[>\s]/i.test(str);
}
function isLinkClose$1(str) {
  return /^<\/a\s*>/i.test(str);
}
function linkify$1(state) {
  const blockTokens = state.tokens;
  if (!state.md.options.linkify) {
    return;
  }
  for (let j2 = 0, l2 = blockTokens.length; j2 < l2; j2++) {
    if (blockTokens[j2].type !== "inline" || !state.md.linkify.pretest(blockTokens[j2].content)) {
      continue;
    }
    let tokens = blockTokens[j2].children;
    let htmlLinkLevel = 0;
    for (let i2 = tokens.length - 1; i2 >= 0; i2--) {
      const currentToken = tokens[i2];
      if (currentToken.type === "link_close") {
        i2--;
        while (tokens[i2].level !== currentToken.level && tokens[i2].type !== "link_open") {
          i2--;
        }
        continue;
      }
      if (currentToken.type === "html_inline") {
        if (isLinkOpen$1(currentToken.content) && htmlLinkLevel > 0) {
          htmlLinkLevel--;
        }
        if (isLinkClose$1(currentToken.content)) {
          htmlLinkLevel++;
        }
      }
      if (htmlLinkLevel > 0) {
        continue;
      }
      if (currentToken.type === "text" && state.md.linkify.test(currentToken.content)) {
        const text2 = currentToken.content;
        let links2 = state.md.linkify.match(text2);
        const nodes = [];
        let level = currentToken.level;
        let lastPos = 0;
        if (links2.length > 0 && links2[0].index === 0 && i2 > 0 && tokens[i2 - 1].type === "text_special") {
          links2 = links2.slice(1);
        }
        for (let ln = 0; ln < links2.length; ln++) {
          const url = links2[ln].url;
          const fullUrl = state.md.normalizeLink(url);
          if (!state.md.validateLink(fullUrl)) {
            continue;
          }
          let urlText = links2[ln].text;
          if (!links2[ln].schema) {
            urlText = state.md.normalizeLinkText("http://" + urlText).replace(/^http:\/\//, "");
          } else if (links2[ln].schema === "mailto:" && !/^mailto:/i.test(urlText)) {
            urlText = state.md.normalizeLinkText("mailto:" + urlText).replace(/^mailto:/, "");
          } else {
            urlText = state.md.normalizeLinkText(urlText);
          }
          const pos2 = links2[ln].index;
          if (pos2 > lastPos) {
            const token2 = new state.Token("text", "", 0);
            token2.content = text2.slice(lastPos, pos2);
            token2.level = level;
            nodes.push(token2);
          }
          const token_o = new state.Token("link_open", "a", 1);
          token_o.attrs = [["href", fullUrl]];
          token_o.level = level++;
          token_o.markup = "linkify";
          token_o.info = "auto";
          nodes.push(token_o);
          const token_t = new state.Token("text", "", 0);
          token_t.content = urlText;
          token_t.level = level;
          nodes.push(token_t);
          const token_c = new state.Token("link_close", "a", -1);
          token_c.level = --level;
          token_c.markup = "linkify";
          token_c.info = "auto";
          nodes.push(token_c);
          lastPos = links2[ln].lastIndex;
        }
        if (lastPos < text2.length) {
          const token2 = new state.Token("text", "", 0);
          token2.content = text2.slice(lastPos);
          token2.level = level;
          nodes.push(token2);
        }
        blockTokens[j2].children = tokens = arrayReplaceAt(tokens, i2, nodes);
      }
    }
  }
}
const RARE_RE = /\+-|\.\.|\?\?\?\?|!!!!|,,|--/;
const SCOPED_ABBR_TEST_RE = /\((c|tm|r)\)/i;
const SCOPED_ABBR_RE = /\((c|tm|r)\)/ig;
const SCOPED_ABBR = {
  c: "©",
  r: "®",
  tm: "™"
};
function replaceFn(match3, name2) {
  return SCOPED_ABBR[name2.toLowerCase()];
}
function replace_scoped(inlineTokens) {
  let inside_autolink = 0;
  for (let i2 = inlineTokens.length - 1; i2 >= 0; i2--) {
    const token2 = inlineTokens[i2];
    if (token2.type === "text" && !inside_autolink) {
      token2.content = token2.content.replace(SCOPED_ABBR_RE, replaceFn);
    }
    if (token2.type === "link_open" && token2.info === "auto") {
      inside_autolink--;
    }
    if (token2.type === "link_close" && token2.info === "auto") {
      inside_autolink++;
    }
  }
}
function replace_rare(inlineTokens) {
  let inside_autolink = 0;
  for (let i2 = inlineTokens.length - 1; i2 >= 0; i2--) {
    const token2 = inlineTokens[i2];
    if (token2.type === "text" && !inside_autolink) {
      if (RARE_RE.test(token2.content)) {
        token2.content = token2.content.replace(/\+-/g, "±").replace(/\.{2,}/g, "…").replace(/([?!])…/g, "$1..").replace(/([?!]){4,}/g, "$1$1$1").replace(/,{2,}/g, ",").replace(/(^|[^-])---(?=[^-]|$)/mg, "$1—").replace(/(^|\s)--(?=\s|$)/mg, "$1–").replace(/(^|[^-\s])--(?=[^-\s]|$)/mg, "$1–");
      }
    }
    if (token2.type === "link_open" && token2.info === "auto") {
      inside_autolink--;
    }
    if (token2.type === "link_close" && token2.info === "auto") {
      inside_autolink++;
    }
  }
}
function replace(state) {
  let blkIdx;
  if (!state.md.options.typographer) {
    return;
  }
  for (blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) {
    if (state.tokens[blkIdx].type !== "inline") {
      continue;
    }
    if (SCOPED_ABBR_TEST_RE.test(state.tokens[blkIdx].content)) {
      replace_scoped(state.tokens[blkIdx].children);
    }
    if (RARE_RE.test(state.tokens[blkIdx].content)) {
      replace_rare(state.tokens[blkIdx].children);
    }
  }
}
const QUOTE_TEST_RE = /['"]/;
const QUOTE_RE = /['"]/g;
const APOSTROPHE = "’";
function replaceAt(str, index, ch) {
  return str.slice(0, index) + ch + str.slice(index + 1);
}
function process_inlines(tokens, state) {
  let j2;
  const stack2 = [];
  for (let i2 = 0; i2 < tokens.length; i2++) {
    const token2 = tokens[i2];
    const thisLevel = tokens[i2].level;
    for (j2 = stack2.length - 1; j2 >= 0; j2--) {
      if (stack2[j2].level <= thisLevel) {
        break;
      }
    }
    stack2.length = j2 + 1;
    if (token2.type !== "text") {
      continue;
    }
    let text2 = token2.content;
    let pos2 = 0;
    let max2 = text2.length;
    OUTER:
      while (pos2 < max2) {
        QUOTE_RE.lastIndex = pos2;
        const t2 = QUOTE_RE.exec(text2);
        if (!t2) {
          break;
        }
        let canOpen = true;
        let canClose = true;
        pos2 = t2.index + 1;
        const isSingle = t2[0] === "'";
        let lastChar = 32;
        if (t2.index - 1 >= 0) {
          lastChar = text2.charCodeAt(t2.index - 1);
        } else {
          for (j2 = i2 - 1; j2 >= 0; j2--) {
            if (tokens[j2].type === "softbreak" || tokens[j2].type === "hardbreak") break;
            if (!tokens[j2].content) continue;
            lastChar = tokens[j2].content.charCodeAt(tokens[j2].content.length - 1);
            break;
          }
        }
        let nextChar = 32;
        if (pos2 < max2) {
          nextChar = text2.charCodeAt(pos2);
        } else {
          for (j2 = i2 + 1; j2 < tokens.length; j2++) {
            if (tokens[j2].type === "softbreak" || tokens[j2].type === "hardbreak") break;
            if (!tokens[j2].content) continue;
            nextChar = tokens[j2].content.charCodeAt(0);
            break;
          }
        }
        const isLastPunctChar = isMdAsciiPunct(lastChar) || isPunctChar(String.fromCharCode(lastChar));
        const isNextPunctChar = isMdAsciiPunct(nextChar) || isPunctChar(String.fromCharCode(nextChar));
        const isLastWhiteSpace = isWhiteSpace(lastChar);
        const isNextWhiteSpace = isWhiteSpace(nextChar);
        if (isNextWhiteSpace) {
          canOpen = false;
        } else if (isNextPunctChar) {
          if (!(isLastWhiteSpace || isLastPunctChar)) {
            canOpen = false;
          }
        }
        if (isLastWhiteSpace) {
          canClose = false;
        } else if (isLastPunctChar) {
          if (!(isNextWhiteSpace || isNextPunctChar)) {
            canClose = false;
          }
        }
        if (nextChar === 34 && t2[0] === '"') {
          if (lastChar >= 48 && lastChar <= 57) {
            canClose = canOpen = false;
          }
        }
        if (canOpen && canClose) {
          canOpen = isLastPunctChar;
          canClose = isNextPunctChar;
        }
        if (!canOpen && !canClose) {
          if (isSingle) {
            token2.content = replaceAt(token2.content, t2.index, APOSTROPHE);
          }
          continue;
        }
        if (canClose) {
          for (j2 = stack2.length - 1; j2 >= 0; j2--) {
            let item2 = stack2[j2];
            if (stack2[j2].level < thisLevel) {
              break;
            }
            if (item2.single === isSingle && stack2[j2].level === thisLevel) {
              item2 = stack2[j2];
              let openQuote;
              let closeQuote;
              if (isSingle) {
                openQuote = state.md.options.quotes[2];
                closeQuote = state.md.options.quotes[3];
              } else {
                openQuote = state.md.options.quotes[0];
                closeQuote = state.md.options.quotes[1];
              }
              token2.content = replaceAt(token2.content, t2.index, closeQuote);
              tokens[item2.token].content = replaceAt(
                tokens[item2.token].content,
                item2.pos,
                openQuote
              );
              pos2 += closeQuote.length - 1;
              if (item2.token === i2) {
                pos2 += openQuote.length - 1;
              }
              text2 = token2.content;
              max2 = text2.length;
              stack2.length = j2;
              continue OUTER;
            }
          }
        }
        if (canOpen) {
          stack2.push({
            token: i2,
            pos: t2.index,
            single: isSingle,
            level: thisLevel
          });
        } else if (canClose && isSingle) {
          token2.content = replaceAt(token2.content, t2.index, APOSTROPHE);
        }
      }
  }
}
function smartquotes(state) {
  if (!state.md.options.typographer) {
    return;
  }
  for (let blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) {
    if (state.tokens[blkIdx].type !== "inline" || !QUOTE_TEST_RE.test(state.tokens[blkIdx].content)) {
      continue;
    }
    process_inlines(state.tokens[blkIdx].children, state);
  }
}
function text_join(state) {
  let curr, last2;
  const blockTokens = state.tokens;
  const l2 = blockTokens.length;
  for (let j2 = 0; j2 < l2; j2++) {
    if (blockTokens[j2].type !== "inline") continue;
    const tokens = blockTokens[j2].children;
    const max2 = tokens.length;
    for (curr = 0; curr < max2; curr++) {
      if (tokens[curr].type === "text_special") {
        tokens[curr].type = "text";
      }
    }
    for (curr = last2 = 0; curr < max2; curr++) {
      if (tokens[curr].type === "text" && curr + 1 < max2 && tokens[curr + 1].type === "text") {
        tokens[curr + 1].content = tokens[curr].content + tokens[curr + 1].content;
      } else {
        if (curr !== last2) {
          tokens[last2] = tokens[curr];
        }
        last2++;
      }
    }
    if (curr !== last2) {
      tokens.length = last2;
    }
  }
}
const _rules$2 = [
  ["normalize", normalize],
  ["block", block],
  ["inline", inline$1],
  ["linkify", linkify$1],
  ["replacements", replace],
  ["smartquotes", smartquotes],
  // `text_join` finds `text_special` tokens (for escape sequences)
  // and joins them with the rest of the text
  ["text_join", text_join]
];
function Core$1() {
  this.ruler = new Ruler();
  for (let i2 = 0; i2 < _rules$2.length; i2++) {
    this.ruler.push(_rules$2[i2][0], _rules$2[i2][1]);
  }
}
Core$1.prototype.process = function(state) {
  const rules = this.ruler.getRules("");
  for (let i2 = 0, l2 = rules.length; i2 < l2; i2++) {
    rules[i2](state);
  }
};
Core$1.prototype.State = StateCore;
function StateBlock(src, md, env, tokens) {
  this.src = src;
  this.md = md;
  this.env = env;
  this.tokens = tokens;
  this.bMarks = [];
  this.eMarks = [];
  this.tShift = [];
  this.sCount = [];
  this.bsCount = [];
  this.blkIndent = 0;
  this.line = 0;
  this.lineMax = 0;
  this.tight = false;
  this.ddIndent = -1;
  this.listIndent = -1;
  this.parentType = "root";
  this.level = 0;
  const s = this.src;
  for (let start2 = 0, pos2 = 0, indent = 0, offset3 = 0, len = s.length, indent_found = false; pos2 < len; pos2++) {
    const ch = s.charCodeAt(pos2);
    if (!indent_found) {
      if (isSpace(ch)) {
        indent++;
        if (ch === 9) {
          offset3 += 4 - offset3 % 4;
        } else {
          offset3++;
        }
        continue;
      } else {
        indent_found = true;
      }
    }
    if (ch === 10 || pos2 === len - 1) {
      if (ch !== 10) {
        pos2++;
      }
      this.bMarks.push(start2);
      this.eMarks.push(pos2);
      this.tShift.push(indent);
      this.sCount.push(offset3);
      this.bsCount.push(0);
      indent_found = false;
      indent = 0;
      offset3 = 0;
      start2 = pos2 + 1;
    }
  }
  this.bMarks.push(s.length);
  this.eMarks.push(s.length);
  this.tShift.push(0);
  this.sCount.push(0);
  this.bsCount.push(0);
  this.lineMax = this.bMarks.length - 1;
}
StateBlock.prototype.push = function(type, tag, nesting) {
  const token2 = new Token2(type, tag, nesting);
  token2.block = true;
  if (nesting < 0) this.level--;
  token2.level = this.level;
  if (nesting > 0) this.level++;
  this.tokens.push(token2);
  return token2;
};
StateBlock.prototype.isEmpty = function isEmpty(line2) {
  return this.bMarks[line2] + this.tShift[line2] >= this.eMarks[line2];
};
StateBlock.prototype.skipEmptyLines = function skipEmptyLines(from2) {
  for (let max2 = this.lineMax; from2 < max2; from2++) {
    if (this.bMarks[from2] + this.tShift[from2] < this.eMarks[from2]) {
      break;
    }
  }
  return from2;
};
StateBlock.prototype.skipSpaces = function skipSpaces(pos2) {
  for (let max2 = this.src.length; pos2 < max2; pos2++) {
    const ch = this.src.charCodeAt(pos2);
    if (!isSpace(ch)) {
      break;
    }
  }
  return pos2;
};
StateBlock.prototype.skipSpacesBack = function skipSpacesBack(pos2, min2) {
  if (pos2 <= min2) {
    return pos2;
  }
  while (pos2 > min2) {
    if (!isSpace(this.src.charCodeAt(--pos2))) {
      return pos2 + 1;
    }
  }
  return pos2;
};
StateBlock.prototype.skipChars = function skipChars(pos2, code2) {
  for (let max2 = this.src.length; pos2 < max2; pos2++) {
    if (this.src.charCodeAt(pos2) !== code2) {
      break;
    }
  }
  return pos2;
};
StateBlock.prototype.skipCharsBack = function skipCharsBack(pos2, code2, min2) {
  if (pos2 <= min2) {
    return pos2;
  }
  while (pos2 > min2) {
    if (code2 !== this.src.charCodeAt(--pos2)) {
      return pos2 + 1;
    }
  }
  return pos2;
};
StateBlock.prototype.getLines = function getLines(begin, end2, indent, keepLastLF) {
  if (begin >= end2) {
    return "";
  }
  const queue = new Array(end2 - begin);
  for (let i2 = 0, line2 = begin; line2 < end2; line2++, i2++) {
    let lineIndent = 0;
    const lineStart = this.bMarks[line2];
    let first2 = lineStart;
    let last2;
    if (line2 + 1 < end2 || keepLastLF) {
      last2 = this.eMarks[line2] + 1;
    } else {
      last2 = this.eMarks[line2];
    }
    while (first2 < last2 && lineIndent < indent) {
      const ch = this.src.charCodeAt(first2);
      if (isSpace(ch)) {
        if (ch === 9) {
          lineIndent += 4 - (lineIndent + this.bsCount[line2]) % 4;
        } else {
          lineIndent++;
        }
      } else if (first2 - lineStart < this.tShift[line2]) {
        lineIndent++;
      } else {
        break;
      }
      first2++;
    }
    if (lineIndent > indent) {
      queue[i2] = new Array(lineIndent - indent + 1).join(" ") + this.src.slice(first2, last2);
    } else {
      queue[i2] = this.src.slice(first2, last2);
    }
  }
  return queue.join("");
};
StateBlock.prototype.Token = Token2;
const MAX_AUTOCOMPLETED_CELLS = 65536;
function getLine(state, line2) {
  const pos2 = state.bMarks[line2] + state.tShift[line2];
  const max2 = state.eMarks[line2];
  return state.src.slice(pos2, max2);
}
function escapedSplit(str) {
  const result2 = [];
  const max2 = str.length;
  let pos2 = 0;
  let ch = str.charCodeAt(pos2);
  let isEscaped = false;
  let lastPos = 0;
  let current3 = "";
  while (pos2 < max2) {
    if (ch === 124) {
      if (!isEscaped) {
        result2.push(current3 + str.substring(lastPos, pos2));
        current3 = "";
        lastPos = pos2 + 1;
      } else {
        current3 += str.substring(lastPos, pos2 - 1);
        lastPos = pos2;
      }
    }
    isEscaped = ch === 92;
    pos2++;
    ch = str.charCodeAt(pos2);
  }
  result2.push(current3 + str.substring(lastPos));
  return result2;
}
function table$1(state, startLine, endLine, silent) {
  if (startLine + 2 > endLine) {
    return false;
  }
  let nextLine = startLine + 1;
  if (state.sCount[nextLine] < state.blkIndent) {
    return false;
  }
  if (state.sCount[nextLine] - state.blkIndent >= 4) {
    return false;
  }
  let pos2 = state.bMarks[nextLine] + state.tShift[nextLine];
  if (pos2 >= state.eMarks[nextLine]) {
    return false;
  }
  const firstCh = state.src.charCodeAt(pos2++);
  if (firstCh !== 124 && firstCh !== 45 && firstCh !== 58) {
    return false;
  }
  if (pos2 >= state.eMarks[nextLine]) {
    return false;
  }
  const secondCh = state.src.charCodeAt(pos2++);
  if (secondCh !== 124 && secondCh !== 45 && secondCh !== 58 && !isSpace(secondCh)) {
    return false;
  }
  if (firstCh === 45 && isSpace(secondCh)) {
    return false;
  }
  while (pos2 < state.eMarks[nextLine]) {
    const ch = state.src.charCodeAt(pos2);
    if (ch !== 124 && ch !== 45 && ch !== 58 && !isSpace(ch)) {
      return false;
    }
    pos2++;
  }
  let lineText = getLine(state, startLine + 1);
  let columns2 = lineText.split("|");
  const aligns = [];
  for (let i2 = 0; i2 < columns2.length; i2++) {
    const t2 = columns2[i2].trim();
    if (!t2) {
      if (i2 === 0 || i2 === columns2.length - 1) {
        continue;
      } else {
        return false;
      }
    }
    if (!/^:?-+:?$/.test(t2)) {
      return false;
    }
    if (t2.charCodeAt(t2.length - 1) === 58) {
      aligns.push(t2.charCodeAt(0) === 58 ? "center" : "right");
    } else if (t2.charCodeAt(0) === 58) {
      aligns.push("left");
    } else {
      aligns.push("");
    }
  }
  lineText = getLine(state, startLine).trim();
  if (lineText.indexOf("|") === -1) {
    return false;
  }
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  columns2 = escapedSplit(lineText);
  if (columns2.length && columns2[0] === "") columns2.shift();
  if (columns2.length && columns2[columns2.length - 1] === "") columns2.pop();
  const columnCount = columns2.length;
  if (columnCount === 0 || columnCount !== aligns.length) {
    return false;
  }
  if (silent) {
    return true;
  }
  const oldParentType = state.parentType;
  state.parentType = "table";
  const terminatorRules = state.md.block.ruler.getRules("blockquote");
  const token_to = state.push("table_open", "table", 1);
  const tableLines = [startLine, 0];
  token_to.map = tableLines;
  const token_tho = state.push("thead_open", "thead", 1);
  token_tho.map = [startLine, startLine + 1];
  const token_htro = state.push("tr_open", "tr", 1);
  token_htro.map = [startLine, startLine + 1];
  for (let i2 = 0; i2 < columns2.length; i2++) {
    const token_ho = state.push("th_open", "th", 1);
    if (aligns[i2]) {
      token_ho.attrs = [["style", "text-align:" + aligns[i2]]];
    }
    const token_il = state.push("inline", "", 0);
    token_il.content = columns2[i2].trim();
    token_il.children = [];
    state.push("th_close", "th", -1);
  }
  state.push("tr_close", "tr", -1);
  state.push("thead_close", "thead", -1);
  let tbodyLines;
  let autocompletedCells = 0;
  for (nextLine = startLine + 2; nextLine < endLine; nextLine++) {
    if (state.sCount[nextLine] < state.blkIndent) {
      break;
    }
    let terminate = false;
    for (let i2 = 0, l2 = terminatorRules.length; i2 < l2; i2++) {
      if (terminatorRules[i2](state, nextLine, endLine, true)) {
        terminate = true;
        break;
      }
    }
    if (terminate) {
      break;
    }
    lineText = getLine(state, nextLine).trim();
    if (!lineText) {
      break;
    }
    if (state.sCount[nextLine] - state.blkIndent >= 4) {
      break;
    }
    columns2 = escapedSplit(lineText);
    if (columns2.length && columns2[0] === "") columns2.shift();
    if (columns2.length && columns2[columns2.length - 1] === "") columns2.pop();
    autocompletedCells += columnCount - columns2.length;
    if (autocompletedCells > MAX_AUTOCOMPLETED_CELLS) {
      break;
    }
    if (nextLine === startLine + 2) {
      const token_tbo = state.push("tbody_open", "tbody", 1);
      token_tbo.map = tbodyLines = [startLine + 2, 0];
    }
    const token_tro = state.push("tr_open", "tr", 1);
    token_tro.map = [nextLine, nextLine + 1];
    for (let i2 = 0; i2 < columnCount; i2++) {
      const token_tdo = state.push("td_open", "td", 1);
      if (aligns[i2]) {
        token_tdo.attrs = [["style", "text-align:" + aligns[i2]]];
      }
      const token_il = state.push("inline", "", 0);
      token_il.content = columns2[i2] ? columns2[i2].trim() : "";
      token_il.children = [];
      state.push("td_close", "td", -1);
    }
    state.push("tr_close", "tr", -1);
  }
  if (tbodyLines) {
    state.push("tbody_close", "tbody", -1);
    tbodyLines[1] = nextLine;
  }
  state.push("table_close", "table", -1);
  tableLines[1] = nextLine;
  state.parentType = oldParentType;
  state.line = nextLine;
  return true;
}
function code$3(state, startLine, endLine) {
  if (state.sCount[startLine] - state.blkIndent < 4) {
    return false;
  }
  let nextLine = startLine + 1;
  let last2 = nextLine;
  while (nextLine < endLine) {
    if (state.isEmpty(nextLine)) {
      nextLine++;
      continue;
    }
    if (state.sCount[nextLine] - state.blkIndent >= 4) {
      nextLine++;
      last2 = nextLine;
      continue;
    }
    break;
  }
  state.line = last2;
  const token2 = state.push("code_block", "code", 0);
  token2.content = state.getLines(startLine, last2, 4 + state.blkIndent, false) + "\n";
  token2.map = [startLine, state.line];
  return true;
}
function fence(state, startLine, endLine, silent) {
  let pos2 = state.bMarks[startLine] + state.tShift[startLine];
  let max2 = state.eMarks[startLine];
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  if (pos2 + 3 > max2) {
    return false;
  }
  const marker = state.src.charCodeAt(pos2);
  if (marker !== 126 && marker !== 96) {
    return false;
  }
  let mem = pos2;
  pos2 = state.skipChars(pos2, marker);
  let len = pos2 - mem;
  if (len < 3) {
    return false;
  }
  const markup = state.src.slice(mem, pos2);
  const params = state.src.slice(pos2, max2);
  if (marker === 96) {
    if (params.indexOf(String.fromCharCode(marker)) >= 0) {
      return false;
    }
  }
  if (silent) {
    return true;
  }
  let nextLine = startLine;
  let haveEndMarker = false;
  for (; ; ) {
    nextLine++;
    if (nextLine >= endLine) {
      break;
    }
    pos2 = mem = state.bMarks[nextLine] + state.tShift[nextLine];
    max2 = state.eMarks[nextLine];
    if (pos2 < max2 && state.sCount[nextLine] < state.blkIndent) {
      break;
    }
    if (state.src.charCodeAt(pos2) !== marker) {
      continue;
    }
    if (state.sCount[nextLine] - state.blkIndent >= 4) {
      continue;
    }
    pos2 = state.skipChars(pos2, marker);
    if (pos2 - mem < len) {
      continue;
    }
    pos2 = state.skipSpaces(pos2);
    if (pos2 < max2) {
      continue;
    }
    haveEndMarker = true;
    break;
  }
  len = state.sCount[startLine];
  state.line = nextLine + (haveEndMarker ? 1 : 0);
  const token2 = state.push("fence", "code", 0);
  token2.info = params;
  token2.content = state.getLines(startLine + 1, nextLine, len, true);
  token2.markup = markup;
  token2.map = [startLine, state.line];
  return true;
}
function blockquote(state, startLine, endLine, silent) {
  let pos2 = state.bMarks[startLine] + state.tShift[startLine];
  let max2 = state.eMarks[startLine];
  const oldLineMax = state.lineMax;
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  if (state.src.charCodeAt(pos2) !== 62) {
    return false;
  }
  if (silent) {
    return true;
  }
  const oldBMarks = [];
  const oldBSCount = [];
  const oldSCount = [];
  const oldTShift = [];
  const terminatorRules = state.md.block.ruler.getRules("blockquote");
  const oldParentType = state.parentType;
  state.parentType = "blockquote";
  let lastLineEmpty = false;
  let nextLine;
  for (nextLine = startLine; nextLine < endLine; nextLine++) {
    const isOutdented = state.sCount[nextLine] < state.blkIndent;
    pos2 = state.bMarks[nextLine] + state.tShift[nextLine];
    max2 = state.eMarks[nextLine];
    if (pos2 >= max2) {
      break;
    }
    if (state.src.charCodeAt(pos2++) === 62 && !isOutdented) {
      let initial = state.sCount[nextLine] + 1;
      let spaceAfterMarker;
      let adjustTab;
      if (state.src.charCodeAt(pos2) === 32) {
        pos2++;
        initial++;
        adjustTab = false;
        spaceAfterMarker = true;
      } else if (state.src.charCodeAt(pos2) === 9) {
        spaceAfterMarker = true;
        if ((state.bsCount[nextLine] + initial) % 4 === 3) {
          pos2++;
          initial++;
          adjustTab = false;
        } else {
          adjustTab = true;
        }
      } else {
        spaceAfterMarker = false;
      }
      let offset3 = initial;
      oldBMarks.push(state.bMarks[nextLine]);
      state.bMarks[nextLine] = pos2;
      while (pos2 < max2) {
        const ch = state.src.charCodeAt(pos2);
        if (isSpace(ch)) {
          if (ch === 9) {
            offset3 += 4 - (offset3 + state.bsCount[nextLine] + (adjustTab ? 1 : 0)) % 4;
          } else {
            offset3++;
          }
        } else {
          break;
        }
        pos2++;
      }
      lastLineEmpty = pos2 >= max2;
      oldBSCount.push(state.bsCount[nextLine]);
      state.bsCount[nextLine] = state.sCount[nextLine] + 1 + (spaceAfterMarker ? 1 : 0);
      oldSCount.push(state.sCount[nextLine]);
      state.sCount[nextLine] = offset3 - initial;
      oldTShift.push(state.tShift[nextLine]);
      state.tShift[nextLine] = pos2 - state.bMarks[nextLine];
      continue;
    }
    if (lastLineEmpty) {
      break;
    }
    let terminate = false;
    for (let i2 = 0, l2 = terminatorRules.length; i2 < l2; i2++) {
      if (terminatorRules[i2](state, nextLine, endLine, true)) {
        terminate = true;
        break;
      }
    }
    if (terminate) {
      state.lineMax = nextLine;
      if (state.blkIndent !== 0) {
        oldBMarks.push(state.bMarks[nextLine]);
        oldBSCount.push(state.bsCount[nextLine]);
        oldTShift.push(state.tShift[nextLine]);
        oldSCount.push(state.sCount[nextLine]);
        state.sCount[nextLine] -= state.blkIndent;
      }
      break;
    }
    oldBMarks.push(state.bMarks[nextLine]);
    oldBSCount.push(state.bsCount[nextLine]);
    oldTShift.push(state.tShift[nextLine]);
    oldSCount.push(state.sCount[nextLine]);
    state.sCount[nextLine] = -1;
  }
  const oldIndent = state.blkIndent;
  state.blkIndent = 0;
  const token_o = state.push("blockquote_open", "blockquote", 1);
  token_o.markup = ">";
  const lines = [startLine, 0];
  token_o.map = lines;
  state.md.block.tokenize(state, startLine, nextLine);
  const token_c = state.push("blockquote_close", "blockquote", -1);
  token_c.markup = ">";
  state.lineMax = oldLineMax;
  state.parentType = oldParentType;
  lines[1] = state.line;
  for (let i2 = 0; i2 < oldTShift.length; i2++) {
    state.bMarks[i2 + startLine] = oldBMarks[i2];
    state.tShift[i2 + startLine] = oldTShift[i2];
    state.sCount[i2 + startLine] = oldSCount[i2];
    state.bsCount[i2 + startLine] = oldBSCount[i2];
  }
  state.blkIndent = oldIndent;
  return true;
}
function hr(state, startLine, endLine, silent) {
  const max2 = state.eMarks[startLine];
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  let pos2 = state.bMarks[startLine] + state.tShift[startLine];
  const marker = state.src.charCodeAt(pos2++);
  if (marker !== 42 && marker !== 45 && marker !== 95) {
    return false;
  }
  let cnt = 1;
  while (pos2 < max2) {
    const ch = state.src.charCodeAt(pos2++);
    if (ch !== marker && !isSpace(ch)) {
      return false;
    }
    if (ch === marker) {
      cnt++;
    }
  }
  if (cnt < 3) {
    return false;
  }
  if (silent) {
    return true;
  }
  state.line = startLine + 1;
  const token2 = state.push("hr", "hr", 0);
  token2.map = [startLine, state.line];
  token2.markup = Array(cnt + 1).join(String.fromCharCode(marker));
  return true;
}
function skipBulletListMarker(state, startLine) {
  const max2 = state.eMarks[startLine];
  let pos2 = state.bMarks[startLine] + state.tShift[startLine];
  const marker = state.src.charCodeAt(pos2++);
  if (marker !== 42 && marker !== 45 && marker !== 43) {
    return -1;
  }
  if (pos2 < max2) {
    const ch = state.src.charCodeAt(pos2);
    if (!isSpace(ch)) {
      return -1;
    }
  }
  return pos2;
}
function skipOrderedListMarker(state, startLine) {
  const start2 = state.bMarks[startLine] + state.tShift[startLine];
  const max2 = state.eMarks[startLine];
  let pos2 = start2;
  if (pos2 + 1 >= max2) {
    return -1;
  }
  let ch = state.src.charCodeAt(pos2++);
  if (ch < 48 || ch > 57) {
    return -1;
  }
  for (; ; ) {
    if (pos2 >= max2) {
      return -1;
    }
    ch = state.src.charCodeAt(pos2++);
    if (ch >= 48 && ch <= 57) {
      if (pos2 - start2 >= 10) {
        return -1;
      }
      continue;
    }
    if (ch === 41 || ch === 46) {
      break;
    }
    return -1;
  }
  if (pos2 < max2) {
    ch = state.src.charCodeAt(pos2);
    if (!isSpace(ch)) {
      return -1;
    }
  }
  return pos2;
}
function markTightParagraphs(state, idx) {
  const level = state.level + 2;
  for (let i2 = idx + 2, l2 = state.tokens.length - 2; i2 < l2; i2++) {
    if (state.tokens[i2].level === level && state.tokens[i2].type === "paragraph_open") {
      state.tokens[i2 + 2].hidden = true;
      state.tokens[i2].hidden = true;
      i2 += 2;
    }
  }
}
function list(state, startLine, endLine, silent) {
  let max2, pos2, start2, token2;
  let nextLine = startLine;
  let tight = true;
  if (state.sCount[nextLine] - state.blkIndent >= 4) {
    return false;
  }
  if (state.listIndent >= 0 && state.sCount[nextLine] - state.listIndent >= 4 && state.sCount[nextLine] < state.blkIndent) {
    return false;
  }
  let isTerminatingParagraph = false;
  if (silent && state.parentType === "paragraph") {
    if (state.sCount[nextLine] >= state.blkIndent) {
      isTerminatingParagraph = true;
    }
  }
  let isOrdered;
  let markerValue;
  let posAfterMarker;
  if ((posAfterMarker = skipOrderedListMarker(state, nextLine)) >= 0) {
    isOrdered = true;
    start2 = state.bMarks[nextLine] + state.tShift[nextLine];
    markerValue = Number(state.src.slice(start2, posAfterMarker - 1));
    if (isTerminatingParagraph && markerValue !== 1) return false;
  } else if ((posAfterMarker = skipBulletListMarker(state, nextLine)) >= 0) {
    isOrdered = false;
  } else {
    return false;
  }
  if (isTerminatingParagraph) {
    if (state.skipSpaces(posAfterMarker) >= state.eMarks[nextLine]) return false;
  }
  if (silent) {
    return true;
  }
  const markerCharCode = state.src.charCodeAt(posAfterMarker - 1);
  const listTokIdx = state.tokens.length;
  if (isOrdered) {
    token2 = state.push("ordered_list_open", "ol", 1);
    if (markerValue !== 1) {
      token2.attrs = [["start", markerValue]];
    }
  } else {
    token2 = state.push("bullet_list_open", "ul", 1);
  }
  const listLines = [nextLine, 0];
  token2.map = listLines;
  token2.markup = String.fromCharCode(markerCharCode);
  let prevEmptyEnd = false;
  const terminatorRules = state.md.block.ruler.getRules("list");
  const oldParentType = state.parentType;
  state.parentType = "list";
  while (nextLine < endLine) {
    pos2 = posAfterMarker;
    max2 = state.eMarks[nextLine];
    const initial = state.sCount[nextLine] + posAfterMarker - (state.bMarks[nextLine] + state.tShift[nextLine]);
    let offset3 = initial;
    while (pos2 < max2) {
      const ch = state.src.charCodeAt(pos2);
      if (ch === 9) {
        offset3 += 4 - (offset3 + state.bsCount[nextLine]) % 4;
      } else if (ch === 32) {
        offset3++;
      } else {
        break;
      }
      pos2++;
    }
    const contentStart = pos2;
    let indentAfterMarker;
    if (contentStart >= max2) {
      indentAfterMarker = 1;
    } else {
      indentAfterMarker = offset3 - initial;
    }
    if (indentAfterMarker > 4) {
      indentAfterMarker = 1;
    }
    const indent = initial + indentAfterMarker;
    token2 = state.push("list_item_open", "li", 1);
    token2.markup = String.fromCharCode(markerCharCode);
    const itemLines = [nextLine, 0];
    token2.map = itemLines;
    if (isOrdered) {
      token2.info = state.src.slice(start2, posAfterMarker - 1);
    }
    const oldTight = state.tight;
    const oldTShift = state.tShift[nextLine];
    const oldSCount = state.sCount[nextLine];
    const oldListIndent = state.listIndent;
    state.listIndent = state.blkIndent;
    state.blkIndent = indent;
    state.tight = true;
    state.tShift[nextLine] = contentStart - state.bMarks[nextLine];
    state.sCount[nextLine] = offset3;
    if (contentStart >= max2 && state.isEmpty(nextLine + 1)) {
      state.line = Math.min(state.line + 2, endLine);
    } else {
      state.md.block.tokenize(state, nextLine, endLine, true);
    }
    if (!state.tight || prevEmptyEnd) {
      tight = false;
    }
    prevEmptyEnd = state.line - nextLine > 1 && state.isEmpty(state.line - 1);
    state.blkIndent = state.listIndent;
    state.listIndent = oldListIndent;
    state.tShift[nextLine] = oldTShift;
    state.sCount[nextLine] = oldSCount;
    state.tight = oldTight;
    token2 = state.push("list_item_close", "li", -1);
    token2.markup = String.fromCharCode(markerCharCode);
    nextLine = state.line;
    itemLines[1] = nextLine;
    if (nextLine >= endLine) {
      break;
    }
    if (state.sCount[nextLine] < state.blkIndent) {
      break;
    }
    if (state.sCount[nextLine] - state.blkIndent >= 4) {
      break;
    }
    let terminate = false;
    for (let i2 = 0, l2 = terminatorRules.length; i2 < l2; i2++) {
      if (terminatorRules[i2](state, nextLine, endLine, true)) {
        terminate = true;
        break;
      }
    }
    if (terminate) {
      break;
    }
    if (isOrdered) {
      posAfterMarker = skipOrderedListMarker(state, nextLine);
      if (posAfterMarker < 0) {
        break;
      }
      start2 = state.bMarks[nextLine] + state.tShift[nextLine];
    } else {
      posAfterMarker = skipBulletListMarker(state, nextLine);
      if (posAfterMarker < 0) {
        break;
      }
    }
    if (markerCharCode !== state.src.charCodeAt(posAfterMarker - 1)) {
      break;
    }
  }
  if (isOrdered) {
    token2 = state.push("ordered_list_close", "ol", -1);
  } else {
    token2 = state.push("bullet_list_close", "ul", -1);
  }
  token2.markup = String.fromCharCode(markerCharCode);
  listLines[1] = nextLine;
  state.line = nextLine;
  state.parentType = oldParentType;
  if (tight) {
    markTightParagraphs(state, listTokIdx);
  }
  return true;
}
function reference$1(state, startLine, _endLine, silent) {
  let pos2 = state.bMarks[startLine] + state.tShift[startLine];
  let max2 = state.eMarks[startLine];
  let nextLine = startLine + 1;
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  if (state.src.charCodeAt(pos2) !== 91) {
    return false;
  }
  function getNextLine(nextLine2) {
    const endLine = state.lineMax;
    if (nextLine2 >= endLine || state.isEmpty(nextLine2)) {
      return null;
    }
    let isContinuation = false;
    if (state.sCount[nextLine2] - state.blkIndent > 3) {
      isContinuation = true;
    }
    if (state.sCount[nextLine2] < 0) {
      isContinuation = true;
    }
    if (!isContinuation) {
      const terminatorRules = state.md.block.ruler.getRules("reference");
      const oldParentType = state.parentType;
      state.parentType = "reference";
      let terminate = false;
      for (let i2 = 0, l2 = terminatorRules.length; i2 < l2; i2++) {
        if (terminatorRules[i2](state, nextLine2, endLine, true)) {
          terminate = true;
          break;
        }
      }
      state.parentType = oldParentType;
      if (terminate) {
        return null;
      }
    }
    const pos3 = state.bMarks[nextLine2] + state.tShift[nextLine2];
    const max3 = state.eMarks[nextLine2];
    return state.src.slice(pos3, max3 + 1);
  }
  let str = state.src.slice(pos2, max2 + 1);
  max2 = str.length;
  let labelEnd = -1;
  for (pos2 = 1; pos2 < max2; pos2++) {
    const ch = str.charCodeAt(pos2);
    if (ch === 91) {
      return false;
    } else if (ch === 93) {
      labelEnd = pos2;
      break;
    } else if (ch === 10) {
      const lineContent = getNextLine(nextLine);
      if (lineContent !== null) {
        str += lineContent;
        max2 = str.length;
        nextLine++;
      }
    } else if (ch === 92) {
      pos2++;
      if (pos2 < max2 && str.charCodeAt(pos2) === 10) {
        const lineContent = getNextLine(nextLine);
        if (lineContent !== null) {
          str += lineContent;
          max2 = str.length;
          nextLine++;
        }
      }
    }
  }
  if (labelEnd < 0 || str.charCodeAt(labelEnd + 1) !== 58) {
    return false;
  }
  for (pos2 = labelEnd + 2; pos2 < max2; pos2++) {
    const ch = str.charCodeAt(pos2);
    if (ch === 10) {
      const lineContent = getNextLine(nextLine);
      if (lineContent !== null) {
        str += lineContent;
        max2 = str.length;
        nextLine++;
      }
    } else if (isSpace(ch)) ;
    else {
      break;
    }
  }
  const destRes = state.md.helpers.parseLinkDestination(str, pos2, max2);
  if (!destRes.ok) {
    return false;
  }
  const href = state.md.normalizeLink(destRes.str);
  if (!state.md.validateLink(href)) {
    return false;
  }
  pos2 = destRes.pos;
  const destEndPos = pos2;
  const destEndLineNo = nextLine;
  const start2 = pos2;
  for (; pos2 < max2; pos2++) {
    const ch = str.charCodeAt(pos2);
    if (ch === 10) {
      const lineContent = getNextLine(nextLine);
      if (lineContent !== null) {
        str += lineContent;
        max2 = str.length;
        nextLine++;
      }
    } else if (isSpace(ch)) ;
    else {
      break;
    }
  }
  let titleRes = state.md.helpers.parseLinkTitle(str, pos2, max2);
  while (titleRes.can_continue) {
    const lineContent = getNextLine(nextLine);
    if (lineContent === null) break;
    str += lineContent;
    pos2 = max2;
    max2 = str.length;
    nextLine++;
    titleRes = state.md.helpers.parseLinkTitle(str, pos2, max2, titleRes);
  }
  let title2;
  if (pos2 < max2 && start2 !== pos2 && titleRes.ok) {
    title2 = titleRes.str;
    pos2 = titleRes.pos;
  } else {
    title2 = "";
    pos2 = destEndPos;
    nextLine = destEndLineNo;
  }
  while (pos2 < max2) {
    const ch = str.charCodeAt(pos2);
    if (!isSpace(ch)) {
      break;
    }
    pos2++;
  }
  if (pos2 < max2 && str.charCodeAt(pos2) !== 10) {
    if (title2) {
      title2 = "";
      pos2 = destEndPos;
      nextLine = destEndLineNo;
      while (pos2 < max2) {
        const ch = str.charCodeAt(pos2);
        if (!isSpace(ch)) {
          break;
        }
        pos2++;
      }
    }
  }
  if (pos2 < max2 && str.charCodeAt(pos2) !== 10) {
    return false;
  }
  const label2 = normalizeReference(str.slice(1, labelEnd));
  if (!label2) {
    return false;
  }
  if (silent) {
    return true;
  }
  if (typeof state.env.references === "undefined") {
    state.env.references = {};
  }
  if (typeof state.env.references[label2] === "undefined") {
    state.env.references[label2] = { title: title2, href };
  }
  state.line = nextLine;
  return true;
}
const block_names = [
  "address",
  "article",
  "aside",
  "base",
  "basefont",
  "blockquote",
  "body",
  "caption",
  "center",
  "col",
  "colgroup",
  "dd",
  "details",
  "dialog",
  "dir",
  "div",
  "dl",
  "dt",
  "fieldset",
  "figcaption",
  "figure",
  "footer",
  "form",
  "frame",
  "frameset",
  "h1",
  "h2",
  "h3",
  "h4",
  "h5",
  "h6",
  "head",
  "header",
  "hr",
  "html",
  "iframe",
  "legend",
  "li",
  "link",
  "main",
  "menu",
  "menuitem",
  "nav",
  "noframes",
  "ol",
  "optgroup",
  "option",
  "p",
  "param",
  "search",
  "section",
  "summary",
  "table",
  "tbody",
  "td",
  "tfoot",
  "th",
  "thead",
  "title",
  "tr",
  "track",
  "ul"
];
const attr_name = "[a-zA-Z_:][a-zA-Z0-9:._-]*";
const unquoted = "[^\"'=<>`\\x00-\\x20]+";
const single_quoted = "'[^']*'";
const double_quoted = '"[^"]*"';
const attr_value = "(?:" + unquoted + "|" + single_quoted + "|" + double_quoted + ")";
const attribute = "(?:\\s+" + attr_name + "(?:\\s*=\\s*" + attr_value + ")?)";
const open_tag = "<[A-Za-z][A-Za-z0-9\\-]*" + attribute + "*\\s*\\/?>";
const close_tag = "<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>";
const comment = "<!---?>|<!--(?:[^-]|-[^-]|--[^>])*-->";
const processing = "<[?][\\s\\S]*?[?]>";
const declaration = "<![A-Za-z][^>]*>";
const cdata = "<!\\[CDATA\\[[\\s\\S]*?\\]\\]>";
const HTML_TAG_RE = new RegExp("^(?:" + open_tag + "|" + close_tag + "|" + comment + "|" + processing + "|" + declaration + "|" + cdata + ")");
const HTML_OPEN_CLOSE_TAG_RE = new RegExp("^(?:" + open_tag + "|" + close_tag + ")");
const HTML_SEQUENCES = [
  [/^<(script|pre|style|textarea)(?=(\s|>|$))/i, /<\/(script|pre|style|textarea)>/i, true],
  [/^<!--/, /-->/, true],
  [/^<\?/, /\?>/, true],
  [/^<![A-Z]/, />/, true],
  [/^<!\[CDATA\[/, /\]\]>/, true],
  [new RegExp("^</?(" + block_names.join("|") + ")(?=(\\s|/?>|$))", "i"), /^$/, true],
  [new RegExp(HTML_OPEN_CLOSE_TAG_RE.source + "\\s*$"), /^$/, false]
];
function html_block(state, startLine, endLine, silent) {
  let pos2 = state.bMarks[startLine] + state.tShift[startLine];
  let max2 = state.eMarks[startLine];
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  if (!state.md.options.html) {
    return false;
  }
  if (state.src.charCodeAt(pos2) !== 60) {
    return false;
  }
  let lineText = state.src.slice(pos2, max2);
  let i2 = 0;
  for (; i2 < HTML_SEQUENCES.length; i2++) {
    if (HTML_SEQUENCES[i2][0].test(lineText)) {
      break;
    }
  }
  if (i2 === HTML_SEQUENCES.length) {
    return false;
  }
  if (silent) {
    return HTML_SEQUENCES[i2][2];
  }
  let nextLine = startLine + 1;
  if (!HTML_SEQUENCES[i2][1].test(lineText)) {
    for (; nextLine < endLine; nextLine++) {
      if (state.sCount[nextLine] < state.blkIndent) {
        break;
      }
      pos2 = state.bMarks[nextLine] + state.tShift[nextLine];
      max2 = state.eMarks[nextLine];
      lineText = state.src.slice(pos2, max2);
      if (HTML_SEQUENCES[i2][1].test(lineText)) {
        if (lineText.length !== 0) {
          nextLine++;
        }
        break;
      }
    }
  }
  state.line = nextLine;
  const token2 = state.push("html_block", "", 0);
  token2.map = [startLine, nextLine];
  token2.content = state.getLines(startLine, nextLine, state.blkIndent, true);
  return true;
}
function heading(state, startLine, endLine, silent) {
  let pos2 = state.bMarks[startLine] + state.tShift[startLine];
  let max2 = state.eMarks[startLine];
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  let ch = state.src.charCodeAt(pos2);
  if (ch !== 35 || pos2 >= max2) {
    return false;
  }
  let level = 1;
  ch = state.src.charCodeAt(++pos2);
  while (ch === 35 && pos2 < max2 && level <= 6) {
    level++;
    ch = state.src.charCodeAt(++pos2);
  }
  if (level > 6 || pos2 < max2 && !isSpace(ch)) {
    return false;
  }
  if (silent) {
    return true;
  }
  max2 = state.skipSpacesBack(max2, pos2);
  const tmp2 = state.skipCharsBack(max2, 35, pos2);
  if (tmp2 > pos2 && isSpace(state.src.charCodeAt(tmp2 - 1))) {
    max2 = tmp2;
  }
  state.line = startLine + 1;
  const token_o = state.push("heading_open", "h" + String(level), 1);
  token_o.markup = "########".slice(0, level);
  token_o.map = [startLine, state.line];
  const token_i = state.push("inline", "", 0);
  token_i.content = state.src.slice(pos2, max2).trim();
  token_i.map = [startLine, state.line];
  token_i.children = [];
  const token_c = state.push("heading_close", "h" + String(level), -1);
  token_c.markup = "########".slice(0, level);
  return true;
}
function lheading(state, startLine, endLine) {
  const terminatorRules = state.md.block.ruler.getRules("paragraph");
  if (state.sCount[startLine] - state.blkIndent >= 4) {
    return false;
  }
  const oldParentType = state.parentType;
  state.parentType = "paragraph";
  let level = 0;
  let marker;
  let nextLine = startLine + 1;
  for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) {
    if (state.sCount[nextLine] - state.blkIndent > 3) {
      continue;
    }
    if (state.sCount[nextLine] >= state.blkIndent) {
      let pos2 = state.bMarks[nextLine] + state.tShift[nextLine];
      const max2 = state.eMarks[nextLine];
      if (pos2 < max2) {
        marker = state.src.charCodeAt(pos2);
        if (marker === 45 || marker === 61) {
          pos2 = state.skipChars(pos2, marker);
          pos2 = state.skipSpaces(pos2);
          if (pos2 >= max2) {
            level = marker === 61 ? 1 : 2;
            break;
          }
        }
      }
    }
    if (state.sCount[nextLine] < 0) {
      continue;
    }
    let terminate = false;
    for (let i2 = 0, l2 = terminatorRules.length; i2 < l2; i2++) {
      if (terminatorRules[i2](state, nextLine, endLine, true)) {
        terminate = true;
        break;
      }
    }
    if (terminate) {
      break;
    }
  }
  if (!level) {
    return false;
  }
  const content2 = state.getLines(startLine, nextLine, state.blkIndent, false).trim();
  state.line = nextLine + 1;
  const token_o = state.push("heading_open", "h" + String(level), 1);
  token_o.markup = String.fromCharCode(marker);
  token_o.map = [startLine, state.line];
  const token_i = state.push("inline", "", 0);
  token_i.content = content2;
  token_i.map = [startLine, state.line - 1];
  token_i.children = [];
  const token_c = state.push("heading_close", "h" + String(level), -1);
  token_c.markup = String.fromCharCode(marker);
  state.parentType = oldParentType;
  return true;
}
function paragraph(state, startLine, endLine) {
  const terminatorRules = state.md.block.ruler.getRules("paragraph");
  const oldParentType = state.parentType;
  let nextLine = startLine + 1;
  state.parentType = "paragraph";
  for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) {
    if (state.sCount[nextLine] - state.blkIndent > 3) {
      continue;
    }
    if (state.sCount[nextLine] < 0) {
      continue;
    }
    let terminate = false;
    for (let i2 = 0, l2 = terminatorRules.length; i2 < l2; i2++) {
      if (terminatorRules[i2](state, nextLine, endLine, true)) {
        terminate = true;
        break;
      }
    }
    if (terminate) {
      break;
    }
  }
  const content2 = state.getLines(startLine, nextLine, state.blkIndent, false).trim();
  state.line = nextLine;
  const token_o = state.push("paragraph_open", "p", 1);
  token_o.map = [startLine, state.line];
  const token_i = state.push("inline", "", 0);
  token_i.content = content2;
  token_i.map = [startLine, state.line];
  token_i.children = [];
  state.push("paragraph_close", "p", -1);
  state.parentType = oldParentType;
  return true;
}
const _rules$1 = [
  // First 2 params - rule name & source. Secondary array - list of rules,
  // which can be terminated by this one.
  ["table", table$1, ["paragraph", "reference"]],
  ["code", code$3],
  ["fence", fence, ["paragraph", "reference", "blockquote", "list"]],
  ["blockquote", blockquote, ["paragraph", "reference", "blockquote", "list"]],
  ["hr", hr, ["paragraph", "reference", "blockquote", "list"]],
  ["list", list, ["paragraph", "reference", "blockquote"]],
  ["reference", reference$1],
  ["html_block", html_block, ["paragraph", "reference", "blockquote"]],
  ["heading", heading, ["paragraph", "reference", "blockquote"]],
  ["lheading", lheading],
  ["paragraph", paragraph]
];
function ParserBlock() {
  this.ruler = new Ruler();
  for (let i2 = 0; i2 < _rules$1.length; i2++) {
    this.ruler.push(_rules$1[i2][0], _rules$1[i2][1], { alt: (_rules$1[i2][2] || []).slice() });
  }
}
ParserBlock.prototype.tokenize = function(state, startLine, endLine) {
  const rules = this.ruler.getRules("");
  const len = rules.length;
  const maxNesting = state.md.options.maxNesting;
  let line2 = startLine;
  let hasEmptyLines = false;
  while (line2 < endLine) {
    state.line = line2 = state.skipEmptyLines(line2);
    if (line2 >= endLine) {
      break;
    }
    if (state.sCount[line2] < state.blkIndent) {
      break;
    }
    if (state.level >= maxNesting) {
      state.line = endLine;
      break;
    }
    const prevLine = state.line;
    let ok = false;
    for (let i2 = 0; i2 < len; i2++) {
      ok = rules[i2](state, line2, endLine, false);
      if (ok) {
        if (prevLine >= state.line) {
          throw new Error("block rule didn't increment state.line");
        }
        break;
      }
    }
    if (!ok) throw new Error("none of the block rules matched");
    state.tight = !hasEmptyLines;
    if (state.isEmpty(state.line - 1)) {
      hasEmptyLines = true;
    }
    line2 = state.line;
    if (line2 < endLine && state.isEmpty(line2)) {
      hasEmptyLines = true;
      line2++;
      state.line = line2;
    }
  }
};
ParserBlock.prototype.parse = function(src, md, env, outTokens) {
  if (!src) {
    return;
  }
  const state = new this.State(src, md, env, outTokens);
  this.tokenize(state, state.line, state.lineMax);
};
ParserBlock.prototype.State = StateBlock;
function StateInline(src, md, env, outTokens) {
  this.src = src;
  this.env = env;
  this.md = md;
  this.tokens = outTokens;
  this.tokens_meta = Array(outTokens.length);
  this.pos = 0;
  this.posMax = this.src.length;
  this.level = 0;
  this.pending = "";
  this.pendingLevel = 0;
  this.cache = {};
  this.delimiters = [];
  this._prev_delimiters = [];
  this.backticks = {};
  this.backticksScanned = false;
  this.linkLevel = 0;
}
StateInline.prototype.pushPending = function() {
  const token2 = new Token2("text", "", 0);
  token2.content = this.pending;
  token2.level = this.pendingLevel;
  this.tokens.push(token2);
  this.pending = "";
  return token2;
};
StateInline.prototype.push = function(type, tag, nesting) {
  if (this.pending) {
    this.pushPending();
  }
  const token2 = new Token2(type, tag, nesting);
  let token_meta = null;
  if (nesting < 0) {
    this.level--;
    this.delimiters = this._prev_delimiters.pop();
  }
  token2.level = this.level;
  if (nesting > 0) {
    this.level++;
    this._prev_delimiters.push(this.delimiters);
    this.delimiters = [];
    token_meta = { delimiters: this.delimiters };
  }
  this.pendingLevel = this.level;
  this.tokens.push(token2);
  this.tokens_meta.push(token_meta);
  return token2;
};
StateInline.prototype.scanDelims = function(start2, canSplitWord) {
  const max2 = this.posMax;
  const marker = this.src.charCodeAt(start2);
  const lastChar = start2 > 0 ? this.src.charCodeAt(start2 - 1) : 32;
  let pos2 = start2;
  while (pos2 < max2 && this.src.charCodeAt(pos2) === marker) {
    pos2++;
  }
  const count2 = pos2 - start2;
  const nextChar = pos2 < max2 ? this.src.charCodeAt(pos2) : 32;
  const isLastPunctChar = isMdAsciiPunct(lastChar) || isPunctChar(String.fromCharCode(lastChar));
  const isNextPunctChar = isMdAsciiPunct(nextChar) || isPunctChar(String.fromCharCode(nextChar));
  const isLastWhiteSpace = isWhiteSpace(lastChar);
  const isNextWhiteSpace = isWhiteSpace(nextChar);
  const left_flanking = !isNextWhiteSpace && (!isNextPunctChar || isLastWhiteSpace || isLastPunctChar);
  const right_flanking = !isLastWhiteSpace && (!isLastPunctChar || isNextWhiteSpace || isNextPunctChar);
  const can_open = left_flanking && (canSplitWord || !right_flanking || isLastPunctChar);
  const can_close = right_flanking && (canSplitWord || !left_flanking || isNextPunctChar);
  return { can_open, can_close, length: count2 };
};
StateInline.prototype.Token = Token2;
function isTerminatorChar(ch) {
  switch (ch) {
    case 10:
    case 33:
    case 35:
    case 36:
    case 37:
    case 38:
    case 42:
    case 43:
    case 45:
    case 58:
    case 60:
    case 61:
    case 62:
    case 64:
    case 91:
    case 92:
    case 93:
    case 94:
    case 95:
    case 96:
    case 123:
    case 125:
    case 126:
      return true;
    default:
      return false;
  }
}
function text(state, silent) {
  let pos2 = state.pos;
  while (pos2 < state.posMax && !isTerminatorChar(state.src.charCodeAt(pos2))) {
    pos2++;
  }
  if (pos2 === state.pos) {
    return false;
  }
  if (!silent) {
    state.pending += state.src.slice(state.pos, pos2);
  }
  state.pos = pos2;
  return true;
}
const SCHEME_RE = /(?:^|[^a-z0-9.+-])([a-z][a-z0-9.+-]*)$/i;
function linkify(state, silent) {
  if (!state.md.options.linkify) return false;
  if (state.linkLevel > 0) return false;
  const pos2 = state.pos;
  const max2 = state.posMax;
  if (pos2 + 3 > max2) return false;
  if (state.src.charCodeAt(pos2) !== 58) return false;
  if (state.src.charCodeAt(pos2 + 1) !== 47) return false;
  if (state.src.charCodeAt(pos2 + 2) !== 47) return false;
  const match3 = state.pending.match(SCHEME_RE);
  if (!match3) return false;
  const proto = match3[1];
  const link2 = state.md.linkify.matchAtStart(state.src.slice(pos2 - proto.length));
  if (!link2) return false;
  let url = link2.url;
  if (url.length <= proto.length) return false;
  url = url.replace(/\*+$/, "");
  const fullUrl = state.md.normalizeLink(url);
  if (!state.md.validateLink(fullUrl)) return false;
  if (!silent) {
    state.pending = state.pending.slice(0, -proto.length);
    const token_o = state.push("link_open", "a", 1);
    token_o.attrs = [["href", fullUrl]];
    token_o.markup = "linkify";
    token_o.info = "auto";
    const token_t = state.push("text", "", 0);
    token_t.content = state.md.normalizeLinkText(url);
    const token_c = state.push("link_close", "a", -1);
    token_c.markup = "linkify";
    token_c.info = "auto";
  }
  state.pos += url.length - proto.length;
  return true;
}
function newline(state, silent) {
  let pos2 = state.pos;
  if (state.src.charCodeAt(pos2) !== 10) {
    return false;
  }
  const pmax = state.pending.length - 1;
  const max2 = state.posMax;
  if (!silent) {
    if (pmax >= 0 && state.pending.charCodeAt(pmax) === 32) {
      if (pmax >= 1 && state.pending.charCodeAt(pmax - 1) === 32) {
        let ws = pmax - 1;
        while (ws >= 1 && state.pending.charCodeAt(ws - 1) === 32) ws--;
        state.pending = state.pending.slice(0, ws);
        state.push("hardbreak", "br", 0);
      } else {
        state.pending = state.pending.slice(0, -1);
        state.push("softbreak", "br", 0);
      }
    } else {
      state.push("softbreak", "br", 0);
    }
  }
  pos2++;
  while (pos2 < max2 && isSpace(state.src.charCodeAt(pos2))) {
    pos2++;
  }
  state.pos = pos2;
  return true;
}
const ESCAPED = [];
for (let i2 = 0; i2 < 256; i2++) {
  ESCAPED.push(0);
}
"\\!\"#$%&'()*+,./:;<=>?@[]^_`{|}~-".split("").forEach(function(ch) {
  ESCAPED[ch.charCodeAt(0)] = 1;
});
function escape(state, silent) {
  let pos2 = state.pos;
  const max2 = state.posMax;
  if (state.src.charCodeAt(pos2) !== 92) return false;
  pos2++;
  if (pos2 >= max2) return false;
  let ch1 = state.src.charCodeAt(pos2);
  if (ch1 === 10) {
    if (!silent) {
      state.push("hardbreak", "br", 0);
    }
    pos2++;
    while (pos2 < max2) {
      ch1 = state.src.charCodeAt(pos2);
      if (!isSpace(ch1)) break;
      pos2++;
    }
    state.pos = pos2;
    return true;
  }
  let escapedStr = state.src[pos2];
  if (ch1 >= 55296 && ch1 <= 56319 && pos2 + 1 < max2) {
    const ch2 = state.src.charCodeAt(pos2 + 1);
    if (ch2 >= 56320 && ch2 <= 57343) {
      escapedStr += state.src[pos2 + 1];
      pos2++;
    }
  }
  const origStr = "\\" + escapedStr;
  if (!silent) {
    const token2 = state.push("text_special", "", 0);
    if (ch1 < 256 && ESCAPED[ch1] !== 0) {
      token2.content = escapedStr;
    } else {
      token2.content = origStr;
    }
    token2.markup = origStr;
    token2.info = "escape";
  }
  state.pos = pos2 + 1;
  return true;
}
function backtick(state, silent) {
  let pos2 = state.pos;
  const ch = state.src.charCodeAt(pos2);
  if (ch !== 96) {
    return false;
  }
  const start2 = pos2;
  pos2++;
  const max2 = state.posMax;
  while (pos2 < max2 && state.src.charCodeAt(pos2) === 96) {
    pos2++;
  }
  const marker = state.src.slice(start2, pos2);
  const openerLength = marker.length;
  if (state.backticksScanned && (state.backticks[openerLength] || 0) <= start2) {
    if (!silent) state.pending += marker;
    state.pos += openerLength;
    return true;
  }
  let matchEnd = pos2;
  let matchStart;
  while ((matchStart = state.src.indexOf("`", matchEnd)) !== -1) {
    matchEnd = matchStart + 1;
    while (matchEnd < max2 && state.src.charCodeAt(matchEnd) === 96) {
      matchEnd++;
    }
    const closerLength = matchEnd - matchStart;
    if (closerLength === openerLength) {
      if (!silent) {
        const token2 = state.push("code_inline", "code", 0);
        token2.markup = marker;
        token2.content = state.src.slice(pos2, matchStart).replace(/\n/g, " ").replace(/^ (.+) $/, "$1");
      }
      state.pos = matchEnd;
      return true;
    }
    state.backticks[closerLength] = matchStart;
  }
  state.backticksScanned = true;
  if (!silent) state.pending += marker;
  state.pos += openerLength;
  return true;
}
function strikethrough_tokenize(state, silent) {
  const start2 = state.pos;
  const marker = state.src.charCodeAt(start2);
  if (silent) {
    return false;
  }
  if (marker !== 126) {
    return false;
  }
  const scanned = state.scanDelims(state.pos, true);
  let len = scanned.length;
  const ch = String.fromCharCode(marker);
  if (len < 2) {
    return false;
  }
  let token2;
  if (len % 2) {
    token2 = state.push("text", "", 0);
    token2.content = ch;
    len--;
  }
  for (let i2 = 0; i2 < len; i2 += 2) {
    token2 = state.push("text", "", 0);
    token2.content = ch + ch;
    state.delimiters.push({
      marker,
      length: 0,
      // disable "rule of 3" length checks meant for emphasis
      token: state.tokens.length - 1,
      end: -1,
      open: scanned.can_open,
      close: scanned.can_close
    });
  }
  state.pos += scanned.length;
  return true;
}
function postProcess$1(state, delimiters) {
  let token2;
  const loneMarkers = [];
  const max2 = delimiters.length;
  for (let i2 = 0; i2 < max2; i2++) {
    const startDelim = delimiters[i2];
    if (startDelim.marker !== 126) {
      continue;
    }
    if (startDelim.end === -1) {
      continue;
    }
    const endDelim = delimiters[startDelim.end];
    token2 = state.tokens[startDelim.token];
    token2.type = "s_open";
    token2.tag = "s";
    token2.nesting = 1;
    token2.markup = "~~";
    token2.content = "";
    token2 = state.tokens[endDelim.token];
    token2.type = "s_close";
    token2.tag = "s";
    token2.nesting = -1;
    token2.markup = "~~";
    token2.content = "";
    if (state.tokens[endDelim.token - 1].type === "text" && state.tokens[endDelim.token - 1].content === "~") {
      loneMarkers.push(endDelim.token - 1);
    }
  }
  while (loneMarkers.length) {
    const i2 = loneMarkers.pop();
    let j2 = i2 + 1;
    while (j2 < state.tokens.length && state.tokens[j2].type === "s_close") {
      j2++;
    }
    j2--;
    if (i2 !== j2) {
      token2 = state.tokens[j2];
      state.tokens[j2] = state.tokens[i2];
      state.tokens[i2] = token2;
    }
  }
}
function strikethrough_postProcess(state) {
  const tokens_meta = state.tokens_meta;
  const max2 = state.tokens_meta.length;
  postProcess$1(state, state.delimiters);
  for (let curr = 0; curr < max2; curr++) {
    if (tokens_meta[curr] && tokens_meta[curr].delimiters) {
      postProcess$1(state, tokens_meta[curr].delimiters);
    }
  }
}
const r_strikethrough = {
  tokenize: strikethrough_tokenize,
  postProcess: strikethrough_postProcess
};
function emphasis_tokenize(state, silent) {
  const start2 = state.pos;
  const marker = state.src.charCodeAt(start2);
  if (silent) {
    return false;
  }
  if (marker !== 95 && marker !== 42) {
    return false;
  }
  const scanned = state.scanDelims(state.pos, marker === 42);
  for (let i2 = 0; i2 < scanned.length; i2++) {
    const token2 = state.push("text", "", 0);
    token2.content = String.fromCharCode(marker);
    state.delimiters.push({
      // Char code of the starting marker (number).
      //
      marker,
      // Total length of these series of delimiters.
      //
      length: scanned.length,
      // A position of the token this delimiter corresponds to.
      //
      token: state.tokens.length - 1,
      // If this delimiter is matched as a valid opener, `end` will be
      // equal to its position, otherwise it's `-1`.
      //
      end: -1,
      // Boolean flags that determine if this delimiter could open or close
      // an emphasis.
      //
      open: scanned.can_open,
      close: scanned.can_close
    });
  }
  state.pos += scanned.length;
  return true;
}
function postProcess(state, delimiters) {
  const max2 = delimiters.length;
  for (let i2 = max2 - 1; i2 >= 0; i2--) {
    const startDelim = delimiters[i2];
    if (startDelim.marker !== 95 && startDelim.marker !== 42) {
      continue;
    }
    if (startDelim.end === -1) {
      continue;
    }
    const endDelim = delimiters[startDelim.end];
    const isStrong = i2 > 0 && delimiters[i2 - 1].end === startDelim.end + 1 && // check that first two markers match and adjacent
    delimiters[i2 - 1].marker === startDelim.marker && delimiters[i2 - 1].token === startDelim.token - 1 && // check that last two markers are adjacent (we can safely assume they match)
    delimiters[startDelim.end + 1].token === endDelim.token + 1;
    const ch = String.fromCharCode(startDelim.marker);
    const token_o = state.tokens[startDelim.token];
    token_o.type = isStrong ? "strong_open" : "em_open";
    token_o.tag = isStrong ? "strong" : "em";
    token_o.nesting = 1;
    token_o.markup = isStrong ? ch + ch : ch;
    token_o.content = "";
    const token_c = state.tokens[endDelim.token];
    token_c.type = isStrong ? "strong_close" : "em_close";
    token_c.tag = isStrong ? "strong" : "em";
    token_c.nesting = -1;
    token_c.markup = isStrong ? ch + ch : ch;
    token_c.content = "";
    if (isStrong) {
      state.tokens[delimiters[i2 - 1].token].content = "";
      state.tokens[delimiters[startDelim.end + 1].token].content = "";
      i2--;
    }
  }
}
function emphasis_post_process(state) {
  const tokens_meta = state.tokens_meta;
  const max2 = state.tokens_meta.length;
  postProcess(state, state.delimiters);
  for (let curr = 0; curr < max2; curr++) {
    if (tokens_meta[curr] && tokens_meta[curr].delimiters) {
      postProcess(state, tokens_meta[curr].delimiters);
    }
  }
}
const r_emphasis = {
  tokenize: emphasis_tokenize,
  postProcess: emphasis_post_process
};
function link$1(state, silent) {
  let code2, label2, res, ref2;
  let href = "";
  let title2 = "";
  let start2 = state.pos;
  let parseReference = true;
  if (state.src.charCodeAt(state.pos) !== 91) {
    return false;
  }
  const oldPos = state.pos;
  const max2 = state.posMax;
  const labelStart = state.pos + 1;
  const labelEnd = state.md.helpers.parseLinkLabel(state, state.pos, true);
  if (labelEnd < 0) {
    return false;
  }
  let pos2 = labelEnd + 1;
  if (pos2 < max2 && state.src.charCodeAt(pos2) === 40) {
    parseReference = false;
    pos2++;
    for (; pos2 < max2; pos2++) {
      code2 = state.src.charCodeAt(pos2);
      if (!isSpace(code2) && code2 !== 10) {
        break;
      }
    }
    if (pos2 >= max2) {
      return false;
    }
    start2 = pos2;
    res = state.md.helpers.parseLinkDestination(state.src, pos2, state.posMax);
    if (res.ok) {
      href = state.md.normalizeLink(res.str);
      if (state.md.validateLink(href)) {
        pos2 = res.pos;
      } else {
        href = "";
      }
      start2 = pos2;
      for (; pos2 < max2; pos2++) {
        code2 = state.src.charCodeAt(pos2);
        if (!isSpace(code2) && code2 !== 10) {
          break;
        }
      }
      res = state.md.helpers.parseLinkTitle(state.src, pos2, state.posMax);
      if (pos2 < max2 && start2 !== pos2 && res.ok) {
        title2 = res.str;
        pos2 = res.pos;
        for (; pos2 < max2; pos2++) {
          code2 = state.src.charCodeAt(pos2);
          if (!isSpace(code2) && code2 !== 10) {
            break;
          }
        }
      }
    }
    if (pos2 >= max2 || state.src.charCodeAt(pos2) !== 41) {
      parseReference = true;
    }
    pos2++;
  }
  if (parseReference) {
    if (typeof state.env.references === "undefined") {
      return false;
    }
    if (pos2 < max2 && state.src.charCodeAt(pos2) === 91) {
      start2 = pos2 + 1;
      pos2 = state.md.helpers.parseLinkLabel(state, pos2);
      if (pos2 >= 0) {
        label2 = state.src.slice(start2, pos2++);
      } else {
        pos2 = labelEnd + 1;
      }
    } else {
      pos2 = labelEnd + 1;
    }
    if (!label2) {
      label2 = state.src.slice(labelStart, labelEnd);
    }
    ref2 = state.env.references[normalizeReference(label2)];
    if (!ref2) {
      state.pos = oldPos;
      return false;
    }
    href = ref2.href;
    title2 = ref2.title;
  }
  if (!silent) {
    state.pos = labelStart;
    state.posMax = labelEnd;
    const token_o = state.push("link_open", "a", 1);
    const attrs = [["href", href]];
    token_o.attrs = attrs;
    if (title2) {
      attrs.push(["title", title2]);
    }
    state.linkLevel++;
    state.md.inline.tokenize(state);
    state.linkLevel--;
    state.push("link_close", "a", -1);
  }
  state.pos = pos2;
  state.posMax = max2;
  return true;
}
function image$1(state, silent) {
  let code2, content2, label2, pos2, ref2, res, title2, start2;
  let href = "";
  const oldPos = state.pos;
  const max2 = state.posMax;
  if (state.src.charCodeAt(state.pos) !== 33) {
    return false;
  }
  if (state.src.charCodeAt(state.pos + 1) !== 91) {
    return false;
  }
  const labelStart = state.pos + 2;
  const labelEnd = state.md.helpers.parseLinkLabel(state, state.pos + 1, false);
  if (labelEnd < 0) {
    return false;
  }
  pos2 = labelEnd + 1;
  if (pos2 < max2 && state.src.charCodeAt(pos2) === 40) {
    pos2++;
    for (; pos2 < max2; pos2++) {
      code2 = state.src.charCodeAt(pos2);
      if (!isSpace(code2) && code2 !== 10) {
        break;
      }
    }
    if (pos2 >= max2) {
      return false;
    }
    start2 = pos2;
    res = state.md.helpers.parseLinkDestination(state.src, pos2, state.posMax);
    if (res.ok) {
      href = state.md.normalizeLink(res.str);
      if (state.md.validateLink(href)) {
        pos2 = res.pos;
      } else {
        href = "";
      }
    }
    start2 = pos2;
    for (; pos2 < max2; pos2++) {
      code2 = state.src.charCodeAt(pos2);
      if (!isSpace(code2) && code2 !== 10) {
        break;
      }
    }
    res = state.md.helpers.parseLinkTitle(state.src, pos2, state.posMax);
    if (pos2 < max2 && start2 !== pos2 && res.ok) {
      title2 = res.str;
      pos2 = res.pos;
      for (; pos2 < max2; pos2++) {
        code2 = state.src.charCodeAt(pos2);
        if (!isSpace(code2) && code2 !== 10) {
          break;
        }
      }
    } else {
      title2 = "";
    }
    if (pos2 >= max2 || state.src.charCodeAt(pos2) !== 41) {
      state.pos = oldPos;
      return false;
    }
    pos2++;
  } else {
    if (typeof state.env.references === "undefined") {
      return false;
    }
    if (pos2 < max2 && state.src.charCodeAt(pos2) === 91) {
      start2 = pos2 + 1;
      pos2 = state.md.helpers.parseLinkLabel(state, pos2);
      if (pos2 >= 0) {
        label2 = state.src.slice(start2, pos2++);
      } else {
        pos2 = labelEnd + 1;
      }
    } else {
      pos2 = labelEnd + 1;
    }
    if (!label2) {
      label2 = state.src.slice(labelStart, labelEnd);
    }
    ref2 = state.env.references[normalizeReference(label2)];
    if (!ref2) {
      state.pos = oldPos;
      return false;
    }
    href = ref2.href;
    title2 = ref2.title;
  }
  if (!silent) {
    content2 = state.src.slice(labelStart, labelEnd);
    const tokens = [];
    state.md.inline.parse(
      content2,
      state.md,
      state.env,
      tokens
    );
    const token2 = state.push("image", "img", 0);
    const attrs = [["src", href], ["alt", ""]];
    token2.attrs = attrs;
    token2.children = tokens;
    token2.content = content2;
    if (title2) {
      attrs.push(["title", title2]);
    }
  }
  state.pos = pos2;
  state.posMax = max2;
  return true;
}
const EMAIL_RE = /^([a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$/;
const AUTOLINK_RE = /^([a-zA-Z][a-zA-Z0-9+.-]{1,31}):([^<>\x00-\x20]*)$/;
function autolink(state, silent) {
  let pos2 = state.pos;
  if (state.src.charCodeAt(pos2) !== 60) {
    return false;
  }
  const start2 = state.pos;
  const max2 = state.posMax;
  for (; ; ) {
    if (++pos2 >= max2) return false;
    const ch = state.src.charCodeAt(pos2);
    if (ch === 60) return false;
    if (ch === 62) break;
  }
  const url = state.src.slice(start2 + 1, pos2);
  if (AUTOLINK_RE.test(url)) {
    const fullUrl = state.md.normalizeLink(url);
    if (!state.md.validateLink(fullUrl)) {
      return false;
    }
    if (!silent) {
      const token_o = state.push("link_open", "a", 1);
      token_o.attrs = [["href", fullUrl]];
      token_o.markup = "autolink";
      token_o.info = "auto";
      const token_t = state.push("text", "", 0);
      token_t.content = state.md.normalizeLinkText(url);
      const token_c = state.push("link_close", "a", -1);
      token_c.markup = "autolink";
      token_c.info = "auto";
    }
    state.pos += url.length + 2;
    return true;
  }
  if (EMAIL_RE.test(url)) {
    const fullUrl = state.md.normalizeLink("mailto:" + url);
    if (!state.md.validateLink(fullUrl)) {
      return false;
    }
    if (!silent) {
      const token_o = state.push("link_open", "a", 1);
      token_o.attrs = [["href", fullUrl]];
      token_o.markup = "autolink";
      token_o.info = "auto";
      const token_t = state.push("text", "", 0);
      token_t.content = state.md.normalizeLinkText(url);
      const token_c = state.push("link_close", "a", -1);
      token_c.markup = "autolink";
      token_c.info = "auto";
    }
    state.pos += url.length + 2;
    return true;
  }
  return false;
}
function isLinkOpen(str) {
  return /^<a[>\s]/i.test(str);
}
function isLinkClose(str) {
  return /^<\/a\s*>/i.test(str);
}
function isLetter(ch) {
  const lc = ch | 32;
  return lc >= 97 && lc <= 122;
}
function html_inline(state, silent) {
  if (!state.md.options.html) {
    return false;
  }
  const max2 = state.posMax;
  const pos2 = state.pos;
  if (state.src.charCodeAt(pos2) !== 60 || pos2 + 2 >= max2) {
    return false;
  }
  const ch = state.src.charCodeAt(pos2 + 1);
  if (ch !== 33 && ch !== 63 && ch !== 47 && !isLetter(ch)) {
    return false;
  }
  const match3 = state.src.slice(pos2).match(HTML_TAG_RE);
  if (!match3) {
    return false;
  }
  if (!silent) {
    const token2 = state.push("html_inline", "", 0);
    token2.content = match3[0];
    if (isLinkOpen(token2.content)) state.linkLevel++;
    if (isLinkClose(token2.content)) state.linkLevel--;
  }
  state.pos += match3[0].length;
  return true;
}
const DIGITAL_RE = /^&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));/i;
const NAMED_RE = /^&([a-z][a-z0-9]{1,31});/i;
function entity(state, silent) {
  const pos2 = state.pos;
  const max2 = state.posMax;
  if (state.src.charCodeAt(pos2) !== 38) return false;
  if (pos2 + 1 >= max2) return false;
  const ch = state.src.charCodeAt(pos2 + 1);
  if (ch === 35) {
    const match3 = state.src.slice(pos2).match(DIGITAL_RE);
    if (match3) {
      if (!silent) {
        const code2 = match3[1][0].toLowerCase() === "x" ? parseInt(match3[1].slice(1), 16) : parseInt(match3[1], 10);
        const token2 = state.push("text_special", "", 0);
        token2.content = isValidEntityCode(code2) ? fromCodePoint(code2) : fromCodePoint(65533);
        token2.markup = match3[0];
        token2.info = "entity";
      }
      state.pos += match3[0].length;
      return true;
    }
  } else {
    const match3 = state.src.slice(pos2).match(NAMED_RE);
    if (match3) {
      const decoded = decodeHTML(match3[0]);
      if (decoded !== match3[0]) {
        if (!silent) {
          const token2 = state.push("text_special", "", 0);
          token2.content = decoded;
          token2.markup = match3[0];
          token2.info = "entity";
        }
        state.pos += match3[0].length;
        return true;
      }
    }
  }
  return false;
}
function processDelimiters(delimiters) {
  const openersBottom = {};
  const max2 = delimiters.length;
  if (!max2) return;
  let headerIdx = 0;
  let lastTokenIdx = -2;
  const jumps = [];
  for (let closerIdx = 0; closerIdx < max2; closerIdx++) {
    const closer = delimiters[closerIdx];
    jumps.push(0);
    if (delimiters[headerIdx].marker !== closer.marker || lastTokenIdx !== closer.token - 1) {
      headerIdx = closerIdx;
    }
    lastTokenIdx = closer.token;
    closer.length = closer.length || 0;
    if (!closer.close) continue;
    if (!openersBottom.hasOwnProperty(closer.marker)) {
      openersBottom[closer.marker] = [-1, -1, -1, -1, -1, -1];
    }
    const minOpenerIdx = openersBottom[closer.marker][(closer.open ? 3 : 0) + closer.length % 3];
    let openerIdx = headerIdx - jumps[headerIdx] - 1;
    let newMinOpenerIdx = openerIdx;
    for (; openerIdx > minOpenerIdx; openerIdx -= jumps[openerIdx] + 1) {
      const opener = delimiters[openerIdx];
      if (opener.marker !== closer.marker) continue;
      if (opener.open && opener.end < 0) {
        let isOddMatch = false;
        if (opener.close || closer.open) {
          if ((opener.length + closer.length) % 3 === 0) {
            if (opener.length % 3 !== 0 || closer.length % 3 !== 0) {
              isOddMatch = true;
            }
          }
        }
        if (!isOddMatch) {
          const lastJump = openerIdx > 0 && !delimiters[openerIdx - 1].open ? jumps[openerIdx - 1] + 1 : 0;
          jumps[closerIdx] = closerIdx - openerIdx + lastJump;
          jumps[openerIdx] = lastJump;
          closer.open = false;
          opener.end = closerIdx;
          opener.close = false;
          newMinOpenerIdx = -1;
          lastTokenIdx = -2;
          break;
        }
      }
    }
    if (newMinOpenerIdx !== -1) {
      openersBottom[closer.marker][(closer.open ? 3 : 0) + (closer.length || 0) % 3] = newMinOpenerIdx;
    }
  }
}
function link_pairs(state) {
  const tokens_meta = state.tokens_meta;
  const max2 = state.tokens_meta.length;
  processDelimiters(state.delimiters);
  for (let curr = 0; curr < max2; curr++) {
    if (tokens_meta[curr] && tokens_meta[curr].delimiters) {
      processDelimiters(tokens_meta[curr].delimiters);
    }
  }
}
function fragments_join(state) {
  let curr, last2;
  let level = 0;
  const tokens = state.tokens;
  const max2 = state.tokens.length;
  for (curr = last2 = 0; curr < max2; curr++) {
    if (tokens[curr].nesting < 0) level--;
    tokens[curr].level = level;
    if (tokens[curr].nesting > 0) level++;
    if (tokens[curr].type === "text" && curr + 1 < max2 && tokens[curr + 1].type === "text") {
      tokens[curr + 1].content = tokens[curr].content + tokens[curr + 1].content;
    } else {
      if (curr !== last2) {
        tokens[last2] = tokens[curr];
      }
      last2++;
    }
  }
  if (curr !== last2) {
    tokens.length = last2;
  }
}
const _rules = [
  ["text", text],
  ["linkify", linkify],
  ["newline", newline],
  ["escape", escape],
  ["backticks", backtick],
  ["strikethrough", r_strikethrough.tokenize],
  ["emphasis", r_emphasis.tokenize],
  ["link", link$1],
  ["image", image$1],
  ["autolink", autolink],
  ["html_inline", html_inline],
  ["entity", entity]
];
const _rules2 = [
  ["balance_pairs", link_pairs],
  ["strikethrough", r_strikethrough.postProcess],
  ["emphasis", r_emphasis.postProcess],
  // rules for pairs separate '**' into its own text tokens, which may be left unused,
  // rule below merges unused segments back with the rest of the text
  ["fragments_join", fragments_join]
];
function ParserInline() {
  this.ruler = new Ruler();
  for (let i2 = 0; i2 < _rules.length; i2++) {
    this.ruler.push(_rules[i2][0], _rules[i2][1]);
  }
  this.ruler2 = new Ruler();
  for (let i2 = 0; i2 < _rules2.length; i2++) {
    this.ruler2.push(_rules2[i2][0], _rules2[i2][1]);
  }
}
ParserInline.prototype.skipToken = function(state) {
  const pos2 = state.pos;
  const rules = this.ruler.getRules("");
  const len = rules.length;
  const maxNesting = state.md.options.maxNesting;
  const cache = state.cache;
  if (typeof cache[pos2] !== "undefined") {
    state.pos = cache[pos2];
    return;
  }
  let ok = false;
  if (state.level < maxNesting) {
    for (let i2 = 0; i2 < len; i2++) {
      state.level++;
      ok = rules[i2](state, true);
      state.level--;
      if (ok) {
        if (pos2 >= state.pos) {
          throw new Error("inline rule didn't increment state.pos");
        }
        break;
      }
    }
  } else {
    state.pos = state.posMax;
  }
  if (!ok) {
    state.pos++;
  }
  cache[pos2] = state.pos;
};
ParserInline.prototype.tokenize = function(state) {
  const rules = this.ruler.getRules("");
  const len = rules.length;
  const end2 = state.posMax;
  const maxNesting = state.md.options.maxNesting;
  while (state.pos < end2) {
    const prevPos = state.pos;
    let ok = false;
    if (state.level < maxNesting) {
      for (let i2 = 0; i2 < len; i2++) {
        ok = rules[i2](state, false);
        if (ok) {
          if (prevPos >= state.pos) {
            throw new Error("inline rule didn't increment state.pos");
          }
          break;
        }
      }
    }
    if (ok) {
      if (state.pos >= end2) {
        break;
      }
      continue;
    }
    state.pending += state.src[state.pos++];
  }
  if (state.pending) {
    state.pushPending();
  }
};
ParserInline.prototype.parse = function(str, md, env, outTokens) {
  const state = new this.State(str, md, env, outTokens);
  this.tokenize(state);
  const rules = this.ruler2.getRules("");
  const len = rules.length;
  for (let i2 = 0; i2 < len; i2++) {
    rules[i2](state);
  }
};
ParserInline.prototype.State = StateInline;
function reFactory(opts) {
  const re2 = {};
  opts = opts || {};
  re2.src_Any = Any.source;
  re2.src_Cc = Cc.source;
  re2.src_Z = Z.source;
  re2.src_P = P.source;
  re2.src_ZPCc = [re2.src_Z, re2.src_P, re2.src_Cc].join("|");
  re2.src_ZCc = [re2.src_Z, re2.src_Cc].join("|");
  const text_separators = "[><｜]";
  re2.src_pseudo_letter = "(?:(?!" + text_separators + "|" + re2.src_ZPCc + ")" + re2.src_Any + ")";
  re2.src_ip4 = "(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
  re2.src_auth = "(?:(?:(?!" + re2.src_ZCc + "|[@/\\[\\]()]).)+@)?";
  re2.src_port = "(?::(?:6(?:[0-4]\\d{3}|5(?:[0-4]\\d{2}|5(?:[0-2]\\d|3[0-5])))|[1-5]?\\d{1,4}))?";
  re2.src_host_terminator = "(?=$|" + text_separators + "|" + re2.src_ZPCc + ")(?!" + (opts["---"] ? "-(?!--)|" : "-|") + "_|:\\d|\\.-|\\.(?!$|" + re2.src_ZPCc + "))";
  re2.src_path = "(?:[/?#](?:(?!" + re2.src_ZCc + "|" + text_separators + `|[()[\\]{}.,"'?!\\-;]).|\\[(?:(?!` + re2.src_ZCc + "|\\]).)*\\]|\\((?:(?!" + re2.src_ZCc + "|[)]).)*\\)|\\{(?:(?!" + re2.src_ZCc + '|[}]).)*\\}|\\"(?:(?!' + re2.src_ZCc + `|["]).)+\\"|\\'(?:(?!` + re2.src_ZCc + "|[']).)+\\'|\\'(?=" + re2.src_pseudo_letter + "|[-])|\\.{2,}[a-zA-Z0-9%/&]|\\.(?!" + re2.src_ZCc + "|[.]|$)|" + (opts["---"] ? "\\-(?!--(?:[^-]|$))(?:-*)|" : "\\-+|") + // allow `,,,` in paths
  ",(?!" + re2.src_ZCc + "|$)|;(?!" + re2.src_ZCc + "|$)|\\!+(?!" + re2.src_ZCc + "|[!]|$)|\\?(?!" + re2.src_ZCc + "|[?]|$))+|\\/)?";
  re2.src_email_name = '[\\-;:&=\\+\\$,\\.a-zA-Z0-9_][\\-;:&=\\+\\$,\\"\\.a-zA-Z0-9_]*';
  re2.src_xn = "xn--[a-z0-9\\-]{1,59}";
  re2.src_domain_root = // Allow letters & digits (http://test1)
  "(?:" + re2.src_xn + "|" + re2.src_pseudo_letter + "{1,63})";
  re2.src_domain = "(?:" + re2.src_xn + "|(?:" + re2.src_pseudo_letter + ")|(?:" + re2.src_pseudo_letter + "(?:-|" + re2.src_pseudo_letter + "){0,61}" + re2.src_pseudo_letter + "))";
  re2.src_host = "(?:(?:(?:(?:" + re2.src_domain + ")\\.)*" + re2.src_domain + "))";
  re2.tpl_host_fuzzy = "(?:" + re2.src_ip4 + "|(?:(?:(?:" + re2.src_domain + ")\\.)+(?:%TLDS%)))";
  re2.tpl_host_no_ip_fuzzy = "(?:(?:(?:" + re2.src_domain + ")\\.)+(?:%TLDS%))";
  re2.src_host_strict = re2.src_host + re2.src_host_terminator;
  re2.tpl_host_fuzzy_strict = re2.tpl_host_fuzzy + re2.src_host_terminator;
  re2.src_host_port_strict = re2.src_host + re2.src_port + re2.src_host_terminator;
  re2.tpl_host_port_fuzzy_strict = re2.tpl_host_fuzzy + re2.src_port + re2.src_host_terminator;
  re2.tpl_host_port_no_ip_fuzzy_strict = re2.tpl_host_no_ip_fuzzy + re2.src_port + re2.src_host_terminator;
  re2.tpl_host_fuzzy_test = "localhost|www\\.|\\.\\d{1,3}\\.|(?:\\.(?:%TLDS%)(?:" + re2.src_ZPCc + "|>|$))";
  re2.tpl_email_fuzzy = "(^|" + text_separators + '|"|\\(|' + re2.src_ZCc + ")(" + re2.src_email_name + "@" + re2.tpl_host_fuzzy_strict + ")";
  re2.tpl_link_fuzzy = // Fuzzy link can't be prepended with .:/\- and non punctuation.
  // but can start with > (markdown blockquote)
  "(^|(?![.:/\\-_@])(?:[$+<=>^`|｜]|" + re2.src_ZPCc + "))((?![$+<=>^`|｜])" + re2.tpl_host_port_fuzzy_strict + re2.src_path + ")";
  re2.tpl_link_no_ip_fuzzy = // Fuzzy link can't be prepended with .:/\- and non punctuation.
  // but can start with > (markdown blockquote)
  "(^|(?![.:/\\-_@])(?:[$+<=>^`|｜]|" + re2.src_ZPCc + "))((?![$+<=>^`|｜])" + re2.tpl_host_port_no_ip_fuzzy_strict + re2.src_path + ")";
  return re2;
}
function assign(obj) {
  const sources = Array.prototype.slice.call(arguments, 1);
  sources.forEach(function(source2) {
    if (!source2) {
      return;
    }
    Object.keys(source2).forEach(function(key2) {
      obj[key2] = source2[key2];
    });
  });
  return obj;
}
function _class(obj) {
  return Object.prototype.toString.call(obj);
}
function isString(obj) {
  return _class(obj) === "[object String]";
}
function isObject(obj) {
  return _class(obj) === "[object Object]";
}
function isRegExp(obj) {
  return _class(obj) === "[object RegExp]";
}
function isFunction(obj) {
  return _class(obj) === "[object Function]";
}
function escapeRE(str) {
  return str.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");
}
const defaultOptions = {
  fuzzyLink: true,
  fuzzyEmail: true,
  fuzzyIP: false
};
function isOptionsObj(obj) {
  return Object.keys(obj || {}).reduce(function(acc, k) {
    return acc || defaultOptions.hasOwnProperty(k);
  }, false);
}
const defaultSchemas = {
  "http:": {
    validate: function(text2, pos2, self2) {
      const tail = text2.slice(pos2);
      if (!self2.re.http) {
        self2.re.http = new RegExp(
          "^\\/\\/" + self2.re.src_auth + self2.re.src_host_port_strict + self2.re.src_path,
          "i"
        );
      }
      if (self2.re.http.test(tail)) {
        return tail.match(self2.re.http)[0].length;
      }
      return 0;
    }
  },
  "https:": "http:",
  "ftp:": "http:",
  "//": {
    validate: function(text2, pos2, self2) {
      const tail = text2.slice(pos2);
      if (!self2.re.no_http) {
        self2.re.no_http = new RegExp(
          "^" + self2.re.src_auth + // Don't allow single-level domains, because of false positives like '//test'
          // with code comments
          "(?:localhost|(?:(?:" + self2.re.src_domain + ")\\.)+" + self2.re.src_domain_root + ")" + self2.re.src_port + self2.re.src_host_terminator + self2.re.src_path,
          "i"
        );
      }
      if (self2.re.no_http.test(tail)) {
        if (pos2 >= 3 && text2[pos2 - 3] === ":") {
          return 0;
        }
        if (pos2 >= 3 && text2[pos2 - 3] === "/") {
          return 0;
        }
        return tail.match(self2.re.no_http)[0].length;
      }
      return 0;
    }
  },
  "mailto:": {
    validate: function(text2, pos2, self2) {
      const tail = text2.slice(pos2);
      if (!self2.re.mailto) {
        self2.re.mailto = new RegExp(
          "^" + self2.re.src_email_name + "@" + self2.re.src_host_strict,
          "i"
        );
      }
      if (self2.re.mailto.test(tail)) {
        return tail.match(self2.re.mailto)[0].length;
      }
      return 0;
    }
  }
};
const tlds_2ch_src_re = "a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvwxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvxyz]|t[cdfghjklmnortvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]";
const tlds_default = "biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф".split("|");
function resetScanCache(self2) {
  self2.__index__ = -1;
  self2.__text_cache__ = "";
}
function createValidator(re2) {
  return function(text2, pos2) {
    const tail = text2.slice(pos2);
    if (re2.test(tail)) {
      return tail.match(re2)[0].length;
    }
    return 0;
  };
}
function createNormalizer() {
  return function(match3, self2) {
    self2.normalize(match3);
  };
}
function compile(self2) {
  const re2 = self2.re = reFactory(self2.__opts__);
  const tlds2 = self2.__tlds__.slice();
  self2.onCompile();
  if (!self2.__tlds_replaced__) {
    tlds2.push(tlds_2ch_src_re);
  }
  tlds2.push(re2.src_xn);
  re2.src_tlds = tlds2.join("|");
  function untpl(tpl) {
    return tpl.replace("%TLDS%", re2.src_tlds);
  }
  re2.email_fuzzy = RegExp(untpl(re2.tpl_email_fuzzy), "i");
  re2.link_fuzzy = RegExp(untpl(re2.tpl_link_fuzzy), "i");
  re2.link_no_ip_fuzzy = RegExp(untpl(re2.tpl_link_no_ip_fuzzy), "i");
  re2.host_fuzzy_test = RegExp(untpl(re2.tpl_host_fuzzy_test), "i");
  const aliases = [];
  self2.__compiled__ = {};
  function schemaError(name2, val) {
    throw new Error('(LinkifyIt) Invalid schema "' + name2 + '": ' + val);
  }
  Object.keys(self2.__schemas__).forEach(function(name2) {
    const val = self2.__schemas__[name2];
    if (val === null) {
      return;
    }
    const compiled = { validate: null, link: null };
    self2.__compiled__[name2] = compiled;
    if (isObject(val)) {
      if (isRegExp(val.validate)) {
        compiled.validate = createValidator(val.validate);
      } else if (isFunction(val.validate)) {
        compiled.validate = val.validate;
      } else {
        schemaError(name2, val);
      }
      if (isFunction(val.normalize)) {
        compiled.normalize = val.normalize;
      } else if (!val.normalize) {
        compiled.normalize = createNormalizer();
      } else {
        schemaError(name2, val);
      }
      return;
    }
    if (isString(val)) {
      aliases.push(name2);
      return;
    }
    schemaError(name2, val);
  });
  aliases.forEach(function(alias) {
    if (!self2.__compiled__[self2.__schemas__[alias]]) {
      return;
    }
    self2.__compiled__[alias].validate = self2.__compiled__[self2.__schemas__[alias]].validate;
    self2.__compiled__[alias].normalize = self2.__compiled__[self2.__schemas__[alias]].normalize;
  });
  self2.__compiled__[""] = { validate: null, normalize: createNormalizer() };
  const slist = Object.keys(self2.__compiled__).filter(function(name2) {
    return name2.length > 0 && self2.__compiled__[name2];
  }).map(escapeRE).join("|");
  self2.re.schema_test = RegExp("(^|(?!_)(?:[><｜]|" + re2.src_ZPCc + "))(" + slist + ")", "i");
  self2.re.schema_search = RegExp("(^|(?!_)(?:[><｜]|" + re2.src_ZPCc + "))(" + slist + ")", "ig");
  self2.re.schema_at_start = RegExp("^" + self2.re.schema_search.source, "i");
  self2.re.pretest = RegExp(
    "(" + self2.re.schema_test.source + ")|(" + self2.re.host_fuzzy_test.source + ")|@",
    "i"
  );
  resetScanCache(self2);
}
function Match$1(self2, shift) {
  const start2 = self2.__index__;
  const end2 = self2.__last_index__;
  const text2 = self2.__text_cache__.slice(start2, end2);
  this.schema = self2.__schema__.toLowerCase();
  this.index = start2 + shift;
  this.lastIndex = end2 + shift;
  this.raw = text2;
  this.text = text2;
  this.url = text2;
}
function createMatch(self2, shift) {
  const match3 = new Match$1(self2, shift);
  self2.__compiled__[match3.schema].normalize(match3, self2);
  return match3;
}
function LinkifyIt(schemas, options) {
  if (!(this instanceof LinkifyIt)) {
    return new LinkifyIt(schemas, options);
  }
  if (!options) {
    if (isOptionsObj(schemas)) {
      options = schemas;
      schemas = {};
    }
  }
  this.__opts__ = assign({}, defaultOptions, options);
  this.__index__ = -1;
  this.__last_index__ = -1;
  this.__schema__ = "";
  this.__text_cache__ = "";
  this.__schemas__ = assign({}, defaultSchemas, schemas);
  this.__compiled__ = {};
  this.__tlds__ = tlds_default;
  this.__tlds_replaced__ = false;
  this.re = {};
  compile(this);
}
LinkifyIt.prototype.add = function add(schema, definition) {
  this.__schemas__[schema] = definition;
  compile(this);
  return this;
};
LinkifyIt.prototype.set = function set2(options) {
  this.__opts__ = assign(this.__opts__, options);
  return this;
};
LinkifyIt.prototype.test = function test(text2) {
  this.__text_cache__ = text2;
  this.__index__ = -1;
  if (!text2.length) {
    return false;
  }
  let m, ml, me, len, shift, next, re2, tld_pos, at_pos;
  if (this.re.schema_test.test(text2)) {
    re2 = this.re.schema_search;
    re2.lastIndex = 0;
    while ((m = re2.exec(text2)) !== null) {
      len = this.testSchemaAt(text2, m[2], re2.lastIndex);
      if (len) {
        this.__schema__ = m[2];
        this.__index__ = m.index + m[1].length;
        this.__last_index__ = m.index + m[0].length + len;
        break;
      }
    }
  }
  if (this.__opts__.fuzzyLink && this.__compiled__["http:"]) {
    tld_pos = text2.search(this.re.host_fuzzy_test);
    if (tld_pos >= 0) {
      if (this.__index__ < 0 || tld_pos < this.__index__) {
        if ((ml = text2.match(this.__opts__.fuzzyIP ? this.re.link_fuzzy : this.re.link_no_ip_fuzzy)) !== null) {
          shift = ml.index + ml[1].length;
          if (this.__index__ < 0 || shift < this.__index__) {
            this.__schema__ = "";
            this.__index__ = shift;
            this.__last_index__ = ml.index + ml[0].length;
          }
        }
      }
    }
  }
  if (this.__opts__.fuzzyEmail && this.__compiled__["mailto:"]) {
    at_pos = text2.indexOf("@");
    if (at_pos >= 0) {
      if ((me = text2.match(this.re.email_fuzzy)) !== null) {
        shift = me.index + me[1].length;
        next = me.index + me[0].length;
        if (this.__index__ < 0 || shift < this.__index__ || shift === this.__index__ && next > this.__last_index__) {
          this.__schema__ = "mailto:";
          this.__index__ = shift;
          this.__last_index__ = next;
        }
      }
    }
  }
  return this.__index__ >= 0;
};
LinkifyIt.prototype.pretest = function pretest(text2) {
  return this.re.pretest.test(text2);
};
LinkifyIt.prototype.testSchemaAt = function testSchemaAt(text2, schema, pos2) {
  if (!this.__compiled__[schema.toLowerCase()]) {
    return 0;
  }
  return this.__compiled__[schema.toLowerCase()].validate(text2, pos2, this);
};
LinkifyIt.prototype.match = function match2(text2) {
  const result2 = [];
  let shift = 0;
  if (this.__index__ >= 0 && this.__text_cache__ === text2) {
    result2.push(createMatch(this, shift));
    shift = this.__last_index__;
  }
  let tail = shift ? text2.slice(shift) : text2;
  while (this.test(tail)) {
    result2.push(createMatch(this, shift));
    tail = tail.slice(this.__last_index__);
    shift += this.__last_index__;
  }
  if (result2.length) {
    return result2;
  }
  return null;
};
LinkifyIt.prototype.matchAtStart = function matchAtStart(text2) {
  this.__text_cache__ = text2;
  this.__index__ = -1;
  if (!text2.length) return null;
  const m = this.re.schema_at_start.exec(text2);
  if (!m) return null;
  const len = this.testSchemaAt(text2, m[2], m[0].length);
  if (!len) return null;
  this.__schema__ = m[2];
  this.__index__ = m.index + m[1].length;
  this.__last_index__ = m.index + m[0].length + len;
  return createMatch(this, 0);
};
LinkifyIt.prototype.tlds = function tlds(list2, keepOld) {
  list2 = Array.isArray(list2) ? list2 : [list2];
  if (!keepOld) {
    this.__tlds__ = list2.slice();
    this.__tlds_replaced__ = true;
    compile(this);
    return this;
  }
  this.__tlds__ = this.__tlds__.concat(list2).sort().filter(function(el, idx, arr) {
    return el !== arr[idx - 1];
  }).reverse();
  compile(this);
  return this;
};
LinkifyIt.prototype.normalize = function normalize2(match3) {
  if (!match3.schema) {
    match3.url = "http://" + match3.url;
  }
  if (match3.schema === "mailto:" && !/^mailto:/i.test(match3.url)) {
    match3.url = "mailto:" + match3.url;
  }
};
LinkifyIt.prototype.onCompile = function onCompile() {
};
const maxInt = 2147483647;
const base = 36;
const tMin = 1;
const tMax = 26;
const skew = 38;
const damp = 700;
const initialBias = 72;
const initialN = 128;
const delimiter = "-";
const regexPunycode = /^xn--/;
const regexNonASCII = /[^\0-\x7F]/;
const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g;
const errors = {
  "overflow": "Overflow: input needs wider integers to process",
  "not-basic": "Illegal input >= 0x80 (not a basic code point)",
  "invalid-input": "Invalid input"
};
const baseMinusTMin = base - tMin;
const floor = Math.floor;
const stringFromCharCode = String.fromCharCode;
function error$3(type) {
  throw new RangeError(errors[type]);
}
function map(array2, callback) {
  const result2 = [];
  let length2 = array2.length;
  while (length2--) {
    result2[length2] = callback(array2[length2]);
  }
  return result2;
}
function mapDomain(domain, callback) {
  const parts = domain.split("@");
  let result2 = "";
  if (parts.length > 1) {
    result2 = parts[0] + "@";
    domain = parts[1];
  }
  domain = domain.replace(regexSeparators, ".");
  const labels = domain.split(".");
  const encoded = map(labels, callback).join(".");
  return result2 + encoded;
}
function ucs2decode(string2) {
  const output2 = [];
  let counter2 = 0;
  const length2 = string2.length;
  while (counter2 < length2) {
    const value2 = string2.charCodeAt(counter2++);
    if (value2 >= 55296 && value2 <= 56319 && counter2 < length2) {
      const extra = string2.charCodeAt(counter2++);
      if ((extra & 64512) == 56320) {
        output2.push(((value2 & 1023) << 10) + (extra & 1023) + 65536);
      } else {
        output2.push(value2);
        counter2--;
      }
    } else {
      output2.push(value2);
    }
  }
  return output2;
}
const ucs2encode = (codePoints) => String.fromCodePoint(...codePoints);
const basicToDigit = function(codePoint) {
  if (codePoint >= 48 && codePoint < 58) {
    return 26 + (codePoint - 48);
  }
  if (codePoint >= 65 && codePoint < 91) {
    return codePoint - 65;
  }
  if (codePoint >= 97 && codePoint < 123) {
    return codePoint - 97;
  }
  return base;
};
const digitToBasic = function(digit, flag) {
  return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
};
const adapt = function(delta, numPoints, firstTime) {
  let k = 0;
  delta = firstTime ? floor(delta / damp) : delta >> 1;
  delta += floor(delta / numPoints);
  for (; delta > baseMinusTMin * tMax >> 1; k += base) {
    delta = floor(delta / baseMinusTMin);
  }
  return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
};
const decode = function(input2) {
  const output2 = [];
  const inputLength = input2.length;
  let i2 = 0;
  let n2 = initialN;
  let bias = initialBias;
  let basic = input2.lastIndexOf(delimiter);
  if (basic < 0) {
    basic = 0;
  }
  for (let j2 = 0; j2 < basic; ++j2) {
    if (input2.charCodeAt(j2) >= 128) {
      error$3("not-basic");
    }
    output2.push(input2.charCodeAt(j2));
  }
  for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; ) {
    const oldi = i2;
    for (let w2 = 1, k = base; ; k += base) {
      if (index >= inputLength) {
        error$3("invalid-input");
      }
      const digit = basicToDigit(input2.charCodeAt(index++));
      if (digit >= base) {
        error$3("invalid-input");
      }
      if (digit > floor((maxInt - i2) / w2)) {
        error$3("overflow");
      }
      i2 += digit * w2;
      const t2 = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
      if (digit < t2) {
        break;
      }
      const baseMinusT = base - t2;
      if (w2 > floor(maxInt / baseMinusT)) {
        error$3("overflow");
      }
      w2 *= baseMinusT;
    }
    const out = output2.length + 1;
    bias = adapt(i2 - oldi, out, oldi == 0);
    if (floor(i2 / out) > maxInt - n2) {
      error$3("overflow");
    }
    n2 += floor(i2 / out);
    i2 %= out;
    output2.splice(i2++, 0, n2);
  }
  return String.fromCodePoint(...output2);
};
const encode = function(input2) {
  const output2 = [];
  input2 = ucs2decode(input2);
  const inputLength = input2.length;
  let n2 = initialN;
  let delta = 0;
  let bias = initialBias;
  for (const currentValue of input2) {
    if (currentValue < 128) {
      output2.push(stringFromCharCode(currentValue));
    }
  }
  const basicLength = output2.length;
  let handledCPCount = basicLength;
  if (basicLength) {
    output2.push(delimiter);
  }
  while (handledCPCount < inputLength) {
    let m = maxInt;
    for (const currentValue of input2) {
      if (currentValue >= n2 && currentValue < m) {
        m = currentValue;
      }
    }
    const handledCPCountPlusOne = handledCPCount + 1;
    if (m - n2 > floor((maxInt - delta) / handledCPCountPlusOne)) {
      error$3("overflow");
    }
    delta += (m - n2) * handledCPCountPlusOne;
    n2 = m;
    for (const currentValue of input2) {
      if (currentValue < n2 && ++delta > maxInt) {
        error$3("overflow");
      }
      if (currentValue === n2) {
        let q = delta;
        for (let k = base; ; k += base) {
          const t2 = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
          if (q < t2) {
            break;
          }
          const qMinusT = q - t2;
          const baseMinusT = base - t2;
          output2.push(
            stringFromCharCode(digitToBasic(t2 + qMinusT % baseMinusT, 0))
          );
          q = floor(qMinusT / baseMinusT);
        }
        output2.push(stringFromCharCode(digitToBasic(q, 0)));
        bias = adapt(delta, handledCPCountPlusOne, handledCPCount === basicLength);
        delta = 0;
        ++handledCPCount;
      }
    }
    ++delta;
    ++n2;
  }
  return output2.join("");
};
const toUnicode = function(input2) {
  return mapDomain(input2, function(string2) {
    return regexPunycode.test(string2) ? decode(string2.slice(4).toLowerCase()) : string2;
  });
};
const toASCII = function(input2) {
  return mapDomain(input2, function(string2) {
    return regexNonASCII.test(string2) ? "xn--" + encode(string2) : string2;
  });
};
const punycode = {
  /**
   * A string representing the current Punycode.js version number.
   * @memberOf punycode
   * @type String
   */
  "version": "2.3.1",
  /**
   * An object of methods to convert from JavaScript's internal character
   * representation (UCS-2) to Unicode code points, and back.
   * @see <https://mathiasbynens.be/notes/javascript-encoding>
   * @memberOf punycode
   * @type Object
   */
  "ucs2": {
    "decode": ucs2decode,
    "encode": ucs2encode
  },
  "decode": decode,
  "encode": encode,
  "toASCII": toASCII,
  "toUnicode": toUnicode
};
const cfg_default = {
  options: {
    // Enable HTML tags in source
    html: false,
    // Use '/' to close single tags (<br />)
    xhtmlOut: false,
    // Convert '\n' in paragraphs into <br>
    breaks: false,
    // CSS language prefix for fenced blocks
    langPrefix: "language-",
    // autoconvert URL-like texts to links
    linkify: false,
    // Enable some language-neutral replacements + quotes beautification
    typographer: false,
    // Double + single quotes replacement pairs, when typographer enabled,
    // and smartquotes on. Could be either a String or an Array.
    //
    // For example, you can use '«»„“' for Russian, '„“‚‘' for German,
    // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
    quotes: "“”‘’",
    /* “”‘’ */
    // Highlighter function. Should return escaped HTML,
    // or '' if the source string is not changed and should be escaped externaly.
    // If result starts with <pre... internal wrapper is skipped.
    //
    // function (/*str, lang*/) { return ''; }
    //
    highlight: null,
    // Internal protection, recursion limit
    maxNesting: 100
  },
  components: {
    core: {},
    block: {},
    inline: {}
  }
};
const cfg_zero = {
  options: {
    // Enable HTML tags in source
    html: false,
    // Use '/' to close single tags (<br />)
    xhtmlOut: false,
    // Convert '\n' in paragraphs into <br>
    breaks: false,
    // CSS language prefix for fenced blocks
    langPrefix: "language-",
    // autoconvert URL-like texts to links
    linkify: false,
    // Enable some language-neutral replacements + quotes beautification
    typographer: false,
    // Double + single quotes replacement pairs, when typographer enabled,
    // and smartquotes on. Could be either a String or an Array.
    //
    // For example, you can use '«»„“' for Russian, '„“‚‘' for German,
    // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
    quotes: "“”‘’",
    /* “”‘’ */
    // Highlighter function. Should return escaped HTML,
    // or '' if the source string is not changed and should be escaped externaly.
    // If result starts with <pre... internal wrapper is skipped.
    //
    // function (/*str, lang*/) { return ''; }
    //
    highlight: null,
    // Internal protection, recursion limit
    maxNesting: 20
  },
  components: {
    core: {
      rules: [
        "normalize",
        "block",
        "inline",
        "text_join"
      ]
    },
    block: {
      rules: [
        "paragraph"
      ]
    },
    inline: {
      rules: [
        "text"
      ],
      rules2: [
        "balance_pairs",
        "fragments_join"
      ]
    }
  }
};
const cfg_commonmark = {
  options: {
    // Enable HTML tags in source
    html: true,
    // Use '/' to close single tags (<br />)
    xhtmlOut: true,
    // Convert '\n' in paragraphs into <br>
    breaks: false,
    // CSS language prefix for fenced blocks
    langPrefix: "language-",
    // autoconvert URL-like texts to links
    linkify: false,
    // Enable some language-neutral replacements + quotes beautification
    typographer: false,
    // Double + single quotes replacement pairs, when typographer enabled,
    // and smartquotes on. Could be either a String or an Array.
    //
    // For example, you can use '«»„“' for Russian, '„“‚‘' for German,
    // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
    quotes: "“”‘’",
    /* “”‘’ */
    // Highlighter function. Should return escaped HTML,
    // or '' if the source string is not changed and should be escaped externaly.
    // If result starts with <pre... internal wrapper is skipped.
    //
    // function (/*str, lang*/) { return ''; }
    //
    highlight: null,
    // Internal protection, recursion limit
    maxNesting: 20
  },
  components: {
    core: {
      rules: [
        "normalize",
        "block",
        "inline",
        "text_join"
      ]
    },
    block: {
      rules: [
        "blockquote",
        "code",
        "fence",
        "heading",
        "hr",
        "html_block",
        "lheading",
        "list",
        "reference",
        "paragraph"
      ]
    },
    inline: {
      rules: [
        "autolink",
        "backticks",
        "emphasis",
        "entity",
        "escape",
        "html_inline",
        "image",
        "link",
        "newline",
        "text"
      ],
      rules2: [
        "balance_pairs",
        "emphasis",
        "fragments_join"
      ]
    }
  }
};
const config = {
  default: cfg_default,
  zero: cfg_zero,
  commonmark: cfg_commonmark
};
const BAD_PROTO_RE = /^(vbscript|javascript|file|data):/;
const GOOD_DATA_RE = /^data:image\/(gif|png|jpeg|webp);/;
function validateLink(url) {
  const str = url.trim().toLowerCase();
  return BAD_PROTO_RE.test(str) ? GOOD_DATA_RE.test(str) : true;
}
const RECODE_HOSTNAME_FOR = ["http:", "https:", "mailto:"];
function normalizeLink(url) {
  const parsed = urlParse(url, true);
  if (parsed.hostname) {
    if (!parsed.protocol || RECODE_HOSTNAME_FOR.indexOf(parsed.protocol) >= 0) {
      try {
        parsed.hostname = punycode.toASCII(parsed.hostname);
      } catch (er2) {
      }
    }
  }
  return encode$1(format$1(parsed));
}
function normalizeLinkText(url) {
  const parsed = urlParse(url, true);
  if (parsed.hostname) {
    if (!parsed.protocol || RECODE_HOSTNAME_FOR.indexOf(parsed.protocol) >= 0) {
      try {
        parsed.hostname = punycode.toUnicode(parsed.hostname);
      } catch (er2) {
      }
    }
  }
  return decode$1(format$1(parsed), decode$1.defaultChars + "%");
}
function MarkdownIt(presetName, options) {
  if (!(this instanceof MarkdownIt)) {
    return new MarkdownIt(presetName, options);
  }
  if (!options) {
    if (!isString$1(presetName)) {
      options = presetName || {};
      presetName = "default";
    }
  }
  this.inline = new ParserInline();
  this.block = new ParserBlock();
  this.core = new Core$1();
  this.renderer = new Renderer();
  this.linkify = new LinkifyIt();
  this.validateLink = validateLink;
  this.normalizeLink = normalizeLink;
  this.normalizeLinkText = normalizeLinkText;
  this.utils = utils;
  this.helpers = assign$1({}, helpers);
  this.options = {};
  this.configure(presetName);
  if (options) {
    this.set(options);
  }
}
MarkdownIt.prototype.set = function(options) {
  assign$1(this.options, options);
  return this;
};
MarkdownIt.prototype.configure = function(presets) {
  const self2 = this;
  if (isString$1(presets)) {
    const presetName = presets;
    presets = config[presetName];
    if (!presets) {
      throw new Error('Wrong `markdown-it` preset "' + presetName + '", check name');
    }
  }
  if (!presets) {
    throw new Error("Wrong `markdown-it` preset, can't be empty");
  }
  if (presets.options) {
    self2.set(presets.options);
  }
  if (presets.components) {
    Object.keys(presets.components).forEach(function(name2) {
      if (presets.components[name2].rules) {
        self2[name2].ruler.enableOnly(presets.components[name2].rules);
      }
      if (presets.components[name2].rules2) {
        self2[name2].ruler2.enableOnly(presets.components[name2].rules2);
      }
    });
  }
  return this;
};
MarkdownIt.prototype.enable = function(list2, ignoreInvalid) {
  let result2 = [];
  if (!Array.isArray(list2)) {
    list2 = [list2];
  }
  ["core", "block", "inline"].forEach(function(chain) {
    result2 = result2.concat(this[chain].ruler.enable(list2, true));
  }, this);
  result2 = result2.concat(this.inline.ruler2.enable(list2, true));
  const missed = list2.filter(function(name2) {
    return result2.indexOf(name2) < 0;
  });
  if (missed.length && !ignoreInvalid) {
    throw new Error("MarkdownIt. Failed to enable unknown rule(s): " + missed);
  }
  return this;
};
MarkdownIt.prototype.disable = function(list2, ignoreInvalid) {
  let result2 = [];
  if (!Array.isArray(list2)) {
    list2 = [list2];
  }
  ["core", "block", "inline"].forEach(function(chain) {
    result2 = result2.concat(this[chain].ruler.disable(list2, true));
  }, this);
  result2 = result2.concat(this.inline.ruler2.disable(list2, true));
  const missed = list2.filter(function(name2) {
    return result2.indexOf(name2) < 0;
  });
  if (missed.length && !ignoreInvalid) {
    throw new Error("MarkdownIt. Failed to disable unknown rule(s): " + missed);
  }
  return this;
};
MarkdownIt.prototype.use = function(plugin) {
  const args2 = [this].concat(Array.prototype.slice.call(arguments, 1));
  plugin.apply(plugin, args2);
  return this;
};
MarkdownIt.prototype.parse = function(src, env) {
  if (typeof src !== "string") {
    throw new Error("Input data should be a String");
  }
  const state = new this.core.State(src, this, env);
  this.core.process(state);
  return state.tokens;
};
MarkdownIt.prototype.render = function(src, env) {
  env = env || {};
  return this.renderer.render(this.parse(src, env), this.options, env);
};
MarkdownIt.prototype.parseInline = function(src, env) {
  const state = new this.core.State(src, this, env);
  state.inlineMode = true;
  this.core.process(state);
  return state.tokens;
};
MarkdownIt.prototype.renderInline = function(src, env) {
  env = env || {};
  return this.renderer.render(this.parseInline(src, env), this.options, env);
};
const scriptRel = "modulepreload";
const assetsURL = function(dep, importerUrl) {
  return new URL(dep, importerUrl).href;
};
const seen = {};
const __vitePreload = function preload(baseModule, deps, importerUrl) {
  let promise = Promise.resolve();
  if (deps && deps.length > 0) {
    let allSettled = function(promises$2) {
      return Promise.all(promises$2.map((p) => Promise.resolve(p).then((value$1) => ({
        status: "fulfilled",
        value: value$1
      }), (reason) => ({
        status: "rejected",
        reason
      }))));
    };
    const links2 = document.getElementsByTagName("link");
    const cspNonceMeta = document.querySelector("meta[property=csp-nonce]");
    const cspNonce = cspNonceMeta?.nonce || cspNonceMeta?.getAttribute("nonce");
    promise = allSettled(deps.map((dep) => {
      dep = assetsURL(dep, importerUrl);
      if (dep in seen) return;
      seen[dep] = true;
      const isCss = dep.endsWith(".css");
      const cssSelector = isCss ? '[rel="stylesheet"]' : "";
      if (!!importerUrl) for (let i$1 = links2.length - 1; i$1 >= 0; i$1--) {
        const link$12 = links2[i$1];
        if (link$12.href === dep && (!isCss || link$12.rel === "stylesheet")) return;
      }
      else if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) return;
      const link2 = document.createElement("link");
      link2.rel = isCss ? "stylesheet" : scriptRel;
      if (!isCss) link2.as = "script";
      link2.crossOrigin = "";
      link2.href = dep;
      if (cspNonce) link2.setAttribute("nonce", cspNonce);
      document.head.appendChild(link2);
      if (isCss) return new Promise((res, rej) => {
        link2.addEventListener("load", res);
        link2.addEventListener("error", () => rej(/* @__PURE__ */ new Error(`Unable to preload CSS for ${dep}`)));
      });
    }));
  }
  function handlePreloadError(err$2) {
    const e$1 = new Event("vite:preloadError", { cancelable: true });
    e$1.payload = err$2;
    window.dispatchEvent(e$1);
    if (!e$1.defaultPrevented) throw err$2;
  }
  return promise.then((res) => {
    for (const item2 of res || []) {
      if (item2.status !== "rejected") continue;
      handlePreloadError(item2.reason);
    }
    return baseModule().catch(handlePreloadError);
  });
};
const t = { "xmldom-sre": await __vitePreload(() => import("./lib-CBtriEt5.js"), true ? __vite__mapDeps([0,1]) : void 0, import.meta.url).then(l()), "wicked-good-xpath": await __vitePreload(() => import("./wgxpath.install-node-Csk64Aj9.js"), true ? __vite__mapDeps([2,1]) : void 0, import.meta.url).then(l()), commander: {}, fs: {} }, n = (e) => t[e];
globalThis.MathJax_require = n;
const r = { "mathjax/es5/adaptors/liteDOM.js": () => __vitePreload(() => import("./liteDOM-Cp0aN3bP.js").then((n2) => n2.l), true ? __vite__mapDeps([3,4]) : void 0, import.meta.url), "xyjax/build/xypic.js": () => __vitePreload(() => import("./xypic-DrMJn58R.js").then((n2) => n2.x), true ? __vite__mapDeps([5,4]) : void 0, import.meta.url) }, i = (e) => r[e]();
globalThis.MathJax = { loader: { source: {}, require: i, load: [`adaptors/liteDOM`, `[custom]/xypic`], paths: { mathjax: `mathjax/es5`, custom: `xyjax/build` } }, tex: { packages: { "[+]": [`xypic`] } }, svg: { fontCache: `none` }, startup: { typeset: false } }, await __vitePreload(() => import("./tex-svg-full-BI3fonbT.js").then((n2) => n2.t), true ? __vite__mapDeps([6,4]) : void 0, import.meta.url), await globalThis.MathJax.startup?.promise;
function a(e = ``, t2 = {}) {
  let n2 = globalThis.MathJax.tex2svg(e, { display: true, ...t2 }), r2 = globalThis.MathJax.startup.adaptor, i2 = r2.textContent(globalThis.MathJax.svgStylesheet()), a2 = r2.outerHTML(n2), o = `mjx-${Math.random().toString(16).substring(8)}`;
  return `
    <span id="${o}">
      <style>
      #${o}{
        display:contents;
        mjx-assistive-mml {
          user-select: text !important;
          clip: auto !important;
          color: rgba(0,0,0,0);
        }
        ${i2}
      }
      </style>
      ${a2}
    </span>
  `;
}
const import_mathxyjax3 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  tex2svgHtml: a
}, Symbol.toStringTag, { value: "Module" }));
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __esm = (fn3, res) => function() {
  return fn3 && (res = (0, fn3[__getOwnPropNames(fn3)[0]])(fn3 = 0)), res;
};
var __commonJS = (cb, mod2) => function() {
  return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports;
};
var __copyProps = (to2, from2, except2, desc) => {
  if (from2 && typeof from2 === "object" || typeof from2 === "function") for (var keys2 = __getOwnPropNames(from2), i2 = 0, n2 = keys2.length, key2; i2 < n2; i2++) {
    key2 = keys2[i2];
    if (!__hasOwnProp.call(to2, key2) && key2 !== except2) __defProp(to2, key2, {
      get: ((k) => from2[k]).bind(null, key2),
      enumerable: !(desc = __getOwnPropDesc(from2, key2)) || desc.enumerable
    });
  }
  return to2;
};
var __reExport = (target, mod2, secondTarget) => (__copyProps(target, mod2, "default"), secondTarget);
var mathjax_exports = {};
__reExport(mathjax_exports, import_mathxyjax3);
var init_mathjax = __esm({ "src/mathjax.mts": (() => {
}) });
var require_src = /* @__PURE__ */ __commonJS({ "src/index.ts": ((exports2, module) => {
  init_mathjax();
  function isValidDelim(state, pos2) {
    let max2 = state.posMax, can_open = true, can_close = true;
    const prevChar = pos2 > 0 ? state.src.charCodeAt(pos2 - 1) : -1, nextChar = pos2 + 1 <= max2 ? state.src.charCodeAt(pos2 + 1) : -1;
    if (prevChar === 32 || prevChar === 9 || nextChar >= 48 && nextChar <= 57) can_close = false;
    if (nextChar === 32 || nextChar === 9) can_open = false;
    return {
      can_open,
      can_close
    };
  }
  function math_inline(state, silent) {
    if (state.src[state.pos] !== "$") return false;
    let res = isValidDelim(state, state.pos);
    if (!res.can_open) {
      if (!silent) state.pending += "$";
      state.pos += 1;
      return true;
    }
    const start2 = state.pos + 1;
    let match3 = start2;
    while ((match3 = state.src.indexOf("$", match3)) !== -1) {
      let pos2 = match3 - 1;
      while (state.src[pos2] === "\\") pos2 -= 1;
      if ((match3 - pos2) % 2 == 1) break;
      match3 += 1;
    }
    if (match3 === -1) {
      if (!silent) state.pending += "$";
      state.pos = start2;
      return true;
    }
    if (match3 - start2 === 0) {
      if (!silent) state.pending += "$$";
      state.pos = start2 + 1;
      return true;
    }
    res = isValidDelim(state, match3);
    if (!res.can_close) {
      if (!silent) state.pending += "$";
      state.pos = start2;
      return true;
    }
    if (!silent) {
      const token2 = state.push("math_inline", "math", 0);
      token2.markup = "$";
      token2.content = state.src.slice(start2, match3);
    }
    state.pos = match3 + 1;
    return true;
  }
  function math_block(state, start2, end2, silent) {
    let next, lastPos;
    let found = false, pos2 = state.bMarks[start2] + state.tShift[start2], max2 = state.eMarks[start2], lastLine = "";
    if (pos2 + 2 > max2) return false;
    if (state.src.slice(pos2, pos2 + 2) !== "$$") return false;
    pos2 += 2;
    let firstLine = state.src.slice(pos2, max2);
    if (silent) return true;
    if (firstLine.trim().slice(-2) === "$$") {
      firstLine = firstLine.trim().slice(0, -2);
      found = true;
    }
    for (next = start2; !found; ) {
      next++;
      if (next >= end2) break;
      pos2 = state.bMarks[next] + state.tShift[next];
      max2 = state.eMarks[next];
      if (pos2 < max2 && state.tShift[next] < state.blkIndent) break;
      if (state.src.slice(pos2, max2).trim().slice(-2) === "$$") {
        lastPos = state.src.slice(0, max2).lastIndexOf("$$");
        lastLine = state.src.slice(pos2, lastPos);
        found = true;
      }
    }
    state.line = next + 1;
    const token2 = state.push("math_block", "math", 0);
    token2.block = true;
    token2.content = (firstLine && firstLine.trim() ? firstLine + "\n" : "") + state.getLines(start2 + 1, next, state.tShift[start2], true) + (lastLine && lastLine.trim() ? lastLine : "");
    token2.map = [start2, state.line];
    token2.markup = "$$";
    return true;
  }
  const plugin = (md) => {
    md.inline.ruler.after("escape", "math_inline", math_inline);
    md.block.ruler.after("blockquote", "math_block", math_block, { alt: [
      "paragraph",
      "reference",
      "blockquote",
      "list"
    ] });
    md.renderer.rules.math_inline = function(tokens, idx) {
      return mathjax_exports.tex2svgHtml(tokens[idx].content, { display: false });
    };
    md.renderer.rules.math_block = function(tokens, idx) {
      return mathjax_exports.tex2svgHtml(tokens[idx].content, { display: true });
    };
  };
  plugin.default = plugin;
  module.exports = plugin;
}) });
const markdownitMathjax3 = require_src();
const MarkdownDivComponent = reactExports.forwardRef(
  ({ markdown, omitMedia, style: style2, className: className2, postProcess: postProcess2 }, ref2) => {
    const cacheKey = `${markdown}:${omitMedia ? "1" : "0"}`;
    const cachedHtml = renderCache.get(cacheKey);
    const [renderedHtml, setRenderedHtml] = reactExports.useState(() => {
      if (cachedHtml) {
        return cachedHtml;
      }
      return markdown.replace(/\n/g, "<br/>");
    });
    reactExports.useEffect(() => {
      if (cachedHtml) {
        if (renderedHtml !== cachedHtml) {
          reactExports.startTransition(() => {
            setRenderedHtml(cachedHtml);
          });
        }
        return;
      }
      setRenderedHtml(markdown.replace(/\n/g, "<br/>"));
      const { promise, cancel } = renderQueue.enqueue(async () => {
        const protectedContent = protectBackslashesInLatex(markdown);
        const escaped = escapeHtmlCharacters(protectedContent);
        const preRendered = preRenderText(escaped);
        const protectedText = protectMarkdown(preRendered);
        const preparedForMarkdown = restoreBackslashesForLatex(protectedText);
        let html = preparedForMarkdown;
        try {
          const md = omitMedia ? mdInstanceNoMedia : mdInstance;
          html = md.render(preparedForMarkdown);
        } catch (ex) {
          console.log("Unable to markdown render content");
          console.error(ex);
        }
        const unescaped = unprotectMarkdown(html);
        const finalContent = unescapeCodeHtmlEntities(unescaped);
        const processedContent = postProcess2 ? postProcess2(finalContent) : finalContent;
        const withSup = unescapeSupHtmlEntities(processedContent);
        return Promise.resolve(withSup);
      });
      promise.then((result2) => {
        if (renderCache.size >= MAX_CACHE_SIZE) {
          const firstKey = renderCache.keys().next().value;
          if (firstKey) {
            renderCache.delete(firstKey);
          }
        }
        renderCache.set(cacheKey, result2);
        reactExports.startTransition(() => {
          setRenderedHtml(result2);
        });
      }).catch((error2) => {
        console.error("Markdown rendering error:", error2);
      });
      return () => {
        cancel();
      };
    }, [markdown, omitMedia, cachedHtml, renderedHtml]);
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "div",
      {
        ref: ref2,
        dangerouslySetInnerHTML: { __html: renderedHtml },
        style: style2,
        className: clsx(className2, "markdown-content")
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/MarkdownDiv.tsx",
        lineNumber: 123,
        columnNumber: 7
      },
      void 0
    );
  }
);
const MarkdownDiv = reactExports.memo(MarkdownDivComponent);
const renderCache = /* @__PURE__ */ new Map();
const MAX_CACHE_SIZE = 500;
const mdInstance = MarkdownIt({ breaks: true, html: true }).use(
  markdownitMathjax3
);
const mdInstanceNoMedia = MarkdownIt({ breaks: true, html: true }).use(markdownitMathjax3).disable(["image"]);
class MarkdownRenderQueue {
  queue = [];
  activeCount = 0;
  maxConcurrent;
  constructor(maxConcurrent = 10) {
    this.maxConcurrent = maxConcurrent;
  }
  enqueue(task) {
    let cancelled = false;
    const promise = new Promise((resolve2, reject) => {
      const wrappedTask = async () => {
        if (cancelled) {
          return;
        }
        try {
          const result2 = await task();
          if (!cancelled) {
            resolve2(result2);
          }
        } catch (error2) {
          if (!cancelled) {
            reject(error2 instanceof Error ? error2 : new Error(String(error2)));
          }
        }
      };
      const queueTask = {
        task: wrappedTask,
        cancelled: false
      };
      this.queue.push(queueTask);
      void this.processQueue();
    });
    const cancel = () => {
      cancelled = true;
      const index = this.queue.findIndex((t2) => !t2.cancelled);
      if (index !== -1 && this.queue[index]) {
        this.queue[index].cancelled = true;
      }
    };
    return { promise, cancel };
  }
  async processQueue() {
    if (this.activeCount >= this.maxConcurrent || this.queue.length === 0) {
      return;
    }
    let queueTask;
    while (this.queue.length > 0) {
      const task = this.queue.shift();
      if (task && !task.cancelled) {
        queueTask = task;
        break;
      }
    }
    if (!queueTask) {
      return;
    }
    this.activeCount++;
    try {
      await queueTask.task();
    } finally {
      this.activeCount--;
      void this.processQueue();
    }
  }
}
const renderQueue = new MarkdownRenderQueue(10);
const kLetterListPattern = /^([a-zA-Z][).]\s.*?)$/gm;
const kCommonmarkReferenceLinkPattern = /\[([^\]]*)\]: (?!http)(.*)/g;
const protectBackslashesInLatex = (content2) => {
  if (!content2) return content2;
  try {
    const inlineRegex = /\$(.*?)\$/g;
    const blockRegex = /\$\$([\s\S]*?)\$\$/g;
    let result2 = content2.replace(inlineRegex, (_match, latex) => {
      const protectedTex = latex.replace(/\\/g, "___LATEX_BACKSLASH___").replace(/</g, "___LATEX_LT___").replace(/>/g, "___LATEX_GT___").replace(/&/g, "___LATEX_AMP___").replace(/'/g, "___LATEX_APOS___").replace(/"/g, "___LATEX_QUOT___");
      return `$${protectedTex}$`;
    });
    result2 = result2.replace(blockRegex, (_match, latex) => {
      const protectedTex = latex.replace(/\\/g, "___LATEX_BACKSLASH___").replace(/</g, "___LATEX_LT___").replace(/>/g, "___LATEX_GT___").replace(/&/g, "___LATEX_AMP___").replace(/'/g, "___LATEX_APOS___").replace(/"/g, "___LATEX_QUOT___");
      return `$$${protectedTex}$$`;
    });
    return result2;
  } catch (error2) {
    console.error("Error protecting LaTeX content:", error2);
    return content2;
  }
};
const restoreBackslashesForLatex = (content2) => {
  if (!content2) {
    return content2;
  }
  try {
    let result2 = content2.replace(/___LATEX_BACKSLASH___/g, "\\").replace(/___LATEX_LT___/g, "<").replace(/___LATEX_GT___/g, ">").replace(/___LATEX_AMP___/g, "&").replace(/___LATEX_APOS___/g, "'").replace(/___LATEX_QUOT___/g, '"');
    result2 = fixDotsNotation(result2);
    return result2;
  } catch (error2) {
    console.error("Error restoring LaTeX content:", error2);
    return content2;
  }
};
const fixDotsNotation = (content2) => {
  if (!content2) return content2;
  try {
    let result2 = content2.replace(/(\$[^$]*?)\\dots([^$]*?\$)/g, "$1\\ldots$2");
    result2 = result2.replace(/(\$\$[^$]*?)\\dots([^$]*?\$\$)/g, "$1\\ldots$2");
    return result2;
  } catch (error2) {
    console.error("Error fixing dots notation:", error2);
    return content2;
  }
};
const escapeHtmlCharacters = (content2) => {
  if (!content2) return content2;
  return content2.replace(/[<>&'"]/g, (c2) => {
    switch (c2) {
      case "<":
        return "&lt;";
      case ">":
        return "&gt;";
      case "&":
        return "&amp;";
      case "'":
        return "&apos;";
      case '"':
        return "&quot;";
      default:
        throw new Error("Matched a value that isn't replaceable");
    }
  });
};
const preRenderText = (txt) => {
  if (!txt) return txt;
  txt = txt.replace(/^[\u200B\u200C\u200D\u200E\u200F\uFEFF]/, "");
  return txt.replaceAll(
    kLetterListPattern,
    "<p class='markdown-ordered-list-item'>$1</p>"
  );
};
const protectMarkdown = (txt) => {
  if (!txt) return txt;
  return txt.replaceAll(
    kCommonmarkReferenceLinkPattern,
    "(open:767A125E)$1(close:767A125E) $2 "
  );
};
const unprotectMarkdown = (txt) => {
  if (!txt) return txt;
  txt = txt.replaceAll("(open:767A125E)", "[");
  txt = txt.replaceAll("(close:767A125E)", "]");
  return txt;
};
function unescapeSupHtmlEntities(str) {
  if (!str) {
    return str;
  }
  return str.replace(/&lt;sup&gt;/g, "<sup>").replace(/&lt;\/sup&gt;/g, "</sup>");
}
function unescapeCodeHtmlEntities(str) {
  if (!str) return str;
  const htmlEntities = {
    "&lt;": "<",
    "&gt;": ">",
    "&amp;": "&",
    "&#x5C;": "\\",
    "&quot;": '"'
  };
  return str.replace(
    /(<code[^>]*>)([\s\S]*?)(<\/code>)/gi,
    (_match, starttag, content2, endtag) => {
      return starttag + content2.replace(
        /&(?:amp|lt|gt|quot|#39|#x2F|#x5C|#96);/g,
        (entity2) => htmlEntities[entity2] || entity2
      ) + endtag;
    }
  );
}
const cite = "_cite_1t1bm_1";
const styles$1c = {
  cite
};
const panel$1 = "_panel_twp3v_1";
const container$g = "_container_twp3v_7";
const styles$1b = {
  panel: panel$1,
  container: container$g
};
const NoContentsPanel = ({ text: text2 }) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$1b.panel), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$1b.container, "text-size-smaller"), children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("i", { className: ApplicationIcons.noSamples }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/NoContentsPanel.tsx",
      lineNumber: 16,
      columnNumber: 9
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: text2 }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/NoContentsPanel.tsx",
      lineNumber: 17,
      columnNumber: 9
    }, void 0)
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/NoContentsPanel.tsx",
    lineNumber: 15,
    columnNumber: 7
  }, void 0) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/NoContentsPanel.tsx",
    lineNumber: 14,
    columnNumber: 5
  }, void 0);
};
var fromEntries = function fromEntries2(entries2) {
  return entries2.reduce(function(acc, _ref) {
    var key2 = _ref[0], value2 = _ref[1];
    acc[key2] = value2;
    return acc;
  }, {});
};
var useIsomorphicLayoutEffect = typeof window !== "undefined" && window.document && window.document.createElement ? reactExports.useLayoutEffect : reactExports.useEffect;
var top = "top";
var bottom = "bottom";
var right$1 = "right";
var left$1 = "left";
var auto = "auto";
var basePlacements = [top, bottom, right$1, left$1];
var start = "start";
var end = "end";
var clippingParents = "clippingParents";
var viewport = "viewport";
var popper = "popper";
var reference = "reference";
var variationPlacements = /* @__PURE__ */ basePlacements.reduce(function(acc, placement) {
  return acc.concat([placement + "-" + start, placement + "-" + end]);
}, []);
var placements = /* @__PURE__ */ [].concat(basePlacements, [auto]).reduce(function(acc, placement) {
  return acc.concat([placement, placement + "-" + start, placement + "-" + end]);
}, []);
var beforeRead = "beforeRead";
var read = "read";
var afterRead = "afterRead";
var beforeMain = "beforeMain";
var main = "main";
var afterMain = "afterMain";
var beforeWrite = "beforeWrite";
var write = "write";
var afterWrite = "afterWrite";
var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite];
function getNodeName(element) {
  return element ? (element.nodeName || "").toLowerCase() : null;
}
function getWindow(node2) {
  if (node2 == null) {
    return window;
  }
  if (node2.toString() !== "[object Window]") {
    var ownerDocument = node2.ownerDocument;
    return ownerDocument ? ownerDocument.defaultView || window : window;
  }
  return node2;
}
function isElement(node2) {
  var OwnElement = getWindow(node2).Element;
  return node2 instanceof OwnElement || node2 instanceof Element;
}
function isHTMLElement(node2) {
  var OwnElement = getWindow(node2).HTMLElement;
  return node2 instanceof OwnElement || node2 instanceof HTMLElement;
}
function isShadowRoot(node2) {
  if (typeof ShadowRoot === "undefined") {
    return false;
  }
  var OwnElement = getWindow(node2).ShadowRoot;
  return node2 instanceof OwnElement || node2 instanceof ShadowRoot;
}
function applyStyles(_ref) {
  var state = _ref.state;
  Object.keys(state.elements).forEach(function(name2) {
    var style2 = state.styles[name2] || {};
    var attributes = state.attributes[name2] || {};
    var element = state.elements[name2];
    if (!isHTMLElement(element) || !getNodeName(element)) {
      return;
    }
    Object.assign(element.style, style2);
    Object.keys(attributes).forEach(function(name3) {
      var value2 = attributes[name3];
      if (value2 === false) {
        element.removeAttribute(name3);
      } else {
        element.setAttribute(name3, value2 === true ? "" : value2);
      }
    });
  });
}
function effect$2(_ref2) {
  var state = _ref2.state;
  var initialStyles = {
    popper: {
      position: state.options.strategy,
      left: "0",
      top: "0",
      margin: "0"
    },
    arrow: {
      position: "absolute"
    },
    reference: {}
  };
  Object.assign(state.elements.popper.style, initialStyles.popper);
  state.styles = initialStyles;
  if (state.elements.arrow) {
    Object.assign(state.elements.arrow.style, initialStyles.arrow);
  }
  return function() {
    Object.keys(state.elements).forEach(function(name2) {
      var element = state.elements[name2];
      var attributes = state.attributes[name2] || {};
      var styleProperties = Object.keys(state.styles.hasOwnProperty(name2) ? state.styles[name2] : initialStyles[name2]);
      var style2 = styleProperties.reduce(function(style3, property) {
        style3[property] = "";
        return style3;
      }, {});
      if (!isHTMLElement(element) || !getNodeName(element)) {
        return;
      }
      Object.assign(element.style, style2);
      Object.keys(attributes).forEach(function(attribute2) {
        element.removeAttribute(attribute2);
      });
    });
  };
}
const applyStyles$1 = {
  name: "applyStyles",
  enabled: true,
  phase: "write",
  fn: applyStyles,
  effect: effect$2,
  requires: ["computeStyles"]
};
function getBasePlacement(placement) {
  return placement.split("-")[0];
}
var max = Math.max;
var min = Math.min;
var round = Math.round;
function getUAString() {
  var uaData = navigator.userAgentData;
  if (uaData != null && uaData.brands && Array.isArray(uaData.brands)) {
    return uaData.brands.map(function(item2) {
      return item2.brand + "/" + item2.version;
    }).join(" ");
  }
  return navigator.userAgent;
}
function isLayoutViewport() {
  return !/^((?!chrome|android).)*safari/i.test(getUAString());
}
function getBoundingClientRect(element, includeScale, isFixedStrategy) {
  if (includeScale === void 0) {
    includeScale = false;
  }
  if (isFixedStrategy === void 0) {
    isFixedStrategy = false;
  }
  var clientRect = element.getBoundingClientRect();
  var scaleX = 1;
  var scaleY = 1;
  if (includeScale && isHTMLElement(element)) {
    scaleX = element.offsetWidth > 0 ? round(clientRect.width) / element.offsetWidth || 1 : 1;
    scaleY = element.offsetHeight > 0 ? round(clientRect.height) / element.offsetHeight || 1 : 1;
  }
  var _ref = isElement(element) ? getWindow(element) : window, visualViewport = _ref.visualViewport;
  var addVisualOffsets = !isLayoutViewport() && isFixedStrategy;
  var x = (clientRect.left + (addVisualOffsets && visualViewport ? visualViewport.offsetLeft : 0)) / scaleX;
  var y = (clientRect.top + (addVisualOffsets && visualViewport ? visualViewport.offsetTop : 0)) / scaleY;
  var width = clientRect.width / scaleX;
  var height = clientRect.height / scaleY;
  return {
    width,
    height,
    top: y,
    right: x + width,
    bottom: y + height,
    left: x,
    x,
    y
  };
}
function getLayoutRect(element) {
  var clientRect = getBoundingClientRect(element);
  var width = element.offsetWidth;
  var height = element.offsetHeight;
  if (Math.abs(clientRect.width - width) <= 1) {
    width = clientRect.width;
  }
  if (Math.abs(clientRect.height - height) <= 1) {
    height = clientRect.height;
  }
  return {
    x: element.offsetLeft,
    y: element.offsetTop,
    width,
    height
  };
}
function contains(parent, child) {
  var rootNode = child.getRootNode && child.getRootNode();
  if (parent.contains(child)) {
    return true;
  } else if (rootNode && isShadowRoot(rootNode)) {
    var next = child;
    do {
      if (next && parent.isSameNode(next)) {
        return true;
      }
      next = next.parentNode || next.host;
    } while (next);
  }
  return false;
}
function getComputedStyle$1(element) {
  return getWindow(element).getComputedStyle(element);
}
function isTableElement(element) {
  return ["table", "td", "th"].indexOf(getNodeName(element)) >= 0;
}
function getDocumentElement(element) {
  return ((isElement(element) ? element.ownerDocument : (
    // $FlowFixMe[prop-missing]
    element.document
  )) || window.document).documentElement;
}
function getParentNode(element) {
  if (getNodeName(element) === "html") {
    return element;
  }
  return (
    // this is a quicker (but less type safe) way to save quite some bytes from the bundle
    // $FlowFixMe[incompatible-return]
    // $FlowFixMe[prop-missing]
    element.assignedSlot || // step into the shadow DOM of the parent of a slotted node
    element.parentNode || // DOM Element detected
    (isShadowRoot(element) ? element.host : null) || // ShadowRoot detected
    // $FlowFixMe[incompatible-call]: HTMLElement is a Node
    getDocumentElement(element)
  );
}
function getTrueOffsetParent(element) {
  if (!isHTMLElement(element) || // https://github.com/popperjs/popper-core/issues/837
  getComputedStyle$1(element).position === "fixed") {
    return null;
  }
  return element.offsetParent;
}
function getContainingBlock(element) {
  var isFirefox2 = /firefox/i.test(getUAString());
  var isIE = /Trident/i.test(getUAString());
  if (isIE && isHTMLElement(element)) {
    var elementCss = getComputedStyle$1(element);
    if (elementCss.position === "fixed") {
      return null;
    }
  }
  var currentNode = getParentNode(element);
  if (isShadowRoot(currentNode)) {
    currentNode = currentNode.host;
  }
  while (isHTMLElement(currentNode) && ["html", "body"].indexOf(getNodeName(currentNode)) < 0) {
    var css = getComputedStyle$1(currentNode);
    if (css.transform !== "none" || css.perspective !== "none" || css.contain === "paint" || ["transform", "perspective"].indexOf(css.willChange) !== -1 || isFirefox2 && css.willChange === "filter" || isFirefox2 && css.filter && css.filter !== "none") {
      return currentNode;
    } else {
      currentNode = currentNode.parentNode;
    }
  }
  return null;
}
function getOffsetParent(element) {
  var window2 = getWindow(element);
  var offsetParent = getTrueOffsetParent(element);
  while (offsetParent && isTableElement(offsetParent) && getComputedStyle$1(offsetParent).position === "static") {
    offsetParent = getTrueOffsetParent(offsetParent);
  }
  if (offsetParent && (getNodeName(offsetParent) === "html" || getNodeName(offsetParent) === "body" && getComputedStyle$1(offsetParent).position === "static")) {
    return window2;
  }
  return offsetParent || getContainingBlock(element) || window2;
}
function getMainAxisFromPlacement(placement) {
  return ["top", "bottom"].indexOf(placement) >= 0 ? "x" : "y";
}
function within(min$12, value2, max$12) {
  return max(min$12, min(value2, max$12));
}
function withinMaxClamp(min2, value2, max2) {
  var v = within(min2, value2, max2);
  return v > max2 ? max2 : v;
}
function getFreshSideObject() {
  return {
    top: 0,
    right: 0,
    bottom: 0,
    left: 0
  };
}
function mergePaddingObject(paddingObject) {
  return Object.assign({}, getFreshSideObject(), paddingObject);
}
function expandToHashMap(value2, keys2) {
  return keys2.reduce(function(hashMap, key2) {
    hashMap[key2] = value2;
    return hashMap;
  }, {});
}
var toPaddingObject = function toPaddingObject2(padding, state) {
  padding = typeof padding === "function" ? padding(Object.assign({}, state.rects, {
    placement: state.placement
  })) : padding;
  return mergePaddingObject(typeof padding !== "number" ? padding : expandToHashMap(padding, basePlacements));
};
function arrow(_ref) {
  var _state$modifiersData$;
  var state = _ref.state, name2 = _ref.name, options = _ref.options;
  var arrowElement = state.elements.arrow;
  var popperOffsets2 = state.modifiersData.popperOffsets;
  var basePlacement = getBasePlacement(state.placement);
  var axis = getMainAxisFromPlacement(basePlacement);
  var isVertical = [left$1, right$1].indexOf(basePlacement) >= 0;
  var len = isVertical ? "height" : "width";
  if (!arrowElement || !popperOffsets2) {
    return;
  }
  var paddingObject = toPaddingObject(options.padding, state);
  var arrowRect = getLayoutRect(arrowElement);
  var minProp = axis === "y" ? top : left$1;
  var maxProp = axis === "y" ? bottom : right$1;
  var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets2[axis] - state.rects.popper[len];
  var startDiff = popperOffsets2[axis] - state.rects.reference[axis];
  var arrowOffsetParent = getOffsetParent(arrowElement);
  var clientSize = arrowOffsetParent ? axis === "y" ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0;
  var centerToReference = endDiff / 2 - startDiff / 2;
  var min2 = paddingObject[minProp];
  var max2 = clientSize - arrowRect[len] - paddingObject[maxProp];
  var center2 = clientSize / 2 - arrowRect[len] / 2 + centerToReference;
  var offset3 = within(min2, center2, max2);
  var axisProp = axis;
  state.modifiersData[name2] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset3, _state$modifiersData$.centerOffset = offset3 - center2, _state$modifiersData$);
}
function effect$1(_ref2) {
  var state = _ref2.state, options = _ref2.options;
  var _options$element = options.element, arrowElement = _options$element === void 0 ? "[data-popper-arrow]" : _options$element;
  if (arrowElement == null) {
    return;
  }
  if (typeof arrowElement === "string") {
    arrowElement = state.elements.popper.querySelector(arrowElement);
    if (!arrowElement) {
      return;
    }
  }
  if (!contains(state.elements.popper, arrowElement)) {
    return;
  }
  state.elements.arrow = arrowElement;
}
const arrow$1 = {
  name: "arrow",
  enabled: true,
  phase: "main",
  fn: arrow,
  effect: effect$1,
  requires: ["popperOffsets"],
  requiresIfExists: ["preventOverflow"]
};
function getVariation(placement) {
  return placement.split("-")[1];
}
var unsetSides = {
  top: "auto",
  right: "auto",
  bottom: "auto",
  left: "auto"
};
function roundOffsetsByDPR(_ref, win) {
  var x = _ref.x, y = _ref.y;
  var dpr = win.devicePixelRatio || 1;
  return {
    x: round(x * dpr) / dpr || 0,
    y: round(y * dpr) / dpr || 0
  };
}
function mapToStyles(_ref2) {
  var _Object$assign2;
  var popper2 = _ref2.popper, popperRect = _ref2.popperRect, placement = _ref2.placement, variation = _ref2.variation, offsets = _ref2.offsets, position = _ref2.position, gpuAcceleration = _ref2.gpuAcceleration, adaptive = _ref2.adaptive, roundOffsets = _ref2.roundOffsets, isFixed = _ref2.isFixed;
  var _offsets$x = offsets.x, x = _offsets$x === void 0 ? 0 : _offsets$x, _offsets$y = offsets.y, y = _offsets$y === void 0 ? 0 : _offsets$y;
  var _ref3 = typeof roundOffsets === "function" ? roundOffsets({
    x,
    y
  }) : {
    x,
    y
  };
  x = _ref3.x;
  y = _ref3.y;
  var hasX = offsets.hasOwnProperty("x");
  var hasY = offsets.hasOwnProperty("y");
  var sideX = left$1;
  var sideY = top;
  var win = window;
  if (adaptive) {
    var offsetParent = getOffsetParent(popper2);
    var heightProp = "clientHeight";
    var widthProp = "clientWidth";
    if (offsetParent === getWindow(popper2)) {
      offsetParent = getDocumentElement(popper2);
      if (getComputedStyle$1(offsetParent).position !== "static" && position === "absolute") {
        heightProp = "scrollHeight";
        widthProp = "scrollWidth";
      }
    }
    offsetParent = offsetParent;
    if (placement === top || (placement === left$1 || placement === right$1) && variation === end) {
      sideY = bottom;
      var offsetY = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.height : (
        // $FlowFixMe[prop-missing]
        offsetParent[heightProp]
      );
      y -= offsetY - popperRect.height;
      y *= gpuAcceleration ? 1 : -1;
    }
    if (placement === left$1 || (placement === top || placement === bottom) && variation === end) {
      sideX = right$1;
      var offsetX = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.width : (
        // $FlowFixMe[prop-missing]
        offsetParent[widthProp]
      );
      x -= offsetX - popperRect.width;
      x *= gpuAcceleration ? 1 : -1;
    }
  }
  var commonStyles = Object.assign({
    position
  }, adaptive && unsetSides);
  var _ref4 = roundOffsets === true ? roundOffsetsByDPR({
    x,
    y
  }, getWindow(popper2)) : {
    x,
    y
  };
  x = _ref4.x;
  y = _ref4.y;
  if (gpuAcceleration) {
    var _Object$assign;
    return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? "0" : "", _Object$assign[sideX] = hasX ? "0" : "", _Object$assign.transform = (win.devicePixelRatio || 1) <= 1 ? "translate(" + x + "px, " + y + "px)" : "translate3d(" + x + "px, " + y + "px, 0)", _Object$assign));
  }
  return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + "px" : "", _Object$assign2[sideX] = hasX ? x + "px" : "", _Object$assign2.transform = "", _Object$assign2));
}
function computeStyles(_ref5) {
  var state = _ref5.state, options = _ref5.options;
  var _options$gpuAccelerat = options.gpuAcceleration, gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat, _options$adaptive = options.adaptive, adaptive = _options$adaptive === void 0 ? true : _options$adaptive, _options$roundOffsets = options.roundOffsets, roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets;
  var commonStyles = {
    placement: getBasePlacement(state.placement),
    variation: getVariation(state.placement),
    popper: state.elements.popper,
    popperRect: state.rects.popper,
    gpuAcceleration,
    isFixed: state.options.strategy === "fixed"
  };
  if (state.modifiersData.popperOffsets != null) {
    state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, {
      offsets: state.modifiersData.popperOffsets,
      position: state.options.strategy,
      adaptive,
      roundOffsets
    })));
  }
  if (state.modifiersData.arrow != null) {
    state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, {
      offsets: state.modifiersData.arrow,
      position: "absolute",
      adaptive: false,
      roundOffsets
    })));
  }
  state.attributes.popper = Object.assign({}, state.attributes.popper, {
    "data-popper-placement": state.placement
  });
}
const computeStyles$1 = {
  name: "computeStyles",
  enabled: true,
  phase: "beforeWrite",
  fn: computeStyles,
  data: {}
};
var passive = {
  passive: true
};
function effect(_ref) {
  var state = _ref.state, instance2 = _ref.instance, options = _ref.options;
  var _options$scroll = options.scroll, scroll = _options$scroll === void 0 ? true : _options$scroll, _options$resize = options.resize, resize2 = _options$resize === void 0 ? true : _options$resize;
  var window2 = getWindow(state.elements.popper);
  var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper);
  if (scroll) {
    scrollParents.forEach(function(scrollParent) {
      scrollParent.addEventListener("scroll", instance2.update, passive);
    });
  }
  if (resize2) {
    window2.addEventListener("resize", instance2.update, passive);
  }
  return function() {
    if (scroll) {
      scrollParents.forEach(function(scrollParent) {
        scrollParent.removeEventListener("scroll", instance2.update, passive);
      });
    }
    if (resize2) {
      window2.removeEventListener("resize", instance2.update, passive);
    }
  };
}
const eventListeners = {
  name: "eventListeners",
  enabled: true,
  phase: "write",
  fn: function fn2() {
  },
  effect,
  data: {}
};
var hash$1 = {
  left: "right",
  right: "left",
  bottom: "top",
  top: "bottom"
};
function getOppositePlacement(placement) {
  return placement.replace(/left|right|bottom|top/g, function(matched) {
    return hash$1[matched];
  });
}
var hash = {
  start: "end",
  end: "start"
};
function getOppositeVariationPlacement(placement) {
  return placement.replace(/start|end/g, function(matched) {
    return hash[matched];
  });
}
function getWindowScroll(node2) {
  var win = getWindow(node2);
  var scrollLeft = win.pageXOffset;
  var scrollTop = win.pageYOffset;
  return {
    scrollLeft,
    scrollTop
  };
}
function getWindowScrollBarX(element) {
  return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft;
}
function getViewportRect(element, strategy) {
  var win = getWindow(element);
  var html = getDocumentElement(element);
  var visualViewport = win.visualViewport;
  var width = html.clientWidth;
  var height = html.clientHeight;
  var x = 0;
  var y = 0;
  if (visualViewport) {
    width = visualViewport.width;
    height = visualViewport.height;
    var layoutViewport = isLayoutViewport();
    if (layoutViewport || !layoutViewport && strategy === "fixed") {
      x = visualViewport.offsetLeft;
      y = visualViewport.offsetTop;
    }
  }
  return {
    width,
    height,
    x: x + getWindowScrollBarX(element),
    y
  };
}
function getDocumentRect(element) {
  var _element$ownerDocumen;
  var html = getDocumentElement(element);
  var winScroll = getWindowScroll(element);
  var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body;
  var width = max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0);
  var height = max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0);
  var x = -winScroll.scrollLeft + getWindowScrollBarX(element);
  var y = -winScroll.scrollTop;
  if (getComputedStyle$1(body || html).direction === "rtl") {
    x += max(html.clientWidth, body ? body.clientWidth : 0) - width;
  }
  return {
    width,
    height,
    x,
    y
  };
}
function isScrollParent(element) {
  var _getComputedStyle = getComputedStyle$1(element), overflow = _getComputedStyle.overflow, overflowX = _getComputedStyle.overflowX, overflowY = _getComputedStyle.overflowY;
  return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX);
}
function getScrollParent(node2) {
  if (["html", "body", "#document"].indexOf(getNodeName(node2)) >= 0) {
    return node2.ownerDocument.body;
  }
  if (isHTMLElement(node2) && isScrollParent(node2)) {
    return node2;
  }
  return getScrollParent(getParentNode(node2));
}
function listScrollParents(element, list2) {
  var _element$ownerDocumen;
  if (list2 === void 0) {
    list2 = [];
  }
  var scrollParent = getScrollParent(element);
  var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body);
  var win = getWindow(scrollParent);
  var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent;
  var updatedList = list2.concat(target);
  return isBody ? updatedList : (
    // $FlowFixMe[incompatible-call]: isBody tells us target will be an HTMLElement here
    updatedList.concat(listScrollParents(getParentNode(target)))
  );
}
function rectToClientRect(rect) {
  return Object.assign({}, rect, {
    left: rect.x,
    top: rect.y,
    right: rect.x + rect.width,
    bottom: rect.y + rect.height
  });
}
function getInnerBoundingClientRect(element, strategy) {
  var rect = getBoundingClientRect(element, false, strategy === "fixed");
  rect.top = rect.top + element.clientTop;
  rect.left = rect.left + element.clientLeft;
  rect.bottom = rect.top + element.clientHeight;
  rect.right = rect.left + element.clientWidth;
  rect.width = element.clientWidth;
  rect.height = element.clientHeight;
  rect.x = rect.left;
  rect.y = rect.top;
  return rect;
}
function getClientRectFromMixedType(element, clippingParent, strategy) {
  return clippingParent === viewport ? rectToClientRect(getViewportRect(element, strategy)) : isElement(clippingParent) ? getInnerBoundingClientRect(clippingParent, strategy) : rectToClientRect(getDocumentRect(getDocumentElement(element)));
}
function getClippingParents(element) {
  var clippingParents2 = listScrollParents(getParentNode(element));
  var canEscapeClipping = ["absolute", "fixed"].indexOf(getComputedStyle$1(element).position) >= 0;
  var clipperElement = canEscapeClipping && isHTMLElement(element) ? getOffsetParent(element) : element;
  if (!isElement(clipperElement)) {
    return [];
  }
  return clippingParents2.filter(function(clippingParent) {
    return isElement(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== "body";
  });
}
function getClippingRect(element, boundary, rootBoundary, strategy) {
  var mainClippingParents = boundary === "clippingParents" ? getClippingParents(element) : [].concat(boundary);
  var clippingParents2 = [].concat(mainClippingParents, [rootBoundary]);
  var firstClippingParent = clippingParents2[0];
  var clippingRect = clippingParents2.reduce(function(accRect, clippingParent) {
    var rect = getClientRectFromMixedType(element, clippingParent, strategy);
    accRect.top = max(rect.top, accRect.top);
    accRect.right = min(rect.right, accRect.right);
    accRect.bottom = min(rect.bottom, accRect.bottom);
    accRect.left = max(rect.left, accRect.left);
    return accRect;
  }, getClientRectFromMixedType(element, firstClippingParent, strategy));
  clippingRect.width = clippingRect.right - clippingRect.left;
  clippingRect.height = clippingRect.bottom - clippingRect.top;
  clippingRect.x = clippingRect.left;
  clippingRect.y = clippingRect.top;
  return clippingRect;
}
function computeOffsets(_ref) {
  var reference2 = _ref.reference, element = _ref.element, placement = _ref.placement;
  var basePlacement = placement ? getBasePlacement(placement) : null;
  var variation = placement ? getVariation(placement) : null;
  var commonX = reference2.x + reference2.width / 2 - element.width / 2;
  var commonY = reference2.y + reference2.height / 2 - element.height / 2;
  var offsets;
  switch (basePlacement) {
    case top:
      offsets = {
        x: commonX,
        y: reference2.y - element.height
      };
      break;
    case bottom:
      offsets = {
        x: commonX,
        y: reference2.y + reference2.height
      };
      break;
    case right$1:
      offsets = {
        x: reference2.x + reference2.width,
        y: commonY
      };
      break;
    case left$1:
      offsets = {
        x: reference2.x - element.width,
        y: commonY
      };
      break;
    default:
      offsets = {
        x: reference2.x,
        y: reference2.y
      };
  }
  var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null;
  if (mainAxis != null) {
    var len = mainAxis === "y" ? "height" : "width";
    switch (variation) {
      case start:
        offsets[mainAxis] = offsets[mainAxis] - (reference2[len] / 2 - element[len] / 2);
        break;
      case end:
        offsets[mainAxis] = offsets[mainAxis] + (reference2[len] / 2 - element[len] / 2);
        break;
    }
  }
  return offsets;
}
function detectOverflow(state, options) {
  if (options === void 0) {
    options = {};
  }
  var _options = options, _options$placement = _options.placement, placement = _options$placement === void 0 ? state.placement : _options$placement, _options$strategy = _options.strategy, strategy = _options$strategy === void 0 ? state.strategy : _options$strategy, _options$boundary = _options.boundary, boundary = _options$boundary === void 0 ? clippingParents : _options$boundary, _options$rootBoundary = _options.rootBoundary, rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary, _options$elementConte = _options.elementContext, elementContext = _options$elementConte === void 0 ? popper : _options$elementConte, _options$altBoundary = _options.altBoundary, altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary, _options$padding = _options.padding, padding = _options$padding === void 0 ? 0 : _options$padding;
  var paddingObject = mergePaddingObject(typeof padding !== "number" ? padding : expandToHashMap(padding, basePlacements));
  var altContext = elementContext === popper ? reference : popper;
  var popperRect = state.rects.popper;
  var element = state.elements[altBoundary ? altContext : elementContext];
  var clippingClientRect = getClippingRect(isElement(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary, strategy);
  var referenceClientRect = getBoundingClientRect(state.elements.reference);
  var popperOffsets2 = computeOffsets({
    reference: referenceClientRect,
    element: popperRect,
    placement
  });
  var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets2));
  var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect;
  var overflowOffsets = {
    top: clippingClientRect.top - elementClientRect.top + paddingObject.top,
    bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom,
    left: clippingClientRect.left - elementClientRect.left + paddingObject.left,
    right: elementClientRect.right - clippingClientRect.right + paddingObject.right
  };
  var offsetData = state.modifiersData.offset;
  if (elementContext === popper && offsetData) {
    var offset3 = offsetData[placement];
    Object.keys(overflowOffsets).forEach(function(key2) {
      var multiply = [right$1, bottom].indexOf(key2) >= 0 ? 1 : -1;
      var axis = [top, bottom].indexOf(key2) >= 0 ? "y" : "x";
      overflowOffsets[key2] += offset3[axis] * multiply;
    });
  }
  return overflowOffsets;
}
function computeAutoPlacement(state, options) {
  if (options === void 0) {
    options = {};
  }
  var _options = options, placement = _options.placement, boundary = _options.boundary, rootBoundary = _options.rootBoundary, padding = _options.padding, flipVariations = _options.flipVariations, _options$allowedAutoP = _options.allowedAutoPlacements, allowedAutoPlacements = _options$allowedAutoP === void 0 ? placements : _options$allowedAutoP;
  var variation = getVariation(placement);
  var placements$1 = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function(placement2) {
    return getVariation(placement2) === variation;
  }) : basePlacements;
  var allowedPlacements = placements$1.filter(function(placement2) {
    return allowedAutoPlacements.indexOf(placement2) >= 0;
  });
  if (allowedPlacements.length === 0) {
    allowedPlacements = placements$1;
  }
  var overflows = allowedPlacements.reduce(function(acc, placement2) {
    acc[placement2] = detectOverflow(state, {
      placement: placement2,
      boundary,
      rootBoundary,
      padding
    })[getBasePlacement(placement2)];
    return acc;
  }, {});
  return Object.keys(overflows).sort(function(a2, b) {
    return overflows[a2] - overflows[b];
  });
}
function getExpandedFallbackPlacements(placement) {
  if (getBasePlacement(placement) === auto) {
    return [];
  }
  var oppositePlacement = getOppositePlacement(placement);
  return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)];
}
function flip(_ref) {
  var state = _ref.state, options = _ref.options, name2 = _ref.name;
  if (state.modifiersData[name2]._skip) {
    return;
  }
  var _options$mainAxis = options.mainAxis, checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, _options$altAxis = options.altAxis, checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis, specifiedFallbackPlacements = options.fallbackPlacements, padding = options.padding, boundary = options.boundary, rootBoundary = options.rootBoundary, altBoundary = options.altBoundary, _options$flipVariatio = options.flipVariations, flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio, allowedAutoPlacements = options.allowedAutoPlacements;
  var preferredPlacement = state.options.placement;
  var basePlacement = getBasePlacement(preferredPlacement);
  var isBasePlacement = basePlacement === preferredPlacement;
  var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement));
  var placements2 = [preferredPlacement].concat(fallbackPlacements).reduce(function(acc, placement2) {
    return acc.concat(getBasePlacement(placement2) === auto ? computeAutoPlacement(state, {
      placement: placement2,
      boundary,
      rootBoundary,
      padding,
      flipVariations,
      allowedAutoPlacements
    }) : placement2);
  }, []);
  var referenceRect = state.rects.reference;
  var popperRect = state.rects.popper;
  var checksMap = /* @__PURE__ */ new Map();
  var makeFallbackChecks = true;
  var firstFittingPlacement = placements2[0];
  for (var i2 = 0; i2 < placements2.length; i2++) {
    var placement = placements2[i2];
    var _basePlacement = getBasePlacement(placement);
    var isStartVariation = getVariation(placement) === start;
    var isVertical = [top, bottom].indexOf(_basePlacement) >= 0;
    var len = isVertical ? "width" : "height";
    var overflow = detectOverflow(state, {
      placement,
      boundary,
      rootBoundary,
      altBoundary,
      padding
    });
    var mainVariationSide = isVertical ? isStartVariation ? right$1 : left$1 : isStartVariation ? bottom : top;
    if (referenceRect[len] > popperRect[len]) {
      mainVariationSide = getOppositePlacement(mainVariationSide);
    }
    var altVariationSide = getOppositePlacement(mainVariationSide);
    var checks = [];
    if (checkMainAxis) {
      checks.push(overflow[_basePlacement] <= 0);
    }
    if (checkAltAxis) {
      checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0);
    }
    if (checks.every(function(check2) {
      return check2;
    })) {
      firstFittingPlacement = placement;
      makeFallbackChecks = false;
      break;
    }
    checksMap.set(placement, checks);
  }
  if (makeFallbackChecks) {
    var numberOfChecks = flipVariations ? 3 : 1;
    var _loop = function _loop2(_i2) {
      var fittingPlacement = placements2.find(function(placement2) {
        var checks2 = checksMap.get(placement2);
        if (checks2) {
          return checks2.slice(0, _i2).every(function(check2) {
            return check2;
          });
        }
      });
      if (fittingPlacement) {
        firstFittingPlacement = fittingPlacement;
        return "break";
      }
    };
    for (var _i = numberOfChecks; _i > 0; _i--) {
      var _ret = _loop(_i);
      if (_ret === "break") break;
    }
  }
  if (state.placement !== firstFittingPlacement) {
    state.modifiersData[name2]._skip = true;
    state.placement = firstFittingPlacement;
    state.reset = true;
  }
}
const flip$1 = {
  name: "flip",
  enabled: true,
  phase: "main",
  fn: flip,
  requiresIfExists: ["offset"],
  data: {
    _skip: false
  }
};
function getSideOffsets(overflow, rect, preventedOffsets) {
  if (preventedOffsets === void 0) {
    preventedOffsets = {
      x: 0,
      y: 0
    };
  }
  return {
    top: overflow.top - rect.height - preventedOffsets.y,
    right: overflow.right - rect.width + preventedOffsets.x,
    bottom: overflow.bottom - rect.height + preventedOffsets.y,
    left: overflow.left - rect.width - preventedOffsets.x
  };
}
function isAnySideFullyClipped(overflow) {
  return [top, right$1, bottom, left$1].some(function(side) {
    return overflow[side] >= 0;
  });
}
function hide(_ref) {
  var state = _ref.state, name2 = _ref.name;
  var referenceRect = state.rects.reference;
  var popperRect = state.rects.popper;
  var preventedOffsets = state.modifiersData.preventOverflow;
  var referenceOverflow = detectOverflow(state, {
    elementContext: "reference"
  });
  var popperAltOverflow = detectOverflow(state, {
    altBoundary: true
  });
  var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect);
  var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets);
  var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets);
  var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets);
  state.modifiersData[name2] = {
    referenceClippingOffsets,
    popperEscapeOffsets,
    isReferenceHidden,
    hasPopperEscaped
  };
  state.attributes.popper = Object.assign({}, state.attributes.popper, {
    "data-popper-reference-hidden": isReferenceHidden,
    "data-popper-escaped": hasPopperEscaped
  });
}
const hide$1 = {
  name: "hide",
  enabled: true,
  phase: "main",
  requiresIfExists: ["preventOverflow"],
  fn: hide
};
function distanceAndSkiddingToXY(placement, rects, offset3) {
  var basePlacement = getBasePlacement(placement);
  var invertDistance = [left$1, top].indexOf(basePlacement) >= 0 ? -1 : 1;
  var _ref = typeof offset3 === "function" ? offset3(Object.assign({}, rects, {
    placement
  })) : offset3, skidding = _ref[0], distance = _ref[1];
  skidding = skidding || 0;
  distance = (distance || 0) * invertDistance;
  return [left$1, right$1].indexOf(basePlacement) >= 0 ? {
    x: distance,
    y: skidding
  } : {
    x: skidding,
    y: distance
  };
}
function offset2(_ref2) {
  var state = _ref2.state, options = _ref2.options, name2 = _ref2.name;
  var _options$offset = options.offset, offset3 = _options$offset === void 0 ? [0, 0] : _options$offset;
  var data2 = placements.reduce(function(acc, placement) {
    acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset3);
    return acc;
  }, {});
  var _data$state$placement = data2[state.placement], x = _data$state$placement.x, y = _data$state$placement.y;
  if (state.modifiersData.popperOffsets != null) {
    state.modifiersData.popperOffsets.x += x;
    state.modifiersData.popperOffsets.y += y;
  }
  state.modifiersData[name2] = data2;
}
const offset$1 = {
  name: "offset",
  enabled: true,
  phase: "main",
  requires: ["popperOffsets"],
  fn: offset2
};
function popperOffsets(_ref) {
  var state = _ref.state, name2 = _ref.name;
  state.modifiersData[name2] = computeOffsets({
    reference: state.rects.reference,
    element: state.rects.popper,
    placement: state.placement
  });
}
const popperOffsets$1 = {
  name: "popperOffsets",
  enabled: true,
  phase: "read",
  fn: popperOffsets,
  data: {}
};
function getAltAxis(axis) {
  return axis === "x" ? "y" : "x";
}
function preventOverflow(_ref) {
  var state = _ref.state, options = _ref.options, name2 = _ref.name;
  var _options$mainAxis = options.mainAxis, checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, _options$altAxis = options.altAxis, checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis, boundary = options.boundary, rootBoundary = options.rootBoundary, altBoundary = options.altBoundary, padding = options.padding, _options$tether = options.tether, tether = _options$tether === void 0 ? true : _options$tether, _options$tetherOffset = options.tetherOffset, tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset;
  var overflow = detectOverflow(state, {
    boundary,
    rootBoundary,
    padding,
    altBoundary
  });
  var basePlacement = getBasePlacement(state.placement);
  var variation = getVariation(state.placement);
  var isBasePlacement = !variation;
  var mainAxis = getMainAxisFromPlacement(basePlacement);
  var altAxis = getAltAxis(mainAxis);
  var popperOffsets2 = state.modifiersData.popperOffsets;
  var referenceRect = state.rects.reference;
  var popperRect = state.rects.popper;
  var tetherOffsetValue = typeof tetherOffset === "function" ? tetherOffset(Object.assign({}, state.rects, {
    placement: state.placement
  })) : tetherOffset;
  var normalizedTetherOffsetValue = typeof tetherOffsetValue === "number" ? {
    mainAxis: tetherOffsetValue,
    altAxis: tetherOffsetValue
  } : Object.assign({
    mainAxis: 0,
    altAxis: 0
  }, tetherOffsetValue);
  var offsetModifierState = state.modifiersData.offset ? state.modifiersData.offset[state.placement] : null;
  var data2 = {
    x: 0,
    y: 0
  };
  if (!popperOffsets2) {
    return;
  }
  if (checkMainAxis) {
    var _offsetModifierState$;
    var mainSide = mainAxis === "y" ? top : left$1;
    var altSide = mainAxis === "y" ? bottom : right$1;
    var len = mainAxis === "y" ? "height" : "width";
    var offset3 = popperOffsets2[mainAxis];
    var min$12 = offset3 + overflow[mainSide];
    var max$12 = offset3 - overflow[altSide];
    var additive = tether ? -popperRect[len] / 2 : 0;
    var minLen = variation === start ? referenceRect[len] : popperRect[len];
    var maxLen = variation === start ? -popperRect[len] : -referenceRect[len];
    var arrowElement = state.elements.arrow;
    var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : {
      width: 0,
      height: 0
    };
    var arrowPaddingObject = state.modifiersData["arrow#persistent"] ? state.modifiersData["arrow#persistent"].padding : getFreshSideObject();
    var arrowPaddingMin = arrowPaddingObject[mainSide];
    var arrowPaddingMax = arrowPaddingObject[altSide];
    var arrowLen = within(0, referenceRect[len], arrowRect[len]);
    var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis : minLen - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis;
    var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis : maxLen + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis;
    var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow);
    var clientOffset = arrowOffsetParent ? mainAxis === "y" ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0;
    var offsetModifierValue = (_offsetModifierState$ = offsetModifierState == null ? void 0 : offsetModifierState[mainAxis]) != null ? _offsetModifierState$ : 0;
    var tetherMin = offset3 + minOffset - offsetModifierValue - clientOffset;
    var tetherMax = offset3 + maxOffset - offsetModifierValue;
    var preventedOffset = within(tether ? min(min$12, tetherMin) : min$12, offset3, tether ? max(max$12, tetherMax) : max$12);
    popperOffsets2[mainAxis] = preventedOffset;
    data2[mainAxis] = preventedOffset - offset3;
  }
  if (checkAltAxis) {
    var _offsetModifierState$2;
    var _mainSide = mainAxis === "x" ? top : left$1;
    var _altSide = mainAxis === "x" ? bottom : right$1;
    var _offset = popperOffsets2[altAxis];
    var _len = altAxis === "y" ? "height" : "width";
    var _min = _offset + overflow[_mainSide];
    var _max = _offset - overflow[_altSide];
    var isOriginSide = [top, left$1].indexOf(basePlacement) !== -1;
    var _offsetModifierValue = (_offsetModifierState$2 = offsetModifierState == null ? void 0 : offsetModifierState[altAxis]) != null ? _offsetModifierState$2 : 0;
    var _tetherMin = isOriginSide ? _min : _offset - referenceRect[_len] - popperRect[_len] - _offsetModifierValue + normalizedTetherOffsetValue.altAxis;
    var _tetherMax = isOriginSide ? _offset + referenceRect[_len] + popperRect[_len] - _offsetModifierValue - normalizedTetherOffsetValue.altAxis : _max;
    var _preventedOffset = tether && isOriginSide ? withinMaxClamp(_tetherMin, _offset, _tetherMax) : within(tether ? _tetherMin : _min, _offset, tether ? _tetherMax : _max);
    popperOffsets2[altAxis] = _preventedOffset;
    data2[altAxis] = _preventedOffset - _offset;
  }
  state.modifiersData[name2] = data2;
}
const preventOverflow$1 = {
  name: "preventOverflow",
  enabled: true,
  phase: "main",
  fn: preventOverflow,
  requiresIfExists: ["offset"]
};
function getHTMLElementScroll(element) {
  return {
    scrollLeft: element.scrollLeft,
    scrollTop: element.scrollTop
  };
}
function getNodeScroll(node2) {
  if (node2 === getWindow(node2) || !isHTMLElement(node2)) {
    return getWindowScroll(node2);
  } else {
    return getHTMLElementScroll(node2);
  }
}
function isElementScaled(element) {
  var rect = element.getBoundingClientRect();
  var scaleX = round(rect.width) / element.offsetWidth || 1;
  var scaleY = round(rect.height) / element.offsetHeight || 1;
  return scaleX !== 1 || scaleY !== 1;
}
function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) {
  if (isFixed === void 0) {
    isFixed = false;
  }
  var isOffsetParentAnElement = isHTMLElement(offsetParent);
  var offsetParentIsScaled = isHTMLElement(offsetParent) && isElementScaled(offsetParent);
  var documentElement = getDocumentElement(offsetParent);
  var rect = getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled, isFixed);
  var scroll = {
    scrollLeft: 0,
    scrollTop: 0
  };
  var offsets = {
    x: 0,
    y: 0
  };
  if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
    if (getNodeName(offsetParent) !== "body" || // https://github.com/popperjs/popper-core/issues/1078
    isScrollParent(documentElement)) {
      scroll = getNodeScroll(offsetParent);
    }
    if (isHTMLElement(offsetParent)) {
      offsets = getBoundingClientRect(offsetParent, true);
      offsets.x += offsetParent.clientLeft;
      offsets.y += offsetParent.clientTop;
    } else if (documentElement) {
      offsets.x = getWindowScrollBarX(documentElement);
    }
  }
  return {
    x: rect.left + scroll.scrollLeft - offsets.x,
    y: rect.top + scroll.scrollTop - offsets.y,
    width: rect.width,
    height: rect.height
  };
}
function order(modifiers) {
  var map2 = /* @__PURE__ */ new Map();
  var visited = /* @__PURE__ */ new Set();
  var result2 = [];
  modifiers.forEach(function(modifier) {
    map2.set(modifier.name, modifier);
  });
  function sort(modifier) {
    visited.add(modifier.name);
    var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []);
    requires.forEach(function(dep) {
      if (!visited.has(dep)) {
        var depModifier = map2.get(dep);
        if (depModifier) {
          sort(depModifier);
        }
      }
    });
    result2.push(modifier);
  }
  modifiers.forEach(function(modifier) {
    if (!visited.has(modifier.name)) {
      sort(modifier);
    }
  });
  return result2;
}
function orderModifiers(modifiers) {
  var orderedModifiers = order(modifiers);
  return modifierPhases.reduce(function(acc, phase) {
    return acc.concat(orderedModifiers.filter(function(modifier) {
      return modifier.phase === phase;
    }));
  }, []);
}
function debounce$1(fn3) {
  var pending;
  return function() {
    if (!pending) {
      pending = new Promise(function(resolve2) {
        Promise.resolve().then(function() {
          pending = void 0;
          resolve2(fn3());
        });
      });
    }
    return pending;
  };
}
function mergeByName(modifiers) {
  var merged = modifiers.reduce(function(merged2, current3) {
    var existing = merged2[current3.name];
    merged2[current3.name] = existing ? Object.assign({}, existing, current3, {
      options: Object.assign({}, existing.options, current3.options),
      data: Object.assign({}, existing.data, current3.data)
    }) : current3;
    return merged2;
  }, {});
  return Object.keys(merged).map(function(key2) {
    return merged[key2];
  });
}
var DEFAULT_OPTIONS = {
  placement: "bottom",
  modifiers: [],
  strategy: "absolute"
};
function areValidElements() {
  for (var _len = arguments.length, args2 = new Array(_len), _key = 0; _key < _len; _key++) {
    args2[_key] = arguments[_key];
  }
  return !args2.some(function(element) {
    return !(element && typeof element.getBoundingClientRect === "function");
  });
}
function popperGenerator(generatorOptions) {
  if (generatorOptions === void 0) {
    generatorOptions = {};
  }
  var _generatorOptions = generatorOptions, _generatorOptions$def = _generatorOptions.defaultModifiers, defaultModifiers2 = _generatorOptions$def === void 0 ? [] : _generatorOptions$def, _generatorOptions$def2 = _generatorOptions.defaultOptions, defaultOptions2 = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2;
  return function createPopper2(reference2, popper2, options) {
    if (options === void 0) {
      options = defaultOptions2;
    }
    var state = {
      placement: "bottom",
      orderedModifiers: [],
      options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions2),
      modifiersData: {},
      elements: {
        reference: reference2,
        popper: popper2
      },
      attributes: {},
      styles: {}
    };
    var effectCleanupFns = [];
    var isDestroyed2 = false;
    var instance2 = {
      state,
      setOptions: function setOptions(setOptionsAction) {
        var options2 = typeof setOptionsAction === "function" ? setOptionsAction(state.options) : setOptionsAction;
        cleanupModifierEffects();
        state.options = Object.assign({}, defaultOptions2, state.options, options2);
        state.scrollParents = {
          reference: isElement(reference2) ? listScrollParents(reference2) : reference2.contextElement ? listScrollParents(reference2.contextElement) : [],
          popper: listScrollParents(popper2)
        };
        var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers2, state.options.modifiers)));
        state.orderedModifiers = orderedModifiers.filter(function(m) {
          return m.enabled;
        });
        runModifierEffects();
        return instance2.update();
      },
      // Sync update – it will always be executed, even if not necessary. This
      // is useful for low frequency updates where sync behavior simplifies the
      // logic.
      // For high frequency updates (e.g. `resize` and `scroll` events), always
      // prefer the async Popper#update method
      forceUpdate: function forceUpdate() {
        if (isDestroyed2) {
          return;
        }
        var _state$elements = state.elements, reference3 = _state$elements.reference, popper3 = _state$elements.popper;
        if (!areValidElements(reference3, popper3)) {
          return;
        }
        state.rects = {
          reference: getCompositeRect(reference3, getOffsetParent(popper3), state.options.strategy === "fixed"),
          popper: getLayoutRect(popper3)
        };
        state.reset = false;
        state.placement = state.options.placement;
        state.orderedModifiers.forEach(function(modifier) {
          return state.modifiersData[modifier.name] = Object.assign({}, modifier.data);
        });
        for (var index = 0; index < state.orderedModifiers.length; index++) {
          if (state.reset === true) {
            state.reset = false;
            index = -1;
            continue;
          }
          var _state$orderedModifie = state.orderedModifiers[index], fn3 = _state$orderedModifie.fn, _state$orderedModifie2 = _state$orderedModifie.options, _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2, name2 = _state$orderedModifie.name;
          if (typeof fn3 === "function") {
            state = fn3({
              state,
              options: _options,
              name: name2,
              instance: instance2
            }) || state;
          }
        }
      },
      // Async and optimistically optimized update – it will not be executed if
      // not necessary (debounced to run at most once-per-tick)
      update: debounce$1(function() {
        return new Promise(function(resolve2) {
          instance2.forceUpdate();
          resolve2(state);
        });
      }),
      destroy: function destroy2() {
        cleanupModifierEffects();
        isDestroyed2 = true;
      }
    };
    if (!areValidElements(reference2, popper2)) {
      return instance2;
    }
    instance2.setOptions(options).then(function(state2) {
      if (!isDestroyed2 && options.onFirstUpdate) {
        options.onFirstUpdate(state2);
      }
    });
    function runModifierEffects() {
      state.orderedModifiers.forEach(function(_ref) {
        var name2 = _ref.name, _ref$options = _ref.options, options2 = _ref$options === void 0 ? {} : _ref$options, effect2 = _ref.effect;
        if (typeof effect2 === "function") {
          var cleanupFn = effect2({
            state,
            name: name2,
            instance: instance2,
            options: options2
          });
          var noopFn = function noopFn2() {
          };
          effectCleanupFns.push(cleanupFn || noopFn);
        }
      });
    }
    function cleanupModifierEffects() {
      effectCleanupFns.forEach(function(fn3) {
        return fn3();
      });
      effectCleanupFns = [];
    }
    return instance2;
  };
}
var defaultModifiers = [eventListeners, popperOffsets$1, computeStyles$1, applyStyles$1, offset$1, flip$1, preventOverflow$1, arrow$1, hide$1];
var createPopper = /* @__PURE__ */ popperGenerator({
  defaultModifiers
});
var reactFastCompare;
var hasRequiredReactFastCompare;
function requireReactFastCompare() {
  if (hasRequiredReactFastCompare) return reactFastCompare;
  hasRequiredReactFastCompare = 1;
  var hasElementType = typeof Element !== "undefined";
  var hasMap = typeof Map === "function";
  var hasSet = typeof Set === "function";
  var hasArrayBuffer = typeof ArrayBuffer === "function" && !!ArrayBuffer.isView;
  function equal2(a2, b) {
    if (a2 === b) return true;
    if (a2 && b && typeof a2 == "object" && typeof b == "object") {
      if (a2.constructor !== b.constructor) return false;
      var length2, i2, keys2;
      if (Array.isArray(a2)) {
        length2 = a2.length;
        if (length2 != b.length) return false;
        for (i2 = length2; i2-- !== 0; )
          if (!equal2(a2[i2], b[i2])) return false;
        return true;
      }
      var it;
      if (hasMap && a2 instanceof Map && b instanceof Map) {
        if (a2.size !== b.size) return false;
        it = a2.entries();
        while (!(i2 = it.next()).done)
          if (!b.has(i2.value[0])) return false;
        it = a2.entries();
        while (!(i2 = it.next()).done)
          if (!equal2(i2.value[1], b.get(i2.value[0]))) return false;
        return true;
      }
      if (hasSet && a2 instanceof Set && b instanceof Set) {
        if (a2.size !== b.size) return false;
        it = a2.entries();
        while (!(i2 = it.next()).done)
          if (!b.has(i2.value[0])) return false;
        return true;
      }
      if (hasArrayBuffer && ArrayBuffer.isView(a2) && ArrayBuffer.isView(b)) {
        length2 = a2.length;
        if (length2 != b.length) return false;
        for (i2 = length2; i2-- !== 0; )
          if (a2[i2] !== b[i2]) return false;
        return true;
      }
      if (a2.constructor === RegExp) return a2.source === b.source && a2.flags === b.flags;
      if (a2.valueOf !== Object.prototype.valueOf && typeof a2.valueOf === "function" && typeof b.valueOf === "function") return a2.valueOf() === b.valueOf();
      if (a2.toString !== Object.prototype.toString && typeof a2.toString === "function" && typeof b.toString === "function") return a2.toString() === b.toString();
      keys2 = Object.keys(a2);
      length2 = keys2.length;
      if (length2 !== Object.keys(b).length) return false;
      for (i2 = length2; i2-- !== 0; )
        if (!Object.prototype.hasOwnProperty.call(b, keys2[i2])) return false;
      if (hasElementType && a2 instanceof Element) return false;
      for (i2 = length2; i2-- !== 0; ) {
        if ((keys2[i2] === "_owner" || keys2[i2] === "__v" || keys2[i2] === "__o") && a2.$$typeof) {
          continue;
        }
        if (!equal2(a2[keys2[i2]], b[keys2[i2]])) return false;
      }
      return true;
    }
    return a2 !== a2 && b !== b;
  }
  reactFastCompare = function isEqual2(a2, b) {
    try {
      return equal2(a2, b);
    } catch (error2) {
      if ((error2.message || "").match(/stack|recursion/i)) {
        console.warn("react-fast-compare cannot handle circular refs");
        return false;
      }
      throw error2;
    }
  };
  return reactFastCompare;
}
var reactFastCompareExports = requireReactFastCompare();
const isEqual = /* @__PURE__ */ getDefaultExportFromCjs(reactFastCompareExports);
var EMPTY_MODIFIERS = [];
var usePopper = function usePopper2(referenceElement, popperElement, options) {
  if (options === void 0) {
    options = {};
  }
  var prevOptions = reactExports.useRef(null);
  var optionsWithDefaults = {
    onFirstUpdate: options.onFirstUpdate,
    placement: options.placement || "bottom",
    strategy: options.strategy || "absolute",
    modifiers: options.modifiers || EMPTY_MODIFIERS
  };
  var _React$useState = reactExports.useState({
    styles: {
      popper: {
        position: optionsWithDefaults.strategy,
        left: "0",
        top: "0"
      },
      arrow: {
        position: "absolute"
      }
    },
    attributes: {}
  }), state = _React$useState[0], setState2 = _React$useState[1];
  var updateStateModifier = reactExports.useMemo(function() {
    return {
      name: "updateState",
      enabled: true,
      phase: "write",
      fn: function fn3(_ref) {
        var state2 = _ref.state;
        var elements = Object.keys(state2.elements);
        reactDomExports.flushSync(function() {
          setState2({
            styles: fromEntries(elements.map(function(element) {
              return [element, state2.styles[element] || {}];
            })),
            attributes: fromEntries(elements.map(function(element) {
              return [element, state2.attributes[element]];
            }))
          });
        });
      },
      requires: ["computeStyles"]
    };
  }, []);
  var popperOptions = reactExports.useMemo(function() {
    var newOptions = {
      onFirstUpdate: optionsWithDefaults.onFirstUpdate,
      placement: optionsWithDefaults.placement,
      strategy: optionsWithDefaults.strategy,
      modifiers: [].concat(optionsWithDefaults.modifiers, [updateStateModifier, {
        name: "applyStyles",
        enabled: false
      }])
    };
    if (isEqual(prevOptions.current, newOptions)) {
      return prevOptions.current || newOptions;
    } else {
      prevOptions.current = newOptions;
      return newOptions;
    }
  }, [optionsWithDefaults.onFirstUpdate, optionsWithDefaults.placement, optionsWithDefaults.strategy, optionsWithDefaults.modifiers, updateStateModifier]);
  var popperInstanceRef = reactExports.useRef();
  useIsomorphicLayoutEffect(function() {
    if (popperInstanceRef.current) {
      popperInstanceRef.current.setOptions(popperOptions);
    }
  }, [popperOptions]);
  useIsomorphicLayoutEffect(function() {
    if (referenceElement == null || popperElement == null) {
      return;
    }
    var createPopper$1 = options.createPopper || createPopper;
    var popperInstance = createPopper$1(referenceElement, popperElement, popperOptions);
    popperInstanceRef.current = popperInstance;
    return function() {
      popperInstance.destroy();
      popperInstanceRef.current = null;
    };
  }, [referenceElement, popperElement, options.createPopper]);
  return {
    state: popperInstanceRef.current ? popperInstanceRef.current.state : null,
    styles: state.styles,
    attributes: state.attributes,
    update: popperInstanceRef.current ? popperInstanceRef.current.update : null,
    forceUpdate: popperInstanceRef.current ? popperInstanceRef.current.forceUpdate : null
  };
};
const PopOver = ({
  id: id2,
  isOpen,
  setIsOpen,
  positionEl,
  children: children2,
  placement = "bottom",
  showArrow = true,
  offset: offset3 = [0, 8],
  className: className2 = "",
  arrowClassName = "",
  usePortal = true,
  hoverDelay = 250,
  styles: styles2 = {}
}) => {
  const popperRef = reactExports.useRef(null);
  const arrowRef = reactExports.useRef(null);
  const [portalContainer, setPortalContainer] = reactExports.useState(
    null
  );
  const [shouldShowPopover, setShouldShowPopover] = reactExports.useState(false);
  const hoverTimerRef = reactExports.useRef(null);
  const isMouseMovingRef = reactExports.useRef(false);
  const isOverPopoverRef = reactExports.useRef(false);
  const dismissalTimerRef = reactExports.useRef(null);
  reactExports.useEffect(() => {
    const handleMouseMove = () => {
      isMouseMovingRef.current = true;
      if (hoverTimerRef.current !== null) {
        window.clearTimeout(hoverTimerRef.current);
      }
      hoverTimerRef.current = window.setTimeout(() => {
        if (isOpen) {
          isMouseMovingRef.current = false;
          setShouldShowPopover(true);
        }
      }, hoverDelay);
    };
    const handleMouseLeave = () => {
      if (hoverTimerRef.current !== null) {
        window.clearTimeout(hoverTimerRef.current);
      }
      isMouseMovingRef.current = false;
      if (dismissalTimerRef.current !== null) {
        window.clearTimeout(dismissalTimerRef.current);
      }
      dismissalTimerRef.current = window.setTimeout(() => {
        if (!isOverPopoverRef.current) {
          setShouldShowPopover(false);
          setIsOpen(false);
        }
      }, 300);
    };
    const handleMouseDown = (event) => {
      if (popperRef.current && !popperRef.current.contains(event.target)) {
        if (hoverTimerRef.current !== null) {
          window.clearTimeout(hoverTimerRef.current);
        }
        setShouldShowPopover(false);
        setIsOpen(false);
      }
    };
    if (!isOpen || hoverDelay <= 0) {
      setShouldShowPopover(isOpen);
      const listener = (event) => {
        if (popperRef.current && !popperRef.current.contains(event.target)) {
          setIsOpen(false);
        }
      };
      document.addEventListener("mousedown", listener);
      return () => {
        document.removeEventListener("mousedown", listener);
      };
    }
    if (positionEl && isOpen) {
      positionEl.addEventListener("mousemove", handleMouseMove);
      positionEl.addEventListener("mouseleave", handleMouseLeave);
      document.addEventListener("mousedown", handleMouseDown);
      handleMouseMove();
    } else {
      setShouldShowPopover(false);
    }
    return () => {
      if (positionEl) {
        positionEl.removeEventListener("mousemove", handleMouseMove);
        positionEl.removeEventListener("mouseleave", handleMouseLeave);
      }
      document.removeEventListener("mousedown", handleMouseDown);
      if (hoverTimerRef.current !== null) {
        window.clearTimeout(hoverTimerRef.current);
        hoverTimerRef.current = null;
      }
      if (dismissalTimerRef.current !== null) {
        window.clearTimeout(dismissalTimerRef.current);
        dismissalTimerRef.current = null;
      }
    };
  }, [isOpen, positionEl, hoverDelay]);
  reactExports.useEffect(() => {
    if (usePortal && isOpen && shouldShowPopover) {
      let container2 = document.getElementById(id2);
      if (!container2) {
        container2 = document.createElement("div");
        container2.id = id2;
        container2.style.position = "absolute";
        container2.style.top = "0";
        container2.style.left = "0";
        container2.style.zIndex = "9999";
        container2.style.width = "0";
        container2.style.height = "0";
        container2.style.overflow = "visible";
        document.body.appendChild(container2);
      }
      setPortalContainer(container2);
      return () => {
        if (document.body.contains(container2)) {
          document.body.removeChild(container2);
          setPortalContainer(null);
        }
      };
    }
    return void 0;
  }, [usePortal, isOpen, shouldShowPopover, id2]);
  const modifiers = [
    { name: "offset", options: { offset: offset3 } },
    { name: "preventOverflow", options: { padding: 8 } },
    {
      name: "arrow",
      enabled: showArrow,
      options: {
        element: arrowRef.current,
        padding: 5
        // This keeps the arrow from getting too close to the corner
      }
    },
    {
      name: "computeStyles",
      options: {
        gpuAcceleration: false,
        adaptive: true
      }
    },
    // Ensure popper is positioned correctly with respect to its reference element
    {
      name: "flip",
      options: {
        fallbackPlacements: ["top", "right", "bottom", "left"]
      }
    }
  ];
  const {
    styles: popperStyles,
    attributes,
    state,
    update: update2
  } = usePopper(positionEl, popperRef.current, {
    placement,
    strategy: "fixed",
    modifiers
  });
  reactExports.useEffect(() => {
    if (update2 && isOpen && shouldShowPopover) {
      const timer = setTimeout(() => {
        void update2();
      }, 10);
      return () => clearTimeout(timer);
    }
  }, [update2, isOpen, shouldShowPopover, showArrow, arrowRef.current]);
  reactExports.useEffect(() => {
    if (!popperRef.current || !isOpen || !shouldShowPopover || !state?.placement) {
      return;
    }
    const handlePopoverMouseEnter = () => {
      isOverPopoverRef.current = true;
      if (dismissalTimerRef.current !== null) {
        window.clearTimeout(dismissalTimerRef.current);
        dismissalTimerRef.current = null;
      }
      if (hoverTimerRef.current !== null) {
        window.clearTimeout(hoverTimerRef.current);
      }
      setShouldShowPopover(true);
    };
    const handlePopoverMouseLeave = (e) => {
      if (e.relatedTarget && popperRef.current?.contains(e.relatedTarget)) {
        return;
      }
      isOverPopoverRef.current = false;
      setShouldShowPopover(false);
      setIsOpen(false);
    };
    popperRef.current.addEventListener(
      "mouseenter",
      handlePopoverMouseEnter,
      true
    );
    popperRef.current.addEventListener(
      "mouseleave",
      handlePopoverMouseLeave,
      true
    );
    return () => {
      if (popperRef.current) {
        popperRef.current.removeEventListener(
          "mouseenter",
          handlePopoverMouseEnter,
          true
        );
        popperRef.current.removeEventListener(
          "mouseleave",
          handlePopoverMouseLeave,
          true
        );
      }
    };
  }, [isOpen, shouldShowPopover, state?.placement]);
  const getArrowDataPlacement = () => {
    if (!state || !state.placement) return placement;
    return state.placement;
  };
  const actualPlacement = state?.placement || placement;
  const defaultPopperStyles = {
    backgroundColor: "var(--bs-body-bg)",
    padding: "12px",
    borderRadius: "4px",
    boxShadow: "0 2px 10px rgba(0,0,0,0.1)",
    border: "solid 1px var(--bs-border-color)",
    zIndex: 1200,
    position: "relative",
    // Apply opacity transition to smooth the appearance
    opacity: state?.placement ? 1 : 0,
    transition: "opacity 0.1s",
    maxWidth: "80%",
    maxHeight: "80%",
    overflowY: "hidden"
  };
  if (!isOpen || hoverDelay > 0 && !shouldShowPopover) {
    return null;
  }
  const positionedStyle = state && state.styles && state.styles.popper ? {
    ...popperStyles.popper,
    opacity: 1
  } : {
    ...popperStyles.popper,
    opacity: 0,
    // Position offscreen initially to prevent flicker
    position: "fixed",
    top: "-9999px",
    left: "-9999px"
  };
  const popperContent = /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "div",
    {
      ref: popperRef,
      style: { ...defaultPopperStyles, ...positionedStyle, ...styles2 },
      className: clsx(className2),
      ...attributes.popper,
      children: [
        children2,
        showArrow && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(jsxDevRuntimeExports.Fragment, { children: [
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            "div",
            {
              ref: arrowRef,
              style: { position: "absolute", visibility: "hidden" },
              "data-placement": getArrowDataPlacement()
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/PopOver.tsx",
              lineNumber: 385,
              columnNumber: 11
            },
            void 0
          ),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            "div",
            {
              className: clsx("popper-arrow-container", arrowClassName),
              style: {
                ...popperStyles.arrow,
                position: "absolute",
                zIndex: 1,
                // Size and positioning based on placement - smaller arrow
                ...actualPlacement.startsWith("top") && {
                  bottom: "-8px",
                  width: "16px",
                  height: "8px"
                },
                ...actualPlacement.startsWith("bottom") && {
                  top: "-8px",
                  width: "16px",
                  height: "8px"
                },
                ...actualPlacement.startsWith("left") && {
                  right: "-8px",
                  width: "8px",
                  height: "16px"
                },
                ...actualPlacement.startsWith("right") && {
                  left: "-8px",
                  width: "8px",
                  height: "16px"
                },
                // Content positioning
                overflow: "hidden"
              },
              children: [
                actualPlacement.startsWith("top") && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
                  "div",
                  {
                    style: {
                      position: "absolute",
                      width: 0,
                      height: 0,
                      borderStyle: "solid",
                      borderWidth: "8px 8px 0 8px",
                      borderColor: "#eee transparent transparent transparent",
                      top: "0px",
                      left: "0px"
                    }
                  },
                  void 0,
                  false,
                  {
                    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/PopOver.tsx",
                    lineNumber: 425,
                    columnNumber: 15
                  },
                  void 0
                ),
                actualPlacement.startsWith("bottom") && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
                  "div",
                  {
                    style: {
                      position: "absolute",
                      width: 0,
                      height: 0,
                      borderStyle: "solid",
                      borderWidth: "0 8px 8px 8px",
                      borderColor: "transparent transparent #eee transparent",
                      top: "0px",
                      left: "0px"
                    }
                  },
                  void 0,
                  false,
                  {
                    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/PopOver.tsx",
                    lineNumber: 439,
                    columnNumber: 15
                  },
                  void 0
                ),
                actualPlacement.startsWith("left") && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
                  "div",
                  {
                    style: {
                      position: "absolute",
                      width: 0,
                      height: 0,
                      borderStyle: "solid",
                      borderWidth: "8px 0 8px 8px",
                      borderColor: "transparent transparent transparent #eee",
                      top: "0px",
                      left: "0px"
                    }
                  },
                  void 0,
                  false,
                  {
                    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/PopOver.tsx",
                    lineNumber: 453,
                    columnNumber: 15
                  },
                  void 0
                ),
                actualPlacement.startsWith("right") && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
                  "div",
                  {
                    style: {
                      position: "absolute",
                      width: 0,
                      height: 0,
                      borderStyle: "solid",
                      borderWidth: "8px 8px 8px 0",
                      borderColor: "transparent #eee transparent transparent",
                      top: "0px",
                      left: "0px"
                    }
                  },
                  void 0,
                  false,
                  {
                    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/PopOver.tsx",
                    lineNumber: 467,
                    columnNumber: 15
                  },
                  void 0
                ),
                /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
                  "div",
                  {
                    style: {
                      position: "absolute",
                      width: 0,
                      height: 0,
                      borderStyle: "solid",
                      backgroundColor: "transparent",
                      // Position relative to border triangle
                      left: "0px",
                      zIndex: 1,
                      // Top placement - pointing down
                      ...actualPlacement.startsWith("top") && {
                        borderWidth: "7px 7px 0 7px",
                        borderColor: "white transparent transparent transparent",
                        top: "0px"
                      },
                      // Bottom placement - pointing up
                      ...actualPlacement.startsWith("bottom") && {
                        borderWidth: "0 7px 7px 7px",
                        borderColor: "transparent transparent white transparent",
                        top: "1px"
                      },
                      // Left placement - pointing right
                      ...actualPlacement.startsWith("left") && {
                        borderWidth: "7px 0 7px 7px",
                        borderColor: "transparent transparent transparent white",
                        left: "0px"
                      },
                      // Right placement - pointing left
                      ...actualPlacement.startsWith("right") && {
                        borderWidth: "7px 7px 7px 0",
                        borderColor: "transparent white transparent transparent",
                        left: "1px"
                      }
                    }
                  },
                  void 0,
                  false,
                  {
                    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/PopOver.tsx",
                    lineNumber: 482,
                    columnNumber: 13
                  },
                  void 0
                )
              ]
            },
            void 0,
            true,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/PopOver.tsx",
              lineNumber: 392,
              columnNumber: 11
            },
            void 0
          )
        ] }, void 0, true, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/PopOver.tsx",
          lineNumber: 383,
          columnNumber: 9
        }, void 0)
      ]
    },
    void 0,
    true,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/PopOver.tsx",
      lineNumber: 374,
      columnNumber: 5
    },
    void 0
  );
  if (usePortal && portalContainer) {
    return reactDomExports.createPortal(popperContent, portalContainer);
  }
  return popperContent;
};
const MarkdownDivWithReferences = reactExports.forwardRef(({ markdown, references, className: className2, style: style2, omitMedia }, ref2) => {
  const containerRef = reactExports.useRef(null);
  const [positionEl, setPositionEl] = reactExports.useState(null);
  const [currentRef, setCurrentRef] = reactExports.useState(null);
  const showingRefPopover = useStore((state) => state.showingRefPopover);
  const setShowingRefPopover = useStore((state) => state.setShowingRefPopover);
  const clearShowingRefPopover = useStore(
    (state) => state.clearShowingRefPopover
  );
  const refMap = reactExports.useMemo(
    () => new Map(references?.map((ref22) => [ref22.id, ref22])),
    [references]
  );
  const postProcess2 = reactExports.useCallback(
    (html) => {
      let processedHtml = html;
      references?.forEach((ref22) => {
        const escapedCite = ref22.cite.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        const regex2 = new RegExp(escapedCite, "g");
        const href = ref22.citeUrl || "javascript:void(0)";
        const replacement = `<a href="${href}" class="${styles$1c.cite}" data-ref-id="${ref22.id}">${ref22.cite}</a>`;
        processedHtml = processedHtml.replace(regex2, replacement);
      });
      return processedHtml;
    },
    [references, styles$1c.cite]
  );
  const memoizedMarkdown = reactExports.useMemo(
    () => /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      MarkdownDiv,
      {
        ref: ref2,
        markdown,
        postProcess: postProcess2,
        className: className2,
        style: style2,
        omitMedia
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/MarkdownDivWithReferences.tsx",
        lineNumber: 79,
        columnNumber: 7
      },
      void 0
    ),
    [markdown, postProcess2]
  );
  reactExports.useEffect(() => {
    const container2 = containerRef.current;
    if (!container2) {
      return;
    }
    const citeLinks = container2.querySelectorAll(
      `.${styles$1c.cite}`
    );
    const handleMouseEnter = (e) => {
      const el = e.currentTarget;
      const id2 = el.getAttribute("data-ref-id");
      if (!id2) {
        return;
      }
      const ref22 = refMap.get(id2);
      if (!ref22) {
        return;
      }
      setPositionEl(el);
      setCurrentRef(ref22);
      setShowingRefPopover(popoverKey(ref22));
    };
    const handleClick = (e) => {
      e.stopPropagation();
    };
    const cleanup = [];
    citeLinks.forEach((link2) => {
      link2.addEventListener("mouseenter", handleMouseEnter);
      link2.addEventListener("click", handleClick);
      cleanup.push(() => {
        link2.removeEventListener("mouseenter", handleMouseEnter);
        link2.removeEventListener("click", handleClick);
      });
    });
    return () => {
      cleanup.forEach((fn3) => fn3());
    };
  }, [
    markdown,
    refMap,
    styles$1c.cite,
    setPositionEl,
    setCurrentRef,
    setShowingRefPopover
  ]);
  const key2 = currentRef ? popoverKey(currentRef) : "unknown-markdown-ref-popover";
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(className2), ref: containerRef, children: [
    memoizedMarkdown,
    positionEl && currentRef && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      PopOver,
      {
        id: key2,
        positionEl,
        isOpen: showingRefPopover === key2,
        setIsOpen: (isOpen) => {
          if (!isOpen) {
            clearShowingRefPopover();
            setCurrentRef(null);
            setPositionEl(null);
          }
        },
        placement: "auto",
        hoverDelay: 200,
        showArrow: true,
        children: currentRef.citePreview && currentRef.citePreview() || /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(NoContentsPanel, { text: "No preview available." }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/MarkdownDivWithReferences.tsx",
          lineNumber: 176,
          columnNumber: 13
        }, void 0)
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/MarkdownDivWithReferences.tsx",
        lineNumber: 160,
        columnNumber: 9
      },
      void 0
    )
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/MarkdownDivWithReferences.tsx",
    lineNumber: 157,
    columnNumber: 5
  }, void 0);
});
const popoverKey = (ref2) => `markdown-ref-popover-${ref2.id}`;
const content = "_content_13ihw_1";
const styles$1a = {
  content
};
reactExports.forwardRef(
  ({ text: text2, style: style2, className: className2 }, ref2) => {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "pre",
      {
        ref: ref2,
        className: clsx(styles$1a.content, "text-size-smaller", className2),
        style: style2,
        children: text2
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/Preformatted.tsx",
        lineNumber: 15,
        columnNumber: 7
      },
      void 0
    );
  }
);
const RenderedText = reactExports.forwardRef(({ markdown, references, style: style2, className: className2, forceRender, omitMedia }, ref2) => {
  {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      MarkdownDivWithReferences,
      {
        ref: ref2,
        markdown,
        references,
        style: style2,
        className: className2,
        omitMedia
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RenderedText.tsx",
        lineNumber: 25,
        columnNumber: 7
      },
      void 0
    );
  }
});
const isJson = (text2) => {
  text2 = text2.trim();
  if (text2.startsWith("{") && text2.endsWith("}")) {
    try {
      JSON.parse(text2);
      return true;
    } catch {
      return false;
    }
  }
  return false;
};
const asJsonObjArray = (text2) => {
  text2 = text2.trim();
  if (text2.startsWith("[") && text2.endsWith("]")) {
    try {
      const arr = JSON.parse(text2);
      if (Array.isArray(arr) && arr.every((item2) => typeof item2 === "object")) {
        return arr;
      } else {
        return void 0;
      }
    } catch {
      return void 0;
    }
  }
  return void 0;
};
const parsedJson = (text2) => {
  text2 = text2.trim();
  if (text2.startsWith("{") && text2.endsWith("}")) {
    try {
      return JSON.parse(text2);
    } catch {
      return void 0;
    }
  }
  return void 0;
};
const contentData = "_contentData_1sd1z_1";
const styles$19 = {
  contentData
};
const webSearch = "_webSearch_1376z_1";
const query$1 = "_query_1376z_8";
const styles$18 = {
  webSearch,
  query: query$1
};
const WebSearch = ({ query: query2 }) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$18.webSearch, "text-size-smaller"), children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("span", { className: clsx("text-style-label", "text-style-secondary"), children: "Web Search:" }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/content-data/WebSearch.tsx",
      lineNumber: 9,
      columnNumber: 7
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("span", { className: clsx(styles$18.query, "text-size-smallest"), children: query2 }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/content-data/WebSearch.tsx",
      lineNumber: 12,
      columnNumber: 7
    }, void 0)
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/content-data/WebSearch.tsx",
    lineNumber: 8,
    columnNumber: 5
  }, void 0);
};
const result$2 = "_result_1mixg_12";
const styles$17 = {
  result: result$2
};
const WebSearchResults = ({
  results
}) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(jsxDevRuntimeExports.Fragment, { children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "div",
      {
        className: clsx(
          styles$17.label,
          "text-style-label",
          "text-style-secondary",
          "text-size-smaller"
        ),
        children: "Results"
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/content-data/WebSearchResults.tsx",
        lineNumber: 17,
        columnNumber: 7
      },
      void 0
    ),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("ol", { className: clsx(styles$17.results, "text-size-smaller"), children: results.map((result2, index) => /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "li",
      {
        className: clsx(styles$17.result, "text-style-secondary"),
        children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "a",
          {
            href: result2.url,
            target: "_blank",
            rel: "noopener noreferrer",
            title: result2.url + (result2.page_age ? `
(Age: ${result2.page_age})` : ""),
            children: result2.title
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/content-data/WebSearchResults.tsx",
            lineNumber: 34,
            columnNumber: 13
          },
          void 0
        )
      },
      index,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/content-data/WebSearchResults.tsx",
        lineNumber: 30,
        columnNumber: 11
      },
      void 0
    )) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/content-data/WebSearchResults.tsx",
      lineNumber: 28,
      columnNumber: 7
    }, void 0)
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/content-data/WebSearchResults.tsx",
    lineNumber: 16,
    columnNumber: 5
  }, void 0);
};
const ContentDataView = ({ id: id2, contentData: contentData2 }) => {
  const renderableData = contentData2.data;
  const renderer = contentDataRenderers.find(
    (r2) => r2.canRender(renderableData)
  );
  if (!renderer) {
    const { encrypted_content, ...record } = renderableData;
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$19.contentData), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      RecordTree,
      {
        id: `${id2}-tree`,
        record,
        className: clsx(styles$19.data),
        defaultExpandLevel: 0
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/content-data/ContentDataView.tsx",
        lineNumber: 33,
        columnNumber: 9
      },
      void 0
    ) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/content-data/ContentDataView.tsx",
      lineNumber: 32,
      columnNumber: 7
    }, void 0);
  }
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$19.contentData), children: renderer.render(renderableData) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/content-data/ContentDataView.tsx",
    lineNumber: 44,
    columnNumber: 5
  }, void 0);
};
const webSearchServerToolRenderer = {
  name: "WebSearch",
  canRender: (data2) => {
    return data2.type === "server_tool_use" && data2.name === "web_search";
  },
  render: (data2) => {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(WebSearch, { query: data2.input.query }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/content-data/ContentDataView.tsx",
      lineNumber: 65,
      columnNumber: 12
    }, void 0);
  }
};
const webSearchResultsServerToolRenderer = {
  name: "WebSearchResults",
  canRender: (data2) => {
    return data2.type === "web_search_tool_result" && Array.isArray(data2.content);
  },
  render: (data2) => {
    const results = data2.content;
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(WebSearchResults, { results }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/content-data/ContentDataView.tsx",
      lineNumber: 79,
      columnNumber: 12
    }, void 0);
  }
};
const serverToolRenderer = {
  name: "ServerTool",
  canRender: (data2) => data2.type === "server_tool_use",
  render: (data2) => {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(jsxDevRuntimeExports.Fragment, { children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "div",
        {
          className: clsx(
            "text-style-label",
            "text-style-secondary",
            "text-size-smaller"
          ),
          children: "Server Tool"
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/content-data/ContentDataView.tsx",
          lineNumber: 89,
          columnNumber: 9
        },
        void 0
      ),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        RecordTree,
        {
          id: data2.name || "server-tool",
          record: data2,
          className: clsx(styles$19.data)
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/content-data/ContentDataView.tsx",
          lineNumber: 98,
          columnNumber: 9
        },
        void 0
      )
    ] }, void 0, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/content-data/ContentDataView.tsx",
      lineNumber: 88,
      columnNumber: 7
    }, void 0);
  }
};
const contentDataRenderers = [
  webSearchServerToolRenderer,
  webSearchResultsServerToolRenderer,
  serverToolRenderer
];
const isImage = (mimeType) => {
  return mimeType.startsWith("image/");
};
const documentFrame = "_documentFrame_1576h_1";
const documentFrameTitle = "_documentFrameTitle_1576h_9";
const downloadLink = "_downloadLink_1576h_16";
const imageDocument = "_imageDocument_1576h_21";
const styles$16 = {
  documentFrame,
  documentFrameTitle,
  downloadLink,
  imageDocument
};
const ContentDocumentView = ({
  id: id2,
  document: document2
}) => {
  const canDownloadFiles = false;
  if (isImage(document2.mime_type)) {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ContentDocumentFrame, { document: document2, downloadable: canDownloadFiles, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "img",
      {
        className: clsx(styles$16.imageDocument),
        src: document2.document,
        alt: document2.filename,
        id: id2
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/documents/ContentDocumentView.tsx",
        lineNumber: 24,
        columnNumber: 9
      },
      void 0
    ) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/documents/ContentDocumentView.tsx",
      lineNumber: 23,
      columnNumber: 7
    }, void 0);
  } else {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      ContentDocumentFrame,
      {
        document: document2,
        downloadable: canDownloadFiles
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/documents/ContentDocumentView.tsx",
        lineNumber: 34,
        columnNumber: 7
      },
      void 0
    );
  }
};
const ContentDocumentFrame = ({
  document: document2,
  children: children2,
  downloadable
}) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "div",
    {
      className: clsx(
        styles$16.documentFrame,
        "text-size-small",
        "text-style-secondary"
      ),
      children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$16.documentFrameTitle), children: [
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("i", { className: clsx(iconForMimeType(document2.mime_type)) }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/documents/ContentDocumentView.tsx",
            lineNumber: 62,
            columnNumber: 9
          }, void 0),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: downloadable ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            "a",
            {
              className: clsx(styles$16.downloadLink),
              onClick: () => {
              },
              children: document2.filename
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/documents/ContentDocumentView.tsx",
              lineNumber: 65,
              columnNumber: 13
            },
            void 0
          ) : document2.filename }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/documents/ContentDocumentView.tsx",
            lineNumber: 63,
            columnNumber: 9
          }, void 0)
        ] }, void 0, true, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/documents/ContentDocumentView.tsx",
          lineNumber: 61,
          columnNumber: 7
        }, void 0),
        children2
      ]
    },
    void 0,
    true,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/documents/ContentDocumentView.tsx",
      lineNumber: 54,
      columnNumber: 5
    },
    void 0
  );
};
const jsonMessage = "_jsonMessage_oxf8d_1";
const styles$15 = {
  jsonMessage
};
const JsonMessageContent = ({
  id: id2,
  json: json2,
  className: className2
}) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    RecordTree,
    {
      id: id2,
      record: json2,
      className: clsx(styles$15.jsonMessage, className2),
      useBorders: false
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/JsonMessageContent.tsx",
      lineNumber: 20,
      columnNumber: 5
    },
    void 0
  );
};
const decodeHtmlEntities = (text2) => {
  const parser = new DOMParser();
  const doc = parser.parseFromString(text2, "text/html");
  return doc.documentElement.textContent || text2;
};
const citations = "_citations_1ggvf_1";
const citationLink = "_citationLink_1ggvf_9";
const styles$14 = {
  citations,
  citationLink
};
const MessageCitations = ({ citations: citations2 }) => {
  if (citations2.length === 0) {
    return void 0;
  }
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$14.citations, "text-size-smallest"), children: citations2.map((citation, index) => /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(reactExports.Fragment, { children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("span", { children: index + 1 }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/MessageCitations.tsx",
      lineNumber: 23,
      columnNumber: 11
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(MessageCitation, { citation }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/MessageCitations.tsx",
      lineNumber: 24,
      columnNumber: 11
    }, void 0)
  ] }, index, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/MessageCitations.tsx",
    lineNumber: 22,
    columnNumber: 9
  }, void 0)) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/MessageCitations.tsx",
    lineNumber: 20,
    columnNumber: 5
  }, void 0);
};
const MessageCitation = ({ citation }) => {
  const innards = decodeHtmlEntities(
    citation.title ?? (typeof citation.cited_text === "string" ? citation.cited_text : citation.type === "url" ? citation.url : "")
  );
  return citation.type === "url" ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(UrlCitation, { citation, children: innards }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/MessageCitations.tsx",
    lineNumber: 45,
    columnNumber: 5
  }, void 0) : /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(OtherCitation, { children: innards }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/MessageCitations.tsx",
    lineNumber: 47,
    columnNumber: 5
  }, void 0);
};
const UrlCitation = ({
  children: children2,
  citation
}) => /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
  "a",
  {
    href: citation.url,
    target: "_blank",
    rel: "noopener noreferrer",
    className: clsx(styles$14.citationLink),
    title: citation.cited_text && typeof citation.cited_text === "string" ? `${citation.cited_text}
${citation.url}` : citation.url,
    children: children2
  },
  void 0,
  false,
  {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/MessageCitations.tsx",
    lineNumber: 55,
    columnNumber: 3
  },
  void 0
);
const OtherCitation = ({ children: children2 }) => /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(jsxDevRuntimeExports.Fragment, { children: children2 }, void 0, false, {
  fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/MessageCitations.tsx",
  lineNumber: 71,
  columnNumber: 3
}, void 0);
const contentImage = "_contentImage_8rgix_1";
const reasoning = "_reasoning_8rgix_6";
const styles$13 = {
  contentImage,
  reasoning
};
const mcpToolUse = "_mcpToolUse_1792k_1";
const title$3 = "_title_1792k_9";
const titleText = "_titleText_1792k_18";
const args = "_args_1792k_22";
const argLabel = "_argLabel_1792k_31";
const error$2 = "_error_1792k_35";
const toolPanel = "_toolPanel_1792k_40";
const styles$12 = {
  mcpToolUse,
  title: title$3,
  titleText,
  args,
  argLabel,
  error: error$2,
  toolPanel
};
const ServerToolCall = ({
  id: id2,
  content: content2,
  className: className2
}) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(McpToolUse, { id: id2, content: content2, className: className2 }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/server-tools/ServerToolCall.tsx",
    lineNumber: 27,
    columnNumber: 10
  }, void 0);
};
const McpToolUse = ({ id: id2, content: content2, className: className2 }) => {
  const args2 = resolveArgs(content2);
  const titleStr = content2.context ? `${content2.context} — ${content2.name}()` : `${content2.name}()`;
  const listToolsResult = maybeListTools(content2);
  const webSearchResult = maybeWebSearchResult(content2);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { id: id2, className: clsx(styles$12.mcpToolUse, className2), children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "div",
      {
        className: clsx(
          styles$12.title,
          "text-size-small",
          "text-style-secondary"
        ),
        children: [
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("i", { className: ApplicationIcons.role.tool }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/server-tools/ServerToolCall.tsx",
            lineNumber: 50,
            columnNumber: 9
          }, void 0),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("pre", { className: styles$12.titleText, children: titleStr }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/server-tools/ServerToolCall.tsx",
            lineNumber: 51,
            columnNumber: 9
          }, void 0),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: styles$12.type, children: content2.type }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/server-tools/ServerToolCall.tsx",
            lineNumber: 52,
            columnNumber: 9
          }, void 0)
        ]
      },
      void 0,
      true,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/server-tools/ServerToolCall.tsx",
        lineNumber: 43,
        columnNumber: 7
      },
      void 0
    ),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: styles$12.args, children: [
      Object.keys(args2).map((key2, index) => {
        const value2 = args2[key2];
        let valueRecord = void 0;
        if (Array.isArray(value2)) {
          valueRecord = {};
          for (let i2 = 0; i2 < value2.length; i2++) {
            valueRecord[`[${i2}]`] = value2[i2];
          }
        } else if (value2 && typeof value2 === "object") {
          valueRecord = value2;
        }
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(jsxDevRuntimeExports.Fragment, { children: [
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(LabelDiv, { label: key2 }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/server-tools/ServerToolCall.tsx",
            lineNumber: 71,
            columnNumber: 15
          }, void 0),
          valueRecord ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(RecordTree, { id: `${id2}-val-${index}`, record: valueRecord }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/server-tools/ServerToolCall.tsx",
            lineNumber: 73,
            columnNumber: 17
          }, void 0) : /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ValueDiv, { children: value2 }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/server-tools/ServerToolCall.tsx",
            lineNumber: 75,
            columnNumber: 17
          }, void 0)
        ] }, void 0, true, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/server-tools/ServerToolCall.tsx",
          lineNumber: 70,
          columnNumber: 13
        }, void 0);
      }),
      webSearchResult ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(jsxDevRuntimeExports.Fragment, { children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(LabelDiv, { label: "results" }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/server-tools/ServerToolCall.tsx",
          lineNumber: 83,
          columnNumber: 13
        }, void 0),
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ValueDiv, { children: webSearchResult.result.map((result2, index) => /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: styles$12.result, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "a",
          {
            href: result2.url,
            target: "_blank",
            rel: "noopener noreferrer",
            children: result2.title
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/server-tools/ServerToolCall.tsx",
            lineNumber: 87,
            columnNumber: 19
          },
          void 0
        ) }, index, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/server-tools/ServerToolCall.tsx",
          lineNumber: 86,
          columnNumber: 17
        }, void 0)) }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/server-tools/ServerToolCall.tsx",
          lineNumber: 84,
          columnNumber: 13
        }, void 0)
      ] }, void 0, true, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/server-tools/ServerToolCall.tsx",
        lineNumber: 82,
        columnNumber: 11
      }, void 0) : void 0,
      listToolsResult ? listToolsResult.result.map((tool2, index) => /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(jsxDevRuntimeExports.Fragment, { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        ExpandablePanel,
        {
          id: `${id2}-output`,
          collapse: true,
          className: clsx(styles$12.toolPanel),
          children: [
            /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(LabelDiv, { label: tool2.name }, void 0, false, {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/server-tools/ServerToolCall.tsx",
              lineNumber: 108,
              columnNumber: 19
            }, void 0),
            /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ValueDiv, { children: [
              /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: tool2.description }, void 0, false, {
                fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/server-tools/ServerToolCall.tsx",
                lineNumber: 110,
                columnNumber: 21
              }, void 0),
              /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
                RecordTree,
                {
                  id: `${id2}-tool-${index}`,
                  record: { schema: tool2.input_schema },
                  defaultExpandLevel: 0
                },
                void 0,
                false,
                {
                  fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/server-tools/ServerToolCall.tsx",
                  lineNumber: 111,
                  columnNumber: 21
                },
                void 0
              )
            ] }, void 0, true, {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/server-tools/ServerToolCall.tsx",
              lineNumber: 109,
              columnNumber: 19
            }, void 0)
          ]
        },
        void 0,
        true,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/server-tools/ServerToolCall.tsx",
          lineNumber: 103,
          columnNumber: 17
        },
        void 0
      ) }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/server-tools/ServerToolCall.tsx",
        lineNumber: 102,
        columnNumber: 15
      }, void 0)) : void 0
    ] }, void 0, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/server-tools/ServerToolCall.tsx",
      lineNumber: 55,
      columnNumber: 7
    }, void 0),
    content2.error ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: styles$12.error, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("span", { children: [
      "Error: ",
      content2.error
    ] }, void 0, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/server-tools/ServerToolCall.tsx",
      lineNumber: 125,
      columnNumber: 11
    }, void 0) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/server-tools/ServerToolCall.tsx",
      lineNumber: 124,
      columnNumber: 9
    }, void 0) : !listToolsResult && !webSearchResult ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("text-size-small"), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ExpandablePanel, { id: `${id2}-output`, collapse: true, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      RenderedContent,
      {
        id: `${id2}-output`,
        entry: { name: "Output", value: content2.result },
        renderOptions: { renderString: "markdown" }
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/server-tools/ServerToolCall.tsx",
        lineNumber: 130,
        columnNumber: 13
      },
      void 0
    ) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/server-tools/ServerToolCall.tsx",
      lineNumber: 129,
      columnNumber: 11
    }, void 0) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/server-tools/ServerToolCall.tsx",
      lineNumber: 128,
      columnNumber: 9
    }, void 0) : void 0
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/server-tools/ServerToolCall.tsx",
    lineNumber: 42,
    columnNumber: 5
  }, void 0);
};
const resolveArgs = (content2) => {
  if (typeof content2.arguments === "string") {
    if (isJson(content2.arguments)) {
      try {
        return JSON.parse(content2.arguments);
      } catch (e) {
        console.warn("Failed to parse arguments as JSON", e);
      }
    }
    if (content2.arguments) {
      return { arguments: content2.arguments };
    }
    return {};
  } else if (typeof content2.arguments === "object") {
    return content2.arguments;
  } else if (content2.arguments) {
    return { arguments: content2.arguments };
  } else {
    return {};
  }
};
const maybeWebSearchResult = (content2) => {
  if (content2.name !== "web_search") {
    return void 0;
  }
  const objArray = asJsonObjArray(content2.result);
  if (objArray !== void 0) {
    return { result: objArray };
  }
};
const maybeListTools = (content2) => {
  if (content2.name !== "mcp_list_tools") {
    return void 0;
  }
  const objArray = asJsonObjArray(content2.result);
  if (objArray !== void 0) {
    return { result: objArray };
  }
};
const LabelDiv = ({ label: label2 }) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "div",
    {
      className: clsx(
        styles$12.argLabel,
        "text-style-secondary",
        "text-size-smaller"
      ),
      children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("pre", { children: label2 }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/server-tools/ServerToolCall.tsx",
        lineNumber: 198,
        columnNumber: 7
      }, void 0)
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/server-tools/ServerToolCall.tsx",
      lineNumber: 191,
      columnNumber: 5
    },
    void 0
  );
};
const ValueDiv = ({ children: children2 }) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("text-size-smaller"), children: children2 }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/server-tools/ServerToolCall.tsx",
    lineNumber: 204,
    columnNumber: 10
  }, void 0);
};
const toolImage = "_toolImage_1wvgr_1";
const output = "_output_1wvgr_6";
const textOutput = "_textOutput_1wvgr_10";
const textCode = "_textCode_1wvgr_18";
const styles$11 = {
  toolImage,
  output,
  textOutput,
  textCode
};
const ToolOutput = ({ output: output2, className: className2 }) => {
  if (!output2) {
    return null;
  }
  const outputs = [];
  if (Array.isArray(output2)) {
    output2.forEach((out, idx) => {
      const key2 = `tool-output-${idx}`;
      if (out.type === "text") {
        outputs.push(/* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ToolTextOutput, { text: out.text }, key2, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/ToolOutput.tsx",
          lineNumber: 30,
          columnNumber: 22
        }, void 0));
      } else {
        if (out.image.startsWith("data:")) {
          outputs.push(
            /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("img", { className: clsx(styles$11.toolImage), src: out.image }, key2, false, {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/ToolOutput.tsx",
              lineNumber: 34,
              columnNumber: 13
            }, void 0)
          );
        } else {
          outputs.push(/* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ToolTextOutput, { text: String(out.image) }, key2, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/ToolOutput.tsx",
            lineNumber: 37,
            columnNumber: 24
          }, void 0));
        }
      }
    });
  } else {
    outputs.push(
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ToolTextOutput, { text: String(output2) }, "tool-output-single", false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/ToolOutput.tsx",
        lineNumber: 43,
        columnNumber: 7
      }, void 0)
    );
  }
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$11.output, className2), children: outputs }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/ToolOutput.tsx",
    lineNumber: 46,
    columnNumber: 10
  }, void 0);
};
const ToolTextOutput = ({ text: text2 }) => {
  if (isJson(text2)) {
    const obj = JSON.parse(text2);
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(JsonMessageContent, { id: `1-json`, json: obj }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/ToolOutput.tsx",
      lineNumber: 59,
      columnNumber: 12
    }, void 0);
  }
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("pre", { className: clsx(styles$11.textOutput, "tool-output"), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("code", { className: clsx("sourceCode", styles$11.textCode), children: text2.trim() }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/ToolOutput.tsx",
    lineNumber: 64,
    columnNumber: 7
  }, void 0) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/ToolOutput.tsx",
    lineNumber: 63,
    columnNumber: 5
  }, void 0);
};
const isMessageContent = (content2) => {
  return typeof content2 === "object" && content2 !== null && "type" in content2 && typeof content2.type === "string";
};
const MessageContent = ({
  contents: contents2,
  context
}) => {
  const normalized = normalizeContent$2(contents2);
  if (Array.isArray(normalized)) {
    return normalized.map((content2, index) => {
      if (typeof content2 === "string") {
        return messageRenderers["text"]?.render(
          `text-content-${index}`,
          {
            type: "text",
            text: content2,
            refusal: null,
            internal: null,
            citations: null
          },
          index === contents2.length - 1,
          context
        );
      } else {
        if (content2) {
          const renderer = messageRenderers[content2.type];
          if (renderer) {
            return renderer.render(
              `text-${content2.type}-${index}`,
              content2,
              index === contents2.length - 1,
              context
            );
          } else {
            console.error(`Unknown message content type '${content2.type}'`);
          }
        }
      }
    });
  } else {
    const contentText = {
      type: "text",
      text: normalized,
      refusal: null,
      internal: null,
      citations: null
    };
    return messageRenderers["text"]?.render(
      "text-message-content",
      contentText,
      true,
      context
    );
  }
};
const messageRenderers = {
  text: {
    render: (key2, content2, isLast, _context) => {
      const c2 = content2;
      const cites = c2.citations ?? [];
      if (!c2.text && !cites.length) {
        return void 0;
      }
      const purgeInternalContainers = (text2) => {
        const internalTags = ["internal", "content-internal", "think"];
        internalTags.forEach((tag) => {
          const regex2 = new RegExp(`<${tag}[^>]*>[\\s\\S]*?<\\/${tag}>`, "gm");
          text2 = text2.replace(regex2, "");
        });
        return text2.trim();
      };
      if (isJson(c2.text)) {
        const obj = JSON.parse(c2.text);
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(JsonMessageContent, { id: `${key2}-json`, json: obj }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/MessageContent.tsx",
          lineNumber: 154,
          columnNumber: 16
        }, void 0);
      } else {
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(reactExports.Fragment, { children: [
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            RenderedText,
            {
              markdown: purgeInternalContainers(c2.text) || "",
              className: isLast ? "no-last-para-padding" : ""
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/MessageContent.tsx",
              lineNumber: 158,
              columnNumber: 13
            },
            void 0
          ),
          c2.citations && c2.citations.length > 0 ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(MessageCitations, { citations: c2.citations }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/MessageContent.tsx",
            lineNumber: 163,
            columnNumber: 15
          }, void 0) : void 0
        ] }, key2, true, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/MessageContent.tsx",
          lineNumber: 157,
          columnNumber: 11
        }, void 0);
      }
    }
  },
  reasoning: {
    render: (key2, content2, isLast, _context) => {
      const r2 = content2;
      let text2 = r2.reasoning;
      if (r2.redacted) {
        text2 = r2.summary || "Reasoning encrypted by model provider.";
      } else if (!text2) {
        text2 = r2.summary || "Reasoning text not provided.";
      }
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$13.reasoning, "text-size-small"), children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "div",
          {
            className: clsx(
              "text-style-label",
              "text-style-secondary",
              isLast ? "no-last-para-padding" : ""
            ),
            children: "Reasoning"
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/MessageContent.tsx",
            lineNumber: 183,
            columnNumber: 11
          },
          void 0
        ),
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ExpandablePanel, { id: `${key2}-reasoning`, collapse: true, children: [
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(RenderedText, { markdown: text2 }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/MessageContent.tsx",
            lineNumber: 193,
            columnNumber: 13
          }, void 0),
          " "
        ] }, void 0, true, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/MessageContent.tsx",
          lineNumber: 192,
          columnNumber: 11
        }, void 0)
      ] }, key2, true, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/MessageContent.tsx",
        lineNumber: 182,
        columnNumber: 9
      }, void 0);
    }
  },
  image: {
    render: (key2, content2, _isLast, _context) => {
      const c2 = content2;
      if (c2.image.startsWith("data:")) {
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("img", { src: c2.image, className: styles$13.contentImage }, key2, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/MessageContent.tsx",
          lineNumber: 203,
          columnNumber: 16
        }, void 0);
      } else {
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("code", { children: c2.image }, key2, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/MessageContent.tsx",
          lineNumber: 205,
          columnNumber: 16
        }, void 0);
      }
    }
  },
  audio: {
    render: (key2, content2, _isLast, _context) => {
      const c2 = content2;
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("audio", { controls: true, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("source", { src: c2.audio, type: mimeTypeForFormat(c2.format) }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/MessageContent.tsx",
        lineNumber: 214,
        columnNumber: 11
      }, void 0) }, key2, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/MessageContent.tsx",
        lineNumber: 213,
        columnNumber: 9
      }, void 0);
    }
  },
  video: {
    render: (key2, content2, _isLast, _context) => {
      const c2 = content2;
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("video", { width: "500", height: "375", controls: true, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("source", { src: c2.video, type: mimeTypeForFormat(c2.format) }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/MessageContent.tsx",
        lineNumber: 224,
        columnNumber: 11
      }, void 0) }, key2, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/MessageContent.tsx",
        lineNumber: 223,
        columnNumber: 9
      }, void 0);
    }
  },
  tool: {
    render: (key2, content2, _isLast, _context) => {
      const c2 = content2;
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ToolOutput, { output: c2.content }, key2, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/MessageContent.tsx",
        lineNumber: 232,
        columnNumber: 14
      }, void 0);
    }
  },
  // server-side tool use
  tool_use: {
    render: (key2, content2, _isLast, _context) => {
      const c2 = content2;
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ServerToolCall, { id: key2, content: c2 }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/MessageContent.tsx",
        lineNumber: 240,
        columnNumber: 14
      }, void 0);
    }
  },
  data: {
    render: (key2, content2, _isLast, _context) => {
      const c2 = content2;
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ContentDataView, { id: key2, contentData: c2 }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/MessageContent.tsx",
        lineNumber: 246,
        columnNumber: 14
      }, void 0);
    }
  },
  document: {
    render: (key2, content2, _isLast, _context) => {
      const c2 = content2;
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ContentDocumentView, { id: key2, document: c2 }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/MessageContent.tsx",
        lineNumber: 252,
        columnNumber: 14
      }, void 0);
    }
  }
};
const mimeTypeForFormat = (format2) => {
  switch (format2) {
    case "mov":
      return "video/quicktime";
    case "wav":
      return "audio/wav";
    case "mp3":
      return "audio/mpeg";
    case "mp4":
      return "video/mp4";
    case "mpeg":
      return "video/mpeg";
    default:
      return "video/mp4";
  }
};
const normalizeContent$2 = (contents2) => {
  if (typeof contents2 === "string") {
    return contents2;
  }
  if (contents2.length > 0 && typeof contents2[0] === "string") {
    return contents2;
  }
  const result2 = [];
  const collection = [];
  const collect = () => {
    if (collection.length > 0) {
      const filteredCitations = collection.flatMap((c2) => c2.citations || []);
      let citeCount = 0;
      const textWithCites = collection.map((c2) => {
        const positionalCites = (c2.citations ?? []).filter(isCitationWithRange).sort((a2, b) => b.cited_text[1] - a2.cited_text[1]);
        const endCites = c2.citations?.filter(
          (citation) => !isCitationWithRange(citation)
        );
        let textWithCites2 = c2.text;
        for (let i2 = 0; i2 < positionalCites.length; i2++) {
          const end_index = positionalCites[i2]?.cited_text[1];
          textWithCites2 = textWithCites2.slice(0, end_index) + `<sup>${positionalCites.length - i2}</sup>` + textWithCites2.slice(end_index);
        }
        citeCount = citeCount + positionalCites.length;
        const citeText = endCites?.map((_citation) => `${++citeCount}`);
        let inlineCites = "";
        if (citeText && citeText.length > 0) {
          inlineCites = `<sup>${citeText.join(",")}</sup>`;
        }
        return (textWithCites2 || "") + inlineCites;
      }).join("");
      result2.push({
        type: "text",
        text: textWithCites,
        refusal: null,
        internal: null,
        citations: filteredCitations
      });
      collection.length = 0;
    }
  };
  for (const content2 of contents2) {
    if (typeof content2 === "string") {
      result2.push({
        type: "text",
        text: content2,
        refusal: null,
        internal: null,
        citations: null
      });
      continue;
    }
    if (content2.type === "text") {
      collection.push(content2);
      continue;
    } else {
      collect();
      result2.push(content2);
    }
  }
  collect();
  return result2;
};
const isCitationWithRange = (citation) => Array.isArray(citation.cited_text);
const defaultContext = () => {
  return {
    citeOffset: 0,
    citations: []
  };
};
const MessageContents = ({ message: message2 }) => {
  const context = defaultContext();
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(jsxDevRuntimeExports.Fragment, { children: message2.content && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(MessageContent, { contents: message2.content, context }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/MessageContents.tsx",
    lineNumber: 37,
    columnNumber: 9
  }, void 0) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/MessageContents.tsx",
    lineNumber: 35,
    columnNumber: 5
  }, void 0);
};
const ChatMessage = reactExports.memo(
  ({ id: id2, message: message2, indented: indented2, allowLinking = true }) => {
    const messageUrl = void 0;
    const supportsLinking = reactExports.useCallback(() => {
      return false;
    }, []);
    const toFullUrl = reactExports.useCallback((url) => {
      return url;
    }, []);
    const collapse = message2.role === "system" || message2.role === "user";
    const [mouseOver, setMouseOver] = reactExports.useState(false);
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "div",
      {
        className: clsx(
          message2.role,
          "text-size-base",
          styles$1d.message,
          message2.role === "system" ? styles$1d.systemRole : void 0,
          message2.role === "user" ? styles$1d.userRole : void 0,
          mouseOver ? styles$1d.hover : void 0
        ),
        onMouseEnter: () => setMouseOver(true),
        onMouseLeave: () => setMouseOver(false),
        children: [
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            "div",
            {
              className: clsx(
                styles$1d.messageGrid,
                message2.role === "tool" ? styles$1d.toolMessageGrid : void 0,
                "text-style-label"
              ),
              children: [
                message2.role,
                message2.role === "tool" ? `: ${message2.function}` : "",
                supportsLinking() && messageUrl ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
                  CopyButton,
                  {
                    icon: ApplicationIcons.link,
                    value: toFullUrl(messageUrl),
                    className: clsx(styles$1d.copyLink)
                  },
                  void 0,
                  false,
                  {
                    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/ChatMessage.tsx",
                    lineNumber: 71,
                    columnNumber: 13
                  },
                  void 0
                ) : ""
              ]
            },
            void 0,
            true,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/ChatMessage.tsx",
              lineNumber: 61,
              columnNumber: 9
            },
            void 0
          ),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            "div",
            {
              className: clsx(
                styles$1d.messageContents,
                indented2 ? styles$1d.indented : void 0
              ),
              children: [
                /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
                  ExpandablePanel,
                  {
                    id: `${id2}-message`,
                    collapse,
                    lines: collapse ? 15 : 25,
                    children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(MessageContents, { message: message2 }, `${id2}-contents`, false, {
                      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/ChatMessage.tsx",
                      lineNumber: 91,
                      columnNumber: 13
                    }, void 0)
                  },
                  void 0,
                  false,
                  {
                    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/ChatMessage.tsx",
                    lineNumber: 86,
                    columnNumber: 11
                  },
                  void 0
                ),
                message2.metadata && Object.keys(message2.metadata).length > 0 ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
                  LabeledValue,
                  {
                    label: "Metadata",
                    className: clsx(styles$1d.metadataLabel, "text-size-smaller"),
                    children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
                      RecordTree,
                      {
                        record: message2.metadata,
                        id: `${id2}-metadata`,
                        defaultExpandLevel: 0
                      },
                      void 0,
                      false,
                      {
                        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/ChatMessage.tsx",
                        lineNumber: 99,
                        columnNumber: 15
                      },
                      void 0
                    )
                  },
                  void 0,
                  false,
                  {
                    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/ChatMessage.tsx",
                    lineNumber: 95,
                    columnNumber: 13
                  },
                  void 0
                ) : ""
              ]
            },
            void 0,
            true,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/ChatMessage.tsx",
              lineNumber: 80,
              columnNumber: 9
            },
            void 0
          )
        ]
      },
      void 0,
      true,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/ChatMessage.tsx",
        lineNumber: 49,
        columnNumber: 7
      },
      void 0
    );
  }
);
const grid$3 = "_grid_17ltx_1";
const number = "_number_17ltx_8";
const user = "_user_17ltx_12";
const container$f = "_container_17ltx_18";
const first = "_first_17ltx_26";
const last = "_last_17ltx_33";
const label$4 = "_label_17ltx_40";
const highlight = "_highlight_17ltx_44";
const bottomMargin = "_bottomMargin_17ltx_48";
const styles$10 = {
  grid: grid$3,
  number,
  user,
  container: container$f,
  first,
  last,
  label: label$4,
  highlight,
  bottomMargin
};
(function(Prism2) {
  var envVars = "\\b(?:BASH|BASHOPTS|BASH_ALIASES|BASH_ARGC|BASH_ARGV|BASH_CMDS|BASH_COMPLETION_COMPAT_DIR|BASH_LINENO|BASH_REMATCH|BASH_SOURCE|BASH_VERSINFO|BASH_VERSION|COLORTERM|COLUMNS|COMP_WORDBREAKS|DBUS_SESSION_BUS_ADDRESS|DEFAULTS_PATH|DESKTOP_SESSION|DIRSTACK|DISPLAY|EUID|GDMSESSION|GDM_LANG|GNOME_KEYRING_CONTROL|GNOME_KEYRING_PID|GPG_AGENT_INFO|GROUPS|HISTCONTROL|HISTFILE|HISTFILESIZE|HISTSIZE|HOME|HOSTNAME|HOSTTYPE|IFS|INSTANCE|JOB|LANG|LANGUAGE|LC_ADDRESS|LC_ALL|LC_IDENTIFICATION|LC_MEASUREMENT|LC_MONETARY|LC_NAME|LC_NUMERIC|LC_PAPER|LC_TELEPHONE|LC_TIME|LESSCLOSE|LESSOPEN|LINES|LOGNAME|LS_COLORS|MACHTYPE|MAILCHECK|MANDATORY_PATH|NO_AT_BRIDGE|OLDPWD|OPTERR|OPTIND|ORBIT_SOCKETDIR|OSTYPE|PAPERSIZE|PATH|PIPESTATUS|PPID|PS1|PS2|PS3|PS4|PWD|RANDOM|REPLY|SECONDS|SELINUX_INIT|SESSION|SESSIONTYPE|SESSION_MANAGER|SHELL|SHELLOPTS|SHLVL|SSH_AUTH_SOCK|TERM|UID|UPSTART_EVENTS|UPSTART_INSTANCE|UPSTART_JOB|UPSTART_SESSION|USER|WINDOWID|XAUTHORITY|XDG_CONFIG_DIRS|XDG_CURRENT_DESKTOP|XDG_DATA_DIRS|XDG_GREETER_DATA_DIR|XDG_MENU_PREFIX|XDG_RUNTIME_DIR|XDG_SEAT|XDG_SEAT_PATH|XDG_SESSION_DESKTOP|XDG_SESSION_ID|XDG_SESSION_PATH|XDG_SESSION_TYPE|XDG_VTNR|XMODIFIERS)\\b";
  var commandAfterHeredoc = {
    pattern: /(^(["']?)\w+\2)[ \t]+\S.*/,
    lookbehind: true,
    alias: "punctuation",
    // this looks reasonably well in all themes
    inside: null
    // see below
  };
  var insideString = {
    "bash": commandAfterHeredoc,
    "environment": {
      pattern: RegExp("\\$" + envVars),
      alias: "constant"
    },
    "variable": [
      // [0]: Arithmetic Environment
      {
        pattern: /\$?\(\([\s\S]+?\)\)/,
        greedy: true,
        inside: {
          // If there is a $ sign at the beginning highlight $(( and )) as variable
          "variable": [
            {
              pattern: /(^\$\(\([\s\S]+)\)\)/,
              lookbehind: true
            },
            /^\$\(\(/
          ],
          "number": /\b0x[\dA-Fa-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:[Ee]-?\d+)?/,
          // Operators according to https://www.gnu.org/software/bash/manual/bashref.html#Shell-Arithmetic
          "operator": /--|\+\+|\*\*=?|<<=?|>>=?|&&|\|\||[=!+\-*/%<>^&|]=?|[?~:]/,
          // If there is no $ sign at the beginning highlight (( and )) as punctuation
          "punctuation": /\(\(?|\)\)?|,|;/
        }
      },
      // [1]: Command Substitution
      {
        pattern: /\$\((?:\([^)]+\)|[^()])+\)|`[^`]+`/,
        greedy: true,
        inside: {
          "variable": /^\$\(|^`|\)$|`$/
        }
      },
      // [2]: Brace expansion
      {
        pattern: /\$\{[^}]+\}/,
        greedy: true,
        inside: {
          "operator": /:[-=?+]?|[!\/]|##?|%%?|\^\^?|,,?/,
          "punctuation": /[\[\]]/,
          "environment": {
            pattern: RegExp("(\\{)" + envVars),
            lookbehind: true,
            alias: "constant"
          }
        }
      },
      /\$(?:\w+|[#?*!@$])/
    ],
    // Escape sequences from echo and printf's manuals, and escaped quotes.
    "entity": /\\(?:[abceEfnrtv\\"]|O?[0-7]{1,3}|U[0-9a-fA-F]{8}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{1,2})/
  };
  Prism2.languages.bash = {
    "shebang": {
      pattern: /^#!\s*\/.*/,
      alias: "important"
    },
    "comment": {
      pattern: /(^|[^"{\\$])#.*/,
      lookbehind: true
    },
    "function-name": [
      // a) function foo {
      // b) foo() {
      // c) function foo() {
      // but not “foo {”
      {
        // a) and c)
        pattern: /(\bfunction\s+)[\w-]+(?=(?:\s*\(?:\s*\))?\s*\{)/,
        lookbehind: true,
        alias: "function"
      },
      {
        // b)
        pattern: /\b[\w-]+(?=\s*\(\s*\)\s*\{)/,
        alias: "function"
      }
    ],
    // Highlight variable names as variables in for and select beginnings.
    "for-or-select": {
      pattern: /(\b(?:for|select)\s+)\w+(?=\s+in\s)/,
      alias: "variable",
      lookbehind: true
    },
    // Highlight variable names as variables in the left-hand part
    // of assignments (“=” and “+=”).
    "assign-left": {
      pattern: /(^|[\s;|&]|[<>]\()\w+(?:\.\w+)*(?=\+?=)/,
      inside: {
        "environment": {
          pattern: RegExp("(^|[\\s;|&]|[<>]\\()" + envVars),
          lookbehind: true,
          alias: "constant"
        }
      },
      alias: "variable",
      lookbehind: true
    },
    // Highlight parameter names as variables
    "parameter": {
      pattern: /(^|\s)-{1,2}(?:\w+:[+-]?)?\w+(?:\.\w+)*(?=[=\s]|$)/,
      alias: "variable",
      lookbehind: true
    },
    "string": [
      // Support for Here-documents https://en.wikipedia.org/wiki/Here_document
      {
        pattern: /((?:^|[^<])<<-?\s*)(\w+)\s[\s\S]*?(?:\r?\n|\r)\2/,
        lookbehind: true,
        greedy: true,
        inside: insideString
      },
      // Here-document with quotes around the tag
      // → No expansion (so no “inside”).
      {
        pattern: /((?:^|[^<])<<-?\s*)(["'])(\w+)\2\s[\s\S]*?(?:\r?\n|\r)\3/,
        lookbehind: true,
        greedy: true,
        inside: {
          "bash": commandAfterHeredoc
        }
      },
      // “Normal” string
      {
        // https://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html
        pattern: /(^|[^\\](?:\\\\)*)"(?:\\[\s\S]|\$\([^)]+\)|\$(?!\()|`[^`]+`|[^"\\`$])*"/,
        lookbehind: true,
        greedy: true,
        inside: insideString
      },
      {
        // https://www.gnu.org/software/bash/manual/html_node/Single-Quotes.html
        pattern: /(^|[^$\\])'[^']*'/,
        lookbehind: true,
        greedy: true
      },
      {
        // https://www.gnu.org/software/bash/manual/html_node/ANSI_002dC-Quoting.html
        pattern: /\$'(?:[^'\\]|\\[\s\S])*'/,
        greedy: true,
        inside: {
          "entity": insideString.entity
        }
      }
    ],
    "environment": {
      pattern: RegExp("\\$?" + envVars),
      alias: "constant"
    },
    "variable": insideString.variable,
    "function": {
      pattern: /(^|[\s;|&]|[<>]\()(?:add|apropos|apt|apt-cache|apt-get|aptitude|aspell|automysqlbackup|awk|basename|bash|bc|bconsole|bg|bzip2|cal|cargo|cat|cfdisk|chgrp|chkconfig|chmod|chown|chroot|cksum|clear|cmp|column|comm|composer|cp|cron|crontab|csplit|curl|cut|date|dc|dd|ddrescue|debootstrap|df|diff|diff3|dig|dir|dircolors|dirname|dirs|dmesg|docker|docker-compose|du|egrep|eject|env|ethtool|expand|expect|expr|fdformat|fdisk|fg|fgrep|file|find|fmt|fold|format|free|fsck|ftp|fuser|gawk|git|gparted|grep|groupadd|groupdel|groupmod|groups|grub-mkconfig|gzip|halt|head|hg|history|host|hostname|htop|iconv|id|ifconfig|ifdown|ifup|import|install|ip|java|jobs|join|kill|killall|less|link|ln|locate|logname|logrotate|look|lpc|lpr|lprint|lprintd|lprintq|lprm|ls|lsof|lynx|make|man|mc|mdadm|mkconfig|mkdir|mke2fs|mkfifo|mkfs|mkisofs|mknod|mkswap|mmv|more|most|mount|mtools|mtr|mutt|mv|nano|nc|netstat|nice|nl|node|nohup|notify-send|npm|nslookup|op|open|parted|passwd|paste|pathchk|ping|pkill|pnpm|podman|podman-compose|popd|pr|printcap|printenv|ps|pushd|pv|quota|quotacheck|quotactl|ram|rar|rcp|reboot|remsync|rename|renice|rev|rm|rmdir|rpm|rsync|scp|screen|sdiff|sed|sendmail|seq|service|sftp|sh|shellcheck|shuf|shutdown|sleep|slocate|sort|split|ssh|stat|strace|su|sudo|sum|suspend|swapon|sync|sysctl|tac|tail|tar|tee|time|timeout|top|touch|tr|traceroute|tsort|tty|umount|uname|unexpand|uniq|units|unrar|unshar|unzip|update-grub|uptime|useradd|userdel|usermod|users|uudecode|uuencode|v|vcpkg|vdir|vi|vim|virsh|vmstat|wait|watch|wc|wget|whereis|which|who|whoami|write|xargs|xdg-open|yarn|yes|zenity|zip|zsh|zypper)(?=$|[)\s;|&])/,
      lookbehind: true
    },
    "keyword": {
      pattern: /(^|[\s;|&]|[<>]\()(?:case|do|done|elif|else|esac|fi|for|function|if|in|select|then|until|while)(?=$|[)\s;|&])/,
      lookbehind: true
    },
    // https://www.gnu.org/software/bash/manual/html_node/Shell-Builtin-Commands.html
    "builtin": {
      pattern: /(^|[\s;|&]|[<>]\()(?:\.|:|alias|bind|break|builtin|caller|cd|command|continue|declare|echo|enable|eval|exec|exit|export|getopts|hash|help|let|local|logout|mapfile|printf|pwd|read|readarray|readonly|return|set|shift|shopt|source|test|times|trap|type|typeset|ulimit|umask|unalias|unset)(?=$|[)\s;|&])/,
      lookbehind: true,
      // Alias added to make those easier to distinguish from strings.
      alias: "class-name"
    },
    "boolean": {
      pattern: /(^|[\s;|&]|[<>]\()(?:false|true)(?=$|[)\s;|&])/,
      lookbehind: true
    },
    "file-descriptor": {
      pattern: /\B&\d\b/,
      alias: "important"
    },
    "operator": {
      // Lots of redirections here, but not just that.
      pattern: /\d?<>|>\||\+=|=[=~]?|!=?|<<[<-]?|[&\d]?>>|\d[<>]&?|[<>][&=]?|&[>&]?|\|[&|]?/,
      inside: {
        "file-descriptor": {
          pattern: /^\d/,
          alias: "important"
        }
      }
    },
    "punctuation": /\$?\(\(?|\)\)?|\.\.|[{}[\];\\]/,
    "number": {
      pattern: /(^|\s)(?:[1-9]\d*|0)(?:[.,]\d+)?\b/,
      lookbehind: true
    }
  };
  commandAfterHeredoc.inside = Prism2.languages.bash;
  var toBeCopied = [
    "comment",
    "function-name",
    "for-or-select",
    "assign-left",
    "parameter",
    "string",
    "environment",
    "function",
    "keyword",
    "builtin",
    "boolean",
    "file-descriptor",
    "operator",
    "punctuation",
    "number"
  ];
  var inside = insideString.variable[1].inside;
  for (var i2 = 0; i2 < toBeCopied.length; i2++) {
    inside[toBeCopied[i2]] = Prism2.languages.bash[toBeCopied[i2]];
  }
  Prism2.languages.sh = Prism2.languages.bash;
  Prism2.languages.shell = Prism2.languages.bash;
})(Prism);
Prism.languages.json = {
  "property": {
    pattern: /(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?=\s*:)/,
    lookbehind: true,
    greedy: true
  },
  "string": {
    pattern: /(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?!\s*:)/,
    lookbehind: true,
    greedy: true
  },
  "comment": {
    pattern: /\/\/.*|\/\*[\s\S]*?(?:\*\/|$)/,
    greedy: true
  },
  "number": /-?\b\d+(?:\.\d+)?(?:e[+-]?\d+)?\b/i,
  "punctuation": /[{}[\],]/,
  "operator": /:/,
  "boolean": /\b(?:false|true)\b/,
  "null": {
    pattern: /\bnull\b/,
    alias: "keyword"
  }
};
Prism.languages.webmanifest = Prism.languages.json;
var prismPython = {};
var hasRequiredPrismPython;
function requirePrismPython() {
  if (hasRequiredPrismPython) return prismPython;
  hasRequiredPrismPython = 1;
  Prism.languages.python = {
    "comment": {
      pattern: /(^|[^\\])#.*/,
      lookbehind: true,
      greedy: true
    },
    "string-interpolation": {
      pattern: /(?:f|fr|rf)(?:("""|''')[\s\S]*?\1|("|')(?:\\.|(?!\2)[^\\\r\n])*\2)/i,
      greedy: true,
      inside: {
        "interpolation": {
          // "{" <expression> <optional "!s", "!r", or "!a"> <optional ":" format specifier> "}"
          pattern: /((?:^|[^{])(?:\{\{)*)\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}])+\})+\})+\}/,
          lookbehind: true,
          inside: {
            "format-spec": {
              pattern: /(:)[^:(){}]+(?=\}$)/,
              lookbehind: true
            },
            "conversion-option": {
              pattern: /![sra](?=[:}]$)/,
              alias: "punctuation"
            },
            rest: null
          }
        },
        "string": /[\s\S]+/
      }
    },
    "triple-quoted-string": {
      pattern: /(?:[rub]|br|rb)?("""|''')[\s\S]*?\1/i,
      greedy: true,
      alias: "string"
    },
    "string": {
      pattern: /(?:[rub]|br|rb)?("|')(?:\\.|(?!\1)[^\\\r\n])*\1/i,
      greedy: true
    },
    "function": {
      pattern: /((?:^|\s)def[ \t]+)[a-zA-Z_]\w*(?=\s*\()/g,
      lookbehind: true
    },
    "class-name": {
      pattern: /(\bclass\s+)\w+/i,
      lookbehind: true
    },
    "decorator": {
      pattern: /(^[\t ]*)@\w+(?:\.\w+)*/m,
      lookbehind: true,
      alias: ["annotation", "punctuation"],
      inside: {
        "punctuation": /\./
      }
    },
    "keyword": /\b(?:_(?=\s*:)|and|as|assert|async|await|break|case|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|match|nonlocal|not|or|pass|print|raise|return|try|while|with|yield)\b/,
    "builtin": /\b(?:__import__|abs|all|any|apply|ascii|basestring|bin|bool|buffer|bytearray|bytes|callable|chr|classmethod|cmp|coerce|compile|complex|delattr|dict|dir|divmod|enumerate|eval|execfile|file|filter|float|format|frozenset|getattr|globals|hasattr|hash|help|hex|id|input|int|intern|isinstance|issubclass|iter|len|list|locals|long|map|max|memoryview|min|next|object|oct|open|ord|pow|property|range|raw_input|reduce|reload|repr|reversed|round|set|setattr|slice|sorted|staticmethod|str|sum|super|tuple|type|unichr|unicode|vars|xrange|zip)\b/,
    "boolean": /\b(?:False|None|True)\b/,
    "number": /\b0(?:b(?:_?[01])+|o(?:_?[0-7])+|x(?:_?[a-f0-9])+)\b|(?:\b\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\B\.\d+(?:_\d+)*)(?:e[+-]?\d+(?:_\d+)*)?j?(?!\w)/i,
    "operator": /[-+%=]=?|!=|:=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]/,
    "punctuation": /[{}[\];(),.:]/
  };
  Prism.languages.python["string-interpolation"].inside["interpolation"].inside.rest = Prism.languages.python;
  Prism.languages.py = Prism.languages.python;
  return prismPython;
}
requirePrismPython();
const kToolTodoContentType = "agent/todo-list";
const resolveToolInput = (fn3, toolArgs) => {
  const toolName = fn3;
  const inputDescriptor = extractInputMetadata(toolName);
  const { input: input2, description: description2, args: args2 } = extractInput(
    toolArgs,
    inputDescriptor
  );
  const functionCall = args2.length > 0 ? `${toolName}(${args2.join(", ")})` : toolName;
  return {
    name: fn3,
    functionCall,
    input: input2,
    description: description2,
    contentType: inputDescriptor?.contentType
  };
};
const extractInputMetadata = (toolName) => {
  if (toolName === "bash") {
    return {
      inputArg: "cmd",
      contentType: "bash"
    };
  } else if (toolName === "python") {
    return {
      inputArg: "code",
      contentType: "python"
    };
  } else if (toolName === "web_search") {
    return {
      inputArg: "query",
      contentType: "json"
    };
  } else if (toolName === "Bash") {
    return {
      inputArg: "command",
      descriptionArg: "description",
      contentType: "bash"
    };
  } else if (toolName === "shell") {
    return {
      inputArg: "command",
      contentType: "bash",
      inputToStr: (input2) => {
        if (Array.isArray(input2)) {
          return input2.join(" ");
        }
        return void 0;
      }
    };
  } else if (toolName == "TodoWrite") {
    return {
      inputArg: "todos",
      contentType: kToolTodoContentType
    };
  } else if (toolName == "update_plan") {
    return {
      inputArg: "plan",
      contentType: kToolTodoContentType
    };
  } else {
    return void 0;
  }
};
const extractInput = (args2, inputDescriptor) => {
  const formatArg = (key2, value2) => {
    const quotedValue = value2 === null ? "None" : typeof value2 === "string" ? `"${value2}"` : typeof value2 === "object" || Array.isArray(value2) ? JSON.stringify(value2, void 0, 2) : String(value2);
    return `${key2}: ${quotedValue}`;
  };
  if (!args2) {
    return {
      args: []
    };
  }
  if (inputDescriptor) {
    const filterKeys = /* @__PURE__ */ new Set();
    const base2 = {};
    if (inputDescriptor.inputArg && args2[inputDescriptor.inputArg]) {
      filterKeys.add(inputDescriptor.inputArg);
      base2.input = inputDescriptor.inputToStr ? inputDescriptor.inputToStr(args2[inputDescriptor.inputArg]) || args2[inputDescriptor.inputArg] : args2[inputDescriptor.inputArg];
    }
    if (inputDescriptor.descriptionArg && args2[inputDescriptor.descriptionArg]) {
      filterKeys.add(inputDescriptor.descriptionArg);
      base2.description = String(args2[inputDescriptor.descriptionArg]);
    }
    const filteredArgs = Object.keys(args2).filter((key2) => {
      return !filterKeys.has(key2);
    }).map((key2) => {
      return formatArg(key2, args2[key2]);
    });
    return {
      ...base2,
      args: filteredArgs
    };
  } else {
    const formattedArgs = Object.keys(args2).map((key2) => {
      return formatArg(key2, args2[key2]);
    });
    return {
      args: formattedArgs
    };
  }
};
const sourcePanel = "_sourcePanel_bat6y_1";
const simple = "_simple_bat6y_6";
const code$2 = "_code_bat6y_11";
const styles$$ = {
  sourcePanel,
  simple,
  code: code$2
};
const SourceCodePanel = ({
  id: id2,
  code: code2,
  language,
  simple: simple2 = false,
  style: style2,
  className: className2
}) => {
  const sourceCodeRef = reactExports.useRef(null);
  usePrismHighlight(sourceCodeRef, code2.length);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { ref: sourceCodeRef, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "pre",
    {
      className: clsx(
        styles$$.sourcePanel,
        simple2 ? styles$$.simple : "",
        className2
      ),
      style: style2,
      children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "code",
        {
          id: id2,
          className: clsx("source-code", styles$$.code, `language-${language}`),
          children: code2
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/SourceCodePanel.tsx",
          lineNumber: 37,
          columnNumber: 9
        },
        void 0
      )
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/SourceCodePanel.tsx",
      lineNumber: 29,
      columnNumber: 7
    },
    void 0
  ) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/SourceCodePanel.tsx",
    lineNumber: 28,
    columnNumber: 5
  }, void 0);
};
const getCustomToolView = (props) => {
  if (props.tool === "answer") {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(AnswerToolCallView, { ...props }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/customToolRendering.tsx",
      lineNumber: 9,
      columnNumber: 12
    }, void 0);
  }
  return void 0;
};
const AnswerToolCallView = (props) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    SourceCodePanel,
    {
      code: props.functionCall,
      language: "python",
      id: props.id
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/customToolRendering.tsx",
      lineNumber: 16,
      columnNumber: 5
    },
    void 0
  );
};
const toolCallView = "_toolCallView_x6cus_1";
const styles$_ = {
  toolCallView
};
const todoList = "_todoList_1t8rx_1";
const inProgress = "_inProgress_1t8rx_9";
const styles$Z = {
  todoList,
  inProgress
};
const toToolTodos = (obj) => {
  if (Array.isArray(obj) && obj.every((item2) => typeof item2 === "object") && obj.every(
    (item2) => item2 !== null && ("content" in item2 || "step" in item2) && "status" in item2
  )) {
    return obj.map((o) => {
      return {
        content: o.content || o.step || "",
        status: o.status
      };
    });
  } else {
    return [];
  }
};
const TodoWriteInput = ({ contents: contents2, parentRef }) => {
  const todoItems = toToolTodos(contents2);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { ref: parentRef, className: clsx(styles$Z.todoList), children: todoItems.map((todo) => {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(jsxDevRuntimeExports.Fragment, { children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "i",
        {
          className: clsx(
            todo.status === "completed" ? ApplicationIcons.checkbox.checked : ApplicationIcons.checkbox.unchecked,
            "text-size-smallest"
          )
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/tool-input/TodoWriteInput.tsx",
          lineNumber: 45,
          columnNumber: 13
        },
        void 0
      ),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "span",
        {
          className: clsx(
            styles$Z.todoItem,
            "text-size-smallest",
            todo.status === "in_progress" ? styles$Z.inProgress : void 0
          ),
          children: todo.content
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/tool-input/TodoWriteInput.tsx",
          lineNumber: 53,
          columnNumber: 13
        },
        void 0
      )
    ] }, void 0, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/tool-input/TodoWriteInput.tsx",
      lineNumber: 44,
      columnNumber: 11
    }, void 0);
  }) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/tool-input/TodoWriteInput.tsx",
    lineNumber: 41,
    columnNumber: 5
  }, void 0);
};
const outputPre = "_outputPre_1jznn_1";
const toolView = "_toolView_1jznn_7";
const outputCode = "_outputCode_1jznn_15";
const styles$Y = {
  outputPre,
  toolView,
  outputCode
};
const ToolInput = (props) => {
  const { contentType, contents: contents2, toolCallView: toolCallView2, className: className2 } = props;
  const sourceCodeRef = reactExports.useRef(null);
  const sourceCodeLength = toolCallView2 ? toolCallView2.content.length : contents2 ? typeof contents2 === "string" ? contents2.length : JSON.stringify(contents2).length : 0;
  usePrismHighlight(sourceCodeRef, sourceCodeLength);
  if (!contents2 && !toolCallView2?.content) return null;
  if (toolCallView2) {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      RenderedText,
      {
        markdown: toolCallView2.content,
        ref: sourceCodeRef,
        className: clsx("tool-output", styles$Y.toolView, className2)
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/ToolInput.tsx",
        lineNumber: 35,
        columnNumber: 7
      },
      void 0
    );
  } else {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      RenderTool,
      {
        contents: contents2,
        contentType: contentType || "",
        parentRef: sourceCodeRef,
        className: className2
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/ToolInput.tsx",
        lineNumber: 43,
        columnNumber: 7
      },
      void 0
    );
  }
};
const RenderTool = ({
  contents: contents2,
  contentType,
  parentRef,
  className: className2
}) => {
  if (contentType === kToolTodoContentType) {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(TodoWriteInput, { contents: contents2, parentRef }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/ToolInput.tsx",
      lineNumber: 67,
      columnNumber: 12
    }, void 0);
  }
  const formattedContent = typeof contents2 === "object" ? JSON.stringify(contents2) : contents2;
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { ref: parentRef, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "pre",
    {
      className: clsx(
        "tool-output",
        styles$Y.outputPre,
        styles$Y.bottomMargin,
        className2
      ),
      children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "code",
        {
          className: clsx(
            "source-code",
            "sourceCode",
            contentType ? `language-${contentType}` : void 0,
            styles$Y.outputCode
          ),
          children: formattedContent
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/ToolInput.tsx",
          lineNumber: 83,
          columnNumber: 9
        },
        void 0
      )
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/ToolInput.tsx",
      lineNumber: 75,
      columnNumber: 7
    },
    void 0
  ) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/ToolInput.tsx",
    lineNumber: 74,
    columnNumber: 5
  }, void 0);
};
const image = "_image_1vcac_1";
const toolTitle = "_toolTitle_1vcac_6";
const description = "_description_1vcac_10";
const styles$X = {
  image,
  toolTitle,
  description
};
const ToolTitle = ({ title: title2, description: description2 }) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(reactExports.Fragment, { children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("i", { className: clsx("bi", "bi-tools", styles$X.image) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/ToolTitle.tsx",
      lineNumber: 16,
      columnNumber: 7
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("code", { className: clsx("text-size-small", styles$X.toolTitle), children: title2 }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/ToolTitle.tsx",
      lineNumber: 17,
      columnNumber: 7
    }, void 0),
    description2 ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("span", { className: clsx(styles$X.description, "text-size-smallest"), children: [
      "- ",
      description2
    ] }, void 0, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/ToolTitle.tsx",
      lineNumber: 19,
      columnNumber: 9
    }, void 0) : void 0
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/ToolTitle.tsx",
    lineNumber: 15,
    columnNumber: 5
  }, void 0);
};
const ToolCallView = ({
  id: id2,
  tool: tool2,
  functionCall,
  input: input2,
  description: description2,
  contentType,
  view,
  output: output2,
  mode,
  collapsible = true
}) => {
  function isContentImage(value2) {
    if (value2 && typeof value2 === "object") {
      if (value2.type === "image") {
        return true;
      } else if (value2.type === "tool") {
        if (Array.isArray(value2.content) && value2.content.some(isContentImage)) {
          return true;
        }
      }
    }
    return false;
  }
  const collapse = Array.isArray(output2) ? output2.every((item2) => !isContentImage(item2)) : !isContentImage(output2);
  const normalizedContent = reactExports.useMemo(() => normalizeContent$1(output2), [output2]);
  const hasContent = normalizedContent.find((c2) => {
    if (c2.type === "tool") {
      for (const t2 of c2.content) {
        if (t2.type === "text") {
          if (t2.text) {
            return true;
          }
        } else {
          return true;
        }
      }
      return false;
    } else {
      return true;
    }
  });
  const customToolView = getCustomToolView({
    id: id2,
    tool: tool2,
    functionCall,
    input: input2,
    description: description2,
    contentType,
    output: output2
  });
  if (customToolView) {
    return customToolView;
  }
  const contents2 = mode !== "compact" ? input2 : input2 || functionCall;
  const context = defaultContext();
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$_.toolCallView), children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: [
      mode !== "compact" && (!view || view.title) ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        ToolTitle,
        {
          title: view?.title || functionCall,
          description: description2
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/ToolCallView.tsx",
          lineNumber: 141,
          columnNumber: 11
        },
        void 0
      ) : "",
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        ToolInput,
        {
          contentType,
          contents: contents2,
          toolCallView: view
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/ToolCallView.tsx",
          lineNumber: 148,
          columnNumber: 9
        },
        void 0
      )
    ] }, void 0, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/ToolCallView.tsx",
      lineNumber: 139,
      columnNumber: 7
    }, void 0),
    hasContent && collapsible ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      ExpandablePanel,
      {
        id: `${id2}-tool-input`,
        collapse,
        border: true,
        lines: 15,
        className: clsx("text-size-small"),
        children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(MessageContent, { contents: normalizedContent, context }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/ToolCallView.tsx",
          lineNumber: 162,
          columnNumber: 11
        }, void 0)
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/ToolCallView.tsx",
        lineNumber: 155,
        columnNumber: 9
      },
      void 0
    ) : /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(MessageContent, { contents: normalizedContent, context }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/ToolCallView.tsx",
      lineNumber: 165,
      columnNumber: 9
    }, void 0)
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/tools/ToolCallView.tsx",
    lineNumber: 138,
    columnNumber: 5
  }, void 0);
};
const normalizeContent$1 = (output2) => {
  if (Array.isArray(output2)) {
    return output2;
  } else {
    return [
      {
        type: "tool",
        content: [
          {
            type: "text",
            text: String(output2),
            refusal: null,
            internal: null,
            citations: null
          }
        ]
      }
    ];
  }
};
const ChatMessageRow = ({
  index,
  parentName,
  showLabels,
  labels,
  highlightLabeled,
  resolvedMessage,
  toolCallStyle,
  indented: indented2,
  highlightUserMessage,
  allowLinking = true,
  className: className2
}) => {
  const views = [];
  const viewLabels = [];
  const useLabels = showLabels && Object.keys(labels || {}).length > 0;
  if (useLabels) {
    const number2 = index + 1;
    const maxlabelLen = labels ? Object.values(labels).reduce((curr, r2) => {
      return Math.max(r2.length, curr);
    }, 0) : 3;
    const chatMessageLabel = labels && resolvedMessage.message.id ? labels[resolvedMessage.message.id] || " ".repeat(maxlabelLen * 2) : String(number2) || void 0;
    viewLabels.push(chatMessageLabel);
  }
  views.push(
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      ChatMessage,
      {
        id: `${parentName}-chat-messages`,
        message: resolvedMessage.message,
        toolMessages: resolvedMessage.toolMessages,
        indented: indented2,
        toolCallStyle,
        allowLinking
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/ChatMessageRow.tsx",
        lineNumber: 67,
        columnNumber: 5
      },
      void 0
    )
  );
  if (toolCallStyle !== "omit" && resolvedMessage.message.role === "assistant" && resolvedMessage.message.tool_calls && resolvedMessage.message.tool_calls.length) {
    const toolMessages = resolvedMessage.toolMessages || [];
    let idx = 0;
    for (const tool_call of resolvedMessage.message.tool_calls) {
      const { name: name2, input: input2, description: description2, functionCall, contentType } = resolveToolInput(tool_call.function, tool_call.arguments);
      let toolMessage;
      if (tool_call.id) {
        toolMessage = toolMessages.find((msg) => {
          return msg.tool_call_id === tool_call.id;
        });
      } else {
        toolMessage = toolMessages[idx];
      }
      const toolLabel = labels?.[toolMessage?.id || ""] || void 0;
      const resolvedToolOutput = resolveToolMessage(toolMessage);
      if (useLabels) {
        viewLabels.push(toolLabel);
      }
      if (toolCallStyle === "compact") {
        views.push(
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ToolCallViewCompact, { idx, functionCall }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/ChatMessageRow.tsx",
            lineNumber: 111,
            columnNumber: 11
          }, void 0)
        );
      } else {
        views.push(
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            ToolCallView,
            {
              id: `${index}-tool-call-${idx}`,
              tool: name2,
              functionCall,
              input: input2,
              description: description2,
              contentType,
              output: resolvedToolOutput,
              collapsible: false
            },
            `tool-call-${idx}`,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/ChatMessageRow.tsx",
              lineNumber: 115,
              columnNumber: 11
            },
            void 0
          )
        );
      }
      idx++;
    }
  }
  if (useLabels) {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(jsxDevRuntimeExports.Fragment, { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$10.grid, className2), children: views.map((view, idx) => {
      const label2 = viewLabels[idx];
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(jsxDevRuntimeExports.Fragment, { children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "div",
          {
            className: clsx(
              "text-size-smaller",
              "text-style-secondary",
              styles$10.number,
              styles$10.label
            ),
            children: label2
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/ChatMessageRow.tsx",
            lineNumber: 140,
            columnNumber: 17
          },
          void 0
        ),
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "div",
          {
            className: clsx(
              styles$10.container,
              highlightUserMessage && resolvedMessage.message.role === "user" ? styles$10.user : void 0,
              idx === 0 ? styles$10.first : void 0,
              idx === views.length - 1 ? styles$10.last : void 0,
              highlightLabeled && label2?.trim() ? styles$10.highlight : void 0
            ),
            children: view
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/ChatMessageRow.tsx",
            lineNumber: 150,
            columnNumber: 17
          },
          void 0
        )
      ] }, void 0, true, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/ChatMessageRow.tsx",
        lineNumber: 139,
        columnNumber: 15
      }, void 0);
    }) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/ChatMessageRow.tsx",
      lineNumber: 135,
      columnNumber: 9
    }, void 0) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/ChatMessageRow.tsx",
      lineNumber: 134,
      columnNumber: 7
    }, void 0);
  } else {
    return views.map((view, idx) => {
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "div",
        {
          className: clsx(
            styles$10.container,
            idx === 0 ? styles$10.first : void 0,
            idx === views.length - 1 ? styles$10.last : void 0,
            idx === views.length - 1 ? styles$10.bottomMargin : void 0,
            className2,
            styles$10.simple,
            highlightUserMessage && resolvedMessage.message.role === "user" ? styles$10.user : void 0
          ),
          children: view
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/ChatMessageRow.tsx",
          lineNumber: 175,
          columnNumber: 9
        },
        void 0
      );
    });
  }
};
const resolveToolMessage = (toolMessage) => {
  if (!toolMessage) {
    return [];
  }
  const content2 = toolMessage.error !== null && toolMessage.error ? toolMessage.error.message : toolMessage.content;
  if (typeof content2 === "string") {
    return [
      {
        type: "tool",
        content: [
          {
            type: "text",
            text: content2,
            refusal: null,
            internal: null,
            citations: null
          }
        ]
      }
    ];
  } else {
    const result2 = content2.map((con) => {
      if (typeof con === "string") {
        return {
          type: "tool",
          content: [
            {
              type: "text",
              text: con,
              refusal: null,
              internal: null,
              citations: null
            }
          ]
        };
      } else if (con.type === "text") {
        return {
          content: [con],
          type: "tool"
        };
      } else if (con.type === "image") {
        return {
          content: [con],
          type: "tool"
        };
      }
    }).filter((con) => con !== void 0);
    return result2;
  }
};
const ToolCallViewCompact = ({ idx, functionCall }) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("code", { className: clsx(styles$10.codeCompact), children: [
    "tool: ",
    functionCall
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/ChatMessageRow.tsx",
    lineNumber: 258,
    columnNumber: 7
  }, void 0) }, `tool-call-${idx}`, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/ChatMessageRow.tsx",
    lineNumber: 257,
    columnNumber: 5
  }, void 0);
};
const resolveMessages = (messages2) => {
  const resolvedMessages = [];
  let index = 0;
  for (const message2 of messages2) {
    if (message2.role === "tool") {
      if (resolvedMessages.length > 0) {
        const msg = resolvedMessages[resolvedMessages.length - 1];
        if (msg) {
          msg.toolMessages = msg.toolMessages || [];
          msg.toolMessages.push(message2);
        }
      }
    } else {
      resolvedMessages.push({ message: message2, toolMessages: [] });
    }
    if (message2.id === void 0) {
      message2.id = `msg-${index}`;
    }
    index++;
  }
  const systemMessages = [];
  const collapsedMessages = resolvedMessages.map((resolved) => {
    if (resolved.message.role === "system") {
      systemMessages.push(resolved.message);
    }
    return resolved;
  }).filter((resolved) => {
    return resolved.message.role !== "system";
  });
  const systemContent = [];
  for (const systemMessage2 of systemMessages) {
    const contents2 = Array.isArray(systemMessage2.content) ? systemMessage2.content : [systemMessage2.content];
    systemContent.push(...contents2.map(normalizeContent));
  }
  const systemMessage = {
    id: "sys-message-6815A84B062A",
    role: "system",
    content: systemContent,
    source: "input",
    metadata: null
  };
  if (systemMessage && systemMessage.content.length > 0) {
    collapsedMessages.unshift({ message: systemMessage, toolMessages: [] });
  }
  return collapsedMessages;
};
const normalizeContent = (content2) => {
  if (typeof content2 === "string") {
    return {
      type: "text",
      text: content2,
      refusal: null,
      internal: null,
      citations: null
    };
  } else {
    return content2;
  }
};
const messagesFromEvents = (runningEvents) => {
  const messages2 = /* @__PURE__ */ new Map();
  runningEvents.filter((e) => e.event === "model").forEach((e) => {
    for (const m of e.input) {
      const inputMessage = m;
      if (inputMessage.id && !messages2.has(inputMessage.id)) {
        messages2.set(inputMessage.id, inputMessage);
      }
    }
    const outputMessage = e.output.choices[0]?.message;
    if (outputMessage?.id) {
      messages2.set(outputMessage.id, outputMessage);
    }
  });
  if (messages2.size > 0) {
    return messages2.values().toArray();
  } else {
    return [];
  }
};
const ChatView = ({
  id: id2,
  messages: messages2,
  toolCallStyle = "complete",
  resolveToolCallsIntoPreviousMessage = true,
  indented: indented2,
  labels,
  showLabels = true,
  highlightLabeled = false,
  className: className2,
  allowLinking = true
}) => {
  const collapsedMessages = resolveToolCallsIntoPreviousMessage ? resolveMessages(messages2) : messages2.map((msg) => {
    return {
      message: msg,
      toolMessages: []
    };
  });
  const result2 = /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(className2), children: collapsedMessages.map((msg, index) => {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      ChatMessageRow,
      {
        index,
        parentName: id2 || "chat-view",
        showLabels,
        labels,
        highlightLabeled,
        resolvedMessage: msg,
        indented: indented2,
        toolCallStyle,
        allowLinking
      },
      `${id2}-msg-${index}`,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/ChatView.tsx",
        lineNumber: 51,
        columnNumber: 11
      },
      void 0
    );
  }) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/ChatView.tsx",
    lineNumber: 48,
    columnNumber: 5
  }, void 0);
  return result2;
};
const ChatMessageRenderer = {
  bucket: Buckets.first,
  canRender: (entry2) => {
    const val = entry2.value;
    return Array.isArray(val) && val.length > 0 && val[0]?.role !== void 0 && val[0]?.content !== void 0;
  },
  render: (id2, entry2) => {
    return {
      rendered: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(NavPills, { id: `${id2}-navpills`, children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ChatSummary, { title: "Last Turn", id: id2, messages: entry2.value }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/ChatMessageRenderer.tsx",
          lineNumber: 33,
          columnNumber: 11
        }, void 0),
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          ChatView,
          {
            title: "All",
            id: id2,
            messages: entry2.value,
            allowLinking: false
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/ChatMessageRenderer.tsx",
            lineNumber: 34,
            columnNumber: 11
          },
          void 0
        )
      ] }, void 0, true, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/ChatMessageRenderer.tsx",
        lineNumber: 32,
        columnNumber: 9
      }, void 0)
    };
  }
};
const ChatSummary = ({ id: id2, messages: messages2 }) => {
  const summaryMessages = [];
  for (const message2 of messages2.slice().reverse()) {
    summaryMessages.unshift(message2);
    if (message2.role === "user") {
      break;
    }
  }
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ChatView, { id: id2, messages: summaryMessages }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/ChatMessageRenderer.tsx",
    lineNumber: 68,
    columnNumber: 10
  }, void 0);
};
const formatTime$1 = (seconds2) => {
  if (seconds2 < 60) {
    return `${formatPrettyDecimal(seconds2, 1)} sec`;
  } else if (seconds2 < 60 * 60) {
    return `${Math.floor(seconds2 / 60)} min ${Math.floor(seconds2 % 60)} sec`;
  } else if (seconds2 < 60 * 60 * 24) {
    const hours2 = Math.floor(seconds2 / (60 * 60));
    const minutes2 = Math.floor(seconds2 % (60 * 60) / 60);
    const remainingSeconds = seconds2 % 60;
    return `${hours2} hr ${minutes2} min ${Math.floor(remainingSeconds)} sec`;
  } else {
    const days = Math.floor(seconds2 / (60 * 60 * 24));
    const hours2 = Math.floor(seconds2 % (60 * 60 * 24) / (60 * 60));
    const minutes2 = Math.floor(seconds2 % (60 * 60) / 60);
    const remainingSeconds = seconds2 % 60;
    return `${days} days ${hours2} hr ${minutes2} min ${Math.floor(remainingSeconds)} sec`;
  }
};
function formatPrettyDecimal(num, maxDecimals = 3) {
  const numDecimalPlaces = num.toString().includes(".") ? num.toString().split(".")[1]?.length || 0 : 0;
  if (numDecimalPlaces === 0) {
    return num.toFixed(1);
  } else if (numDecimalPlaces > maxDecimals) {
    return num.toFixed(maxDecimals);
  } else {
    return num.toString();
  }
}
function formatNumber(num) {
  return num.toLocaleString(navigator.language, {
    minimumFractionDigits: 0,
    maximumFractionDigits: 5
  });
}
function formatDateTime(date2) {
  const options = {
    year: "2-digit",
    month: "2-digit",
    day: "2-digit",
    hour: "numeric",
    minute: "2-digit",
    second: "2-digit",
    hour12: true
  };
  return new Intl.DateTimeFormat(void 0, options).format(date2);
}
function centerTruncate(str, maxLength = 50) {
  if (str.length <= maxLength) {
    return str;
  }
  const ellipsis2 = " … ";
  const availableLength = maxLength - ellipsis2.length;
  if (availableLength <= 0) {
    return ellipsis2;
  }
  const startLength = Math.ceil(availableLength / 2);
  const endLength = Math.floor(availableLength / 2);
  const start2 = str.slice(0, startLength);
  const end2 = str.slice(-endLength);
  return start2 + ellipsis2 + end2;
}
function formatPercent(value2) {
  return `${formatPrettyDecimal(value2 * 100, 2)}%`;
}
const grid$2 = "_grid_14885_1";
const cell = "_cell_14885_8";
const styles$W = {
  grid: grid$2,
  cell
};
const MetaDataGrid = ({
  id: id2,
  entries: entries2,
  className: className2,
  references,
  size,
  style: style2,
  plain
}) => {
  const baseId = "metadata-grid";
  const fontStyle = size === "mini" ? "text-size-smallest" : "text-size-smaller";
  const entryEls = entryRecords(entries2).map((entry2, index) => {
    const id22 = `${baseId}-value-${index}`;
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(reactExports.Fragment, { children: [
      index !== 0 ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "div",
        {
          style: {
            gridColumn: "1 / -1",
            borderBottom: `${!plain ? "solid 1px var(--bs-light-border-subtle" : ""}`
          }
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/MetaDataGrid.tsx",
          lineNumber: 40,
          columnNumber: 11
        },
        void 0
      ) : void 0,
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "div",
        {
          className: clsx(
            `${baseId}-key`,
            styles$W.cell,
            "text-style-label",
            "text-style-secondary",
            fontStyle
          ),
          children: entry2?.name
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/MetaDataGrid.tsx",
          lineNumber: 47,
          columnNumber: 9
        },
        void 0
      ),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$W.value, `${baseId}-value`, fontStyle), children: entry2 && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        RenderedContent,
        {
          id: id22,
          entry: entry2,
          references,
          renderObject: (obj) => {
            return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
              MetaDataGrid,
              {
                id: id22,
                className: clsx(styles$W.nested),
                entries: obj,
                size,
                plain,
                references
              },
              void 0,
              false,
              {
                fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/MetaDataGrid.tsx",
                lineNumber: 66,
                columnNumber: 19
              },
              void 0
            );
          }
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/MetaDataGrid.tsx",
          lineNumber: 60,
          columnNumber: 13
        },
        void 0
      ) }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/MetaDataGrid.tsx",
        lineNumber: 58,
        columnNumber: 9
      }, void 0)
    ] }, `${baseId}-record-${index}`, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/MetaDataGrid.tsx",
      lineNumber: 38,
      columnNumber: 7
    }, void 0);
  });
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { id: id2, className: clsx(className2, styles$W.grid), style: style2, children: entryEls }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/MetaDataGrid.tsx",
    lineNumber: 84,
    columnNumber: 5
  }, void 0);
};
const entryRecords = (entries2) => {
  if (!entries2) {
    return [];
  }
  if (!Array.isArray(entries2)) {
    return Object.entries(entries2 || {}).map(([key2, value2]) => {
      return { name: key2, value: value2 };
    });
  } else {
    return entries2;
  }
};
const query = "_query_seqs2_1";
const summary$3 = "_summary_seqs2_6";
const preWrap = "_preWrap_seqs2_10";
const preCompact = "_preCompact_seqs2_15";
const styles$V = {
  query,
  summary: summary$3,
  preWrap,
  preCompact
};
const RenderedContent = ({
  id: id2,
  entry: entry2,
  references,
  renderOptions = { renderString: "markdown" },
  renderObject
}) => {
  if (entry2.value === null) {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("span", { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("pre", { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("code", { children: "[null]" }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RenderedContent.tsx",
      lineNumber: 43,
      columnNumber: 11
    }, void 0) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RenderedContent.tsx",
      lineNumber: 42,
      columnNumber: 9
    }, void 0) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RenderedContent.tsx",
      lineNumber: 41,
      columnNumber: 7
    }, void 0);
  }
  const renderers = contentRenderers(renderObject);
  const renderer = Object.keys(renderers).map((key2) => {
    return renderers[key2];
  }).sort((a2, b) => {
    if (!a2 || !b) {
      return 0;
    }
    return a2.bucket - b.bucket;
  }).find((renderer2) => {
    return renderer2?.canRender(entry2);
  });
  if (renderer) {
    const { rendered } = renderer.render(id2, entry2, renderOptions, references);
    if (rendered !== void 0 && reactExports.isValidElement(rendered)) {
      return rendered;
    }
  }
  const displayValue = (() => {
    try {
      if (typeof entry2.value === "object") {
        return JSON.stringify(entry2.value);
      }
      return String(entry2.value).trim();
    } catch (e) {
      return "[Unable to display value]";
    }
  })();
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("span", { children: displayValue }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RenderedContent.tsx",
    lineNumber: 82,
    columnNumber: 10
  }, void 0);
};
const contentRenderers = (renderObject) => {
  const contentRenderers2 = {
    AnsiString: {
      bucket: Buckets.first,
      canRender: (entry2) => {
        return typeof entry2.value === "string" && entry2.value.indexOf("\x1B") > -1;
      },
      render: (_id, entry2, _options) => {
        return {
          rendered: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ANSIDisplay, { output: entry2.value }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RenderedContent.tsx",
            lineNumber: 102,
            columnNumber: 21
          }, void 0)
        };
      }
    },
    JsonString: {
      bucket: Buckets.first,
      canRender: (entry2) => {
        if (typeof entry2.value === "string") {
          const trimmed = entry2.value.trim();
          return isJson(trimmed);
        }
        return false;
      },
      render: (_id, entry2, _options) => {
        const obj = lib$1.parse(entry2.value);
        return {
          rendered: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(JSONPanel, { data: obj }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RenderedContent.tsx",
            lineNumber: 118,
            columnNumber: 21
          }, void 0)
        };
      }
    },
    Model: {
      bucket: Buckets.intermediate,
      canRender: (entry2) => {
        return typeof entry2.value === "object" && entry2.value._model;
      },
      render: (_id, entry2, _options) => {
        return {
          rendered: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(reactExports.Fragment, { children: [
            /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("i", { className: ApplicationIcons.model }, void 0, false, {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RenderedContent.tsx",
              lineNumber: 132,
              columnNumber: 15
            }, void 0),
            " ",
            entry2.value._model
          ] }, void 0, true, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RenderedContent.tsx",
            lineNumber: 131,
            columnNumber: 13
          }, void 0)
        };
      }
    },
    Boolean: {
      bucket: Buckets.intermediate,
      canRender: (entry2) => {
        return typeof entry2.value === "boolean";
      },
      render: (id2, entry2, options) => {
        entry2.value = entry2.value.toString();
        return contentRenderers2.String?.render(id2, entry2, options) || {
          rendered: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("span", { children: entry2.value }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RenderedContent.tsx",
            lineNumber: 147,
            columnNumber: 23
          }, void 0)
        };
      }
    },
    Number: {
      bucket: Buckets.intermediate,
      canRender: (entry2) => {
        return typeof entry2.value === "number";
      },
      render: (id2, entry2, options) => {
        entry2.value = formatNumber(entry2.value);
        return contentRenderers2.String?.render(id2, entry2, options) || {
          rendered: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("span", { children: entry2.value }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RenderedContent.tsx",
            lineNumber: 161,
            columnNumber: 23
          }, void 0)
        };
      }
    },
    String: {
      bucket: Buckets.final,
      canRender: (entry2) => {
        return typeof entry2.value === "string";
      },
      render: (_id, entry2, options, references) => {
        const rendered = entry2.value.trim();
        if (options.renderString === "markdown") {
          return {
            rendered: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(RenderedText, { markdown: rendered, references }, void 0, false, {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RenderedContent.tsx",
              lineNumber: 176,
              columnNumber: 15
            }, void 0)
          };
        } else {
          return {
            rendered: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("pre", { className: clsx(styles$V.preWrap, styles$V.preCompact), children: rendered }, void 0, false, {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RenderedContent.tsx",
              lineNumber: 182,
              columnNumber: 15
            }, void 0)
          };
        }
      }
    },
    Array: {
      bucket: Buckets.intermediate,
      canRender: (entry2) => {
        const isArray2 = Array.isArray(entry2.value);
        if (isArray2) {
          if (entry2.value.length === 0 || entry2.value.length === 1) {
            return true;
          }
          const types2 = new Set(
            entry2.value.filter((e) => e !== null).map((e) => {
              return typeof e;
            })
          );
          return types2.size === 1;
        } else {
          return false;
        }
      },
      render: (id2, entry2, _options) => {
        const arrayMap = {};
        entry2.value.forEach((e, index) => {
          arrayMap[`[${index}]`] = e;
        });
        const arrayRendered = renderObject ? renderObject(arrayMap) : /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          MetaDataGrid,
          {
            id: id2,
            className: "font-size-small",
            entries: arrayMap,
            plain: true
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RenderedContent.tsx",
            lineNumber: 219,
            columnNumber: 11
          },
          void 0
        );
        return { rendered: arrayRendered };
      }
    },
    ChatMessage: ChatMessageRenderer,
    web_search: {
      bucket: Buckets.intermediate,
      canRender: (entry2) => {
        return typeof entry2.value === "object" && entry2.name === "web_search";
      },
      render: (_id, entry2, _options) => {
        const results = [];
        results.push(
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: styles$V.query, children: [
            /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("i", { className: ApplicationIcons.search }, void 0, false, {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RenderedContent.tsx",
              lineNumber: 239,
              columnNumber: 13
            }, void 0),
            " ",
            entry2.value.query
          ] }, void 0, true, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RenderedContent.tsx",
            lineNumber: 238,
            columnNumber: 11
          }, void 0)
        );
        entry2.value.results.forEach(
          (result2) => {
            results.push(
              /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("a", { href: result2.url, children: result2.url }, void 0, false, {
                fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RenderedContent.tsx",
                lineNumber: 246,
                columnNumber: 17
              }, void 0) }, void 0, false, {
                fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RenderedContent.tsx",
                lineNumber: 245,
                columnNumber: 15
              }, void 0)
            );
            results.push(
              /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("text-size-smaller", styles$V.summary), children: result2.summary }, void 0, false, {
                fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RenderedContent.tsx",
                lineNumber: 250,
                columnNumber: 15
              }, void 0)
            );
          }
        );
        return {
          rendered: results
        };
      }
    },
    web_browser: {
      bucket: Buckets.intermediate,
      canRender: (entry2) => {
        return typeof entry2.value === "string" && entry2.name?.startsWith("web_browser");
      },
      render: (_id, entry2, _options) => {
        return {
          rendered: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("pre", { className: styles$V.preWrap, children: entry2.value }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RenderedContent.tsx",
            lineNumber: 271,
            columnNumber: 21
          }, void 0)
        };
      }
    },
    Html: {
      bucket: Buckets.intermediate,
      canRender: (entry2) => {
        return typeof entry2.value === "object" && entry2.value._html;
      },
      render: (_id, entry2, _options) => {
        return {
          rendered: entry2.value._html
        };
      }
    },
    MessageContent: {
      bucket: Buckets.first,
      canRender: (entry2) => {
        return Array.isArray(entry2.value) && entry2.value.every((item2) => {
          return isMessageContent(item2);
        });
      },
      render: (_id, entry2, _options) => {
        return {
          rendered: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(MessageContent, { contents: entry2.value, context: defaultContext() }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RenderedContent.tsx",
            lineNumber: 300,
            columnNumber: 13
          }, void 0)
        };
      }
    },
    Image: {
      bucket: Buckets.intermediate,
      canRender: (entry2) => {
        return typeof entry2.value === "string" && entry2.value.startsWith("data:image/");
      },
      render: (_id, entry2, _options) => {
        return {
          rendered: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("img", { src: entry2.value }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RenderedContent.tsx",
            lineNumber: 315,
            columnNumber: 21
          }, void 0)
        };
      }
    },
    Object: {
      bucket: Buckets.intermediate,
      canRender: (entry2) => {
        return typeof entry2.value === "object";
      },
      render: (id2, entry2, _options) => {
        if (renderObject) {
          return { rendered: renderObject(entry2.value) };
        } else {
          return {
            rendered: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
              MetaDataGrid,
              {
                id: id2,
                className: "font-size-small",
                entries: entry2.value,
                plain: true
              },
              void 0,
              false,
              {
                fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RenderedContent.tsx",
                lineNumber: 330,
                columnNumber: 15
              },
              void 0
            )
          };
        }
      }
    }
  };
  return contentRenderers2;
};
const kRecordTreeKey = "record-tree-key";
const RecordTree = ({
  id: id2,
  record,
  className: className2,
  scrollRef,
  defaultExpandLevel = 1,
  processStore = false,
  useBorders = true
}) => {
  const listHandle = reactExports.useRef(null);
  const { getRestoreState } = useVirtuosoState(
    listHandle,
    `metadata-grid-${id2}`
  );
  const [collapsedIds, setCollapsed, clearIds] = useCollapsibleIds(id2);
  const setCollapsedIds = reactExports.useCallback(
    (values2) => {
      Object.entries(values2).forEach(([key2, value2]) => {
        setCollapsed(key2, value2);
      });
    },
    [setCollapsed]
  );
  reactExports.useEffect(() => {
    return () => {
      clearIds();
    };
  }, [clearIds, id2]);
  const items = reactExports.useMemo(() => {
    const items2 = toTreeItems(
      record,
      collapsedIds || {},
      processStore ? [resolveStoreKeys] : []
    );
    return items2;
  }, [record, collapsedIds, processStore]);
  reactExports.useEffect(() => {
    if (collapsedIds) {
      return;
    }
    const defaultCollapsedIds = items.reduce(
      (prev, item2) => {
        if (item2.depth >= defaultExpandLevel && item2.hasChildren) {
          prev[item2.id] = true;
        }
        return prev;
      },
      {}
    );
    setCollapsedIds(defaultCollapsedIds);
  }, [collapsedIds, items]);
  const keyUpHandler = reactExports.useCallback(
    (itemId, index) => {
      return (event) => {
        switch (event.key) {
          case "Enter":
            event.preventDefault();
            event.stopPropagation();
            setCollapsed(itemId, !collapsedIds?.[id2]);
            break;
          case "ArrowDown": {
            event.preventDefault();
            event.stopPropagation();
            if (index === items.length - 1) {
              return;
            }
            const treeRoot = document.getElementById(id2);
            const nextEl = treeRoot?.querySelector(
              `.${kRecordTreeKey}[data-index="${index + 1}"]`
            );
            if (nextEl) {
              nextEl.focus();
            }
            break;
          }
          case "ArrowUp": {
            event.preventDefault();
            event.stopPropagation();
            if (index === 0) {
              return;
            }
            const treeRoot = document.getElementById(id2);
            const prevEl = treeRoot?.querySelector(
              `.${kRecordTreeKey}[data-index="${index - 1}"]`
            );
            if (prevEl) {
              prevEl.focus();
            }
            break;
          }
          case "ArrowRight":
            event.preventDefault();
            event.stopPropagation();
            setCollapsed(itemId, false);
            break;
          case "ArrowLeft":
            event.preventDefault();
            event.stopPropagation();
            setCollapsed(itemId, true);
            break;
        }
      };
    },
    [collapsedIds, items]
  );
  const renderRow = (index) => {
    const item2 = items[index];
    if (!item2) {
      return null;
    }
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "div",
      {
        className: clsx(
          styles$1g.keyPairContainer,
          index < items.length - 1 && useBorders ? styles$1g.keyPairBordered : void 0,
          "text-size-small"
        ),
        style: {
          paddingLeft: `${item2.depth * 20}px`
        },
        children: [
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            "div",
            {
              "data-index": index,
              className: clsx(
                kRecordTreeKey,
                styles$1g.key,
                "font-monospace",
                "text-style-secondary"
              ),
              onKeyUp: keyUpHandler(item2.id, index),
              tabIndex: 0,
              onClick: () => {
                setCollapsed(item2.id, !collapsedIds?.[item2.id]);
              },
              children: [
                /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: item2.hasChildren ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("pre", { className: clsx(styles$1g.pre), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
                  "i",
                  {
                    className: clsx(
                      collapsedIds && collapsedIds[item2.id] ? ApplicationIcons.tree.closed : ApplicationIcons.tree.open,
                      styles$1g.treeIcon
                    )
                  },
                  void 0,
                  false,
                  {
                    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RecordTree.tsx",
                    lineNumber: 196,
                    columnNumber: 17
                  },
                  void 0
                ) }, void 0, false, {
                  fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RecordTree.tsx",
                  lineNumber: 195,
                  columnNumber: 15
                }, void 0) : void 0 }, void 0, false, {
                  fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RecordTree.tsx",
                  lineNumber: 193,
                  columnNumber: 11
                }, void 0),
                /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("pre", { className: clsx(styles$1g.pre), children: [
                  item2.key,
                  ":"
                ] }, void 0, true, {
                  fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RecordTree.tsx",
                  lineNumber: 207,
                  columnNumber: 11
                }, void 0)
              ]
            },
            void 0,
            true,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RecordTree.tsx",
              lineNumber: 179,
              columnNumber: 9
            },
            void 0
          ),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: item2.value !== null && (!item2.hasChildren || collapsedIds?.[item2.id]) ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            ExpandablePanel,
            {
              id: `${id2}-collapse-${item2.id}`,
              collapse: true,
              lines: 15,
              togglePosition: "block-left",
              children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
                RenderedContent,
                {
                  id: `${id2}-value-${item2.id}`,
                  entry: {
                    name: item2.key,
                    value: item2.value
                  },
                  renderOptions: { renderString: "pre" }
                },
                void 0,
                false,
                {
                  fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RecordTree.tsx",
                  lineNumber: 218,
                  columnNumber: 15
                },
                void 0
              )
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RecordTree.tsx",
              lineNumber: 212,
              columnNumber: 13
            },
            void 0
          ) : void 0 }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RecordTree.tsx",
            lineNumber: 209,
            columnNumber: 9
          }, void 0)
        ]
      },
      item2.id,
      true,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RecordTree.tsx",
        lineNumber: 166,
        columnNumber: 7
      },
      void 0
    );
  };
  if (!collapsedIds) {
    return null;
  }
  if (!scrollRef) {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "div",
      {
        id: id2,
        className: clsx(className2, "samples-list"),
        style: { width: "100%" },
        tabIndex: 0,
        children: items.map((_, index) => renderRow(index))
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RecordTree.tsx",
        lineNumber: 241,
        columnNumber: 7
      },
      void 0
    );
  }
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    qr,
    {
      ref: listHandle,
      customScrollParent: scrollRef?.current ? scrollRef.current : void 0,
      id: id2,
      style: { width: "100%", height: "100%" },
      data: items,
      defaultItemHeight: 50,
      itemContent: renderRow,
      atBottomThreshold: 30,
      increaseViewportBy: { top: 300, bottom: 300 },
      overscan: {
        main: 10,
        reverse: 10
      },
      className: clsx(className2, "samples-list"),
      skipAnimationFrameInResizeObserver: true,
      restoreStateFrom: getRestoreState(),
      tabIndex: 0
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/content/RecordTree.tsx",
      lineNumber: 252,
      columnNumber: 5
    },
    void 0
  );
};
const toTreeItems = (record, collapsedIds, recordProcessors = [], currentDepth = 0, currentPath = []) => {
  if (!record) {
    return [];
  }
  if (recordProcessors.length > 0) {
    for (const processor of recordProcessors) {
      record = processor(record);
    }
  }
  const result2 = [];
  Object.entries(record).forEach(([key2, value2], index) => {
    const itemSegment = index.toString();
    result2.push(
      ...processNodeRecursive(
        key2,
        value2,
        currentDepth,
        currentPath,
        itemSegment,
        collapsedIds
      )
    );
  });
  return result2;
};
const processNodeRecursive = (key2, value2, depth, parentPath, thisPath, collapsedIds) => {
  const items = [];
  const currentItemPath = [...parentPath, thisPath];
  const id2 = `${depth}.${currentItemPath.join(".")}`;
  if (isPrimitiveOrNull(value2)) {
    items.push({
      id: id2,
      key: key2,
      value: value2 === void 0 ? null : value2,
      depth,
      hasChildren: false
    });
    return items;
  }
  let displayValue = null;
  let processChildren = false;
  if (Array.isArray(value2)) {
    processChildren = true;
    displayValue = `Array(${value2.length})`;
  } else if (typeof value2 === "object" && value2 !== null) {
    processChildren = true;
    displayValue = `Object(${Object.keys(value2).length})`;
  } else {
    displayValue = String(value2);
    processChildren = false;
  }
  items.push({ id: id2, key: key2, value: displayValue, depth, hasChildren: true });
  if (processChildren && !collapsedIds[id2]) {
    const childDepth = depth + 1;
    if (Array.isArray(value2)) {
      if (value2.length > 0) {
        value2.forEach((element, index) => {
          const elementKey = `[${index}]`;
          const elementIdentifier = `[${index}]`;
          items.push(
            ...processNodeRecursive(
              elementKey,
              element,
              childDepth,
              currentItemPath,
              elementIdentifier,
              collapsedIds
            )
          );
        });
      }
    } else if (typeof value2 === "object" && value2 !== null) {
      Object.entries(value2).forEach(
        ([childKey, childValue], index) => {
          const childIdentifier = index.toString();
          items.push(
            ...processNodeRecursive(
              childKey,
              childValue,
              childDepth,
              currentItemPath,
              childIdentifier,
              collapsedIds
            )
          );
        }
      );
    }
  }
  return items;
};
const isPrimitiveOrNull = (value2) => {
  return value2 === null || value2 === void 0 || typeof value2 === "string" || typeof value2 === "number" || typeof value2 === "boolean";
};
const wrapper$1 = "_wrapper_sq96g_1";
const col2$1 = "_col2_sq96g_8";
const col1_3$1 = "_col1_3_sq96g_12";
const col3$1 = "_col3_sq96g_16";
const separator$3 = "_separator_sq96g_20";
const padded = "_padded_sq96g_26";
const styles$U = {
  wrapper: wrapper$1,
  col2: col2$1,
  col1_3: col1_3$1,
  col3: col3$1,
  separator: separator$3,
  padded
};
const ModelUsagePanel = ({ usage, className: className2 }) => {
  if (!usage) {
    return null;
  }
  const rows = [];
  if (usage.reasoning_tokens) {
    rows.push({
      label: "Reasoning",
      value: usage.reasoning_tokens,
      secondary: false,
      bordered: true
    });
    rows.push({
      label: "---",
      value: void 0,
      secondary: false,
      padded: true
    });
  }
  rows.push({
    label: "input",
    value: usage.input_tokens,
    secondary: false
  });
  if (usage.input_tokens_cache_read) {
    rows.push({
      label: "cache_read",
      value: usage.input_tokens_cache_read,
      secondary: true
    });
  }
  if (usage.input_tokens_cache_write) {
    rows.push({
      label: "cache_write",
      value: usage.input_tokens_cache_write,
      secondary: true
    });
  }
  rows.push({
    label: "Output",
    value: usage.output_tokens,
    secondary: false,
    bordered: true
  });
  rows.push({
    label: "---",
    value: void 0,
    secondary: false
  });
  rows.push({
    label: "Total",
    value: usage.total_tokens,
    secondary: false
  });
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("text-size-small", styles$U.wrapper, className2), children: rows.map((row2, idx) => {
    if (row2.label === "---") {
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "div",
        {
          className: clsx(
            styles$U.separator,
            row2.padded ? styles$U.padded : void 0
          )
        },
        `$usage-sep-${idx}`,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/usage/ModelUsagePanel.tsx",
          lineNumber: 94,
          columnNumber: 13
        },
        void 0
      );
    } else {
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(reactExports.Fragment, { children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "div",
          {
            className: clsx(
              "text-style-label",
              "text-style-secondary",
              row2.secondary ? styles$U.col2 : styles$U.col1_3
            ),
            children: row2.label
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/usage/ModelUsagePanel.tsx",
            lineNumber: 105,
            columnNumber: 15
          },
          void 0
        ),
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: styles$U.col3, children: row2.value ? formatNumber(row2.value) : "" }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/usage/ModelUsagePanel.tsx",
          lineNumber: 114,
          columnNumber: 15
        }, void 0)
      ] }, `$usage-row-${idx}`, true, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/usage/ModelUsagePanel.tsx",
        lineNumber: 104,
        columnNumber: 13
      }, void 0);
    }
  }) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/usage/ModelUsagePanel.tsx",
    lineNumber: 90,
    columnNumber: 5
  }, void 0);
};
const table = "_table_z217i_1";
const tableTokens = "_tableTokens_z217i_5";
const tableH = "_tableH_z217i_9";
const model = "_model_z217i_14";
const cellContents = "_cellContents_z217i_18";
const styles$T = {
  table,
  tableTokens,
  tableH,
  model,
  cellContents
};
const TokenTable = ({ className: className2, children: children2 }) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "table",
    {
      className: clsx(
        "table",
        "table-sm",
        "text-size-smaller",
        styles$T.table,
        className2
      ),
      children: children2
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/usage/TokenTable.tsx",
      lineNumber: 16,
      columnNumber: 5
    },
    void 0
  );
};
const TokenHeader = () => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("thead", { children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("tr", { children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("td", {}, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/usage/TokenTable.tsx",
        lineNumber: 34,
        columnNumber: 9
      }, void 0),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "td",
        {
          colSpan: 3,
          className: clsx(
            "card-subheading",
            styles$T.tableTokens,
            "text-size-small",
            "text-style-label",
            "text-style-secondary"
          ),
          align: "center",
          children: "Tokens"
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/usage/TokenTable.tsx",
          lineNumber: 35,
          columnNumber: 9
        },
        void 0
      )
    ] }, void 0, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/usage/TokenTable.tsx",
      lineNumber: 33,
      columnNumber: 7
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("tr", { children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "th",
        {
          className: clsx(
            styles$T.tableH,
            "text-sixe-small",
            "text-style-label",
            "text-style-secondary"
          ),
          children: "Model"
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/usage/TokenTable.tsx",
          lineNumber: 50,
          columnNumber: 9
        },
        void 0
      ),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "th",
        {
          className: clsx(
            styles$T.tableH,
            "text-sixe-small",
            "text-style-label",
            "text-style-secondary"
          ),
          children: "Usage"
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/usage/TokenTable.tsx",
          lineNumber: 60,
          columnNumber: 9
        },
        void 0
      )
    ] }, void 0, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/usage/TokenTable.tsx",
      lineNumber: 49,
      columnNumber: 7
    }, void 0)
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/usage/TokenTable.tsx",
    lineNumber: 32,
    columnNumber: 5
  }, void 0);
};
const TokenRow = ({ model: model2, usage }) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("tr", { children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("td", { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$T.model, styles$T.cellContents), children: model2 }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/usage/TokenTable.tsx",
      lineNumber: 84,
      columnNumber: 9
    }, void 0) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/usage/TokenTable.tsx",
      lineNumber: 83,
      columnNumber: 7
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("td", { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ModelUsagePanel, { usage, className: clsx(styles$T.cellContents) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/usage/TokenTable.tsx",
      lineNumber: 87,
      columnNumber: 9
    }, void 0) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/usage/TokenTable.tsx",
      lineNumber: 86,
      columnNumber: 7
    }, void 0)
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/usage/TokenTable.tsx",
    lineNumber: 82,
    columnNumber: 5
  }, void 0);
};
const ModelTokenTable = ({
  model_usage,
  className: className2
}) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(TokenTable, { className: className2, children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(TokenHeader, {}, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/usage/ModelTokenTable.tsx",
      lineNumber: 18,
      columnNumber: 7
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("tbody", { children: Object.keys(model_usage).map((key2) => {
      if (!model_usage[key2]) {
        return null;
      }
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(TokenRow, { model: key2, usage: model_usage[key2] }, key2, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/usage/ModelTokenTable.tsx",
        lineNumber: 24,
        columnNumber: 18
      }, void 0);
    }) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/usage/ModelTokenTable.tsx",
      lineNumber: 19,
      columnNumber: 7
    }, void 0)
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/usage/ModelTokenTable.tsx",
    lineNumber: 17,
    columnNumber: 5
  }, void 0);
};
const scanInfo = "_scanInfo_76qrl_1";
const container$e = "_container_76qrl_7";
const styles$S = {
  scanInfo,
  container: container$e
};
const InfoPanel = ({ result: result2 }) => {
  return result2 && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$S.container), children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Card, { children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(CardHeader, { label: "Scanner Info", type: "modern" }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/info/InfoPanel.tsx",
        lineNumber: 23,
        columnNumber: 11
      }, void 0),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(CardBody, { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ScannerInfoPanel, { result: result2 }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/info/InfoPanel.tsx",
        lineNumber: 25,
        columnNumber: 13
      }, void 0) }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/info/InfoPanel.tsx",
        lineNumber: 24,
        columnNumber: 11
      }, void 0)
    ] }, void 0, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/info/InfoPanel.tsx",
      lineNumber: 22,
      columnNumber: 9
    }, void 0),
    result2?.scanModelUsage && Object.keys(result2?.scanModelUsage).length > 0 && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Card, { children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(CardHeader, { label: "Model Usage", type: "modern" }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/info/InfoPanel.tsx",
        lineNumber: 31,
        columnNumber: 15
      }, void 0),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(CardBody, { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        ModelTokenTable,
        {
          model_usage: result2?.scanModelUsage
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/info/InfoPanel.tsx",
          lineNumber: 33,
          columnNumber: 17
        },
        void 0
      ) }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/info/InfoPanel.tsx",
        lineNumber: 32,
        columnNumber: 15
      }, void 0)
    ] }, void 0, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/info/InfoPanel.tsx",
      lineNumber: 30,
      columnNumber: 13
    }, void 0),
    result2?.scanMetadata && Object.keys(result2.scanMetadata).length > 0 && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Card, { children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(CardHeader, { label: "Metadata", type: "modern" }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/info/InfoPanel.tsx",
        lineNumber: 46,
        columnNumber: 15
      }, void 0),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(CardBody, { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        RecordTree,
        {
          id: `scan-metadata-${result2?.uuid}`,
          record: result2?.scanMetadata || {}
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/info/InfoPanel.tsx",
          lineNumber: 48,
          columnNumber: 17
        },
        void 0
      ) }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/info/InfoPanel.tsx",
        lineNumber: 47,
        columnNumber: 15
      }, void 0)
    ] }, void 0, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/info/InfoPanel.tsx",
      lineNumber: 45,
      columnNumber: 13
    }, void 0)
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/info/InfoPanel.tsx",
    lineNumber: 21,
    columnNumber: 7
  }, void 0);
};
const ScannerInfoPanel = ({ result: result2 }) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("text-size-small"), children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$S.scanInfo), children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(LabeledValue, { label: "Name", children: result2?.scannerName }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/info/InfoPanel.tsx",
        lineNumber: 64,
        columnNumber: 9
      }, void 0),
      result2?.scannerFile && result2.scannerFile !== null && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(LabeledValue, { label: "File", children: result2?.scannerFile }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/info/InfoPanel.tsx",
        lineNumber: 66,
        columnNumber: 11
      }, void 0),
      (result2?.scanTotalTokens || 0) > 0 && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(LabeledValue, { label: "Tokens", children: result2?.scanTotalTokens ? formatNumber(result2.scanTotalTokens) : "" }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/info/InfoPanel.tsx",
        lineNumber: 69,
        columnNumber: 11
      }, void 0)
    ] }, void 0, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/info/InfoPanel.tsx",
      lineNumber: 63,
      columnNumber: 7
    }, void 0),
    result2?.scanTags && result2.scanTags.length > 0 && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(LabeledValue, { label: "Tags", children: (result2?.scanTags || []).join(", ") }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/info/InfoPanel.tsx",
      lineNumber: 77,
      columnNumber: 9
    }, void 0),
    result2?.scannerParams && Object.keys(result2.scannerParams).length > 0 && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(LabeledValue, { label: "Params", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      RecordTree,
      {
        id: `scanner-params-${result2?.uuid}`,
        record: result2?.scannerParams
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/info/InfoPanel.tsx",
        lineNumber: 84,
        columnNumber: 13
      },
      void 0
    ) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/info/InfoPanel.tsx",
      lineNumber: 83,
      columnNumber: 11
    }, void 0)
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/info/InfoPanel.tsx",
    lineNumber: 62,
    columnNumber: 5
  }, void 0);
};
const progressContainer = "_progressContainer_1cjjr_1";
const styles$R = {
  progressContainer
};
const container$d = "_container_4p85e_2";
const dotsContainer = "_dotsContainer_4p85e_8";
const small = "_small_4p85e_15";
const medium = "_medium_4p85e_19";
const large = "_large_4p85e_24";
const dot = "_dot_4p85e_8";
const subtle = "_subtle_4p85e_36";
const primary = "_primary_4p85e_40";
const visuallyHidden = "_visuallyHidden_4p85e_59";
const styles$Q = {
  container: container$d,
  dotsContainer,
  small,
  medium,
  large,
  dot,
  subtle,
  primary,
  visuallyHidden
};
const PulsingDots = ({
  text: text2 = "Loading...",
  dotsCount = 3,
  subtle: subtle2 = true,
  size = "small",
  className: className2
}) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "div",
    {
      className: clsx(
        styles$Q.container,
        size === "small" ? styles$Q.small : size === "medium" ? styles$Q.medium : styles$Q.large,
        className2
      ),
      role: "status",
      children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: styles$Q.dotsContainer, children: Array.from({ length: dotsCount }, (_, index) => /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "div",
          {
            className: clsx(
              styles$Q.dot,
              subtle2 ? styles$Q.subtle : styles$Q.primary
            ),
            style: { animationDelay: `${index * 0.2}s` }
          },
          `dot-${index}`,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/PulsingDots.tsx",
            lineNumber: 36,
            columnNumber: 11
          },
          void 0
        )) }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/PulsingDots.tsx",
          lineNumber: 34,
          columnNumber: 7
        }, void 0),
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("span", { className: styles$Q.visuallyHidden, children: text2 }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/PulsingDots.tsx",
          lineNumber: 46,
          columnNumber: 7
        }, void 0)
      ]
    },
    void 0,
    true,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/PulsingDots.tsx",
      lineNumber: 22,
      columnNumber: 5
    },
    void 0
  );
};
const LiveVirtualList = ({
  id: id2,
  listHandle,
  className: className2,
  data: data2,
  renderRow,
  scrollRef,
  live,
  showProgress,
  initialTopMostItemIndex,
  offsetTop,
  components,
  searchInItem,
  animation = true
}) => {
  const { getRestoreState, isScrolling, visibleRange, setVisibleRange } = useVirtuosoState(listHandle, `live-virtual-list-${id2}`);
  const { registerVirtualList } = useExtendedFind();
  const pendingSearchCallback = reactExports.useRef(null);
  const [isCurrentlyScrolling, setIsCurrentlyScrolling] = reactExports.useState(false);
  const [followOutput, setFollowOutput] = useProperty(
    id2,
    "follow",
    {
      defaultValue: null
    }
  );
  const isAutoScrollingRef = reactExports.useRef(false);
  reactExports.useEffect(() => {
    if (followOutput === null) {
      setFollowOutput(!!live);
    }
  }, [followOutput, live, setFollowOutput]);
  const prevLive = usePrevious(live);
  reactExports.useEffect(() => {
    if (!live && prevLive && followOutput && scrollRef?.current) {
      setFollowOutput(false);
      setTimeout(() => {
        if (scrollRef.current) {
          scrollRef.current.scrollTo({ top: 0, behavior: "instant" });
        }
      }, 100);
    }
  }, [live, followOutput, prevLive, scrollRef, setFollowOutput]);
  const handleScroll = useRafThrottle(() => {
    if (isAutoScrollingRef.current) return;
    if (!live) return;
    if (scrollRef?.current && listHandle.current) {
      const parent = scrollRef.current;
      const isAtBottom = parent.scrollHeight - parent.scrollTop <= parent.clientHeight + 30;
      if (isAtBottom && !followOutput) {
        setFollowOutput(true);
      } else if (!isAtBottom && followOutput) {
        setFollowOutput(false);
      }
    }
  });
  const heightChanged = reactExports.useCallback(
    (height) => {
      requestAnimationFrame(() => {
        if (followOutput && live && scrollRef?.current) {
          isAutoScrollingRef.current = true;
          listHandle.current?.scrollTo({ top: height });
          requestAnimationFrame(() => {
            isAutoScrollingRef.current = false;
          });
        }
      });
    },
    [followOutput, live, scrollRef, listHandle]
  );
  const [, forceRender] = reactExports.useState({});
  const forceUpdate = reactExports.useCallback(() => {
    forceRender({});
  }, []);
  reactExports.useEffect(() => {
    const timer = setTimeout(() => {
      forceUpdate();
    }, 0);
    return () => {
      clearTimeout(timer);
    };
  }, [forceUpdate]);
  const defaultSearchInItem = reactExports.useCallback(
    (item2, searchTerm) => {
      const searchLower = searchTerm.toLowerCase();
      try {
        const itemString = JSON.stringify(item2).toLowerCase();
        return itemString.includes(searchLower);
      } catch {
        return false;
      }
    },
    []
  );
  const searchInData = reactExports.useCallback(
    async (term, direction, onContentReady) => {
      if (!data2.length || !term) return false;
      const searchFn = searchInItem || defaultSearchInItem;
      const currentIndex = direction === "forward" ? visibleRange.endIndex : visibleRange.startIndex;
      const searchStart = direction === "forward" ? Math.max(0, currentIndex + 1) : Math.min(data2.length - 1, currentIndex - 1);
      const step = direction === "forward" ? 1 : -1;
      for (let i2 = searchStart; i2 >= 0 && i2 < data2.length; i2 += step) {
        const item2 = data2[i2];
        if (item2 && searchFn(item2, term)) {
          pendingSearchCallback.current = onContentReady;
          listHandle.current?.scrollToIndex({
            index: i2,
            behavior: "auto",
            align: "center"
          });
          return true;
        }
      }
      return false;
    },
    [
      data2,
      searchInItem,
      defaultSearchInItem,
      visibleRange.endIndex,
      visibleRange.startIndex,
      listHandle
    ]
  );
  reactExports.useEffect(() => {
    const unregister = registerVirtualList(id2, searchInData);
    return unregister;
  }, [id2, registerVirtualList, searchInData]);
  const Footer3 = () => {
    return showProgress ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$R.progressContainer), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(PulsingDots, { subtle: false, size: "medium" }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/LiveVirtualList.tsx",
      lineNumber: 243,
      columnNumber: 9
    }, void 0) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/LiveVirtualList.tsx",
      lineNumber: 242,
      columnNumber: 7
    }, void 0) : void 0;
  };
  reactExports.useEffect(() => {
    const parent = scrollRef?.current;
    if (parent) {
      parent.addEventListener("scroll", handleScroll);
      return () => {
        parent.removeEventListener("scroll", handleScroll);
      };
    }
  }, [scrollRef, handleScroll]);
  const hasScrolled = reactExports.useRef(false);
  reactExports.useEffect(() => {
    if (initialTopMostItemIndex !== void 0 && listHandle.current) {
      const timer = setTimeout(() => {
        listHandle.current?.scrollToIndex({
          index: initialTopMostItemIndex,
          align: "start",
          behavior: !animation ? "auto" : !hasScrolled.current ? "auto" : "smooth",
          offset: offsetTop ? -offsetTop : void 0
        });
        hasScrolled.current = true;
      }, 50);
      return () => {
        clearTimeout(timer);
      };
    }
  }, [initialTopMostItemIndex, listHandle, offsetTop]);
  reactExports.useEffect(() => {
    if (!isCurrentlyScrolling && pendingSearchCallback.current) {
      setTimeout(() => {
        const callback = pendingSearchCallback.current;
        pendingSearchCallback.current = null;
        callback?.();
      }, 100);
    }
  }, [isCurrentlyScrolling]);
  const handleScrollingChange = reactExports.useCallback(
    (scrolling) => {
      setIsCurrentlyScrolling(scrolling);
      isScrolling(scrolling);
    },
    [isScrolling]
  );
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    qr,
    {
      ref: listHandle,
      customScrollParent: scrollRef?.current ? scrollRef.current : void 0,
      style: { height: "100%", width: "100%" },
      data: data2,
      defaultItemHeight: 500,
      itemContent: renderRow,
      increaseViewportBy: { top: 1e3, bottom: 1e3 },
      overscan: { main: 5, reverse: 5 },
      className: clsx("transcript", className2),
      isScrolling: handleScrollingChange,
      rangeChanged: (range) => {
        setVisibleRange(range);
      },
      restoreStateFrom: getRestoreState(),
      totalListHeightChanged: heightChanged,
      components: {
        Footer: Footer3,
        ...components
      },
      computeItemKey: (index) => {
        return `${id2}-item-${index}`;
      }
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/LiveVirtualList.tsx",
      lineNumber: 306,
      columnNumber: 5
    },
    void 0
  );
};
const item$1 = "_item_5fj0m_6";
const styles$P = {
  item: item$1
};
const ChatViewVirtualList = reactExports.memo(
  ({
    id: id2,
    messages: messages2,
    initialMessageId,
    topOffset,
    className: className2,
    toolCallStyle,
    indented: indented2,
    scrollRef,
    running,
    allowLinking = true,
    labels,
    showLabels = true,
    highlightLabeled = false
  }) => {
    const listHandle = reactExports.useRef(null);
    reactExports.useEffect(() => {
      const handleKeyDown = (event) => {
        if (event.metaKey || event.ctrlKey) {
          if (event.key === "ArrowUp") {
            listHandle.current?.scrollToIndex({ index: 0, align: "center" });
            event.preventDefault();
          } else if (event.key === "ArrowDown") {
            listHandle.current?.scrollToIndex({
              index: Math.min(messages2.length - 5, 0),
              align: "center"
            });
            setTimeout(() => {
              listHandle.current?.scrollToIndex({
                index: messages2.length - 1,
                align: "end"
              });
            }, 250);
            event.preventDefault();
          }
        }
      };
      const scrollElement = scrollRef?.current;
      if (scrollElement) {
        scrollElement.addEventListener("keydown", handleKeyDown);
        if (!scrollElement.hasAttribute("tabIndex")) {
          scrollElement.setAttribute("tabIndex", "0");
        }
        return () => {
          scrollElement.removeEventListener("keydown", handleKeyDown);
        };
      }
    }, [scrollRef, messages2]);
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      ChatViewVirtualListComponent,
      {
        id: id2,
        listHandle,
        className: className2,
        scrollRef,
        messages: messages2,
        initialMessageId,
        topOffset,
        toolCallStyle,
        indented: indented2,
        running,
        allowLinking,
        labels,
        showLabels,
        highlightLabeled
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/ChatViewVirtualList.tsx",
        lineNumber: 103,
        columnNumber: 7
      },
      void 0
    );
  }
);
const ChatViewVirtualListComponent = reactExports.memo(
  ({
    id: id2,
    listHandle,
    messages: messages2,
    initialMessageId,
    topOffset,
    className: className2,
    toolCallStyle,
    indented: indented2,
    scrollRef,
    running,
    allowLinking = true,
    labels,
    showLabels = true,
    highlightLabeled
  }) => {
    const collapsedMessages = reactExports.useMemo(() => {
      return resolveMessages(messages2);
    }, [messages2]);
    const initialMessageIndex = reactExports.useMemo(() => {
      if (initialMessageId === null || initialMessageId === void 0) {
        return void 0;
      }
      const index = collapsedMessages.findIndex((message2) => {
        const messageId = message2.message.id === initialMessageId;
        if (messageId) {
          return true;
        }
        if (message2.toolMessages.find((tm) => tm.id === initialMessageId)) {
          return true;
        }
      });
      return index !== -1 ? index : void 0;
    }, [initialMessageId, collapsedMessages]);
    const renderRow = reactExports.useCallback(
      (index, item2) => {
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          ChatMessageRow,
          {
            index,
            parentName: id2 || "chat-virtual-list",
            showLabels,
            highlightLabeled,
            labels,
            resolvedMessage: item2,
            indented: indented2,
            toolCallStyle,
            highlightUserMessage: true,
            allowLinking
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/ChatViewVirtualList.tsx",
            lineNumber: 169,
            columnNumber: 13
          },
          void 0
        );
      },
      [
        id2,
        showLabels,
        labels,
        indented2,
        toolCallStyle,
        collapsedMessages,
        highlightLabeled,
        allowLinking
      ]
    );
    const Item = ({
      children: children2,
      ...props
    }) => {
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "div",
        {
          className: clsx(styles$P.item),
          "data-index": props["data-index"],
          "data-item-group-index": props["data-item-group-index"],
          "data-item-index": props["data-item-index"],
          "data-known-size": props["data-known-size"],
          style: props.style,
          children: children2
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/ChatViewVirtualList.tsx",
          lineNumber: 200,
          columnNumber: 11
        },
        void 0
      );
    };
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      LiveVirtualList,
      {
        id: "chat-virtual-list",
        listHandle,
        className: className2,
        scrollRef,
        data: collapsedMessages,
        renderRow,
        initialTopMostItemIndex: initialMessageIndex,
        offsetTop: topOffset,
        live: running,
        showProgress: running,
        components: { Item }
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/chat/ChatViewVirtualList.tsx",
        lineNumber: 214,
        columnNumber: 9
      },
      void 0
    );
  }
);
const styles$O = {};
const title$2 = "_title_19l1b_1";
const contents = "_contents_19l1b_8";
const styles$N = {
  title: title$2,
  contents
};
const EventRow = ({
  title: title2,
  icon: icon2,
  className: className2,
  children: children2
}) => {
  const contentEl = title2 ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("text-size-small", styles$N.title, className2), children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("i", { className: icon2 || ApplicationIcons.metadata }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventRow.tsx",
      lineNumber: 25,
      columnNumber: 7
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("text-style-label"), children: title2 }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventRow.tsx",
      lineNumber: 26,
      columnNumber: 7
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: children2 }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventRow.tsx",
      lineNumber: 27,
      columnNumber: 7
    }, void 0)
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventRow.tsx",
    lineNumber: 24,
    columnNumber: 5
  }, void 0) : "";
  const card2 = /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("card", styles$N.contents), children: contentEl }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventRow.tsx",
    lineNumber: 33,
    columnNumber: 16
  }, void 0);
  return card2;
};
const ApprovalEventView = ({
  eventNode,
  className: className2
}) => {
  const event = eventNode.event;
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    EventRow,
    {
      title: decisionLabel(event.decision),
      icon: decisionIcon(event.decision),
      className: className2,
      children: event.explanation || ""
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ApprovalEventView.tsx",
      lineNumber: 23,
      columnNumber: 5
    },
    void 0
  );
};
const decisionLabel = (decision) => {
  switch (decision) {
    case "approve":
      return "Approved";
    case "reject":
      return "Rejected";
    case "terminate":
      return "Terminated";
    case "escalate":
      return "Escalated";
    case "modify":
      return "Modified";
    default:
      return decision;
  }
};
const decisionIcon = (decision) => {
  switch (decision) {
    case "approve":
      return ApplicationIcons.approvals.approve;
    case "reject":
      return ApplicationIcons.approvals.reject;
    case "terminate":
      return ApplicationIcons.approvals.terminate;
    case "escalate":
      return ApplicationIcons.approvals.escalate;
    case "modify":
      return ApplicationIcons.approvals.modify;
    default:
      return ApplicationIcons.approve;
  }
};
const useCollapseTranscriptEvent = (scope, id2) => {
  const collapsed = useStore((state) => state.transcriptCollapsedEvents);
  const collapseEvent = useStore((state) => state.setTranscriptCollapsedEvent);
  return reactExports.useMemo(() => {
    const isCollapsed = collapsed !== null && collapsed[scope]?.[id2] === true;
    const set3 = (value2) => {
      collapseEvent(scope, id2, value2);
    };
    return [isCollapsed, set3];
  }, [collapsed, collapseEvent, id2]);
};
const STEP = "step";
const ACTION_BEGIN = "begin";
const SPAN_BEGIN = "span_begin";
const SPAN_END = "span_end";
const TOOL = "tool";
const STORE = "store";
const STATE = "state";
const TYPE_TOOL = "tool";
const TYPE_SUBTASK = "subtask";
const TYPE_SOLVER = "solver";
const TYPE_SOLVERS = "solvers";
const TYPE_AGENT = "agent";
const TYPE_HANDOFF = "handoff";
const TYPE_SCORERS = "scorers";
const TYPE_SCORER = "scorer";
const hasSpans = (events) => {
  return events.some((event) => event.event === SPAN_BEGIN);
};
const kTranscriptCollapseScope = "transcript-collapse";
const kCollapsibleEventTypes = [
  STEP,
  SPAN_BEGIN,
  TYPE_TOOL,
  TYPE_SUBTASK
];
class EventNode {
  id;
  event;
  children = [];
  depth;
  constructor(id2, event, depth) {
    this.id = id2;
    this.event = event;
    this.depth = depth;
  }
}
const tab = "_tab_1je38_1";
const styles$M = {
  tab
};
const EventNav = ({
  target,
  title: title2,
  selectedNav,
  setSelectedNav
}) => {
  const active = target === selectedNav;
  const handleClick = reactExports.useCallback(() => {
    setSelectedNav(target);
  }, [setSelectedNav, target]);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("li", { className: "nav-item", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "button",
    {
      type: "button",
      role: "tab",
      "aria-controls": target,
      "aria-selected": active,
      className: clsx(
        "nav-link",
        active ? "active " : "",
        "text-style-label",
        "text-size-small",
        styles$M.tab
      ),
      onClick: handleClick,
      children: title2
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventNav.tsx",
      lineNumber: 29,
      columnNumber: 7
    },
    void 0
  ) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventNav.tsx",
    lineNumber: 28,
    columnNumber: 5
  }, void 0);
};
const navs$1 = "_navs_1vm6p_1";
const styles$L = {
  navs: navs$1
};
const EventNavs = ({
  navs: navs2,
  selectedNav,
  setSelectedNav
}) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "ul",
    {
      className: clsx("nav", "nav-pills", styles$L.navs),
      role: "tablist",
      "aria-orientation": "horizontal",
      children: navs2.map((nav2) => {
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          EventNav,
          {
            target: nav2.target,
            title: nav2.title,
            selectedNav,
            setSelectedNav
          },
          nav2.title,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventNavs.tsx",
            lineNumber: 29,
            columnNumber: 11
          },
          void 0
        );
      })
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventNavs.tsx",
      lineNumber: 22,
      columnNumber: 5
    },
    void 0
  );
};
const label$3 = "_label_1nn7f_1";
const navs = "_navs_1nn7f_6";
const card = "_card_1nn7f_12";
const cardContent = "_cardContent_1nn7f_20";
const hidden$1 = "_hidden_1nn7f_25";
const hover = "_hover_1nn7f_41";
const root$3 = "_root_1nn7f_45";
const bottomDongle = "_bottomDongle_1nn7f_50";
const dongleIcon = "_dongleIcon_1nn7f_67";
const styles$K = {
  label: label$3,
  navs,
  card,
  cardContent,
  hidden: hidden$1,
  hover,
  root: root$3,
  bottomDongle,
  dongleIcon
};
const EventPanel = ({
  eventNodeId,
  depth,
  className: className2,
  title: title2,
  subTitle: subTitle2,
  text: text2,
  icon: icon2,
  children: children2,
  childIds,
  collapsibleContent,
  collapseControl = "top"
}) => {
  const [collapsed, setCollapsed] = useCollapseTranscriptEvent(
    kTranscriptCollapseScope,
    eventNodeId
  );
  const isCollapsible = (childIds || []).length > 0 || collapsibleContent;
  const useBottomDongle = isCollapsible && collapseControl === "bottom";
  const pillId = (index) => {
    return `${eventNodeId}-nav-pill-${index}`;
  };
  const filteredArrChildren = (Array.isArray(children2) ? children2 : [children2]).filter((child) => !!child);
  const defaultPill = filteredArrChildren.findIndex((node2) => {
    return hasDataDefault(node2) && node2.props["data-default"];
  });
  const defaultPillId = defaultPill !== -1 ? pillId(defaultPill) : pillId(0);
  const [selectedNav, setSelectedNav] = useProperty(
    eventNodeId,
    "selectedNav",
    {
      defaultValue: defaultPillId
    }
  );
  const gridColumns = [];
  if (isCollapsible && !useBottomDongle) {
    gridColumns.push("minmax(0, max-content)");
  }
  if (icon2) {
    gridColumns.push("max-content");
  }
  gridColumns.push("minmax(0, max-content)");
  gridColumns.push("auto");
  gridColumns.push("minmax(0, max-content)");
  gridColumns.push("minmax(0, max-content)");
  const toggleCollapse = reactExports.useCallback(() => {
    setCollapsed(!collapsed);
  }, [setCollapsed, collapsed, childIds]);
  const [mouseOver, setMouseOver] = reactExports.useState(false);
  const titleEl = title2 || icon2 || filteredArrChildren.length > 1 ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "div",
    {
      title: subTitle2,
      className: clsx("text-size-small", mouseOver ? styles$K.hover : ""),
      style: {
        display: "grid",
        gridTemplateColumns: gridColumns.join(" "),
        columnGap: "0.3em",
        cursor: isCollapsible && !useBottomDongle ? "pointer" : void 0
      },
      onMouseEnter: () => setMouseOver(true),
      onMouseLeave: () => setMouseOver(false),
      children: [
        isCollapsible && !useBottomDongle ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "i",
          {
            onClick: toggleCollapse,
            className: collapsed ? ApplicationIcons.chevron.right : ApplicationIcons.chevron.down
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventPanel.tsx",
            lineNumber: 130,
            columnNumber: 11
          },
          void 0
        ) : "",
        icon2 ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "i",
          {
            className: clsx(
              icon2 || ApplicationIcons.metadata,
              "text-style-secondary"
            ),
            onClick: toggleCollapse
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventPanel.tsx",
            lineNumber: 142,
            columnNumber: 11
          },
          void 0
        ) : "",
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "div",
          {
            className: clsx("text-style-secondary", "text-style-label"),
            onClick: toggleCollapse,
            children: title2
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventPanel.tsx",
            lineNumber: 152,
            columnNumber: 9
          },
          void 0
        ),
        "",
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { onClick: toggleCollapse }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventPanel.tsx",
          lineNumber: 167,
          columnNumber: 9
        }, void 0),
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "div",
          {
            className: clsx("text-style-secondary", styles$K.label),
            onClick: toggleCollapse,
            children: collapsed ? text2 : ""
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventPanel.tsx",
            lineNumber: 168,
            columnNumber: 9
          },
          void 0
        ),
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: styles$K.navs, children: isCollapsible && collapsibleContent && collapsed ? "" : filteredArrChildren && filteredArrChildren.length > 1 ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          EventNavs,
          {
            navs: filteredArrChildren.map((child, index) => {
              const defaultTitle = `Tab ${index}`;
              const title22 = child && reactExports.isValidElement(child) ? child.props["data-name"] || defaultTitle : defaultTitle;
              return {
                id: `eventpanel-${eventNodeId}-${index}`,
                title: title22,
                target: pillId(index)
              };
            }),
            selectedNav: selectedNav || "",
            setSelectedNav
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventPanel.tsx",
            lineNumber: 178,
            columnNumber: 13
          },
          void 0
        ) : "" }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventPanel.tsx",
          lineNumber: 174,
          columnNumber: 9
        }, void 0)
      ]
    },
    void 0,
    true,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventPanel.tsx",
      lineNumber: 117,
      columnNumber: 7
    },
    void 0
  ) : "";
  const card2 = /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "div",
    {
      id: `event-panel-${eventNodeId}`,
      className: clsx(
        className2,
        styles$K.card,
        depth === 0 ? styles$K.root : void 0
      ),
      children: [
        titleEl,
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "div",
          {
            className: clsx(
              "tab-content",
              styles$K.cardContent,
              isCollapsible && collapsed && collapsibleContent ? styles$K.hidden : void 0
            ),
            children: filteredArrChildren?.map((child, index) => {
              const id2 = pillId(index);
              const isSelected = id2 === selectedNav;
              return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
                "div",
                {
                  id: id2,
                  className: clsx("tab-pane", "show", isSelected ? "active" : ""),
                  children: child
                },
                `children-${id2}-${index}`,
                false,
                {
                  fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventPanel.tsx",
                  lineNumber: 227,
                  columnNumber: 13
                },
                void 0
              );
            })
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventPanel.tsx",
            lineNumber: 213,
            columnNumber: 7
          },
          void 0
        ),
        isCollapsible && useBottomDongle ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "div",
          {
            className: clsx(styles$K.bottomDongle, "text-size-smallest"),
            onClick: toggleCollapse,
            children: [
              /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
                "i",
                {
                  className: clsx(
                    collapsed ? ApplicationIcons.chevron.right : ApplicationIcons.chevron.down,
                    styles$K.dongleIcon
                  )
                },
                void 0,
                false,
                {
                  fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventPanel.tsx",
                  lineNumber: 243,
                  columnNumber: 11
                },
                void 0
              ),
              "transcript (",
              childIds?.length,
              " ",
              childIds?.length === 1 ? "event" : "events",
              ")"
            ]
          },
          void 0,
          true,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventPanel.tsx",
            lineNumber: 239,
            columnNumber: 9
          },
          void 0
        ) : void 0
      ]
    },
    void 0,
    true,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventPanel.tsx",
      lineNumber: 204,
      columnNumber: 5
    },
    void 0
  );
  return card2;
};
function hasDataDefault(node2) {
  return reactExports.isValidElement(node2) && node2.props !== null && typeof node2.props === "object" && "data-default" in node2.props;
}
const ErrorEventView = ({
  eventNode,
  className: className2
}) => {
  const event = eventNode.event;
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    EventPanel,
    {
      eventNodeId: eventNode.id,
      depth: eventNode.depth,
      title: "Error",
      className: className2,
      subTitle: formatDateTime(new Date(event.timestamp)),
      icon: ApplicationIcons.error,
      children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        ANSIDisplay,
        {
          output: event.error.traceback_ansi,
          style: {
            fontSize: "clamp(0.3rem, 1.1vw, 0.8rem)",
            margin: "0.5em 0"
          }
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ErrorEventView.tsx",
          lineNumber: 33,
          columnNumber: 7
        },
        void 0
      )
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ErrorEventView.tsx",
      lineNumber: 25,
      columnNumber: 5
    },
    void 0
  );
};
const panel = "_panel_vz394_1";
const styles$J = {
  panel
};
const InfoEventView = ({
  eventNode,
  className: className2
}) => {
  const event = eventNode.event;
  const panels = [];
  if (typeof event.data === "string") {
    panels.push(
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        RenderedText,
        {
          markdown: event.data,
          className: clsx(styles$J.panel, "text-size-base")
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/InfoEventView.tsx",
          lineNumber: 30,
          columnNumber: 7
        },
        void 0
      )
    );
  } else {
    panels.push(/* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(JSONPanel, { data: event.data, className: styles$J.panel }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/InfoEventView.tsx",
      lineNumber: 36,
      columnNumber: 17
    }, void 0));
  }
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    EventPanel,
    {
      eventNodeId: eventNode.id,
      depth: eventNode.depth,
      title: "Info" + (event.source ? ": " + event.source : ""),
      className: className2,
      subTitle: formatDateTime(new Date(event.timestamp)),
      icon: ApplicationIcons.info,
      children: panels
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/InfoEventView.tsx",
      lineNumber: 40,
      columnNumber: 5
    },
    void 0
  );
};
const InputEventView = ({
  eventNode,
  className: className2
}) => {
  const event = eventNode.event;
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    EventPanel,
    {
      eventNodeId: eventNode.id,
      depth: eventNode.depth,
      title: "Input",
      className: className2,
      subTitle: formatDateTime(new Date(event.timestamp)),
      icon: ApplicationIcons.input,
      children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        ANSIDisplay,
        {
          output: event.input_ansi,
          style: { fontSize: "clamp(0.4rem, 1.15vw, 0.9rem)" }
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/InputEventView.tsx",
          lineNumber: 33,
          columnNumber: 7
        },
        void 0
      )
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/InputEventView.tsx",
      lineNumber: 25,
      columnNumber: 5
    },
    void 0
  );
};
const grid$1 = "_grid_1eq5o_1";
const styles$I = {
  grid: grid$1
};
const LoggerEventView = ({
  eventNode,
  className: className2
}) => {
  const event = eventNode.event;
  const obj = parsedJson(event.message.message);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    EventRow,
    {
      className: className2,
      title: event.message.level,
      icon: ApplicationIcons.logging[event.message.level.toLowerCase()] || ApplicationIcons.info,
      children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("text-size-base", styles$I.grid), children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("text-size-smaller"), children: obj !== void 0 && obj !== null ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(MetaDataGrid, { entries: obj }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/LoggerEventView.tsx",
          lineNumber: 39,
          columnNumber: 13
        }, void 0) : event.message.message }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/LoggerEventView.tsx",
          lineNumber: 37,
          columnNumber: 9
        }, void 0),
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("text-size-smaller", "text-style-secondary"), children: [
          event.message.filename,
          ":",
          event.message.lineno
        ] }, void 0, true, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/LoggerEventView.tsx",
          lineNumber: 44,
          columnNumber: 9
        }, void 0)
      ] }, void 0, true, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/LoggerEventView.tsx",
        lineNumber: 36,
        columnNumber: 7
      }, void 0)
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/LoggerEventView.tsx",
      lineNumber: 28,
      columnNumber: 5
    },
    void 0
  );
};
const container$c = "_container_1ww70_1";
const titleRow = "_titleRow_1ww70_5";
const title$1 = "_title_1ww70_5";
const styles$H = {
  container: container$c,
  titleRow,
  title: title$1
};
const EventSection = ({
  title: title2,
  children: children2,
  copyContent,
  className: className2
}) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$H.container, className2), children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$H.titleRow), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "div",
      {
        className: clsx("text-size-small", "text-style-label", styles$H.title),
        children: [
          title2,
          copyContent ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(CopyButton, { value: copyContent, ariaLabel: "Copy to clipboard" }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventSection.tsx",
            lineNumber: 32,
            columnNumber: 13
          }, void 0) : null
        ]
      },
      void 0,
      true,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventSection.tsx",
        lineNumber: 27,
        columnNumber: 9
      },
      void 0
    ) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventSection.tsx",
      lineNumber: 26,
      columnNumber: 7
    }, void 0),
    children2
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventSection.tsx",
    lineNumber: 25,
    columnNumber: 5
  }, void 0);
};
const wrapper = "_wrapper_45f60_1";
const col2 = "_col2_45f60_8";
const col1_3 = "_col1_3_45f60_12";
const col3 = "_col3_45f60_16";
const separator$2 = "_separator_45f60_20";
const topMargin = "_topMargin_45f60_26";
const styles$G = {
  wrapper,
  col2,
  col1_3,
  col3,
  separator: separator$2,
  topMargin
};
const EventTimingPanel = ({
  timestamp: timestamp2,
  completed,
  working_start,
  working_time
}) => {
  const rows = [
    {
      label: "Clock Time",
      value: void 0,
      secondary: false
    },
    {
      label: "---",
      value: void 0,
      secondary: false
    }
  ];
  if (!completed) {
    rows.push({
      label: "Timestamp",
      value: formatDateTime(new Date(timestamp2))
    });
  } else {
    rows.push({ label: "Start", value: formatDateTime(new Date(timestamp2)) });
    rows.push({ label: "End", value: formatDateTime(new Date(completed)) });
  }
  if (working_start || working_time) {
    rows.push({
      label: "Working Time",
      value: void 0,
      secondary: false,
      topMargin: true
    });
    rows.push({
      label: "---",
      value: void 0,
      secondary: false
    });
    if (working_start) {
      rows.push({
        label: "Start",
        value: formatTime$1(working_start)
      });
    }
    if (working_time) {
      rows.push({
        label: "Duration",
        value: formatTime$1(working_time)
      });
    }
    if (working_start && working_time) {
      rows.push({
        label: "End",
        value: formatTime$1(
          Math.round(working_start * 10) / 10 + Math.round(working_time * 10) / 10
        )
      });
    }
  }
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("text-size-small", styles$G.wrapper), children: rows.map((row2, idx) => {
    if (row2.label === "---") {
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: styles$G.separator }, `$usage-sep-${idx}`, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventTimingPanel.tsx",
        lineNumber: 95,
        columnNumber: 13
      }, void 0);
    } else {
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(reactExports.Fragment, { children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "div",
          {
            className: clsx(
              "text-style-label",
              "text-style-secondary",
              row2.secondary ? styles$G.col2 : styles$G.col1_3,
              row2.topMargin ? styles$G.topMargin : void 0
            ),
            children: row2.label
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventTimingPanel.tsx",
            lineNumber: 100,
            columnNumber: 15
          },
          void 0
        ),
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: styles$G.col3, children: row2.value ? row2.value : "" }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventTimingPanel.tsx",
          lineNumber: 110,
          columnNumber: 15
        }, void 0)
      ] }, `$usage-row-${idx}`, true, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventTimingPanel.tsx",
        lineNumber: 99,
        columnNumber: 13
      }, void 0);
    }
  }) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/event/EventTimingPanel.tsx",
    lineNumber: 91,
    columnNumber: 5
  }, void 0);
};
const formatTiming = (timestamp2, working_start) => {
  if (working_start) {
    return `${formatDateTime(new Date(timestamp2))}
@ working time: ${formatTime$1(working_start)}`;
  } else {
    return formatDateTime(new Date(timestamp2));
  }
};
const formatTitle = (title2, total_tokens, working_start) => {
  const subItems = [];
  if (total_tokens) {
    subItems.push(`${formatNumber(total_tokens)} tokens`);
  }
  if (working_start) {
    subItems.push(`${formatTime$1(working_start)}`);
  }
  const subtitle2 = subItems.length > 0 ? ` (${subItems.join(", ")})` : "";
  return `${title2}${subtitle2}`;
};
const container$b = "_container_e0l2n_1";
const all = "_all_e0l2n_6";
const tableSelection = "_tableSelection_e0l2n_12";
const codePre = "_codePre_e0l2n_22";
const code$1 = "_code_e0l2n_22";
const progress$1 = "_progress_e0l2n_34";
const toolConfig = "_toolConfig_e0l2n_38";
const toolChoice = "_toolChoice_e0l2n_46";
const styles$F = {
  container: container$b,
  all,
  tableSelection,
  codePre,
  code: code$1,
  progress: progress$1,
  toolConfig,
  toolChoice
};
const ModelEventView = ({
  eventNode,
  showToolCalls,
  className: className2,
  context
}) => {
  const event = eventNode.event;
  const totalUsage = event.output.usage?.total_tokens;
  const callTime = event.output.time;
  const outputMessages = event.output.choices?.map((choice) => {
    return choice.message;
  });
  const entries2 = { ...event.config };
  delete entries2["max_connections"];
  const userMessages = [];
  for (const msg of event.input.slice().reverse()) {
    if (msg.role === "user" && !msg.tool_call_id || msg.role === "system" || // If the client doesn't support tool events, then tools messages are allowed to be displayed
    // in this view, since no tool events will be shown. This pretty much happens for bridged agents
    // where tool events aren't captured.
    context?.hasToolEvents === false && msg.role === "tool") {
      userMessages.unshift(msg);
    } else {
      break;
    }
  }
  const panelTitle = event.role ? `Model Call (${event.role}): ${event.model}` : `Model Call: ${event.model}`;
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    EventPanel,
    {
      eventNodeId: eventNode.id,
      depth: eventNode.depth,
      className: className2,
      title: formatTitle(panelTitle, totalUsage, callTime),
      subTitle: formatTiming(event.timestamp, event.working_start),
      icon: ApplicationIcons.model,
      children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { "data-name": "Summary", className: styles$F.container, children: [
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            ChatView,
            {
              id: `${eventNode.id}-model-output`,
              messages: [...userMessages, ...outputMessages || []],
              toolCallStyle: showToolCalls ? "complete" : "omit",
              resolveToolCallsIntoPreviousMessage: context?.hasToolEvents !== false,
              allowLinking: false
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
              lineNumber: 92,
              columnNumber: 9
            },
            void 0
          ),
          event.pending ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$F.progress), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(PulsingDots, { subtle: false, size: "medium" }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
            lineNumber: 101,
            columnNumber: 13
          }, void 0) }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
            lineNumber: 100,
            columnNumber: 11
          }, void 0) : void 0
        ] }, void 0, true, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
          lineNumber: 91,
          columnNumber: 7
        }, void 0),
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { "data-name": "All", className: styles$F.container, children: [
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: styles$F.all, children: [
            Object.keys(entries2).length > 0 && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
              EventSection,
              {
                title: "Configuration",
                className: styles$F.tableSelection,
                children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(MetaDataGrid, { entries: entries2, plain: true }, void 0, false, {
                  fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
                  lineNumber: 112,
                  columnNumber: 15
                }, void 0)
              },
              void 0,
              false,
              {
                fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
                lineNumber: 108,
                columnNumber: 13
              },
              void 0
            ),
            /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(EventSection, { title: "Usage", className: styles$F.tableSelection, children: event.output.usage !== null ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ModelUsagePanel, { usage: event.output.usage }, void 0, false, {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
              lineNumber: 118,
              columnNumber: 15
            }, void 0) : void 0 }, void 0, false, {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
              lineNumber: 116,
              columnNumber: 11
            }, void 0),
            /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(EventSection, { title: "Timing", className: styles$F.tableSelection, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
              EventTimingPanel,
              {
                timestamp: event.timestamp,
                completed: event.completed,
                working_start: event.working_start,
                working_time: event.working_time
              },
              void 0,
              false,
              {
                fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
                lineNumber: 123,
                columnNumber: 13
              },
              void 0
            ) }, void 0, false, {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
              lineNumber: 122,
              columnNumber: 11
            }, void 0)
          ] }, void 0, true, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
            lineNumber: 106,
            columnNumber: 9
          }, void 0),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(EventSection, { title: "Messages", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            ChatView,
            {
              id: `${eventNode.id}-model-input-full`,
              messages: [...event.input, ...outputMessages || []],
              resolveToolCallsIntoPreviousMessage: context?.hasToolEvents !== false,
              allowLinking: false
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
              lineNumber: 133,
              columnNumber: 11
            },
            void 0
          ) }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
            lineNumber: 132,
            columnNumber: 9
          }, void 0)
        ] }, void 0, true, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
          lineNumber: 105,
          columnNumber: 7
        }, void 0),
        event.tools.length > 1 && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { "data-name": "Tools", className: styles$F.container, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ToolsConfig, { tools: event.tools, toolChoice: event.tool_choice }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
          lineNumber: 146,
          columnNumber: 11
        }, void 0) }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
          lineNumber: 145,
          columnNumber: 9
        }, void 0),
        event.call ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          APIView,
          {
            "data-name": "API",
            call: event.call,
            className: styles$F.container
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
            lineNumber: 151,
            columnNumber: 9
          },
          void 0
        ) : ""
      ]
    },
    void 0,
    true,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
      lineNumber: 83,
      columnNumber: 5
    },
    void 0
  );
};
const APIView = ({ call: call2, className: className2 }) => {
  const requestCode = reactExports.useMemo(() => {
    return JSON.stringify(call2.request, void 0, 2);
  }, [call2.request]);
  const responseCode = reactExports.useMemo(() => {
    return JSON.stringify(call2.response, void 0, 2);
  }, [call2.response]);
  if (!call2) {
    return null;
  }
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(className2), children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(EventSection, { title: "Request", copyContent: requestCode, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(APICodeCell, { sourceCode: requestCode }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
      lineNumber: 184,
      columnNumber: 9
    }, void 0) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
      lineNumber: 183,
      columnNumber: 7
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(EventSection, { title: "Response", copyContent: responseCode, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(APICodeCell, { sourceCode: responseCode }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
      lineNumber: 187,
      columnNumber: 9
    }, void 0) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
      lineNumber: 186,
      columnNumber: 7
    }, void 0)
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
    lineNumber: 182,
    columnNumber: 5
  }, void 0);
};
const APICodeCell = ({ id: id2, sourceCode }) => {
  const sourceCodeRef = reactExports.useRef(null);
  usePrismHighlight(sourceCodeRef, sourceCode.length);
  if (!sourceCode) {
    return null;
  }
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { ref: sourceCodeRef, className: clsx("model-call"), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("pre", { className: clsx(styles$F.codePre), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "code",
    {
      id: id2,
      className: clsx("language-json", styles$F.code, "text-size-small"),
      children: sourceCode
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
      lineNumber: 209,
      columnNumber: 9
    },
    void 0
  ) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
    lineNumber: 208,
    columnNumber: 7
  }, void 0) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
    lineNumber: 207,
    columnNumber: 5
  }, void 0);
};
const ToolsConfig = ({ tools: tools2, toolChoice: toolChoice2 }) => {
  const toolEls = tools2.map((tool2, idx) => {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(reactExports.Fragment, { children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("text-style-label", "text-style-secondary"), children: tool2.name }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
        lineNumber: 229,
        columnNumber: 9
      }, void 0),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: tool2.description }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
        lineNumber: 232,
        columnNumber: 9
      }, void 0)
    ] }, `${tool2.name}-${idx}`, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
      lineNumber: 228,
      columnNumber: 7
    }, void 0);
  });
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(jsxDevRuntimeExports.Fragment, { children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$F.toolConfig, "text-size-small"), children: toolEls }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
      lineNumber: 239,
      columnNumber: 7
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$F.toolChoice, "text-size-small"), children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("text-style-label", "text-style-secondary"), children: "Tool Choice" }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
        lineNumber: 243,
        columnNumber: 9
      }, void 0),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ToolChoiceView, { toolChoice: toolChoice2 }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
        lineNumber: 247,
        columnNumber: 11
      }, void 0) }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
        lineNumber: 246,
        columnNumber: 9
      }, void 0)
    ] }, void 0, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
      lineNumber: 242,
      columnNumber: 7
    }, void 0)
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
    lineNumber: 238,
    columnNumber: 5
  }, void 0);
};
const ToolChoiceView = ({ toolChoice: toolChoice2 }) => {
  if (typeof toolChoice2 === "string") {
    return toolChoice2;
  } else {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("code", { children: [
      "`$",
      toolChoice2.name,
      "()`"
    ] }, void 0, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ModelEventView.tsx",
      lineNumber: 262,
      columnNumber: 12
    }, void 0);
  }
};
const toArray = (val) => {
  if (Array.isArray(val)) {
    return val;
  } else {
    return [val];
  }
};
const noMargin = "_noMargin_1a3fk_1";
const code = "_code_1a3fk_5";
const sample = "_sample_1a3fk_10";
const section$1 = "_section_1a3fk_14";
const metadata = "_metadata_1a3fk_21";
const styles$E = {
  noMargin,
  code,
  sample,
  section: section$1,
  metadata
};
const SampleInitEventView = ({
  eventNode,
  className: className2
}) => {
  const event = eventNode.event;
  const stateObj = event.state;
  const sections = [];
  if (event.sample.files && Object.keys(event.sample.files).length > 0) {
    sections.push(
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(EventSection, { title: "Files", children: Object.keys(event.sample.files).map((file) => {
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("pre", { className: styles$E.noMargin, children: file }, `sample-init-file-${file}`, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SampleInitEventView.tsx",
          lineNumber: 39,
          columnNumber: 13
        }, void 0);
      }) }, `event-${eventNode.id}`, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SampleInitEventView.tsx",
        lineNumber: 36,
        columnNumber: 7
      }, void 0)
    );
  }
  if (event.sample.setup) {
    sections.push(
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(EventSection, { title: "Setup", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("pre", { className: styles$E.code, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("code", { className: "sourceCode", children: event.sample.setup }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SampleInitEventView.tsx",
        lineNumber: 52,
        columnNumber: 11
      }, void 0) }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SampleInitEventView.tsx",
        lineNumber: 51,
        columnNumber: 9
      }, void 0) }, `${eventNode.id}-section-setup`, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SampleInitEventView.tsx",
        lineNumber: 50,
        columnNumber: 7
      }, void 0)
    );
  }
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    EventPanel,
    {
      eventNodeId: eventNode.id,
      depth: eventNode.depth,
      className: className2,
      title: "Sample",
      icon: ApplicationIcons.sample,
      subTitle: formatDateTime(new Date(event.timestamp)),
      children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { "data-name": "Sample", className: styles$E.sample, children: [
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            ChatView,
            {
              messages: stateObj["messages"],
              allowLinking: false
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SampleInitEventView.tsx",
              lineNumber: 68,
              columnNumber: 9
            },
            void 0
          ),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: [
            event.sample.choices ? event.sample.choices.map((choice, index) => {
              return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: [
                String.fromCharCode(65 + index),
                ") ",
                choice
              ] }, `$choice-{choice}`, true, {
                fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SampleInitEventView.tsx",
                lineNumber: 76,
                columnNumber: 19
              }, void 0);
            }) : "",
            sections.length > 0 ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: styles$E.section, children: sections }, void 0, false, {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SampleInitEventView.tsx",
              lineNumber: 83,
              columnNumber: 13
            }, void 0) : "",
            event.sample.target ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(EventSection, { title: "Target", children: toArray(event.sample.target).map((target) => {
              return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("text-size-base"), children: target }, target, false, {
                fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SampleInitEventView.tsx",
                lineNumber: 91,
                columnNumber: 19
              }, void 0);
            }) }, void 0, false, {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SampleInitEventView.tsx",
              lineNumber: 88,
              columnNumber: 13
            }, void 0) : void 0
          ] }, void 0, true, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SampleInitEventView.tsx",
            lineNumber: 72,
            columnNumber: 9
          }, void 0)
        ] }, void 0, true, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SampleInitEventView.tsx",
          lineNumber: 67,
          columnNumber: 7
        }, void 0),
        event.sample.metadata && Object.keys(event.sample.metadata).length > 0 ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          MetaDataGrid,
          {
            "data-name": "Metadata",
            className: styles$E.metadata,
            entries: event.sample.metadata
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SampleInitEventView.tsx",
            lineNumber: 102,
            columnNumber: 9
          },
          void 0
        ) : ""
      ]
    },
    void 0,
    true,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SampleInitEventView.tsx",
      lineNumber: 59,
      columnNumber: 5
    },
    void 0
  );
};
const SampleLimitEventView = ({
  eventNode,
  className: className2
}) => {
  const resolve_title = (type) => {
    switch (type) {
      case "custom":
        return "Custom Limit Exceeded";
      case "time":
        return "Time Limit Exceeded";
      case "message":
        return "Message Limit Exceeded";
      case "token":
        return "Token Limit Exceeded";
      case "operator":
        return "Operator Canceled";
      case "working":
        return "Execution Time Limit Exceeded";
    }
  };
  const resolve_icon = (type) => {
    switch (type) {
      case "custom":
        return ApplicationIcons.limits.custom;
      case "time":
        return ApplicationIcons.limits.time;
      case "message":
        return ApplicationIcons.limits.messages;
      case "token":
        return ApplicationIcons.limits.tokens;
      case "operator":
        return ApplicationIcons.limits.operator;
      case "working":
        return ApplicationIcons.limits.execution;
    }
  };
  const title2 = resolve_title(eventNode.event.type);
  const icon2 = resolve_icon(eventNode.event.type);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    EventPanel,
    {
      eventNodeId: eventNode.id,
      depth: eventNode.depth,
      title: title2,
      icon: icon2,
      className: className2,
      children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("text-size-smaller"), children: eventNode.event.message }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SampleLimitEventView.tsx",
        lineNumber: 67,
        columnNumber: 7
      }, void 0)
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SampleLimitEventView.tsx",
      lineNumber: 60,
      columnNumber: 5
    },
    void 0
  );
};
const twoColumn = "_twoColumn_1irga_9";
const exec = "_exec_1irga_15";
const result$1 = "_result_1irga_19";
const fileLabel = "_fileLabel_1irga_23";
const wrapPre = "_wrapPre_1irga_28";
const styles$D = {
  twoColumn,
  exec,
  result: result$1,
  fileLabel,
  wrapPre
};
const SandboxEventView = ({
  eventNode,
  className: className2
}) => {
  const event = eventNode.event;
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    EventPanel,
    {
      eventNodeId: eventNode.id,
      depth: eventNode.depth,
      className: className2,
      title: `Sandbox: ${event.action}`,
      icon: ApplicationIcons.sandbox,
      subTitle: formatTiming(event.timestamp, event.working_start),
      children: event.action === "exec" ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ExecView, { id: `${eventNode.id}-exec`, event }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SandboxEventView.tsx",
        lineNumber: 39,
        columnNumber: 9
      }, void 0) : event.action === "read_file" ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ReadFileView, { id: `${eventNode.id}-read-file`, event }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SandboxEventView.tsx",
        lineNumber: 41,
        columnNumber: 9
      }, void 0) : /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(WriteFileView, { id: `${eventNode.id}-write-file`, event }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SandboxEventView.tsx",
        lineNumber: 43,
        columnNumber: 9
      }, void 0)
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SandboxEventView.tsx",
      lineNumber: 30,
      columnNumber: 5
    },
    void 0
  );
};
const ExecView = ({ id: id2, event }) => {
  if (event.cmd === null) {
    return void 0;
  }
  const cmd = event.cmd;
  const options = event.options;
  const input2 = event.input;
  const result2 = event.result;
  const output2 = event.output ? event.output.trim() : void 0;
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$D.exec), children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(EventSection, { title: `Command`, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$D.twoColumn), children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("pre", { className: clsx(styles$D.wrapPre), children: cmd }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SandboxEventView.tsx",
        lineNumber: 68,
        columnNumber: 11
      }, void 0),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("pre", { className: clsx(styles$D.wrapPre), children: input2 !== null ? input2?.trim() : void 0 }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SandboxEventView.tsx",
        lineNumber: 69,
        columnNumber: 11
      }, void 0),
      options !== null && Object.keys(options).length > 0 ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(EventSection, { title: `Options`, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        MetaDataGrid,
        {
          entries: options,
          plain: true
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SandboxEventView.tsx",
          lineNumber: 75,
          columnNumber: 15
        },
        void 0
      ) }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SandboxEventView.tsx",
        lineNumber: 74,
        columnNumber: 13
      }, void 0) : void 0
    ] }, void 0, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SandboxEventView.tsx",
      lineNumber: 67,
      columnNumber: 9
    }, void 0) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SandboxEventView.tsx",
      lineNumber: 66,
      columnNumber: 7
    }, void 0),
    output2 || result2 !== null && result2 !== 0 ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(EventSection, { title: `Result`, children: [
      output2 ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ExpandablePanel, { id: `${id2}-output`, collapse: false, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        RenderedContent,
        {
          id: `${id2}-output-content`,
          entry: { name: "sandbox_output", value: output2 }
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SandboxEventView.tsx",
          lineNumber: 87,
          columnNumber: 15
        },
        void 0
      ) }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SandboxEventView.tsx",
        lineNumber: 86,
        columnNumber: 13
      }, void 0) : void 0,
      result2 !== 0 ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$D.result, "text-size-base"), children: [
        "(exited with code ",
        result2,
        ")"
      ] }, void 0, true, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SandboxEventView.tsx",
        lineNumber: 94,
        columnNumber: 13
      }, void 0) : void 0
    ] }, void 0, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SandboxEventView.tsx",
      lineNumber: 84,
      columnNumber: 9
    }, void 0) : void 0
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SandboxEventView.tsx",
    lineNumber: 65,
    columnNumber: 5
  }, void 0);
};
const ReadFileView = ({ id: id2, event }) => {
  if (event.file === null) {
    return void 0;
  }
  const file = event.file;
  const output2 = event.output;
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(FileView, { id: id2, file, contents: output2?.trim() }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SandboxEventView.tsx",
    lineNumber: 115,
    columnNumber: 10
  }, void 0);
};
const WriteFileView = ({ id: id2, event }) => {
  if (event.file === null) {
    return void 0;
  }
  const file = event.file;
  const input2 = event.input;
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(FileView, { id: id2, file, contents: input2?.trim() }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SandboxEventView.tsx",
    lineNumber: 130,
    columnNumber: 10
  }, void 0);
};
const FileView = ({ id: id2, file, contents: contents2 }) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(EventSection, { title: "File", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("pre", { className: clsx(styles$D.fileLabel), children: file }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SandboxEventView.tsx",
      lineNumber: 143,
      columnNumber: 9
    }, void 0) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SandboxEventView.tsx",
      lineNumber: 142,
      columnNumber: 7
    }, void 0),
    contents2 ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(EventSection, { title: "Contents", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ExpandablePanel, { id: `${id2}-file`, collapse: false, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("pre", { children: contents2 }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SandboxEventView.tsx",
      lineNumber: 149,
      columnNumber: 13
    }, void 0) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SandboxEventView.tsx",
      lineNumber: 148,
      columnNumber: 11
    }, void 0) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SandboxEventView.tsx",
      lineNumber: 147,
      columnNumber: 9
    }, void 0) : void 0
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SandboxEventView.tsx",
    lineNumber: 141,
    columnNumber: 5
  }, void 0);
};
const container$a = "_container_io1r0_1";
const wrappingContent$1 = "_wrappingContent_io1r0_8";
const separator$1 = "_separator_io1r0_13";
const unchanged = "_unchanged_io1r0_22";
const section = "_section_io1r0_27";
const spacer = "_spacer_io1r0_31";
const styles$C = {
  container: container$a,
  wrappingContent: wrappingContent$1,
  separator: separator$1,
  unchanged,
  section,
  spacer
};
const explanation$2 = "_explanation_1k2k0_1";
const wrappingContent = "_wrappingContent_1k2k0_8";
const separator = "_separator_1k2k0_13";
const styles$B = {
  explanation: explanation$2,
  wrappingContent,
  separator
};
const ScoreEventView = ({
  eventNode,
  className: className2
}) => {
  const event = eventNode.event;
  const resolvedTarget = event.target ? Array.isArray(event.target) ? event.target.join("\n") : event.target : void 0;
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    EventPanel,
    {
      eventNodeId: eventNode.id,
      depth: eventNode.depth,
      title: (event.intermediate ? "Intermediate " : "") + "Score",
      className: clsx(className2, "text-size-small"),
      subTitle: formatDateTime(new Date(event.timestamp)),
      icon: ApplicationIcons.scorer,
      collapsibleContent: true,
      children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { "data-name": "Explanation", className: clsx(styles$B.explanation), children: [
          event.target ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(reactExports.Fragment, { children: [
            /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$B.separator) }, void 0, false, {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEventView.tsx",
              lineNumber: 47,
              columnNumber: 13
            }, void 0),
            /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "text-style-label", children: "Target" }, void 0, false, {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEventView.tsx",
              lineNumber: 48,
              columnNumber: 13
            }, void 0),
            /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(RenderedText, { markdown: resolvedTarget || "" }, void 0, false, {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEventView.tsx",
              lineNumber: 50,
              columnNumber: 15
            }, void 0) }, void 0, false, {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEventView.tsx",
              lineNumber: 49,
              columnNumber: 13
            }, void 0)
          ] }, void 0, true, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEventView.tsx",
            lineNumber: 46,
            columnNumber: 11
          }, void 0) : "",
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$B.separator) }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEventView.tsx",
            lineNumber: 56,
            columnNumber: 9
          }, void 0),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "text-style-label", children: "Answer" }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEventView.tsx",
            lineNumber: 57,
            columnNumber: 9
          }, void 0),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$B.wrappingContent), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(RenderedText, { markdown: event.score.answer || "" }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEventView.tsx",
            lineNumber: 59,
            columnNumber: 11
          }, void 0) }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEventView.tsx",
            lineNumber: 58,
            columnNumber: 9
          }, void 0),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$B.separator) }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEventView.tsx",
            lineNumber: 61,
            columnNumber: 9
          }, void 0),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "text-style-label", children: "Explanation" }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEventView.tsx",
            lineNumber: 62,
            columnNumber: 9
          }, void 0),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$B.wrappingContent), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(RenderedText, { markdown: event.score.explanation || "" }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEventView.tsx",
            lineNumber: 64,
            columnNumber: 11
          }, void 0) }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEventView.tsx",
            lineNumber: 63,
            columnNumber: 9
          }, void 0),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$B.separator) }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEventView.tsx",
            lineNumber: 66,
            columnNumber: 9
          }, void 0),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "text-style-label", children: "Score" }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEventView.tsx",
            lineNumber: 67,
            columnNumber: 9
          }, void 0),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: renderScore(event.score.value) }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEventView.tsx",
            lineNumber: 68,
            columnNumber: 9
          }, void 0),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$B.separator) }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEventView.tsx",
            lineNumber: 69,
            columnNumber: 9
          }, void 0)
        ] }, void 0, true, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEventView.tsx",
          lineNumber: 44,
          columnNumber: 7
        }, void 0),
        event.score.metadata ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { "data-name": "Metadata", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          RecordTree,
          {
            id: `${eventNode.id}-score-metadata`,
            record: event.score.metadata,
            className: styles$B.metadataTree,
            defaultExpandLevel: 0
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEventView.tsx",
            lineNumber: 73,
            columnNumber: 11
          },
          void 0
        ) }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEventView.tsx",
          lineNumber: 72,
          columnNumber: 9
        }, void 0) : void 0
      ]
    },
    void 0,
    true,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEventView.tsx",
      lineNumber: 35,
      columnNumber: 5
    },
    void 0
  );
};
const renderScore = (value2) => {
  if (Array.isArray(value2)) {
    return value2.join(" ");
  } else if (typeof value2 === "object") {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(MetaDataGrid, { entries: value2 }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEventView.tsx",
      lineNumber: 89,
      columnNumber: 12
    }, void 0);
  } else {
    return value2;
  }
};
const kUnchangedSentinel = "UNCHANGED";
const ScoreEditEventView = ({
  eventNode,
  className: className2
}) => {
  const event = eventNode.event;
  const subtitle2 = event.edit.provenance ? `[${formatDateTime(new Date(event.edit.provenance.timestamp))}] ${event.edit.provenance.author}: ${event.edit.provenance.reason || ""}` : void 0;
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    EventPanel,
    {
      eventNodeId: eventNode.id,
      depth: eventNode.depth,
      title: "Edit Score",
      className: clsx(className2, "text-size-small"),
      subTitle: subtitle2,
      collapsibleContent: true,
      icon: ApplicationIcons.edit,
      children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { "data-name": "Summary", children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "div",
          {
            className: clsx(
              "text-style-label",
              "text-style-secondary",
              styles$C.section
            ),
            children: "Updated Values"
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
            lineNumber: 45,
            columnNumber: 9
          },
          void 0
        ),
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$C.container), children: [
          event.edit.value ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(reactExports.Fragment, { children: [
            /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$C.separator) }, void 0, false, {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
              lineNumber: 57,
              columnNumber: 15
            }, void 0),
            /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "text-style-label", children: "Value" }, void 0, false, {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
              lineNumber: 58,
              columnNumber: 15
            }, void 0),
            /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: renderScore(event.edit.value) }, void 0, false, {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
              lineNumber: 59,
              columnNumber: 15
            }, void 0)
          ] }, void 0, true, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
            lineNumber: 56,
            columnNumber: 13
          }, void 0) : "",
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$C.separator) }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
            lineNumber: 65,
            columnNumber: 11
          }, void 0),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "text-style-label", children: "Answer" }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
            lineNumber: 66,
            columnNumber: 11
          }, void 0),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$C.wrappingContent), children: event.edit.answer === kUnchangedSentinel ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("pre", { className: clsx(styles$C.unchanged), children: "[unchanged]" }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
            lineNumber: 69,
            columnNumber: 15
          }, void 0) : /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(RenderedText, { markdown: event.edit.answer || "" }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
            lineNumber: 71,
            columnNumber: 15
          }, void 0) }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
            lineNumber: 67,
            columnNumber: 11
          }, void 0),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$C.separator) }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
            lineNumber: 75,
            columnNumber: 11
          }, void 0),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "text-style-label", children: "Explanation" }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
            lineNumber: 76,
            columnNumber: 11
          }, void 0),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$C.wrappingContent), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(RenderedText, { markdown: event.edit.explanation || "" }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
            lineNumber: 78,
            columnNumber: 13
          }, void 0) }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
            lineNumber: 77,
            columnNumber: 11
          }, void 0)
        ] }, void 0, true, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
          lineNumber: 54,
          columnNumber: 9
        }, void 0),
        event.edit.provenance ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$C.container), children: [
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            "div",
            {
              className: clsx(
                "text-style-label",
                "text-style-secondary",
                styles$C.section
              ),
              children: "Provenance"
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
              lineNumber: 84,
              columnNumber: 13
            },
            void 0
          ),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$C.spacer) }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
            lineNumber: 93,
            columnNumber: 13
          }, void 0),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$C.separator) }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
            lineNumber: 95,
            columnNumber: 13
          }, void 0),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "text-style-label", children: "Author" }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
            lineNumber: 96,
            columnNumber: 13
          }, void 0),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$C.wrappingContent), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(RenderedText, { markdown: event.edit.provenance.author }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
            lineNumber: 98,
            columnNumber: 15
          }, void 0) }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
            lineNumber: 97,
            columnNumber: 13
          }, void 0),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$C.separator) }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
            lineNumber: 101,
            columnNumber: 13
          }, void 0),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "text-style-label", children: "Reason" }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
            lineNumber: 102,
            columnNumber: 13
          }, void 0),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$C.wrappingContent), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(RenderedText, { markdown: event.edit.provenance.reason || "" }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
            lineNumber: 104,
            columnNumber: 15
          }, void 0) }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
            lineNumber: 103,
            columnNumber: 13
          }, void 0),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$C.separator) }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
            lineNumber: 107,
            columnNumber: 13
          }, void 0),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "text-style-label", children: "Time" }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
            lineNumber: 108,
            columnNumber: 13
          }, void 0),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$C.wrappingContent), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            RenderedText,
            {
              markdown: formatDateTime(new Date(event.edit.provenance.timestamp)) || ""
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
              lineNumber: 110,
              columnNumber: 15
            },
            void 0
          ) }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
            lineNumber: 109,
            columnNumber: 13
          }, void 0)
        ] }, void 0, true, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
          lineNumber: 83,
          columnNumber: 11
        }, void 0) : "",
        event.edit.metadata && event.edit.metadata !== kUnchangedSentinel ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { "data-name": "Metadata", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          RecordTree,
          {
            id: `${eventNode.id}-score-metadata`,
            record: event.edit.metadata || {},
            className: styles$C.metadataTree,
            defaultExpandLevel: 0
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
            lineNumber: 124,
            columnNumber: 13
          },
          void 0
        ) }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
          lineNumber: 123,
          columnNumber: 11
        }, void 0) : void 0
      ] }, void 0, true, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
        lineNumber: 44,
        columnNumber: 7
      }, void 0)
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ScoreEditEventView.tsx",
      lineNumber: 35,
      columnNumber: 5
    },
    void 0
  );
};
const kSandboxSignalName = "53787D8A-D3FC-426D-B383-9F880B70E4AA";
const fixupEventStream = (events, filterPending = true) => {
  const collapsed = processPendingEvents(events, filterPending);
  const fixedUp = collapseSampleInit(collapsed);
  return groupSandboxEvents(fixedUp);
};
const processPendingEvents = (events, filter2) => {
  return filter2 ? events.filter((e) => !e.pending) : events.reduce((acc, event) => {
    if (!event.pending) {
      acc.push(event);
    } else {
      const lastIndex = acc.length - 1;
      if (lastIndex >= 0 && acc[lastIndex]?.pending && acc[lastIndex]?.event === event.event) {
        acc[lastIndex] = event;
      } else {
        acc.push(event);
      }
    }
    return acc;
  }, []);
};
const collapseSampleInit = (events) => {
  const hasSpans2 = events.some((e) => {
    return e.event === "span_begin" || e.event === "span_end";
  });
  if (hasSpans2) {
    return events;
  }
  const hasInitStep = events.findIndex((e) => {
    return e.event === "step" && e.name === "init";
  }) !== -1;
  if (hasInitStep) {
    return events;
  }
  const initEventIndex = events.findIndex((e) => {
    return e.event === "sample_init";
  });
  const initEvent = events[initEventIndex];
  if (!initEvent) {
    return events;
  }
  const fixedUp = [...events];
  fixedUp.splice(initEventIndex, 0, {
    timestamp: initEvent.timestamp,
    event: "step",
    action: "begin",
    type: null,
    name: "sample_init",
    pending: false,
    working_start: 0,
    span_id: initEvent.span_id,
    uuid: null,
    metadata: null
  });
  fixedUp.splice(initEventIndex + 2, 0, {
    timestamp: initEvent.timestamp,
    event: "step",
    action: "end",
    type: null,
    name: "sample_init",
    pending: false,
    working_start: 0,
    span_id: initEvent.span_id,
    uuid: null,
    metadata: null
  });
  return fixedUp;
};
const groupSandboxEvents = (events) => {
  const result2 = [];
  const pendingSandboxEvents = [];
  const useSpans = hasSpans(events);
  const pushPendingSandboxEvents = () => {
    const timestamp2 = pendingSandboxEvents[pendingSandboxEvents.length - 1]?.timestamp || "";
    if (useSpans) {
      result2.push(createSpanBegin(kSandboxSignalName, timestamp2, null));
    } else {
      result2.push(createStepEvent(kSandboxSignalName, timestamp2, "begin"));
    }
    result2.push(...pendingSandboxEvents);
    if (useSpans) {
      result2.push(createSpanEnd(kSandboxSignalName, timestamp2));
    } else {
      result2.push(createStepEvent(kSandboxSignalName, timestamp2, "end"));
    }
    pendingSandboxEvents.length = 0;
  };
  for (const event of events) {
    if (event.event === "sandbox") {
      pendingSandboxEvents.push(event);
      continue;
    }
    if (pendingSandboxEvents.length > 0) {
      pushPendingSandboxEvents();
    }
    result2.push(event);
  }
  if (pendingSandboxEvents.length > 0) {
    pushPendingSandboxEvents();
  }
  return result2;
};
const createStepEvent = (name2, timestamp2, action) => ({
  timestamp: timestamp2,
  event: "step",
  action,
  type: null,
  name: name2,
  pending: false,
  working_start: 0,
  span_id: null,
  uuid: null,
  metadata: null
});
const createSpanBegin = (name2, timestamp2, parent_id) => {
  return {
    name: name2,
    id: `${name2}-begin`,
    span_id: name2,
    parent_id,
    timestamp: timestamp2,
    event: "span_begin",
    type: null,
    pending: false,
    working_start: 0,
    uuid: null,
    metadata: null
  };
};
const createSpanEnd = (name2, timestamp2) => {
  return {
    id: `${name2}-end`,
    timestamp: timestamp2,
    event: "span_end",
    pending: false,
    working_start: 0,
    span_id: name2,
    uuid: null,
    metadata: null
  };
};
const SpanEventView = ({
  eventNode,
  children: children2,
  className: className2
}) => {
  const event = eventNode.event;
  const descriptor = spanDescriptor(event);
  const title2 = descriptor.name || `${event.type ? event.type + ": " : "Step: "}${event.name}`;
  const text2 = reactExports.useMemo(() => summarize$1(children2), [children2]);
  const childIds = reactExports.useMemo(() => children2.map((child) => child.id), [children2]);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    EventPanel,
    {
      eventNodeId: eventNode.id,
      depth: eventNode.depth,
      childIds,
      className: clsx("transcript-span", className2),
      title: title2,
      subTitle: formatDateTime(new Date(event.timestamp)),
      text: text2,
      icon: descriptor.icon
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SpanEventView.tsx",
      lineNumber: 35,
      columnNumber: 5
    },
    void 0
  );
};
const summarize$1 = (children2) => {
  if (children2.length === 0) {
    return "(no events)";
  }
  const formatEvent = (event, count2) => {
    if (count2 === 1) {
      return `${count2} ${event} event`;
    } else {
      return `${count2} ${event} events`;
    }
  };
  const typeCount = {};
  children2.forEach((child) => {
    const currentCount = typeCount[child.event.event] || 0;
    typeCount[child.event.event] = currentCount + 1;
  });
  const numberOfTypes = Object.keys(typeCount).length;
  if (numberOfTypes < 3) {
    return Object.keys(typeCount).map((key2) => {
      return formatEvent(key2, typeCount[key2] || 0);
    }).join(", ");
  }
  if (children2.length === 1) {
    return "1 event";
  } else {
    return `${children2.length} events`;
  }
};
const spanDescriptor = (event) => {
  const rootStepDescriptor = {
    endSpace: true
  };
  if (event.type === "solver") {
    switch (event.name) {
      case "chain_of_thought":
        return {
          ...rootStepDescriptor
        };
      case "generate":
        return {
          ...rootStepDescriptor
        };
      case "self_critique":
        return {
          ...rootStepDescriptor
        };
      case "system_message":
        return {
          ...rootStepDescriptor
        };
      case "use_tools":
        return {
          ...rootStepDescriptor
        };
      case "multiple_choice":
        return {
          ...rootStepDescriptor
        };
      default:
        return {
          ...rootStepDescriptor
        };
    }
  } else if (event.type === "scorer") {
    return {
      ...rootStepDescriptor
    };
  } else if (event.event === "span_begin") {
    if (event.span_id === kSandboxSignalName) {
      return {
        ...rootStepDescriptor,
        name: "Sandbox Events"
      };
    } else if (event.name === "init") {
      return {
        ...rootStepDescriptor,
        name: "Init"
      };
    } else {
      return {
        ...rootStepDescriptor
      };
    }
  } else {
    switch (event.name) {
      case "sample_init":
        return {
          ...rootStepDescriptor,
          name: "Sample Init"
        };
      default:
        return {
          endSpace: false
        };
    }
  }
};
function cloneRegExp(re2) {
  var _a2;
  const regexMatch = /^\/(.*)\/([gimyu]*)$/.exec(re2.toString());
  if (!regexMatch) {
    throw new Error("Invalid RegExp");
  }
  return new RegExp((_a2 = regexMatch[1]) !== null && _a2 !== void 0 ? _a2 : "", regexMatch[2]);
}
function clone(arg) {
  if (typeof arg !== "object") {
    return arg;
  }
  if (arg === null) {
    return null;
  }
  if (Array.isArray(arg)) {
    return arg.map(clone);
  }
  if (arg instanceof Date) {
    return new Date(arg.getTime());
  }
  if (arg instanceof RegExp) {
    return cloneRegExp(arg);
  }
  const cloned = {};
  for (const name2 in arg) {
    if (Object.prototype.hasOwnProperty.call(arg, name2)) {
      cloned[name2] = clone(arg[name2]);
    }
  }
  return cloned;
}
function assertNonEmptyArray(arr, message2) {
  if (arr.length === 0) {
    throw new Error("Expected a non-empty array");
  }
}
function assertArrayHasAtLeast2(arr, message2) {
  if (arr.length < 2) {
    throw new Error("Expected an array with at least 2 items");
  }
}
const lastNonEmpty = (arr) => arr[arr.length - 1];
class Context {
  setResult(result2) {
    this.result = result2;
    this.hasResult = true;
    return this;
  }
  exit() {
    this.exiting = true;
    return this;
  }
  push(child, name2) {
    child.parent = this;
    if (typeof name2 !== "undefined") {
      child.childName = name2;
    }
    child.root = this.root || this;
    child.options = child.options || this.options;
    if (!this.children) {
      this.children = [child];
      this.nextAfterChildren = this.next || null;
      this.next = child;
    } else {
      assertNonEmptyArray(this.children);
      lastNonEmpty(this.children).next = child;
      this.children.push(child);
    }
    child.next = this;
    return this;
  }
}
class DiffContext extends Context {
  constructor(left2, right2) {
    super();
    this.left = left2;
    this.right = right2;
    this.pipe = "diff";
  }
  prepareDeltaResult(result2) {
    var _a2, _b2, _c2, _d2;
    if (typeof result2 === "object") {
      if (((_a2 = this.options) === null || _a2 === void 0 ? void 0 : _a2.omitRemovedValues) && Array.isArray(result2) && result2.length > 1 && (result2.length === 2 || // modified
      result2[2] === 0 || // deleted
      result2[2] === 3)) {
        result2[0] = 0;
      }
      if ((_b2 = this.options) === null || _b2 === void 0 ? void 0 : _b2.cloneDiffValues) {
        const clone$1 = typeof ((_c2 = this.options) === null || _c2 === void 0 ? void 0 : _c2.cloneDiffValues) === "function" ? (_d2 = this.options) === null || _d2 === void 0 ? void 0 : _d2.cloneDiffValues : clone;
        if (typeof result2[0] === "object") {
          result2[0] = clone$1(result2[0]);
        }
        if (typeof result2[1] === "object") {
          result2[1] = clone$1(result2[1]);
        }
      }
    }
    return result2;
  }
  setResult(result2) {
    this.prepareDeltaResult(result2);
    return super.setResult(result2);
  }
}
class PatchContext extends Context {
  constructor(left2, delta) {
    super();
    this.left = left2;
    this.delta = delta;
    this.pipe = "patch";
  }
}
class ReverseContext extends Context {
  constructor(delta) {
    super();
    this.delta = delta;
    this.pipe = "reverse";
  }
}
class Pipe {
  constructor(name2) {
    this.name = name2;
    this.filters = [];
  }
  process(input2) {
    if (!this.processor) {
      throw new Error("add this pipe to a processor before using it");
    }
    const debug = this.debug;
    const length2 = this.filters.length;
    const context = input2;
    for (let index = 0; index < length2; index++) {
      const filter2 = this.filters[index];
      if (!filter2)
        continue;
      if (debug) {
        this.log(`filter: ${filter2.filterName}`);
      }
      filter2(context);
      if (typeof context === "object" && context.exiting) {
        context.exiting = false;
        break;
      }
    }
    if (!context.next && this.resultCheck) {
      this.resultCheck(context);
    }
  }
  log(msg) {
    console.log(`[jsondiffpatch] ${this.name} pipe, ${msg}`);
  }
  append(...args2) {
    this.filters.push(...args2);
    return this;
  }
  prepend(...args2) {
    this.filters.unshift(...args2);
    return this;
  }
  indexOf(filterName) {
    if (!filterName) {
      throw new Error("a filter name is required");
    }
    for (let index = 0; index < this.filters.length; index++) {
      const filter2 = this.filters[index];
      if ((filter2 === null || filter2 === void 0 ? void 0 : filter2.filterName) === filterName) {
        return index;
      }
    }
    throw new Error(`filter not found: ${filterName}`);
  }
  list() {
    return this.filters.map((f) => f.filterName);
  }
  after(filterName, ...params) {
    const index = this.indexOf(filterName);
    this.filters.splice(index + 1, 0, ...params);
    return this;
  }
  before(filterName, ...params) {
    const index = this.indexOf(filterName);
    this.filters.splice(index, 0, ...params);
    return this;
  }
  replace(filterName, ...params) {
    const index = this.indexOf(filterName);
    this.filters.splice(index, 1, ...params);
    return this;
  }
  remove(filterName) {
    const index = this.indexOf(filterName);
    this.filters.splice(index, 1);
    return this;
  }
  clear() {
    this.filters.length = 0;
    return this;
  }
  shouldHaveResult(should) {
    if (should === false) {
      this.resultCheck = null;
      return this;
    }
    if (this.resultCheck) {
      return this;
    }
    this.resultCheck = (context) => {
      if (!context.hasResult) {
        console.log(context);
        const error2 = new Error(`${this.name} failed`);
        error2.noResult = true;
        throw error2;
      }
    };
    return this;
  }
}
class Processor {
  constructor(options) {
    this.selfOptions = options || {};
    this.pipes = {};
  }
  options(options) {
    if (options) {
      this.selfOptions = options;
    }
    return this.selfOptions;
  }
  pipe(name2, pipeArg) {
    let pipe = pipeArg;
    if (typeof name2 === "string") {
      if (typeof pipe === "undefined") {
        return this.pipes[name2];
      }
      this.pipes[name2] = pipe;
    }
    if (name2 && name2.name) {
      pipe = name2;
      if (pipe.processor === this) {
        return pipe;
      }
      this.pipes[pipe.name] = pipe;
    }
    if (!pipe) {
      throw new Error(`pipe is not defined: ${name2}`);
    }
    pipe.processor = this;
    return pipe;
  }
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  process(input2, pipe) {
    let context = input2;
    context.options = this.options();
    let nextPipe = pipe || input2.pipe || "default";
    let lastPipe = void 0;
    while (nextPipe) {
      if (typeof context.nextAfterChildren !== "undefined") {
        context.next = context.nextAfterChildren;
        context.nextAfterChildren = null;
      }
      if (typeof nextPipe === "string") {
        nextPipe = this.pipe(nextPipe);
      }
      nextPipe.process(context);
      lastPipe = nextPipe;
      nextPipe = null;
      if (context) {
        if (context.next) {
          context = context.next;
          nextPipe = context.pipe || lastPipe;
        }
      }
    }
    return context.hasResult ? context.result : void 0;
  }
}
const defaultMatch = (array1, array2, index1, index2) => array1[index1] === array2[index2];
const lengthMatrix = (array1, array2, match3, context) => {
  var _a2, _b2, _c2;
  const len1 = array1.length;
  const len2 = array2.length;
  let x;
  let y;
  const matrix = new Array(len1 + 1);
  for (x = 0; x < len1 + 1; x++) {
    const matrixNewRow = new Array(len2 + 1);
    for (y = 0; y < len2 + 1; y++) {
      matrixNewRow[y] = 0;
    }
    matrix[x] = matrixNewRow;
  }
  matrix.match = match3;
  for (x = 1; x < len1 + 1; x++) {
    const matrixRowX = matrix[x];
    if (matrixRowX === void 0) {
      throw new Error("LCS matrix row is undefined");
    }
    const matrixRowBeforeX = matrix[x - 1];
    if (matrixRowBeforeX === void 0) {
      throw new Error("LCS matrix row is undefined");
    }
    for (y = 1; y < len2 + 1; y++) {
      if (match3(array1, array2, x - 1, y - 1, context)) {
        matrixRowX[y] = ((_a2 = matrixRowBeforeX[y - 1]) !== null && _a2 !== void 0 ? _a2 : 0) + 1;
      } else {
        matrixRowX[y] = Math.max((_b2 = matrixRowBeforeX[y]) !== null && _b2 !== void 0 ? _b2 : 0, (_c2 = matrixRowX[y - 1]) !== null && _c2 !== void 0 ? _c2 : 0);
      }
    }
  }
  return matrix;
};
const backtrack = (matrix, array1, array2, context) => {
  let index1 = array1.length;
  let index2 = array2.length;
  const subsequence = {
    sequence: [],
    indices1: [],
    indices2: []
  };
  while (index1 !== 0 && index2 !== 0) {
    if (matrix.match === void 0) {
      throw new Error("LCS matrix match function is undefined");
    }
    const sameLetter = matrix.match(array1, array2, index1 - 1, index2 - 1, context);
    if (sameLetter) {
      subsequence.sequence.unshift(array1[index1 - 1]);
      subsequence.indices1.unshift(index1 - 1);
      subsequence.indices2.unshift(index2 - 1);
      --index1;
      --index2;
    } else {
      const matrixRowIndex1 = matrix[index1];
      if (matrixRowIndex1 === void 0) {
        throw new Error("LCS matrix row is undefined");
      }
      const valueAtMatrixAbove = matrixRowIndex1[index2 - 1];
      if (valueAtMatrixAbove === void 0) {
        throw new Error("LCS matrix value is undefined");
      }
      const matrixRowBeforeIndex1 = matrix[index1 - 1];
      if (matrixRowBeforeIndex1 === void 0) {
        throw new Error("LCS matrix row is undefined");
      }
      const valueAtMatrixLeft = matrixRowBeforeIndex1[index2];
      if (valueAtMatrixLeft === void 0) {
        throw new Error("LCS matrix value is undefined");
      }
      if (valueAtMatrixAbove > valueAtMatrixLeft) {
        --index2;
      } else {
        --index1;
      }
    }
  }
  return subsequence;
};
const get = (array1, array2, match3, context) => {
  const innerContext = context || {};
  const matrix = lengthMatrix(array1, array2, match3 || defaultMatch, innerContext);
  return backtrack(matrix, array1, array2, innerContext);
};
const lcs = {
  get
};
const ARRAY_MOVE = 3;
function arraysHaveMatchByRef(array1, array2, len1, len2) {
  for (let index1 = 0; index1 < len1; index1++) {
    const val1 = array1[index1];
    for (let index2 = 0; index2 < len2; index2++) {
      const val2 = array2[index2];
      if (index1 !== index2 && val1 === val2) {
        return true;
      }
    }
  }
  return false;
}
function matchItems(array1, array2, index1, index2, context) {
  const value1 = array1[index1];
  const value2 = array2[index2];
  if (value1 === value2) {
    return true;
  }
  if (typeof value1 !== "object" || typeof value2 !== "object") {
    return false;
  }
  const objectHash = context.objectHash;
  if (!objectHash) {
    return context.matchByPosition && index1 === index2;
  }
  context.hashCache1 = context.hashCache1 || [];
  let hash1 = context.hashCache1[index1];
  if (typeof hash1 === "undefined") {
    context.hashCache1[index1] = hash1 = objectHash(value1, index1);
  }
  if (typeof hash1 === "undefined") {
    return false;
  }
  context.hashCache2 = context.hashCache2 || [];
  let hash2 = context.hashCache2[index2];
  if (typeof hash2 === "undefined") {
    context.hashCache2[index2] = hash2 = objectHash(value2, index2);
  }
  if (typeof hash2 === "undefined") {
    return false;
  }
  return hash1 === hash2;
}
const diffFilter$3 = function arraysDiffFilter(context) {
  var _a2, _b2, _c2, _d2, _e2;
  if (!context.leftIsArray) {
    return;
  }
  const matchContext = {
    objectHash: (_a2 = context.options) === null || _a2 === void 0 ? void 0 : _a2.objectHash,
    matchByPosition: (_b2 = context.options) === null || _b2 === void 0 ? void 0 : _b2.matchByPosition
  };
  let commonHead = 0;
  let commonTail = 0;
  let index;
  let index1;
  let index2;
  const array1 = context.left;
  const array2 = context.right;
  const len1 = array1.length;
  const len2 = array2.length;
  let child;
  if (len1 > 0 && len2 > 0 && !matchContext.objectHash && typeof matchContext.matchByPosition !== "boolean") {
    matchContext.matchByPosition = !arraysHaveMatchByRef(array1, array2, len1, len2);
  }
  while (commonHead < len1 && commonHead < len2 && matchItems(array1, array2, commonHead, commonHead, matchContext)) {
    index = commonHead;
    child = new DiffContext(array1[index], array2[index]);
    context.push(child, index);
    commonHead++;
  }
  while (commonTail + commonHead < len1 && commonTail + commonHead < len2 && matchItems(array1, array2, len1 - 1 - commonTail, len2 - 1 - commonTail, matchContext)) {
    index1 = len1 - 1 - commonTail;
    index2 = len2 - 1 - commonTail;
    child = new DiffContext(array1[index1], array2[index2]);
    context.push(child, index2);
    commonTail++;
  }
  let result2;
  if (commonHead + commonTail === len1) {
    if (len1 === len2) {
      context.setResult(void 0).exit();
      return;
    }
    result2 = result2 || {
      _t: "a"
    };
    for (index = commonHead; index < len2 - commonTail; index++) {
      result2[index] = [array2[index]];
      context.prepareDeltaResult(result2[index]);
    }
    context.setResult(result2).exit();
    return;
  }
  if (commonHead + commonTail === len2) {
    result2 = result2 || {
      _t: "a"
    };
    for (index = commonHead; index < len1 - commonTail; index++) {
      const key2 = `_${index}`;
      result2[key2] = [array1[index], 0, 0];
      context.prepareDeltaResult(result2[key2]);
    }
    context.setResult(result2).exit();
    return;
  }
  matchContext.hashCache1 = void 0;
  matchContext.hashCache2 = void 0;
  const trimmed1 = array1.slice(commonHead, len1 - commonTail);
  const trimmed2 = array2.slice(commonHead, len2 - commonTail);
  const seq = lcs.get(trimmed1, trimmed2, matchItems, matchContext);
  const removedItems = [];
  result2 = result2 || {
    _t: "a"
  };
  for (index = commonHead; index < len1 - commonTail; index++) {
    if (seq.indices1.indexOf(index - commonHead) < 0) {
      const key2 = `_${index}`;
      result2[key2] = [array1[index], 0, 0];
      context.prepareDeltaResult(result2[key2]);
      removedItems.push(index);
    }
  }
  let detectMove = true;
  if (((_c2 = context.options) === null || _c2 === void 0 ? void 0 : _c2.arrays) && context.options.arrays.detectMove === false) {
    detectMove = false;
  }
  let includeValueOnMove = false;
  if ((_e2 = (_d2 = context.options) === null || _d2 === void 0 ? void 0 : _d2.arrays) === null || _e2 === void 0 ? void 0 : _e2.includeValueOnMove) {
    includeValueOnMove = true;
  }
  const removedItemsLength = removedItems.length;
  for (index = commonHead; index < len2 - commonTail; index++) {
    const indexOnArray2 = seq.indices2.indexOf(index - commonHead);
    if (indexOnArray2 < 0) {
      let isMove = false;
      if (detectMove && removedItemsLength > 0) {
        for (let removeItemIndex1 = 0; removeItemIndex1 < removedItemsLength; removeItemIndex1++) {
          index1 = removedItems[removeItemIndex1];
          const resultItem = index1 === void 0 ? void 0 : result2[`_${index1}`];
          if (index1 !== void 0 && resultItem && matchItems(trimmed1, trimmed2, index1 - commonHead, index - commonHead, matchContext)) {
            resultItem.splice(1, 2, index, ARRAY_MOVE);
            resultItem.splice(1, 2, index, ARRAY_MOVE);
            if (!includeValueOnMove) {
              resultItem[0] = "";
            }
            index2 = index;
            child = new DiffContext(array1[index1], array2[index2]);
            context.push(child, index2);
            removedItems.splice(removeItemIndex1, 1);
            isMove = true;
            break;
          }
        }
      }
      if (!isMove) {
        result2[index] = [array2[index]];
        context.prepareDeltaResult(result2[index]);
      }
    } else {
      if (seq.indices1[indexOnArray2] === void 0) {
        throw new Error(`Invalid indexOnArray2: ${indexOnArray2}, seq.indices1: ${seq.indices1}`);
      }
      index1 = seq.indices1[indexOnArray2] + commonHead;
      if (seq.indices2[indexOnArray2] === void 0) {
        throw new Error(`Invalid indexOnArray2: ${indexOnArray2}, seq.indices2: ${seq.indices2}`);
      }
      index2 = seq.indices2[indexOnArray2] + commonHead;
      child = new DiffContext(array1[index1], array2[index2]);
      context.push(child, index2);
    }
  }
  context.setResult(result2).exit();
};
diffFilter$3.filterName = "arrays";
const compare = {
  numerically(a2, b) {
    return a2 - b;
  },
  numericallyBy(name2) {
    return (a2, b) => a2[name2] - b[name2];
  }
};
const patchFilter$3 = function nestedPatchFilter(context) {
  var _a2;
  if (!context.nested) {
    return;
  }
  const nestedDelta = context.delta;
  if (nestedDelta._t !== "a") {
    return;
  }
  let index;
  let index1;
  const delta = nestedDelta;
  const array2 = context.left;
  let toRemove = [];
  let toInsert = [];
  const toModify = [];
  for (index in delta) {
    if (index !== "_t") {
      if (index[0] === "_") {
        const removedOrMovedIndex = index;
        if (delta[removedOrMovedIndex] !== void 0 && (delta[removedOrMovedIndex][2] === 0 || delta[removedOrMovedIndex][2] === ARRAY_MOVE)) {
          toRemove.push(Number.parseInt(index.slice(1), 10));
        } else {
          throw new Error(`only removal or move can be applied at original array indices, invalid diff type: ${(_a2 = delta[removedOrMovedIndex]) === null || _a2 === void 0 ? void 0 : _a2[2]}`);
        }
      } else {
        const numberIndex = index;
        if (delta[numberIndex].length === 1) {
          toInsert.push({
            index: Number.parseInt(numberIndex, 10),
            value: delta[numberIndex][0]
          });
        } else {
          toModify.push({
            index: Number.parseInt(numberIndex, 10),
            delta: delta[numberIndex]
          });
        }
      }
    }
  }
  toRemove = toRemove.sort(compare.numerically);
  for (index = toRemove.length - 1; index >= 0; index--) {
    index1 = toRemove[index];
    if (index1 === void 0)
      continue;
    const indexDiff = delta[`_${index1}`];
    const removedValue = array2.splice(index1, 1)[0];
    if ((indexDiff === null || indexDiff === void 0 ? void 0 : indexDiff[2]) === ARRAY_MOVE) {
      toInsert.push({
        index: indexDiff[1],
        value: removedValue
      });
    }
  }
  toInsert = toInsert.sort(compare.numericallyBy("index"));
  const toInsertLength = toInsert.length;
  for (index = 0; index < toInsertLength; index++) {
    const insertion = toInsert[index];
    if (insertion === void 0)
      continue;
    array2.splice(insertion.index, 0, insertion.value);
  }
  const toModifyLength = toModify.length;
  if (toModifyLength > 0) {
    for (index = 0; index < toModifyLength; index++) {
      const modification = toModify[index];
      if (modification === void 0)
        continue;
      const child = new PatchContext(array2[modification.index], modification.delta);
      context.push(child, modification.index);
    }
  }
  if (!context.children) {
    context.setResult(array2).exit();
    return;
  }
  context.exit();
};
patchFilter$3.filterName = "arrays";
const collectChildrenPatchFilter$1 = function collectChildrenPatchFilter(context) {
  if (!context || !context.children) {
    return;
  }
  const deltaWithChildren = context.delta;
  if (deltaWithChildren._t !== "a") {
    return;
  }
  const array2 = context.left;
  const length2 = context.children.length;
  for (let index = 0; index < length2; index++) {
    const child = context.children[index];
    if (child === void 0)
      continue;
    const arrayIndex = child.childName;
    array2[arrayIndex] = child.result;
  }
  context.setResult(array2).exit();
};
collectChildrenPatchFilter$1.filterName = "arraysCollectChildren";
const reverseFilter$3 = function arraysReverseFilter(context) {
  if (!context.nested) {
    const nonNestedDelta = context.delta;
    if (nonNestedDelta[2] === ARRAY_MOVE) {
      const arrayMoveDelta = nonNestedDelta;
      context.newName = `_${arrayMoveDelta[1]}`;
      context.setResult([
        arrayMoveDelta[0],
        Number.parseInt(context.childName.substring(1), 10),
        ARRAY_MOVE
      ]).exit();
    }
    return;
  }
  const nestedDelta = context.delta;
  if (nestedDelta._t !== "a") {
    return;
  }
  const arrayDelta = nestedDelta;
  for (const name2 in arrayDelta) {
    if (name2 === "_t") {
      continue;
    }
    const child = new ReverseContext(arrayDelta[name2]);
    context.push(child, name2);
  }
  context.exit();
};
reverseFilter$3.filterName = "arrays";
const reverseArrayDeltaIndex = (delta, index, itemDelta) => {
  if (typeof index === "string" && index[0] === "_") {
    return Number.parseInt(index.substring(1), 10);
  }
  if (Array.isArray(itemDelta) && itemDelta[2] === 0) {
    return `_${index}`;
  }
  let reverseIndex = +index;
  for (const deltaIndex in delta) {
    const deltaItem = delta[deltaIndex];
    if (Array.isArray(deltaItem)) {
      if (deltaItem[2] === ARRAY_MOVE) {
        const moveFromIndex = Number.parseInt(deltaIndex.substring(1), 10);
        const moveToIndex = deltaItem[1];
        if (moveToIndex === +index) {
          return moveFromIndex;
        }
        if (moveFromIndex <= reverseIndex && moveToIndex > reverseIndex) {
          reverseIndex++;
        } else if (moveFromIndex >= reverseIndex && moveToIndex < reverseIndex) {
          reverseIndex--;
        }
      } else if (deltaItem[2] === 0) {
        const deleteIndex = Number.parseInt(deltaIndex.substring(1), 10);
        if (deleteIndex <= reverseIndex) {
          reverseIndex++;
        }
      } else if (deltaItem.length === 1 && Number.parseInt(deltaIndex, 10) <= reverseIndex) {
        reverseIndex--;
      }
    }
  }
  return reverseIndex;
};
const collectChildrenReverseFilter$1 = (context) => {
  if (!context || !context.children) {
    return;
  }
  const deltaWithChildren = context.delta;
  if (deltaWithChildren._t !== "a") {
    return;
  }
  const arrayDelta = deltaWithChildren;
  const length2 = context.children.length;
  const delta = {
    _t: "a"
  };
  for (let index = 0; index < length2; index++) {
    const child = context.children[index];
    if (child === void 0)
      continue;
    let name2 = child.newName;
    if (typeof name2 === "undefined") {
      if (child.childName === void 0) {
        throw new Error("child.childName is undefined");
      }
      name2 = reverseArrayDeltaIndex(arrayDelta, child.childName, child.result);
    }
    if (delta[name2] !== child.result) {
      delta[name2] = child.result;
    }
  }
  context.setResult(delta).exit();
};
collectChildrenReverseFilter$1.filterName = "arraysCollectChildren";
const diffFilter$2 = function datesDiffFilter(context) {
  if (context.left instanceof Date) {
    if (context.right instanceof Date) {
      if (context.left.getTime() !== context.right.getTime()) {
        context.setResult([context.left, context.right]);
      } else {
        context.setResult(void 0);
      }
    } else {
      context.setResult([context.left, context.right]);
    }
    context.exit();
  } else if (context.right instanceof Date) {
    context.setResult([context.left, context.right]).exit();
  }
};
diffFilter$2.filterName = "dates";
const collectChildrenDiffFilter = (context) => {
  if (!context || !context.children) {
    return;
  }
  const length2 = context.children.length;
  let result2 = context.result;
  for (let index = 0; index < length2; index++) {
    const child = context.children[index];
    if (child === void 0)
      continue;
    if (typeof child.result === "undefined") {
      continue;
    }
    result2 = result2 || {};
    if (child.childName === void 0) {
      throw new Error("diff child.childName is undefined");
    }
    result2[child.childName] = child.result;
  }
  if (result2 && context.leftIsArray) {
    result2._t = "a";
  }
  context.setResult(result2).exit();
};
collectChildrenDiffFilter.filterName = "collectChildren";
const objectsDiffFilter = (context) => {
  var _a2;
  if (context.leftIsArray || context.leftType !== "object") {
    return;
  }
  const left2 = context.left;
  const right2 = context.right;
  const propertyFilter = (_a2 = context.options) === null || _a2 === void 0 ? void 0 : _a2.propertyFilter;
  for (const name2 in left2) {
    if (!Object.prototype.hasOwnProperty.call(left2, name2)) {
      continue;
    }
    if (propertyFilter && !propertyFilter(name2, context)) {
      continue;
    }
    const child = new DiffContext(left2[name2], right2[name2]);
    context.push(child, name2);
  }
  for (const name2 in right2) {
    if (!Object.prototype.hasOwnProperty.call(right2, name2)) {
      continue;
    }
    if (propertyFilter && !propertyFilter(name2, context)) {
      continue;
    }
    if (typeof left2[name2] === "undefined") {
      const child = new DiffContext(void 0, right2[name2]);
      context.push(child, name2);
    }
  }
  if (!context.children || context.children.length === 0) {
    context.setResult(void 0).exit();
    return;
  }
  context.exit();
};
objectsDiffFilter.filterName = "objects";
const patchFilter$2 = function nestedPatchFilter2(context) {
  if (!context.nested) {
    return;
  }
  const nestedDelta = context.delta;
  if (nestedDelta._t) {
    return;
  }
  const objectDelta = nestedDelta;
  for (const name2 in objectDelta) {
    const child = new PatchContext(context.left[name2], objectDelta[name2]);
    context.push(child, name2);
  }
  context.exit();
};
patchFilter$2.filterName = "objects";
const collectChildrenPatchFilter2 = function collectChildrenPatchFilter3(context) {
  if (!context || !context.children) {
    return;
  }
  const deltaWithChildren = context.delta;
  if (deltaWithChildren._t) {
    return;
  }
  const object2 = context.left;
  const length2 = context.children.length;
  for (let index = 0; index < length2; index++) {
    const child = context.children[index];
    if (child === void 0)
      continue;
    const property = child.childName;
    if (Object.prototype.hasOwnProperty.call(context.left, property) && child.result === void 0) {
      delete object2[property];
    } else if (object2[property] !== child.result) {
      object2[property] = child.result;
    }
  }
  context.setResult(object2).exit();
};
collectChildrenPatchFilter2.filterName = "collectChildren";
const reverseFilter$2 = function nestedReverseFilter(context) {
  if (!context.nested) {
    return;
  }
  const nestedDelta = context.delta;
  if (nestedDelta._t) {
    return;
  }
  const objectDelta = context.delta;
  for (const name2 in objectDelta) {
    const child = new ReverseContext(objectDelta[name2]);
    context.push(child, name2);
  }
  context.exit();
};
reverseFilter$2.filterName = "objects";
const collectChildrenReverseFilter = (context) => {
  if (!context || !context.children) {
    return;
  }
  const deltaWithChildren = context.delta;
  if (deltaWithChildren._t) {
    return;
  }
  const length2 = context.children.length;
  const delta = {};
  for (let index = 0; index < length2; index++) {
    const child = context.children[index];
    if (child === void 0)
      continue;
    const property = child.childName;
    if (delta[property] !== child.result) {
      delta[property] = child.result;
    }
  }
  context.setResult(delta).exit();
};
collectChildrenReverseFilter.filterName = "collectChildren";
const TEXT_DIFF = 2;
const DEFAULT_MIN_LENGTH = 60;
let cachedDiffPatch = null;
function getDiffMatchPatch(options, required) {
  var _a2;
  if (!cachedDiffPatch) {
    let instance2;
    if ((_a2 = options === null || options === void 0 ? void 0 : options.textDiff) === null || _a2 === void 0 ? void 0 : _a2.diffMatchPatch) {
      instance2 = new options.textDiff.diffMatchPatch();
    } else {
      if (!required) {
        return null;
      }
      const error2 = new Error("The diff-match-patch library was not provided. Pass the library in through the options or use the `jsondiffpatch/with-text-diffs` entry-point.");
      error2.diff_match_patch_not_found = true;
      throw error2;
    }
    cachedDiffPatch = {
      diff: (txt1, txt2) => instance2.patch_toText(instance2.patch_make(txt1, txt2)),
      patch: (txt1, patch) => {
        const results = instance2.patch_apply(instance2.patch_fromText(patch), txt1);
        for (const resultOk of results[1]) {
          if (!resultOk) {
            const error2 = new Error("text patch failed");
            error2.textPatchFailed = true;
            throw error2;
          }
        }
        return results[0];
      }
    };
  }
  return cachedDiffPatch;
}
const diffFilter$1 = function textsDiffFilter(context) {
  var _a2, _b2;
  if (context.leftType !== "string") {
    return;
  }
  const left2 = context.left;
  const right2 = context.right;
  const minLength = ((_b2 = (_a2 = context.options) === null || _a2 === void 0 ? void 0 : _a2.textDiff) === null || _b2 === void 0 ? void 0 : _b2.minLength) || DEFAULT_MIN_LENGTH;
  if (left2.length < minLength || right2.length < minLength) {
    context.setResult([left2, right2]).exit();
    return;
  }
  const diffMatchPatch = getDiffMatchPatch(context.options);
  if (!diffMatchPatch) {
    context.setResult([left2, right2]).exit();
    return;
  }
  const diff2 = diffMatchPatch.diff;
  context.setResult([diff2(left2, right2), 0, TEXT_DIFF]).exit();
};
diffFilter$1.filterName = "texts";
const patchFilter$1 = function textsPatchFilter(context) {
  if (context.nested) {
    return;
  }
  const nonNestedDelta = context.delta;
  if (nonNestedDelta[2] !== TEXT_DIFF) {
    return;
  }
  const textDiffDelta = nonNestedDelta;
  const patch = getDiffMatchPatch(context.options, true).patch;
  context.setResult(patch(context.left, textDiffDelta[0])).exit();
};
patchFilter$1.filterName = "texts";
const textDeltaReverse = (delta) => {
  var _a2, _b2, _c2;
  const headerRegex = /^@@ +-(\d+),(\d+) +\+(\d+),(\d+) +@@$/;
  const lines = delta.split("\n");
  for (let i2 = 0; i2 < lines.length; i2++) {
    const line2 = lines[i2];
    if (line2 === void 0)
      continue;
    const lineStart = line2.slice(0, 1);
    if (lineStart === "@") {
      const header2 = headerRegex.exec(line2);
      if (header2 !== null) {
        const lineHeader = i2;
        lines[lineHeader] = `@@ -${header2[3]},${header2[4]} +${header2[1]},${header2[2]} @@`;
      }
    } else if (lineStart === "+") {
      lines[i2] = `-${(_a2 = lines[i2]) === null || _a2 === void 0 ? void 0 : _a2.slice(1)}`;
      if (((_b2 = lines[i2 - 1]) === null || _b2 === void 0 ? void 0 : _b2.slice(0, 1)) === "+") {
        const lineTmp = lines[i2];
        lines[i2] = lines[i2 - 1];
        lines[i2 - 1] = lineTmp;
      }
    } else if (lineStart === "-") {
      lines[i2] = `+${(_c2 = lines[i2]) === null || _c2 === void 0 ? void 0 : _c2.slice(1)}`;
    }
  }
  return lines.join("\n");
};
const reverseFilter$1 = function textsReverseFilter(context) {
  if (context.nested) {
    return;
  }
  const nonNestedDelta = context.delta;
  if (nonNestedDelta[2] !== TEXT_DIFF) {
    return;
  }
  const textDiffDelta = nonNestedDelta;
  context.setResult([textDeltaReverse(textDiffDelta[0]), 0, TEXT_DIFF]).exit();
};
reverseFilter$1.filterName = "texts";
const diffFilter = function trivialMatchesDiffFilter(context) {
  if (context.left === context.right) {
    context.setResult(void 0).exit();
    return;
  }
  if (typeof context.left === "undefined") {
    if (typeof context.right === "function") {
      throw new Error("functions are not supported");
    }
    context.setResult([context.right]).exit();
    return;
  }
  if (typeof context.right === "undefined") {
    context.setResult([context.left, 0, 0]).exit();
    return;
  }
  if (typeof context.left === "function" || typeof context.right === "function") {
    throw new Error("functions are not supported");
  }
  context.leftType = context.left === null ? "null" : typeof context.left;
  context.rightType = context.right === null ? "null" : typeof context.right;
  if (context.leftType !== context.rightType) {
    context.setResult([context.left, context.right]).exit();
    return;
  }
  if (context.leftType === "boolean" || context.leftType === "number") {
    context.setResult([context.left, context.right]).exit();
    return;
  }
  if (context.leftType === "object") {
    context.leftIsArray = Array.isArray(context.left);
  }
  if (context.rightType === "object") {
    context.rightIsArray = Array.isArray(context.right);
  }
  if (context.leftIsArray !== context.rightIsArray) {
    context.setResult([context.left, context.right]).exit();
    return;
  }
  if (context.left instanceof RegExp) {
    if (context.right instanceof RegExp) {
      context.setResult([context.left.toString(), context.right.toString()]).exit();
    } else {
      context.setResult([context.left, context.right]).exit();
    }
  }
};
diffFilter.filterName = "trivial";
const patchFilter = function trivialMatchesPatchFilter(context) {
  if (typeof context.delta === "undefined") {
    context.setResult(context.left).exit();
    return;
  }
  context.nested = !Array.isArray(context.delta);
  if (context.nested) {
    return;
  }
  const nonNestedDelta = context.delta;
  if (nonNestedDelta.length === 1) {
    context.setResult(nonNestedDelta[0]).exit();
    return;
  }
  if (nonNestedDelta.length === 2) {
    if (context.left instanceof RegExp) {
      const regexArgs = /^\/(.*)\/([gimyu]+)$/.exec(nonNestedDelta[1]);
      if (regexArgs === null || regexArgs === void 0 ? void 0 : regexArgs[1]) {
        context.setResult(new RegExp(regexArgs[1], regexArgs[2])).exit();
        return;
      }
    }
    context.setResult(nonNestedDelta[1]).exit();
    return;
  }
  if (nonNestedDelta.length === 3 && nonNestedDelta[2] === 0) {
    context.setResult(void 0).exit();
  }
};
patchFilter.filterName = "trivial";
const reverseFilter = function trivialReferseFilter(context) {
  if (typeof context.delta === "undefined") {
    context.setResult(context.delta).exit();
    return;
  }
  context.nested = !Array.isArray(context.delta);
  if (context.nested) {
    return;
  }
  const nonNestedDelta = context.delta;
  if (nonNestedDelta.length === 1) {
    context.setResult([nonNestedDelta[0], 0, 0]).exit();
    return;
  }
  if (nonNestedDelta.length === 2) {
    context.setResult([nonNestedDelta[1], nonNestedDelta[0]]).exit();
    return;
  }
  if (nonNestedDelta.length === 3 && nonNestedDelta[2] === 0) {
    context.setResult([nonNestedDelta[0]]).exit();
  }
};
reverseFilter.filterName = "trivial";
class DiffPatcher {
  constructor(options) {
    this.processor = new Processor(options);
    this.processor.pipe(new Pipe("diff").append(collectChildrenDiffFilter, diffFilter, diffFilter$2, diffFilter$1, objectsDiffFilter, diffFilter$3).shouldHaveResult());
    this.processor.pipe(new Pipe("patch").append(collectChildrenPatchFilter2, collectChildrenPatchFilter$1, patchFilter, patchFilter$1, patchFilter$2, patchFilter$3).shouldHaveResult());
    this.processor.pipe(new Pipe("reverse").append(collectChildrenReverseFilter, collectChildrenReverseFilter$1, reverseFilter, reverseFilter$1, reverseFilter$2, reverseFilter$3).shouldHaveResult());
  }
  options(options) {
    return this.processor.options(options);
  }
  diff(left2, right2) {
    return this.processor.process(new DiffContext(left2, right2));
  }
  patch(left2, delta) {
    return this.processor.process(new PatchContext(left2, delta));
  }
  reverse(delta) {
    return this.processor.process(new ReverseContext(delta));
  }
  unpatch(right2, delta) {
    return this.patch(right2, this.reverse(delta));
  }
  clone(value2) {
    return clone(value2);
  }
}
let defaultInstance$1;
function diff$1(left2, right2) {
  if (!defaultInstance$1) {
    defaultInstance$1 = new DiffPatcher();
  }
  return defaultInstance$1.diff(left2, right2);
}
class BaseFormatter {
  format(delta, left2) {
    const context = {};
    this.prepareContext(context);
    const preparedContext = context;
    this.recurse(preparedContext, delta, left2);
    return this.finalize(preparedContext);
  }
  prepareContext(context) {
    context.buffer = [];
    context.out = function(...args2) {
      if (!this.buffer) {
        throw new Error("context buffer is not initialized");
      }
      this.buffer.push(...args2);
    };
  }
  typeFormattterNotFound(_context, deltaType) {
    throw new Error(`cannot format delta type: ${deltaType}`);
  }
  /* eslint-disable @typescript-eslint/no-unused-vars */
  typeFormattterErrorFormatter(_context, _err, _delta, _leftValue, _key, _leftKey, _movedFrom) {
  }
  /* eslint-enable @typescript-eslint/no-unused-vars */
  finalize({ buffer: buffer2 }) {
    if (Array.isArray(buffer2)) {
      return buffer2.join("");
    }
    return "";
  }
  recurse(context, delta, left2, key2, leftKey, movedFrom, isLast) {
    const useMoveOriginHere = delta && movedFrom;
    const leftValue = useMoveOriginHere ? movedFrom.value : left2;
    if (typeof delta === "undefined" && typeof key2 === "undefined") {
      return void 0;
    }
    const type = this.getDeltaType(delta, movedFrom);
    const nodeType = type === "node" ? delta._t === "a" ? "array" : "object" : "";
    if (typeof key2 !== "undefined") {
      this.nodeBegin(context, key2, leftKey, type, nodeType, isLast !== null && isLast !== void 0 ? isLast : false);
    } else {
      this.rootBegin(context, type, nodeType);
    }
    let typeFormattter;
    try {
      typeFormattter = type !== "unknown" ? this[`format_${type}`] : this.typeFormattterNotFound(context, type);
      typeFormattter.call(this, context, delta, leftValue, key2, leftKey, movedFrom);
    } catch (err) {
      this.typeFormattterErrorFormatter(context, err, delta, leftValue, key2, leftKey, movedFrom);
      if (typeof console !== "undefined" && console.error) {
        console.error(err.stack);
      }
    }
    if (typeof key2 !== "undefined") {
      this.nodeEnd(context, key2, leftKey, type, nodeType, isLast !== null && isLast !== void 0 ? isLast : false);
    } else {
      this.rootEnd(context, type, nodeType);
    }
  }
  formatDeltaChildren(context, delta, left2) {
    this.forEachDeltaKey(delta, left2, (key2, leftKey, movedFrom, isLast) => {
      this.recurse(context, delta[key2], left2 ? left2[leftKey] : void 0, key2, leftKey, movedFrom, isLast);
    });
  }
  forEachDeltaKey(delta, left2, fn3) {
    const keys2 = [];
    const arrayKeys = delta._t === "a";
    if (!arrayKeys) {
      const deltaKeys = Object.keys(delta);
      if (typeof left2 === "object" && left2 !== null) {
        keys2.push(...Object.keys(left2));
      }
      for (const key2 of deltaKeys) {
        if (keys2.indexOf(key2) >= 0)
          continue;
        keys2.push(key2);
      }
      for (let index = 0; index < keys2.length; index++) {
        const key2 = keys2[index];
        if (key2 === void 0)
          continue;
        const isLast = index === keys2.length - 1;
        fn3(
          // for object diff, the delta key and left key are the same
          key2,
          key2,
          // there's no "move" in object diff
          void 0,
          isLast
        );
      }
      return;
    }
    const movedFrom = {};
    for (const key2 in delta) {
      if (Object.prototype.hasOwnProperty.call(delta, key2)) {
        const value2 = delta[key2];
        if (Array.isArray(value2) && value2[2] === 3) {
          const movedDelta = value2;
          movedFrom[movedDelta[1]] = Number.parseInt(key2.substring(1));
        }
      }
    }
    const arrayDelta = delta;
    let leftIndex = 0;
    let rightIndex = 0;
    const leftArray = Array.isArray(left2) ? left2 : void 0;
    const leftLength = leftArray ? leftArray.length : (
      // if we don't have the original array,
      // use a length that ensures we'll go thru all delta keys
      Object.keys(arrayDelta).reduce((max2, key2) => {
        if (key2 === "_t")
          return max2;
        const isLeftKey = key2.substring(0, 1) === "_";
        if (isLeftKey) {
          const itemDelta = arrayDelta[key2];
          const leftIndex3 = Number.parseInt(key2.substring(1));
          const rightIndex3 = Array.isArray(itemDelta) && itemDelta.length >= 3 && itemDelta[2] === 3 ? itemDelta[1] : void 0;
          const maxIndex2 = Math.max(leftIndex3, rightIndex3 !== null && rightIndex3 !== void 0 ? rightIndex3 : 0);
          return maxIndex2 > max2 ? maxIndex2 : max2;
        }
        const rightIndex2 = Number.parseInt(key2);
        const leftIndex2 = movedFrom[rightIndex2];
        const maxIndex = Math.max(leftIndex2 !== null && leftIndex2 !== void 0 ? leftIndex2 : 0, rightIndex2 !== null && rightIndex2 !== void 0 ? rightIndex2 : 0);
        return maxIndex > max2 ? maxIndex : max2;
      }, 0) + 1
    );
    let rightLength = leftLength;
    let previousFnArgs;
    const addKey = (...args2) => {
      if (previousFnArgs) {
        fn3(...previousFnArgs);
      }
      previousFnArgs = args2;
    };
    const flushLastKey = () => {
      if (!previousFnArgs) {
        return;
      }
      fn3(previousFnArgs[0], previousFnArgs[1], previousFnArgs[2], true);
    };
    while (leftIndex < leftLength || rightIndex < rightLength || `${rightIndex}` in arrayDelta) {
      let hasDelta = false;
      const leftIndexKey = `_${leftIndex}`;
      const rightIndexKey = `${rightIndex}`;
      const movedFromIndex = rightIndex in movedFrom ? movedFrom[rightIndex] : void 0;
      if (leftIndexKey in arrayDelta) {
        hasDelta = true;
        const itemDelta = arrayDelta[leftIndexKey];
        addKey(leftIndexKey, movedFromIndex !== null && movedFromIndex !== void 0 ? movedFromIndex : leftIndex, movedFromIndex ? {
          key: `_${movedFromIndex}`,
          value: leftArray ? leftArray[movedFromIndex] : void 0
        } : void 0, false);
        if (Array.isArray(itemDelta)) {
          if (itemDelta[2] === 0) {
            rightLength--;
            leftIndex++;
          } else if (itemDelta[2] === 3) {
            leftIndex++;
          } else {
            leftIndex++;
          }
        } else {
          leftIndex++;
        }
      }
      if (rightIndexKey in arrayDelta) {
        hasDelta = true;
        const itemDelta = arrayDelta[rightIndexKey];
        const isItemAdded = Array.isArray(itemDelta) && itemDelta.length === 1;
        addKey(rightIndexKey, movedFromIndex !== null && movedFromIndex !== void 0 ? movedFromIndex : leftIndex, movedFromIndex ? {
          key: `_${movedFromIndex}`,
          value: leftArray ? leftArray[movedFromIndex] : void 0
        } : void 0, false);
        if (isItemAdded) {
          rightLength++;
          rightIndex++;
        } else if (movedFromIndex === void 0) {
          leftIndex++;
          rightIndex++;
        } else {
          rightIndex++;
        }
      }
      if (!hasDelta) {
        if (leftArray && movedFromIndex === void 0 || this.includeMoveDestinations !== false) {
          addKey(rightIndexKey, movedFromIndex !== null && movedFromIndex !== void 0 ? movedFromIndex : leftIndex, movedFromIndex ? {
            key: `_${movedFromIndex}`,
            value: leftArray ? leftArray[movedFromIndex] : void 0
          } : void 0, false);
        }
        if (movedFromIndex !== void 0) {
          rightIndex++;
        } else {
          leftIndex++;
          rightIndex++;
        }
      }
    }
    flushLastKey();
  }
  getDeltaType(delta, movedFrom) {
    if (typeof delta === "undefined") {
      if (typeof movedFrom !== "undefined") {
        return "movedestination";
      }
      return "unchanged";
    }
    if (Array.isArray(delta)) {
      if (delta.length === 1) {
        return "added";
      }
      if (delta.length === 2) {
        return "modified";
      }
      if (delta.length === 3 && delta[2] === 0) {
        return "deleted";
      }
      if (delta.length === 3 && delta[2] === 2) {
        return "textdiff";
      }
      if (delta.length === 3 && delta[2] === 3) {
        return "moved";
      }
    } else if (typeof delta === "object") {
      return "node";
    }
    return "unknown";
  }
  parseTextDiff(value2) {
    var _a2;
    const output2 = [];
    const lines = value2.split("\n@@ ");
    for (const line2 of lines) {
      const lineOutput = {
        pieces: []
      };
      const location = (_a2 = /^(?:@@ )?[-+]?(\d+),(\d+)/.exec(line2)) === null || _a2 === void 0 ? void 0 : _a2.slice(1);
      if (!location) {
        throw new Error("invalid text diff format");
      }
      assertArrayHasAtLeast2(location);
      lineOutput.location = {
        line: location[0],
        chr: location[1]
      };
      const pieces = line2.split("\n").slice(1);
      for (let pieceIndex = 0, piecesLength = pieces.length; pieceIndex < piecesLength; pieceIndex++) {
        const piece = pieces[pieceIndex];
        if (piece === void 0 || !piece.length) {
          continue;
        }
        const pieceOutput = {
          type: "context"
        };
        if (piece.substring(0, 1) === "+") {
          pieceOutput.type = "added";
        } else if (piece.substring(0, 1) === "-") {
          pieceOutput.type = "deleted";
        }
        pieceOutput.text = piece.slice(1);
        lineOutput.pieces.push(pieceOutput);
      }
      output2.push(lineOutput);
    }
    return output2;
  }
}
class HtmlFormatter extends BaseFormatter {
  typeFormattterErrorFormatter(context, err) {
    const message2 = typeof err === "object" && err !== null && "message" in err && typeof err.message === "string" ? err.message : String(err);
    context.out(`<pre class="jsondiffpatch-error">${htmlEscape(message2)}</pre>`);
  }
  formatValue(context, value2) {
    const valueAsHtml = typeof value2 === "undefined" ? "undefined" : htmlEscape(JSON.stringify(value2, null, 2));
    context.out(`<pre>${valueAsHtml}</pre>`);
  }
  formatTextDiffString(context, value2) {
    const lines = this.parseTextDiff(value2);
    context.out('<ul class="jsondiffpatch-textdiff">');
    for (let i2 = 0, l2 = lines.length; i2 < l2; i2++) {
      const line2 = lines[i2];
      if (line2 === void 0)
        return;
      context.out(`<li><div class="jsondiffpatch-textdiff-location"><span class="jsondiffpatch-textdiff-line-number">${line2.location.line}</span><span class="jsondiffpatch-textdiff-char">${line2.location.chr}</span></div><div class="jsondiffpatch-textdiff-line">`);
      const pieces = line2.pieces;
      for (let pieceIndex = 0, piecesLength = pieces.length; pieceIndex < piecesLength; pieceIndex++) {
        const piece = pieces[pieceIndex];
        if (piece === void 0)
          return;
        context.out(`<span class="jsondiffpatch-textdiff-${piece.type}">${htmlEscape(decodeURI(piece.text))}</span>`);
      }
      context.out("</div></li>");
    }
    context.out("</ul>");
  }
  rootBegin(context, type, nodeType) {
    const nodeClass = `jsondiffpatch-${type}${nodeType ? ` jsondiffpatch-child-node-type-${nodeType}` : ""}`;
    context.out(`<div class="jsondiffpatch-delta ${nodeClass}">`);
  }
  rootEnd(context) {
    context.out(`</div>${context.hasArrows ? `<script type="text/javascript">setTimeout(${adjustArrows.toString()},10);<\/script>` : ""}`);
  }
  nodeBegin(context, key2, leftKey, type, nodeType) {
    const nodeClass = `jsondiffpatch-${type}${nodeType ? ` jsondiffpatch-child-node-type-${nodeType}` : ""}`;
    const label2 = typeof leftKey === "number" && key2.substring(0, 1) === "_" ? key2.substring(1) : key2;
    context.out(`<li class="${nodeClass}" data-key="${htmlEscape(key2)}"><div class="jsondiffpatch-property-name">${htmlEscape(label2)}</div>`);
  }
  nodeEnd(context) {
    context.out("</li>");
  }
  format_unchanged(context, _delta, left2) {
    if (typeof left2 === "undefined") {
      return;
    }
    context.out('<div class="jsondiffpatch-value">');
    this.formatValue(context, left2);
    context.out("</div>");
  }
  format_movedestination(context, _delta, left2) {
    if (typeof left2 === "undefined") {
      return;
    }
    context.out('<div class="jsondiffpatch-value">');
    this.formatValue(context, left2);
    context.out("</div>");
  }
  format_node(context, delta, left2) {
    const nodeType = delta._t === "a" ? "array" : "object";
    context.out(`<ul class="jsondiffpatch-node jsondiffpatch-node-type-${nodeType}">`);
    this.formatDeltaChildren(context, delta, left2);
    context.out("</ul>");
  }
  format_added(context, delta) {
    context.out('<div class="jsondiffpatch-value">');
    this.formatValue(context, delta[0]);
    context.out("</div>");
  }
  format_modified(context, delta) {
    context.out('<div class="jsondiffpatch-value jsondiffpatch-left-value">');
    this.formatValue(context, delta[0]);
    context.out('</div><div class="jsondiffpatch-value jsondiffpatch-right-value">');
    this.formatValue(context, delta[1]);
    context.out("</div>");
  }
  format_deleted(context, delta) {
    context.out('<div class="jsondiffpatch-value">');
    this.formatValue(context, delta[0]);
    context.out("</div>");
  }
  format_moved(context, delta) {
    context.out('<div class="jsondiffpatch-value">');
    this.formatValue(context, delta[0]);
    context.out(`</div><div class="jsondiffpatch-moved-destination">${delta[1]}</div>`);
    context.out(
      /* jshint multistr: true */
      `<div class="jsondiffpatch-arrow" style="position: relative; left: -34px;">
          <svg width="30" height="60" style="position: absolute; display: none;">
          <defs>
              <marker id="markerArrow" markerWidth="8" markerHeight="8"
                 refx="2" refy="4" stroke="#88f"
                     orient="auto" markerUnits="userSpaceOnUse">
                  <path d="M1,1 L1,7 L7,4 L1,1" style="fill: #339;" />
              </marker>
          </defs>
          <path d="M30,0 Q-10,25 26,50"
            style="stroke: #88f; stroke-width: 2px; fill: none; stroke-opacity: 0.5; marker-end: url(#markerArrow);"
          ></path>
          </svg>
      </div>`
    );
    context.hasArrows = true;
  }
  format_textdiff(context, delta) {
    context.out('<div class="jsondiffpatch-value">');
    this.formatTextDiffString(context, delta[0]);
    context.out("</div>");
  }
}
function htmlEscape(value2) {
  if (typeof value2 === "number")
    return value2;
  let html = String(value2);
  const replacements = [
    [/&/g, "&amp;"],
    [/</g, "&lt;"],
    [/>/g, "&gt;"],
    [/'/g, "&apos;"],
    [/"/g, "&quot;"]
  ];
  for (const replacement of replacements) {
    html = html.replace(replacement[0], replacement[1]);
  }
  return html;
}
const adjustArrows = function jsondiffpatchHtmlFormatterAdjustArrows(nodeArg) {
  const node2 = nodeArg || document;
  const getElementText = ({ textContent, innerText }) => textContent || innerText;
  const eachByQuery = (el, query2, fn3) => {
    const elems = el.querySelectorAll(query2);
    for (let i2 = 0, l2 = elems.length; i2 < l2; i2++) {
      fn3(elems[i2]);
    }
  };
  const eachChildren = ({ children: children2 }, fn3) => {
    for (let i2 = 0, l2 = children2.length; i2 < l2; i2++) {
      const element = children2[i2];
      if (!element)
        continue;
      fn3(element, i2);
    }
  };
  eachByQuery(node2, ".jsondiffpatch-arrow", ({ parentNode, children: children2, style: style2 }) => {
    const arrowParent = parentNode;
    const svg = children2[0];
    const path = svg.children[1];
    svg.style.display = "none";
    const moveDestinationElem = arrowParent.querySelector(".jsondiffpatch-moved-destination");
    if (!(moveDestinationElem instanceof HTMLElement))
      return;
    const destination = getElementText(moveDestinationElem);
    const container2 = arrowParent.parentNode;
    if (!container2)
      return;
    let destinationElem;
    eachChildren(container2, (child) => {
      if (child.getAttribute("data-key") === destination) {
        destinationElem = child;
      }
    });
    if (!destinationElem) {
      return;
    }
    try {
      const distance = destinationElem.offsetTop - arrowParent.offsetTop;
      svg.setAttribute("height", `${Math.abs(distance) + 6}`);
      style2.top = `${-8 + (distance > 0 ? 0 : distance)}px`;
      const curve = distance > 0 ? `M30,0 Q-10,${Math.round(distance / 2)} 26,${distance - 4}` : `M30,${-distance} Q-10,${Math.round(-distance / 2)} 26,4`;
      path.setAttribute("d", curve);
      svg.style.display = "";
    } catch (err) {
      console.debug(`[jsondiffpatch] error adjusting arrows: ${err}`);
    }
  });
};
let defaultInstance;
function format(delta, left2) {
  if (!defaultInstance) {
    defaultInstance = new HtmlFormatter();
  }
  return defaultInstance.format(delta, left2);
}
const StateDiffView = ({
  before,
  after,
  className: className2
}) => {
  const state_diff = diff$1(sanitizeKeys(before), sanitizeKeys(after));
  const html_result = format(state_diff) || "Unable to render differences";
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "div",
    {
      dangerouslySetInnerHTML: { __html: unescapeNewlines(html_result) },
      className: clsx(className2)
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/state/StateDiffView.tsx",
      lineNumber: 25,
      columnNumber: 5
    },
    void 0
  );
};
function unescapeNewlines(obj) {
  if (typeof obj === "string") {
    return obj.replace(/\\n/g, "\n");
  }
  if (obj === null || typeof obj !== "object") {
    return obj;
  }
  if (Array.isArray(obj)) {
    return obj.map((item2) => unescapeNewlines(item2));
  }
  return Object.fromEntries(
    Object.entries(obj).map(([key2, value2]) => [
      key2,
      unescapeNewlines(value2)
    ])
  );
}
function sanitizeKeys(obj) {
  if (typeof obj !== "object" || obj === null) {
    return obj;
  }
  if (Array.isArray(obj)) {
    return obj.map((item2) => sanitizeKeys(item2));
  }
  return Object.fromEntries(
    Object.entries(obj).map(([key2, value2]) => [
      key2.replace(/</g, "&lt;").replace(/>/g, "&gt;"),
      sanitizeKeys(value2)
    ])
  );
}
function parseNpt(time2) {
  if (typeof time2 === "number") {
    return time2;
  } else if (typeof time2 === "string") {
    return time2.split(":").reverse().map(parseFloat).reduce((sum, n2, i2) => sum + n2 * Math.pow(60, i2));
  } else {
    return void 0;
  }
}
function debounce(f, delay) {
  let timeout;
  return function() {
    for (var _len = arguments.length, args2 = new Array(_len), _key = 0; _key < _len; _key++) {
      args2[_key] = arguments[_key];
    }
    clearTimeout(timeout);
    timeout = setTimeout(() => f.apply(this, args2), delay);
  };
}
function throttle(f, interval2) {
  let enableCall = true;
  return function() {
    if (!enableCall) return;
    enableCall = false;
    for (var _len2 = arguments.length, args2 = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
      args2[_key2] = arguments[_key2];
    }
    f.apply(this, args2);
    setTimeout(() => enableCall = true, interval2);
  };
}
class DummyLogger {
  log() {
  }
  debug() {
  }
  info() {
  }
  warn() {
  }
  error() {
  }
}
class PrefixedLogger {
  constructor(logger, prefix) {
    this.logger = logger;
    this.prefix = prefix;
  }
  log(message2) {
    for (var _len = arguments.length, args2 = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
      args2[_key - 1] = arguments[_key];
    }
    this.logger.log(`${this.prefix}${message2}`, ...args2);
  }
  debug(message2) {
    for (var _len2 = arguments.length, args2 = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
      args2[_key2 - 1] = arguments[_key2];
    }
    this.logger.debug(`${this.prefix}${message2}`, ...args2);
  }
  info(message2) {
    for (var _len3 = arguments.length, args2 = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
      args2[_key3 - 1] = arguments[_key3];
    }
    this.logger.info(`${this.prefix}${message2}`, ...args2);
  }
  warn(message2) {
    for (var _len4 = arguments.length, args2 = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
      args2[_key4 - 1] = arguments[_key4];
    }
    this.logger.warn(`${this.prefix}${message2}`, ...args2);
  }
  error(message2) {
    for (var _len5 = arguments.length, args2 = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {
      args2[_key5 - 1] = arguments[_key5];
    }
    this.logger.error(`${this.prefix}${message2}`, ...args2);
  }
}
let wasm;
const heap = new Array(128).fill(void 0);
heap.push(void 0, null, true, false);
function getObject(idx) {
  return heap[idx];
}
function debugString(val) {
  const type = typeof val;
  if (type == "number" || type == "boolean" || val == null) {
    return `${val}`;
  }
  if (type == "string") {
    return `"${val}"`;
  }
  if (type == "symbol") {
    const description2 = val.description;
    if (description2 == null) {
      return "Symbol";
    } else {
      return `Symbol(${description2})`;
    }
  }
  if (type == "function") {
    const name2 = val.name;
    if (typeof name2 == "string" && name2.length > 0) {
      return `Function(${name2})`;
    } else {
      return "Function";
    }
  }
  if (Array.isArray(val)) {
    const length2 = val.length;
    let debug = "[";
    if (length2 > 0) {
      debug += debugString(val[0]);
    }
    for (let i2 = 1; i2 < length2; i2++) {
      debug += ", " + debugString(val[i2]);
    }
    debug += "]";
    return debug;
  }
  const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val));
  let className2;
  if (builtInMatches.length > 1) {
    className2 = builtInMatches[1];
  } else {
    return toString.call(val);
  }
  if (className2 == "Object") {
    try {
      return "Object(" + JSON.stringify(val) + ")";
    } catch (_) {
      return "Object";
    }
  }
  if (val instanceof Error) {
    return `${val.name}: ${val.message}
${val.stack}`;
  }
  return className2;
}
let WASM_VECTOR_LEN = 0;
let cachedUint8Memory0 = null;
function getUint8Memory0() {
  if (cachedUint8Memory0 === null || cachedUint8Memory0.byteLength === 0) {
    cachedUint8Memory0 = new Uint8Array(wasm.memory.buffer);
  }
  return cachedUint8Memory0;
}
const cachedTextEncoder = typeof TextEncoder !== "undefined" ? new TextEncoder("utf-8") : {
  encode: () => {
    throw Error("TextEncoder not available");
  }
};
const encodeString = typeof cachedTextEncoder.encodeInto === "function" ? function(arg, view) {
  return cachedTextEncoder.encodeInto(arg, view);
} : function(arg, view) {
  const buf2 = cachedTextEncoder.encode(arg);
  view.set(buf2);
  return {
    read: arg.length,
    written: buf2.length
  };
};
function passStringToWasm0(arg, malloc, realloc) {
  if (realloc === void 0) {
    const buf2 = cachedTextEncoder.encode(arg);
    const ptr2 = malloc(buf2.length, 1) >>> 0;
    getUint8Memory0().subarray(ptr2, ptr2 + buf2.length).set(buf2);
    WASM_VECTOR_LEN = buf2.length;
    return ptr2;
  }
  let len = arg.length;
  let ptr = malloc(len, 1) >>> 0;
  const mem = getUint8Memory0();
  let offset3 = 0;
  for (; offset3 < len; offset3++) {
    const code2 = arg.charCodeAt(offset3);
    if (code2 > 127) break;
    mem[ptr + offset3] = code2;
  }
  if (offset3 !== len) {
    if (offset3 !== 0) {
      arg = arg.slice(offset3);
    }
    ptr = realloc(ptr, len, len = offset3 + arg.length * 3, 1) >>> 0;
    const view = getUint8Memory0().subarray(ptr + offset3, ptr + len);
    const ret = encodeString(arg, view);
    offset3 += ret.written;
    ptr = realloc(ptr, len, offset3, 1) >>> 0;
  }
  WASM_VECTOR_LEN = offset3;
  return ptr;
}
let cachedInt32Memory0 = null;
function getInt32Memory0() {
  if (cachedInt32Memory0 === null || cachedInt32Memory0.byteLength === 0) {
    cachedInt32Memory0 = new Int32Array(wasm.memory.buffer);
  }
  return cachedInt32Memory0;
}
let heap_next = heap.length;
function dropObject(idx) {
  if (idx < 132) return;
  heap[idx] = heap_next;
  heap_next = idx;
}
function takeObject(idx) {
  const ret = getObject(idx);
  dropObject(idx);
  return ret;
}
function addHeapObject(obj) {
  if (heap_next === heap.length) heap.push(heap.length + 1);
  const idx = heap_next;
  heap_next = heap[idx];
  heap[idx] = obj;
  return idx;
}
const cachedTextDecoder = typeof TextDecoder !== "undefined" ? new TextDecoder("utf-8", {
  ignoreBOM: true,
  fatal: true
}) : {
  decode: () => {
    throw Error("TextDecoder not available");
  }
};
if (typeof TextDecoder !== "undefined") {
  cachedTextDecoder.decode();
}
function getStringFromWasm0(ptr, len) {
  ptr = ptr >>> 0;
  return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len));
}
function create$1(cols, rows, scrollback_limit) {
  const ret = wasm.create(cols, rows, scrollback_limit);
  return Vt.__wrap(ret);
}
let cachedUint32Memory0 = null;
function getUint32Memory0() {
  if (cachedUint32Memory0 === null || cachedUint32Memory0.byteLength === 0) {
    cachedUint32Memory0 = new Uint32Array(wasm.memory.buffer);
  }
  return cachedUint32Memory0;
}
function getArrayU32FromWasm0(ptr, len) {
  ptr = ptr >>> 0;
  return getUint32Memory0().subarray(ptr / 4, ptr / 4 + len);
}
const VtFinalization = typeof FinalizationRegistry === "undefined" ? {
  register: () => {
  },
  unregister: () => {
  }
} : new FinalizationRegistry((ptr) => wasm.__wbg_vt_free(ptr >>> 0));
class Vt {
  static __wrap(ptr) {
    ptr = ptr >>> 0;
    const obj = Object.create(Vt.prototype);
    obj.__wbg_ptr = ptr;
    VtFinalization.register(obj, obj.__wbg_ptr, obj);
    return obj;
  }
  __destroy_into_raw() {
    const ptr = this.__wbg_ptr;
    this.__wbg_ptr = 0;
    VtFinalization.unregister(this);
    return ptr;
  }
  free() {
    const ptr = this.__destroy_into_raw();
    wasm.__wbg_vt_free(ptr);
  }
  /**
  * @param {string} s
  * @returns {any}
  */
  feed(s) {
    const ptr0 = passStringToWasm0(s, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
    const len0 = WASM_VECTOR_LEN;
    const ret = wasm.vt_feed(this.__wbg_ptr, ptr0, len0);
    return takeObject(ret);
  }
  /**
  * @param {number} cols
  * @param {number} rows
  * @returns {any}
  */
  resize(cols, rows) {
    const ret = wasm.vt_resize(this.__wbg_ptr, cols, rows);
    return takeObject(ret);
  }
  /**
  * @returns {Uint32Array}
  */
  getSize() {
    try {
      const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
      wasm.vt_getSize(retptr, this.__wbg_ptr);
      var r0 = getInt32Memory0()[retptr / 4 + 0];
      var r1 = getInt32Memory0()[retptr / 4 + 1];
      var v1 = getArrayU32FromWasm0(r0, r1).slice();
      wasm.__wbindgen_export_2(r0, r1 * 4, 4);
      return v1;
    } finally {
      wasm.__wbindgen_add_to_stack_pointer(16);
    }
  }
  /**
  * @param {number} n
  * @returns {any}
  */
  getLine(n2) {
    const ret = wasm.vt_getLine(this.__wbg_ptr, n2);
    return takeObject(ret);
  }
  /**
  * @returns {any}
  */
  getCursor() {
    const ret = wasm.vt_getCursor(this.__wbg_ptr);
    return takeObject(ret);
  }
}
async function __wbg_load(module, imports) {
  if (typeof Response === "function" && module instanceof Response) {
    if (typeof WebAssembly.instantiateStreaming === "function") {
      try {
        return await WebAssembly.instantiateStreaming(module, imports);
      } catch (e) {
        if (module.headers.get("Content-Type") != "application/wasm") {
          console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
        } else {
          throw e;
        }
      }
    }
    const bytes = await module.arrayBuffer();
    return await WebAssembly.instantiate(bytes, imports);
  } else {
    const instance2 = await WebAssembly.instantiate(module, imports);
    if (instance2 instanceof WebAssembly.Instance) {
      return {
        instance: instance2,
        module
      };
    } else {
      return instance2;
    }
  }
}
function __wbg_get_imports() {
  const imports = {};
  imports.wbg = {};
  imports.wbg.__wbindgen_is_string = function(arg0) {
    const ret = typeof getObject(arg0) === "string";
    return ret;
  };
  imports.wbg.__wbg_new_b525de17f44a8943 = function() {
    const ret = new Array();
    return addHeapObject(ret);
  };
  imports.wbg.__wbg_set_17224bc548dd1d7b = function(arg0, arg1, arg2) {
    getObject(arg0)[arg1 >>> 0] = takeObject(arg2);
  };
  imports.wbg.__wbindgen_debug_string = function(arg0, arg1) {
    const ret = debugString(getObject(arg1));
    const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_export_0, wasm.__wbindgen_export_1);
    const len1 = WASM_VECTOR_LEN;
    getInt32Memory0()[arg0 / 4 + 1] = len1;
    getInt32Memory0()[arg0 / 4 + 0] = ptr1;
  };
  imports.wbg.__wbindgen_object_drop_ref = function(arg0) {
    takeObject(arg0);
  };
  imports.wbg.__wbindgen_number_new = function(arg0) {
    const ret = arg0;
    return addHeapObject(ret);
  };
  imports.wbg.__wbindgen_bigint_from_u64 = function(arg0) {
    const ret = BigInt.asUintN(64, arg0);
    return addHeapObject(ret);
  };
  imports.wbg.__wbindgen_error_new = function(arg0, arg1) {
    const ret = new Error(getStringFromWasm0(arg0, arg1));
    return addHeapObject(ret);
  };
  imports.wbg.__wbg_new_f9876326328f45ed = function() {
    const ret = new Object();
    return addHeapObject(ret);
  };
  imports.wbg.__wbg_set_f975102236d3c502 = function(arg0, arg1, arg2) {
    getObject(arg0)[takeObject(arg1)] = takeObject(arg2);
  };
  imports.wbg.__wbg_new_f841cc6f2098f4b5 = function() {
    const ret = /* @__PURE__ */ new Map();
    return addHeapObject(ret);
  };
  imports.wbg.__wbg_set_388c4c6422704173 = function(arg0, arg1, arg2) {
    const ret = getObject(arg0).set(getObject(arg1), getObject(arg2));
    return addHeapObject(ret);
  };
  imports.wbg.__wbindgen_string_new = function(arg0, arg1) {
    const ret = getStringFromWasm0(arg0, arg1);
    return addHeapObject(ret);
  };
  imports.wbg.__wbindgen_object_clone_ref = function(arg0) {
    const ret = getObject(arg0);
    return addHeapObject(ret);
  };
  imports.wbg.__wbindgen_throw = function(arg0, arg1) {
    throw new Error(getStringFromWasm0(arg0, arg1));
  };
  return imports;
}
function __wbg_finalize_init(instance2, module) {
  wasm = instance2.exports;
  __wbg_init.__wbindgen_wasm_module = module;
  cachedInt32Memory0 = null;
  cachedUint32Memory0 = null;
  cachedUint8Memory0 = null;
  return wasm;
}
function initSync(module) {
  if (wasm !== void 0) return wasm;
  const imports = __wbg_get_imports();
  if (!(module instanceof WebAssembly.Module)) {
    module = new WebAssembly.Module(module);
  }
  const instance2 = new WebAssembly.Instance(module, imports);
  return __wbg_finalize_init(instance2, module);
}
async function __wbg_init(input2) {
  if (wasm !== void 0) return wasm;
  const imports = __wbg_get_imports();
  if (typeof input2 === "string" || typeof Request === "function" && input2 instanceof Request || typeof URL === "function" && input2 instanceof URL) {
    input2 = fetch(input2);
  }
  const {
    instance: instance2,
    module
  } = await __wbg_load(await input2, imports);
  return __wbg_finalize_init(instance2, module);
}
var exports = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  Vt,
  create: create$1,
  default: __wbg_init,
  initSync
});
const base64codes = [62, 0, 0, 0, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51];
function getBase64Code(charCode) {
  return base64codes[charCode - 43];
}
function base64_decode(str) {
  let missingOctets = str.endsWith("==") ? 2 : str.endsWith("=") ? 1 : 0;
  let n2 = str.length;
  let result2 = new Uint8Array(3 * (n2 / 4));
  let buffer2;
  for (let i2 = 0, j2 = 0; i2 < n2; i2 += 4, j2 += 3) {
    buffer2 = getBase64Code(str.charCodeAt(i2)) << 18 | getBase64Code(str.charCodeAt(i2 + 1)) << 12 | getBase64Code(str.charCodeAt(i2 + 2)) << 6 | getBase64Code(str.charCodeAt(i2 + 3));
    result2[j2] = buffer2 >> 16;
    result2[j2 + 1] = buffer2 >> 8 & 255;
    result2[j2 + 2] = buffer2 & 255;
  }
  return result2.subarray(0, result2.length - missingOctets);
}
const wasm_code = base64_decode(" ");
var loadVt = async (opt2 = {}) => {
  let { initializeHook } = opt2;
  if (initializeHook != null) {
    await initializeHook(__wbg_init, wasm_code);
  } else {
    await __wbg_init(wasm_code);
  }
  return exports;
};
class Clock {
  constructor() {
    let speed = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : 1;
    this.speed = speed;
    this.startTime = performance.now();
  }
  getTime() {
    return this.speed * (performance.now() - this.startTime) / 1e3;
  }
  setTime(time2) {
    this.startTime = performance.now() - time2 / this.speed * 1e3;
  }
}
class NullClock {
  constructor() {
  }
  getTime(_speed) {
  }
  setTime(_time) {
  }
}
class Stream {
  constructor(input2, xfs) {
    this.input = typeof input2.next === "function" ? input2 : input2[Symbol.iterator]();
    this.xfs = xfs ?? [];
  }
  map(f) {
    return this.transform(Map$1(f));
  }
  flatMap(f) {
    return this.transform(FlatMap(f));
  }
  filter(f) {
    return this.transform(Filter(f));
  }
  take(n2) {
    return this.transform(Take(n2));
  }
  drop(n2) {
    return this.transform(Drop(n2));
  }
  transform(f) {
    return new Stream(this.input, this.xfs.concat([f]));
  }
  multiplex(other, comparator) {
    return new Stream(new Multiplexer(this[Symbol.iterator](), other[Symbol.iterator](), comparator));
  }
  toArray() {
    return Array.from(this);
  }
  [Symbol.iterator]() {
    let v = 0;
    let values2 = [];
    let flushed = false;
    const xf = compose(this.xfs, (val) => values2.push(val));
    return {
      next: () => {
        if (v === values2.length) {
          values2 = [];
          v = 0;
        }
        while (values2.length === 0) {
          const next = this.input.next();
          if (next.done) {
            break;
          } else {
            xf.step(next.value);
          }
        }
        if (values2.length === 0 && !flushed) {
          xf.flush();
          flushed = true;
        }
        if (values2.length > 0) {
          return {
            done: false,
            value: values2[v++]
          };
        } else {
          return {
            done: true
          };
        }
      }
    };
  }
}
function Map$1(f) {
  return (emit) => {
    return (input2) => {
      emit(f(input2));
    };
  };
}
function FlatMap(f) {
  return (emit) => {
    return (input2) => {
      f(input2).forEach(emit);
    };
  };
}
function Filter(f) {
  return (emit) => {
    return (input2) => {
      if (f(input2)) {
        emit(input2);
      }
    };
  };
}
function Take(n2) {
  let c2 = 0;
  return (emit) => {
    return (input2) => {
      if (c2 < n2) {
        emit(input2);
      }
      c2 += 1;
    };
  };
}
function Drop(n2) {
  let c2 = 0;
  return (emit) => {
    return (input2) => {
      c2 += 1;
      if (c2 > n2) {
        emit(input2);
      }
    };
  };
}
function compose(xfs, push2) {
  return xfs.reverse().reduce((next, curr) => {
    const xf = toXf(curr(next.step));
    return {
      step: xf.step,
      flush: () => {
        xf.flush();
        next.flush();
      }
    };
  }, toXf(push2));
}
function toXf(xf) {
  if (typeof xf === "function") {
    return {
      step: xf,
      flush: () => {
      }
    };
  } else {
    return xf;
  }
}
class Multiplexer {
  constructor(left2, right2, comparator) {
    this.left = left2;
    this.right = right2;
    this.comparator = comparator;
  }
  [Symbol.iterator]() {
    let leftItem;
    let rightItem;
    return {
      next: () => {
        if (leftItem === void 0 && this.left !== void 0) {
          const result2 = this.left.next();
          if (result2.done) {
            this.left = void 0;
          } else {
            leftItem = result2.value;
          }
        }
        if (rightItem === void 0 && this.right !== void 0) {
          const result2 = this.right.next();
          if (result2.done) {
            this.right = void 0;
          } else {
            rightItem = result2.value;
          }
        }
        if (leftItem === void 0 && rightItem === void 0) {
          return {
            done: true
          };
        } else if (leftItem === void 0) {
          const value2 = rightItem;
          rightItem = void 0;
          return {
            done: false,
            value: value2
          };
        } else if (rightItem === void 0) {
          const value2 = leftItem;
          leftItem = void 0;
          return {
            done: false,
            value: value2
          };
        } else if (this.comparator(leftItem, rightItem)) {
          const value2 = leftItem;
          leftItem = void 0;
          return {
            done: false,
            value: value2
          };
        } else {
          const value2 = rightItem;
          rightItem = void 0;
          return {
            done: false,
            value: value2
          };
        }
      }
    };
  }
}
async function parse$2(data2) {
  if (data2 instanceof Response) {
    const text2 = await data2.text();
    const result2 = parseJsonl(text2);
    if (result2 !== void 0) {
      const {
        header: header2,
        events
      } = result2;
      if (header2.version === 2) {
        return parseAsciicastV2(header2, events);
      } else if (header2.version === 3) {
        return parseAsciicastV3(header2, events);
      } else {
        throw `asciicast v${header2.version} format not supported`;
      }
    } else {
      const header2 = JSON.parse(text2);
      if (header2.version === 1) {
        return parseAsciicastV1(header2);
      }
    }
  } else if (typeof data2 === "object" && data2.version === 1) {
    return parseAsciicastV1(data2);
  } else if (Array.isArray(data2)) {
    const header2 = data2[0];
    if (header2.version === 2) {
      const events = data2.slice(1, data2.length);
      return parseAsciicastV2(header2, events);
    } else if (header2.version === 3) {
      const events = data2.slice(1, data2.length);
      return parseAsciicastV3(header2, events);
    } else {
      throw `asciicast v${header2.version} format not supported`;
    }
  }
  throw "invalid data";
}
function parseJsonl(jsonl) {
  const lines = jsonl.split("\n");
  let header2;
  try {
    header2 = JSON.parse(lines[0]);
  } catch (_error2) {
    return;
  }
  const events = new Stream(lines).drop(1).filter((l2) => l2[0] === "[").map(JSON.parse);
  return {
    header: header2,
    events
  };
}
function parseAsciicastV1(data2) {
  let time2 = 0;
  const events = new Stream(data2.stdout).map((e) => {
    time2 += e[0];
    return [time2, "o", e[1]];
  });
  return {
    cols: data2.width,
    rows: data2.height,
    events
  };
}
function parseAsciicastV2(header2, events) {
  return {
    cols: header2.width,
    rows: header2.height,
    theme: parseTheme$1(header2.theme),
    events,
    idleTimeLimit: header2.idle_time_limit
  };
}
function parseAsciicastV3(header2, events) {
  if (!(events instanceof Stream)) {
    events = new Stream(events);
  }
  let time2 = 0;
  events = events.map((e) => {
    time2 += e[0];
    return [time2, e[1], e[2]];
  });
  return {
    cols: header2.term.cols,
    rows: header2.term.rows,
    theme: parseTheme$1(header2.term?.theme),
    events,
    idleTimeLimit: header2.idle_time_limit
  };
}
function parseTheme$1(theme) {
  if (theme === void 0) return;
  const colorRegex = /^#[0-9A-Fa-f]{6}$/;
  const paletteRegex = /^(#[0-9A-Fa-f]{6}:){7,}#[0-9A-Fa-f]{6}$/;
  const fg = theme?.fg;
  const bg = theme?.bg;
  const palette = theme?.palette;
  if (colorRegex.test(fg) && colorRegex.test(bg) && paletteRegex.test(palette)) {
    return {
      foreground: fg,
      background: bg,
      palette: palette.split(":")
    };
  }
}
function unparseAsciicastV2(recording2) {
  const header2 = JSON.stringify({
    version: 2,
    width: recording2.cols,
    height: recording2.rows
  });
  const events = recording2.events.map(JSON.stringify).join("\n");
  return `${header2}
${events}
`;
}
function recording(src, _ref, _ref2) {
  let {
    feed,
    resize: resize2,
    onInput,
    onMarker,
    setState: setState2,
    logger
  } = _ref;
  let {
    speed,
    idleTimeLimit,
    startAt,
    loop,
    posterTime,
    markers: markers_,
    pauseOnMarkers,
    cols: initialCols,
    rows: initialRows,
    audioUrl
  } = _ref2;
  let cols;
  let rows;
  let events;
  let markers;
  let duration2;
  let effectiveStartAt;
  let eventTimeoutId;
  let nextEventIndex = 0;
  let lastEventTime = 0;
  let startTime;
  let pauseElapsedTime;
  let playCount = 0;
  let waitingForAudio = false;
  let waitingTimeout;
  let shouldResumeOnAudioPlaying = false;
  let now2 = () => performance.now() * speed;
  let audioCtx;
  let audioElement;
  let audioSeekable = false;
  async function init() {
    const timeout = setTimeout(() => {
      setState2("loading");
    }, 3e3);
    try {
      let metadata2 = loadRecording(src, logger, {
        idleTimeLimit,
        startAt,
        markers_
      });
      const hasAudio = await loadAudio(audioUrl);
      metadata2 = await metadata2;
      return {
        ...metadata2,
        hasAudio
      };
    } finally {
      clearTimeout(timeout);
    }
  }
  async function loadRecording(src2, logger2, opts) {
    const {
      parser,
      minFrameTime,
      inputOffset,
      dumpFilename,
      encoding = "utf-8"
    } = src2;
    const data2 = await doFetch(src2);
    const recording2 = prepare(await parser(data2, {
      encoding
    }), logger2, {
      ...opts,
      minFrameTime,
      inputOffset
    });
    ({
      cols,
      rows,
      events,
      duration: duration2,
      effectiveStartAt
    } = recording2);
    initialCols = initialCols ?? cols;
    initialRows = initialRows ?? rows;
    if (events.length === 0) {
      throw "recording is missing events";
    }
    if (dumpFilename !== void 0) {
      dump(recording2, dumpFilename);
    }
    const poster = posterTime !== void 0 ? getPoster(posterTime) : void 0;
    markers = events.filter((e) => e[1] === "m").map((e) => [e[0], e[2].label]);
    return {
      cols,
      rows,
      duration: duration2,
      theme: recording2.theme,
      poster,
      markers
    };
  }
  async function loadAudio(audioUrl2) {
    if (!audioUrl2) return false;
    audioElement = await createAudioElement(audioUrl2);
    audioSeekable = audioElement.duration !== NaN && audioElement.duration !== Infinity && audioElement.seekable.length > 0 && audioElement.seekable.end(audioElement.seekable.length - 1) === audioElement.duration;
    if (audioSeekable) {
      audioElement.addEventListener("playing", onAudioPlaying);
      audioElement.addEventListener("waiting", onAudioWaiting);
    } else {
      logger.warn(`audio is not seekable - you must enable range request support on the server providing ${audioElement.src} for audio seeking to work`);
    }
    return true;
  }
  async function doFetch(_ref3) {
    let {
      url,
      data: data2,
      fetchOpts = {}
    } = _ref3;
    if (typeof url === "string") {
      return await doFetchOne(url, fetchOpts);
    } else if (Array.isArray(url)) {
      return await Promise.all(url.map((url2) => doFetchOne(url2, fetchOpts)));
    } else if (data2 !== void 0) {
      if (typeof data2 === "function") {
        data2 = data2();
      }
      if (!(data2 instanceof Promise)) {
        data2 = Promise.resolve(data2);
      }
      const value2 = await data2;
      if (typeof value2 === "string" || value2 instanceof ArrayBuffer) {
        return new Response(value2);
      } else {
        return value2;
      }
    } else {
      throw "failed fetching recording file: url/data missing in src";
    }
  }
  async function doFetchOne(url, fetchOpts) {
    const response = await fetch(url, fetchOpts);
    if (!response.ok) {
      throw `failed fetching recording from ${url}: ${response.status} ${response.statusText}`;
    }
    return response;
  }
  function scheduleNextEvent() {
    const nextEvent = events[nextEventIndex];
    if (nextEvent) {
      eventTimeoutId = scheduleAt(runNextEvent, nextEvent[0]);
    } else {
      onEnd();
    }
  }
  function scheduleAt(f, targetTime) {
    let timeout = (targetTime * 1e3 - (now2() - startTime)) / speed;
    if (timeout < 0) {
      timeout = 0;
    }
    return setTimeout(f, timeout);
  }
  function runNextEvent() {
    let event = events[nextEventIndex];
    let elapsedWallTime;
    do {
      lastEventTime = event[0];
      nextEventIndex++;
      const stop = executeEvent2(event);
      if (stop) {
        return;
      }
      event = events[nextEventIndex];
      elapsedWallTime = now2() - startTime;
    } while (event && elapsedWallTime > event[0] * 1e3);
    scheduleNextEvent();
  }
  function cancelNextEvent() {
    clearTimeout(eventTimeoutId);
    eventTimeoutId = null;
  }
  function executeEvent2(event) {
    const [time2, type, data2] = event;
    if (type === "o") {
      feed(data2);
    } else if (type === "i") {
      onInput(data2);
    } else if (type === "r") {
      const [cols2, rows2] = data2.split("x");
      resize2(cols2, rows2);
    } else if (type === "m") {
      onMarker(data2);
      if (pauseOnMarkers) {
        pause();
        pauseElapsedTime = time2 * 1e3;
        setState2("idle", {
          reason: "paused"
        });
        return true;
      }
    }
    return false;
  }
  function onEnd() {
    cancelNextEvent();
    playCount++;
    if (loop === true || typeof loop === "number" && playCount < loop) {
      nextEventIndex = 0;
      startTime = now2();
      feed("\x1Bc");
      resizeTerminalToInitialSize();
      scheduleNextEvent();
      if (audioElement) {
        audioElement.currentTime = 0;
      }
    } else {
      pauseElapsedTime = duration2 * 1e3;
      setState2("ended");
      if (audioElement) {
        audioElement.pause();
      }
    }
  }
  async function play() {
    if (eventTimeoutId) throw "already playing";
    if (events[nextEventIndex] === void 0) throw "already ended";
    if (effectiveStartAt !== null) {
      seek(effectiveStartAt);
    }
    await resume();
    return true;
  }
  function pause() {
    shouldResumeOnAudioPlaying = false;
    if (audioElement) {
      audioElement.pause();
    }
    if (!eventTimeoutId) return true;
    cancelNextEvent();
    pauseElapsedTime = now2() - startTime;
    return true;
  }
  async function resume() {
    if (audioElement && !audioCtx) setupAudioCtx();
    startTime = now2() - pauseElapsedTime;
    pauseElapsedTime = null;
    scheduleNextEvent();
    if (audioElement) {
      await audioElement.play();
    }
  }
  async function seek(where) {
    if (waitingForAudio) {
      return false;
    }
    const isPlaying = !!eventTimeoutId;
    pause();
    if (audioElement) {
      audioElement.pause();
    }
    const currentTime = (pauseElapsedTime ?? 0) / 1e3;
    if (typeof where === "string") {
      if (where === "<<") {
        where = currentTime - 5;
      } else if (where === ">>") {
        where = currentTime + 5;
      } else if (where === "<<<") {
        where = currentTime - 0.1 * duration2;
      } else if (where === ">>>") {
        where = currentTime + 0.1 * duration2;
      } else if (where[where.length - 1] === "%") {
        where = parseFloat(where.substring(0, where.length - 1)) / 100 * duration2;
      }
    } else if (typeof where === "object") {
      if (where.marker === "prev") {
        where = findMarkerTimeBefore(currentTime) ?? 0;
        if (isPlaying && currentTime - where < 1) {
          where = findMarkerTimeBefore(where) ?? 0;
        }
      } else if (where.marker === "next") {
        where = findMarkerTimeAfter(currentTime) ?? duration2;
      } else if (typeof where.marker === "number") {
        const marker = markers[where.marker];
        if (marker === void 0) {
          throw `invalid marker index: ${where.marker}`;
        } else {
          where = marker[0];
        }
      }
    }
    const targetTime = Math.min(Math.max(where, 0), duration2);
    if (targetTime * 1e3 === pauseElapsedTime) return false;
    if (targetTime < lastEventTime) {
      feed("\x1Bc");
      resizeTerminalToInitialSize();
      nextEventIndex = 0;
      lastEventTime = 0;
    }
    let event = events[nextEventIndex];
    while (event && event[0] <= targetTime) {
      if (event[1] === "o" || event[1] === "r") {
        executeEvent2(event);
      }
      lastEventTime = event[0];
      event = events[++nextEventIndex];
    }
    pauseElapsedTime = targetTime * 1e3;
    effectiveStartAt = null;
    if (audioElement && audioSeekable) {
      audioElement.currentTime = targetTime / speed;
    }
    if (isPlaying) {
      await resume();
    } else if (events[nextEventIndex] === void 0) {
      onEnd();
    }
    return true;
  }
  function findMarkerTimeBefore(time2) {
    if (markers.length == 0) return;
    let i2 = 0;
    let marker = markers[i2];
    let lastMarkerTimeBefore;
    while (marker && marker[0] < time2) {
      lastMarkerTimeBefore = marker[0];
      marker = markers[++i2];
    }
    return lastMarkerTimeBefore;
  }
  function findMarkerTimeAfter(time2) {
    if (markers.length == 0) return;
    let i2 = markers.length - 1;
    let marker = markers[i2];
    let firstMarkerTimeAfter;
    while (marker && marker[0] > time2) {
      firstMarkerTimeAfter = marker[0];
      marker = markers[--i2];
    }
    return firstMarkerTimeAfter;
  }
  function step(n2) {
    if (n2 === void 0) {
      n2 = 1;
    }
    let nextEvent;
    let targetIndex;
    if (n2 > 0) {
      let index = nextEventIndex;
      nextEvent = events[index];
      for (let i2 = 0; i2 < n2; i2++) {
        while (nextEvent !== void 0 && nextEvent[1] !== "o") {
          nextEvent = events[++index];
        }
        if (nextEvent !== void 0 && nextEvent[1] === "o") {
          targetIndex = index;
        }
      }
    } else {
      let index = Math.max(nextEventIndex - 2, 0);
      nextEvent = events[index];
      for (let i2 = n2; i2 < 0; i2++) {
        while (nextEvent !== void 0 && nextEvent[1] !== "o") {
          nextEvent = events[--index];
        }
        if (nextEvent !== void 0 && nextEvent[1] === "o") {
          targetIndex = index;
        }
      }
      if (targetIndex !== void 0) {
        feed("\x1Bc");
        resizeTerminalToInitialSize();
        nextEventIndex = 0;
      }
    }
    if (targetIndex === void 0) return;
    while (nextEventIndex <= targetIndex) {
      nextEvent = events[nextEventIndex++];
      if (nextEvent[1] === "o" || nextEvent[1] === "r") {
        executeEvent2(nextEvent);
      }
    }
    lastEventTime = nextEvent[0];
    pauseElapsedTime = lastEventTime * 1e3;
    effectiveStartAt = null;
    if (audioElement && audioSeekable) {
      audioElement.currentTime = lastEventTime / speed;
    }
    if (events[targetIndex + 1] === void 0) {
      onEnd();
    }
  }
  async function restart() {
    if (eventTimeoutId) throw "still playing";
    if (events[nextEventIndex] !== void 0) throw "not ended";
    seek(0);
    await resume();
    return true;
  }
  function getPoster(time2) {
    return events.filter((e) => e[0] < time2 && e[1] === "o").map((e) => e[2]);
  }
  function getCurrentTime() {
    if (eventTimeoutId) {
      return (now2() - startTime) / 1e3;
    } else {
      return (pauseElapsedTime ?? 0) / 1e3;
    }
  }
  function resizeTerminalToInitialSize() {
    resize2(initialCols, initialRows);
  }
  function setupAudioCtx() {
    audioCtx = new AudioContext({
      latencyHint: "interactive"
    });
    const src2 = audioCtx.createMediaElementSource(audioElement);
    src2.connect(audioCtx.destination);
    now2 = audioNow;
  }
  function audioNow() {
    if (!audioCtx) throw "audio context not started - can't tell time!";
    const {
      contextTime,
      performanceTime
    } = audioCtx.getOutputTimestamp();
    return performanceTime === 0 ? contextTime * 1e3 : contextTime * 1e3 + (performance.now() - performanceTime);
  }
  function onAudioWaiting() {
    logger.debug("audio buffering");
    waitingForAudio = true;
    shouldResumeOnAudioPlaying = !!eventTimeoutId;
    waitingTimeout = setTimeout(() => setState2("loading"), 1e3);
    if (!eventTimeoutId) return true;
    logger.debug("pausing session playback");
    cancelNextEvent();
    pauseElapsedTime = now2() - startTime;
  }
  function onAudioPlaying() {
    logger.debug("audio resumed");
    clearTimeout(waitingTimeout);
    setState2("playing");
    if (!waitingForAudio) return;
    waitingForAudio = false;
    if (shouldResumeOnAudioPlaying) {
      logger.debug("resuming session playback");
      startTime = now2() - pauseElapsedTime;
      pauseElapsedTime = null;
      scheduleNextEvent();
    }
  }
  function mute() {
    if (audioElement) {
      audioElement.muted = true;
      return true;
    }
  }
  function unmute() {
    if (audioElement) {
      audioElement.muted = false;
      return true;
    }
  }
  return {
    init,
    play,
    pause,
    seek,
    step,
    restart,
    stop: pause,
    mute,
    unmute,
    getCurrentTime
  };
}
function batcher(logger) {
  let minFrameTime = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 1 / 60;
  let prevEvent;
  return (emit) => {
    let ic = 0;
    let oc = 0;
    return {
      step: (event) => {
        ic++;
        if (prevEvent === void 0) {
          prevEvent = event;
          return;
        }
        if (event[1] === "o" && prevEvent[1] === "o" && event[0] - prevEvent[0] < minFrameTime) {
          prevEvent[2] += event[2];
        } else {
          emit(prevEvent);
          prevEvent = event;
          oc++;
        }
      },
      flush: () => {
        if (prevEvent !== void 0) {
          emit(prevEvent);
          oc++;
        }
        logger.debug(`batched ${ic} frames to ${oc} frames`);
      }
    };
  };
}
function prepare(recording2, logger, _ref4) {
  let {
    startAt = 0,
    idleTimeLimit,
    minFrameTime,
    inputOffset,
    markers_
  } = _ref4;
  let {
    events
  } = recording2;
  if (!(events instanceof Stream)) {
    events = new Stream(events);
  }
  idleTimeLimit = idleTimeLimit ?? recording2.idleTimeLimit ?? Infinity;
  const limiterOutput = {
    offset: 0
  };
  events = events.transform(batcher(logger, minFrameTime)).map(timeLimiter(idleTimeLimit, startAt, limiterOutput)).map(markerWrapper());
  if (markers_ !== void 0) {
    markers_ = new Stream(markers_).map(normalizeMarker);
    events = events.filter((e) => e[1] !== "m").multiplex(markers_, (a2, b) => a2[0] < b[0]).map(markerWrapper());
  }
  events = events.toArray();
  if (inputOffset !== void 0) {
    events = events.map((e) => e[1] === "i" ? [e[0] + inputOffset, e[1], e[2]] : e);
    events.sort((a2, b) => a2[0] - b[0]);
  }
  const duration2 = events[events.length - 1][0];
  const effectiveStartAt = startAt - limiterOutput.offset;
  return {
    ...recording2,
    events,
    duration: duration2,
    effectiveStartAt
  };
}
function normalizeMarker(m) {
  return typeof m === "number" ? [m, "m", ""] : [m[0], "m", m[1]];
}
function timeLimiter(idleTimeLimit, startAt, output2) {
  let prevT = 0;
  let shift = 0;
  return function(e) {
    const delay = e[0] - prevT;
    const delta = delay - idleTimeLimit;
    prevT = e[0];
    if (delta > 0) {
      shift += delta;
      if (e[0] < startAt) {
        output2.offset += delta;
      }
    }
    return [e[0] - shift, e[1], e[2]];
  };
}
function markerWrapper() {
  let i2 = 0;
  return function(e) {
    if (e[1] === "m") {
      return [e[0], e[1], {
        index: i2++,
        time: e[0],
        label: e[2]
      }];
    } else {
      return e;
    }
  };
}
function dump(recording2, filename2) {
  const link2 = document.createElement("a");
  const events = recording2.events.map((e) => e[1] === "m" ? [e[0], e[1], e[2].label] : e);
  const asciicast = unparseAsciicastV2({
    ...recording2,
    events
  });
  link2.href = URL.createObjectURL(new Blob([asciicast], {
    type: "text/plain"
  }));
  link2.download = filename2;
  link2.click();
}
async function createAudioElement(src) {
  const audio = new Audio();
  audio.preload = "metadata";
  audio.loop = false;
  audio.crossOrigin = "anonymous";
  let resolve2;
  const canPlay = new Promise((resolve_) => {
    resolve2 = resolve_;
  });
  function onCanPlay() {
    resolve2();
    audio.removeEventListener("canplay", onCanPlay);
  }
  audio.addEventListener("canplay", onCanPlay);
  audio.src = src;
  audio.load();
  await canPlay;
  return audio;
}
function clock(_ref, _ref2, _ref3) {
  let {
    hourColor = 3,
    minuteColor = 4,
    separatorColor = 9
  } = _ref;
  let {
    feed
  } = _ref2;
  let {
    cols = 5,
    rows = 1
  } = _ref3;
  const middleRow = Math.floor(rows / 2);
  const leftPad = Math.floor(cols / 2) - 2;
  const setupCursor = `\x1B[?25l\x1B[1m\x1B[${middleRow}B`;
  let intervalId;
  const getCurrentTime = () => {
    const d = /* @__PURE__ */ new Date();
    const h = d.getHours();
    const m = d.getMinutes();
    const seqs = [];
    seqs.push("\r");
    for (let i2 = 0; i2 < leftPad; i2++) {
      seqs.push(" ");
    }
    seqs.push(`\x1B[3${hourColor}m`);
    if (h < 10) {
      seqs.push("0");
    }
    seqs.push(`${h}`);
    seqs.push(`\x1B[3${separatorColor};5m:\x1B[25m`);
    seqs.push(`\x1B[3${minuteColor}m`);
    if (m < 10) {
      seqs.push("0");
    }
    seqs.push(`${m}`);
    return seqs;
  };
  const updateTime = () => {
    getCurrentTime().forEach(feed);
  };
  return {
    init: () => {
      const duration2 = 24 * 60;
      const poster = [setupCursor].concat(getCurrentTime());
      return {
        cols,
        rows,
        duration: duration2,
        poster
      };
    },
    play: () => {
      feed(setupCursor);
      updateTime();
      intervalId = setInterval(updateTime, 1e3);
      return true;
    },
    stop: () => {
      clearInterval(intervalId);
    },
    getCurrentTime: () => {
      const d = /* @__PURE__ */ new Date();
      return d.getHours() * 60 + d.getMinutes();
    }
  };
}
function random(src, _ref, _ref2) {
  let {
    feed
  } = _ref;
  let {
    speed
  } = _ref2;
  const base2 = " ".charCodeAt(0);
  const range = "~".charCodeAt(0) - base2;
  let timeoutId;
  const schedule = () => {
    const t2 = Math.pow(5, Math.random() * 4);
    timeoutId = setTimeout(print, t2 / speed);
  };
  const print = () => {
    schedule();
    const char = String.fromCharCode(base2 + Math.floor(Math.random() * range));
    feed(char);
  };
  return () => {
    schedule();
    return () => clearInterval(timeoutId);
  };
}
function benchmark(_ref, _ref2) {
  let {
    url,
    iterations = 10
  } = _ref;
  let {
    feed,
    setState: setState2
  } = _ref2;
  let data2;
  let byteCount = 0;
  return {
    async init() {
      const recording2 = await parse$2(await fetch(url));
      const {
        cols,
        rows,
        events
      } = recording2;
      data2 = Array.from(events).filter((_ref3) => {
        let [_time, type, _text] = _ref3;
        return type === "o";
      }).map((_ref4) => {
        let [time2, _type, text2] = _ref4;
        return [time2, text2];
      });
      const duration2 = data2[data2.length - 1][0];
      for (const [_, text2] of data2) {
        byteCount += new Blob([text2]).size;
      }
      return {
        cols,
        rows,
        duration: duration2
      };
    },
    play() {
      const startTime = performance.now();
      for (let i2 = 0; i2 < iterations; i2++) {
        for (const [_, text2] of data2) {
          feed(text2);
        }
        feed("\x1Bc");
      }
      const endTime = performance.now();
      const duration2 = (endTime - startTime) / 1e3;
      const throughput = byteCount * iterations / duration2;
      const throughputMbs = byteCount / (1024 * 1024) * iterations / duration2;
      console.info("benchmark: result", {
        byteCount,
        iterations,
        duration: duration2,
        throughput,
        throughputMbs
      });
      setTimeout(() => {
        setState2("stopped", {
          reason: "ended"
        });
      }, 0);
      return true;
    }
  };
}
class Queue {
  constructor() {
    this.items = [];
    this.onPush = void 0;
  }
  push(item2) {
    this.items.push(item2);
    if (this.onPush !== void 0) {
      this.onPush(this.popAll());
      this.onPush = void 0;
    }
  }
  popAll() {
    if (this.items.length > 0) {
      const items = this.items;
      this.items = [];
      return items;
    } else {
      const thiz = this;
      return new Promise((resolve2) => {
        thiz.onPush = resolve2;
      });
    }
  }
}
function getBuffer(bufferTime, feed, resize2, onInput, onMarker, setTime2, baseStreamTime, minFrameTime, logger) {
  const execute = executeEvent(feed, resize2, onInput, onMarker);
  if (bufferTime === 0) {
    logger.debug("using no buffer");
    return nullBuffer(execute);
  } else {
    bufferTime = bufferTime ?? {};
    let getBufferTime;
    if (typeof bufferTime === "number") {
      logger.debug(`using fixed time buffer (${bufferTime} ms)`);
      getBufferTime = (_latency) => bufferTime;
    } else if (typeof bufferTime === "function") {
      logger.debug("using custom dynamic buffer");
      getBufferTime = bufferTime({
        logger
      });
    } else {
      logger.debug("using adaptive buffer", bufferTime);
      getBufferTime = adaptiveBufferTimeProvider({
        logger
      }, bufferTime);
    }
    return buffer(getBufferTime, execute, setTime2, logger, baseStreamTime ?? 0, minFrameTime);
  }
}
function nullBuffer(execute) {
  return {
    pushEvent(event) {
      execute(event[1], event[2]);
    },
    pushText(text2) {
      execute("o", text2);
    },
    stop() {
    }
  };
}
function executeEvent(feed, resize2, onInput, onMarker) {
  return function(code2, data2) {
    if (code2 === "o") {
      feed(data2);
    } else if (code2 === "i") {
      onInput(data2);
    } else if (code2 === "r") {
      resize2(data2.cols, data2.rows);
    } else if (code2 === "m") {
      onMarker(data2);
    }
  };
}
function buffer(getBufferTime, execute, setTime2, logger, baseStreamTime) {
  let minFrameTime = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : 1 / 60;
  let epoch = performance.now() - baseStreamTime * 1e3;
  let bufferTime = getBufferTime(0);
  const queue = new Queue();
  minFrameTime *= 1e3;
  let prevElapsedStreamTime = -minFrameTime;
  let stop = false;
  function elapsedWallTime() {
    return performance.now() - epoch;
  }
  setTimeout(async () => {
    while (!stop) {
      const events = await queue.popAll();
      if (stop) return;
      for (const event of events) {
        const elapsedStreamTime = event[0] * 1e3 + bufferTime;
        if (elapsedStreamTime - prevElapsedStreamTime < minFrameTime) {
          execute(event[1], event[2]);
          continue;
        }
        const delay = elapsedStreamTime - elapsedWallTime();
        if (delay > 0) {
          await sleep(delay);
          if (stop) return;
        }
        setTime2(event[0]);
        execute(event[1], event[2]);
        prevElapsedStreamTime = elapsedStreamTime;
      }
    }
  }, 0);
  return {
    pushEvent(event) {
      let latency = elapsedWallTime() - event[0] * 1e3;
      if (latency < 0) {
        logger.debug(`correcting epoch by ${latency} ms`);
        epoch += latency;
        latency = 0;
      }
      bufferTime = getBufferTime(latency);
      queue.push(event);
    },
    pushText(text2) {
      queue.push([elapsedWallTime() / 1e3, "o", text2]);
    },
    stop() {
      stop = true;
      queue.push(void 0);
    }
  };
}
function sleep(t2) {
  return new Promise((resolve2) => {
    setTimeout(resolve2, t2);
  });
}
function adaptiveBufferTimeProvider() {
  let {
    logger
  } = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
  let {
    minBufferTime = 50,
    bufferLevelStep = 100,
    maxBufferLevel = 50,
    transitionDuration = 500,
    peakHalfLifeUp = 100,
    peakHalfLifeDown = 1e4,
    floorHalfLifeUp = 5e3,
    floorHalfLifeDown = 100,
    idealHalfLifeUp = 1e3,
    idealHalfLifeDown = 5e3,
    safetyMultiplier = 1.2,
    minImprovementDuration = 3e3
  } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
  function levelToMs(level) {
    return level === 0 ? minBufferTime : bufferLevelStep * level;
  }
  let bufferLevel = 1;
  let bufferTime = levelToMs(bufferLevel);
  let lastUpdateTime = performance.now();
  let smoothedPeakLatency = null;
  let smoothedFloorLatency = null;
  let smoothedIdealBufferTime = null;
  let stableSince = null;
  let targetBufferTime = null;
  let transitionRate = null;
  return function(latency) {
    const now2 = performance.now();
    const dt = Math.max(0, now2 - lastUpdateTime);
    lastUpdateTime = now2;
    if (smoothedPeakLatency === null) {
      smoothedPeakLatency = latency;
    } else if (latency > smoothedPeakLatency) {
      const alphaUp = 1 - Math.pow(2, -dt / peakHalfLifeUp);
      smoothedPeakLatency += alphaUp * (latency - smoothedPeakLatency);
    } else {
      const alphaDown = 1 - Math.pow(2, -dt / peakHalfLifeDown);
      smoothedPeakLatency += alphaDown * (latency - smoothedPeakLatency);
    }
    smoothedPeakLatency = Math.max(smoothedPeakLatency, 0);
    if (smoothedFloorLatency === null) {
      smoothedFloorLatency = latency;
    } else if (latency > smoothedFloorLatency) {
      const alphaUp = 1 - Math.pow(2, -dt / floorHalfLifeUp);
      smoothedFloorLatency += alphaUp * (latency - smoothedFloorLatency);
    } else {
      const alphaDown = 1 - Math.pow(2, -dt / floorHalfLifeDown);
      smoothedFloorLatency += alphaDown * (latency - smoothedFloorLatency);
    }
    smoothedFloorLatency = Math.max(smoothedFloorLatency, 0);
    const jitter = smoothedPeakLatency - smoothedFloorLatency;
    const idealBufferTime = safetyMultiplier * (smoothedPeakLatency + jitter);
    if (smoothedIdealBufferTime === null) {
      smoothedIdealBufferTime = idealBufferTime;
    } else if (idealBufferTime > smoothedIdealBufferTime) {
      const alphaUp = 1 - Math.pow(2, -dt / idealHalfLifeUp);
      smoothedIdealBufferTime += +alphaUp * (idealBufferTime - smoothedIdealBufferTime);
    } else {
      const alphaDown = 1 - Math.pow(2, -dt / idealHalfLifeDown);
      smoothedIdealBufferTime += +alphaDown * (idealBufferTime - smoothedIdealBufferTime);
    }
    let newBufferLevel;
    if (smoothedIdealBufferTime <= minBufferTime) {
      newBufferLevel = 0;
    } else {
      newBufferLevel = clamp$1(Math.ceil(smoothedIdealBufferTime / bufferLevelStep), 1, maxBufferLevel);
    }
    if (latency > bufferTime) {
      logger.debug("buffer underrun", {
        latency,
        bufferTime
      });
    }
    if (newBufferLevel > bufferLevel) {
      if (latency > bufferTime) {
        bufferLevel = Math.min(newBufferLevel, bufferLevel + 3);
      } else {
        bufferLevel += 1;
      }
      targetBufferTime = levelToMs(bufferLevel);
      transitionRate = (targetBufferTime - bufferTime) / transitionDuration;
      stableSince = null;
      logger.debug("raising buffer", {
        latency,
        bufferTime,
        targetBufferTime
      });
    } else if (newBufferLevel < bufferLevel) {
      if (stableSince == null) stableSince = now2;
      if (now2 - stableSince >= minImprovementDuration) {
        bufferLevel -= 1;
        targetBufferTime = levelToMs(bufferLevel);
        transitionRate = (targetBufferTime - bufferTime) / transitionDuration;
        stableSince = now2;
        logger.debug("lowering buffer", {
          latency,
          bufferTime,
          targetBufferTime
        });
      }
    } else {
      stableSince = null;
    }
    if (targetBufferTime !== null) {
      bufferTime += transitionRate * dt;
      if (transitionRate >= 0 && bufferTime > targetBufferTime || transitionRate < 0 && bufferTime < targetBufferTime) {
        bufferTime = targetBufferTime;
        targetBufferTime = null;
      }
    }
    return bufferTime;
  };
}
function clamp$1(x, lo, hi) {
  return Math.min(hi, Math.max(lo, x));
}
const ONE_SEC_IN_USEC = 1e6;
function alisHandler(logger) {
  const outputDecoder = new TextDecoder();
  const inputDecoder = new TextDecoder();
  let handler = parseMagicString;
  let lastEventTime;
  let markerIndex = 0;
  function parseMagicString(buffer2) {
    const text2 = new TextDecoder().decode(buffer2);
    if (text2 === "ALiS") {
      handler = parseFirstFrame;
    } else {
      throw "not an ALiS v1 live stream";
    }
  }
  function parseFirstFrame(buffer2) {
    const view = new BinaryReader(new DataView(buffer2));
    const type = view.getUint8();
    if (type !== 1) throw `expected reset (0x01) frame, got ${type}`;
    return parseResetFrame(view, buffer2);
  }
  function parseResetFrame(view, buffer2) {
    view.decodeVarUint();
    let time2 = view.decodeVarUint();
    lastEventTime = time2;
    time2 = time2 / ONE_SEC_IN_USEC;
    markerIndex = 0;
    const cols = view.decodeVarUint();
    const rows = view.decodeVarUint();
    const themeFormat = view.getUint8();
    let theme;
    if (themeFormat === 8) {
      const len = (2 + 8) * 3;
      theme = parseTheme(new Uint8Array(buffer2, view.offset, len));
      view.forward(len);
    } else if (themeFormat === 16) {
      const len = (2 + 16) * 3;
      theme = parseTheme(new Uint8Array(buffer2, view.offset, len));
      view.forward(len);
    } else if (themeFormat !== 0) {
      throw `alis: invalid theme format (${themeFormat})`;
    }
    const initLen = view.decodeVarUint();
    let init;
    if (initLen > 0) {
      init = outputDecoder.decode(new Uint8Array(buffer2, view.offset, initLen));
    }
    handler = parseFrame2;
    return {
      time: time2,
      term: {
        size: {
          cols,
          rows
        },
        theme,
        init
      }
    };
  }
  function parseFrame2(buffer2) {
    const view = new BinaryReader(new DataView(buffer2));
    const type = view.getUint8();
    if (type === 1) {
      return parseResetFrame(view, buffer2);
    } else if (type === 111) {
      return parseOutputFrame(view, buffer2);
    } else if (type === 105) {
      return parseInputFrame(view, buffer2);
    } else if (type === 114) {
      return parseResizeFrame(view);
    } else if (type === 109) {
      return parseMarkerFrame(view, buffer2);
    } else if (type === 4) {
      handler = parseFirstFrame;
      return false;
    } else {
      logger.debug(`alis: unknown frame type: ${type}`);
    }
  }
  function parseOutputFrame(view, buffer2) {
    view.decodeVarUint();
    const relTime = view.decodeVarUint();
    lastEventTime += relTime;
    const len = view.decodeVarUint();
    const text2 = outputDecoder.decode(new Uint8Array(buffer2, view.offset, len));
    return [lastEventTime / ONE_SEC_IN_USEC, "o", text2];
  }
  function parseInputFrame(view, buffer2) {
    view.decodeVarUint();
    const relTime = view.decodeVarUint();
    lastEventTime += relTime;
    const len = view.decodeVarUint();
    const text2 = inputDecoder.decode(new Uint8Array(buffer2, view.offset, len));
    return [lastEventTime / ONE_SEC_IN_USEC, "i", text2];
  }
  function parseResizeFrame(view) {
    view.decodeVarUint();
    const relTime = view.decodeVarUint();
    lastEventTime += relTime;
    const cols = view.decodeVarUint();
    const rows = view.decodeVarUint();
    return [lastEventTime / ONE_SEC_IN_USEC, "r", {
      cols,
      rows
    }];
  }
  function parseMarkerFrame(view, buffer2) {
    view.decodeVarUint();
    const relTime = view.decodeVarUint();
    lastEventTime += relTime;
    const len = view.decodeVarUint();
    const decoder2 = new TextDecoder();
    const index = markerIndex++;
    const time2 = lastEventTime / ONE_SEC_IN_USEC;
    const label2 = decoder2.decode(new Uint8Array(buffer2, view.offset, len));
    return [time2, "m", {
      index,
      time: time2,
      label: label2
    }];
  }
  return function(buffer2) {
    return handler(buffer2);
  };
}
function parseTheme(arr) {
  const colorCount = arr.length / 3;
  const foreground = hexColor(arr[0], arr[1], arr[2]);
  const background = hexColor(arr[3], arr[4], arr[5]);
  const palette = [];
  for (let i2 = 2; i2 < colorCount; i2++) {
    palette.push(hexColor(arr[i2 * 3], arr[i2 * 3 + 1], arr[i2 * 3 + 2]));
  }
  return {
    foreground,
    background,
    palette
  };
}
function hexColor(r2, g, b) {
  return `#${byteToHex(r2)}${byteToHex(g)}${byteToHex(b)}`;
}
function byteToHex(value2) {
  return value2.toString(16).padStart(2, "0");
}
class BinaryReader {
  constructor(inner) {
    let offset3 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0;
    this.inner = inner;
    this.offset = offset3;
  }
  forward(delta) {
    this.offset += delta;
  }
  getUint8() {
    const value2 = this.inner.getUint8(this.offset);
    this.offset += 1;
    return value2;
  }
  decodeVarUint() {
    let number2 = BigInt(0);
    let shift = BigInt(0);
    let byte = this.getUint8();
    while (byte > 127) {
      byte &= 127;
      number2 += BigInt(byte) << shift;
      shift += BigInt(7);
      byte = this.getUint8();
    }
    number2 = number2 + (BigInt(byte) << shift);
    return Number(number2);
  }
}
function ascicastV2Handler() {
  let parse5 = parseHeader;
  function parseHeader(buffer2) {
    const header2 = JSON.parse(buffer2);
    if (header2.version !== 2) {
      throw "not an asciicast v2 stream";
    }
    parse5 = parseEvent;
    return {
      time: 0,
      term: {
        size: {
          cols: header2.width,
          rows: header2.height
        }
      }
    };
  }
  function parseEvent(buffer2) {
    const event = JSON.parse(buffer2);
    if (event[1] === "r") {
      const [cols, rows] = event[2].split("x");
      return [event[0], "r", {
        cols: parseInt(cols, 10),
        rows: parseInt(rows, 10)
      }];
    } else {
      return event;
    }
  }
  return function(buffer2) {
    return parse5(buffer2);
  };
}
function ascicastV3Handler() {
  let parse5 = parseHeader;
  let currentTime = 0;
  function parseHeader(buffer2) {
    const header2 = JSON.parse(buffer2);
    if (header2.version !== 3) {
      throw "not an asciicast v3 stream";
    }
    parse5 = parseEvent;
    const term = {
      size: {
        cols: header2.term.cols,
        rows: header2.term.rows
      }
    };
    if (header2.term.theme) {
      term.theme = {
        foreground: header2.term.theme.fg,
        background: header2.term.theme.bg,
        palette: header2.term.theme.palette.split(":")
      };
    }
    return {
      time: 0,
      term
    };
  }
  function parseEvent(buffer2) {
    const event = JSON.parse(buffer2);
    const [interval2, eventType, data2] = event;
    currentTime += interval2;
    if (eventType === "r") {
      const [cols, rows] = data2.split("x");
      return [currentTime, "r", {
        cols: parseInt(cols, 10),
        rows: parseInt(rows, 10)
      }];
    } else {
      return [currentTime, eventType, data2];
    }
  }
  return function(buffer2) {
    return parse5(buffer2);
  };
}
function rawHandler() {
  const outputDecoder = new TextDecoder();
  let parse5 = parseSize2;
  function parseSize2(buffer2) {
    const text2 = outputDecoder.decode(buffer2, {
      stream: true
    });
    const [cols, rows] = sizeFromResizeSeq(text2) ?? sizeFromScriptStartMessage(text2) ?? [80, 24];
    parse5 = parseOutput;
    return {
      time: 0,
      term: {
        size: {
          cols,
          rows
        },
        init: text2
      }
    };
  }
  function parseOutput(buffer2) {
    return outputDecoder.decode(buffer2, {
      stream: true
    });
  }
  return function(buffer2) {
    return parse5(buffer2);
  };
}
function sizeFromResizeSeq(text2) {
  const match3 = text2.match(/\x1b\[8;(\d+);(\d+)t/);
  if (match3 !== null) {
    return [parseInt(match3[2], 10), parseInt(match3[1], 10)];
  }
}
function sizeFromScriptStartMessage(text2) {
  const match3 = text2.match(/\[.*COLUMNS="(\d{1,3})" LINES="(\d{1,3})".*\]/);
  if (match3 !== null) {
    return [parseInt(match3[1], 10), parseInt(match3[2], 10)];
  }
}
const RECONNECT_DELAY_BASE = 500;
const RECONNECT_DELAY_CAP = 1e4;
function exponentialDelay(attempt) {
  const base2 = Math.min(RECONNECT_DELAY_BASE * Math.pow(2, attempt), RECONNECT_DELAY_CAP);
  return Math.random() * base2;
}
function websocket(_ref, _ref2, _ref3) {
  let {
    url,
    bufferTime,
    reconnectDelay = exponentialDelay,
    minFrameTime
  } = _ref;
  let {
    feed,
    reset: reset2,
    resize: resize2,
    onInput,
    onMarker,
    setState: setState2,
    logger
  } = _ref2;
  let {
    audioUrl
  } = _ref3;
  logger = new PrefixedLogger(logger, "websocket: ");
  let socket;
  let buf2;
  let clock2 = new NullClock();
  let reconnectAttempt = 0;
  let successfulConnectionTimeout;
  let stop = false;
  let wasOnline = false;
  let initTimeout;
  let audioElement;
  function connect() {
    socket = new WebSocket(url, ["v1.alis", "v2.asciicast", "v3.asciicast", "raw"]);
    socket.binaryType = "arraybuffer";
    socket.onopen = () => {
      const proto = socket.protocol || "raw";
      logger.info("opened");
      logger.info(`activating ${proto} protocol handler`);
      if (proto === "v1.alis") {
        socket.onmessage = onMessage(alisHandler(logger));
      } else if (proto === "v2.asciicast") {
        socket.onmessage = onMessage(ascicastV2Handler());
      } else if (proto === "v3.asciicast") {
        socket.onmessage = onMessage(ascicastV3Handler());
      } else if (proto === "raw") {
        socket.onmessage = onMessage(rawHandler());
      }
      successfulConnectionTimeout = setTimeout(() => {
        reconnectAttempt = 0;
      }, 1e3);
    };
    socket.onclose = (event) => {
      clearTimeout(initTimeout);
      stopBuffer();
      if (stop || event.code === 1e3 || event.code === 1005) {
        logger.info("closed");
        setState2("ended", {
          message: "Stream ended"
        });
      } else if (event.code === 1002) {
        logger.debug(`close reason: ${event.reason}`);
        setState2("ended", {
          message: "Err: Player not compatible with the server"
        });
      } else {
        clearTimeout(successfulConnectionTimeout);
        const delay = reconnectDelay(reconnectAttempt++);
        logger.info(`unclean close, reconnecting in ${delay}...`);
        setState2("loading");
        setTimeout(connect, delay);
      }
    };
    wasOnline = false;
  }
  function onMessage(handler) {
    initTimeout = setTimeout(onStreamEnd, 5e3);
    return function(event) {
      try {
        const result2 = handler(event.data);
        if (buf2) {
          if (Array.isArray(result2)) {
            buf2.pushEvent(result2);
          } else if (typeof result2 === "string") {
            buf2.pushText(result2);
          } else if (typeof result2 === "object" && !Array.isArray(result2)) {
            onStreamReset(result2);
          } else if (result2 === false) {
            onStreamEnd();
          } else if (result2 !== void 0) {
            throw `unexpected value from protocol handler: ${result2}`;
          }
        } else {
          if (typeof result2 === "object" && !Array.isArray(result2)) {
            onStreamReset(result2);
            clearTimeout(initTimeout);
          } else if (result2 === void 0) {
            clearTimeout(initTimeout);
            initTimeout = setTimeout(onStreamEnd, 1e3);
          } else {
            clearTimeout(initTimeout);
            throw `unexpected value from protocol handler: ${result2}`;
          }
        }
      } catch (e) {
        socket.close();
        throw e;
      }
    };
  }
  function onStreamReset(_ref4) {
    let {
      time: time2,
      term
    } = _ref4;
    const {
      size,
      init,
      theme
    } = term;
    const {
      cols,
      rows
    } = size;
    logger.info(`stream reset (${cols}x${rows} @${time2})`);
    setState2("playing");
    stopBuffer();
    buf2 = getBuffer(bufferTime, feed, resize2, onInput, onMarker, (t2) => clock2.setTime(t2), time2, minFrameTime, logger);
    reset2(cols, rows, init, theme);
    clock2 = new Clock();
    wasOnline = true;
    if (typeof time2 === "number") {
      clock2.setTime(time2);
    }
  }
  function onStreamEnd() {
    stopBuffer();
    if (wasOnline) {
      logger.info("stream ended");
      setState2("offline", {
        message: "Stream ended"
      });
    } else {
      logger.info("stream offline");
      setState2("offline", {
        message: "Stream offline"
      });
    }
    clock2 = new NullClock();
  }
  function stopBuffer() {
    if (buf2) buf2.stop();
    buf2 = null;
  }
  function startAudio() {
    if (!audioUrl) return;
    audioElement = new Audio();
    audioElement.preload = "auto";
    audioElement.crossOrigin = "anonymous";
    audioElement.src = audioUrl;
    audioElement.play();
  }
  function stopAudio() {
    if (!audioElement) return;
    audioElement.pause();
  }
  function mute() {
    if (audioElement) {
      audioElement.muted = true;
      return true;
    }
  }
  function unmute() {
    if (audioElement) {
      audioElement.muted = false;
      return true;
    }
  }
  return {
    init: () => {
      return {
        hasAudio: !!audioUrl
      };
    },
    play: () => {
      connect();
      startAudio();
    },
    stop: () => {
      stop = true;
      stopBuffer();
      if (socket !== void 0) socket.close();
      stopAudio();
    },
    mute,
    unmute,
    getCurrentTime: () => clock2.getTime()
  };
}
function eventsource(_ref, _ref2) {
  let {
    url,
    bufferTime,
    minFrameTime
  } = _ref;
  let {
    feed,
    reset: reset2,
    resize: resize2,
    onInput,
    onMarker,
    setState: setState2,
    logger
  } = _ref2;
  logger = new PrefixedLogger(logger, "eventsource: ");
  let es;
  let buf2;
  let clock2 = new NullClock();
  function initBuffer(baseStreamTime) {
    if (buf2 !== void 0) buf2.stop();
    buf2 = getBuffer(bufferTime, feed, resize2, onInput, onMarker, (t2) => clock2.setTime(t2), baseStreamTime, minFrameTime, logger);
  }
  return {
    play: () => {
      es = new EventSource(url);
      es.addEventListener("open", () => {
        logger.info("opened");
        initBuffer();
      });
      es.addEventListener("error", (e) => {
        logger.info("errored");
        logger.debug({
          e
        });
        setState2("loading");
      });
      es.addEventListener("message", (event) => {
        const e = JSON.parse(event.data);
        if (Array.isArray(e)) {
          buf2.pushEvent(e);
        } else if (e.cols !== void 0 || e.width !== void 0) {
          const cols = e.cols ?? e.width;
          const rows = e.rows ?? e.height;
          logger.debug(`vt reset (${cols}x${rows})`);
          setState2("playing");
          initBuffer(e.time);
          reset2(cols, rows, e.init ?? void 0);
          clock2 = new Clock();
          if (typeof e.time === "number") {
            clock2.setTime(e.time);
          }
        } else if (e.state === "offline") {
          logger.info("stream offline");
          setState2("offline", {
            message: "Stream offline"
          });
          clock2 = new NullClock();
        }
      });
      es.addEventListener("done", () => {
        logger.info("closed");
        es.close();
        setState2("ended", {
          message: "Stream ended"
        });
      });
    },
    stop: () => {
      if (buf2 !== void 0) buf2.stop();
      if (es !== void 0) es.close();
    },
    getCurrentTime: () => clock2.getTime()
  };
}
async function parse$1(responses, _ref) {
  let {
    encoding
  } = _ref;
  const textDecoder2 = new TextDecoder(encoding);
  let cols;
  let rows;
  let timing = (await responses[0].text()).split("\n").filter((line2) => line2.length > 0).map((line2) => line2.split(" "));
  if (timing[0].length < 3) {
    timing = timing.map((entry2) => ["O", entry2[0], entry2[1]]);
  }
  const buffer2 = await responses[1].arrayBuffer();
  const array2 = new Uint8Array(buffer2);
  const dataOffset = array2.findIndex((byte) => byte == 10) + 1;
  const header2 = textDecoder2.decode(array2.subarray(0, dataOffset));
  const sizeMatch = header2.match(/COLUMNS="(\d+)" LINES="(\d+)"/);
  if (sizeMatch !== null) {
    cols = parseInt(sizeMatch[1], 10);
    rows = parseInt(sizeMatch[2], 10);
  }
  const stdout = {
    array: array2,
    cursor: dataOffset
  };
  let stdin = stdout;
  if (responses[2] !== void 0) {
    const buffer3 = await responses[2].arrayBuffer();
    const array3 = new Uint8Array(buffer3);
    stdin = {
      array: array3,
      cursor: dataOffset
    };
  }
  const events = [];
  let time2 = 0;
  for (const entry2 of timing) {
    time2 += parseFloat(entry2[1]);
    if (entry2[0] === "O") {
      const count2 = parseInt(entry2[2], 10);
      const bytes = stdout.array.subarray(stdout.cursor, stdout.cursor + count2);
      const text2 = textDecoder2.decode(bytes);
      events.push([time2, "o", text2]);
      stdout.cursor += count2;
    } else if (entry2[0] === "I") {
      const count2 = parseInt(entry2[2], 10);
      const bytes = stdin.array.subarray(stdin.cursor, stdin.cursor + count2);
      const text2 = textDecoder2.decode(bytes);
      events.push([time2, "i", text2]);
      stdin.cursor += count2;
    } else if (entry2[0] === "S" && entry2[2] === "SIGWINCH") {
      const cols2 = parseInt(entry2[4].slice(5), 10);
      const rows2 = parseInt(entry2[3].slice(5), 10);
      events.push([time2, "r", `${cols2}x${rows2}`]);
    } else if (entry2[0] === "H" && entry2[2] === "COLUMNS") {
      cols = parseInt(entry2[3], 10);
    } else if (entry2[0] === "H" && entry2[2] === "LINES") {
      rows = parseInt(entry2[3], 10);
    }
  }
  cols = cols ?? 80;
  rows = rows ?? 24;
  return {
    cols,
    rows,
    events
  };
}
async function parse4(response, _ref) {
  let {
    encoding
  } = _ref;
  const textDecoder2 = new TextDecoder(encoding);
  const buffer2 = await response.arrayBuffer();
  const array2 = new Uint8Array(buffer2);
  const firstFrame = parseFrame(array2);
  const baseTime = firstFrame.time;
  const firstFrameText = textDecoder2.decode(firstFrame.data);
  const sizeMatch = firstFrameText.match(/\x1b\[8;(\d+);(\d+)t/);
  const events = [];
  let cols = 80;
  let rows = 24;
  if (sizeMatch !== null) {
    cols = parseInt(sizeMatch[2], 10);
    rows = parseInt(sizeMatch[1], 10);
  }
  let cursor = 0;
  let frame = parseFrame(array2);
  while (frame !== void 0) {
    const time2 = frame.time - baseTime;
    const text2 = textDecoder2.decode(frame.data);
    events.push([time2, "o", text2]);
    cursor += frame.len;
    frame = parseFrame(array2.subarray(cursor));
  }
  return {
    cols,
    rows,
    events
  };
}
function parseFrame(array2) {
  if (array2.length < 13) return;
  const time2 = parseTimestamp(array2.subarray(0, 8));
  const len = parseNumber(array2.subarray(8, 12));
  const data2 = array2.subarray(12, 12 + len);
  return {
    time: time2,
    data: data2,
    len: len + 12
  };
}
function parseNumber(array2) {
  return array2[0] + array2[1] * 256 + array2[2] * 256 * 256 + array2[3] * 256 * 256 * 256;
}
function parseTimestamp(array2) {
  const sec = parseNumber(array2.subarray(0, 4));
  const usec = parseNumber(array2.subarray(4, 8));
  return sec + usec / 1e6;
}
const vt = loadVt();
class State {
  constructor(core) {
    this.core = core;
    this.driver = core.driver;
  }
  onEnter(data2) {
  }
  init() {
  }
  play() {
  }
  pause() {
  }
  togglePlay() {
  }
  mute() {
    if (this.driver && this.driver.mute()) {
      this.core._dispatchEvent("muted", true);
    }
  }
  unmute() {
    if (this.driver && this.driver.unmute()) {
      this.core._dispatchEvent("muted", false);
    }
  }
  seek(where) {
    return false;
  }
  step(n2) {
  }
  stop() {
    this.driver.stop();
  }
}
class UninitializedState extends State {
  async init() {
    try {
      await this.core._initializeDriver();
      return this.core._setState("idle");
    } catch (e) {
      this.core._setState("errored");
      throw e;
    }
  }
  async play() {
    this.core._dispatchEvent("play");
    const idleState = await this.init();
    await idleState.doPlay();
  }
  async togglePlay() {
    await this.play();
  }
  async seek(where) {
    const idleState = await this.init();
    return await idleState.seek(where);
  }
  async step(n2) {
    const idleState = await this.init();
    await idleState.step(n2);
  }
  stop() {
  }
}
class Idle extends State {
  onEnter(_ref) {
    let {
      reason,
      message: message2
    } = _ref;
    this.core._dispatchEvent("idle", {
      message: message2
    });
    if (reason === "paused") {
      this.core._dispatchEvent("pause");
    }
  }
  async play() {
    this.core._dispatchEvent("play");
    await this.doPlay();
  }
  async doPlay() {
    const stop = await this.driver.play();
    if (stop === true) {
      this.core._setState("playing");
    } else if (typeof stop === "function") {
      this.core._setState("playing");
      this.driver.stop = stop;
    }
  }
  async togglePlay() {
    await this.play();
  }
  seek(where) {
    return this.driver.seek(where);
  }
  step(n2) {
    this.driver.step(n2);
  }
}
class PlayingState extends State {
  onEnter() {
    this.core._dispatchEvent("playing");
  }
  pause() {
    if (this.driver.pause() === true) {
      this.core._setState("idle", {
        reason: "paused"
      });
    }
  }
  togglePlay() {
    this.pause();
  }
  seek(where) {
    return this.driver.seek(where);
  }
}
class LoadingState extends State {
  onEnter() {
    this.core._dispatchEvent("loading");
  }
}
class OfflineState extends State {
  onEnter(_ref2) {
    let {
      message: message2
    } = _ref2;
    this.core._dispatchEvent("offline", {
      message: message2
    });
  }
}
class EndedState extends State {
  onEnter(_ref3) {
    let {
      message: message2
    } = _ref3;
    this.core._dispatchEvent("ended", {
      message: message2
    });
  }
  async play() {
    this.core._dispatchEvent("play");
    if (await this.driver.restart()) {
      this.core._setState("playing");
    }
  }
  async togglePlay() {
    await this.play();
  }
  async seek(where) {
    if (await this.driver.seek(where) === true) {
      this.core._setState("idle");
      return true;
    }
    return false;
  }
}
class ErroredState extends State {
  onEnter() {
    this.core._dispatchEvent("errored");
  }
}
class Core {
  constructor(src, opts) {
    this.logger = opts.logger;
    this.state = new UninitializedState(this);
    this.stateName = "uninitialized";
    this.driver = getDriver(src);
    this.changedLines = /* @__PURE__ */ new Set();
    this.cursor = void 0;
    this.duration = void 0;
    this.cols = opts.cols;
    this.rows = opts.rows;
    this.speed = opts.speed;
    this.loop = opts.loop;
    this.autoPlay = opts.autoPlay;
    this.idleTimeLimit = opts.idleTimeLimit;
    this.preload = opts.preload;
    this.startAt = parseNpt(opts.startAt);
    this.poster = this._parsePoster(opts.poster);
    this.markers = this._normalizeMarkers(opts.markers);
    this.pauseOnMarkers = opts.pauseOnMarkers;
    this.audioUrl = opts.audioUrl;
    this.commandQueue = Promise.resolve();
    this.eventHandlers = /* @__PURE__ */ new Map([["ended", []], ["errored", []], ["idle", []], ["input", []], ["loading", []], ["marker", []], ["metadata", []], ["muted", []], ["offline", []], ["pause", []], ["play", []], ["playing", []], ["ready", []], ["reset", []], ["resize", []], ["seeked", []], ["terminalUpdate", []]]);
  }
  async init() {
    this.wasm = await vt;
    const feed = this._feed.bind(this);
    const onInput = (data2) => {
      this._dispatchEvent("input", {
        data: data2
      });
    };
    const onMarker = (_ref4) => {
      let {
        index,
        time: time2,
        label: label2
      } = _ref4;
      this._dispatchEvent("marker", {
        index,
        time: time2,
        label: label2
      });
    };
    const reset2 = this._resetVt.bind(this);
    const resize2 = this._resizeVt.bind(this);
    const setState2 = this._setState.bind(this);
    const posterTime = this.poster.type === "npt" ? this.poster.value : void 0;
    this.driver = this.driver({
      feed,
      onInput,
      onMarker,
      reset: reset2,
      resize: resize2,
      setState: setState2,
      logger: this.logger
    }, {
      cols: this.cols,
      rows: this.rows,
      speed: this.speed,
      idleTimeLimit: this.idleTimeLimit,
      startAt: this.startAt,
      loop: this.loop,
      posterTime,
      markers: this.markers,
      pauseOnMarkers: this.pauseOnMarkers,
      audioUrl: this.audioUrl
    });
    if (typeof this.driver === "function") {
      this.driver = {
        play: this.driver
      };
    }
    if (this.preload || posterTime !== void 0) {
      this._withState((state) => state.init());
    }
    const poster = this.poster.type === "text" ? this._renderPoster(this.poster.value) : null;
    const config2 = {
      isPausable: !!this.driver.pause,
      isSeekable: !!this.driver.seek,
      poster
    };
    if (this.driver.init === void 0) {
      this.driver.init = () => {
        return {};
      };
    }
    if (this.driver.pause === void 0) {
      this.driver.pause = () => {
      };
    }
    if (this.driver.seek === void 0) {
      this.driver.seek = (where) => false;
    }
    if (this.driver.step === void 0) {
      this.driver.step = (n2) => {
      };
    }
    if (this.driver.stop === void 0) {
      this.driver.stop = () => {
      };
    }
    if (this.driver.restart === void 0) {
      this.driver.restart = () => {
      };
    }
    if (this.driver.mute === void 0) {
      this.driver.mute = () => {
      };
    }
    if (this.driver.unmute === void 0) {
      this.driver.unmute = () => {
      };
    }
    if (this.driver.getCurrentTime === void 0) {
      const play = this.driver.play;
      let clock2 = new NullClock();
      this.driver.play = () => {
        clock2 = new Clock(this.speed);
        return play();
      };
      this.driver.getCurrentTime = () => clock2.getTime();
    }
    this._dispatchEvent("ready", config2);
    if (this.autoPlay) {
      this.play();
    }
  }
  play() {
    return this._withState((state) => state.play());
  }
  pause() {
    return this._withState((state) => state.pause());
  }
  togglePlay() {
    return this._withState((state) => state.togglePlay());
  }
  seek(where) {
    return this._withState(async (state) => {
      if (await state.seek(where)) {
        this._dispatchEvent("seeked");
      }
    });
  }
  step(n2) {
    return this._withState((state) => state.step(n2));
  }
  stop() {
    return this._withState((state) => state.stop());
  }
  mute() {
    return this._withState((state) => state.mute());
  }
  unmute() {
    return this._withState((state) => state.unmute());
  }
  getChanges() {
    const changes = {};
    if (this.changedLines.size > 0) {
      const lines = /* @__PURE__ */ new Map();
      const rows = this.vt.rows;
      for (const i2 of this.changedLines) {
        if (i2 < rows) {
          lines.set(i2, {
            id: i2,
            segments: this.vt.getLine(i2)
          });
        }
      }
      this.changedLines.clear();
      changes.lines = lines;
    }
    if (this.cursor === void 0 && this.vt) {
      this.cursor = this.vt.getCursor() ?? false;
      changes.cursor = this.cursor;
    }
    return changes;
  }
  getCurrentTime() {
    return this.driver.getCurrentTime();
  }
  getRemainingTime() {
    if (typeof this.duration === "number") {
      return this.duration - Math.min(this.getCurrentTime(), this.duration);
    }
  }
  getProgress() {
    if (typeof this.duration === "number") {
      return Math.min(this.getCurrentTime(), this.duration) / this.duration;
    }
  }
  getDuration() {
    return this.duration;
  }
  addEventListener(eventName, handler) {
    this.eventHandlers.get(eventName).push(handler);
  }
  _dispatchEvent(eventName) {
    let data2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    for (const h of this.eventHandlers.get(eventName)) {
      h(data2);
    }
  }
  _withState(f) {
    return this._enqueueCommand(() => f(this.state));
  }
  _enqueueCommand(f) {
    this.commandQueue = this.commandQueue.then(f);
    return this.commandQueue;
  }
  _setState(newState) {
    let data2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    if (this.stateName === newState) return this.state;
    this.stateName = newState;
    if (newState === "playing") {
      this.state = new PlayingState(this);
    } else if (newState === "idle") {
      this.state = new Idle(this);
    } else if (newState === "loading") {
      this.state = new LoadingState(this);
    } else if (newState === "ended") {
      this.state = new EndedState(this);
    } else if (newState === "offline") {
      this.state = new OfflineState(this);
    } else if (newState === "errored") {
      this.state = new ErroredState(this);
    } else {
      throw `invalid state: ${newState}`;
    }
    this.state.onEnter(data2);
    return this.state;
  }
  _feed(data2) {
    this._doFeed(data2);
    this._dispatchEvent("terminalUpdate");
  }
  _doFeed(data2) {
    const affectedLines = this.vt.feed(data2);
    affectedLines.forEach((i2) => this.changedLines.add(i2));
    this.cursor = void 0;
  }
  async _initializeDriver() {
    const meta = await this.driver.init();
    this.cols = this.cols ?? meta.cols ?? 80;
    this.rows = this.rows ?? meta.rows ?? 24;
    this.duration = this.duration ?? meta.duration;
    this.markers = this._normalizeMarkers(meta.markers) ?? this.markers ?? [];
    if (this.cols === 0) {
      this.cols = 80;
    }
    if (this.rows === 0) {
      this.rows = 24;
    }
    this._initializeVt(this.cols, this.rows);
    const poster = meta.poster !== void 0 ? this._renderPoster(meta.poster) : null;
    this._dispatchEvent("metadata", {
      cols: this.cols,
      rows: this.rows,
      duration: this.duration,
      markers: this.markers,
      theme: meta.theme,
      hasAudio: meta.hasAudio,
      poster
    });
  }
  _resetVt(cols, rows) {
    let init = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : void 0;
    let theme = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : void 0;
    this.logger.debug(`core: vt reset (${cols}x${rows})`);
    this.cols = cols;
    this.rows = rows;
    this.cursor = void 0;
    this._initializeVt(cols, rows);
    if (init !== void 0 && init !== "") {
      this._doFeed(init);
    }
    this._dispatchEvent("reset", {
      cols,
      rows,
      theme
    });
  }
  _resizeVt(cols, rows) {
    if (cols === this.vt.cols && rows === this.vt.rows) return;
    const affectedLines = this.vt.resize(cols, rows);
    affectedLines.forEach((i2) => this.changedLines.add(i2));
    this.cursor = void 0;
    this.vt.cols = cols;
    this.vt.rows = rows;
    this.logger.debug(`core: vt resize (${cols}x${rows})`);
    this._dispatchEvent("resize", {
      cols,
      rows
    });
  }
  _initializeVt(cols, rows) {
    this.vt = this.wasm.create(cols, rows, true, 100);
    this.vt.cols = cols;
    this.vt.rows = rows;
    this.changedLines.clear();
    for (let i2 = 0; i2 < rows; i2++) {
      this.changedLines.add(i2);
    }
  }
  _parsePoster(poster) {
    if (typeof poster !== "string") return {};
    if (poster.substring(0, 16) == "data:text/plain,") {
      return {
        type: "text",
        value: [poster.substring(16)]
      };
    } else if (poster.substring(0, 4) == "npt:") {
      return {
        type: "npt",
        value: parseNpt(poster.substring(4))
      };
    }
    return {};
  }
  _renderPoster(poster) {
    const cols = this.cols ?? 80;
    const rows = this.rows ?? 24;
    this.logger.debug(`core: poster init (${cols}x${rows})`);
    const vt2 = this.wasm.create(cols, rows, false, 0);
    poster.forEach((text2) => vt2.feed(text2));
    const cursor = vt2.getCursor() ?? false;
    const lines = [];
    for (let i2 = 0; i2 < rows; i2++) {
      lines.push({
        id: i2,
        segments: vt2.getLine(i2)
      });
    }
    return {
      cursor,
      lines
    };
  }
  _normalizeMarkers(markers) {
    if (Array.isArray(markers)) {
      return markers.map((m) => typeof m === "number" ? [m, ""] : m);
    }
  }
}
const DRIVERS = /* @__PURE__ */ new Map([["benchmark", benchmark], ["clock", clock], ["eventsource", eventsource], ["random", random], ["recording", recording], ["websocket", websocket]]);
const PARSERS = /* @__PURE__ */ new Map([["asciicast", parse$2], ["typescript", parse$1], ["ttyrec", parse4]]);
function getDriver(src) {
  if (typeof src === "function") return src;
  if (typeof src === "string") {
    if (src.substring(0, 5) == "ws://" || src.substring(0, 6) == "wss://") {
      src = {
        driver: "websocket",
        url: src
      };
    } else if (src.substring(0, 6) == "clock:") {
      src = {
        driver: "clock"
      };
    } else if (src.substring(0, 7) == "random:") {
      src = {
        driver: "random"
      };
    } else if (src.substring(0, 10) == "benchmark:") {
      src = {
        driver: "benchmark",
        url: src.substring(10)
      };
    } else {
      src = {
        driver: "recording",
        url: src
      };
    }
  }
  if (src.driver === void 0) {
    src.driver = "recording";
  }
  if (src.driver == "recording") {
    if (src.parser === void 0) {
      src.parser = "asciicast";
    }
    if (typeof src.parser === "string") {
      if (PARSERS.has(src.parser)) {
        src.parser = PARSERS.get(src.parser);
      } else {
        throw `unknown parser: ${src.parser}`;
      }
    }
  }
  if (DRIVERS.has(src.driver)) {
    const driver = DRIVERS.get(src.driver);
    return (callbacks, opts) => driver(src, callbacks, opts);
  } else {
    throw `unsupported driver: ${JSON.stringify(src)}`;
  }
}
const IS_DEV = false;
const equalFn = (a2, b) => a2 === b;
const $PROXY = Symbol("solid-proxy");
const SUPPORTS_PROXY = typeof Proxy === "function";
const $TRACK = Symbol("solid-track");
const signalOptions = {
  equals: equalFn
};
let runEffects = runQueue;
const STALE = 1;
const PENDING = 2;
const UNOWNED = {
  owned: null,
  cleanups: null,
  context: null,
  owner: null
};
var Owner = null;
let Transition$1 = null;
let ExternalSourceConfig = null;
let Listener = null;
let Updates = null;
let Effects = null;
let ExecCount = 0;
function createRoot(fn3, detachedOwner) {
  const listener = Listener, owner = Owner, unowned = fn3.length === 0, current3 = detachedOwner === void 0 ? owner : detachedOwner, root2 = unowned ? UNOWNED : {
    owned: null,
    cleanups: null,
    context: current3 ? current3.context : null,
    owner: current3
  }, updateFn = unowned ? fn3 : () => fn3(() => untrack(() => cleanNode(root2)));
  Owner = root2;
  Listener = null;
  try {
    return runUpdates(updateFn, true);
  } finally {
    Listener = listener;
    Owner = owner;
  }
}
function createSignal(value2, options) {
  options = options ? Object.assign({}, signalOptions, options) : signalOptions;
  const s = {
    value: value2,
    observers: null,
    observerSlots: null,
    comparator: options.equals || void 0
  };
  const setter = (value3) => {
    if (typeof value3 === "function") {
      value3 = value3(s.value);
    }
    return writeSignal(s, value3);
  };
  return [readSignal.bind(s), setter];
}
function createComputed(fn3, value2, options) {
  const c2 = createComputation(fn3, value2, true, STALE);
  updateComputation(c2);
}
function createRenderEffect(fn3, value2, options) {
  const c2 = createComputation(fn3, value2, false, STALE);
  updateComputation(c2);
}
function createEffect(fn3, value2, options) {
  runEffects = runUserEffects;
  const c2 = createComputation(fn3, value2, false, STALE);
  c2.user = true;
  Effects ? Effects.push(c2) : updateComputation(c2);
}
function createMemo(fn3, value2, options) {
  options = options ? Object.assign({}, signalOptions, options) : signalOptions;
  const c2 = createComputation(fn3, value2, true, 0);
  c2.observers = null;
  c2.observerSlots = null;
  c2.comparator = options.equals || void 0;
  updateComputation(c2);
  return readSignal.bind(c2);
}
function batch(fn3) {
  return runUpdates(fn3, false);
}
function untrack(fn3) {
  if (Listener === null) return fn3();
  const listener = Listener;
  Listener = null;
  try {
    if (ExternalSourceConfig) ;
    return fn3();
  } finally {
    Listener = listener;
  }
}
function onMount(fn3) {
  createEffect(() => untrack(fn3));
}
function onCleanup(fn3) {
  if (Owner === null) ;
  else if (Owner.cleanups === null) Owner.cleanups = [fn3];
  else Owner.cleanups.push(fn3);
  return fn3;
}
function getListener() {
  return Listener;
}
function startTransition(fn3) {
  const l2 = Listener;
  const o = Owner;
  return Promise.resolve().then(() => {
    Listener = l2;
    Owner = o;
    let t2;
    runUpdates(fn3, false);
    Listener = Owner = null;
    return t2 ? t2.done : void 0;
  });
}
const [transPending] = /* @__PURE__ */ createSignal(false);
function useTransition() {
  return [transPending, startTransition];
}
function children(fn3) {
  const children2 = createMemo(fn3);
  const memo2 = createMemo(() => resolveChildren(children2()));
  memo2.toArray = () => {
    const c2 = memo2();
    return Array.isArray(c2) ? c2 : c2 != null ? [c2] : [];
  };
  return memo2;
}
function readSignal() {
  if (this.sources && this.state) {
    if (this.state === STALE) updateComputation(this);
    else {
      const updates = Updates;
      Updates = null;
      runUpdates(() => lookUpstream(this), false);
      Updates = updates;
    }
  }
  if (Listener) {
    const sSlot = this.observers ? this.observers.length : 0;
    if (!Listener.sources) {
      Listener.sources = [this];
      Listener.sourceSlots = [sSlot];
    } else {
      Listener.sources.push(this);
      Listener.sourceSlots.push(sSlot);
    }
    if (!this.observers) {
      this.observers = [Listener];
      this.observerSlots = [Listener.sources.length - 1];
    } else {
      this.observers.push(Listener);
      this.observerSlots.push(Listener.sources.length - 1);
    }
  }
  return this.value;
}
function writeSignal(node2, value2, isComp) {
  let current3 = node2.value;
  if (!node2.comparator || !node2.comparator(current3, value2)) {
    node2.value = value2;
    if (node2.observers && node2.observers.length) {
      runUpdates(() => {
        for (let i2 = 0; i2 < node2.observers.length; i2 += 1) {
          const o = node2.observers[i2];
          const TransitionRunning = Transition$1 && Transition$1.running;
          if (TransitionRunning && Transition$1.disposed.has(o)) ;
          if (TransitionRunning ? !o.tState : !o.state) {
            if (o.pure) Updates.push(o);
            else Effects.push(o);
            if (o.observers) markDownstream(o);
          }
          if (!TransitionRunning) o.state = STALE;
        }
        if (Updates.length > 1e6) {
          Updates = [];
          if (IS_DEV) ;
          throw new Error();
        }
      }, false);
    }
  }
  return value2;
}
function updateComputation(node2) {
  if (!node2.fn) return;
  cleanNode(node2);
  const time2 = ExecCount;
  runComputation(
    node2,
    node2.value,
    time2
  );
}
function runComputation(node2, value2, time2) {
  let nextValue;
  const owner = Owner, listener = Listener;
  Listener = Owner = node2;
  try {
    nextValue = node2.fn(value2);
  } catch (err) {
    if (node2.pure) {
      {
        node2.state = STALE;
        node2.owned && node2.owned.forEach(cleanNode);
        node2.owned = null;
      }
    }
    node2.updatedAt = time2 + 1;
    return handleError(err);
  } finally {
    Listener = listener;
    Owner = owner;
  }
  if (!node2.updatedAt || node2.updatedAt <= time2) {
    if (node2.updatedAt != null && "observers" in node2) {
      writeSignal(node2, nextValue);
    } else node2.value = nextValue;
    node2.updatedAt = time2;
  }
}
function createComputation(fn3, init, pure, state = STALE, options) {
  const c2 = {
    fn: fn3,
    state,
    updatedAt: null,
    owned: null,
    sources: null,
    sourceSlots: null,
    cleanups: null,
    value: init,
    owner: Owner,
    context: Owner ? Owner.context : null,
    pure
  };
  if (Owner === null) ;
  else if (Owner !== UNOWNED) {
    {
      if (!Owner.owned) Owner.owned = [c2];
      else Owner.owned.push(c2);
    }
  }
  return c2;
}
function runTop(node2) {
  if (node2.state === 0) return;
  if (node2.state === PENDING) return lookUpstream(node2);
  if (node2.suspense && untrack(node2.suspense.inFallback)) return node2.suspense.effects.push(node2);
  const ancestors = [node2];
  while ((node2 = node2.owner) && (!node2.updatedAt || node2.updatedAt < ExecCount)) {
    if (node2.state) ancestors.push(node2);
  }
  for (let i2 = ancestors.length - 1; i2 >= 0; i2--) {
    node2 = ancestors[i2];
    if (node2.state === STALE) {
      updateComputation(node2);
    } else if (node2.state === PENDING) {
      const updates = Updates;
      Updates = null;
      runUpdates(() => lookUpstream(node2, ancestors[0]), false);
      Updates = updates;
    }
  }
}
function runUpdates(fn3, init) {
  if (Updates) return fn3();
  let wait = false;
  if (!init) Updates = [];
  if (Effects) wait = true;
  else Effects = [];
  ExecCount++;
  try {
    const res = fn3();
    completeUpdates(wait);
    return res;
  } catch (err) {
    if (!wait) Effects = null;
    Updates = null;
    handleError(err);
  }
}
function completeUpdates(wait) {
  if (Updates) {
    runQueue(Updates);
    Updates = null;
  }
  if (wait) return;
  const e = Effects;
  Effects = null;
  if (e.length) runUpdates(() => runEffects(e), false);
}
function runQueue(queue) {
  for (let i2 = 0; i2 < queue.length; i2++) runTop(queue[i2]);
}
function runUserEffects(queue) {
  let i2, userLength = 0;
  for (i2 = 0; i2 < queue.length; i2++) {
    const e = queue[i2];
    if (!e.user) runTop(e);
    else queue[userLength++] = e;
  }
  for (i2 = 0; i2 < userLength; i2++) runTop(queue[i2]);
}
function lookUpstream(node2, ignore) {
  node2.state = 0;
  for (let i2 = 0; i2 < node2.sources.length; i2 += 1) {
    const source2 = node2.sources[i2];
    if (source2.sources) {
      const state = source2.state;
      if (state === STALE) {
        if (source2 !== ignore && (!source2.updatedAt || source2.updatedAt < ExecCount))
          runTop(source2);
      } else if (state === PENDING) lookUpstream(source2, ignore);
    }
  }
}
function markDownstream(node2) {
  for (let i2 = 0; i2 < node2.observers.length; i2 += 1) {
    const o = node2.observers[i2];
    if (!o.state) {
      o.state = PENDING;
      if (o.pure) Updates.push(o);
      else Effects.push(o);
      o.observers && markDownstream(o);
    }
  }
}
function cleanNode(node2) {
  let i2;
  if (node2.sources) {
    while (node2.sources.length) {
      const source2 = node2.sources.pop(), index = node2.sourceSlots.pop(), obs = source2.observers;
      if (obs && obs.length) {
        const n2 = obs.pop(), s = source2.observerSlots.pop();
        if (index < obs.length) {
          n2.sourceSlots[s] = index;
          obs[index] = n2;
          source2.observerSlots[index] = s;
        }
      }
    }
  }
  if (node2.tOwned) {
    for (i2 = node2.tOwned.length - 1; i2 >= 0; i2--) cleanNode(node2.tOwned[i2]);
    delete node2.tOwned;
  }
  if (node2.owned) {
    for (i2 = node2.owned.length - 1; i2 >= 0; i2--) cleanNode(node2.owned[i2]);
    node2.owned = null;
  }
  if (node2.cleanups) {
    for (i2 = node2.cleanups.length - 1; i2 >= 0; i2--) node2.cleanups[i2]();
    node2.cleanups = null;
  }
  node2.state = 0;
}
function castError(err) {
  if (err instanceof Error) return err;
  return new Error(typeof err === "string" ? err : "Unknown error", {
    cause: err
  });
}
function handleError(err, owner = Owner) {
  const error2 = castError(err);
  throw error2;
}
function resolveChildren(children2) {
  if (typeof children2 === "function" && !children2.length) return resolveChildren(children2());
  if (Array.isArray(children2)) {
    const results = [];
    for (let i2 = 0; i2 < children2.length; i2++) {
      const result2 = resolveChildren(children2[i2]);
      Array.isArray(result2) ? results.push.apply(results, result2) : results.push(result2);
    }
    return results;
  }
  return children2;
}
const FALLBACK = Symbol("fallback");
function dispose(d) {
  for (let i2 = 0; i2 < d.length; i2++) d[i2]();
}
function mapArray(list2, mapFn, options = {}) {
  let items = [], mapped = [], disposers = [], len = 0, indexes = mapFn.length > 1 ? [] : null;
  onCleanup(() => dispose(disposers));
  return () => {
    let newItems = list2() || [], newLen = newItems.length, i2, j2;
    newItems[$TRACK];
    return untrack(() => {
      let newIndices, newIndicesNext, temp, tempdisposers, tempIndexes, start2, end2, newEnd, item2;
      if (newLen === 0) {
        if (len !== 0) {
          dispose(disposers);
          disposers = [];
          items = [];
          mapped = [];
          len = 0;
          indexes && (indexes = []);
        }
        if (options.fallback) {
          items = [FALLBACK];
          mapped[0] = createRoot((disposer) => {
            disposers[0] = disposer;
            return options.fallback();
          });
          len = 1;
        }
      } else if (len === 0) {
        mapped = new Array(newLen);
        for (j2 = 0; j2 < newLen; j2++) {
          items[j2] = newItems[j2];
          mapped[j2] = createRoot(mapper);
        }
        len = newLen;
      } else {
        temp = new Array(newLen);
        tempdisposers = new Array(newLen);
        indexes && (tempIndexes = new Array(newLen));
        for (start2 = 0, end2 = Math.min(len, newLen); start2 < end2 && items[start2] === newItems[start2]; start2++) ;
        for (end2 = len - 1, newEnd = newLen - 1; end2 >= start2 && newEnd >= start2 && items[end2] === newItems[newEnd]; end2--, newEnd--) {
          temp[newEnd] = mapped[end2];
          tempdisposers[newEnd] = disposers[end2];
          indexes && (tempIndexes[newEnd] = indexes[end2]);
        }
        newIndices = /* @__PURE__ */ new Map();
        newIndicesNext = new Array(newEnd + 1);
        for (j2 = newEnd; j2 >= start2; j2--) {
          item2 = newItems[j2];
          i2 = newIndices.get(item2);
          newIndicesNext[j2] = i2 === void 0 ? -1 : i2;
          newIndices.set(item2, j2);
        }
        for (i2 = start2; i2 <= end2; i2++) {
          item2 = items[i2];
          j2 = newIndices.get(item2);
          if (j2 !== void 0 && j2 !== -1) {
            temp[j2] = mapped[i2];
            tempdisposers[j2] = disposers[i2];
            indexes && (tempIndexes[j2] = indexes[i2]);
            j2 = newIndicesNext[j2];
            newIndices.set(item2, j2);
          } else disposers[i2]();
        }
        for (j2 = start2; j2 < newLen; j2++) {
          if (j2 in temp) {
            mapped[j2] = temp[j2];
            disposers[j2] = tempdisposers[j2];
            if (indexes) {
              indexes[j2] = tempIndexes[j2];
              indexes[j2](j2);
            }
          } else mapped[j2] = createRoot(mapper);
        }
        mapped = mapped.slice(0, len = newLen);
        items = newItems.slice(0);
      }
      return mapped;
    });
    function mapper(disposer) {
      disposers[j2] = disposer;
      if (indexes) {
        const [s, set3] = createSignal(j2);
        indexes[j2] = set3;
        return mapFn(newItems[j2], s);
      }
      return mapFn(newItems[j2]);
    }
  };
}
function indexArray(list2, mapFn, options = {}) {
  let items = [], mapped = [], disposers = [], signals = [], len = 0, i2;
  onCleanup(() => dispose(disposers));
  return () => {
    const newItems = list2() || [], newLen = newItems.length;
    newItems[$TRACK];
    return untrack(() => {
      if (newLen === 0) {
        if (len !== 0) {
          dispose(disposers);
          disposers = [];
          items = [];
          mapped = [];
          len = 0;
          signals = [];
        }
        if (options.fallback) {
          items = [FALLBACK];
          mapped[0] = createRoot((disposer) => {
            disposers[0] = disposer;
            return options.fallback();
          });
          len = 1;
        }
        return mapped;
      }
      if (items[0] === FALLBACK) {
        disposers[0]();
        disposers = [];
        items = [];
        mapped = [];
        len = 0;
      }
      for (i2 = 0; i2 < newLen; i2++) {
        if (i2 < items.length && items[i2] !== newItems[i2]) {
          signals[i2](() => newItems[i2]);
        } else if (i2 >= items.length) {
          mapped[i2] = createRoot(mapper);
        }
      }
      for (; i2 < items.length; i2++) {
        disposers[i2]();
      }
      len = signals.length = disposers.length = newLen;
      items = newItems.slice(0);
      return mapped = mapped.slice(0, len);
    });
    function mapper(disposer) {
      disposers[i2] = disposer;
      const [s, set3] = createSignal(newItems[i2]);
      signals[i2] = set3;
      return mapFn(s, i2);
    }
  };
}
function createComponent(Comp, props) {
  return untrack(() => Comp(props || {}));
}
function trueFn() {
  return true;
}
const propTraps = {
  get(_, property, receiver) {
    if (property === $PROXY) return receiver;
    return _.get(property);
  },
  has(_, property) {
    if (property === $PROXY) return true;
    return _.has(property);
  },
  set: trueFn,
  deleteProperty: trueFn,
  getOwnPropertyDescriptor(_, property) {
    return {
      configurable: true,
      enumerable: true,
      get() {
        return _.get(property);
      },
      set: trueFn,
      deleteProperty: trueFn
    };
  },
  ownKeys(_) {
    return _.keys();
  }
};
function resolveSource(s) {
  return !(s = typeof s === "function" ? s() : s) ? {} : s;
}
function resolveSources() {
  for (let i2 = 0, length2 = this.length; i2 < length2; ++i2) {
    const v = this[i2]();
    if (v !== void 0) return v;
  }
}
function mergeProps(...sources) {
  let proxy = false;
  for (let i2 = 0; i2 < sources.length; i2++) {
    const s = sources[i2];
    proxy = proxy || !!s && $PROXY in s;
    sources[i2] = typeof s === "function" ? (proxy = true, createMemo(s)) : s;
  }
  if (SUPPORTS_PROXY && proxy) {
    return new Proxy(
      {
        get(property) {
          for (let i2 = sources.length - 1; i2 >= 0; i2--) {
            const v = resolveSource(sources[i2])[property];
            if (v !== void 0) return v;
          }
        },
        has(property) {
          for (let i2 = sources.length - 1; i2 >= 0; i2--) {
            if (property in resolveSource(sources[i2])) return true;
          }
          return false;
        },
        keys() {
          const keys2 = [];
          for (let i2 = 0; i2 < sources.length; i2++)
            keys2.push(...Object.keys(resolveSource(sources[i2])));
          return [...new Set(keys2)];
        }
      },
      propTraps
    );
  }
  const sourcesMap = {};
  const defined = /* @__PURE__ */ Object.create(null);
  for (let i2 = sources.length - 1; i2 >= 0; i2--) {
    const source2 = sources[i2];
    if (!source2) continue;
    const sourceKeys = Object.getOwnPropertyNames(source2);
    for (let i3 = sourceKeys.length - 1; i3 >= 0; i3--) {
      const key2 = sourceKeys[i3];
      if (key2 === "__proto__" || key2 === "constructor") continue;
      const desc = Object.getOwnPropertyDescriptor(source2, key2);
      if (!defined[key2]) {
        defined[key2] = desc.get ? {
          enumerable: true,
          configurable: true,
          get: resolveSources.bind(sourcesMap[key2] = [desc.get.bind(source2)])
        } : desc.value !== void 0 ? desc : void 0;
      } else {
        const sources2 = sourcesMap[key2];
        if (sources2) {
          if (desc.get) sources2.push(desc.get.bind(source2));
          else if (desc.value !== void 0) sources2.push(() => desc.value);
        }
      }
    }
  }
  const target = {};
  const definedKeys = Object.keys(defined);
  for (let i2 = definedKeys.length - 1; i2 >= 0; i2--) {
    const key2 = definedKeys[i2], desc = defined[key2];
    if (desc && desc.get) Object.defineProperty(target, key2, desc);
    else target[key2] = desc ? desc.value : void 0;
  }
  return target;
}
const narrowedError = (name2) => `Stale read from <${name2}>.`;
function For(props) {
  const fallback = "fallback" in props && {
    fallback: () => props.fallback
  };
  return createMemo(mapArray(() => props.each, props.children, fallback || void 0));
}
function Index(props) {
  const fallback = "fallback" in props && {
    fallback: () => props.fallback
  };
  return createMemo(indexArray(() => props.each, props.children, fallback || void 0));
}
function Show(props) {
  const keyed = props.keyed;
  const conditionValue = createMemo(() => props.when, void 0, void 0);
  const condition = keyed ? conditionValue : createMemo(conditionValue, void 0, {
    equals: (a2, b) => !a2 === !b
  });
  return createMemo(
    () => {
      const c2 = condition();
      if (c2) {
        const child = props.children;
        const fn3 = typeof child === "function" && child.length > 0;
        return fn3 ? untrack(
          () => child(
            keyed ? c2 : () => {
              if (!untrack(condition)) throw narrowedError("Show");
              return conditionValue();
            }
          )
        ) : child;
      }
      return props.fallback;
    },
    void 0,
    void 0
  );
}
function Switch(props) {
  const chs = children(() => props.children);
  const switchFunc = createMemo(() => {
    const ch = chs();
    const mps = Array.isArray(ch) ? ch : [ch];
    let func2 = () => void 0;
    for (let i2 = 0; i2 < mps.length; i2++) {
      const index = i2;
      const mp = mps[i2];
      const prevFunc = func2;
      const conditionValue = createMemo(
        () => prevFunc() ? void 0 : mp.when,
        void 0,
        void 0
      );
      const condition = mp.keyed ? conditionValue : createMemo(conditionValue, void 0, {
        equals: (a2, b) => !a2 === !b
      });
      func2 = () => prevFunc() || (condition() ? [index, conditionValue, mp] : void 0);
    }
    return func2;
  });
  return createMemo(
    () => {
      const sel = switchFunc()();
      if (!sel) return props.fallback;
      const [index, conditionValue, mp] = sel;
      const child = mp.children;
      const fn3 = typeof child === "function" && child.length > 0;
      return fn3 ? untrack(
        () => child(
          mp.keyed ? conditionValue() : () => {
            if (untrack(switchFunc)()?.[0] !== index) throw narrowedError("Match");
            return conditionValue();
          }
        )
      ) : child;
    },
    void 0,
    void 0
  );
}
function Match(props) {
  return props;
}
const memo = (fn3) => createMemo(() => fn3());
function reconcileArrays(parentNode, a2, b) {
  let bLength = b.length, aEnd = a2.length, bEnd = bLength, aStart = 0, bStart = 0, after = a2[aEnd - 1].nextSibling, map2 = null;
  while (aStart < aEnd || bStart < bEnd) {
    if (a2[aStart] === b[bStart]) {
      aStart++;
      bStart++;
      continue;
    }
    while (a2[aEnd - 1] === b[bEnd - 1]) {
      aEnd--;
      bEnd--;
    }
    if (aEnd === aStart) {
      const node2 = bEnd < bLength ? bStart ? b[bStart - 1].nextSibling : b[bEnd - bStart] : after;
      while (bStart < bEnd) parentNode.insertBefore(b[bStart++], node2);
    } else if (bEnd === bStart) {
      while (aStart < aEnd) {
        if (!map2 || !map2.has(a2[aStart])) a2[aStart].remove();
        aStart++;
      }
    } else if (a2[aStart] === b[bEnd - 1] && b[bStart] === a2[aEnd - 1]) {
      const node2 = a2[--aEnd].nextSibling;
      parentNode.insertBefore(b[bStart++], a2[aStart++].nextSibling);
      parentNode.insertBefore(b[--bEnd], node2);
      a2[aEnd] = b[bEnd];
    } else {
      if (!map2) {
        map2 = /* @__PURE__ */ new Map();
        let i2 = bStart;
        while (i2 < bEnd) map2.set(b[i2], i2++);
      }
      const index = map2.get(a2[aStart]);
      if (index != null) {
        if (bStart < index && index < bEnd) {
          let i2 = aStart, sequence2 = 1, t2;
          while (++i2 < aEnd && i2 < bEnd) {
            if ((t2 = map2.get(a2[i2])) == null || t2 !== index + sequence2) break;
            sequence2++;
          }
          if (sequence2 > index - bStart) {
            const node2 = a2[aStart];
            while (bStart < index) parentNode.insertBefore(b[bStart++], node2);
          } else parentNode.replaceChild(b[bStart++], a2[aStart++]);
        } else aStart++;
      } else a2[aStart++].remove();
    }
  }
}
const $$EVENTS = "_$DX_DELEGATE";
function render(code2, element, init, options = {}) {
  let disposer;
  createRoot((dispose2) => {
    disposer = dispose2;
    element === document ? code2() : insert(element, code2(), element.firstChild ? null : void 0, init);
  }, options.owner);
  return () => {
    disposer();
    element.textContent = "";
  };
}
function template(html, isImportNode, isSVG, isMathML) {
  let node2;
  const create2 = () => {
    const t2 = document.createElement("template");
    t2.innerHTML = html;
    return t2.content.firstChild;
  };
  const fn3 = isImportNode ? () => untrack(() => document.importNode(node2 || (node2 = create2()), true)) : () => (node2 || (node2 = create2())).cloneNode(true);
  fn3.cloneNode = fn3;
  return fn3;
}
function delegateEvents(eventNames, document2 = window.document) {
  const e = document2[$$EVENTS] || (document2[$$EVENTS] = /* @__PURE__ */ new Set());
  for (let i2 = 0, l2 = eventNames.length; i2 < l2; i2++) {
    const name2 = eventNames[i2];
    if (!e.has(name2)) {
      e.add(name2);
      document2.addEventListener(name2, eventHandler);
    }
  }
}
function setAttribute(node2, name2, value2) {
  node2.removeAttribute(name2);
}
function className(node2, value2) {
  if (value2 == null) node2.removeAttribute("class");
  else node2.className = value2;
}
function addEventListener$1(node2, name2, handler, delegate) {
  {
    if (Array.isArray(handler)) {
      node2[`$$${name2}`] = handler[0];
      node2[`$$${name2}Data`] = handler[1];
    } else node2[`$$${name2}`] = handler;
  }
}
function style(node2, value2, prev) {
  if (!value2) return prev ? setAttribute(node2, "style") : value2;
  const nodeStyle = node2.style;
  if (typeof value2 === "string") return nodeStyle.cssText = value2;
  typeof prev === "string" && (nodeStyle.cssText = prev = void 0);
  prev || (prev = {});
  value2 || (value2 = {});
  let v, s;
  for (s in prev) {
    value2[s] == null && nodeStyle.removeProperty(s);
    delete prev[s];
  }
  for (s in value2) {
    v = value2[s];
    if (v !== prev[s]) {
      nodeStyle.setProperty(s, v);
      prev[s] = v;
    }
  }
  return prev;
}
function use(fn3, element, arg) {
  return untrack(() => fn3(element, arg));
}
function insert(parent, accessor, marker, initial) {
  if (marker !== void 0 && !initial) initial = [];
  if (typeof accessor !== "function") return insertExpression(parent, accessor, initial, marker);
  createRenderEffect((current3) => insertExpression(parent, accessor(), current3, marker), initial);
}
function eventHandler(e) {
  let node2 = e.target;
  const key2 = `$$${e.type}`;
  const oriTarget = e.target;
  const oriCurrentTarget = e.currentTarget;
  const retarget = (value2) => Object.defineProperty(e, "target", {
    configurable: true,
    value: value2
  });
  const handleNode = () => {
    const handler = node2[key2];
    if (handler && !node2.disabled) {
      const data2 = node2[`${key2}Data`];
      data2 !== void 0 ? handler.call(node2, data2, e) : handler.call(node2, e);
      if (e.cancelBubble) return;
    }
    node2.host && typeof node2.host !== "string" && !node2.host._$host && node2.contains(e.target) && retarget(node2.host);
    return true;
  };
  const walkUpTree = () => {
    while (handleNode() && (node2 = node2._$host || node2.parentNode || node2.host)) ;
  };
  Object.defineProperty(e, "currentTarget", {
    configurable: true,
    get() {
      return node2 || document;
    }
  });
  if (e.composedPath) {
    const path = e.composedPath();
    retarget(path[0]);
    for (let i2 = 0; i2 < path.length - 2; i2++) {
      node2 = path[i2];
      if (!handleNode()) break;
      if (node2._$host) {
        node2 = node2._$host;
        walkUpTree();
        break;
      }
      if (node2.parentNode === oriCurrentTarget) {
        break;
      }
    }
  } else walkUpTree();
  retarget(oriTarget);
}
function insertExpression(parent, value2, current3, marker, unwrapArray) {
  while (typeof current3 === "function") current3 = current3();
  if (value2 === current3) return current3;
  const t2 = typeof value2, multi = marker !== void 0;
  parent = multi && current3[0] && current3[0].parentNode || parent;
  if (t2 === "string" || t2 === "number") {
    if (t2 === "number") {
      value2 = value2.toString();
      if (value2 === current3) return current3;
    }
    if (multi) {
      let node2 = current3[0];
      if (node2 && node2.nodeType === 3) {
        node2.data !== value2 && (node2.data = value2);
      } else node2 = document.createTextNode(value2);
      current3 = cleanChildren(parent, current3, marker, node2);
    } else {
      if (current3 !== "" && typeof current3 === "string") {
        current3 = parent.firstChild.data = value2;
      } else current3 = parent.textContent = value2;
    }
  } else if (value2 == null || t2 === "boolean") {
    current3 = cleanChildren(parent, current3, marker);
  } else if (t2 === "function") {
    createRenderEffect(() => {
      let v = value2();
      while (typeof v === "function") v = v();
      current3 = insertExpression(parent, v, current3, marker);
    });
    return () => current3;
  } else if (Array.isArray(value2)) {
    const array2 = [];
    const currentArray = current3 && Array.isArray(current3);
    if (normalizeIncomingArray(array2, value2, current3, unwrapArray)) {
      createRenderEffect(() => current3 = insertExpression(parent, array2, current3, marker, true));
      return () => current3;
    }
    if (array2.length === 0) {
      current3 = cleanChildren(parent, current3, marker);
      if (multi) return current3;
    } else if (currentArray) {
      if (current3.length === 0) {
        appendNodes(parent, array2, marker);
      } else reconcileArrays(parent, current3, array2);
    } else {
      current3 && cleanChildren(parent);
      appendNodes(parent, array2);
    }
    current3 = array2;
  } else if (value2.nodeType) {
    if (Array.isArray(current3)) {
      if (multi) return current3 = cleanChildren(parent, current3, marker, value2);
      cleanChildren(parent, current3, null, value2);
    } else if (current3 == null || current3 === "" || !parent.firstChild) {
      parent.appendChild(value2);
    } else parent.replaceChild(value2, parent.firstChild);
    current3 = value2;
  } else ;
  return current3;
}
function normalizeIncomingArray(normalized, array2, current3, unwrap2) {
  let dynamic = false;
  for (let i2 = 0, len = array2.length; i2 < len; i2++) {
    let item2 = array2[i2], prev = current3 && current3[normalized.length], t2;
    if (item2 == null || item2 === true || item2 === false) ;
    else if ((t2 = typeof item2) === "object" && item2.nodeType) {
      normalized.push(item2);
    } else if (Array.isArray(item2)) {
      dynamic = normalizeIncomingArray(normalized, item2, prev) || dynamic;
    } else if (t2 === "function") {
      if (unwrap2) {
        while (typeof item2 === "function") item2 = item2();
        dynamic = normalizeIncomingArray(
          normalized,
          Array.isArray(item2) ? item2 : [item2],
          Array.isArray(prev) ? prev : [prev]
        ) || dynamic;
      } else {
        normalized.push(item2);
        dynamic = true;
      }
    } else {
      const value2 = String(item2);
      if (prev && prev.nodeType === 3 && prev.data === value2) normalized.push(prev);
      else normalized.push(document.createTextNode(value2));
    }
  }
  return dynamic;
}
function appendNodes(parent, array2, marker = null) {
  for (let i2 = 0, len = array2.length; i2 < len; i2++) parent.insertBefore(array2[i2], marker);
}
function cleanChildren(parent, current3, marker, replacement) {
  if (marker === void 0) return parent.textContent = "";
  const node2 = replacement || document.createTextNode("");
  if (current3.length) {
    let inserted = false;
    for (let i2 = current3.length - 1; i2 >= 0; i2--) {
      const el = current3[i2];
      if (node2 !== el) {
        const isParent = el.parentNode === parent;
        if (!inserted && !i2)
          isParent ? parent.replaceChild(node2, el) : parent.insertBefore(node2, marker);
        else isParent && el.remove();
      } else inserted = true;
    }
  } else parent.insertBefore(node2, marker);
  return [node2];
}
const $RAW = Symbol("store-raw"), $NODE = Symbol("store-node"), $HAS = Symbol("store-has"), $SELF = Symbol("store-self");
function wrap$1(value2) {
  let p = value2[$PROXY];
  if (!p) {
    Object.defineProperty(value2, $PROXY, {
      value: p = new Proxy(value2, proxyTraps$1)
    });
    if (!Array.isArray(value2)) {
      const keys2 = Object.keys(value2), desc = Object.getOwnPropertyDescriptors(value2);
      for (let i2 = 0, l2 = keys2.length; i2 < l2; i2++) {
        const prop = keys2[i2];
        if (desc[prop].get) {
          Object.defineProperty(value2, prop, {
            enumerable: desc[prop].enumerable,
            get: desc[prop].get.bind(p)
          });
        }
      }
    }
  }
  return p;
}
function isWrappable(obj) {
  let proto;
  return obj != null && typeof obj === "object" && (obj[$PROXY] || !(proto = Object.getPrototypeOf(obj)) || proto === Object.prototype || Array.isArray(obj));
}
function unwrap(item2, set3 = /* @__PURE__ */ new Set()) {
  let result2, unwrapped, v, prop;
  if (result2 = item2 != null && item2[$RAW]) return result2;
  if (!isWrappable(item2) || set3.has(item2)) return item2;
  if (Array.isArray(item2)) {
    if (Object.isFrozen(item2)) item2 = item2.slice(0);
    else set3.add(item2);
    for (let i2 = 0, l2 = item2.length; i2 < l2; i2++) {
      v = item2[i2];
      if ((unwrapped = unwrap(v, set3)) !== v) item2[i2] = unwrapped;
    }
  } else {
    if (Object.isFrozen(item2)) item2 = Object.assign({}, item2);
    else set3.add(item2);
    const keys2 = Object.keys(item2), desc = Object.getOwnPropertyDescriptors(item2);
    for (let i2 = 0, l2 = keys2.length; i2 < l2; i2++) {
      prop = keys2[i2];
      if (desc[prop].get) continue;
      v = item2[prop];
      if ((unwrapped = unwrap(v, set3)) !== v) item2[prop] = unwrapped;
    }
  }
  return item2;
}
function getNodes(target, symbol) {
  let nodes = target[symbol];
  if (!nodes)
    Object.defineProperty(target, symbol, {
      value: nodes = /* @__PURE__ */ Object.create(null)
    });
  return nodes;
}
function getNode(nodes, property, value2) {
  if (nodes[property]) return nodes[property];
  const [s, set3] = createSignal(value2, {
    equals: false,
    internal: true
  });
  s.$ = set3;
  return nodes[property] = s;
}
function proxyDescriptor$1(target, property) {
  const desc = Reflect.getOwnPropertyDescriptor(target, property);
  if (!desc || desc.get || !desc.configurable || property === $PROXY || property === $NODE)
    return desc;
  delete desc.value;
  delete desc.writable;
  desc.get = () => target[$PROXY][property];
  return desc;
}
function trackSelf(target) {
  getListener() && getNode(getNodes(target, $NODE), $SELF)();
}
function ownKeys(target) {
  trackSelf(target);
  return Reflect.ownKeys(target);
}
const proxyTraps$1 = {
  get(target, property, receiver) {
    if (property === $RAW) return target;
    if (property === $PROXY) return receiver;
    if (property === $TRACK) {
      trackSelf(target);
      return receiver;
    }
    const nodes = getNodes(target, $NODE);
    const tracked = nodes[property];
    let value2 = tracked ? tracked() : target[property];
    if (property === $NODE || property === $HAS || property === "__proto__") return value2;
    if (!tracked) {
      const desc = Object.getOwnPropertyDescriptor(target, property);
      if (getListener() && (typeof value2 !== "function" || target.hasOwnProperty(property)) && !(desc && desc.get))
        value2 = getNode(nodes, property, value2)();
    }
    return isWrappable(value2) ? wrap$1(value2) : value2;
  },
  has(target, property) {
    if (property === $RAW || property === $PROXY || property === $TRACK || property === $NODE || property === $HAS || property === "__proto__")
      return true;
    getListener() && getNode(getNodes(target, $HAS), property)();
    return property in target;
  },
  set() {
    return true;
  },
  deleteProperty() {
    return true;
  },
  ownKeys,
  getOwnPropertyDescriptor: proxyDescriptor$1
};
function setProperty(state, property, value2, deleting = false) {
  if (!deleting && state[property] === value2) return;
  const prev = state[property], len = state.length;
  if (value2 === void 0) {
    delete state[property];
    if (state[$HAS] && state[$HAS][property] && prev !== void 0) state[$HAS][property].$();
  } else {
    state[property] = value2;
    if (state[$HAS] && state[$HAS][property] && prev === void 0) state[$HAS][property].$();
  }
  let nodes = getNodes(state, $NODE), node2;
  if (node2 = getNode(nodes, property, prev)) node2.$(() => value2);
  if (Array.isArray(state) && state.length !== len) {
    for (let i2 = state.length; i2 < len; i2++) (node2 = nodes[i2]) && node2.$();
    (node2 = getNode(nodes, "length", len)) && node2.$(state.length);
  }
  (node2 = nodes[$SELF]) && node2.$();
}
function mergeStoreNode(state, value2) {
  const keys2 = Object.keys(value2);
  for (let i2 = 0; i2 < keys2.length; i2 += 1) {
    const key2 = keys2[i2];
    setProperty(state, key2, value2[key2]);
  }
}
function updateArray(current3, next) {
  if (typeof next === "function") next = next(current3);
  next = unwrap(next);
  if (Array.isArray(next)) {
    if (current3 === next) return;
    let i2 = 0, len = next.length;
    for (; i2 < len; i2++) {
      const value2 = next[i2];
      if (current3[i2] !== value2) setProperty(current3, i2, value2);
    }
    setProperty(current3, "length", len);
  } else mergeStoreNode(current3, next);
}
function updatePath(current3, path, traversed = []) {
  let part, prev = current3;
  if (path.length > 1) {
    part = path.shift();
    const partType = typeof part, isArray2 = Array.isArray(current3);
    if (Array.isArray(part)) {
      for (let i2 = 0; i2 < part.length; i2++) {
        updatePath(current3, [part[i2]].concat(path), traversed);
      }
      return;
    } else if (isArray2 && partType === "function") {
      for (let i2 = 0; i2 < current3.length; i2++) {
        if (part(current3[i2], i2)) updatePath(current3, [i2].concat(path), traversed);
      }
      return;
    } else if (isArray2 && partType === "object") {
      const { from: from2 = 0, to: to2 = current3.length - 1, by = 1 } = part;
      for (let i2 = from2; i2 <= to2; i2 += by) {
        updatePath(current3, [i2].concat(path), traversed);
      }
      return;
    } else if (path.length > 1) {
      updatePath(current3[part], path, [part].concat(traversed));
      return;
    }
    prev = current3[part];
    traversed = [part].concat(traversed);
  }
  let value2 = path[0];
  if (typeof value2 === "function") {
    value2 = value2(prev, traversed);
    if (value2 === prev) return;
  }
  if (part === void 0 && value2 == void 0) return;
  value2 = unwrap(value2);
  if (part === void 0 || isWrappable(prev) && isWrappable(value2) && !Array.isArray(value2)) {
    mergeStoreNode(prev, value2);
  } else setProperty(current3, part, value2);
}
function createStore(...[store2, options]) {
  const unwrappedStore = unwrap(store2 || {});
  const isArray2 = Array.isArray(unwrappedStore);
  const wrappedStore = wrap$1(unwrappedStore);
  function setStore(...args2) {
    batch(() => {
      isArray2 && args2.length === 1 ? updateArray(unwrappedStore, args2[0]) : updatePath(unwrappedStore, args2);
    });
  }
  return [wrappedStore, setStore];
}
const $ROOT = Symbol("store-root");
function applyState(target, parent, property, merge, key2) {
  const previous = parent[property];
  if (target === previous) return;
  const isArray2 = Array.isArray(target);
  if (property !== $ROOT && (!isWrappable(target) || !isWrappable(previous) || isArray2 !== Array.isArray(previous) || key2 && target[key2] !== previous[key2])) {
    setProperty(parent, property, target);
    return;
  }
  if (isArray2) {
    if (target.length && previous.length && (!merge || key2 && target[0] && target[0][key2] != null)) {
      let i2, j2, start2, end2, newEnd, item2, newIndicesNext, keyVal;
      for (start2 = 0, end2 = Math.min(previous.length, target.length); start2 < end2 && (previous[start2] === target[start2] || key2 && previous[start2] && target[start2] && previous[start2][key2] === target[start2][key2]); start2++) {
        applyState(target[start2], previous, start2, merge, key2);
      }
      const temp = new Array(target.length), newIndices = /* @__PURE__ */ new Map();
      for (end2 = previous.length - 1, newEnd = target.length - 1; end2 >= start2 && newEnd >= start2 && (previous[end2] === target[newEnd] || key2 && previous[end2] && target[newEnd] && previous[end2][key2] === target[newEnd][key2]); end2--, newEnd--) {
        temp[newEnd] = previous[end2];
      }
      if (start2 > newEnd || start2 > end2) {
        for (j2 = start2; j2 <= newEnd; j2++) setProperty(previous, j2, target[j2]);
        for (; j2 < target.length; j2++) {
          setProperty(previous, j2, temp[j2]);
          applyState(target[j2], previous, j2, merge, key2);
        }
        if (previous.length > target.length) setProperty(previous, "length", target.length);
        return;
      }
      newIndicesNext = new Array(newEnd + 1);
      for (j2 = newEnd; j2 >= start2; j2--) {
        item2 = target[j2];
        keyVal = key2 && item2 ? item2[key2] : item2;
        i2 = newIndices.get(keyVal);
        newIndicesNext[j2] = i2 === void 0 ? -1 : i2;
        newIndices.set(keyVal, j2);
      }
      for (i2 = start2; i2 <= end2; i2++) {
        item2 = previous[i2];
        keyVal = key2 && item2 ? item2[key2] : item2;
        j2 = newIndices.get(keyVal);
        if (j2 !== void 0 && j2 !== -1) {
          temp[j2] = previous[i2];
          j2 = newIndicesNext[j2];
          newIndices.set(keyVal, j2);
        }
      }
      for (j2 = start2; j2 < target.length; j2++) {
        if (j2 in temp) {
          setProperty(previous, j2, temp[j2]);
          applyState(target[j2], previous, j2, merge, key2);
        } else setProperty(previous, j2, target[j2]);
      }
    } else {
      for (let i2 = 0, len = target.length; i2 < len; i2++) {
        applyState(target[i2], previous, i2, merge, key2);
      }
    }
    if (previous.length > target.length) setProperty(previous, "length", target.length);
    return;
  }
  const targetKeys = Object.keys(target);
  for (let i2 = 0, len = targetKeys.length; i2 < len; i2++) {
    applyState(target[targetKeys[i2]], previous, targetKeys[i2], merge, key2);
  }
  const previousKeys = Object.keys(previous);
  for (let i2 = 0, len = previousKeys.length; i2 < len; i2++) {
    if (target[previousKeys[i2]] === void 0) setProperty(previous, previousKeys[i2], void 0);
  }
}
function reconcile(value2, options = {}) {
  const { merge, key: key2 = "id" } = options, v = unwrap(value2);
  return (state) => {
    if (!isWrappable(state) || !isWrappable(v)) return v;
    const res = applyState(
      v,
      {
        [$ROOT]: state
      },
      $ROOT,
      merge,
      key2
    );
    return res === void 0 ? state : res;
  };
}
const noop = () => {
};
const noopTransition = (el, done) => done();
function createSwitchTransition(source2, options) {
  const initSource = untrack(source2);
  const initReturned = initSource ? [initSource] : [];
  const { onEnter = noopTransition, onExit = noopTransition } = options;
  const [returned, setReturned] = createSignal(options.appear ? [] : initReturned);
  const [isTransitionPending] = useTransition();
  let next;
  let isExiting = false;
  function exitTransition2(el, after) {
    if (!el)
      return after && after();
    isExiting = true;
    onExit(el, () => {
      batch(() => {
        isExiting = false;
        setReturned((p) => p.filter((e) => e !== el));
        after && after();
      });
    });
  }
  function enterTransition2(after) {
    const el = next;
    if (!el)
      return after && after();
    next = void 0;
    setReturned((p) => [el, ...p]);
    onEnter(el, after ?? noop);
  }
  const triggerTransitions = options.mode === "out-in" ? (
    // exit -> enter
    // exit -> enter
    (prev) => isExiting || exitTransition2(prev, enterTransition2)
  ) : options.mode === "in-out" ? (
    // enter -> exit
    // enter -> exit
    (prev) => enterTransition2(() => exitTransition2(prev))
  ) : (
    // exit & enter
    // exit & enter
    (prev) => {
      exitTransition2(prev);
      enterTransition2();
    }
  );
  createComputed((prev) => {
    const el = source2();
    if (untrack(isTransitionPending)) {
      isTransitionPending();
      return prev;
    }
    if (el !== prev) {
      next = el;
      batch(() => untrack(() => triggerTransitions(prev)));
    }
    return el;
  }, options.appear ? void 0 : initSource);
  return returned;
}
const defaultElementPredicate = (item2) => item2 instanceof Element;
function getFirstChild(value2, predicate) {
  if (predicate(value2))
    return value2;
  if (typeof value2 === "function" && !value2.length)
    return getFirstChild(value2(), predicate);
  if (Array.isArray(value2)) {
    for (const item2 of value2) {
      const result2 = getFirstChild(item2, predicate);
      if (result2)
        return result2;
    }
  }
  return null;
}
function resolveFirst(fn3, predicate = defaultElementPredicate, serverPredicate = defaultElementPredicate) {
  const children2 = createMemo(fn3);
  return createMemo(() => getFirstChild(children2(), predicate));
}
function createClassnames(props) {
  return createMemo(() => {
    const name2 = props.name || "s";
    return {
      enterActive: (props.enterActiveClass || name2 + "-enter-active").split(" "),
      enter: (props.enterClass || name2 + "-enter").split(" "),
      enterTo: (props.enterToClass || name2 + "-enter-to").split(" "),
      exitActive: (props.exitActiveClass || name2 + "-exit-active").split(" "),
      exit: (props.exitClass || name2 + "-exit").split(" "),
      exitTo: (props.exitToClass || name2 + "-exit-to").split(" "),
      move: (props.moveClass || name2 + "-move").split(" ")
    };
  });
}
function nextFrame(fn3) {
  requestAnimationFrame(() => requestAnimationFrame(fn3));
}
function enterTransition(classes, events, el, done) {
  const { onBeforeEnter, onEnter, onAfterEnter } = events;
  onBeforeEnter?.(el);
  el.classList.add(...classes.enter);
  el.classList.add(...classes.enterActive);
  queueMicrotask(() => {
    if (!el.parentNode)
      return done?.();
    onEnter?.(el, () => endTransition());
  });
  nextFrame(() => {
    el.classList.remove(...classes.enter);
    el.classList.add(...classes.enterTo);
    if (!onEnter || onEnter.length < 2) {
      el.addEventListener("transitionend", endTransition);
      el.addEventListener("animationend", endTransition);
    }
  });
  function endTransition(e) {
    if (!e || e.target === el) {
      done?.();
      el.removeEventListener("transitionend", endTransition);
      el.removeEventListener("animationend", endTransition);
      el.classList.remove(...classes.enterActive);
      el.classList.remove(...classes.enterTo);
      onAfterEnter?.(el);
    }
  }
}
function exitTransition(classes, events, el, done) {
  const { onBeforeExit, onExit, onAfterExit } = events;
  if (!el.parentNode)
    return done?.();
  onBeforeExit?.(el);
  el.classList.add(...classes.exit);
  el.classList.add(...classes.exitActive);
  onExit?.(el, () => endTransition());
  nextFrame(() => {
    el.classList.remove(...classes.exit);
    el.classList.add(...classes.exitTo);
    if (!onExit || onExit.length < 2) {
      el.addEventListener("transitionend", endTransition);
      el.addEventListener("animationend", endTransition);
    }
  });
  function endTransition(e) {
    if (!e || e.target === el) {
      done?.();
      el.removeEventListener("transitionend", endTransition);
      el.removeEventListener("animationend", endTransition);
      el.classList.remove(...classes.exitActive);
      el.classList.remove(...classes.exitTo);
      onAfterExit?.(el);
    }
  }
}
var TRANSITION_MODE_MAP = {
  inout: "in-out",
  outin: "out-in"
};
var Transition = (props) => {
  const classnames = createClassnames(props);
  return createSwitchTransition(
    resolveFirst(() => props.children),
    {
      mode: TRANSITION_MODE_MAP[props.mode],
      appear: props.appear,
      onEnter(el, done) {
        enterTransition(classnames(), props, el, done);
      },
      onExit(el, done) {
        exitTransition(classnames(), props, el, done);
      }
    }
  );
};
const _tmpl$$g = /* @__PURE__ */ template(`<span></span>`, 2);
var Segment = ((props) => {
  const codePoint = createMemo(() => {
    if (props.text.length == 1) {
      const cp = props.text.codePointAt(0);
      if (cp >= 9600 && cp <= 9631 || cp == 57520 || cp == 57522) {
        return cp;
      }
    }
  });
  const text2 = createMemo(() => codePoint() ? " " : props.text);
  const style$1 = createMemo(() => buildStyle(props.pen, props.offset, props.cellCount));
  const className$1 = createMemo(() => buildClassName(props.pen, codePoint(), props.extraClass));
  return (() => {
    const _el$ = _tmpl$$g.cloneNode(true);
    insert(_el$, text2);
    createRenderEffect((_p$) => {
      const _v$ = className$1(), _v$2 = style$1();
      _v$ !== _p$._v$ && className(_el$, _p$._v$ = _v$);
      _p$._v$2 = style(_el$, _v$2, _p$._v$2);
      return _p$;
    }, {
      _v$: void 0,
      _v$2: void 0
    });
    return _el$;
  })();
});
function buildClassName(attrs, codePoint, extraClass) {
  const fgClass = colorClass(attrs.get("fg"), attrs.get("bold"), "fg-");
  const bgClass = colorClass(attrs.get("bg"), false, "bg-");
  let cls = extraClass ?? "";
  if (codePoint !== void 0) {
    cls += ` cp-${codePoint.toString(16)}`;
  }
  if (fgClass) {
    cls += " " + fgClass;
  }
  if (bgClass) {
    cls += " " + bgClass;
  }
  if (attrs.has("bold")) {
    cls += " ap-bright";
  }
  if (attrs.has("faint")) {
    cls += " ap-faint";
  }
  if (attrs.has("italic")) {
    cls += " ap-italic";
  }
  if (attrs.has("underline")) {
    cls += " ap-underline";
  }
  if (attrs.has("blink")) {
    cls += " ap-blink";
  }
  if (attrs.get("inverse")) {
    cls += " ap-inverse";
  }
  return cls;
}
function colorClass(color, intense, prefix) {
  if (typeof color === "number") {
    if (intense && color < 8) {
      color += 8;
    }
    return `${prefix}${color}`;
  }
}
function buildStyle(attrs, offset3, width) {
  const fg = attrs.get("fg");
  const bg = attrs.get("bg");
  let style2 = {
    "--offset": offset3,
    width: `${width + 0.01}ch`
  };
  if (typeof fg === "string") {
    style2["--fg"] = fg;
  }
  if (typeof bg === "string") {
    style2["--bg"] = bg;
  }
  return style2;
}
const _tmpl$$f = /* @__PURE__ */ template(`<span class="ap-line" role="paragraph"></span>`, 2);
var Line = ((props) => {
  const segments = () => {
    if (typeof props.cursor === "number") {
      const segs = [];
      let cellOffset = 0;
      let segIndex = 0;
      while (segIndex < props.segments.length && cellOffset + props.segments[segIndex].cellCount - 1 < props.cursor) {
        const seg = props.segments[segIndex];
        segs.push(seg);
        cellOffset += seg.cellCount;
        segIndex++;
      }
      if (segIndex < props.segments.length) {
        const seg = props.segments[segIndex];
        const charWidth = seg.charWidth;
        let cellIndex = props.cursor - cellOffset;
        const charIndex = Math.floor(cellIndex / charWidth);
        cellIndex = charIndex * charWidth;
        const chars = Array.from(seg.text);
        if (charIndex > 0) {
          segs.push({
            ...seg,
            text: chars.slice(0, charIndex).join("")
          });
        }
        segs.push({
          ...seg,
          text: chars[charIndex],
          offset: cellOffset + cellIndex,
          cellCount: charWidth,
          extraClass: "ap-cursor"
        });
        if (charIndex < chars.length - 1) {
          segs.push({
            ...seg,
            text: chars.slice(charIndex + 1).join(""),
            offset: cellOffset + cellIndex + 1,
            cellCount: seg.cellCount - charWidth
          });
        }
        segIndex++;
        while (segIndex < props.segments.length) {
          const seg2 = props.segments[segIndex];
          segs.push(seg2);
          segIndex++;
        }
      }
      return segs;
    } else {
      return props.segments;
    }
  };
  return (() => {
    const _el$ = _tmpl$$f.cloneNode(true);
    insert(_el$, createComponent(Index, {
      get each() {
        return segments();
      },
      children: (s) => createComponent(Segment, mergeProps(s))
    }));
    return _el$;
  })();
});
const _tmpl$$e = /* @__PURE__ */ template(`<pre class="ap-terminal" aria-live="off" tabindex="0"></pre>`, 2);
var Terminal = ((props) => {
  const lineHeight = () => props.lineHeight ?? 1.3333333333;
  const style$1 = createMemo(() => {
    return {
      width: `${props.cols}ch`,
      height: `${lineHeight() * props.rows}em`,
      "font-size": `${(props.scale || 1) * 100}%`,
      "font-family": props.fontFamily,
      "--term-line-height": `${lineHeight()}em`,
      "--term-cols": props.cols
    };
  });
  const cursorCol = createMemo(() => props.cursor?.[0]);
  const cursorRow = createMemo(() => props.cursor?.[1]);
  return (() => {
    const _el$ = _tmpl$$e.cloneNode(true);
    const _ref$ = props.ref;
    typeof _ref$ === "function" ? use(_ref$, _el$) : props.ref = _el$;
    insert(_el$, createComponent(For, {
      get each() {
        return props.lines;
      },
      children: (line2, i2) => createComponent(Line, {
        get segments() {
          return line2.segments;
        },
        get cursor() {
          return memo(() => i2() === cursorRow())() ? cursorCol() : null;
        }
      })
    }));
    createRenderEffect((_p$) => {
      const _v$ = !!(props.blink || props.cursorHold), _v$2 = !!props.blink, _v$3 = style$1();
      _v$ !== _p$._v$ && _el$.classList.toggle("ap-cursor-on", _p$._v$ = _v$);
      _v$2 !== _p$._v$2 && _el$.classList.toggle("ap-blink", _p$._v$2 = _v$2);
      _p$._v$3 = style(_el$, _v$3, _p$._v$3);
      return _p$;
    }, {
      _v$: void 0,
      _v$2: void 0,
      _v$3: void 0
    });
    return _el$;
  })();
});
const _tmpl$$d = /* @__PURE__ */ template(`<svg version="1.1" viewBox="0 0 12 12" class="ap-icon ap-icon-fullscreen-off"><path d="M7,5 L7,0 L9,2 L11,0 L12,1 L10,3 L12,5 Z"></path><path d="M5,7 L0,7 L2,9 L0,11 L1,12 L3,10 L5,12 Z"></path></svg>`, 6);
var ExpandIcon = ((props) => {
  return _tmpl$$d.cloneNode(true);
});
const _tmpl$$c = /* @__PURE__ */ template(`<svg version="1.1" viewBox="6 8 14 16" class="ap-icon"><path d="M0.938 8.313h22.125c0.5 0 0.938 0.438 0.938 0.938v13.5c0 0.5-0.438 0.938-0.938 0.938h-22.125c-0.5 0-0.938-0.438-0.938-0.938v-13.5c0-0.5 0.438-0.938 0.938-0.938zM1.594 22.063h20.813v-12.156h-20.813v12.156zM3.844 11.188h1.906v1.938h-1.906v-1.938zM7.469 11.188h1.906v1.938h-1.906v-1.938zM11.031 11.188h1.938v1.938h-1.938v-1.938zM14.656 11.188h1.875v1.938h-1.875v-1.938zM18.25 11.188h1.906v1.938h-1.906v-1.938zM5.656 15.031h1.938v1.938h-1.938v-1.938zM9.281 16.969v-1.938h1.906v1.938h-1.906zM12.875 16.969v-1.938h1.906v1.938h-1.906zM18.406 16.969h-1.938v-1.938h1.938v1.938zM16.531 20.781h-9.063v-1.906h9.063v1.906z"></path></svg>`, 4);
var KeyboardIcon = ((props) => {
  return _tmpl$$c.cloneNode(true);
});
const _tmpl$$b = /* @__PURE__ */ template(`<svg version="1.1" viewBox="0 0 12 12" class="ap-icon" aria-label="Pause" role="button"><path d="M1,0 L4,0 L4,12 L1,12 Z"></path><path d="M8,0 L11,0 L11,12 L8,12 Z"></path></svg>`, 6);
var PauseIcon = ((props) => {
  return _tmpl$$b.cloneNode(true);
});
const _tmpl$$a = /* @__PURE__ */ template(`<svg version="1.1" viewBox="0 0 12 12" class="ap-icon" aria-label="Play" role="button"><path d="M1,0 L11,6 L1,12 Z"></path></svg>`, 4);
var PlayIcon = ((props) => {
  return _tmpl$$a.cloneNode(true);
});
const _tmpl$$9 = /* @__PURE__ */ template(`<svg version="1.1" viewBox="0 0 12 12" class="ap-icon ap-icon-fullscreen-on"><path d="M12,0 L7,0 L9,2 L7,4 L8,5 L10,3 L12,5 Z"></path><path d="M0,12 L0,7 L2,9 L4,7 L5,8 L3,10 L5,12 Z"></path></svg>`, 6);
var ShrinkIcon = ((props) => {
  return _tmpl$$9.cloneNode(true);
});
const _tmpl$$8 = /* @__PURE__ */ template(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor"><path d="M10.5 3.75a.75.75 0 0 0-1.264-.546L5.203 7H2.667a.75.75 0 0 0-.7.48A6.985 6.985 0 0 0 1.5 10c0 .887.165 1.737.468 2.52.111.29.39.48.7.48h2.535l4.033 3.796a.75.75 0 0 0 1.264-.546V3.75ZM16.45 5.05a.75.75 0 0 0-1.06 1.061 5.5 5.5 0 0 1 0 7.778.75.75 0 0 0 1.06 1.06 7 7 0 0 0 0-9.899Z"></path><path d="M14.329 7.172a.75.75 0 0 0-1.061 1.06 2.5 2.5 0 0 1 0 3.536.75.75 0 0 0 1.06 1.06 4 4 0 0 0 0-5.656Z"></path></svg>`, 6);
var SpeakerOnIcon = ((props) => {
  return _tmpl$$8.cloneNode(true);
});
const _tmpl$$7 = /* @__PURE__ */ template(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="size-5"><path d="M10.047 3.062a.75.75 0 0 1 .453.688v12.5a.75.75 0 0 1-1.264.546L5.203 13H2.667a.75.75 0 0 1-.7-.48A6.985 6.985 0 0 1 1.5 10c0-.887.165-1.737.468-2.52a.75.75 0 0 1 .7-.48h2.535l4.033-3.796a.75.75 0 0 1 .811-.142ZM13.78 7.22a.75.75 0 1 0-1.06 1.06L14.44 10l-1.72 1.72a.75.75 0 0 0 1.06 1.06l1.72-1.72 1.72 1.72a.75.75 0 1 0 1.06-1.06L16.56 10l1.72-1.72a.75.75 0 0 0-1.06-1.06L15.5 8.94l-1.72-1.72Z"></path></svg>`, 4);
var SpeakerOffIcon = ((props) => {
  return _tmpl$$7.cloneNode(true);
});
const _tmpl$$6 = /* @__PURE__ */ template(`<span class="ap-button ap-playback-button" tabindex="0"></span>`, 2), _tmpl$2$1 = /* @__PURE__ */ template(`<span class="ap-bar"><span class="ap-gutter ap-gutter-empty"></span><span class="ap-gutter ap-gutter-full"></span></span>`, 6), _tmpl$3$1 = /* @__PURE__ */ template(`<span class="ap-tooltip">Unmute (m)</span>`, 2), _tmpl$4$1 = /* @__PURE__ */ template(`<span class="ap-tooltip">Mute (m)</span>`, 2), _tmpl$5$1 = /* @__PURE__ */ template(`<span class="ap-button ap-speaker-button ap-tooltip-container" aria-label="Mute / unmute" role="button" tabindex="0"></span>`, 2), _tmpl$6$1 = /* @__PURE__ */ template(`<div class="ap-control-bar"><span class="ap-timer" aria-readonly="true" role="textbox" tabindex="0"><span class="ap-time-elapsed"></span><span class="ap-time-remaining"></span></span><span class="ap-progressbar"></span><span class="ap-button ap-kbd-button ap-tooltip-container" aria-label="Show keyboard shortcuts" role="button" tabindex="0"><span class="ap-tooltip">Keyboard shortcuts (?)</span></span><span class="ap-button ap-fullscreen-button ap-tooltip-container" aria-label="Toggle fullscreen mode" role="button" tabindex="0"><span class="ap-tooltip">Fullscreen (f)</span></span></div>`, 18), _tmpl$7$1 = /* @__PURE__ */ template(`<span class="ap-marker-container ap-tooltip-container"><span class="ap-marker"></span><span class="ap-tooltip"></span></span>`, 6);
function formatTime(seconds2) {
  let s = Math.floor(seconds2);
  const d = Math.floor(s / 86400);
  s %= 86400;
  const h = Math.floor(s / 3600);
  s %= 3600;
  const m = Math.floor(s / 60);
  s %= 60;
  if (d > 0) {
    return `${zeroPad(d)}:${zeroPad(h)}:${zeroPad(m)}:${zeroPad(s)}`;
  } else if (h > 0) {
    return `${zeroPad(h)}:${zeroPad(m)}:${zeroPad(s)}`;
  } else {
    return `${zeroPad(m)}:${zeroPad(s)}`;
  }
}
function zeroPad(n2) {
  return n2 < 10 ? `0${n2}` : n2.toString();
}
var ControlBar = ((props) => {
  const e = (f) => {
    return (e2) => {
      e2.preventDefault();
      f(e2);
    };
  };
  const currentTime = () => typeof props.currentTime === "number" ? formatTime(props.currentTime) : "--:--";
  const remainingTime = () => typeof props.remainingTime === "number" ? "-" + formatTime(props.remainingTime) : currentTime();
  const markers = createMemo(() => typeof props.duration === "number" ? props.markers.filter((m) => m[0] < props.duration) : []);
  const markerPosition = (m) => `${m[0] / props.duration * 100}%`;
  const markerText = (m) => {
    if (m[1] === "") {
      return formatTime(m[0]);
    } else {
      return `${formatTime(m[0])} - ${m[1]}`;
    }
  };
  const isPastMarker = (m) => typeof props.currentTime === "number" ? m[0] <= props.currentTime : false;
  const gutterBarStyle = () => {
    return {
      transform: `scaleX(${props.progress || 0}`
    };
  };
  const calcPosition = (e2) => {
    const barWidth = e2.currentTarget.offsetWidth;
    const rect = e2.currentTarget.getBoundingClientRect();
    const mouseX = e2.clientX - rect.left;
    const pos2 = Math.max(0, mouseX / barWidth);
    return `${pos2 * 100}%`;
  };
  const [mouseDown, setMouseDown] = createSignal(false);
  const throttledSeek = throttle(props.onSeekClick, 50);
  const onMouseDown = (e2) => {
    if (e2._marker) return;
    if (e2.altKey || e2.shiftKey || e2.metaKey || e2.ctrlKey || e2.button !== 0) return;
    setMouseDown(true);
    props.onSeekClick(calcPosition(e2));
  };
  const seekToMarker = (index) => {
    return e(() => {
      props.onSeekClick({
        marker: index
      });
    });
  };
  const onMove = (e2) => {
    if (e2.altKey || e2.shiftKey || e2.metaKey || e2.ctrlKey) return;
    if (mouseDown()) {
      throttledSeek(calcPosition(e2));
    }
  };
  const onDocumentMouseUp = () => {
    setMouseDown(false);
  };
  document.addEventListener("mouseup", onDocumentMouseUp);
  onCleanup(() => {
    document.removeEventListener("mouseup", onDocumentMouseUp);
  });
  return (() => {
    const _el$ = _tmpl$6$1.cloneNode(true), _el$3 = _el$.firstChild, _el$4 = _el$3.firstChild, _el$5 = _el$4.nextSibling, _el$6 = _el$3.nextSibling, _el$13 = _el$6.nextSibling, _el$14 = _el$13.firstChild, _el$15 = _el$13.nextSibling, _el$16 = _el$15.firstChild;
    const _ref$ = props.ref;
    typeof _ref$ === "function" ? use(_ref$, _el$) : props.ref = _el$;
    insert(_el$, createComponent(Show, {
      get when() {
        return props.isPausable;
      },
      get children() {
        const _el$2 = _tmpl$$6.cloneNode(true);
        addEventListener$1(_el$2, "click", e(props.onPlayClick));
        insert(_el$2, createComponent(Switch, {
          get children() {
            return [createComponent(Match, {
              get when() {
                return props.isPlaying;
              },
              get children() {
                return createComponent(PauseIcon, {});
              }
            }), createComponent(Match, {
              when: true,
              get children() {
                return createComponent(PlayIcon, {});
              }
            })];
          }
        }));
        return _el$2;
      }
    }), _el$3);
    insert(_el$4, currentTime);
    insert(_el$5, remainingTime);
    insert(_el$6, createComponent(Show, {
      get when() {
        return typeof props.progress === "number" || props.isSeekable;
      },
      get children() {
        const _el$7 = _tmpl$2$1.cloneNode(true), _el$8 = _el$7.firstChild, _el$9 = _el$8.nextSibling;
        _el$7.$$mousemove = onMove;
        _el$7.$$mousedown = onMouseDown;
        insert(_el$7, createComponent(For, {
          get each() {
            return markers();
          },
          children: (m, i2) => (() => {
            const _el$17 = _tmpl$7$1.cloneNode(true), _el$18 = _el$17.firstChild, _el$19 = _el$18.nextSibling;
            _el$17.$$mousedown = (e2) => {
              e2._marker = true;
            };
            addEventListener$1(_el$17, "click", seekToMarker(i2()));
            insert(_el$19, () => markerText(m));
            createRenderEffect((_p$) => {
              const _v$ = markerPosition(m), _v$2 = !!isPastMarker(m);
              _v$ !== _p$._v$ && _el$17.style.setProperty("left", _p$._v$ = _v$);
              _v$2 !== _p$._v$2 && _el$18.classList.toggle("ap-marker-past", _p$._v$2 = _v$2);
              return _p$;
            }, {
              _v$: void 0,
              _v$2: void 0
            });
            return _el$17;
          })()
        }), null);
        createRenderEffect((_$p) => style(_el$9, gutterBarStyle(), _$p));
        return _el$7;
      }
    }));
    insert(_el$, createComponent(Show, {
      get when() {
        return props.isMuted !== void 0;
      },
      get children() {
        const _el$10 = _tmpl$5$1.cloneNode(true);
        addEventListener$1(_el$10, "click", e(props.onMuteClick));
        insert(_el$10, createComponent(Switch, {
          get children() {
            return [createComponent(Match, {
              get when() {
                return props.isMuted === true;
              },
              get children() {
                return [createComponent(SpeakerOffIcon, {}), _tmpl$3$1.cloneNode(true)];
              }
            }), createComponent(Match, {
              get when() {
                return props.isMuted === false;
              },
              get children() {
                return [createComponent(SpeakerOnIcon, {}), _tmpl$4$1.cloneNode(true)];
              }
            })];
          }
        }));
        return _el$10;
      }
    }), _el$13);
    addEventListener$1(_el$13, "click", e(props.onHelpClick));
    insert(_el$13, createComponent(KeyboardIcon, {}), _el$14);
    addEventListener$1(_el$15, "click", e(props.onFullscreenClick));
    insert(_el$15, createComponent(ShrinkIcon, {}), _el$16);
    insert(_el$15, createComponent(ExpandIcon, {}), _el$16);
    createRenderEffect(() => _el$.classList.toggle("ap-seekable", !!props.isSeekable));
    return _el$;
  })();
});
delegateEvents(["click", "mousedown", "mousemove"]);
const _tmpl$$5 = /* @__PURE__ */ template(`<div class="ap-overlay ap-overlay-error"><span>💥</span></div>`, 4);
var ErrorOverlay = ((props) => {
  return _tmpl$$5.cloneNode(true);
});
const _tmpl$$4 = /* @__PURE__ */ template(`<div class="ap-overlay ap-overlay-loading"><span class="ap-loader"></span></div>`, 4);
var LoaderOverlay = ((props) => {
  return _tmpl$$4.cloneNode(true);
});
const _tmpl$$3 = /* @__PURE__ */ template(`<div class="ap-overlay ap-overlay-info"><span></span></div>`, 4);
var InfoOverlay = ((props) => {
  const style$1 = () => {
    return {
      "font-family": props.fontFamily
    };
  };
  return (() => {
    const _el$ = _tmpl$$3.cloneNode(true), _el$2 = _el$.firstChild;
    insert(_el$2, () => props.message);
    createRenderEffect((_p$) => {
      const _v$ = !!props.wasPlaying, _v$2 = style$1();
      _v$ !== _p$._v$ && _el$.classList.toggle("ap-was-playing", _p$._v$ = _v$);
      _p$._v$2 = style(_el$2, _v$2, _p$._v$2);
      return _p$;
    }, {
      _v$: void 0,
      _v$2: void 0
    });
    return _el$;
  })();
});
const _tmpl$$2 = /* @__PURE__ */ template(`<div class="ap-overlay ap-overlay-start"><div class="ap-play-button"><div><span><svg version="1.1" viewBox="0 0 1000.0 1000.0" class="ap-icon"><defs><mask id="small-triangle-mask"><rect width="100%" height="100%" fill="white"></rect><polygon points="700.0 500.0, 400.00000000000006 326.7949192431122, 399.9999999999999 673.2050807568877" fill="black"></polygon></mask></defs><polygon points="1000.0 500.0, 250.0000000000001 66.98729810778059, 249.99999999999977 933.0127018922192" mask="url(#small-triangle-mask)" fill="white" class="ap-play-btn-fill"></polygon><polyline points="673.2050807568878 400.0, 326.7949192431123 600.0" stroke="white" stroke-width="90" class="ap-play-btn-stroke"></polyline></svg></span></div></div></div>`, 22);
var StartOverlay = ((props) => {
  const e = (f) => {
    return (e2) => {
      e2.preventDefault();
      f(e2);
    };
  };
  return (() => {
    const _el$ = _tmpl$$2.cloneNode(true);
    addEventListener$1(_el$, "click", e(props.onClick));
    return _el$;
  })();
});
delegateEvents(["click"]);
const _tmpl$$1 = /* @__PURE__ */ template(`<li><kbd>space</kbd> - pause / resume</li>`, 4), _tmpl$2 = /* @__PURE__ */ template(`<li><kbd>←</kbd> / <kbd>→</kbd> - rewind / fast-forward by 5 seconds</li>`, 6), _tmpl$3 = /* @__PURE__ */ template(`<li><kbd>Shift</kbd> + <kbd>←</kbd> / <kbd>→</kbd> - rewind / fast-forward by 10%</li>`, 8), _tmpl$4 = /* @__PURE__ */ template(`<li><kbd>[</kbd> / <kbd>]</kbd> - jump to the previous / next marker</li>`, 6), _tmpl$5 = /* @__PURE__ */ template(`<li><kbd>0</kbd>, <kbd>1</kbd>, <kbd>2</kbd> ... <kbd>9</kbd> - jump to 0%, 10%, 20% ... 90%</li>`, 10), _tmpl$6 = /* @__PURE__ */ template(`<li><kbd>,</kbd> / <kbd>.</kbd> - step back / forward, a frame at a time (when paused)</li>`, 6), _tmpl$7 = /* @__PURE__ */ template(`<li><kbd>m</kbd> - mute / unmute audio</li>`, 4), _tmpl$8 = /* @__PURE__ */ template(`<div class="ap-overlay ap-overlay-help"><div><div><p>Keyboard shortcuts</p><ul><li><kbd>f</kbd> - toggle fullscreen mode</li><li><kbd>?</kbd> - show this help popup</li></ul></div></div></div>`, 18);
var HelpOverlay = ((props) => {
  const style$1 = () => {
    return {
      "font-family": props.fontFamily
    };
  };
  const e = (f) => {
    return (e2) => {
      e2.preventDefault();
      f(e2);
    };
  };
  return (() => {
    const _el$ = _tmpl$8.cloneNode(true), _el$2 = _el$.firstChild, _el$3 = _el$2.firstChild, _el$4 = _el$3.firstChild, _el$5 = _el$4.nextSibling, _el$12 = _el$5.firstChild, _el$14 = _el$12.nextSibling;
    addEventListener$1(_el$, "click", e(props.onClose));
    _el$2.$$click = (e2) => {
      e2.stopPropagation();
    };
    insert(_el$5, createComponent(Show, {
      get when() {
        return props.isPausable;
      },
      get children() {
        return _tmpl$$1.cloneNode(true);
      }
    }), _el$12);
    insert(_el$5, createComponent(Show, {
      get when() {
        return props.isSeekable;
      },
      get children() {
        return [_tmpl$2.cloneNode(true), _tmpl$3.cloneNode(true), _tmpl$4.cloneNode(true), _tmpl$5.cloneNode(true), _tmpl$6.cloneNode(true)];
      }
    }), _el$12);
    insert(_el$5, createComponent(Show, {
      get when() {
        return props.hasAudio;
      },
      get children() {
        return _tmpl$7.cloneNode(true);
      }
    }), _el$14);
    createRenderEffect((_$p) => style(_el$, style$1(), _$p));
    return _el$;
  })();
});
delegateEvents(["click"]);
const _tmpl$ = /* @__PURE__ */ template(`<div class="ap-wrapper" tabindex="-1"><div></div></div>`, 4);
const CONTROL_BAR_HEIGHT = 32;
var Player = ((props) => {
  const logger = props.logger;
  const core = props.core;
  const autoPlay = props.autoPlay;
  const [state, setState2] = createStore({
    lines: [],
    cursor: void 0,
    charW: props.charW,
    charH: props.charH,
    bordersW: props.bordersW,
    bordersH: props.bordersH,
    containerW: 0,
    containerH: 0,
    isPausable: true,
    isSeekable: true,
    isFullscreen: false,
    currentTime: null,
    remainingTime: null,
    progress: null,
    blink: true,
    cursorHold: false
  });
  const [isPlaying, setIsPlaying] = createSignal(false);
  const [isMuted, setIsMuted] = createSignal(void 0);
  const [wasPlaying, setWasPlaying] = createSignal(false);
  const [overlay, setOverlay] = createSignal(!autoPlay ? "start" : null);
  const [infoMessage, setInfoMessage] = createSignal(null);
  const [terminalSize, setTerminalSize] = createSignal({
    cols: props.cols,
    rows: props.rows
  }, {
    equals: (newVal, oldVal) => newVal.cols === oldVal.cols && newVal.rows === oldVal.rows
  });
  const [duration2, setDuration2] = createSignal(void 0);
  const [markers, setMarkers] = createStore([]);
  const [userActive, setUserActive] = createSignal(false);
  const [isHelpVisible, setIsHelpVisible] = createSignal(false);
  const [originalTheme, setOriginalTheme] = createSignal(void 0);
  const terminalCols = createMemo(() => terminalSize().cols || 80);
  const terminalRows = createMemo(() => terminalSize().rows || 24);
  const controlBarHeight = () => props.controls === false ? 0 : CONTROL_BAR_HEIGHT;
  const controlsVisible = () => props.controls === true || props.controls === "auto" && userActive();
  let frameRequestId;
  let userActivityTimeoutId;
  let timeUpdateIntervalId;
  let blinkIntervalId;
  let wrapperRef;
  let playerRef;
  let terminalRef;
  let controlBarRef;
  let resizeObserver;
  function onPlaying() {
    updateTerminal();
    startBlinking();
    startTimeUpdates();
  }
  function onStopped() {
    stopBlinking();
    stopTimeUpdates();
    updateTime();
  }
  function resize2(size_) {
    batch(() => {
      if (size_.rows < terminalSize().rows) {
        setState2("lines", state.lines.slice(0, size_.rows));
      }
      setTerminalSize(size_);
    });
  }
  function setPoster(poster) {
    if (poster !== null && !autoPlay) {
      setState2({
        lines: poster.lines,
        cursor: poster.cursor
      });
    }
  }
  let resolveCoreReady;
  const coreReady = new Promise((resolve2) => {
    resolveCoreReady = resolve2;
  });
  core.addEventListener("ready", (_ref) => {
    let {
      isPausable,
      isSeekable,
      poster
    } = _ref;
    setState2({
      isPausable,
      isSeekable
    });
    setPoster(poster);
    resolveCoreReady();
  });
  core.addEventListener("metadata", (_ref2) => {
    let {
      cols,
      rows,
      duration: duration3,
      theme: theme2,
      poster,
      markers: markers2,
      hasAudio
    } = _ref2;
    batch(() => {
      resize2({
        cols,
        rows
      });
      setDuration2(duration3);
      setOriginalTheme(theme2);
      setMarkers(markers2);
      setPoster(poster);
      setIsMuted(hasAudio ? false : void 0);
    });
  });
  core.addEventListener("play", () => {
    setOverlay(null);
  });
  core.addEventListener("playing", () => {
    batch(() => {
      setIsPlaying(true);
      setWasPlaying(true);
      setOverlay(null);
      onPlaying();
    });
  });
  core.addEventListener("idle", () => {
    batch(() => {
      setIsPlaying(false);
      onStopped();
    });
  });
  core.addEventListener("loading", () => {
    batch(() => {
      setIsPlaying(false);
      onStopped();
      setOverlay("loader");
    });
  });
  core.addEventListener("offline", (_ref3) => {
    let {
      message: message2
    } = _ref3;
    batch(() => {
      setIsPlaying(false);
      onStopped();
      if (message2 !== void 0) {
        setInfoMessage(message2);
        setOverlay("info");
      }
    });
  });
  core.addEventListener("muted", (muted) => {
    setIsMuted(muted);
  });
  let renderCount = 0;
  core.addEventListener("ended", (_ref4) => {
    let {
      message: message2
    } = _ref4;
    batch(() => {
      setIsPlaying(false);
      onStopped();
      if (message2 !== void 0) {
        setInfoMessage(message2);
        setOverlay("info");
      }
    });
    logger.debug(`view: render count: ${renderCount}`);
  });
  core.addEventListener("errored", () => {
    setOverlay("error");
  });
  core.addEventListener("resize", resize2);
  core.addEventListener("reset", (_ref5) => {
    let {
      cols,
      rows,
      theme: theme2
    } = _ref5;
    batch(() => {
      resize2({
        cols,
        rows
      });
      setOriginalTheme(theme2);
      updateTerminal();
    });
  });
  core.addEventListener("seeked", () => {
    updateTime();
  });
  core.addEventListener("terminalUpdate", () => {
    if (frameRequestId === void 0) {
      frameRequestId = requestAnimationFrame(updateTerminal);
    }
  });
  const setupResizeObserver = () => {
    resizeObserver = new ResizeObserver(debounce((_entries) => {
      setState2({
        containerW: wrapperRef.offsetWidth,
        containerH: wrapperRef.offsetHeight
      });
      wrapperRef.dispatchEvent(new CustomEvent("resize", {
        detail: {
          el: playerRef
        }
      }));
    }, 10));
    resizeObserver.observe(wrapperRef);
  };
  onMount(async () => {
    logger.info("view: mounted");
    logger.debug("view: font measurements", {
      charW: state.charW,
      charH: state.charH
    });
    setupResizeObserver();
    setState2({
      containerW: wrapperRef.offsetWidth,
      containerH: wrapperRef.offsetHeight
    });
  });
  onCleanup(() => {
    core.stop();
    stopBlinking();
    stopTimeUpdates();
    resizeObserver.disconnect();
  });
  const updateTerminal = async () => {
    const changes = await core.getChanges();
    batch(() => {
      if (changes.lines !== void 0) {
        changes.lines.forEach((line2, i2) => {
          setState2("lines", i2, reconcile(line2));
        });
      }
      if (changes.cursor !== void 0) {
        setState2("cursor", reconcile(changes.cursor));
      }
      setState2("cursorHold", true);
    });
    frameRequestId = void 0;
    renderCount += 1;
  };
  const terminalElementSize = createMemo(() => {
    const terminalW = state.charW * terminalCols() + state.bordersW;
    const terminalH = state.charH * terminalRows() + state.bordersH;
    let fit = props.fit ?? "width";
    if (fit === "both" || state.isFullscreen) {
      const containerRatio = state.containerW / (state.containerH - controlBarHeight());
      const terminalRatio = terminalW / terminalH;
      if (containerRatio > terminalRatio) {
        fit = "height";
      } else {
        fit = "width";
      }
    }
    if (fit === false || fit === "none") {
      return {};
    } else if (fit === "width") {
      const scale = state.containerW / terminalW;
      return {
        scale,
        width: state.containerW,
        height: terminalH * scale + controlBarHeight()
      };
    } else if (fit === "height") {
      const scale = (state.containerH - controlBarHeight()) / terminalH;
      return {
        scale,
        width: terminalW * scale,
        height: state.containerH
      };
    } else {
      throw `unsupported fit mode: ${fit}`;
    }
  });
  const onFullscreenChange = () => {
    setState2("isFullscreen", document.fullscreenElement ?? document.webkitFullscreenElement);
  };
  const toggleFullscreen = () => {
    if (state.isFullscreen) {
      (document.exitFullscreen ?? document.webkitExitFullscreen ?? (() => {
      })).apply(document);
    } else {
      (wrapperRef.requestFullscreen ?? wrapperRef.webkitRequestFullscreen ?? (() => {
      })).apply(wrapperRef);
    }
  };
  const toggleHelp = () => {
    if (isHelpVisible()) {
      setIsHelpVisible(false);
    } else {
      core.pause();
      setIsHelpVisible(true);
    }
  };
  const onKeyDown = (e) => {
    if (e.altKey || e.metaKey || e.ctrlKey) {
      return;
    }
    if (e.key == " ") {
      core.togglePlay();
    } else if (e.key == ",") {
      core.step(-1).then(updateTime);
    } else if (e.key == ".") {
      core.step().then(updateTime);
    } else if (e.key == "f") {
      toggleFullscreen();
    } else if (e.key == "m") {
      toggleMuted();
    } else if (e.key == "[") {
      core.seek({
        marker: "prev"
      });
    } else if (e.key == "]") {
      core.seek({
        marker: "next"
      });
    } else if (e.key.charCodeAt(0) >= 48 && e.key.charCodeAt(0) <= 57) {
      const pos2 = (e.key.charCodeAt(0) - 48) / 10;
      core.seek(`${pos2 * 100}%`);
    } else if (e.key == "?") {
      toggleHelp();
    } else if (e.key == "ArrowLeft") {
      if (e.shiftKey) {
        core.seek("<<<");
      } else {
        core.seek("<<");
      }
    } else if (e.key == "ArrowRight") {
      if (e.shiftKey) {
        core.seek(">>>");
      } else {
        core.seek(">>");
      }
    } else if (e.key == "Escape") {
      setIsHelpVisible(false);
    } else {
      return;
    }
    e.stopPropagation();
    e.preventDefault();
  };
  const wrapperOnMouseMove = () => {
    if (state.isFullscreen) {
      onUserActive(true);
    }
  };
  const playerOnMouseLeave = () => {
    if (!state.isFullscreen) {
      onUserActive(false);
    }
  };
  const startTimeUpdates = () => {
    timeUpdateIntervalId = setInterval(updateTime, 100);
  };
  const stopTimeUpdates = () => {
    clearInterval(timeUpdateIntervalId);
  };
  const updateTime = async () => {
    const currentTime = await core.getCurrentTime();
    const remainingTime = await core.getRemainingTime();
    const progress2 = await core.getProgress();
    setState2({
      currentTime,
      remainingTime,
      progress: progress2
    });
  };
  const startBlinking = () => {
    blinkIntervalId = setInterval(() => {
      setState2((state2) => {
        const changes = {
          blink: !state2.blink
        };
        if (changes.blink) {
          changes.cursorHold = false;
        }
        return changes;
      });
    }, 600);
  };
  const stopBlinking = () => {
    clearInterval(blinkIntervalId);
    setState2("blink", true);
  };
  const onUserActive = (show) => {
    clearTimeout(userActivityTimeoutId);
    if (show) {
      userActivityTimeoutId = setTimeout(() => onUserActive(false), 2e3);
    }
    setUserActive(show);
  };
  const theme = createMemo(() => {
    const name2 = props.theme || "auto/asciinema";
    if (name2.slice(0, 5) === "auto/") {
      return {
        name: name2.slice(5),
        colors: originalTheme()
      };
    } else {
      return {
        name: name2
      };
    }
  });
  const playerStyle = () => {
    const style2 = {};
    if ((props.fit === false || props.fit === "none") && props.terminalFontSize !== void 0) {
      if (props.terminalFontSize === "small") {
        style2["font-size"] = "12px";
      } else if (props.terminalFontSize === "medium") {
        style2["font-size"] = "18px";
      } else if (props.terminalFontSize === "big") {
        style2["font-size"] = "24px";
      } else {
        style2["font-size"] = props.terminalFontSize;
      }
    }
    const size = terminalElementSize();
    if (size.width !== void 0) {
      style2["width"] = `${size.width}px`;
      style2["height"] = `${size.height}px`;
    }
    const themeColors = theme().colors;
    if (themeColors) {
      style2["--term-color-foreground"] = themeColors.foreground;
      style2["--term-color-background"] = themeColors.background;
      themeColors.palette.forEach((color, i2) => {
        style2[`--term-color-${i2}`] = color;
      });
    }
    return style2;
  };
  const play = () => {
    coreReady.then(() => core.play());
  };
  const togglePlay = () => {
    coreReady.then(() => core.togglePlay());
  };
  const toggleMuted = () => {
    coreReady.then(() => {
      if (isMuted() === true) {
        core.unmute();
      } else {
        core.mute();
      }
    });
  };
  const seek = (pos2) => {
    coreReady.then(() => core.seek(pos2));
  };
  const playerClass = () => `ap-player asciinema-player-theme-${theme().name}`;
  const terminalScale = () => terminalElementSize()?.scale;
  const el = (() => {
    const _el$ = _tmpl$.cloneNode(true), _el$2 = _el$.firstChild;
    const _ref$ = wrapperRef;
    typeof _ref$ === "function" ? use(_ref$, _el$) : wrapperRef = _el$;
    _el$.addEventListener("webkitfullscreenchange", onFullscreenChange);
    _el$.addEventListener("fullscreenchange", onFullscreenChange);
    _el$.$$mousemove = wrapperOnMouseMove;
    _el$.$$keydown = onKeyDown;
    const _ref$2 = playerRef;
    typeof _ref$2 === "function" ? use(_ref$2, _el$2) : playerRef = _el$2;
    _el$2.$$mousemove = () => onUserActive(true);
    _el$2.addEventListener("mouseleave", playerOnMouseLeave);
    insert(_el$2, createComponent(Terminal, {
      get cols() {
        return terminalCols();
      },
      get rows() {
        return terminalRows();
      },
      get scale() {
        return terminalScale();
      },
      get blink() {
        return state.blink;
      },
      get lines() {
        return state.lines;
      },
      get cursor() {
        return state.cursor;
      },
      get cursorHold() {
        return state.cursorHold;
      },
      get fontFamily() {
        return props.terminalFontFamily;
      },
      get lineHeight() {
        return props.terminalLineHeight;
      },
      ref(r$) {
        const _ref$3 = terminalRef;
        typeof _ref$3 === "function" ? _ref$3(r$) : terminalRef = r$;
      }
    }), null);
    insert(_el$2, createComponent(Show, {
      get when() {
        return props.controls !== false;
      },
      get children() {
        return createComponent(ControlBar, {
          get duration() {
            return duration2();
          },
          get currentTime() {
            return state.currentTime;
          },
          get remainingTime() {
            return state.remainingTime;
          },
          get progress() {
            return state.progress;
          },
          markers,
          get isPlaying() {
            return isPlaying() || overlay() == "loader";
          },
          get isPausable() {
            return state.isPausable;
          },
          get isSeekable() {
            return state.isSeekable;
          },
          get isMuted() {
            return isMuted();
          },
          onPlayClick: togglePlay,
          onFullscreenClick: toggleFullscreen,
          onHelpClick: toggleHelp,
          onSeekClick: seek,
          onMuteClick: toggleMuted,
          ref(r$) {
            const _ref$4 = controlBarRef;
            typeof _ref$4 === "function" ? _ref$4(r$) : controlBarRef = r$;
          }
        });
      }
    }), null);
    insert(_el$2, createComponent(Switch, {
      get children() {
        return [createComponent(Match, {
          get when() {
            return overlay() == "start";
          },
          get children() {
            return createComponent(StartOverlay, {
              onClick: play
            });
          }
        }), createComponent(Match, {
          get when() {
            return overlay() == "loader";
          },
          get children() {
            return createComponent(LoaderOverlay, {});
          }
        }), createComponent(Match, {
          get when() {
            return overlay() == "error";
          },
          get children() {
            return createComponent(ErrorOverlay, {});
          }
        })];
      }
    }), null);
    insert(_el$2, createComponent(Transition, {
      name: "slide",
      get children() {
        return createComponent(Show, {
          get when() {
            return overlay() == "info";
          },
          get children() {
            return createComponent(InfoOverlay, {
              get message() {
                return infoMessage();
              },
              get fontFamily() {
                return props.terminalFontFamily;
              },
              get wasPlaying() {
                return wasPlaying();
              }
            });
          }
        });
      }
    }), null);
    insert(_el$2, createComponent(Show, {
      get when() {
        return isHelpVisible();
      },
      get children() {
        return createComponent(HelpOverlay, {
          get fontFamily() {
            return props.terminalFontFamily;
          },
          onClose: () => setIsHelpVisible(false),
          get isPausable() {
            return state.isPausable;
          },
          get isSeekable() {
            return state.isSeekable;
          },
          get hasAudio() {
            return isMuted() !== void 0;
          }
        });
      }
    }), null);
    createRenderEffect((_p$) => {
      const _v$ = !!controlsVisible(), _v$2 = playerClass(), _v$3 = playerStyle();
      _v$ !== _p$._v$ && _el$.classList.toggle("ap-hud", _p$._v$ = _v$);
      _v$2 !== _p$._v$2 && className(_el$2, _p$._v$2 = _v$2);
      _p$._v$3 = style(_el$2, _v$3, _p$._v$3);
      return _p$;
    }, {
      _v$: void 0,
      _v$2: void 0,
      _v$3: void 0
    });
    return _el$;
  })();
  return el;
});
delegateEvents(["keydown", "mousemove"]);
function mount(core, elem) {
  let opts = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
  const metrics = measureTerminal(opts.terminalFontFamily, opts.terminalLineHeight);
  const props = {
    core,
    logger: opts.logger,
    cols: opts.cols,
    rows: opts.rows,
    fit: opts.fit,
    controls: opts.controls,
    autoPlay: opts.autoPlay,
    terminalFontSize: opts.terminalFontSize,
    terminalFontFamily: opts.terminalFontFamily,
    terminalLineHeight: opts.terminalLineHeight,
    theme: opts.theme,
    ...metrics
  };
  let el;
  const dispose2 = render(() => {
    el = createComponent(Player, props);
    return el;
  }, elem);
  return {
    el,
    dispose: dispose2
  };
}
function measureTerminal(fontFamily, lineHeight) {
  const cols = 80;
  const rows = 24;
  const div = document.createElement("div");
  div.style.height = "0px";
  div.style.overflow = "hidden";
  div.style.fontSize = "15px";
  document.body.appendChild(div);
  let el;
  const dispose2 = render(() => {
    el = createComponent(Terminal, {
      cols,
      rows,
      lineHeight,
      fontFamily,
      lines: []
    });
    return el;
  }, div);
  const metrics = {
    charW: el.clientWidth / cols,
    charH: el.clientHeight / rows,
    bordersW: el.offsetWidth - el.clientWidth,
    bordersH: el.offsetHeight - el.clientHeight
  };
  dispose2();
  document.body.removeChild(div);
  return metrics;
}
const CORE_OPTS = ["autoPlay", "autoplay", "cols", "idleTimeLimit", "loop", "markers", "pauseOnMarkers", "poster", "preload", "rows", "speed", "startAt", "audioUrl"];
const UI_OPTS = ["autoPlay", "autoplay", "cols", "controls", "fit", "rows", "terminalFontFamily", "terminalFontSize", "terminalLineHeight", "theme"];
function coreOpts(inputOpts) {
  let overrides = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
  const opts = Object.fromEntries(Object.entries(inputOpts).filter((_ref) => {
    let [key2] = _ref;
    return CORE_OPTS.includes(key2);
  }));
  opts.autoPlay ??= opts.autoplay;
  opts.speed ??= 1;
  return {
    ...opts,
    ...overrides
  };
}
function uiOpts(inputOpts) {
  let overrides = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
  const opts = Object.fromEntries(Object.entries(inputOpts).filter((_ref2) => {
    let [key2] = _ref2;
    return UI_OPTS.includes(key2);
  }));
  opts.autoPlay ??= opts.autoplay;
  opts.controls ??= "auto";
  return {
    ...opts,
    ...overrides
  };
}
function create(src, elem) {
  let opts = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
  const logger = opts.logger ?? new DummyLogger();
  const core = new Core(src, coreOpts(opts, {
    logger
  }));
  const {
    el,
    dispose: dispose2
  } = mount(core, elem, uiOpts(opts, {
    logger
  }));
  const ready = core.init();
  const player = {
    el,
    dispose: dispose2,
    getCurrentTime: () => ready.then(core.getCurrentTime.bind(core)),
    getDuration: () => ready.then(core.getDuration.bind(core)),
    play: () => ready.then(core.play.bind(core)),
    pause: () => ready.then(core.pause.bind(core)),
    seek: (pos2) => ready.then(() => core.seek(pos2))
  };
  player.addEventListener = (name2, callback) => {
    return core.addEventListener(name2, callback.bind(player));
  };
  return player;
}
const AsciinemaPlayer = ({
  id: id2,
  rows,
  cols,
  inputUrl,
  outputUrl,
  timingUrl,
  fit,
  speed,
  autoPlay,
  loop,
  theme,
  idleTimeLimit = 2,
  style: style2
}) => {
  const playerContainerRef = reactExports.useRef(null);
  reactExports.useEffect(() => {
    if (!playerContainerRef.current) return;
    const player = create(
      {
        url: [timingUrl, outputUrl, inputUrl],
        parser: "typescript"
      },
      playerContainerRef.current,
      {
        rows,
        cols,
        autoPlay,
        loop,
        theme,
        speed,
        idleTimeLimit,
        fit
      }
    );
    player.play();
    return () => {
      player.dispose();
    };
  }, [
    timingUrl,
    outputUrl,
    inputUrl,
    rows,
    cols,
    autoPlay,
    loop,
    theme,
    speed,
    idleTimeLimit,
    fit
  ]);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "div",
    {
      id: `asciinema-player-${id2 || "default"}`,
      ref: playerContainerRef,
      style: { ...style2 }
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/AsciinemaPlayer.tsx",
      lineNumber: 80,
      columnNumber: 5
    },
    void 0
  );
};
const carouselThumbs = "_carouselThumbs_1mvg8_1";
const carouselThumb = "_carouselThumb_1mvg8_1";
const carouselPlayIcon = "_carouselPlayIcon_1mvg8_16";
const lightboxOverlay = "_lightboxOverlay_1mvg8_20";
const lightboxContent = "_lightboxContent_1mvg8_33";
const lightboxButtonCloseWrapper = "_lightboxButtonCloseWrapper_1mvg8_45";
const lightboxButtonClose = "_lightboxButtonClose_1mvg8_45";
const lightboxPreviewButton = "_lightboxPreviewButton_1mvg8_63";
const styles$A = {
  carouselThumbs,
  carouselThumb,
  carouselPlayIcon,
  lightboxOverlay,
  lightboxContent,
  lightboxButtonCloseWrapper,
  lightboxButtonClose,
  lightboxPreviewButton
};
const LightboxCarousel = ({ id: id2, slides }) => {
  const [isOpen, setIsOpen] = useProperty(id2, "isOpen", {
    defaultValue: false
  });
  const [currentIndex, setCurrentIndex] = useProperty(id2, "currentIndex", {
    defaultValue: 0
  });
  const [showOverlay, setShowOverlay] = useProperty(id2, "showOverlay", {
    defaultValue: false
  });
  const openLightbox = reactExports.useCallback(
    (index) => {
      setCurrentIndex(index);
      setShowOverlay(true);
      setTimeout(() => setIsOpen(true), 10);
    },
    [setIsOpen]
  );
  const closeLightbox = reactExports.useCallback(() => {
    setIsOpen(false);
  }, [setIsOpen]);
  reactExports.useEffect(() => {
    if (!isOpen && showOverlay) {
      const timer = setTimeout(() => {
        setShowOverlay(false);
      }, 300);
      return () => clearTimeout(timer);
    }
  }, [isOpen, showOverlay, setShowOverlay]);
  const showNext = reactExports.useCallback(() => {
    setCurrentIndex((currentIndex || 0) + 1);
  }, [slides, setCurrentIndex]);
  const showPrev = reactExports.useCallback(() => {
    setCurrentIndex(((currentIndex || 0) - 1 + slides.length) % slides.length);
  }, [slides, setCurrentIndex]);
  reactExports.useEffect(() => {
    if (!isOpen) return;
    const handleKeyUp = (e) => {
      if (e.key === "Escape") {
        closeLightbox();
      } else if (e.key === "ArrowRight") {
        showNext();
      } else if (e.key === "ArrowLeft") {
        showPrev();
      }
      e.preventDefault();
      e.stopPropagation();
    };
    window.addEventListener("keyup", handleKeyUp, true);
    return () => window.removeEventListener("keyup", handleKeyUp);
  }, [isOpen, showNext, showPrev]);
  const handleThumbClick = reactExports.useCallback(
    (e) => {
      const index = Number(e.currentTarget.dataset.index);
      openLightbox(index);
    },
    [openLightbox]
  );
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("lightbox-carousel-container"), children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$A.carouselThumbs), children: slides.map((slide, index) => {
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "div",
        {
          "data-index": index,
          className: clsx(styles$A.carouselThumb),
          onClick: handleThumbClick,
          children: [
            /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: slide.label }, void 0, false, {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/LightboxCarousel.tsx",
              lineNumber: 104,
              columnNumber: 15
            }, void 0),
            /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
              "i",
              {
                className: clsx(
                  ApplicationIcons.play,
                  styles$A.carouselPlayIcon
                )
              },
              void 0,
              false,
              {
                fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/LightboxCarousel.tsx",
                lineNumber: 106,
                columnNumber: 17
              },
              void 0
            ) }, void 0, false, {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/LightboxCarousel.tsx",
              lineNumber: 105,
              columnNumber: 15
            }, void 0)
          ]
        },
        index,
        true,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/LightboxCarousel.tsx",
          lineNumber: 98,
          columnNumber: 13
        },
        void 0
      );
    }) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/LightboxCarousel.tsx",
      lineNumber: 95,
      columnNumber: 7
    }, void 0),
    showOverlay && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "div",
      {
        className: clsx(styles$A.lightboxOverlay, isOpen ? "open" : "closed"),
        children: [
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$A.lightboxButtonCloseWrapper), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            "button",
            {
              className: styles$A.lightboxButtonClose,
              onClick: closeLightbox,
              children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("i", { className: ApplicationIcons.close }, void 0, false, {
                fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/LightboxCarousel.tsx",
                lineNumber: 126,
                columnNumber: 15
              }, void 0)
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/LightboxCarousel.tsx",
              lineNumber: 122,
              columnNumber: 13
            },
            void 0
          ) }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/LightboxCarousel.tsx",
            lineNumber: 121,
            columnNumber: 11
          }, void 0),
          slides.length > 1 ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            "button",
            {
              className: clsx(styles$A.lightboxPreviewButton, "prev"),
              onClick: showPrev,
              children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("i", { className: ApplicationIcons.previous }, void 0, false, {
                fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/LightboxCarousel.tsx",
                lineNumber: 134,
                columnNumber: 15
              }, void 0)
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/LightboxCarousel.tsx",
              lineNumber: 130,
              columnNumber: 13
            },
            void 0
          ) : "",
          slides.length > 1 ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            "button",
            {
              className: clsx(styles$A.lightboxPreviewButton, "next"),
              onClick: showNext,
              children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("i", { className: ApplicationIcons.next }, void 0, false, {
                fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/LightboxCarousel.tsx",
                lineNumber: 144,
                columnNumber: 15
              }, void 0)
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/LightboxCarousel.tsx",
              lineNumber: 140,
              columnNumber: 13
            },
            void 0
          ) : "",
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            "div",
            {
              className: clsx(styles$A.lightboxContent, isOpen ? "open" : "closed"),
              children: slides[currentIndex || 0]?.render()
            },
            `carousel-slide-${currentIndex}`,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/LightboxCarousel.tsx",
              lineNumber: 149,
              columnNumber: 11
            },
            void 0
          )
        ]
      },
      void 0,
      true,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/LightboxCarousel.tsx",
        lineNumber: 118,
        columnNumber: 9
      },
      void 0
    )
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/LightboxCarousel.tsx",
    lineNumber: 94,
    columnNumber: 5
  }, void 0);
};
const HumanBaselineView = ({
  started,
  runtime,
  answer,
  completed,
  running,
  sessionLogs
}) => {
  const player_fns = [];
  const revokableUrls = [];
  const revokableUrl = (data2) => {
    const blob = new Blob([data2], { type: "text/plain" });
    const url = URL.createObjectURL(blob);
    revokableUrls.push(url);
    return url;
  };
  reactExports.useEffect(() => {
    return () => {
      revokableUrls.forEach((url) => URL.revokeObjectURL(url));
    };
  }, []);
  let count2 = 1;
  for (const sessionLog of sessionLogs) {
    const rows = extractSize(sessionLog.output, "LINES", 24);
    const cols = extractSize(sessionLog.output, "COLUMNS", 80);
    const currentCount = count2;
    const title2 = sessionLogs.length === 1 ? "Terminal Session" : `Terminal Session ${currentCount}`;
    player_fns.push({
      label: title2,
      render: () => /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        AsciinemaPlayer,
        {
          id: `player-${currentCount}`,
          inputUrl: revokableUrl(sessionLog.input),
          outputUrl: revokableUrl(sessionLog.output),
          timingUrl: revokableUrl(sessionLog.timing),
          rows,
          cols,
          className: "asciinema-player",
          style: {
            height: `${rows * 2}em`,
            width: `${cols * 2}em`
          },
          fit: "both"
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/HumanBaselineView.tsx",
          lineNumber: 72,
          columnNumber: 9
        },
        void 0
      )
    });
    count2 += 1;
  }
  const StatusMessage = ({
    completed: completed2,
    running: running2,
    answer: answer2
  }) => {
    if (running2) {
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("span", { className: "text-style-label", children: "Running" }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/HumanBaselineView.tsx",
        lineNumber: 103,
        columnNumber: 14
      }, void 0);
    } else if (completed2) {
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "span",
          {
            className: "text-style-label text-style-secondary asciinema-player-status",
            children: "Answer"
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/HumanBaselineView.tsx",
            lineNumber: 107,
            columnNumber: 11
          },
          void 0
        ),
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("span", { children: answer2 }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/HumanBaselineView.tsx",
          lineNumber: 114,
          columnNumber: 11
        }, void 0)
      ] }, void 0, true, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/HumanBaselineView.tsx",
        lineNumber: 106,
        columnNumber: 9
      }, void 0);
    } else {
      return "Unknown status";
    }
  };
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "asciinema-wrapper", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "asciinema-container", children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "asciinema-header-left text-style-label", children: [
      started ? formatDateTime(started) : "",
      runtime ? ` (${formatTime$1(Math.floor(runtime))})` : ""
    ] }, void 0, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/HumanBaselineView.tsx",
      lineNumber: 125,
      columnNumber: 9
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "asciinema-header-center text-style-label" }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/HumanBaselineView.tsx",
      lineNumber: 129,
      columnNumber: 9
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "asciinema-header-right", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      StatusMessage,
      {
        completed,
        running,
        answer
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/HumanBaselineView.tsx",
        lineNumber: 131,
        columnNumber: 11
      },
      void 0
    ) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/HumanBaselineView.tsx",
      lineNumber: 130,
      columnNumber: 9
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "asciinema-body", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(LightboxCarousel, { id: "ascii-cinema", slides: player_fns }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/HumanBaselineView.tsx",
      lineNumber: 138,
      columnNumber: 11
    }, void 0) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/HumanBaselineView.tsx",
      lineNumber: 137,
      columnNumber: 9
    }, void 0)
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/HumanBaselineView.tsx",
    lineNumber: 124,
    columnNumber: 7
  }, void 0) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/HumanBaselineView.tsx",
    lineNumber: 123,
    columnNumber: 5
  }, void 0);
};
const extractSize = (value2, label2, defaultValue) => {
  const regex2 = new RegExp(`${label2}="(\\d+)"`);
  const match3 = value2.match(regex2);
  const size = match3 ? match3[1] : void 0;
  if (size) {
    return parseInt(size);
  } else {
    return defaultValue;
  }
};
const toolsGrid = "_toolsGrid_1qqm2_1";
const tools = "_tools_1qqm2_1";
const tool = "_tool_1qqm2_1";
const styles$z = {
  toolsGrid,
  tools,
  tool
};
const system_msg_added_sig = {
  type: "system_message",
  signature: {
    remove: ["/messages/0/source"],
    replace: ["/messages/0/role", "/messages/0/content"],
    add: ["/messages/1"]
  },
  render: (_changes, resolvedState) => {
    const messages2 = resolvedState["messages"];
    const message2 = messages2[0];
    if (typeof message2 !== "object" || !message2) {
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(jsxDevRuntimeExports.Fragment, {}, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/state/StateEventRenderers.tsx",
        lineNumber: 40,
        columnNumber: 14
      }, void 0);
    }
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      ChatView,
      {
        id: "system_msg_event_preview",
        messages: [message2],
        allowLinking: false
      },
      "system_msg_event_preview",
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/state/StateEventRenderers.tsx",
        lineNumber: 43,
        columnNumber: 7
      },
      void 0
    );
  }
};
const kToolPattern = "/tools/(\\d+)";
const use_tools = {
  type: "use_tools",
  signature: {
    add: ["/tools/0"],
    replace: ["/tool_choice"],
    remove: []
  },
  render: (changes, resolvedState) => {
    return renderTools(changes, resolvedState);
  }
};
const add_tools = {
  type: "add_tools",
  signature: {
    add: [kToolPattern],
    replace: [],
    remove: []
  },
  render: (changes, resolvedState) => {
    return renderTools(changes, resolvedState);
  }
};
const messages = {
  type: "messages",
  match: (changes) => {
    const allMessages = changes.every((change) => {
      if (change.op === "add" && change.path.match(/\/messages\/\d+/)) {
        return typeof change.value["role"] === "string" && ["user", "assistant", "system", "tool"].includes(change.value["role"]);
      }
      return false;
    });
    return allMessages;
  },
  render: (changes) => {
    const messages2 = changes.map((c2) => c2.value);
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      ChatView,
      {
        id: "system_msg_event_preview",
        messages: messages2,
        allowLinking: false
      },
      "system_msg_event_preview",
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/state/StateEventRenderers.tsx",
        lineNumber: 96,
        columnNumber: 7
      },
      void 0
    );
  }
};
const humanAgentKey = (key2) => {
  return `HumanAgentState:${key2}`;
};
const human_baseline_session = {
  type: "human_baseline_session",
  signature: {
    add: ["HumanAgentState:logs"],
    replace: [],
    remove: []
  },
  render: (_changes, state) => {
    const started = state[humanAgentKey("started_running")];
    const runtime = state[humanAgentKey("accumulated_time")];
    const answer = state[humanAgentKey("answer")];
    const completed = !!answer;
    const running = state[humanAgentKey("running_state")];
    const rawSessions = state[humanAgentKey("logs")];
    const startedDate = started ? new Date(started * 1e3) : void 0;
    const sessions = {};
    if (rawSessions) {
      for (const key2 of Object.keys(rawSessions)) {
        const value2 = rawSessions[key2];
        const match3 = key2.match(/(.*)_(\d+_\d+)\.(.*)/);
        if (match3) {
          const user2 = match3[1];
          const timestamp2 = match3[2];
          const type = match3[3];
          if (timestamp2) {
            sessions[timestamp2] = sessions[timestamp2];
            switch (type) {
              case "input":
                sessions[timestamp2].input = value2;
                break;
              case "output":
                sessions[timestamp2].output = value2;
                break;
              case "timing":
                sessions[timestamp2].timing = value2;
                break;
              case "name":
                sessions[timestamp2].name = value2;
                break;
            }
            if (user2) {
              sessions[timestamp2].user = user2;
            }
          }
        }
      }
    }
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      HumanBaselineView,
      {
        started: startedDate,
        running,
        completed,
        answer,
        runtime,
        sessionLogs: Object.values(sessions)
      },
      "human_baseline_view",
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/state/StateEventRenderers.tsx",
        lineNumber: 166,
        columnNumber: 7
      },
      void 0
    );
  }
};
const renderTools = (changes, resolvedState) => {
  const toolIndexes = [];
  for (const change of changes) {
    const match3 = change.path.match(kToolPattern);
    if (match3 && match3[1]) {
      toolIndexes.push(match3[1]);
    }
  }
  const toolName = (toolChoice2) => {
    if (typeof toolChoice2 === "object" && toolChoice2 && !Array.isArray(toolChoice2)) {
      return toolChoice2["name"] || "";
    } else {
      return String(toolChoice2);
    }
  };
  const toolsInfo = {};
  const hasToolChoice = changes.find((change) => {
    return change.path.startsWith("/tool_choice");
  });
  if (resolvedState.tool_choice && hasToolChoice) {
    toolsInfo["Tool Choice"] = /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("span", { className: clsx("text-size-smaller"), children: toolName(resolvedState.tool_choice) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/state/StateEventRenderers.tsx",
      lineNumber: 212,
      columnNumber: 7
    }, void 0);
  }
  const tools2 = resolvedState.tools;
  if (tools2.length > 0) {
    if (toolIndexes.length === 0) {
      toolsInfo["Tools"] = /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Tools, { toolDefinitions: resolvedState.tools }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/state/StateEventRenderers.tsx",
        lineNumber: 223,
        columnNumber: 9
      }, void 0);
    } else {
      const filtered = tools2.filter((_, index) => {
        return toolIndexes.includes(index.toString());
      });
      toolsInfo["Tools"] = /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Tools, { toolDefinitions: filtered }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/state/StateEventRenderers.tsx",
        lineNumber: 229,
        columnNumber: 28
      }, void 0);
    }
  }
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$z.tools), children: Object.keys(toolsInfo).map((key2) => {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(reactExports.Fragment, { children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "div",
        {
          className: clsx(
            "text-size-smaller",
            "text-style-label",
            "text-style-secondary"
          ),
          children: key2
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/state/StateEventRenderers.tsx",
          lineNumber: 238,
          columnNumber: 13
        },
        void 0
      ),
      toolsInfo[key2]
    ] }, key2, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/state/StateEventRenderers.tsx",
      lineNumber: 237,
      columnNumber: 11
    }, void 0);
  }) }, "state-diff-tools", false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/state/StateEventRenderers.tsx",
    lineNumber: 234,
    columnNumber: 5
  }, void 0);
};
const createMessageRenderer = (name2, role) => {
  return {
    type: name2,
    match: (changes) => {
      if (changes.length === 1) {
        const change = changes[0];
        if (change && change.op === "add" && change.path.match(/\/messages\/\d+/)) {
          return change.value["role"] === role;
        }
      }
      return false;
    },
    render: (changes) => {
      const message2 = changes[0]?.value;
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        ChatView,
        {
          id: "system_msg_event_preview",
          messages: [message2],
          allowLinking: false
        },
        "system_msg_event_preview",
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/state/StateEventRenderers.tsx",
          lineNumber: 274,
          columnNumber: 9
        },
        void 0
      );
    }
  };
};
const RenderableChangeTypes = [
  system_msg_added_sig,
  createMessageRenderer("assistant_msg", "assistant"),
  createMessageRenderer("user_msg", "user"),
  use_tools,
  add_tools,
  messages
];
const StoreSpecificRenderableTypes = [
  human_baseline_session
];
const Tools = ({ toolDefinitions }) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: styles$z.toolsGrid, children: toolDefinitions.map((toolDefinition, idx) => {
    const toolName = toolDefinition.name;
    const toolArgs = toolDefinition.parameters?.properties ? Object.keys(toolDefinition.parameters.properties) : [];
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      Tool,
      {
        toolName,
        toolArgs
      },
      `${toolName}-${idx}`,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/state/StateEventRenderers.tsx",
        lineNumber: 332,
        columnNumber: 11
      },
      void 0
    );
  }) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/state/StateEventRenderers.tsx",
    lineNumber: 325,
    columnNumber: 5
  }, void 0);
};
const Tool = ({ toolName, toolArgs }) => {
  const functionCall = toolArgs && toolArgs.length > 0 ? `${toolName}(${toolArgs.join(", ")})` : toolName;
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("code", { className: clsx("text-size-smallest", styles$z.tool), children: functionCall }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/state/StateEventRenderers.tsx",
    lineNumber: 357,
    columnNumber: 5
  }, void 0);
};
const diff = "_diff_eobja_1";
const summary$2 = "_summary_eobja_6";
const styles$y = {
  diff,
  summary: summary$2
};
const StateEventView = ({
  eventNode,
  className: className2
}) => {
  const event = eventNode.event;
  const summary2 = reactExports.useMemo(() => {
    return summarizeChanges(event.changes);
  }, [event.changes]);
  const [before, after] = reactExports.useMemo(() => {
    try {
      return synthesizeComparable(event.changes);
    } catch (e) {
      console.error(
        "Unable to synthesize comparable object to display state diffs.",
        e
      );
      return [{}, {}];
    }
  }, [event.changes]);
  const changePreview = reactExports.useMemo(() => {
    const isStore = eventNode.event.event === "store";
    const afterClone = structuredClone(after) || {};
    return generatePreview(event.changes, afterClone, isStore);
  }, [event.changes, after]);
  const title2 = event.event === "state" ? "State Updated" : "Store Updated";
  const collapseEvent = useStore((state) => state.setTranscriptCollapsedEvent);
  reactExports.useEffect(() => {
    if (changePreview === void 0) {
      collapseEvent(kTranscriptCollapseScope, eventNode.id, true);
    }
  }, [changePreview, collapseEvent]);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    EventPanel,
    {
      eventNodeId: eventNode.id,
      depth: eventNode.depth,
      title: title2,
      className: className2,
      subTitle: formatDateTime(new Date(event.timestamp)),
      text: !changePreview ? summary2 : void 0,
      collapsibleContent: true,
      children: [
        changePreview ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { "data-name": "Summary", className: clsx(styles$y.summary), children: changePreview }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/state/StateEventView.tsx",
          lineNumber: 84,
          columnNumber: 9
        }, void 0) : void 0,
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          StateDiffView,
          {
            before,
            after,
            "data-name": "Diff",
            className: clsx(styles$y.diff)
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/state/StateEventView.tsx",
            lineNumber: 88,
            columnNumber: 7
          },
          void 0
        )
      ]
    },
    void 0,
    true,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/state/StateEventView.tsx",
      lineNumber: 74,
      columnNumber: 5
    },
    void 0
  );
};
const generatePreview = (changes, resolvedState, isStore) => {
  const results = [];
  for (const changeType of [
    ...RenderableChangeTypes,
    ...isStore ? StoreSpecificRenderableTypes : []
  ]) {
    if (changeType.signature) {
      const requiredMatchCount = changeType.signature.remove.length + changeType.signature.replace.length + changeType.signature.add.length;
      let matchingOps = 0;
      for (const change of changes) {
        const op2 = change.op;
        switch (op2) {
          case "add":
            if (changeType.signature.add && changeType.signature.add.length > 0) {
              changeType.signature.add.forEach((signature) => {
                if (change.path.match(signature)) {
                  matchingOps++;
                }
              });
            }
            break;
          case "remove":
            if (changeType.signature.remove && changeType.signature.remove.length > 0) {
              changeType.signature.remove.forEach((signature) => {
                if (change.path.match(signature)) {
                  matchingOps++;
                }
              });
            }
            break;
          case "replace":
            if (changeType.signature.replace && changeType.signature.replace.length > 0) {
              changeType.signature.replace.forEach((signature) => {
                if (change.path.match(signature)) {
                  matchingOps++;
                }
              });
            }
            break;
        }
      }
      if (matchingOps === requiredMatchCount) {
        const el = changeType.render(changes, resolvedState);
        results.push(el);
        break;
      }
    } else if (changeType.match) {
      const matches = changeType.match(changes);
      if (matches) {
        const el = changeType.render(changes, resolvedState);
        results.push(el);
        break;
      }
    }
  }
  return results.length > 0 ? results : void 0;
};
const summarizeChanges = (changes) => {
  const changeMap = {
    add: [],
    copy: [],
    move: [],
    replace: [],
    remove: [],
    test: []
  };
  for (const change of changes) {
    switch (change.op) {
      case "add":
        changeMap.add.push(change.path);
        break;
      case "copy":
        changeMap.copy.push(change.path);
        break;
      case "move":
        changeMap.move.push(change.path);
        break;
      case "replace":
        changeMap.replace.push(change.path);
        break;
      case "remove":
        changeMap.remove.push(change.path);
        break;
      case "test":
        changeMap.test.push(change.path);
        break;
    }
  }
  const changeList = [];
  const totalOpCount = Object.keys(changeMap).reduce((prev, current3) => {
    return prev + changeMap[current3].length;
  }, 0);
  if (totalOpCount > 2) {
    Object.keys(changeMap).forEach((key2) => {
      const opChanges = changeMap[key2];
      if (opChanges.length > 0) {
        changeList.push(`${key2} ${opChanges.length}`);
      }
    });
  } else {
    Object.keys(changeMap).forEach((key2) => {
      const opChanges = changeMap[key2];
      if (opChanges.length > 0) {
        changeList.push(`${key2} ${opChanges.join(", ")}`);
      }
    });
  }
  return changeList.join(", ");
};
const synthesizeComparable = (changes) => {
  const before = {};
  const after = {};
  for (const change of changes) {
    switch (change.op) {
      case "add":
        initializeArrays(before, change.path);
        initializeArrays(after, change.path);
        setPath(after, change.path, change.value);
        break;
      case "copy":
        setPath(before, change.path, change.value);
        setPath(after, change.path, change.value);
        break;
      case "move":
        setPath(before, change.from || "", change.value);
        setPath(after, change.path, change.value);
        break;
      case "remove":
        setPath(before, change.path, change.value);
        break;
      case "replace":
        initializeArrays(before, change.path);
        initializeArrays(after, change.path);
        setPath(before, change.path, change.replaced);
        setPath(after, change.path, change.value);
        break;
    }
  }
  return [before, after];
};
function setPath(target, path, value2) {
  const keys2 = parsePath(path);
  let current3 = target;
  for (let i2 = 0; i2 < keys2.length - 1; i2++) {
    const key2 = keys2[i2];
    if (key2 && !(key2 in current3)) {
      const nextKey = keys2[i2 + 1];
      if (nextKey) {
        current3[key2] = isArrayIndex(nextKey) ? [] : {};
      }
      current3 = current3[key2];
    }
  }
  const lastKey = keys2[keys2.length - 1];
  if (lastKey) {
    current3[lastKey] = value2;
  }
}
function initializeArrays(target, path) {
  const keys2 = parsePath(path);
  let current3 = target;
  for (let i2 = 0; i2 < keys2.length - 1; i2++) {
    const key2 = keys2[i2];
    const nextKey = keys2[i2 + 1];
    if (!key2 || !nextKey) {
      continue;
    }
    if (isArrayIndex(nextKey)) {
      current3[key2] = initializeArray(
        current3[key2],
        nextKey
      );
    } else {
      current3[key2] = initializeObject(current3[key2]);
    }
    current3 = current3[key2];
  }
  const lastKey = keys2[keys2.length - 1];
  if (lastKey && isArrayIndex(lastKey)) {
    const lastValue = current3[lastKey];
    initializeArray(lastValue, lastKey);
  }
}
function parsePath(path) {
  return path.split("/").filter(Boolean);
}
function isArrayIndex(key2) {
  return /^\d+$/.test(key2);
}
function initializeArray(current3, nextKey) {
  if (!Array.isArray(current3)) {
    current3 = [];
  }
  const nextKeyIndex = parseInt(nextKey, 10);
  while (current3.length < nextKeyIndex) {
    current3.push("");
  }
  return current3;
}
function initializeObject(current3) {
  return current3 ?? {};
}
const StepEventView = ({
  eventNode,
  children: children2,
  className: className2
}) => {
  const event = eventNode.event;
  const descriptor = stepDescriptor(event);
  const title2 = descriptor.name || `${event.type ? event.type + ": " : "Step: "}${event.name}`;
  const text2 = summarize(children2);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    EventPanel,
    {
      eventNodeId: eventNode.id,
      depth: eventNode.depth,
      childIds: children2.map((child) => child.id),
      className: clsx("transcript-step", className2),
      title: title2,
      subTitle: formatDateTime(new Date(event.timestamp)),
      icon: descriptor.icon,
      text: text2
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/StepEventView.tsx",
      lineNumber: 33,
      columnNumber: 5
    },
    void 0
  );
};
const summarize = (children2) => {
  if (children2.length === 0) {
    return "(no events)";
  }
  const formatEvent = (event, count2) => {
    if (count2 === 1) {
      return `${count2} ${event} event`;
    } else {
      return `${count2} ${event} events`;
    }
  };
  const typeCount = {};
  children2.forEach((child) => {
    const currentCount = typeCount[child.event.event] || 0;
    typeCount[child.event.event] = currentCount + 1;
  });
  const numberOfTypes = Object.keys(typeCount).length;
  if (numberOfTypes < 3) {
    return Object.keys(typeCount).map((key2) => {
      return formatEvent(key2, typeCount[key2] || 0);
    }).join(", ");
  }
  if (children2.length === 1) {
    return "1 event";
  } else {
    return `${children2.length} events`;
  }
};
const stepDescriptor = (event) => {
  const rootStepDescriptor = {
    endSpace: true
  };
  if (event.type === "solver") {
    switch (event.name) {
      case "chain_of_thought":
        return {
          ...rootStepDescriptor
        };
      case "generate":
        return {
          ...rootStepDescriptor
        };
      case "self_critique":
        return {
          ...rootStepDescriptor
        };
      case "system_message":
        return {
          ...rootStepDescriptor
        };
      case "use_tools":
        return {
          ...rootStepDescriptor
        };
      case "multiple_choice":
        return {
          ...rootStepDescriptor
        };
      default:
        return {
          ...rootStepDescriptor
        };
    }
  } else if (event.type === "scorer") {
    return {
      ...rootStepDescriptor
    };
  } else if (event.event === "step") {
    if (event.name === kSandboxSignalName) {
      return {
        ...rootStepDescriptor,
        name: "Sandbox Events"
      };
    } else if (event.name === "init") {
      return {
        ...rootStepDescriptor,
        name: "Init"
      };
    } else {
      return {
        ...rootStepDescriptor
      };
    }
  } else {
    switch (event.name) {
      case "sample_init":
        return {
          ...rootStepDescriptor,
          name: "Sample Init"
        };
      default:
        return {
          endSpace: false
        };
    }
  }
};
const summary$1 = "_summary_ac4z2_1";
const summaryRendered = "_summaryRendered_ac4z2_6";
const subtaskSummary = "_subtaskSummary_ac4z2_10";
const subtaskLabel = "_subtaskLabel_ac4z2_17";
const styles$x = {
  summary: summary$1,
  summaryRendered,
  subtaskSummary,
  subtaskLabel
};
const SubtaskEventView = ({
  eventNode,
  children: children2,
  className: className2
}) => {
  const event = eventNode.event;
  const body = [];
  if (event.type === "fork") {
    body.push(
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { title: "Summary", className: clsx(styles$x.summary), children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("text-style-label"), children: "Inputs" }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SubtaskEventView.tsx",
          lineNumber: 32,
          columnNumber: 9
        }, void 0),
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$x.summaryRendered), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Rendered, { values: event.input }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SubtaskEventView.tsx",
          lineNumber: 34,
          columnNumber: 11
        }, void 0) }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SubtaskEventView.tsx",
          lineNumber: 33,
          columnNumber: 9
        }, void 0)
      ] }, void 0, true, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SubtaskEventView.tsx",
        lineNumber: 31,
        columnNumber: 7
      }, void 0)
    );
  } else {
    body.push(
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        SubtaskSummary,
        {
          "data-name": "Summary",
          input: event.input,
          result: event.result
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SubtaskEventView.tsx",
          lineNumber: 40,
          columnNumber: 7
        },
        void 0
      )
    );
  }
  const type = event.type === "fork" ? "Fork" : "Subtask";
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    EventPanel,
    {
      eventNodeId: eventNode.id,
      depth: eventNode.depth,
      className: className2,
      title: formatTitle(
        `${type}: ${event.name}`,
        void 0,
        event.working_time
      ),
      subTitle: formatTiming(event.timestamp, event.working_start),
      childIds: children2.map((child) => child.id),
      collapseControl: "bottom",
      children: body
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SubtaskEventView.tsx",
      lineNumber: 51,
      columnNumber: 5
    },
    void 0
  );
};
const SubtaskSummary = ({ input: input2, result: result2 }) => {
  const output2 = typeof result2 === "object" ? result2 : { result: result2 };
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$x.subtaskSummary), children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("text-style-label", "text-size-small"), children: "Input" }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SubtaskEventView.tsx",
      lineNumber: 80,
      columnNumber: 7
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("text-size-large", styles$x.subtaskLabel) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SubtaskEventView.tsx",
      lineNumber: 81,
      columnNumber: 7
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("text-style-label", "text-size-small"), children: "Output" }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SubtaskEventView.tsx",
      lineNumber: 82,
      columnNumber: 7
    }, void 0),
    input2 ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Rendered, { values: input2 }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SubtaskEventView.tsx",
      lineNumber: 83,
      columnNumber: 16
    }, void 0) : void 0,
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("text-size-title-secondary", styles$x.subtaskLabel), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("i", { className: ApplicationIcons.arrows.right }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SubtaskEventView.tsx",
      lineNumber: 85,
      columnNumber: 9
    }, void 0) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SubtaskEventView.tsx",
      lineNumber: 84,
      columnNumber: 7
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Rendered, { values: output2 }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SubtaskEventView.tsx",
      lineNumber: 88,
      columnNumber: 9
    }, void 0) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SubtaskEventView.tsx",
      lineNumber: 87,
      columnNumber: 7
    }, void 0)
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SubtaskEventView.tsx",
    lineNumber: 79,
    columnNumber: 5
  }, void 0);
};
const Rendered = ({ values: values2 }) => {
  if (Array.isArray(values2)) {
    return values2.map((val) => {
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Rendered, { values: val }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SubtaskEventView.tsx",
        lineNumber: 105,
        columnNumber: 14
      }, void 0);
    });
  } else if (values2 && typeof values2 === "object") {
    if (Object.keys(values2).length === 0) {
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(None, {}, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SubtaskEventView.tsx",
        lineNumber: 109,
        columnNumber: 14
      }, void 0);
    } else {
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(MetaDataGrid, { entries: values2 }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SubtaskEventView.tsx",
        lineNumber: 111,
        columnNumber: 14
      }, void 0);
    }
  } else {
    return String(values2);
  }
};
const None = () => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("span", { className: clsx("text-size-small", "text-style-secondary"), children: "[None]" }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/SubtaskEventView.tsx",
    lineNumber: 120,
    columnNumber: 5
  }, void 0);
};
const summary = "_summary_1qsnv_1";
const approval = "_approval_1qsnv_6";
const progress = "_progress_1qsnv_12";
const styles$w = {
  summary,
  approval,
  progress
};
const ToolEventView = ({
  eventNode,
  children: children2,
  className: className2
}) => {
  const event = eventNode.event;
  const { name: name2, input: input2, description: description2, functionCall, contentType } = reactExports.useMemo(
    () => resolveToolInput(event.function, event.arguments),
    [event.function, event.arguments]
  );
  const { approvalNode, lastModelNode } = reactExports.useMemo(() => {
    const approvalNode2 = children2.find((e) => {
      return e.event.event === "approval";
    });
    const lastModelNode2 = children2.findLast((e) => {
      return e.event.event === "model";
    });
    return {
      approvalNode: approvalNode2,
      lastModelNode: lastModelNode2
    };
  }, [event.events]);
  const title2 = `Tool: ${event.view?.title || event.function}`;
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    EventPanel,
    {
      eventNodeId: eventNode.id,
      depth: eventNode.depth,
      title: formatTitle(title2, void 0, event.working_time),
      className: className2,
      subTitle: formatTiming(event.timestamp, event.working_start),
      icon: ApplicationIcons.solvers.use_tools,
      childIds: children2.map((child) => child.id),
      collapseControl: "bottom",
      children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { "data-name": "Summary", className: styles$w.summary, children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          ToolCallView,
          {
            id: `${eventNode.id}-tool-call`,
            tool: name2,
            functionCall,
            input: input2,
            description: description2,
            contentType,
            output: event.error?.message || event.result,
            mode: "compact",
            view: event.view ? event.view : void 0
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ToolEventView.tsx",
            lineNumber: 69,
            columnNumber: 9
          },
          void 0
        ),
        lastModelNode ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          ChatView,
          {
            id: `${eventNode.id}-toolcall-chatmessage`,
            messages: lastModelNode.event.output.choices.map((m) => m.message),
            toolCallStyle: "compact",
            allowLinking: false
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ToolEventView.tsx",
            lineNumber: 82,
            columnNumber: 11
          },
          void 0
        ) : void 0,
        approvalNode ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          ApprovalEventView,
          {
            eventNode: approvalNode,
            className: styles$w.approval
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ToolEventView.tsx",
            lineNumber: 91,
            columnNumber: 11
          },
          void 0
        ) : "",
        event.pending ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$w.progress), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(PulsingDots, { subtle: false, size: "medium" }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ToolEventView.tsx",
          lineNumber: 100,
          columnNumber: 13
        }, void 0) }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ToolEventView.tsx",
          lineNumber: 99,
          columnNumber: 11
        }, void 0) : void 0
      ] }, void 0, true, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ToolEventView.tsx",
        lineNumber: 68,
        columnNumber: 7
      }, void 0)
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/ToolEventView.tsx",
      lineNumber: 58,
      columnNumber: 5
    },
    void 0
  );
};
const node = "_node_1r858_1";
const attached = "_attached_1r858_5";
const attachedParent = "_attachedParent_1r858_9";
const attachedChild = "_attachedChild_1r858_16";
const styles$v = {
  node,
  attached,
  attachedParent,
  attachedChild
};
const TranscriptVirtualListComponent = ({
  id: id2,
  listHandle,
  eventNodes,
  scrollRef,
  running,
  initialEventId,
  offsetTop,
  className: className2
}) => {
  const initialEventIndex = reactExports.useMemo(() => {
    if (initialEventId === null || initialEventId === void 0) {
      return void 0;
    }
    const result2 = eventNodes.findIndex((event) => {
      return event.id === initialEventId;
    });
    return result2 === -1 ? void 0 : result2;
  }, [initialEventId, eventNodes]);
  const hasToolEventsAtCurrentDepth = reactExports.useCallback(
    (startIndex) => {
      for (let i2 = startIndex; i2 >= 0; i2--) {
        const node2 = eventNodes[i2];
        if (!node2 || !eventNodes[startIndex]) {
          return false;
        }
        if (node2.event.event === "tool") {
          return true;
        }
        if (node2.depth < eventNodes[startIndex].depth) {
          return false;
        }
      }
      return false;
    },
    [eventNodes]
  );
  const contextWithToolEvents = reactExports.useMemo(() => ({ hasToolEvents: true }), []);
  const contextWithoutToolEvents = reactExports.useMemo(
    () => ({ hasToolEvents: false }),
    []
  );
  const renderRow = reactExports.useCallback(
    (index, item2) => {
      const paddingClass = index === 0 ? styles$v.first : void 0;
      const previousIndex = index - 1;
      const nextIndex2 = index + 1;
      const previous = previousIndex > 0 && previousIndex <= eventNodes.length ? eventNodes[previousIndex] : void 0;
      const next = nextIndex2 < eventNodes.length ? eventNodes[nextIndex2] : void 0;
      const attached2 = item2.event.event === "tool" && (previous?.event.event === "tool" || previous?.event.event === "model");
      const attachedParent2 = item2.event.event === "model" && next?.event.event === "tool";
      const attachedClass = attached2 ? styles$v.attached : void 0;
      const attachedChildClass = attached2 ? styles$v.attachedChild : void 0;
      const attachedParentClass = attachedParent2 ? styles$v.attachedParent : void 0;
      const hasToolEvents = hasToolEventsAtCurrentDepth(index);
      const context = hasToolEvents ? contextWithToolEvents : contextWithoutToolEvents;
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "div",
        {
          id: item2.id,
          className: clsx(styles$v.node, paddingClass, attachedClass),
          style: {
            paddingLeft: `${item2.depth <= 1 ? item2.depth * 0.7 : (0.7 + item2.depth - 1) * 1}em`,
            paddingRight: `${item2.depth === 0 ? void 0 : ".7em"} `
          },
          children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            RenderedEventNode,
            {
              node: item2,
              next,
              className: clsx(attachedParentClass, attachedChildClass),
              context
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/TranscriptVirtualListComponent.tsx",
              lineNumber: 114,
              columnNumber: 11
            },
            void 0
          )
        },
        item2.id,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/TranscriptVirtualListComponent.tsx",
          lineNumber: 105,
          columnNumber: 9
        },
        void 0
      );
    },
    [
      eventNodes,
      hasToolEventsAtCurrentDepth,
      contextWithToolEvents,
      contextWithoutToolEvents
    ]
  );
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    LiveVirtualList,
    {
      listHandle,
      className: className2,
      id: id2,
      scrollRef,
      data: eventNodes,
      initialTopMostItemIndex: initialEventIndex,
      offsetTop,
      renderRow,
      live: running
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/TranscriptVirtualListComponent.tsx",
      lineNumber: 132,
      columnNumber: 5
    },
    void 0
  );
};
const TranscriptVirtualList = reactExports.memo(
  (props) => {
    const {
      id: id2,
      scrollRef,
      eventNodes,
      listHandle,
      running,
      initialEventId,
      offsetTop,
      className: className2
    } = props;
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      TranscriptVirtualListComponent,
      {
        id: id2,
        listHandle,
        eventNodes,
        initialEventId,
        offsetTop,
        scrollRef,
        running,
        className: className2
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/TranscriptVirtualList.tsx",
        lineNumber: 71,
        columnNumber: 7
      },
      void 0
    );
  }
);
const RenderedEventNode = reactExports.memo(
  ({ node: node2, next, className: className2, context }) => {
    switch (node2.event.event) {
      case "sample_init":
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          SampleInitEventView,
          {
            eventNode: node2,
            className: className2
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/TranscriptVirtualList.tsx",
            lineNumber: 103,
            columnNumber: 11
          },
          void 0
        );
      case "sample_limit":
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          SampleLimitEventView,
          {
            eventNode: node2,
            className: className2
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/TranscriptVirtualList.tsx",
            lineNumber: 111,
            columnNumber: 11
          },
          void 0
        );
      case "info":
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          InfoEventView,
          {
            eventNode: node2,
            className: className2
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/TranscriptVirtualList.tsx",
            lineNumber: 119,
            columnNumber: 11
          },
          void 0
        );
      case "logger":
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          LoggerEventView,
          {
            eventNode: node2,
            className: className2
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/TranscriptVirtualList.tsx",
            lineNumber: 127,
            columnNumber: 11
          },
          void 0
        );
      case "model":
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          ModelEventView,
          {
            eventNode: node2,
            showToolCalls: next?.event.event !== "tool",
            className: className2,
            context
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/TranscriptVirtualList.tsx",
            lineNumber: 135,
            columnNumber: 11
          },
          void 0
        );
      case "score":
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          ScoreEventView,
          {
            eventNode: node2,
            className: className2
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/TranscriptVirtualList.tsx",
            lineNumber: 145,
            columnNumber: 11
          },
          void 0
        );
      case "score_edit":
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          ScoreEditEventView,
          {
            eventNode: node2,
            className: className2
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/TranscriptVirtualList.tsx",
            lineNumber: 153,
            columnNumber: 11
          },
          void 0
        );
      case "state":
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          StateEventView,
          {
            eventNode: node2,
            className: className2
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/TranscriptVirtualList.tsx",
            lineNumber: 161,
            columnNumber: 11
          },
          void 0
        );
      case "span_begin":
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          SpanEventView,
          {
            eventNode: node2,
            children: node2.children,
            className: className2
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/TranscriptVirtualList.tsx",
            lineNumber: 169,
            columnNumber: 11
          },
          void 0
        );
      case "step":
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          StepEventView,
          {
            eventNode: node2,
            children: node2.children,
            className: className2
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/TranscriptVirtualList.tsx",
            lineNumber: 178,
            columnNumber: 11
          },
          void 0
        );
      case "store":
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          StateEventView,
          {
            eventNode: node2,
            className: className2
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/TranscriptVirtualList.tsx",
            lineNumber: 187,
            columnNumber: 11
          },
          void 0
        );
      case "subtask":
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          SubtaskEventView,
          {
            eventNode: node2,
            className: className2,
            children: node2.children
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/TranscriptVirtualList.tsx",
            lineNumber: 195,
            columnNumber: 11
          },
          void 0
        );
      case "tool":
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          ToolEventView,
          {
            eventNode: node2,
            className: className2,
            children: node2.children
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/TranscriptVirtualList.tsx",
            lineNumber: 204,
            columnNumber: 11
          },
          void 0
        );
      case "input":
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          InputEventView,
          {
            eventNode: node2,
            className: className2
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/TranscriptVirtualList.tsx",
            lineNumber: 213,
            columnNumber: 11
          },
          void 0
        );
      case "error":
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          ErrorEventView,
          {
            eventNode: node2,
            className: className2
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/TranscriptVirtualList.tsx",
            lineNumber: 221,
            columnNumber: 11
          },
          void 0
        );
      case "approval":
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          ApprovalEventView,
          {
            eventNode: node2,
            className: className2
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/TranscriptVirtualList.tsx",
            lineNumber: 229,
            columnNumber: 11
          },
          void 0
        );
      case "sandbox":
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          SandboxEventView,
          {
            eventNode: node2,
            className: className2
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/TranscriptVirtualList.tsx",
            lineNumber: 237,
            columnNumber: 11
          },
          void 0
        );
      default:
        return null;
    }
  }
);
const flatTree = (eventNodes, collapsed, visitors2, parentNode) => {
  const result2 = [];
  for (const node2 of eventNodes) {
    {
      result2.push(node2);
      const children2 = flatTree(node2.children, collapsed);
      if (collapsed === null || collapsed[node2.id] !== true) {
        result2.push(...children2);
      }
    }
  }
  return result2;
};
const transformTree = (roots) => {
  const treeNodeTransformers = transformers();
  const visitNode = (node2) => {
    let currentNodes = [node2];
    currentNodes = currentNodes.map((n2) => {
      n2.children = n2.children.flatMap(visitNode);
      return n2;
    });
    for (const transformer of treeNodeTransformers) {
      const nextNodes = [];
      for (const currentNode of currentNodes) {
        if (transformer.matches(currentNode)) {
          const result2 = transformer.process(currentNode);
          if (Array.isArray(result2)) {
            nextNodes.push(...result2);
          } else {
            nextNodes.push(result2);
          }
        } else {
          nextNodes.push(currentNode);
        }
      }
      currentNodes = nextNodes;
    }
    return currentNodes && currentNodes.length === 1 && currentNodes[0] ? currentNodes[0] : currentNodes;
  };
  const processedRoots = roots.flatMap(visitNode);
  const flushedNodes = [];
  for (const transformer of treeNodeTransformers) {
    if (transformer.flush) {
      const flushResults = transformer.flush();
      if (flushResults && flushResults.length > 0) {
        flushedNodes.push(...flushResults);
      }
    }
  }
  return [...processedRoots, ...flushedNodes];
};
const transformers = () => {
  const treeNodeTransformers = [
    {
      name: "unwrap_tools",
      matches: (node2) => node2.event.event === SPAN_BEGIN && node2.event.type === TYPE_TOOL,
      process: (node2) => elevateChildNode(node2, TYPE_TOOL) || node2
    },
    {
      name: "unwrap_subtasks",
      matches: (node2) => node2.event.event === SPAN_BEGIN && node2.event.type === TYPE_SUBTASK,
      process: (node2) => elevateChildNode(node2, TYPE_SUBTASK) || node2
    },
    {
      name: "unwrap_agent_solver",
      matches: (node2) => node2.event.event === SPAN_BEGIN && node2.event["type"] === TYPE_SOLVER && node2.children.length === 2 && node2.children[0]?.event.event === SPAN_BEGIN && node2.children[0]?.event.type === TYPE_AGENT && node2.children[1]?.event.event === STATE,
      process: (node2) => skipFirstChildNode(node2)
    },
    {
      name: "unwrap_agent_solver w/store",
      matches: (node2) => node2.event.event === SPAN_BEGIN && node2.event["type"] === TYPE_SOLVER && node2.children.length === 3 && node2.children[0]?.event.event === SPAN_BEGIN && node2.children[0]?.event.type === TYPE_AGENT && node2.children[1]?.event.event === STATE && node2.children[2]?.event.event === STORE,
      process: (node2) => skipFirstChildNode(node2)
    },
    {
      name: "unwrap_handoff",
      matches: (node2) => {
        const isHandoffNode = node2.event.event === SPAN_BEGIN && node2.event["type"] === TYPE_HANDOFF;
        if (!isHandoffNode) {
          return false;
        }
        if (node2.children.length === 1) {
          return node2.children[0]?.event.event === TOOL && !!node2.children[0]?.event.agent;
        } else {
          return node2.children.length === 2 && node2.children[0]?.event.event === TOOL && node2.children[1]?.event.event === STORE && node2.children[0]?.children.length === 2 && node2.children[0]?.children[0]?.event.event === SPAN_BEGIN && node2.children[0]?.children[0]?.event.type === TYPE_AGENT;
        }
      },
      process: (node2) => skipThisNode(node2)
    },
    {
      name: "discard_solvers_span",
      matches: (Node3) => Node3.event.event === SPAN_BEGIN && Node3.event.type === TYPE_SOLVERS,
      process: (node2) => {
        const nodes = discardNode(node2);
        return nodes;
      }
    }
  ];
  return treeNodeTransformers;
};
const elevateChildNode = (node2, childEventType) => {
  const targetIndex = node2.children.findIndex(
    (child) => child.event.event === childEventType
  );
  if (targetIndex === -1) {
    console.log(
      `No ${childEventType} event found in a span, this is very unexpected.`
    );
    return null;
  }
  const targetNode = { ...node2.children[targetIndex] };
  const remainingChildren = node2.children.filter((_, i2) => i2 !== targetIndex);
  targetNode.depth = node2.depth;
  targetNode.children = setDepth(remainingChildren, node2.depth + 1);
  return targetNode;
};
const skipFirstChildNode = (node2) => {
  const agentSpan = node2.children.splice(0, 1)[0];
  node2.children.unshift(...reduceDepth(agentSpan?.children || []));
  return node2;
};
const skipThisNode = (node2) => {
  const newNode = { ...node2.children[0] };
  newNode.depth = node2.depth;
  newNode.children = reduceDepth(newNode.children || [], 2);
  return newNode;
};
const discardNode = (node2) => {
  const nodes = reduceDepth(node2.children, 1);
  return nodes;
};
const reduceDepth = (nodes, depth = 1) => {
  return nodes.map((node2) => {
    if (node2.children.length > 0) {
      node2.children = reduceDepth(node2.children, 1);
    }
    node2.depth = node2.depth - depth;
    return node2;
  });
};
const setDepth = (nodes, depth) => {
  return nodes.map((node2) => {
    if (node2.children.length > 0) {
      node2.children = setDepth(node2.children, depth + 1);
    }
    node2.depth = depth;
    return node2;
  });
};
function treeifyEvents(events, depth) {
  const useSpans = hasSpans(events);
  events = injectScorersSpan(events);
  const nodes = useSpans ? treeifyWithSpans(events, depth) : treeifyWithSteps(events, depth);
  return useSpans ? transformTree(nodes) : nodes;
}
const treeifyWithSpans = (events, depth) => {
  const { rootNodes, createNode } = createNodeFactory(depth);
  const spanNodes = /* @__PURE__ */ new Map();
  const processEvent = (event, parentOverride) => {
    if (event.event === SPAN_END) {
      return;
    }
    if (event.event === STEP && event.action !== ACTION_BEGIN) {
      return;
    }
    const resolvedParent = resolveParentForEvent(event, spanNodes);
    const parentNode = resolvedParent ?? null;
    const node2 = createNode(event, parentNode);
    if (event.event === SPAN_BEGIN) {
      const spanId = getEventSpanId(event);
      if (spanId !== null) {
        spanNodes.set(spanId, node2);
      }
    }
  };
  events.forEach((event) => processEvent(event));
  return rootNodes;
};
const treeifyWithSteps = (events, depth) => {
  const { rootNodes, createNode } = createNodeFactory(depth);
  const stack2 = [];
  const pushStack = (node2) => {
    stack2.push(node2);
  };
  const popStack = () => {
    if (stack2.length > 0) {
      stack2.pop();
    }
  };
  const processEvent = (event) => {
    const parent = stack2.length > 0 ? stack2[stack2.length - 1] : null;
    switch (event.event) {
      case STEP:
        if (event.action === ACTION_BEGIN) {
          const node2 = createNode(event, parent || null);
          pushStack(node2);
        } else {
          popStack();
        }
        break;
      case SPAN_BEGIN: {
        const node2 = createNode(event, parent || null);
        pushStack(node2);
        break;
      }
      case SPAN_END:
        popStack();
        break;
      default:
        createNode(event, parent || null);
        break;
    }
  };
  events.forEach(processEvent);
  return rootNodes;
};
const createNodeFactory = (depth) => {
  const rootNodes = [];
  const childCounts = /* @__PURE__ */ new Map();
  const pathByNode = /* @__PURE__ */ new Map();
  const createNode = (event, parent) => {
    const parentKey = parent ?? null;
    const nextIndex2 = childCounts.get(parentKey) ?? 0;
    childCounts.set(parentKey, nextIndex2 + 1);
    const parentPath = parent ? pathByNode.get(parent) : void 0;
    const path = parentPath !== void 0 ? `${parentPath}.${nextIndex2}` : `${nextIndex2}`;
    const eventId = event.uuid || `event_node_${path}`;
    const nodeDepth = parent ? parent.depth + 1 : depth;
    const node2 = new EventNode(eventId, event, nodeDepth);
    pathByNode.set(node2, path);
    if (parent) {
      parent.children.push(node2);
    } else {
      rootNodes.push(node2);
    }
    return node2;
  };
  return { rootNodes, createNode };
};
const resolveParentForEvent = (event, spanNodes) => {
  if (event.event === SPAN_BEGIN) {
    const parentId = event.parent_id;
    if (parentId) {
      return spanNodes.get(parentId) ?? null;
    }
    return null;
  }
  const spanId = getEventSpanId(event);
  if (spanId !== null) {
    return spanNodes.get(spanId) ?? null;
  }
  return null;
};
const getEventSpanId = (event) => {
  const spanId = event.span_id;
  return spanId ?? null;
};
const kBeginScorerId = "E617087FA405";
const kEndScorerId = "C39922B09481";
const kScorersSpanId = "C5A831026F2C";
const injectScorersSpan = (events) => {
  const results = [];
  const collectedScorerEvents = [];
  let hasCollectedScorers = false;
  let collecting = null;
  const flushCollected = () => {
    if (collectedScorerEvents.length > 0) {
      const beginSpan = {
        name: "scorers",
        id: kBeginScorerId,
        span_id: kScorersSpanId,
        event: SPAN_BEGIN,
        type: TYPE_SCORERS,
        timestamp: collectedScorerEvents[0]?.timestamp || "",
        working_start: collectedScorerEvents[0]?.working_start || 0,
        pending: false,
        parent_id: null,
        uuid: null,
        metadata: null
      };
      const scoreEvents = collectedScorerEvents.map(
        (event) => {
          return {
            ...event,
            parent_id: event.event === "span_begin" ? event.parent_id || kScorersSpanId : null
          };
        }
      );
      const endSpan = {
        id: kEndScorerId,
        span_id: kScorersSpanId,
        event: SPAN_END,
        pending: false,
        working_start: collectedScorerEvents[collectedScorerEvents.length - 1]?.working_start || 0,
        timestamp: collectedScorerEvents[collectedScorerEvents.length - 1]?.timestamp || "",
        uuid: null,
        metadata: null
      };
      collectedScorerEvents.length = 0;
      hasCollectedScorers = true;
      return [beginSpan, ...scoreEvents, endSpan];
    }
    return [];
  };
  for (const event of events) {
    if (event.event === SPAN_BEGIN && event.type === TYPE_SCORERS) {
      return events;
    }
    if (event.event === SPAN_BEGIN && event.type === TYPE_SCORER && !hasCollectedScorers) {
      collecting = event.span_id;
    }
    if (collecting) {
      if (event.event === SPAN_END && event.span_id === collecting) {
        collecting = null;
        results.push(...flushCollected());
        results.push(event);
      } else {
        collectedScorerEvents.push(event);
      }
    } else {
      results.push(event);
    }
  }
  return results;
};
const useEventNodes = (events, running) => {
  const { eventTree, defaultCollapsedIds } = reactExports.useMemo(() => {
    const resolvedEvents = fixupEventStream(events, !running);
    const rawEventTree = treeifyEvents(resolvedEvents, 0);
    const filterEmpty = (eventNodes) => {
      return eventNodes.filter((node2) => {
        if (node2.children && node2.children.length > 0) {
          node2.children = filterEmpty(node2.children);
        }
        return node2.event.event !== "span_begin" && node2.event.event !== "step" || node2.children && node2.children.length > 0;
      });
    };
    const eventTree2 = filterEmpty(rawEventTree);
    const defaultCollapsedIds2 = {};
    const findCollapsibleEvents = (nodes) => {
      for (const node2 of nodes) {
        if (kCollapsibleEventTypes.includes(node2.event.event) && collapseFilters.some(
          (filter2) => filter2(
            node2.event
          )
        )) {
          defaultCollapsedIds2[node2.id] = true;
        }
        findCollapsibleEvents(node2.children);
      }
    };
    findCollapsibleEvents(eventTree2);
    return { eventTree: eventTree2, defaultCollapsedIds: defaultCollapsedIds2 };
  }, [events, running]);
  return { eventNodes: eventTree, defaultCollapsedIds };
};
const collapseFilters = [
  (event) => event.type === "solver" && event.name === "system_message",
  (event) => {
    if (event.event === "step" || event.event === "span_begin") {
      return event.name === kSandboxSignalName || event.name === "init" || event.name === "sample_init";
    }
    return false;
  },
  (event) => event.event === "tool" && !event.agent && !event.failed,
  (event) => event.event === "subtask"
];
const TranscriptView = ({
  id: id2,
  events,
  nodeFilter,
  scrollRef,
  initialEventId
}) => {
  const listHandle = reactExports.useRef(null);
  const collapsedEvents = useStore((state) => state.transcriptCollapsedEvents);
  const { eventNodes, defaultCollapsedIds } = useEventNodes(
    events || [],
    false
  );
  const flattenedNodes = reactExports.useMemo(() => {
    return flatTree(
      nodeFilter ? nodeFilter(eventNodes) : eventNodes,
      (collapsedEvents ? collapsedEvents[kTranscriptCollapseScope] : void 0) || defaultCollapsedIds
    );
  }, [eventNodes, collapsedEvents, defaultCollapsedIds]);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    TranscriptVirtualList,
    {
      id: id2,
      listHandle,
      eventNodes: flattenedNodes,
      scrollRef,
      offsetTop: 10,
      className: styles$O.listContainer,
      initialEventId
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/transcript/TranscriptView.tsx",
      lineNumber: 48,
      columnNumber: 5
    },
    void 0
  );
};
const container$9 = "_container_kyylo_1";
const styles$u = {
  container: container$9
};
const InputPanel = ({ result: result2 }) => {
  const scrollRef = reactExports.useRef(null);
  const [searchParams] = useSearchParams();
  const initialMessageId = searchParams.get("message");
  const initialEventId = searchParams.get("event");
  const highlightLabeled = useStore((state) => state.highlightLabeled);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { ref: scrollRef, className: clsx(styles$u.container), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    InputRenderer,
    {
      result: result2,
      scrollRef,
      initialMessageId,
      initialEventId,
      highlightLabeled
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/input/InputPanel.tsx",
      lineNumber: 28,
      columnNumber: 7
    },
    void 0
  ) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/input/InputPanel.tsx",
    lineNumber: 27,
    columnNumber: 5
  }, void 0);
};
const InputRenderer = ({
  result: result2,
  className: className2,
  scrollRef,
  initialMessageId,
  initialEventId,
  highlightLabeled
}) => {
  switch (result2?.inputType) {
    case "transcript": {
      if (result2.input.messages.length > 0) {
        const labels = result2?.messageReferences.reduce(
          (acc, ref2) => {
            if (ref2.cite) {
              acc[ref2.id] = ref2.cite;
            }
            return acc;
          },
          {}
        );
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          ChatViewVirtualList,
          {
            messages: result2.input.messages,
            allowLinking: false,
            id: "scan-input-virtual-list",
            toolCallStyle: "complete",
            indented: true,
            className: className2,
            scrollRef,
            initialMessageId,
            showLabels: true,
            highlightLabeled,
            labels
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/input/InputPanel.tsx",
            lineNumber: 70,
            columnNumber: 11
          },
          void 0
        );
      } else if (result2.input.events.length > 0) {
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          TranscriptView,
          {
            id: "scan-input-transcript",
            events: result2.input.events,
            scrollRef,
            initialEventId
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/input/InputPanel.tsx",
            lineNumber: 86,
            columnNumber: 11
          },
          void 0
        );
      } else {
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: "No Transcript Input Available" }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/input/InputPanel.tsx",
          lineNumber: 94,
          columnNumber: 16
        }, void 0);
      }
    }
    case "messages": {
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        ChatViewVirtualList,
        {
          messages: result2.input,
          allowLinking: false,
          id: "scan-input-virtual-list",
          toolCallStyle: "complete",
          indented: true,
          className: className2,
          scrollRef,
          initialMessageId
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/input/InputPanel.tsx",
          lineNumber: 99,
          columnNumber: 9
        },
        void 0
      );
    }
    case "message": {
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        ChatViewVirtualList,
        {
          messages: [result2.input],
          allowLinking: false,
          id: "scan-input-virtual-list",
          toolCallStyle: "complete",
          indented: true,
          className: className2,
          scrollRef,
          initialMessageId
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/input/InputPanel.tsx",
          lineNumber: 113,
          columnNumber: 9
        },
        void 0
      );
    }
    case "events": {
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        TranscriptView,
        {
          id: "scan-input-transcript",
          events: result2.input,
          scrollRef,
          initialEventId
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/input/InputPanel.tsx",
          lineNumber: 127,
          columnNumber: 9
        },
        void 0
      );
    }
    case "event": {
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        TranscriptView,
        {
          id: "scan-input-transcript",
          events: [result2.input],
          scrollRef,
          initialEventId
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/input/InputPanel.tsx",
          lineNumber: 137,
          columnNumber: 9
        },
        void 0
      );
    }
    default:
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: "Unknown Input Type" }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/input/InputPanel.tsx",
        lineNumber: 146,
        columnNumber: 14
      }, void 0);
  }
};
const toMarkdownRefs = (core, makeReferenceUrl) => {
  const refLookup = referenceTable(core);
  const refs = [];
  for (const ref2 of core.messageReferences) {
    const renderPreview = refLookup[ref2.id];
    if (ref2.cite && renderPreview) {
      refs.push({
        id: ref2.id,
        cite: ref2.cite,
        citePreview: renderPreview,
        citeUrl: makeReferenceUrl(ref2.id, "message")
      });
    }
  }
  for (const ref2 of core.eventReferences) {
    const renderPreview = refLookup[ref2.id];
    if (ref2.cite && renderPreview) {
      refs.push({
        id: ref2.id,
        cite: ref2.cite,
        citePreview: renderPreview,
        citeUrl: makeReferenceUrl(ref2.id, "event")
      });
    }
  }
  return refs;
};
const referenceTable = (result2) => {
  if (!result2) {
    return {};
  }
  if (!result2.input) {
    return {};
  }
  if (result2.inputType === "message") {
    if (!result2.input.id) {
      return {};
    }
    return {
      [result2.input.id]: () => {
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          ChatView,
          {
            messages: [result2.input],
            resolveToolCallsIntoPreviousMessage: false
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/utils/refs.tsx",
            lineNumber: 64,
            columnNumber: 11
          },
          void 0
        );
      }
    };
  } else if (result2.inputType === "messages") {
    return result2.input.reduce((acc, msg) => {
      if (msg.id) {
        acc[msg.id] = () => {
          return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            ChatView,
            {
              messages: [msg],
              resolveToolCallsIntoPreviousMessage: false
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/utils/refs.tsx",
              lineNumber: 76,
              columnNumber: 13
            },
            void 0
          );
        };
      }
      return acc;
    }, {});
  } else if (result2.inputType === "event") {
    if (!result2.input.uuid) {
      return {};
    }
    return {
      [result2.input.uuid]: () => {
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(TranscriptView, { id: "input-event-preview", events: [result2.input] }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/utils/refs.tsx",
          lineNumber: 93,
          columnNumber: 11
        }, void 0);
      }
    };
  } else if (result2.inputType === "events") {
    return result2.input.reduce(
      (acc, event, index) => {
        if (event.uuid) {
          acc[event.uuid] = () => {
            return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
              TranscriptView,
              {
                id: `input-event-preview-${index}`,
                events: result2.input
              },
              void 0,
              false,
              {
                fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/utils/refs.tsx",
                lineNumber: 103,
                columnNumber: 15
              },
              void 0
            );
          };
        }
        return acc;
      },
      {}
    );
  } else if (result2.inputType === "transcript") {
    const eventRefs = result2.input.events.reduce((acc, event) => {
      if (event.uuid) {
        acc[event.uuid] = () => {
          return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(TranscriptView, { id: "input-event-preview", events: [event] }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/utils/refs.tsx",
            lineNumber: 120,
            columnNumber: 18
          }, void 0);
        };
      }
      return acc;
    }, {});
    const messageRefs = result2.input.messages.reduce((acc, msg) => {
      if (msg.id) {
        acc[msg.id] = () => {
          return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            ChatView,
            {
              messages: [msg],
              resolveToolCallsIntoPreviousMessage: false
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/utils/refs.tsx",
              lineNumber: 132,
              columnNumber: 13
            },
            void 0
          );
        };
      }
      return acc;
    }, {});
    return { ...eventRefs, ...messageRefs };
  } else {
    return {};
  }
};
const Explanation = ({ result: result2 }) => {
  const params = useParams();
  const buildUrl = reactExports.useMemo(() => {
    if (!result2?.uuid) {
      return (queryParams) => `?${queryParams}`;
    }
    const relativePath = getRelativePathFromParams(params);
    const { scanPath } = parseScanResultPath(relativePath);
    return (queryParams) => {
      const searchParams = new URLSearchParams(queryParams);
      return `#${scanResultRoute(scanPath, result2.uuid, searchParams)}`;
    };
  }, [result2?.uuid, params]);
  const refs = result2 ? toMarkdownRefs(result2, (refId, type) => {
    if (type === "message") {
      return buildUrl(`tab=Input&message=${encodeURIComponent(refId)}`);
    } else {
      return buildUrl(`tab=Input&event=${encodeURIComponent(refId)}`);
    }
  }) : [];
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    MarkdownDivWithReferences,
    {
      markdown: result2?.explanation || "",
      references: refs
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/values/Explanation.tsx",
      lineNumber: 50,
      columnNumber: 5
    },
    void 0
  );
};
const result = "_result_f18wg_1";
const styles$t = {
  result,
  "true": "_true_f18wg_12",
  "false": "_false_f18wg_17"
};
const ValidationResult = ({ result: result2 }) => {
  if (typeof result2 === "boolean") {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Result, { value: result2 }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/values/ValidationResult.tsx",
      lineNumber: 14,
      columnNumber: 12
    }, void 0);
  } else if (typeof result2 === "object") {
    const entries2 = Object.entries(result2);
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$t.validationTable), children: entries2.map(([_key, value2]) => /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Result, { value: value2 }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/values/ValidationResult.tsx",
      lineNumber: 22,
      columnNumber: 13
    }, void 0) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/values/ValidationResult.tsx",
      lineNumber: 21,
      columnNumber: 11
    }, void 0)) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/values/ValidationResult.tsx",
      lineNumber: 19,
      columnNumber: 7
    }, void 0);
  }
};
const Result = ({ value: value2 }) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(value2 ? styles$t.true : styles$t.false, styles$t.result), children: value2 ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("i", { className: clsx(ApplicationIcons.check) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/values/ValidationResult.tsx",
    lineNumber: 34,
    columnNumber: 9
  }, void 0) : /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("i", { className: clsx(ApplicationIcons.x) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/values/ValidationResult.tsx",
    lineNumber: 36,
    columnNumber: 9
  }, void 0) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/values/ValidationResult.tsx",
    lineNumber: 32,
    columnNumber: 5
  }, void 0);
};
const printArray = (arr, size = 50) => {
  const envelope = ["[", "]"];
  const ellipsis2 = "…";
  const separator2 = ", ";
  let remainingSize = size - (envelope[0]?.length || 0) - (envelope[1]?.length || 0) - separator2.length;
  const headItems = [];
  const tailItems = [];
  let headIdx = 0;
  let tailIdx = arr.length - 1;
  while (headIdx <= tailIdx) {
    const headStr = String(arr[headIdx]);
    const tailStr = String(arr[tailIdx]);
    if (headIdx === tailIdx) {
      if (headStr.length <= remainingSize) {
        headItems.push(headStr);
      } else {
        headItems.push(ellipsis2);
      }
      break;
    }
    const bothSize = headStr.length + tailStr.length + separator2.length;
    if (bothSize <= remainingSize) {
      headItems.push(headStr);
      tailItems.unshift(tailStr);
      remainingSize -= bothSize;
      headIdx++;
      tailIdx--;
    } else {
      headItems.push(ellipsis2);
      break;
    }
  }
  if (headItems.length === 0 && arr.length > 0) {
    const firstStr = String(arr[0]);
    const truncateSize = remainingSize - ellipsis2.length;
    if (truncateSize > 0) {
      headItems.push(firstStr.slice(0, truncateSize) + ellipsis2);
      headItems.push(ellipsis2);
    } else {
      headItems.push(ellipsis2);
    }
  }
  const allItems = [...headItems, ...tailItems];
  return envelope[0] + allItems.join(separator2) + envelope[1];
};
const printObject = (val, size = 50) => {
  const envelope = ["{", "}"];
  const ellipsis2 = "…";
  const separator2 = ", ";
  const kvSeparator = ": ";
  let remainingSize = size - (envelope[0]?.length || 0) - (envelope[1]?.length || 0);
  const entries2 = Object.entries(val);
  const headItems = [];
  const tailItems = [];
  let headIdx = 0;
  let tailIdx = entries2.length - 1;
  while (headIdx <= tailIdx) {
    const headPair = `${entries2[headIdx]?.[0]}${kvSeparator}${JSON.stringify(entries2[headIdx]?.[1])}`;
    const tailPair = `${entries2[tailIdx]?.[0]}${kvSeparator}${JSON.stringify(entries2[tailIdx]?.[1])}`;
    if (headIdx === tailIdx) {
      if (headPair.length <= remainingSize) {
        headItems.push(headPair);
      } else {
        headItems.push(ellipsis2);
      }
      break;
    }
    const bothSize = headPair.length + tailPair.length + separator2.length;
    if (bothSize <= remainingSize) {
      headItems.push(headPair);
      tailItems.unshift(tailPair);
      remainingSize -= bothSize;
      headIdx++;
      tailIdx--;
    } else if (headPair.length + separator2.length + ellipsis2.length <= remainingSize) {
      headItems.push(headPair);
      headItems.push(ellipsis2);
      break;
    } else {
      headItems.push(ellipsis2);
      break;
    }
  }
  if (headItems.length === 0 && entries2.length > 0) {
    const firstPair = `${entries2[0]?.[0]}${kvSeparator}${JSON.stringify(entries2[0]?.[1])}`;
    const truncateSize = remainingSize - ellipsis2.length - separator2.length;
    if (truncateSize > 0) {
      headItems.push(firstPair.slice(0, truncateSize) + ellipsis2);
      headItems.push(ellipsis2);
    } else {
      headItems.push(ellipsis2);
    }
  }
  const allItems = [...headItems, ...tailItems];
  return envelope[0] + allItems.join(separator2) + envelope[1];
};
function isStringValue(result2) {
  return result2.valueType === "string";
}
function isNumberValue(result2) {
  return result2.valueType === "number";
}
function isBooleanValue(result2) {
  return result2.valueType === "boolean";
}
function isNullValue(result2) {
  return result2.valueType === "null";
}
function isArrayValue(result2) {
  return result2.valueType === "array";
}
function isObjectValue(result2) {
  return result2.valueType === "object";
}
const boolean = "_boolean_1uivt_1";
const valueTable = "_valueTable_1uivt_24";
const inline = "_inline_1uivt_31";
const valueValue = "_valueValue_1uivt_31";
const value = "_value_1uivt_24";
const styles$s = {
  boolean,
  "true": "_true_1uivt_12",
  "false": "_false_1uivt_18",
  valueTable,
  inline,
  valueValue,
  value
};
const Value = ({
  result: result2,
  style: style2,
  maxTableSize = 5,
  interactive = false
}) => {
  const params = useParams();
  const buildUrl = reactExports.useMemo(() => {
    if (!result2?.uuid) {
      return (queryParams) => `?${queryParams}`;
    }
    const relativePath = getRelativePathFromParams(params);
    const { scanPath } = parseScanResultPath(relativePath);
    return (queryParams) => {
      const searchParams = new URLSearchParams(queryParams);
      return `#${scanResultRoute(scanPath, result2.uuid, searchParams)}`;
    };
  }, [result2?.uuid, params]);
  if (isStringValue(result2)) {
    return `"${result2.value}"`;
  } else if (isNumberValue(result2) && result2.value !== null) {
    return formatPrettyDecimal(result2.value);
  } else if (isBooleanValue(result2)) {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "div",
      {
        className: clsx(
          styles$s.boolean,
          result2.value ? styles$s.true : styles$s.false
        ),
        children: String(result2.value)
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/values/Value.tsx",
        lineNumber: 66,
        columnNumber: 7
      },
      void 0
    );
  } else if (isNullValue(result2)) {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("code", { children: "null" }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/values/Value.tsx",
      lineNumber: 76,
      columnNumber: 12
    }, void 0);
  } else if (isArrayValue(result2)) {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      ValueList2,
      {
        value: result2.value,
        result: result2,
        buildUrl,
        style: style2,
        maxListSize: maxTableSize,
        interactive
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/values/Value.tsx",
        lineNumber: 79,
        columnNumber: 7
      },
      void 0
    );
  } else if (isObjectValue(result2)) {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      ValueTable,
      {
        value: result2.value,
        result: result2,
        buildUrl,
        style: style2,
        maxTableSize,
        interactive
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/values/Value.tsx",
        lineNumber: 90,
        columnNumber: 7
      },
      void 0
    );
  } else {
    return "Unknown value type";
  }
};
const ValueList2 = ({ value: value2, result: result2, maxListSize, interactive, buildUrl, style: style2 }) => {
  const itemsToDisplay = value2.slice(0, maxListSize);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "div",
    {
      className: clsx(
        styles$s.valueTable,
        style2 === "inline" ? styles$s.inline : styles$s.block
      ),
      children: itemsToDisplay.map((item2, index) => {
        const displayValue = renderValue(
          index,
          item2,
          result2,
          buildUrl,
          interactive
        );
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(reactExports.Fragment, { children: [
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            "div",
            {
              className: clsx(
                styles$s.valueKey,
                "text-style-label",
                "text-style-secondary",
                "text-size-smallest"
              ),
              children: [
                "[",
                index,
                "]"
              ]
            },
            void 0,
            true,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/values/Value.tsx",
              lineNumber: 133,
              columnNumber: 13
            },
            void 0
          ),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$s.valueValue), children: displayValue }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/values/Value.tsx",
            lineNumber: 143,
            columnNumber: 13
          }, void 0)
        ] }, `value-table-row-${index}`, true, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/values/Value.tsx",
          lineNumber: 132,
          columnNumber: 11
        }, void 0);
      })
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/values/Value.tsx",
      lineNumber: 117,
      columnNumber: 5
    },
    void 0
  );
};
const ValueTable = ({ value: value2, result: result2, maxTableSize, interactive, buildUrl, style: style2 }) => {
  const keys2 = Object.keys(value2);
  const keysToDisplay = keys2.slice(0, maxTableSize);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "div",
    {
      className: clsx(
        styles$s.valueTable,
        style2 === "inline" ? styles$s.inline : styles$s.block
      ),
      children: keysToDisplay.map((key2, index) => {
        const displayValue = renderValue(
          index,
          value2[key2],
          result2,
          buildUrl,
          interactive
        );
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(reactExports.Fragment, { children: [
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            "div",
            {
              className: clsx(
                styles$s.valueKey,
                "text-style-label",
                "text-style-secondary",
                "text-size-smallest"
              ),
              children: key2
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/values/Value.tsx",
              lineNumber: 181,
              columnNumber: 13
            },
            void 0
          ),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$s.valueValue), children: displayValue }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/values/Value.tsx",
            lineNumber: 191,
            columnNumber: 13
          }, void 0)
        ] }, `value-table-row-${key2}`, true, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/values/Value.tsx",
          lineNumber: 180,
          columnNumber: 11
        }, void 0);
      })
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/values/Value.tsx",
      lineNumber: 165,
      columnNumber: 5
    },
    void 0
  );
};
const renderValue = (index, val, result2, buildUrl, interactive) => {
  if (typeof val === "string") {
    const refs = toMarkdownRefs(
      result2,
      (refId, type) => {
        if (type === "message") {
          return buildUrl(`tab=Input&message=${encodeURIComponent(refId)}`);
        } else {
          return buildUrl(`tab=Input&event=${encodeURIComponent(refId)}`);
        }
      }
    );
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(MarkdownDivWithReferences, { markdown: val, references: refs }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/values/Value.tsx",
      lineNumber: 218,
      columnNumber: 12
    }, void 0);
  } else if (typeof val === "number") {
    return formatPrettyDecimal(val);
  } else if (typeof val === "boolean") {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$s.boolean, val ? styles$s.true : styles$s.false), children: String(val) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/values/Value.tsx",
      lineNumber: 223,
      columnNumber: 7
    }, void 0);
  } else if (val === null) {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("pre", { className: clsx(styles$s.value), children: "null" }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/values/Value.tsx",
      lineNumber: 228,
      columnNumber: 12
    }, void 0);
  } else if (Array.isArray(val)) {
    return printArray(val, 25);
  } else if (typeof val === "object") {
    return !interactive ? printObject(val, 35) : /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      RecordTree,
      {
        id: `value-record-${result2.uuid}-${index}`,
        record: val
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/values/Value.tsx",
        lineNumber: 235,
        columnNumber: 7
      },
      void 0
    );
  } else {
    return "Unknown value type";
  }
};
const container$8 = "_container_15a30_1";
const explanation$1 = "_explanation_15a30_9";
const values = "_values_15a30_20";
const validation = "_validation_15a30_26";
const validationLabel = "_validationLabel_15a30_32";
const styles$r = {
  container: container$8,
  explanation: explanation$1,
  values,
  validation,
  validationLabel
};
const ResultPanel = ({ result: result2 }) => {
  const messages2 = reactExports.useMemo(() => {
    if (result2 && result2.scanEvents && result2.scanEvents.length > 0) {
      return messagesFromEvents(result2.scanEvents);
    }
    return [];
  }, [result2?.scanEvents]);
  return result2 && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$r.container, "text-size-base"), children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Card, { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(CardBody, { className: clsx(styles$r.explanation), children: [
      result2.label && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(jsxDevRuntimeExports.Fragment, { children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "div",
          {
            className: clsx("text-style-label", "text-style-secondary"),
            children: "Label"
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/result/ResultPanel.tsx",
            lineNumber: 36,
            columnNumber: 17
          },
          void 0
        ),
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: result2.label }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/result/ResultPanel.tsx",
          lineNumber: 41,
          columnNumber: 17
        }, void 0)
      ] }, void 0, true, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/result/ResultPanel.tsx",
        lineNumber: 35,
        columnNumber: 15
      }, void 0),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("text-style-label", "text-style-secondary"), children: "Value" }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/result/ResultPanel.tsx",
        lineNumber: 44,
        columnNumber: 13
      }, void 0),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "div",
        {
          className: clsx(
            result2.validationResult !== void 0 ? styles$r.values : void 0
          ),
          children: [
            /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
              Value,
              {
                result: result2,
                style: "block",
                maxTableSize: 1e3,
                interactive: true
              },
              void 0,
              false,
              {
                fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/result/ResultPanel.tsx",
                lineNumber: 54,
                columnNumber: 15
              },
              void 0
            ),
            result2.validationResult !== void 0 ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$r.validation), children: [
              /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
                "div",
                {
                  className: clsx(
                    "text-style-label",
                    "text-style-secondary",
                    "text-size-smallest",
                    styles$r.validationLabel
                  ),
                  children: "Validation"
                },
                void 0,
                false,
                {
                  fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/result/ResultPanel.tsx",
                  lineNumber: 62,
                  columnNumber: 19
                },
                void 0
              ),
              /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ValidationResult, { result: result2.validationResult }, void 0, false, {
                fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/result/ResultPanel.tsx",
                lineNumber: 72,
                columnNumber: 19
              }, void 0)
            ] }, void 0, true, {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/result/ResultPanel.tsx",
              lineNumber: 61,
              columnNumber: 17
            }, void 0) : void 0
          ]
        },
        void 0,
        true,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/result/ResultPanel.tsx",
          lineNumber: 47,
          columnNumber: 13
        },
        void 0
      ),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("text-style-label", "text-style-secondary"), children: "Explanation" }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/result/ResultPanel.tsx",
        lineNumber: 76,
        columnNumber: 13
      }, void 0),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Explanation, { result: result2 }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/result/ResultPanel.tsx",
        lineNumber: 80,
        columnNumber: 15
      }, void 0) }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/result/ResultPanel.tsx",
        lineNumber: 79,
        columnNumber: 13
      }, void 0),
      result2.metadata && Object.keys(result2.metadata).length > 0 && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(jsxDevRuntimeExports.Fragment, { children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "div",
          {
            className: clsx("text-style-label", "text-style-secondary"),
            children: "Metadata"
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/result/ResultPanel.tsx",
            lineNumber: 84,
            columnNumber: 17
          },
          void 0
        ),
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(MetaDataGrid, { entries: result2.metadata }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/result/ResultPanel.tsx",
          lineNumber: 90,
          columnNumber: 19
        }, void 0) }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/result/ResultPanel.tsx",
          lineNumber: 89,
          columnNumber: 17
        }, void 0)
      ] }, void 0, true, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/result/ResultPanel.tsx",
        lineNumber: 83,
        columnNumber: 15
      }, void 0)
    ] }, void 0, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/result/ResultPanel.tsx",
      lineNumber: 33,
      columnNumber: 11
    }, void 0) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/result/ResultPanel.tsx",
      lineNumber: 32,
      columnNumber: 9
    }, void 0),
    messages2.length > 0 && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Card, { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(CardBody, { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(LabeledValue, { label: "Scanner", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      ChatView,
      {
        showLabels: false,
        messages: messages2,
        id: `scan-result-chat`,
        toolCallStyle: "complete",
        indented: false
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/result/ResultPanel.tsx",
        lineNumber: 100,
        columnNumber: 17
      },
      void 0
    ) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/result/ResultPanel.tsx",
      lineNumber: 99,
      columnNumber: 15
    }, void 0) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/result/ResultPanel.tsx",
      lineNumber: 98,
      columnNumber: 13
    }, void 0) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/result/ResultPanel.tsx",
      lineNumber: 97,
      columnNumber: 11
    }, void 0),
    result2.metadata && Object.keys(result2.metadata).length > 0 && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Card, { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(CardBody, { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(LabeledValue, { label: "Metadata", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      RecordTree,
      {
        id: `result-metadata-${result2.uuid}`,
        record: result2.metadata || {}
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/result/ResultPanel.tsx",
        lineNumber: 116,
        columnNumber: 17
      },
      void 0
    ) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/result/ResultPanel.tsx",
      lineNumber: 115,
      columnNumber: 15
    }, void 0) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/result/ResultPanel.tsx",
      lineNumber: 114,
      columnNumber: 13
    }, void 0) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/result/ResultPanel.tsx",
      lineNumber: 113,
      columnNumber: 11
    }, void 0)
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/result/ResultPanel.tsx",
    lineNumber: 31,
    columnNumber: 7
  }, void 0);
};
const header$1 = "_header_ph0sv_1";
const oneCol = "_oneCol_ph0sv_12";
const twoCol = "_twoCol_ph0sv_16";
const threeCol = "_threeCol_ph0sv_20";
const fourCol = "_fourCol_ph0sv_24";
const fiveCol = "_fiveCol_ph0sv_28";
const styles$q = {
  header: header$1,
  oneCol,
  twoCol,
  threeCol,
  fourCol,
  fiveCol
};
const ScanResultHeader = ({ result: result2 }) => {
  const columns2 = colsForResult(result2) || [];
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$q.header, classForCols(columns2.length)), children: [
    columns2.map((col) => {
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "div",
        {
          className: clsx(
            "text-size-smallest",
            "text-style-label",
            "text-style-secondary",
            styles$q.label,
            col.className
          ),
          children: col.label
        },
        `header-label-${col.label}`,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/ScanResultHeader.tsx",
          lineNumber: 25,
          columnNumber: 11
        },
        void 0
      );
    }),
    columns2.map((col) => {
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "div",
        {
          className: clsx("text-size-small", styles$q.value, col.className),
          children: col.value
        },
        `header-val-${col.label}`,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/ScanResultHeader.tsx",
          lineNumber: 42,
          columnNumber: 11
        },
        void 0
      );
    })
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/ScanResultHeader.tsx",
    lineNumber: 22,
    columnNumber: 5
  }, void 0);
};
const classForCols = (numCols) => {
  return clsx(
    numCols === 1 ? styles$q.oneCol : numCols === 2 ? styles$q.twoCol : numCols === 3 ? styles$q.threeCol : numCols === 4 ? styles$q.fourCol : styles$q.fiveCol
  );
};
const colsForResult = (result2) => {
  if (!result2) {
    return [];
  }
  if (result2.inputType === "transcript") {
    return transcriptCols(result2);
  } else if (result2.inputType === "message") {
    return messageCols(result2);
  } else if (result2.inputType === "messages") {
    return messagesCols(result2);
  } else if (result2.inputType === "event") {
    return eventCols(result2);
  } else if (result2.inputType === "events") {
    return eventsCols(result2);
  } else {
    return [];
  }
};
const transcriptCols = (result2) => {
  if (result2.inputType === "transcript") {
    return [
      {
        label: "Log",
        value: filename(result2.input.metadata.log)
      },
      {
        label: "Task",
        value: result2.input.metadata.task_name
      },
      {
        label: "Sample Id",
        value: `${result2.input.metadata.id} Epoch ${result2.input.metadata.epoch}`
      },
      {
        label: "Model",
        value: result2.input.metadata.model
      }
    ];
  }
};
const messageCols = (result2) => {
  if (result2.inputType === "message") {
    const cols = [
      {
        label: "Message ID",
        value: result2.input.id
      }
    ];
    if (result2.input.role === "assistant") {
      cols.push({
        label: "Model",
        value: result2.input.model
      });
      cols.push({
        label: "Tool Calls",
        value: (result2.input.tool_calls || []).length
      });
    } else {
      cols.push({
        label: "Role",
        value: result2.input.role
      });
    }
    return cols;
  }
};
const messagesCols = (result2) => {
  if (result2.inputType === "messages") {
    return [
      {
        label: "Message Count",
        value: result2.input.length
      }
    ];
  }
};
const eventCols = (result2) => {
  if (result2.inputType === "event") {
    return [
      {
        label: "Event Type",
        value: result2.input.event
      },
      {
        label: "Timestamp",
        value: new Date(result2.input.timestamp).toLocaleString()
      }
    ];
  }
};
const eventsCols = (result2) => {
  if (result2.inputType === "events") {
    return [
      {
        label: "Event Count",
        value: result2.input.length
      }
    ];
  }
};
const resultIdentifierStr = (scannerCore) => {
  const identifier = resultIdentifier(scannerCore);
  if (!identifier) {
    return void 0;
  }
  if (identifier.secondaryId || identifier.epoch) {
    const result2 = [identifier.id];
    if (identifier.secondaryId) {
      result2.push(identifier.secondaryId);
    }
    if (identifier.epoch) {
      result2.push(identifier.epoch);
    }
    return result2.join(" ");
  }
};
const resultIdentifier = (scannerCore) => {
  if (!scannerCore) {
    return {
      id: "unknown"
    };
  }
  if (scannerCore.inputType === "transcript") {
    const sampleIdentifier = getSampleIdentifier(scannerCore);
    if (sampleIdentifier) {
      return sampleIdentifier;
    }
  } else if (scannerCore.inputType === "message") {
    const sampleIdentifier = getSampleIdentifier(scannerCore);
    return {
      id: scannerCore.input.id || "null",
      secondaryId: sampleIdentifier ? sampleIdentifier.id : void 0,
      epoch: sampleIdentifier ? sampleIdentifier.epoch : void 0
    };
  } else if (scannerCore.inputType === "event") {
    const sampleIdentifier = getSampleIdentifier(scannerCore);
    return {
      id: scannerCore.input.uuid || "null",
      secondaryId: sampleIdentifier ? sampleIdentifier.id : void 0,
      epoch: sampleIdentifier ? sampleIdentifier.epoch : void 0
    };
  }
  return {
    id: scannerCore.transcriptSourceId
  };
};
const getSampleIdentifier = (scannerCore) => {
  if (scannerCore.transcriptMetadata["id"] && scannerCore.transcriptMetadata["epoch"]) {
    const id2 = String(scannerCore.transcriptMetadata["id"]);
    const epoch = String(scannerCore.transcriptMetadata["epoch"]);
    return {
      id: id2,
      epoch
    };
  }
  return void 0;
};
const resultLog = (scannerCore) => {
  if (scannerCore.inputType === "transcript") {
    return scannerCore.transcriptMetadata["log"];
  }
  return void 0;
};
const resultNav = "_resultNav_oszqi_1";
const nav = "_nav_oszqi_9";
const disabled$1 = "_disabled_oszqi_9";
const styles$p = {
  resultNav,
  nav,
  disabled: disabled$1
};
const ScanResultNav = () => {
  const navigate = useNavigate();
  const params = useParams();
  const [searchParams] = useSearchParams();
  const relativePath = getRelativePathFromParams(params);
  const { scanPath } = parseScanResultPath(relativePath);
  const { scanResultUuid } = parseScanResultPath(relativePath);
  const visibleScannerResults = useStore(
    (state) => state.visibleScannerResults
  );
  const currentIndex = reactExports.useMemo(() => {
    if (!visibleScannerResults) {
      return -1;
    }
    return visibleScannerResults.findIndex((s) => s.uuid === scanResultUuid);
  }, [visibleScannerResults, scanResultUuid]);
  const hasPrevious = currentIndex > 0;
  const hasNext = visibleScannerResults && currentIndex >= 0 && currentIndex < visibleScannerResults.length - 1;
  const handlePrevious = () => {
    if (!hasPrevious || !visibleScannerResults) {
      return;
    }
    const previousResult = visibleScannerResults[currentIndex - 1];
    const route = scanResultRoute(scanPath, previousResult?.uuid, searchParams);
    void navigate(route);
  };
  const handleNext = () => {
    if (!hasNext || !visibleScannerResults) {
      return;
    }
    const nextResult = visibleScannerResults[currentIndex + 1];
    const route = scanResultRoute(scanPath, nextResult?.uuid, searchParams);
    void navigate(route);
  };
  reactExports.useEffect(() => {
    const handleGlobalKeyDown = (e) => {
      const activeElement = document.activeElement;
      const isInputFocused = activeElement && (activeElement.tagName === "INPUT" || activeElement.tagName === "TEXTAREA" || activeElement.tagName === "SELECT");
      if (!isInputFocused) {
        if (e.key === "ArrowLeft") {
          if (hasPrevious && !e.metaKey && !e.ctrlKey && !e.shiftKey && !e.altKey) {
            e.preventDefault();
            handlePrevious();
          }
        } else if (e.key === "ArrowRight" && !e.metaKey && !e.ctrlKey && !e.shiftKey && !e.altKey) {
          if (hasNext) {
            e.preventDefault();
            handleNext();
          }
        }
      }
    };
    document.addEventListener("keydown", handleGlobalKeyDown, true);
    return () => {
      document.removeEventListener("keydown", handleGlobalKeyDown, true);
    };
  }, [hasPrevious, hasNext, handlePrevious, handleNext]);
  const result2 = visibleScannerResults && currentIndex !== -1 ? visibleScannerResults[currentIndex] : void 0;
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$p.resultNav), children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "div",
      {
        onClick: handlePrevious,
        tabIndex: 0,
        className: clsx(!hasPrevious && styles$p.disabled, styles$p.nav),
        children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("i", { className: clsx(ApplicationIcons.previous) }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/ScanResultNav.tsx",
          lineNumber: 118,
          columnNumber: 9
        }, void 0)
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/ScanResultNav.tsx",
        lineNumber: 113,
        columnNumber: 7
      },
      void 0
    ),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$p.sampleInfo, "text-size-smallest"), children: visibleScannerResults && currentIndex !== -1 ? printIdentifier(resultIdentifier(result2), result2?.label) : void 0 }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/ScanResultNav.tsx",
      lineNumber: 120,
      columnNumber: 7
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "div",
      {
        onClick: handleNext,
        tabIndex: 0,
        className: clsx(!hasNext && styles$p.disabled, styles$p.nav),
        children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("i", { className: clsx(ApplicationIcons.next) }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/ScanResultNav.tsx",
          lineNumber: 130,
          columnNumber: 9
        }, void 0)
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/ScanResultNav.tsx",
        lineNumber: 125,
        columnNumber: 7
      },
      void 0
    )
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/ScanResultNav.tsx",
    lineNumber: 112,
    columnNumber: 5
  }, void 0);
};
const printIdentifier = (identifier, label2) => {
  let val = "";
  if (identifier.epoch) {
    val = `${identifier.id} epoch ${identifier.epoch}`;
  } else {
    val = identifier.id;
  }
  if (label2 && label2.length > 0) {
    val += ` (${label2})`;
  }
  return val;
};
const root$2 = "_root_12il0_1";
const tabSet$1 = "_tabSet_12il0_13";
const tabControl$1 = "_tabControl_12il0_19";
const tabs$1 = "_tabs_12il0_23";
const styles$o = {
  root: root$2,
  tabSet: tabSet$1,
  tabControl: tabControl$1,
  tabs: tabs$1
};
const container$7 = "_container_g5onx_1";
const styles$n = {
  container: container$7
};
const TranscriptPanel = ({
  id: id2,
  result: result2,
  nodeFilter
}) => {
  const scrollRef = reactExports.useRef(null);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { ref: scrollRef, className: clsx(styles$n.container), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    TranscriptView,
    {
      id: id2,
      events: result2?.scanEvents || [],
      scrollRef,
      nodeFilter
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/transcript/TranscriptPanel.tsx",
      lineNumber: 25,
      columnNumber: 7
    },
    void 0
  ) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/transcript/TranscriptPanel.tsx",
    lineNumber: 24,
    columnNumber: 5
  }, void 0);
};
const kTabIdResult = "Result";
const kTabIdError = "Error";
const kTabIdInput = "Input";
const kTabIdInfo$1 = "Info";
const kTabIdJson$1 = "JSON";
const kTabIdTranscript = "transcript";
const ScanResultPanel = () => {
  const params = useParams();
  const relativePath = getRelativePathFromParams(params);
  const { scanResultUuid } = parseScanResultPath(relativePath);
  const [searchParams, setSearchParams] = useSearchParams();
  useServerScans();
  useServerScanner();
  useServerScannerDataframe();
  const setSelectedScanner = useStore((state) => state.setSelectedScanner);
  reactExports.useEffect(() => {
    const scannerParam = getScannerParam(searchParams);
    if (scannerParam) {
      setSelectedScanner(scannerParam);
    }
  }, [searchParams, setSelectedScanner]);
  const loading = useStore((state) => state.loading);
  const selectedTab = useStore((state) => state.selectedResultTab);
  const visibleScannerResults = useStore(
    (state) => state.visibleScannerResults
  );
  const setSelectedResultTab = useStore((state) => state.setSelectedResultTab);
  const { data: selectedResult, isLoading: resultLoading } = useSelectedResultsRow(scanResultUuid);
  reactExports.useEffect(() => {
    const tabParam = searchParams.get("tab");
    if (tabParam) {
      const validTabs = [
        kTabIdResult,
        kTabIdInput,
        kTabIdInfo$1,
        kTabIdJson$1,
        kTabIdTranscript
      ];
      if (validTabs.includes(tabParam)) {
        setSelectedResultTab(tabParam);
      }
    }
  }, [searchParams, setSelectedResultTab]);
  const handleTabChange = (tabId) => {
    setSelectedResultTab(tabId);
    const newParams = new URLSearchParams(searchParams);
    newParams.set("tab", tabId);
    setSearchParams(newParams);
  };
  const showEvents = reactExports.useMemo(() => {
    if (!selectedResult?.scanEvents) {
      return false;
    }
    const hasNonSpanEvents = selectedResult.scanEvents.some((event) => {
      return event.event !== "span_begin" && event.event !== "span_end";
    });
    return hasNonSpanEvents;
  }, [selectedResult?.scanEvents]);
  const hasError = selectedResult?.scanError !== void 0 && selectedResult?.scanError !== null;
  const highlightLabeled = useStore((state) => state.highlightLabeled);
  const setHighlightLabeled = useStore((state) => state.setHighlightLabeled);
  const toggleHighlightLabeled = reactExports.useCallback(() => {
    setHighlightLabeled(!highlightLabeled);
  }, [highlightLabeled, setHighlightLabeled]);
  const tools2 = reactExports.useMemo(() => {
    if (selectedTab === kTabIdInput && selectedResult?.inputType === "transcript" && selectedResult?.messageReferences.length > 0) {
      return [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          ToolButton,
          {
            icon: ApplicationIcons.highlight,
            latched: !!highlightLabeled,
            onClick: toggleHighlightLabeled,
            label: "Highlight Refs"
          },
          "highlight-labeled",
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/ScanResultPanel.tsx",
            lineNumber: 127,
            columnNumber: 9
          },
          void 0
        )
      ];
    } else {
      return [];
    }
  }, [highlightLabeled, toggleHighlightLabeled, selectedTab, selectedResult]);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$o.root), children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Navbar, { children: visibleScannerResults.length > 0 && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ScanResultNav, {}, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/ScanResultPanel.tsx",
      lineNumber: 142,
      columnNumber: 52
    }, void 0) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/ScanResultPanel.tsx",
      lineNumber: 142,
      columnNumber: 7
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ActivityBar, { animating: !!loading || resultLoading }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/ScanResultPanel.tsx",
      lineNumber: 143,
      columnNumber: 7
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ScanResultHeader, { result: selectedResult }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/ScanResultPanel.tsx",
      lineNumber: 144,
      columnNumber: 7
    }, void 0),
    selectedResult && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ExtendedFindProvider, { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      TabSet,
      {
        id: "scan-result-tabs",
        type: "pills",
        tabPanelsClassName: clsx(styles$o.tabSet),
        tabControlsClassName: clsx(styles$o.tabControl),
        className: clsx(styles$o.tabs),
        tools: tools2,
        children: [
          hasError ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            TabPanel,
            {
              id: kTabIdError,
              selected: selectedTab === kTabIdError || selectedTab === void 0,
              title: "Error",
              onSelected: () => {
                handleTabChange(kTabIdError);
              },
              children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
                ErrorPanel$1,
                {
                  error: selectedResult.scanError,
                  traceback: selectedResult.scanErrorTraceback
                },
                void 0,
                false,
                {
                  fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/ScanResultPanel.tsx",
                  lineNumber: 166,
                  columnNumber: 17
                },
                void 0
              )
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/ScanResultPanel.tsx",
              lineNumber: 156,
              columnNumber: 15
            },
            void 0
          ) : void 0,
          !hasError ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            TabPanel,
            {
              id: kTabIdResult,
              selected: selectedTab === kTabIdResult || !hasError && selectedTab === void 0,
              title: "Result",
              onSelected: () => {
                handleTabChange(kTabIdResult);
              },
              children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ResultPanel, { result: selectedResult }, void 0, false, {
                fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/ScanResultPanel.tsx",
                lineNumber: 184,
                columnNumber: 17
              }, void 0)
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/ScanResultPanel.tsx",
              lineNumber: 173,
              columnNumber: 15
            },
            void 0
          ) : void 0,
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            TabPanel,
            {
              id: kTabIdInput,
              selected: selectedTab === kTabIdInput,
              title: "Input",
              onSelected: () => {
                handleTabChange(kTabIdInput);
              },
              children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(InputPanel, { result: selectedResult }, void 0, false, {
                fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/ScanResultPanel.tsx",
                lineNumber: 195,
                columnNumber: 15
              }, void 0)
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/ScanResultPanel.tsx",
              lineNumber: 187,
              columnNumber: 13
            },
            void 0
          ),
          showEvents ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            TabPanel,
            {
              id: kTabIdTranscript,
              selected: selectedTab === kTabIdTranscript,
              title: "Events",
              onSelected: () => {
                handleTabChange(kTabIdTranscript);
              },
              children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
                TranscriptPanel,
                {
                  id: "scan-transcript",
                  result: selectedResult,
                  nodeFilter: skipScanSpan
                },
                void 0,
                false,
                {
                  fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/ScanResultPanel.tsx",
                  lineNumber: 206,
                  columnNumber: 17
                },
                void 0
              )
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/ScanResultPanel.tsx",
              lineNumber: 198,
              columnNumber: 15
            },
            void 0
          ) : void 0,
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            TabPanel,
            {
              id: kTabIdInfo$1,
              selected: selectedTab === kTabIdInfo$1,
              title: "Info",
              onSelected: () => {
                handleTabChange(kTabIdInfo$1);
              },
              children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(InfoPanel, { result: selectedResult }, void 0, false, {
                fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/ScanResultPanel.tsx",
                lineNumber: 221,
                columnNumber: 15
              }, void 0)
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/ScanResultPanel.tsx",
              lineNumber: 213,
              columnNumber: 13
            },
            void 0
          ),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            TabPanel,
            {
              id: kTabIdJson$1,
              selected: selectedTab === kTabIdJson$1,
              title: "JSON",
              onSelected: () => {
                handleTabChange(kTabIdJson$1);
              },
              children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
                JSONPanel,
                {
                  id: "scan-result-json-contents",
                  data: selectedResult,
                  simple: true,
                  className: styles$o.json
                },
                void 0,
                false,
                {
                  fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/ScanResultPanel.tsx",
                  lineNumber: 231,
                  columnNumber: 15
                },
                void 0
              )
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/ScanResultPanel.tsx",
              lineNumber: 223,
              columnNumber: 13
            },
            void 0
          )
        ]
      },
      void 0,
      true,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/ScanResultPanel.tsx",
        lineNumber: 147,
        columnNumber: 11
      },
      void 0
    ) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/ScanResultPanel.tsx",
      lineNumber: 146,
      columnNumber: 9
    }, void 0)
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/result/ScanResultPanel.tsx",
    lineNumber: 141,
    columnNumber: 5
  }, void 0);
};
const skipScanSpan = (nodes) => {
  if (nodes.length === 1 && nodes[0]?.event.event === "span_begin") {
    return nodes[0].children;
  }
  return nodes;
};
const ErrorPanel = ({ title: title2, error: error2 }) => {
  const message2 = error2.message;
  const stack2 = error2.stack;
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "error-panel centered-flex", children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "error-panel-heading centered-flex", children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("i", { className: `${ApplicationIcons.error} error-icon` }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/ErrorPanel.tsx",
        lineNumber: 25,
        columnNumber: 11
      }, void 0) }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/ErrorPanel.tsx",
        lineNumber: 24,
        columnNumber: 9
      }, void 0),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: title2 || "" }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/ErrorPanel.tsx",
        lineNumber: 27,
        columnNumber: 9
      }, void 0)
    ] }, void 0, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/ErrorPanel.tsx",
      lineNumber: 23,
      columnNumber: 7
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "error-panel-body", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: [
      message2 || "",
      stack2 && error2.displayStack !== false && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("pre", { className: "error-panel-stack", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("code", { children: [
        "at ",
        stack2
      ] }, void 0, true, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/ErrorPanel.tsx",
        lineNumber: 34,
        columnNumber: 15
      }, void 0) }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/ErrorPanel.tsx",
        lineNumber: 33,
        columnNumber: 13
      }, void 0)
    ] }, void 0, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/ErrorPanel.tsx",
      lineNumber: 30,
      columnNumber: 9
    }, void 0) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/ErrorPanel.tsx",
      lineNumber: 29,
      columnNumber: 7
    }, void 0)
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/ErrorPanel.tsx",
    lineNumber: 22,
    columnNumber: 5
  }, void 0);
};
const footer$1 = "_footer_14uod_1";
const spinnerContainer = "_spinnerContainer_14uod_11";
const spinner = "_spinner_14uod_11";
const label$2 = "_label_14uod_25";
const right = "_right_14uod_30";
const left = "_left_14uod_39";
const center = "_center_14uod_48";
const styles$m = {
  footer: footer$1,
  spinnerContainer,
  spinner,
  label: label$2,
  right,
  left,
  center
};
const pager = "_pager_jzegk_1";
const item = "_item_jzegk_11";
const styles$l = {
  pager,
  item
};
const Pager = ({
  itemCount,
  page,
  setPage,
  itemsPerPage = 20
}) => {
  const pageCount = Math.ceil(itemCount / itemsPerPage);
  if (pageCount <= 1) {
    return null;
  }
  const currentPage = page || 0;
  const generatePaginationSegments = () => {
    const segments2 = [];
    if (pageCount <= 5) {
      for (let i2 = 0; i2 < pageCount; i2++) {
        segments2.push({ type: "page", page: i2, key: `page-${i2}` });
      }
    } else {
      segments2.push({ type: "page", page: 0, key: "page-0" });
      const startPage = Math.max(1, currentPage - 1);
      const endPage = Math.min(pageCount - 2, currentPage + 1);
      if (startPage > 1) {
        segments2.push({ type: "ellipsis", key: "ellipsis-start" });
      }
      for (let i2 = startPage; i2 <= endPage; i2++) {
        segments2.push({ type: "page", page: i2, key: `page-${i2}` });
      }
      if (endPage < pageCount - 2) {
        segments2.push({ type: "ellipsis", key: "ellipsis-end" });
      }
      segments2.push({
        type: "page",
        page: pageCount - 1,
        key: `page-${pageCount - 1}`
      });
    }
    return segments2;
  };
  const segments = generatePaginationSegments();
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("nav", { "aria-label": "Log Pagination", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("ul", { className: clsx("pagination", styles$l.pager), children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("li", { className: clsx(currentPage === 0 ? "disabled" : "", styles$l.item), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "a",
      {
        className: clsx("page-link"),
        onClick: () => {
          if (currentPage > 0 && setPage) {
            setPage(currentPage - 1);
          }
        },
        children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("i", { className: clsx(ApplicationIcons.navbar.back) }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/components/Pager.tsx",
          lineNumber: 90,
          columnNumber: 13
        }, void 0)
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/components/Pager.tsx",
        lineNumber: 82,
        columnNumber: 11
      },
      void 0
    ) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/components/Pager.tsx",
      lineNumber: 81,
      columnNumber: 9
    }, void 0),
    segments.map((segment2) => /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "li",
      {
        className: clsx(
          segment2.type === "page" && segment2.page === currentPage ? "active" : void 0,
          segment2.type === "ellipsis" ? "disabled" : void 0,
          styles$l.item
        ),
        children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "a",
          {
            className: clsx("page-link"),
            onClick: () => {
              if (segment2.type === "page" && segment2.page !== void 0 && setPage) {
                setPage(segment2.page);
              }
            },
            children: segment2.type === "page" ? (segment2.page || 0) + 1 : "..."
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/components/Pager.tsx",
            lineNumber: 105,
            columnNumber: 13
          },
          void 0
        )
      },
      segment2.key,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/components/Pager.tsx",
        lineNumber: 95,
        columnNumber: 11
      },
      void 0
    )),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "li",
      {
        className: clsx(
          currentPage + 1 >= pageCount ? "disabled" : "",
          styles$l.item
        ),
        children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "a",
          {
            className: clsx("page-link"),
            onClick: () => {
              if (currentPage < pageCount && setPage) {
                setPage(currentPage + 1);
              }
            },
            children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("i", { className: clsx(ApplicationIcons.navbar.forward) }, void 0, false, {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/components/Pager.tsx",
              lineNumber: 135,
              columnNumber: 13
            }, void 0)
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/components/Pager.tsx",
            lineNumber: 127,
            columnNumber: 11
          },
          void 0
        )
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/components/Pager.tsx",
        lineNumber: 121,
        columnNumber: 9
      },
      void 0
    )
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/components/Pager.tsx",
    lineNumber: 80,
    columnNumber: 7
  }, void 0) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/components/Pager.tsx",
    lineNumber: 79,
    columnNumber: 5
  }, void 0);
};
const Footer2 = ({
  id: id2,
  className: className2,
  itemCount,
  paginated,
  filteredCount,
  progressText,
  progressBar,
  page,
  setPage,
  itemsPerPage = -1,
  labels = {
    singular: "item",
    plural: "items"
  }
}) => {
  const effectiveItemCount = filteredCount ?? itemCount;
  const currentPage = page || 0;
  const pageItemCount = Math.min(
    itemsPerPage,
    effectiveItemCount - currentPage * itemsPerPage
  );
  const startItem = effectiveItemCount > 0 ? currentPage * itemsPerPage + 1 : 0;
  const endItem = startItem + pageItemCount - 1;
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "div",
    {
      id: id2,
      className: clsx("text-size-smaller", styles$m.footer, className2),
      children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$m.left), children: progressText ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$m.spinnerContainer), children: [
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            "div",
            {
              className: clsx("spinner-border", styles$m.spinner),
              role: "status",
              children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("span", { className: clsx("visually-hidden"), children: [
                progressText,
                "..."
              ] }, void 0, true, {
                fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/components/Footer.tsx",
                lineNumber: 73,
                columnNumber: 15
              }, void 0)
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/components/Footer.tsx",
              lineNumber: 69,
              columnNumber: 13
            },
            void 0
          ),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("text-style-secondary", styles$m.label), children: [
            progressText,
            "..."
          ] }, void 0, true, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/components/Footer.tsx",
            lineNumber: 75,
            columnNumber: 13
          }, void 0)
        ] }, void 0, true, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/components/Footer.tsx",
          lineNumber: 68,
          columnNumber: 11
        }, void 0) : void 0 }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/components/Footer.tsx",
          lineNumber: 66,
          columnNumber: 7
        }, void 0),
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$m.center), children: paginated && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          Pager,
          {
            itemCount: effectiveItemCount,
            itemsPerPage,
            page,
            setPage
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/components/Footer.tsx",
            lineNumber: 83,
            columnNumber: 11
          },
          void 0
        ) }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/components/Footer.tsx",
          lineNumber: 81,
          columnNumber: 7
        }, void 0),
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$m.right), children: progressBar ? progressBar : paginated ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: effectiveItemCount === 0 ? "" : filteredCount !== void 0 && filteredCount !== itemCount ? `${startItem} - ${endItem} / ${effectiveItemCount} (${itemCount} total)` : `${startItem} - ${endItem} / ${effectiveItemCount}` }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/components/Footer.tsx",
          lineNumber: 95,
          columnNumber: 11
        }, void 0) : effectiveItemCount === 1 ? `${effectiveItemCount} ${labels.singular}` : `${effectiveItemCount} ${labels.plural}` }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/components/Footer.tsx",
          lineNumber: 91,
          columnNumber: 7
        }, void 0)
      ]
    },
    void 0,
    true,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/components/Footer.tsx",
      lineNumber: 62,
      columnNumber: 5
    },
    void 0
  );
};
var LocalEventService = class {
  constructor() {
    this.allSyncListeners = /* @__PURE__ */ new Map();
    this.allAsyncListeners = /* @__PURE__ */ new Map();
    this.globalSyncListeners = /* @__PURE__ */ new Set();
    this.globalAsyncListeners = /* @__PURE__ */ new Set();
    this.asyncFunctionsQueue = [];
    this.scheduled = false;
    this.firedEvents = {};
  }
  setFrameworkOverrides(frameworkOverrides) {
    this.frameworkOverrides = frameworkOverrides;
  }
  getListeners(eventType, async, autoCreateListenerCollection) {
    const listenerMap = async ? this.allAsyncListeners : this.allSyncListeners;
    let listeners = listenerMap.get(eventType);
    if (!listeners && autoCreateListenerCollection) {
      listeners = /* @__PURE__ */ new Set();
      listenerMap.set(eventType, listeners);
    }
    return listeners;
  }
  noRegisteredListenersExist() {
    return this.allSyncListeners.size === 0 && this.allAsyncListeners.size === 0 && this.globalSyncListeners.size === 0 && this.globalAsyncListeners.size === 0;
  }
  addEventListener(eventType, listener, async = false) {
    this.getListeners(eventType, async, true).add(listener);
  }
  removeEventListener(eventType, listener, async = false) {
    const listeners = this.getListeners(eventType, async, false);
    if (!listeners) {
      return;
    }
    listeners.delete(listener);
    if (listeners.size === 0) {
      (async ? this.allAsyncListeners : this.allSyncListeners).delete(eventType);
    }
  }
  addGlobalListener(listener, async = false) {
    this.getGlobalListeners(async).add(listener);
  }
  removeGlobalListener(listener, async = false) {
    this.getGlobalListeners(async).delete(listener);
  }
  dispatchEvent(event) {
    this.dispatchToListeners(event, true);
    this.dispatchToListeners(event, false);
    this.firedEvents[event.type] = true;
  }
  dispatchEventOnce(event) {
    if (!this.firedEvents[event.type]) {
      this.dispatchEvent(event);
    }
  }
  dispatchToListeners(event, async) {
    const eventType = event.type;
    if (async && "event" in event) {
      const browserEvent = event.event;
      if (browserEvent instanceof Event) {
        event.eventPath = browserEvent.composedPath();
      }
    }
    const { frameworkOverrides } = this;
    const runCallback = (func2) => {
      const callback = frameworkOverrides ? () => frameworkOverrides.wrapIncoming(func2) : func2;
      if (async) {
        this.dispatchAsync(callback);
      } else {
        callback();
      }
    };
    const originalListeners = this.getListeners(eventType, async, false);
    if ((originalListeners?.size ?? 0) > 0) {
      const listeners = new Set(originalListeners);
      for (const listener of listeners) {
        if (!originalListeners?.has(listener)) {
          continue;
        }
        runCallback(() => listener(event));
      }
    }
    const globalListenersSrc = this.getGlobalListeners(async);
    if (globalListenersSrc.size > 0) {
      const globalListeners = new Set(globalListenersSrc);
      for (const listener of globalListeners) {
        runCallback(() => listener(eventType, event));
      }
    }
  }
  getGlobalListeners(async) {
    return async ? this.globalAsyncListeners : this.globalSyncListeners;
  }
  // this gets called inside the grid's thread, for each event that it
  // wants to set async. the grid then batches the events into one setTimeout()
  // because setTimeout() is an expensive operation. ideally we would have
  // each event in it's own setTimeout(), but we batch for performance.
  dispatchAsync(func2) {
    this.asyncFunctionsQueue.push(func2);
    if (!this.scheduled) {
      const flush = () => {
        window.setTimeout(this.flushAsyncQueue.bind(this), 0);
      };
      this.frameworkOverrides ? this.frameworkOverrides.wrapIncoming(flush) : flush();
      this.scheduled = true;
    }
  }
  // this happens in the next VM turn only, and empties the queue of events
  flushAsyncQueue() {
    this.scheduled = false;
    const queueCopy = this.asyncFunctionsQueue.slice();
    this.asyncFunctionsQueue = [];
    for (const func2 of queueCopy) {
      func2();
    }
  }
};
function _makeNull(value2) {
  if (value2 == null || value2 === "") {
    return null;
  }
  return value2;
}
function _exists(value2) {
  return value2 != null && value2 !== "";
}
function _missing(value2) {
  return !_exists(value2);
}
function _toStringOrNull(value2) {
  return value2 != null && typeof value2.toString === "function" ? value2.toString() : null;
}
function _jsonEquals(val1, val2) {
  const val1Json = val1 ? JSON.stringify(val1) : null;
  const val2Json = val2 ? JSON.stringify(val2) : null;
  return val1Json === val2Json;
}
function _defaultComparator(valueA, valueB, accentedCompare = false) {
  const valueAMissing = valueA == null;
  const valueBMissing = valueB == null;
  if (valueA?.toNumber) {
    valueA = valueA.toNumber();
  }
  if (valueB?.toNumber) {
    valueB = valueB.toNumber();
  }
  if (valueAMissing && valueBMissing) {
    return 0;
  }
  if (valueAMissing) {
    return -1;
  }
  if (valueBMissing) {
    return 1;
  }
  function doQuickCompare(a2, b) {
    return a2 > b ? 1 : a2 < b ? -1 : 0;
  }
  if (typeof valueA !== "string") {
    return doQuickCompare(valueA, valueB);
  }
  if (!accentedCompare) {
    return doQuickCompare(valueA, valueB);
  }
  try {
    return valueA.localeCompare(valueB);
  } catch (e) {
    return doQuickCompare(valueA, valueB);
  }
}
var reUnescapedHtml = /[&<>"']/g;
var HTML_ESCAPES = {
  "&": "&amp;",
  "<": "&lt;",
  ">": "&gt;",
  '"': "&quot;",
  "'": "&#39;"
};
function _toString(toEscape) {
  return toEscape?.toString().toString() ?? null;
}
function _escapeString(toEscape) {
  return _toString(toEscape)?.replace(reUnescapedHtml, (chr) => HTML_ESCAPES[chr]) ?? null;
}
function _getRootNode(beans) {
  return beans.eRootDiv.getRootNode();
}
function _getActiveDomElement(beans) {
  return _getRootNode(beans).activeElement;
}
function _getDocument(beans) {
  const { gos, eRootDiv } = beans;
  let result2 = null;
  const optionsGetDocument = gos.get("getDocument");
  if (optionsGetDocument && _exists(optionsGetDocument)) {
    result2 = optionsGetDocument();
  } else if (eRootDiv) {
    result2 = eRootDiv.ownerDocument;
  }
  if (result2 && _exists(result2)) {
    return result2;
  }
  return document;
}
function _isNothingFocused(beans) {
  const activeEl = _getActiveDomElement(beans);
  return activeEl === null || activeEl === _getDocument(beans).body;
}
function _getWindow(beans) {
  const eDocument = _getDocument(beans);
  return eDocument.defaultView || window;
}
function _getPageBody(beans) {
  let rootNode = null;
  let targetEl = null;
  try {
    rootNode = _getDocument(beans).fullscreenElement;
  } catch (e) {
  } finally {
    if (!rootNode) {
      rootNode = _getRootNode(beans);
    }
    const body = rootNode.querySelector("body");
    if (body) {
      targetEl = body;
    } else if (rootNode instanceof ShadowRoot) {
      targetEl = rootNode;
    } else if (rootNode instanceof Document) {
      targetEl = rootNode?.documentElement;
    } else {
      targetEl = rootNode;
    }
  }
  return targetEl;
}
function _getBodyWidth(beans) {
  const body = _getPageBody(beans);
  return body?.clientWidth ?? (window.innerWidth || -1);
}
function _getBodyHeight(beans) {
  const body = _getPageBody(beans);
  return body?.clientHeight ?? (window.innerHeight || -1);
}
function _toggleAriaAttribute(element, attribute2, value2) {
  if (value2 == null || typeof value2 === "string" && value2 == "") {
    _removeAriaAttribute(element, attribute2);
  } else {
    _setAriaAttribute(element, attribute2, value2);
  }
}
function _setAriaAttribute(element, attribute2, value2) {
  element.setAttribute(_ariaAttributeName(attribute2), value2.toString());
}
function _removeAriaAttribute(element, attribute2) {
  element.removeAttribute(_ariaAttributeName(attribute2));
}
function _ariaAttributeName(attribute2) {
  return `aria-${attribute2}`;
}
function _setAriaRole(element, role) {
  if (role) {
    element.setAttribute("role", role);
  } else {
    element.removeAttribute("role");
  }
}
function _getAriaSortState(sortDirection) {
  let sort;
  if (sortDirection === "asc") {
    sort = "ascending";
  } else if (sortDirection === "desc") {
    sort = "descending";
  } else if (sortDirection === "mixed") {
    sort = "other";
  } else {
    sort = "none";
  }
  return sort;
}
function _getAriaLabel(element) {
  return element.getAttribute("aria-label");
}
function _setAriaLabel(element, label2) {
  _toggleAriaAttribute(element, "label", label2);
}
function _setAriaLabelledBy(element, labelledBy) {
  _toggleAriaAttribute(element, "labelledby", labelledBy);
}
function _setAriaLive(element, live) {
  _toggleAriaAttribute(element, "live", live);
}
function _setAriaAtomic(element, atomic) {
  _toggleAriaAttribute(element, "atomic", atomic);
}
function _setAriaRelevant(element, relevant) {
  _toggleAriaAttribute(element, "relevant", relevant);
}
function _setAriaInvalid(element, invalid) {
  _toggleAriaAttribute(element, "invalid", invalid);
}
function _setAriaDisabled(element, disabled2) {
  _toggleAriaAttribute(element, "disabled", disabled2);
}
function _setAriaHidden(element, hidden2) {
  _toggleAriaAttribute(element, "hidden", hidden2);
}
function _setAriaExpanded(element, expanded) {
  _setAriaAttribute(element, "expanded", expanded);
}
function _setAriaSetSize(element, setsize) {
  _setAriaAttribute(element, "setsize", setsize);
}
function _setAriaPosInSet(element, position) {
  _setAriaAttribute(element, "posinset", position);
}
function _setAriaRowCount(element, rowCount) {
  _setAriaAttribute(element, "rowcount", rowCount);
}
function _setAriaRowIndex(element, rowIndex) {
  _setAriaAttribute(element, "rowindex", rowIndex);
}
function _setAriaRowSpan(element, spanCount) {
  _setAriaAttribute(element, "rowspan", spanCount);
}
function _setAriaColCount(element, colCount) {
  _setAriaAttribute(element, "colcount", colCount);
}
function _setAriaColIndex(element, colIndex) {
  _setAriaAttribute(element, "colindex", colIndex);
}
function _setAriaColSpan(element, colSpan) {
  _setAriaAttribute(element, "colspan", colSpan);
}
function _setAriaSort(element, sort) {
  _setAriaAttribute(element, "sort", sort);
}
function _removeAriaSort(element) {
  _removeAriaAttribute(element, "sort");
}
function _setAriaSelected(element, selected2) {
  _toggleAriaAttribute(element, "selected", selected2);
}
function _setAriaControls(controllerElement, controlledId) {
  _toggleAriaAttribute(controllerElement, "controls", controlledId);
}
function _setAriaControlsAndLabel(controllerElement, controlledElement) {
  _setAriaControls(controllerElement, controlledElement.id);
  _setAriaLabelledBy(controlledElement, controllerElement.id);
}
function _setAriaOwns(ownerElement, ownedId) {
  _toggleAriaAttribute(ownerElement, "owns", ownedId);
}
function _getAriaCheckboxStateName(translate, state) {
  return state === void 0 ? translate("ariaIndeterminate", "indeterminate") : state === true ? translate("ariaChecked", "checked") : translate("ariaUnchecked", "unchecked");
}
var FOCUSABLE_SELECTOR = "[tabindex], input, select, button, textarea, [href]";
var FOCUSABLE_EXCLUDE = "[disabled], .ag-disabled:not(.ag-button), .ag-disabled *";
function _isFocusableFormField(element) {
  if (!element) {
    return false;
  }
  const isFocusable = element.matches("input, select, button, textarea");
  if (!isFocusable) {
    return false;
  }
  const isNotFocusable = element.matches(FOCUSABLE_EXCLUDE);
  if (!isNotFocusable) {
    return false;
  }
  return _isVisible(element);
}
function _setDisplayed(element, displayed, options = {}) {
  const { skipAriaHidden } = options;
  element.classList.toggle("ag-hidden", !displayed);
  if (!skipAriaHidden) {
    _setAriaHidden(element, !displayed);
  }
}
function _setVisible(element, visible2, options = {}) {
  const { skipAriaHidden } = options;
  element.classList.toggle("ag-invisible", !visible2);
  if (!skipAriaHidden) {
    _setAriaHidden(element, !visible2);
  }
}
function _setDisabled(element, disabled2) {
  const attributeName = "disabled";
  const addOrRemoveDisabledAttribute = disabled2 ? (e) => e.setAttribute(attributeName, "") : (e) => e.removeAttribute(attributeName);
  addOrRemoveDisabledAttribute(element);
  const inputs = element.querySelectorAll("input") ?? [];
  for (const input2 of inputs) {
    addOrRemoveDisabledAttribute(input2);
  }
}
function _isElementChildOfClass(element, cls, maxNest) {
  let counter2 = 0;
  while (element) {
    if (element.classList.contains(cls)) {
      return true;
    }
    element = element.parentElement;
    if (typeof maxNest == "number") {
      if (++counter2 > maxNest) {
        break;
      }
    } else if (element === maxNest) {
      break;
    }
  }
  return false;
}
function _getElementSize(el) {
  const {
    height,
    width,
    borderTopWidth,
    borderRightWidth,
    borderBottomWidth,
    borderLeftWidth,
    paddingTop,
    paddingRight,
    paddingBottom,
    paddingLeft,
    marginTop,
    marginRight,
    marginBottom,
    marginLeft,
    boxSizing
  } = window.getComputedStyle(el);
  const pf = Number.parseFloat;
  return {
    height: pf(height || "0"),
    width: pf(width || "0"),
    borderTopWidth: pf(borderTopWidth || "0"),
    borderRightWidth: pf(borderRightWidth || "0"),
    borderBottomWidth: pf(borderBottomWidth || "0"),
    borderLeftWidth: pf(borderLeftWidth || "0"),
    paddingTop: pf(paddingTop || "0"),
    paddingRight: pf(paddingRight || "0"),
    paddingBottom: pf(paddingBottom || "0"),
    paddingLeft: pf(paddingLeft || "0"),
    marginTop: pf(marginTop || "0"),
    marginRight: pf(marginRight || "0"),
    marginBottom: pf(marginBottom || "0"),
    marginLeft: pf(marginLeft || "0"),
    boxSizing
  };
}
function _getInnerHeight(el) {
  const size = _getElementSize(el);
  if (size.boxSizing === "border-box") {
    return size.height - size.paddingTop - size.paddingBottom - size.borderTopWidth - size.borderBottomWidth;
  }
  return size.height;
}
function _getInnerWidth(el) {
  const size = _getElementSize(el);
  if (size.boxSizing === "border-box") {
    return size.width - size.paddingLeft - size.paddingRight - size.borderLeftWidth - size.borderRightWidth;
  }
  return size.width;
}
function _getAbsoluteHeight(el) {
  const { height, marginBottom, marginTop } = _getElementSize(el);
  return Math.floor(height + marginBottom + marginTop);
}
function _getAbsoluteWidth(el) {
  const { width, marginLeft, marginRight } = _getElementSize(el);
  return Math.floor(width + marginLeft + marginRight);
}
function _getElementRectWithOffset(el) {
  const offsetElementRect = el.getBoundingClientRect();
  const { borderTopWidth, borderLeftWidth, borderRightWidth, borderBottomWidth } = _getElementSize(el);
  return {
    top: offsetElementRect.top + (borderTopWidth || 0),
    left: offsetElementRect.left + (borderLeftWidth || 0),
    right: offsetElementRect.right + (borderRightWidth || 0),
    bottom: offsetElementRect.bottom + (borderBottomWidth || 0)
  };
}
function _getScrollLeft(element, rtl) {
  let scrollLeft = element.scrollLeft;
  if (rtl) {
    scrollLeft = Math.abs(scrollLeft);
  }
  return scrollLeft;
}
function _setScrollLeft(element, value2, rtl) {
  if (rtl) {
    value2 *= -1;
  }
  element.scrollLeft = value2;
}
function _clearElement(el) {
  while (el?.firstChild) {
    el.firstChild.remove();
  }
}
function _removeFromParent(node2) {
  if (node2?.parentNode) {
    node2.remove();
  }
}
function _isInDOM(element) {
  return !!element.offsetParent;
}
function _isVisible(element) {
  if (element.checkVisibility) {
    return element.checkVisibility({ checkVisibilityCSS: true });
  }
  const isHidden = !_isInDOM(element) || window.getComputedStyle(element).visibility !== "visible";
  return !isHidden;
}
function _loadTemplate(template2) {
  const tempDiv = document.createElement("div");
  tempDiv.innerHTML = (template2 || "").trim();
  return tempDiv.firstChild;
}
function _isElementOverflowingCallback(getElement2) {
  return () => {
    const element = getElement2();
    if (!element) {
      return true;
    }
    return _isHorizontalScrollShowing(element) || _isVerticalScrollShowing(element);
  };
}
function _isHorizontalScrollShowing(element) {
  return element.clientWidth < element.scrollWidth;
}
function _isVerticalScrollShowing(element) {
  return element.clientHeight < element.scrollHeight;
}
function _setElementWidth(element, width) {
  if (width === "flex") {
    element.style.removeProperty("width");
    element.style.removeProperty("minWidth");
    element.style.removeProperty("maxWidth");
    element.style.flex = "1 1 auto";
  } else {
    _setFixedWidth(element, width);
  }
}
function _setFixedWidth(element, width) {
  width = _formatSize(width);
  element.style.width = width;
  element.style.maxWidth = width;
  element.style.minWidth = width;
}
function _setFixedHeight(element, height) {
  height = _formatSize(height);
  element.style.height = height;
  element.style.maxHeight = height;
  element.style.minHeight = height;
}
function _formatSize(size) {
  return typeof size === "number" ? `${size}px` : size;
}
function _isNodeOrElement(o) {
  return o instanceof Node || o instanceof HTMLElement;
}
function _addOrRemoveAttribute(element, name2, value2) {
  if (value2 == null || value2 === "") {
    element.removeAttribute(name2);
  } else {
    element.setAttribute(name2, value2.toString());
  }
}
function _observeResize(beans, element, callback) {
  const win = _getWindow(beans);
  const ResizeObserverImpl = win.ResizeObserver;
  const resizeObserver = ResizeObserverImpl ? new ResizeObserverImpl(callback) : null;
  resizeObserver?.observe(element);
  return () => resizeObserver?.disconnect();
}
function _requestAnimationFrame(beans, callback) {
  const win = _getWindow(beans);
  if (win.requestAnimationFrame) {
    win.requestAnimationFrame(callback);
  } else if (win.webkitRequestAnimationFrame) {
    win.webkitRequestAnimationFrame(callback);
  } else {
    win.setTimeout(callback, 0);
  }
}
var DataRefAttribute = "data-ref";
var whitespaceNode;
function getWhitespaceNode() {
  whitespaceNode ?? (whitespaceNode = document.createTextNode(" "));
  return whitespaceNode.cloneNode();
}
function _createAgElement(params) {
  const { attrs, children: children2, cls, ref: ref2, role, tag } = params;
  const element = document.createElement(tag);
  if (cls) {
    element.className = cls;
  }
  if (ref2) {
    element.setAttribute(DataRefAttribute, ref2);
  }
  if (role) {
    element.setAttribute("role", role);
  }
  if (attrs) {
    for (const key2 of Object.keys(attrs)) {
      element.setAttribute(key2, attrs[key2]);
    }
  }
  if (children2) {
    if (typeof children2 === "string") {
      element.textContent = children2;
    } else {
      let addFirstWhitespace = true;
      for (const child of children2) {
        if (child) {
          if (typeof child === "string") {
            element.appendChild(document.createTextNode(child));
            addFirstWhitespace = false;
          } else if (typeof child === "function") {
            element.appendChild(child());
          } else {
            if (addFirstWhitespace) {
              element.appendChild(getWhitespaceNode());
              addFirstWhitespace = false;
            }
            element.append(_createAgElement(child));
            element.appendChild(getWhitespaceNode());
          }
        }
      }
    }
  }
  return element;
}
var PASSIVE_EVENTS = ["touchstart", "touchend", "touchmove", "touchcancel", "scroll"];
var NON_PASSIVE_EVENTS = ["wheel"];
var supports = {};
var _isEventSupported = /* @__PURE__ */ (() => {
  const tags = {
    select: "input",
    change: "input",
    submit: "form",
    reset: "form",
    error: "img",
    load: "img",
    abort: "img"
  };
  const eventChecker = (eventName) => {
    if (typeof supports[eventName] === "boolean") {
      return supports[eventName];
    }
    const el = document.createElement(tags[eventName] || "div");
    eventName = "on" + eventName;
    return supports[eventName] = eventName in el;
  };
  return eventChecker;
})();
function _isElementInEventPath(element, event) {
  if (!event || !element) {
    return false;
  }
  return _getEventPath(event).indexOf(element) >= 0;
}
function _createEventPath(event) {
  const res = [];
  let pointer = event.target;
  while (pointer) {
    res.push(pointer);
    pointer = pointer.parentElement;
  }
  return res;
}
function _getEventPath(event) {
  const eventNoType = event;
  if (eventNoType.path) {
    return eventNoType.path;
  }
  if (eventNoType.composedPath) {
    return eventNoType.composedPath();
  }
  return _createEventPath(eventNoType);
}
function _addSafePassiveEventListener(eElement, event, listener) {
  const passive2 = getPassiveStateForEvent(event);
  let options;
  if (passive2 != null) {
    options = { passive: passive2 };
  }
  eElement.addEventListener(event, listener, options);
}
var getPassiveStateForEvent = (event) => {
  const isPassive = PASSIVE_EVENTS.includes(event);
  const isNonPassive = NON_PASSIVE_EVENTS.includes(event);
  if (isPassive) {
    return true;
  }
  if (isNonPassive) {
    return false;
  }
};
function _areEventsNear(e1, e2, pixelCount) {
  if (pixelCount === 0) {
    return false;
  }
  const diffX = Math.abs(e1.clientX - e2.clientX);
  const diffY = Math.abs(e1.clientY - e2.clientY);
  return Math.max(diffX, diffY) <= pixelCount;
}
var _getFirstActiveTouch = (touch, touchList) => {
  const identifier = touch.identifier;
  for (let i2 = 0, len = touchList.length; i2 < len; ++i2) {
    const item2 = touchList[i2];
    if (item2.identifier === identifier) {
      return item2;
    }
  }
  return null;
};
function _isEventFromThisInstance(beans, event) {
  return beans.gos.isElementInThisInstance(event.target);
}
function _anchorElementToMouseMoveEvent(element, mouseMoveEvent, beans) {
  const eRect = element.getBoundingClientRect();
  const height = eRect.height;
  const browserWidth = _getBodyWidth(beans) - 2;
  const browserHeight = _getBodyHeight(beans) - 2;
  const offsetParent = element.offsetParent;
  if (!offsetParent) {
    return;
  }
  const offsetParentSize = _getElementRectWithOffset(element.offsetParent);
  const { clientY, clientX } = mouseMoveEvent;
  let top2 = clientY - offsetParentSize.top - height / 2;
  let left2 = clientX - offsetParentSize.left - 10;
  const eDocument = _getDocument(beans);
  const win = eDocument.defaultView || window;
  const windowScrollY = win.pageYOffset || eDocument.documentElement.scrollTop;
  const windowScrollX = win.pageXOffset || eDocument.documentElement.scrollLeft;
  if (browserWidth > 0 && left2 + element.clientWidth > browserWidth + windowScrollX) {
    left2 = browserWidth + windowScrollX - element.clientWidth;
  }
  if (left2 < 0) {
    left2 = 0;
  }
  if (browserHeight > 0 && top2 + element.clientHeight > browserHeight + windowScrollY) {
    top2 = browserHeight + windowScrollY - element.clientHeight;
  }
  if (top2 < 0) {
    top2 = 0;
  }
  element.style.left = `${left2}px`;
  element.style.top = `${top2}px`;
}
var addTempEventHandlers = (list2, ...handlers) => {
  for (const handler of handlers) {
    const [target, type, eventListener, options] = handler;
    target.addEventListener(type, eventListener, options);
    list2.push(handler);
  }
};
var clearTempEventHandlers = (list2) => {
  if (list2) {
    for (const [target, type, listener, options] of list2) {
      target.removeEventListener(type, listener, options);
    }
    list2.length = 0;
  }
};
var preventEventDefault = (event) => {
  if (event.cancelable) {
    event.preventDefault();
  }
};
function defaultLocaleTextFunc(_key, defaultValue) {
  return defaultValue;
}
function _getLocaleTextFunc(localeSvc) {
  return localeSvc?.getLocaleTextFunc() ?? defaultLocaleTextFunc;
}
function _translate(bean, localeValues, key2, variableValues) {
  const defaultValue = localeValues[key2];
  return bean.getLocaleTextFunc()(
    key2,
    typeof defaultValue === "function" ? defaultValue(variableValues) : defaultValue,
    variableValues
  );
}
function _getLocaleTextFromFunc(getLocaleText) {
  return (key2, defaultValue, variableValues) => {
    return getLocaleText({
      key: key2,
      defaultValue,
      variableValues
    });
  };
}
function _getLocaleTextFromMap(localeText) {
  return (key2, defaultValue, variableValues) => {
    let localisedText = localeText?.[key2];
    if (localisedText && variableValues?.length) {
      let found = 0;
      while (true) {
        if (found >= variableValues.length) {
          break;
        }
        const idx = localisedText.indexOf("${variable}");
        if (idx === -1) {
          break;
        }
        localisedText = localisedText.replace("${variable}", variableValues[found++]);
      }
    }
    return localisedText ?? defaultValue;
  };
}
var AgBeanStub = class {
  constructor() {
    this.destroyFunctions = [];
    this.destroyed = false;
    this.__v_skip = true;
    this.propertyListenerId = 0;
    this.lastChangeSetIdLookup = {};
    this.isAlive = () => !this.destroyed;
  }
  preWireBeans(beans) {
    this.beans = beans;
    this.stubContext = beans.context;
    this.eventSvc = beans.eventSvc;
    this.gos = beans.gos;
  }
  // this was a test constructor niall built, when active, it prints after 5 seconds all beans/components that are
  // not destroyed. to use, create a new grid, then api.destroy() before 5 seconds. then anything that gets printed
  // points to a bean or component that was not properly disposed of.
  // constructor() {
  //     setTimeout(()=> {
  //         if (this.isAlive()) {
  //             let prototype: any = Object.getPrototypeOf(this);
  //             const constructor: any = prototype.constructor;
  //             const constructorString = constructor.toString();
  //             const beanName = constructorString.substring(9, constructorString.indexOf("("));
  //             console.log('is alive ' + beanName);
  //         }
  //     }, 5000);
  // }
  destroy() {
    const { destroyFunctions } = this;
    for (let i2 = 0; i2 < destroyFunctions.length; i2++) {
      destroyFunctions[i2]();
    }
    destroyFunctions.length = 0;
    this.destroyed = true;
    this.dispatchLocalEvent({ type: "destroyed" });
  }
  /** Add a local event listener against this BeanStub */
  addEventListener(eventType, listener, async) {
    if (!this.localEventService) {
      this.localEventService = new LocalEventService();
    }
    this.localEventService.addEventListener(eventType, listener, async);
  }
  /** Remove a local event listener from this BeanStub */
  removeEventListener(eventType, listener, async) {
    this.localEventService?.removeEventListener(eventType, listener, async);
  }
  dispatchLocalEvent(event) {
    this.localEventService?.dispatchEvent(event);
  }
  addManagedElementListeners(object2, handlers) {
    return this._setupListeners(object2, handlers);
  }
  addManagedEventListeners(handlers) {
    return this._setupListeners(this.eventSvc, handlers);
  }
  addManagedListeners(object2, handlers) {
    return this._setupListeners(object2, handlers);
  }
  _setupListeners(object2, handlers) {
    const destroyFuncs = [];
    for (const k of Object.keys(handlers)) {
      const handler = handlers[k];
      if (handler) {
        destroyFuncs.push(this._setupListener(object2, k, handler));
      }
    }
    return destroyFuncs;
  }
  _setupListener(object2, event, listener) {
    if (this.destroyed) {
      return () => null;
    }
    let destroyFunc;
    if (isAgEventEmitter(object2)) {
      object2.__addEventListener(event, listener);
      destroyFunc = () => {
        object2.__removeEventListener(event, listener);
        return null;
      };
    } else {
      const objIsEventService = isEventService(object2);
      if (object2 instanceof HTMLElement) {
        _addSafePassiveEventListener(object2, event, listener);
      } else if (objIsEventService) {
        object2.addListener(event, listener);
      } else {
        object2.addEventListener(event, listener);
      }
      destroyFunc = objIsEventService ? () => {
        object2.removeListener(event, listener);
        return null;
      } : () => {
        object2.removeEventListener(event, listener);
        return null;
      };
    }
    this.destroyFunctions.push(destroyFunc);
    return () => {
      destroyFunc();
      this.destroyFunctions = this.destroyFunctions.filter((fn3) => fn3 !== destroyFunc);
      return null;
    };
  }
  /**
   * Setup a managed property listener for the given property.
   * However, stores the destroy function in the beanStub so that if this bean
   * is a component the destroy function will be called when the component is destroyed
   * as opposed to being cleaned up only when the properties service is destroyed.
   */
  setupPropertyListener(event, listener) {
    const { gos } = this;
    gos.addPropertyEventListener(event, listener);
    const destroyFunc = () => {
      gos.removePropertyEventListener(event, listener);
      return null;
    };
    this.destroyFunctions.push(destroyFunc);
    return () => {
      destroyFunc();
      this.destroyFunctions = this.destroyFunctions.filter((fn3) => fn3 !== destroyFunc);
      return null;
    };
  }
  /**
   * Setup a managed property listener for the given GridOption property.
   * @param event GridOption property to listen to changes for.
   * @param listener Listener to run when property value changes
   */
  addManagedPropertyListener(event, listener) {
    if (this.destroyed) {
      return () => null;
    }
    return this.setupPropertyListener(event, listener);
  }
  /**
   * Setup managed property listeners for the given set of GridOption properties.
   * The listener will be run if any of the property changes but will only run once if
   * multiple of the properties change within the same framework lifecycle event.
   * Works on the basis that GridOptionsService updates all properties *before* any property change events are fired.
   * @param events Array of GridOption properties to listen for changes too.
   * @param listener Shared listener to run if any of the properties change
   */
  addManagedPropertyListeners(events, listener) {
    if (this.destroyed) {
      return;
    }
    const eventsKey = events.join("-") + this.propertyListenerId++;
    const wrappedListener = (event) => {
      if (event.changeSet) {
        if (event.changeSet && event.changeSet.id === this.lastChangeSetIdLookup[eventsKey]) {
          return;
        }
        this.lastChangeSetIdLookup[eventsKey] = event.changeSet.id;
      }
      const propertiesChangeEvent = {
        type: "propertyChanged",
        changeSet: event.changeSet,
        source: event.source
      };
      listener(propertiesChangeEvent);
    };
    for (const event of events) {
      this.setupPropertyListener(event, wrappedListener);
    }
  }
  getLocaleTextFunc() {
    return _getLocaleTextFunc(this.beans.localeSvc);
  }
  addDestroyFunc(func2) {
    if (this.isAlive()) {
      this.destroyFunctions.push(func2);
    } else {
      func2();
    }
  }
  /** doesn't throw an error if `bean` is undefined */
  createOptionalManagedBean(bean, context) {
    return bean ? this.createManagedBean(bean, context) : void 0;
  }
  createManagedBean(bean, context) {
    const res = this.createBean(bean, context);
    this.addDestroyFunc(this.destroyBean.bind(this, bean, context));
    return res;
  }
  createBean(bean, context, afterPreCreateCallback) {
    return (context || this.stubContext).createBean(bean, afterPreCreateCallback);
  }
  /**
   * Destroys a bean and returns undefined to support destruction and clean up in a single line.
   * this.dateComp = this.context.destroyBean(this.dateComp);
   */
  destroyBean(bean, context) {
    return (context || this.stubContext).destroyBean(bean);
  }
  /**
   * Destroys an array of beans and returns an empty array to support destruction and clean up in a single line.
   * this.dateComps = this.context.destroyBeans(this.dateComps);
   */
  destroyBeans(beans, context) {
    return (context || this.stubContext).destroyBeans(beans);
  }
};
function isAgEventEmitter(object2) {
  return object2.__addEventListener !== void 0;
}
function isEventService(object2) {
  return object2.eventServiceType === "global";
}
var BeanStub = class extends AgBeanStub {
};
var doOnceFlags = {};
function _doOnce(func2, key2) {
  if (doOnceFlags[key2]) {
    return;
  }
  func2();
  doOnceFlags[key2] = true;
}
var batchedCallsSetTimeout = {
  pending: false,
  funcs: []
};
var batchedCallsRaf = {
  pending: false,
  funcs: []
};
function _batchCall(func2, mode = "setTimeout", beans) {
  const batch2 = mode === "raf" ? batchedCallsRaf : batchedCallsSetTimeout;
  batch2.funcs.push(func2);
  if (batch2.pending) {
    return;
  }
  batch2.pending = true;
  const runBatch = () => {
    const funcsCopy = batch2.funcs.slice();
    batch2.funcs.length = 0;
    batch2.pending = false;
    for (const func22 of funcsCopy) {
      func22();
    }
  };
  if (mode === "raf") {
    _requestAnimationFrame(beans, runBatch);
  } else {
    window.setTimeout(runBatch, 0);
  }
}
function _debounce(bean, func2, delay) {
  let timeout;
  return function(...args2) {
    const context = this;
    window.clearTimeout(timeout);
    timeout = window.setTimeout(function() {
      if (bean.isAlive()) {
        func2.apply(context, args2);
      }
    }, delay);
  };
}
function _throttle(func2, wait) {
  let previousCall = 0;
  return function(...args2) {
    const context = this;
    const currentCall = Date.now();
    if (currentCall - previousCall < wait) {
      return;
    }
    previousCall = currentCall;
    func2.apply(context, args2);
  };
}
function _waitUntil(bean, condition, callback, timeout = 100) {
  const timeStamp = Date.now();
  let interval2 = null;
  let executed = false;
  const clearWait = () => {
    if (interval2 != null) {
      window.clearInterval(interval2);
      interval2 = null;
    }
  };
  bean.addDestroyFunc(clearWait);
  const internalCallback = () => {
    const reachedTimeout = Date.now() - timeStamp > timeout;
    if (condition() || reachedTimeout) {
      callback();
      executed = true;
      clearWait();
    }
  };
  internalCallback();
  if (!executed) {
    interval2 = window.setInterval(internalCallback, 10);
  }
}
var SKIP_JS_BUILTINS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
function _iterateObject(object2, callback) {
  if (object2 == null) {
    return;
  }
  if (Array.isArray(object2)) {
    for (let i2 = 0; i2 < object2.length; i2++) {
      callback(i2.toString(), object2[i2]);
    }
    return;
  }
  for (const key2 of Object.keys(object2).filter((key22) => !SKIP_JS_BUILTINS.has(key22))) {
    callback(key2, object2[key2]);
  }
}
function _mergeDeep(dest, source2, copyUndefined = true, makeCopyOfSimpleObjects = false) {
  if (!_exists(source2)) {
    return;
  }
  _iterateObject(source2, (key2, sourceValue) => {
    let destValue = dest[key2];
    if (destValue === sourceValue) {
      return;
    }
    if (makeCopyOfSimpleObjects) {
      const objectIsDueToBeCopied = destValue == null && sourceValue != null;
      if (objectIsDueToBeCopied) {
        const doNotCopyAsSourceIsSimpleObject = typeof sourceValue === "object" && sourceValue.constructor === Object;
        if (doNotCopyAsSourceIsSimpleObject) {
          destValue = {};
          dest[key2] = destValue;
        }
      }
    }
    if (_isNonNullObject(sourceValue) && _isNonNullObject(destValue) && !Array.isArray(destValue)) {
      _mergeDeep(destValue, sourceValue, copyUndefined, makeCopyOfSimpleObjects);
    } else if (copyUndefined || sourceValue !== void 0) {
      dest[key2] = sourceValue;
    }
  });
}
function _isNonNullObject(value2) {
  return typeof value2 === "object" && value2 !== null;
}
var _GlobalGridOptions = class _GlobalGridOptions2 {
  /**
   * @param providedOptions
   * @returns Shallow copy of the provided options with global options merged in.
   */
  static applyGlobalGridOptions(providedOptions) {
    if (!_GlobalGridOptions2.gridOptions) {
      return { ...providedOptions };
    }
    let mergedGridOps = {};
    _mergeDeep(mergedGridOps, _GlobalGridOptions2.gridOptions, true, true);
    if (_GlobalGridOptions2.mergeStrategy === "deep") {
      _mergeDeep(mergedGridOps, providedOptions, true, true);
    } else {
      mergedGridOps = { ...mergedGridOps, ...providedOptions };
    }
    if (_GlobalGridOptions2.gridOptions.context) {
      mergedGridOps.context = _GlobalGridOptions2.gridOptions.context;
    }
    if (providedOptions.context) {
      if (_GlobalGridOptions2.mergeStrategy === "deep" && mergedGridOps.context) {
        _mergeDeep(providedOptions.context, mergedGridOps.context, true, true);
      }
      mergedGridOps.context = providedOptions.context;
    }
    return mergedGridOps;
  }
  /**
   * Apply global grid option for a specific option key.
   * If the merge strategy is 'deep' and both global and provided values are objects, they will be merged deeply.
   * Otherwise, the provided value is returned as is.
   * @param optionKey - The key of the grid option to apply.
   * @param providedValue - The value provided to the grid instance.
   * @returns The merged value if applicable, otherwise the provided value.
   */
  static applyGlobalGridOption(optionKey, providedValue) {
    if (_GlobalGridOptions2.mergeStrategy === "deep") {
      const globalValue = _getGlobalGridOption(optionKey);
      if (globalValue && typeof globalValue === "object" && typeof providedValue === "object") {
        return _GlobalGridOptions2.applyGlobalGridOptions({ [optionKey]: providedValue })[optionKey];
      }
    }
    return providedValue;
  }
};
_GlobalGridOptions.gridOptions = void 0;
_GlobalGridOptions.mergeStrategy = "shallow";
var GlobalGridOptions = _GlobalGridOptions;
function _getGlobalGridOption(gridOption) {
  return GlobalGridOptions.gridOptions?.[gridOption];
}
var GRID_OPTION_DEFAULTS = {
  suppressContextMenu: false,
  preventDefaultOnContextMenu: false,
  allowContextMenuWithControlKey: false,
  suppressMenuHide: true,
  enableBrowserTooltips: false,
  tooltipTrigger: "hover",
  tooltipShowDelay: 2e3,
  tooltipHideDelay: 1e4,
  tooltipMouseTrack: false,
  tooltipShowMode: "standard",
  tooltipInteraction: false,
  copyHeadersToClipboard: false,
  copyGroupHeadersToClipboard: false,
  clipboardDelimiter: "	",
  suppressCopyRowsToClipboard: false,
  suppressCopySingleCellRanges: false,
  suppressLastEmptyLineOnPaste: false,
  suppressClipboardPaste: false,
  suppressClipboardApi: false,
  suppressCutToClipboard: false,
  maintainColumnOrder: false,
  enableStrictPivotColumnOrder: false,
  suppressFieldDotNotation: false,
  allowDragFromColumnsToolPanel: false,
  suppressMovableColumns: false,
  suppressColumnMoveAnimation: false,
  suppressMoveWhenColumnDragging: false,
  suppressDragLeaveHidesColumns: false,
  suppressRowGroupHidesColumns: false,
  suppressAutoSize: false,
  autoSizePadding: 20,
  skipHeaderOnAutoSize: false,
  singleClickEdit: false,
  suppressClickEdit: false,
  readOnlyEdit: false,
  stopEditingWhenCellsLoseFocus: false,
  enterNavigatesVertically: false,
  enterNavigatesVerticallyAfterEdit: false,
  enableCellEditingOnBackspace: false,
  undoRedoCellEditing: false,
  undoRedoCellEditingLimit: 10,
  suppressCsvExport: false,
  suppressExcelExport: false,
  cacheQuickFilter: false,
  includeHiddenColumnsInQuickFilter: false,
  excludeChildrenWhenTreeDataFiltering: false,
  enableAdvancedFilter: false,
  includeHiddenColumnsInAdvancedFilter: false,
  enableCharts: false,
  masterDetail: false,
  keepDetailRows: false,
  keepDetailRowsCount: 10,
  detailRowAutoHeight: false,
  tabIndex: 0,
  rowBuffer: 10,
  valueCache: false,
  valueCacheNeverExpires: false,
  enableCellExpressions: false,
  suppressTouch: false,
  suppressFocusAfterRefresh: false,
  suppressBrowserResizeObserver: false,
  suppressPropertyNamesCheck: false,
  suppressChangeDetection: false,
  debug: false,
  suppressLoadingOverlay: false,
  suppressNoRowsOverlay: false,
  pagination: false,
  paginationPageSize: 100,
  paginationPageSizeSelector: true,
  paginationAutoPageSize: false,
  paginateChildRows: false,
  suppressPaginationPanel: false,
  pivotMode: false,
  pivotPanelShow: "never",
  pivotDefaultExpanded: 0,
  pivotSuppressAutoColumn: false,
  suppressExpandablePivotGroups: false,
  functionsReadOnly: false,
  suppressAggFuncInHeader: false,
  alwaysAggregateAtRootLevel: false,
  aggregateOnlyChangedColumns: false,
  suppressAggFilteredOnly: false,
  removePivotHeaderRowWhenSingleValueColumn: false,
  animateRows: true,
  cellFlashDuration: 500,
  cellFadeDuration: 1e3,
  allowShowChangeAfterFilter: false,
  domLayout: "normal",
  ensureDomOrder: false,
  enableRtl: false,
  suppressColumnVirtualisation: false,
  suppressMaxRenderedRowRestriction: false,
  suppressRowVirtualisation: false,
  rowDragManaged: false,
  rowDragInsertDelay: 500,
  suppressRowDrag: false,
  suppressMoveWhenRowDragging: false,
  rowDragEntireRow: false,
  rowDragMultiRow: false,
  embedFullWidthRows: false,
  groupDisplayType: "singleColumn",
  groupDefaultExpanded: 0,
  groupMaintainOrder: false,
  groupSelectsChildren: false,
  groupSuppressBlankHeader: false,
  groupSelectsFiltered: false,
  showOpenedGroup: false,
  groupRemoveSingleChildren: false,
  groupRemoveLowestSingleChildren: false,
  groupHideOpenParents: false,
  groupAllowUnbalanced: false,
  rowGroupPanelShow: "never",
  suppressMakeColumnVisibleAfterUnGroup: false,
  treeData: false,
  rowGroupPanelSuppressSort: false,
  suppressGroupRowsSticky: false,
  rowModelType: "clientSide",
  asyncTransactionWaitMillis: 50,
  suppressModelUpdateAfterUpdateTransaction: false,
  cacheOverflowSize: 1,
  infiniteInitialRowCount: 1,
  serverSideInitialRowCount: 1,
  cacheBlockSize: 100,
  maxBlocksInCache: -1,
  maxConcurrentDatasourceRequests: 2,
  blockLoadDebounceMillis: 0,
  purgeClosedRowNodes: false,
  serverSideSortAllLevels: false,
  serverSideOnlyRefreshFilteredGroups: false,
  serverSidePivotResultFieldSeparator: "_",
  viewportRowModelPageSize: 5,
  viewportRowModelBufferSize: 5,
  alwaysShowHorizontalScroll: false,
  alwaysShowVerticalScroll: false,
  debounceVerticalScrollbar: false,
  suppressHorizontalScroll: false,
  suppressScrollOnNewData: false,
  suppressScrollWhenPopupsAreOpen: false,
  suppressAnimationFrame: false,
  suppressMiddleClickScrolls: false,
  suppressPreventDefaultOnMouseWheel: false,
  rowMultiSelectWithClick: false,
  suppressRowDeselection: false,
  suppressRowClickSelection: false,
  suppressCellFocus: false,
  suppressHeaderFocus: false,
  suppressMultiRangeSelection: false,
  enableCellTextSelection: false,
  enableRangeSelection: false,
  enableRangeHandle: false,
  enableFillHandle: false,
  fillHandleDirection: "xy",
  suppressClearOnFillReduction: false,
  accentedSort: false,
  unSortIcon: false,
  suppressMultiSort: false,
  alwaysMultiSort: false,
  suppressMaintainUnsortedOrder: false,
  suppressRowHoverHighlight: false,
  suppressRowTransform: false,
  columnHoverHighlight: false,
  deltaSort: false,
  enableGroupEdit: false,
  groupLockGroupColumns: 0,
  serverSideEnableClientSideSort: false,
  suppressServerSideFullWidthLoadingRow: false,
  pivotMaxGeneratedColumns: -1,
  columnMenu: "new",
  reactiveCustomComponents: true,
  suppressSetFilterByDefault: false,
  rowNumbers: false,
  enableFilterHandlers: false
};
var BASE_URL = "https://www.ag-grid.com";
function _logIfDebug(gos, message2, ...args2) {
  if (gos.get("debug")) {
    console.log("AG Grid: " + message2, ...args2);
  }
}
function _warnOnce(msg, ...args2) {
  _doOnce(() => console.warn("AG Grid: " + msg, ...args2), msg + args2?.join(""));
}
function _errorOnce(msg, ...args2) {
  _doOnce(() => console.error("AG Grid: " + msg, ...args2), msg + args2?.join(""));
}
var allRegisteredModules = /* @__PURE__ */ new Set();
var globalModulesMap = {};
var gridModulesMap = {};
var currentModuleVersion;
var userHasRegistered = false;
var areGridScopedModules = false;
var isUmd = false;
function isValidModuleVersion(module) {
  const [moduleMajor, moduleMinor] = module.version.split(".") || [];
  const [currentModuleMajor, currentModuleMinor] = currentModuleVersion.split(".") || [];
  return moduleMajor === currentModuleMajor && moduleMinor === currentModuleMinor;
}
function runVersionChecks(module) {
  if (!currentModuleVersion) {
    currentModuleVersion = module.version;
  }
  const errorMsg = (details) => `You are using incompatible versions of AG Grid modules. Major and minor versions should always match across modules. ${details} Please update all modules to the same version.`;
  if (!module.version) {
    _errorOnce(errorMsg(`'${module.moduleName}' is incompatible.`));
  } else if (!isValidModuleVersion(module)) {
    _errorOnce(
      errorMsg(
        `'${module.moduleName}' is version ${module.version} but the other modules are version ${currentModuleVersion}.`
      )
    );
  }
  const result2 = module.validate?.();
  if (result2 && !result2.isValid) {
    _errorOnce(`${result2.message}`);
  }
}
function _registerModule(module, gridId, isInternalRegistration = false) {
  if (!isInternalRegistration) {
    userHasRegistered = true;
  }
  runVersionChecks(module);
  const rowModels = module.rowModels ?? ["all"];
  allRegisteredModules.add(module);
  let moduleStore;
  if (gridId !== void 0) {
    areGridScopedModules = true;
    if (gridModulesMap[gridId] === void 0) {
      gridModulesMap[gridId] = {};
    }
    moduleStore = gridModulesMap[gridId];
  } else {
    moduleStore = globalModulesMap;
  }
  for (const rowModel of rowModels) {
    if (moduleStore[rowModel] === void 0) {
      moduleStore[rowModel] = {};
    }
    moduleStore[rowModel][module.moduleName] = module;
  }
  if (module.dependsOn) {
    for (const dependency of module.dependsOn) {
      _registerModule(dependency, gridId, isInternalRegistration);
    }
  }
}
function _unRegisterGridModules(gridId) {
  delete gridModulesMap[gridId];
}
function _isModuleRegistered(moduleName, gridId, rowModel) {
  const isRegisteredForRowModel = (model2) => !!globalModulesMap[model2]?.[moduleName] || !!gridModulesMap[gridId]?.[model2]?.[moduleName];
  return isRegisteredForRowModel(rowModel) || isRegisteredForRowModel("all");
}
function _areModulesGridScoped() {
  return areGridScopedModules;
}
function _getRegisteredModules(gridId, rowModel) {
  const gridModules = gridModulesMap[gridId] ?? {};
  return [
    ...Object.values(globalModulesMap["all"] ?? {}),
    ...Object.values(gridModules["all"] ?? {}),
    ...Object.values(globalModulesMap[rowModel] ?? {}),
    ...Object.values(gridModules[rowModel] ?? {})
  ];
}
function _getAllRegisteredModules() {
  return new Set(allRegisteredModules);
}
function _getGridRegisteredModules(gridId, rowModel) {
  const gridModules = gridModulesMap[gridId] ?? {};
  return [...Object.values(gridModules["all"] ?? {}), ...Object.values(gridModules[rowModel] ?? {})];
}
function _hasUserRegistered() {
  return userHasRegistered;
}
function _isUmd() {
  return isUmd;
}
var ModuleRegistry = class {
  /**
   * @deprecated v33 Use `registerModules([module])` instead.
   */
  static register(module) {
    _registerModule(module, void 0);
  }
  /**
   * Globally register the given modules for all grids.
   * @param modules - modules to register
   */
  static registerModules(modules) {
    for (const module of modules) {
      _registerModule(module, void 0);
    }
  }
};
var VERSION = "34.3.1";
var MAX_URL_LENGTH = 2e3;
var MIN_PARAM_LENGTH = 100;
var VERSION_PARAM_NAME = "_version_";
var getConsoleMessage = null;
var baseDocLink = `${BASE_URL}/javascript-data-grid`;
function provideValidationServiceLogger(logger) {
  getConsoleMessage = logger;
}
function setValidationDocLink(docLink) {
  baseDocLink = docLink;
}
function getErrorParts(id2, args2, defaultMessage) {
  return getConsoleMessage?.(id2, args2) ?? [minifiedLog(id2, args2, defaultMessage)];
}
function getMsgOrDefault(logger, id2, args2, isWarning, defaultMessage) {
  logger(`${isWarning ? "warning" : "error"} #${id2}`, ...getErrorParts(id2, args2, defaultMessage));
}
function stringifyObject(inputObj) {
  if (!inputObj) {
    return String(inputObj);
  }
  const object2 = {};
  for (const prop of Object.keys(inputObj)) {
    if (typeof inputObj[prop] !== "object" && typeof inputObj[prop] !== "function") {
      object2[prop] = inputObj[prop];
    }
  }
  return JSON.stringify(object2);
}
function stringifyValue(value2) {
  let output2 = value2;
  if (value2 instanceof Error) {
    output2 = value2.toString();
  } else if (typeof value2 === "object") {
    output2 = stringifyObject(value2);
  }
  return output2;
}
function toStringWithNullUndefined(str) {
  return str === void 0 ? "undefined" : str === null ? "null" : str;
}
function getParamsUrl(baseUrl, params) {
  return `${baseUrl}?${params.toString()}`;
}
function truncateUrl(baseUrl, params, maxLength) {
  const sortedParams = Array.from(params.entries()).sort((a2, b) => b[1].length - a2[1].length);
  let url = getParamsUrl(baseUrl, params);
  for (const [key2, value2] of sortedParams) {
    if (key2 === VERSION_PARAM_NAME) {
      continue;
    }
    const excessLength = url.length - maxLength;
    if (excessLength <= 0) {
      break;
    }
    const ellipse = "...";
    const truncateAmount = excessLength + ellipse.length;
    const truncatedValue = value2.length - truncateAmount > MIN_PARAM_LENGTH ? value2.slice(0, value2.length - truncateAmount) + ellipse : value2.slice(0, MIN_PARAM_LENGTH) + ellipse;
    params.set(key2, truncatedValue);
    url = getParamsUrl(baseUrl, params);
  }
  return url;
}
function getErrorLink(errorNum, args2) {
  const params = new URLSearchParams();
  params.append(VERSION_PARAM_NAME, VERSION);
  if (args2) {
    for (const key2 of Object.keys(args2)) {
      params.append(key2, stringifyValue(args2[key2]));
    }
  }
  const baseUrl = `${baseDocLink}/errors/${errorNum}`;
  const url = getParamsUrl(baseUrl, params);
  return url.length <= MAX_URL_LENGTH ? url : truncateUrl(baseUrl, params, MAX_URL_LENGTH);
}
var minifiedLog = (errorNum, args2, defaultMessage) => {
  const errorLink = getErrorLink(errorNum, args2);
  const prefix = `${defaultMessage ? defaultMessage + " \n" : ""}Visit ${errorLink}`;
  return `${prefix}${defaultMessage ? "" : " \n  Alternatively register the ValidationModule to see the full message in the console."}`;
};
function _warn(...args2) {
  getMsgOrDefault(_warnOnce, args2[0], args2[1], true);
}
function _error(...args2) {
  getMsgOrDefault(_errorOnce, args2[0], args2[1], false);
}
function _logPreInitErr(id2, args2, defaultMessage) {
  getMsgOrDefault(_errorOnce, id2, args2, false, defaultMessage);
}
function getErrMsg(defaultMessage, args2) {
  const id2 = args2[0];
  return `error #${id2} ` + getErrorParts(id2, args2[1], defaultMessage).join(" ");
}
function _errMsg(...args2) {
  return getErrMsg(void 0, args2);
}
function isRowModelType(gos, rowModelType) {
  return gos.get("rowModelType") === rowModelType;
}
function _isClientSideRowModel(gos, rowModel) {
  return isRowModelType(gos, "clientSide");
}
function _isServerSideRowModel(gos, rowModel) {
  return isRowModelType(gos, "serverSide");
}
function _isDomLayout(gos, domLayout) {
  return gos.get("domLayout") === domLayout;
}
function _isRowSelection(gos) {
  return _getRowSelectionMode(gos) !== void 0;
}
function _isGetRowHeightFunction(gos) {
  return typeof gos.get("getRowHeight") === "function";
}
function _shouldMaintainColumnOrder(gos, isPivotColumns) {
  if (isPivotColumns) {
    return !gos.get("enableStrictPivotColumnOrder");
  }
  return gos.get("maintainColumnOrder");
}
function _getRowHeightForNode(beans, rowNode, allowEstimate = false, defaultRowHeight) {
  const { gos, environment } = beans;
  if (defaultRowHeight == null) {
    defaultRowHeight = environment.getDefaultRowHeight();
  }
  if (_isGetRowHeightFunction(gos)) {
    if (allowEstimate) {
      return { height: defaultRowHeight, estimated: true };
    }
    const params = {
      node: rowNode,
      data: rowNode.data
    };
    const height = gos.getCallback("getRowHeight")(params);
    if (isNumeric(height)) {
      if (height === 0) {
        _warn(23);
      }
      return { height: Math.max(1, height), estimated: false };
    }
  }
  if (rowNode.detail && gos.get("masterDetail")) {
    return getMasterDetailRowHeight(gos);
  }
  const gridOptionsRowHeight = gos.get("rowHeight");
  const rowHeight = gridOptionsRowHeight && isNumeric(gridOptionsRowHeight) ? gridOptionsRowHeight : defaultRowHeight;
  return { height: rowHeight, estimated: false };
}
function getMasterDetailRowHeight(gos) {
  if (gos.get("detailRowAutoHeight")) {
    return { height: 1, estimated: false };
  }
  const defaultRowHeight = gos.get("detailRowHeight");
  if (isNumeric(defaultRowHeight)) {
    return { height: defaultRowHeight, estimated: false };
  }
  return { height: 300, estimated: false };
}
function _getRowHeightAsNumber(beans) {
  const { environment, gos } = beans;
  const gridOptionsRowHeight = gos.get("rowHeight");
  if (!gridOptionsRowHeight || _missing(gridOptionsRowHeight)) {
    return environment.getDefaultRowHeight();
  }
  const rowHeight = environment.refreshRowHeightVariable();
  if (rowHeight !== -1) {
    return rowHeight;
  }
  _warn(24);
  return environment.getDefaultRowHeight();
}
function isNumeric(value2) {
  return !isNaN(value2) && typeof value2 === "number" && isFinite(value2);
}
function _getDomData(gos, element, key2) {
  const domData = element[gos.getDomDataKey()];
  return domData ? domData[key2] : void 0;
}
function _setDomData(gos, element, key2, value2) {
  const domDataKey = gos.getDomDataKey();
  let domData = element[domDataKey];
  if (_missing(domData)) {
    domData = {};
    element[domDataKey] = domData;
  }
  domData[key2] = value2;
}
function _isAnimateRows(gos) {
  if (gos.get("ensureDomOrder")) {
    return false;
  }
  return gos.get("animateRows");
}
function _isGroupRowsSticky(gos) {
  return !(gos.get("paginateChildRows") || gos.get("groupHideOpenParents") || _isDomLayout(gos, "print"));
}
function _isColumnsSortingCoupledToGroup(gos) {
  const autoGroupColumnDef = gos.get("autoGroupColumnDef");
  return !autoGroupColumnDef?.comparator && !gos.get("treeData");
}
function _getGroupAggFiltering(gos) {
  const userValue = gos.get("groupAggFiltering");
  if (typeof userValue === "function") {
    return gos.getCallback("groupAggFiltering");
  }
  if (userValue === true) {
    return () => true;
  }
  return void 0;
}
function _getGrandTotalRow(gos) {
  return gos.get("grandTotalRow");
}
function _isGroupUseEntireRow(gos, pivotMode) {
  if (pivotMode) {
    return false;
  }
  return gos.get("groupDisplayType") === "groupRows";
}
function _isFullWidthGroupRow(gos, node2, pivotMode) {
  return !!node2.group && !node2.footer && _isGroupUseEntireRow(gos, pivotMode);
}
function _getRowIdCallback(gos) {
  const getRowId = gos.getCallback("getRowId");
  if (getRowId === void 0) {
    return getRowId;
  }
  return (params) => {
    let id2 = getRowId(params);
    if (typeof id2 !== "string") {
      _doOnce(() => _warn(25, { id: id2 }), "getRowIdString");
      id2 = String(id2);
    }
    return id2;
  };
}
function _canSkipShowingRowGroup(gos, node2) {
  const isSkippingGroups = gos.get("groupHideParentOfSingleChild");
  if (isSkippingGroups === true) {
    return true;
  }
  if (isSkippingGroups === "leafGroupsOnly" && node2.leafGroup) {
    return true;
  }
  if (gos.get("groupRemoveSingleChildren")) {
    return true;
  }
  if (gos.get("groupRemoveLowestSingleChildren") && node2.leafGroup) {
    return true;
  }
  return false;
}
function _getMaxConcurrentDatasourceRequests(gos) {
  const res = gos.get("maxConcurrentDatasourceRequests");
  return res > 0 ? res : void 0;
}
function _getCheckboxes(selection) {
  return selection?.checkboxes ?? true;
}
function _getHeaderCheckbox(selection) {
  return selection?.mode === "multiRow" && (selection.headerCheckbox ?? true);
}
function _getCheckboxLocation(rowSelection) {
  if (typeof rowSelection !== "object") {
    return void 0;
  }
  return rowSelection.checkboxLocation ?? "selectionColumn";
}
function _getHideDisabledCheckboxes(selection) {
  return selection?.hideDisabledCheckboxes ?? false;
}
function _isUsingNewRowSelectionAPI(gos) {
  const rowSelection = gos.get("rowSelection");
  return typeof rowSelection !== "string";
}
function _isCellSelectionEnabled(gos) {
  const selection = gos.get("cellSelection");
  const useNewAPI = selection !== void 0;
  return useNewAPI ? !!selection : gos.get("enableRangeSelection");
}
function _getEnableClickSelection(gos) {
  const selection = gos.get("rowSelection") ?? "single";
  if (typeof selection === "string") {
    const suppressRowClickSelection = gos.get("suppressRowClickSelection");
    const suppressRowDeselection = gos.get("suppressRowDeselection");
    if (suppressRowClickSelection && suppressRowDeselection) {
      return false;
    } else if (suppressRowClickSelection) {
      return "enableDeselection";
    } else if (suppressRowDeselection) {
      return "enableSelection";
    } else {
      return true;
    }
  }
  return selection.mode === "singleRow" || selection.mode === "multiRow" ? selection.enableClickSelection ?? false : false;
}
function _getEnableSelection(gos) {
  const enableClickSelection = _getEnableClickSelection(gos);
  return enableClickSelection === true || enableClickSelection === "enableSelection";
}
function _getEnableDeselection(gos) {
  const enableClickSelection = _getEnableClickSelection(gos);
  return enableClickSelection === true || enableClickSelection === "enableDeselection";
}
function _getIsRowSelectable(gos) {
  const selection = gos.get("rowSelection");
  if (typeof selection === "string") {
    return gos.get("isRowSelectable");
  }
  return selection?.isRowSelectable;
}
function _getRowSelectionMode(arg) {
  const selection = "beanName" in arg && arg.beanName === "gos" ? arg.get("rowSelection") : arg.rowSelection;
  if (typeof selection === "string") {
    switch (selection) {
      case "multiple":
        return "multiRow";
      case "single":
        return "singleRow";
      default:
        return;
    }
  }
  switch (selection?.mode) {
    case "multiRow":
    case "singleRow":
      return selection.mode;
    default:
      return;
  }
}
function _isMultiRowSelection(arg) {
  const mode = _getRowSelectionMode(arg);
  return mode === "multiRow";
}
function _getEnableSelectionWithoutKeys(gos) {
  const selection = gos.get("rowSelection");
  if (typeof selection === "string") {
    return gos.get("rowMultiSelectWithClick");
  }
  return selection?.enableSelectionWithoutKeys ?? false;
}
function _getGroupSelection(gos) {
  const selection = gos.get("rowSelection");
  if (typeof selection === "string") {
    const groupSelectsChildren = gos.get("groupSelectsChildren");
    const groupSelectsFiltered = gos.get("groupSelectsFiltered");
    if (groupSelectsChildren && groupSelectsFiltered) {
      return "filteredDescendants";
    } else if (groupSelectsChildren) {
      return "descendants";
    } else {
      return "self";
    }
  }
  return selection?.mode === "multiRow" ? selection.groupSelects : void 0;
}
function _getSelectAll(gos, defaultValue = true) {
  const rowSelection = gos.get("rowSelection");
  if (typeof rowSelection !== "object") {
    return defaultValue ? "all" : void 0;
  }
  return rowSelection.mode === "multiRow" ? rowSelection.selectAll : "all";
}
function _getCtrlASelectsRows(gos) {
  const rowSelection = gos.get("rowSelection");
  if (typeof rowSelection === "string") {
    return false;
  }
  return rowSelection?.mode === "multiRow" ? rowSelection.ctrlASelectsRows ?? false : false;
}
function _getGroupSelectsDescendants(gos) {
  const groupSelection = _getGroupSelection(gos);
  return groupSelection === "descendants" || groupSelection === "filteredDescendants";
}
function _getMasterSelects(gos) {
  const rowSelection = gos.get("rowSelection");
  return typeof rowSelection === "object" && rowSelection.masterSelects || "self";
}
function _isSetFilterByDefault(gos) {
  return gos.isModuleRegistered("SetFilter") && !gos.get("suppressSetFilterByDefault");
}
function _isLegacyMenuEnabled(gos) {
  return gos.get("columnMenu") === "legacy";
}
function _isColumnMenuAnchoringEnabled(gos) {
  return !_isLegacyMenuEnabled(gos);
}
function _getCallbackForEvent(eventName) {
  if (!eventName || eventName.length < 2) {
    return eventName;
  }
  return "on" + eventName[0].toUpperCase() + eventName.substring(1);
}
function _combineAttributesAndGridOptions(gridOptions, component, gridOptionsKeys) {
  if (typeof gridOptions !== "object") {
    gridOptions = {};
  }
  const mergedOptions = { ...gridOptions };
  for (const key2 of gridOptionsKeys) {
    const value2 = component[key2];
    if (typeof value2 !== "undefined") {
      mergedOptions[key2] = value2;
    }
  }
  return mergedOptions;
}
function _processOnChange(changes, api2) {
  if (!changes) {
    return;
  }
  const gridChanges = {};
  let hasChanges = false;
  for (const key2 of Object.keys(changes)) {
    gridChanges[key2] = changes[key2];
    hasChanges = true;
  }
  if (!hasChanges) {
    return;
  }
  const internalUpdateEvent = {
    type: "gridOptionsChanged",
    options: gridChanges
  };
  api2.dispatchEvent(internalUpdateEvent);
  const event = {
    type: "componentStateChanged",
    ...gridChanges
  };
  api2.dispatchEvent(event);
}
function _addGridCommonParams(gos, params) {
  return gos.addCommon(params);
}
function _getGridOption(providedGridOptions, gridOption) {
  return providedGridOptions[gridOption] ?? providedGridOptions[`gridOptions`]?.[gridOption] ?? _getGlobalGridOption(gridOption) ?? GRID_OPTION_DEFAULTS[gridOption];
}
function _interpretAsRightClick({ gos }, event) {
  return event.button === 2 || event.ctrlKey && gos.get("allowContextMenuWithControlKey");
}
var COL_DEF_DEFAULTS = {
  resizable: true,
  sortable: true
};
var instanceIdSequence = 0;
function getNextColInstanceId() {
  return instanceIdSequence++;
}
function isColumn(col) {
  return col instanceof AgColumn;
}
var AgColumn = class extends BeanStub {
  constructor(colDef, userProvidedColDef, colId, primary2) {
    super();
    this.colDef = colDef;
    this.userProvidedColDef = userProvidedColDef;
    this.colId = colId;
    this.primary = primary2;
    this.isColumn = true;
    this.instanceId = getNextColInstanceId();
    this.autoHeaderHeight = null;
    this.moving = false;
    this.resizing = false;
    this.menuVisible = false;
    this.lastLeftPinned = false;
    this.firstRightPinned = false;
    this.filterActive = false;
    this.colEventSvc = new LocalEventService();
    this.tooltipEnabled = false;
    this.rowGroupActive = false;
    this.pivotActive = false;
    this.aggregationActive = false;
    this.flex = null;
    this.colIdSanitised = _escapeString(colId);
  }
  destroy() {
    super.destroy();
    this.beans.rowSpanSvc?.deregister(this);
  }
  getInstanceId() {
    return this.instanceId;
  }
  setState() {
    const {
      colDef,
      beans: { sortSvc, pinnedCols, colFlex }
    } = this;
    sortSvc?.initCol(this);
    const hide2 = colDef.hide;
    if (hide2 !== void 0) {
      this.visible = !hide2;
    } else {
      this.visible = !colDef.initialHide;
    }
    pinnedCols?.initCol(this);
    colFlex?.initCol(this);
  }
  // gets called when user provides an alternative colDef, eg
  setColDef(colDef, userProvidedColDef, source2) {
    const colSpanChanged = colDef.spanRows !== this.colDef.spanRows;
    this.colDef = colDef;
    this.userProvidedColDef = userProvidedColDef;
    this.initMinAndMaxWidths();
    this.initDotNotation();
    this.initTooltip();
    if (colSpanChanged) {
      this.beans.rowSpanSvc?.deregister(this);
      this.initRowSpan();
    }
    this.dispatchColEvent("colDefChanged", source2);
  }
  getUserProvidedColDef() {
    return this.userProvidedColDef;
  }
  getParent() {
    return this.parent;
  }
  getOriginalParent() {
    return this.originalParent;
  }
  // this is done after constructor as it uses gridOptionsService
  postConstruct() {
    this.setState();
    this.initMinAndMaxWidths();
    this.resetActualWidth("gridInitializing");
    this.initDotNotation();
    this.initTooltip();
    this.initRowSpan();
    this.addPivotListener();
  }
  initDotNotation() {
    const {
      gos,
      colDef: { field: field2, tooltipField }
    } = this;
    const suppressDotNotation = gos.get("suppressFieldDotNotation");
    this.fieldContainsDots = _exists(field2) && field2.includes(".") && !suppressDotNotation;
    this.tooltipFieldContainsDots = _exists(tooltipField) && tooltipField.includes(".") && !suppressDotNotation;
  }
  initMinAndMaxWidths() {
    const colDef = this.colDef;
    this.minWidth = colDef.minWidth ?? this.beans.environment.getDefaultColumnMinWidth();
    this.maxWidth = colDef.maxWidth ?? Number.MAX_SAFE_INTEGER;
  }
  initTooltip() {
    this.beans.tooltipSvc?.initCol(this);
  }
  initRowSpan() {
    if (this.colDef.spanRows) {
      this.beans.rowSpanSvc?.register(this);
    }
  }
  addPivotListener() {
    const pivotColDefSvc = this.beans.pivotColDefSvc;
    const pivotValueColumn = this.colDef.pivotValueColumn;
    if (!pivotColDefSvc || !pivotValueColumn) {
      return;
    }
    this.addManagedListeners(pivotValueColumn, {
      colDefChanged: (evt) => {
        const colDef = pivotColDefSvc.recreateColDef(this.colDef);
        this.setColDef(colDef, colDef, evt.source);
      }
    });
  }
  resetActualWidth(source2) {
    const initialWidth = this.calculateColInitialWidth(this.colDef);
    this.setActualWidth(initialWidth, source2, true);
  }
  calculateColInitialWidth(colDef) {
    let width;
    const colDefWidth = colDef.width;
    const colDefInitialWidth = colDef.initialWidth;
    if (colDefWidth != null) {
      width = colDefWidth;
    } else if (colDefInitialWidth != null) {
      width = colDefInitialWidth;
    } else {
      width = 200;
    }
    return Math.max(Math.min(width, this.maxWidth), this.minWidth);
  }
  isEmptyGroup() {
    return false;
  }
  isRowGroupDisplayed(colId) {
    return this.beans.showRowGroupCols?.isRowGroupDisplayed(this, colId) ?? false;
  }
  isPrimary() {
    return this.primary;
  }
  isFilterAllowed() {
    const filterDefined = !!this.colDef.filter;
    return filterDefined;
  }
  isFieldContainsDots() {
    return this.fieldContainsDots;
  }
  isTooltipEnabled() {
    return this.tooltipEnabled;
  }
  isTooltipFieldContainsDots() {
    return this.tooltipFieldContainsDots;
  }
  getHighlighted() {
    return this.highlighted;
  }
  __addEventListener(eventType, listener) {
    this.colEventSvc.addEventListener(eventType, listener);
  }
  __removeEventListener(eventType, listener) {
    this.colEventSvc.removeEventListener(eventType, listener);
  }
  /**
   * PUBLIC USE ONLY: for internal use within AG Grid use the `__addEventListener` and `__removeEventListener` methods.
   */
  addEventListener(eventType, userListener) {
    this.frameworkEventListenerService = this.beans.frameworkOverrides.createLocalEventListenerWrapper?.(
      this.frameworkEventListenerService,
      this.colEventSvc
    );
    const listener = this.frameworkEventListenerService?.wrap(eventType, userListener) ?? userListener;
    this.colEventSvc.addEventListener(eventType, listener);
  }
  /**
   * PUBLIC USE ONLY: for internal use within AG Grid use the `__addEventListener` and `__removeEventListener` methods.
   */
  removeEventListener(eventType, userListener) {
    const listener = this.frameworkEventListenerService?.unwrap(eventType, userListener) ?? userListener;
    this.colEventSvc.removeEventListener(eventType, listener);
  }
  createColumnFunctionCallbackParams(rowNode) {
    return _addGridCommonParams(this.gos, {
      node: rowNode,
      data: rowNode.data,
      column: this,
      colDef: this.colDef
    });
  }
  isSuppressNavigable(rowNode) {
    return this.beans.cellNavigation?.isSuppressNavigable(this, rowNode) ?? false;
  }
  isCellEditable(rowNode) {
    return this.beans.editSvc?.isCellEditable({ rowNode, column: this }) ?? false;
  }
  isSuppressFillHandle() {
    return !!this.colDef.suppressFillHandle;
  }
  isAutoHeight() {
    return !!this.colDef.autoHeight;
  }
  isAutoHeaderHeight() {
    return !!this.colDef.autoHeaderHeight;
  }
  isRowDrag(rowNode) {
    return this.isColumnFunc(rowNode, this.colDef.rowDrag);
  }
  isDndSource(rowNode) {
    return this.isColumnFunc(rowNode, this.colDef.dndSource);
  }
  isCellCheckboxSelection(rowNode) {
    return this.beans.selectionSvc?.isCellCheckboxSelection(this, rowNode) ?? false;
  }
  isSuppressPaste(rowNode) {
    return this.isColumnFunc(rowNode, this.colDef?.suppressPaste ?? null);
  }
  isResizable() {
    return !!this.getColDefValue("resizable");
  }
  /** Get value from ColDef or default if it exists. */
  getColDefValue(key2) {
    return this.colDef[key2] ?? COL_DEF_DEFAULTS[key2];
  }
  isColumnFunc(rowNode, value2) {
    if (typeof value2 === "boolean") {
      return value2;
    }
    if (typeof value2 === "function") {
      const params = this.createColumnFunctionCallbackParams(rowNode);
      const editableFunc = value2;
      return editableFunc(params);
    }
    return false;
  }
  createColumnEvent(type, source2) {
    return _addGridCommonParams(this.gos, {
      type,
      column: this,
      columns: [this],
      source: source2
    });
  }
  isMoving() {
    return this.moving;
  }
  getSort() {
    return this.sort;
  }
  isSortable() {
    return !!this.getColDefValue("sortable");
  }
  /** @deprecated v32 use col.getSort() === 'asc */
  isSortAscending() {
    return this.sort === "asc";
  }
  /** @deprecated v32 use col.getSort() === 'desc */
  isSortDescending() {
    return this.sort === "desc";
  }
  /** @deprecated v32 use col.getSort() === undefined */
  isSortNone() {
    return _missing(this.sort);
  }
  /** @deprecated v32 use col.getSort() !== undefined */
  isSorting() {
    return _exists(this.sort);
  }
  getSortIndex() {
    return this.sortIndex;
  }
  isMenuVisible() {
    return this.menuVisible;
  }
  getAggFunc() {
    return this.aggFunc;
  }
  getLeft() {
    return this.left;
  }
  getOldLeft() {
    return this.oldLeft;
  }
  getRight() {
    return this.left + this.actualWidth;
  }
  setLeft(left2, source2) {
    this.oldLeft = this.left;
    if (this.left !== left2) {
      this.left = left2;
      this.dispatchColEvent("leftChanged", source2);
    }
  }
  isFilterActive() {
    return this.filterActive;
  }
  /** @deprecated v33 Use `api.isColumnHovered(column)` instead. */
  isHovered() {
    _warn(261);
    return !!this.beans.colHover?.isHovered(this);
  }
  setFirstRightPinned(firstRightPinned, source2) {
    if (this.firstRightPinned !== firstRightPinned) {
      this.firstRightPinned = firstRightPinned;
      this.dispatchColEvent("firstRightPinnedChanged", source2);
    }
  }
  setLastLeftPinned(lastLeftPinned, source2) {
    if (this.lastLeftPinned !== lastLeftPinned) {
      this.lastLeftPinned = lastLeftPinned;
      this.dispatchColEvent("lastLeftPinnedChanged", source2);
    }
  }
  isFirstRightPinned() {
    return this.firstRightPinned;
  }
  isLastLeftPinned() {
    return this.lastLeftPinned;
  }
  isPinned() {
    return this.pinned === "left" || this.pinned === "right";
  }
  isPinnedLeft() {
    return this.pinned === "left";
  }
  isPinnedRight() {
    return this.pinned === "right";
  }
  getPinned() {
    return this.pinned;
  }
  setVisible(visible2, source2) {
    const newValue = visible2 === true;
    if (this.visible !== newValue) {
      this.visible = newValue;
      this.dispatchColEvent("visibleChanged", source2);
    }
    this.dispatchStateUpdatedEvent("hide");
  }
  isVisible() {
    return this.visible;
  }
  isSpanHeaderHeight() {
    const colDef = this.getColDef();
    return !colDef.suppressSpanHeaderHeight;
  }
  /**
   * Returns the first parent that is not a padding group.
   */
  getFirstRealParent() {
    let parent = this.getOriginalParent();
    while (parent?.isPadding()) {
      parent = parent.getOriginalParent();
    }
    return parent;
  }
  getColumnGroupPaddingInfo() {
    let parent = this.getParent();
    if (!parent?.isPadding()) {
      return { numberOfParents: 0, isSpanningTotal: false };
    }
    const numberOfParents = parent.getPaddingLevel() + 1;
    let isSpanningTotal = true;
    while (parent) {
      if (!parent.isPadding()) {
        isSpanningTotal = false;
        break;
      }
      parent = parent.getParent();
    }
    return { numberOfParents, isSpanningTotal };
  }
  getColDef() {
    return this.colDef;
  }
  getDefinition() {
    return this.colDef;
  }
  getColumnGroupShow() {
    return this.colDef.columnGroupShow;
  }
  getColId() {
    return this.colId;
  }
  getId() {
    return this.colId;
  }
  getUniqueId() {
    return this.colId;
  }
  getActualWidth() {
    return this.actualWidth;
  }
  getAutoHeaderHeight() {
    return this.autoHeaderHeight;
  }
  /** Returns true if the header height has changed */
  setAutoHeaderHeight(height) {
    const changed = height !== this.autoHeaderHeight;
    this.autoHeaderHeight = height;
    return changed;
  }
  createBaseColDefParams(rowNode) {
    const params = _addGridCommonParams(this.gos, {
      node: rowNode,
      data: rowNode.data,
      colDef: this.colDef,
      column: this
    });
    return params;
  }
  getColSpan(rowNode) {
    if (_missing(this.colDef.colSpan)) {
      return 1;
    }
    const params = this.createBaseColDefParams(rowNode);
    const colSpan = this.colDef.colSpan(params);
    return Math.max(colSpan, 1);
  }
  getRowSpan(rowNode) {
    if (_missing(this.colDef.rowSpan)) {
      return 1;
    }
    const params = this.createBaseColDefParams(rowNode);
    const rowSpan = this.colDef.rowSpan(params);
    return Math.max(rowSpan, 1);
  }
  setActualWidth(actualWidth, source2, silent = false) {
    actualWidth = Math.max(actualWidth, this.minWidth);
    actualWidth = Math.min(actualWidth, this.maxWidth);
    if (this.actualWidth !== actualWidth) {
      this.actualWidth = actualWidth;
      if (this.flex != null && source2 !== "flex" && source2 !== "gridInitializing") {
        this.flex = null;
      }
      if (!silent) {
        this.fireColumnWidthChangedEvent(source2);
      }
    }
    this.dispatchStateUpdatedEvent("width");
  }
  fireColumnWidthChangedEvent(source2) {
    this.dispatchColEvent("widthChanged", source2);
  }
  isGreaterThanMax(width) {
    return width > this.maxWidth;
  }
  getMinWidth() {
    return this.minWidth;
  }
  getMaxWidth() {
    return this.maxWidth;
  }
  getFlex() {
    return this.flex;
  }
  isRowGroupActive() {
    return this.rowGroupActive;
  }
  isPivotActive() {
    return this.pivotActive;
  }
  isAnyFunctionActive() {
    return this.isPivotActive() || this.isRowGroupActive() || this.isValueActive();
  }
  isAnyFunctionAllowed() {
    return this.isAllowPivot() || this.isAllowRowGroup() || this.isAllowValue();
  }
  isValueActive() {
    return this.aggregationActive;
  }
  isAllowPivot() {
    return this.colDef.enablePivot === true;
  }
  isAllowValue() {
    return this.colDef.enableValue === true;
  }
  isAllowRowGroup() {
    return this.colDef.enableRowGroup === true;
  }
  dispatchColEvent(type, source2, additionalEventAttributes) {
    const colEvent = this.createColumnEvent(type, source2);
    if (additionalEventAttributes) {
      _mergeDeep(colEvent, additionalEventAttributes);
    }
    this.colEventSvc.dispatchEvent(colEvent);
  }
  dispatchStateUpdatedEvent(key2) {
    this.colEventSvc.dispatchEvent({
      type: "columnStateUpdated",
      key: key2
    });
  }
};
function isProvidedColumnGroup(col) {
  return col instanceof AgProvidedColumnGroup;
}
var AgProvidedColumnGroup = class extends BeanStub {
  constructor(colGroupDef, groupId, padding, level) {
    super();
    this.colGroupDef = colGroupDef;
    this.groupId = groupId;
    this.padding = padding;
    this.level = level;
    this.isColumn = false;
    this.expandable = false;
    this.instanceId = getNextColInstanceId();
    this.expandableListenerRemoveCallback = null;
    this.expanded = !!colGroupDef?.openByDefault;
  }
  destroy() {
    if (this.expandableListenerRemoveCallback) {
      this.reset(null, void 0);
    }
    super.destroy();
  }
  reset(colGroupDef, level) {
    this.colGroupDef = colGroupDef;
    this.level = level;
    this.originalParent = null;
    if (this.expandableListenerRemoveCallback) {
      this.expandableListenerRemoveCallback();
    }
    this.children = void 0;
    this.expandable = void 0;
  }
  getInstanceId() {
    return this.instanceId;
  }
  getOriginalParent() {
    return this.originalParent;
  }
  getLevel() {
    return this.level;
  }
  isVisible() {
    if (this.children) {
      return this.children.some((child) => child.isVisible());
    }
    return false;
  }
  isPadding() {
    return this.padding;
  }
  setExpanded(expanded) {
    this.expanded = expanded === void 0 ? false : expanded;
    this.dispatchLocalEvent({ type: "expandedChanged" });
  }
  isExpandable() {
    return this.expandable;
  }
  isExpanded() {
    return this.expanded;
  }
  getGroupId() {
    return this.groupId;
  }
  getId() {
    return this.getGroupId();
  }
  setChildren(children2) {
    this.children = children2;
  }
  getChildren() {
    return this.children;
  }
  getColGroupDef() {
    return this.colGroupDef;
  }
  getLeafColumns() {
    const result2 = [];
    this.addLeafColumns(result2);
    return result2;
  }
  forEachLeafColumn(callback) {
    if (!this.children) {
      return;
    }
    for (const child of this.children) {
      if (isColumn(child)) {
        callback(child);
      } else if (isProvidedColumnGroup(child)) {
        child.forEachLeafColumn(callback);
      }
    }
  }
  addLeafColumns(leafColumns) {
    if (!this.children) {
      return;
    }
    for (const child of this.children) {
      if (isColumn(child)) {
        leafColumns.push(child);
      } else if (isProvidedColumnGroup(child)) {
        child.addLeafColumns(leafColumns);
      }
    }
  }
  getColumnGroupShow() {
    const colGroupDef = this.colGroupDef;
    if (!colGroupDef) {
      return;
    }
    return colGroupDef.columnGroupShow;
  }
  // need to check that this group has at least one col showing when both expanded and contracted.
  // if not, then we don't allow expanding and contracting on this group
  setupExpandable() {
    this.setExpandable();
    if (this.expandableListenerRemoveCallback) {
      this.expandableListenerRemoveCallback();
    }
    const listener = this.onColumnVisibilityChanged.bind(this);
    for (const col of this.getLeafColumns()) {
      col.__addEventListener("visibleChanged", listener);
    }
    this.expandableListenerRemoveCallback = () => {
      for (const col of this.getLeafColumns()) {
        col.__removeEventListener("visibleChanged", listener);
      }
      this.expandableListenerRemoveCallback = null;
    };
  }
  setExpandable() {
    if (this.isPadding()) {
      return;
    }
    let atLeastOneShowingWhenOpen = false;
    let atLeastOneShowingWhenClosed = false;
    let atLeastOneChangeable = false;
    const children2 = this.findChildrenRemovingPadding();
    for (let i2 = 0, j2 = children2.length; i2 < j2; i2++) {
      const abstractColumn = children2[i2];
      if (!abstractColumn.isVisible()) {
        continue;
      }
      const headerGroupShow = abstractColumn.getColumnGroupShow();
      if (headerGroupShow === "open") {
        atLeastOneShowingWhenOpen = true;
        atLeastOneChangeable = true;
      } else if (headerGroupShow === "closed") {
        atLeastOneShowingWhenClosed = true;
        atLeastOneChangeable = true;
      } else {
        atLeastOneShowingWhenOpen = true;
        atLeastOneShowingWhenClosed = true;
      }
    }
    const expandable = atLeastOneShowingWhenOpen && atLeastOneShowingWhenClosed && atLeastOneChangeable;
    if (this.expandable !== expandable) {
      this.expandable = expandable;
      this.dispatchLocalEvent({ type: "expandableChanged" });
    }
  }
  findChildrenRemovingPadding() {
    const res = [];
    const process2 = (items) => {
      for (const item2 of items) {
        const skipBecausePadding = isProvidedColumnGroup(item2) && item2.isPadding();
        if (skipBecausePadding) {
          process2(item2.children);
        } else {
          res.push(item2);
        }
      }
    };
    process2(this.children);
    return res;
  }
  onColumnVisibilityChanged() {
    this.setExpandable();
  }
};
var DefaultColumnTypes = {
  numericColumn: {
    headerClass: "ag-right-aligned-header",
    cellClass: "ag-right-aligned-cell"
  },
  rightAligned: {
    headerClass: "ag-right-aligned-header",
    cellClass: "ag-right-aligned-cell"
  }
};
function createMergedColGroupDef(beans, colGroupDef, groupId) {
  const colGroupDefMerged = {};
  const gos = beans.gos;
  Object.assign(colGroupDefMerged, gos.get("defaultColGroupDef"));
  Object.assign(colGroupDefMerged, colGroupDef);
  gos.validateColDef(colGroupDefMerged, groupId);
  return colGroupDefMerged;
}
var ColumnKeyCreator = class {
  constructor() {
    this.existingKeys = {};
  }
  addExistingKeys(keys2) {
    for (let i2 = 0; i2 < keys2.length; i2++) {
      this.existingKeys[keys2[i2]] = true;
    }
  }
  getUniqueKey(colId, colField) {
    colId = _toStringOrNull(colId);
    let count2 = 0;
    while (true) {
      let idToTry = colId ?? colField;
      if (idToTry) {
        if (count2 !== 0) {
          idToTry += "_" + count2;
        }
      } else {
        idToTry = count2;
      }
      if (!this.existingKeys[idToTry]) {
        const usedId = String(idToTry);
        if (colId && count2 > 0) {
          _warn(273, { providedId: colId, usedId });
        }
        this.existingKeys[usedId] = true;
        return usedId;
      }
      count2++;
    }
  }
};
function _last(arr) {
  if (!arr?.length) {
    return;
  }
  return arr[arr.length - 1];
}
function _areEqual(a2, b, comparator) {
  if (a2 === b) {
    return true;
  }
  if (!a2 || !b) {
    return a2 == null && b == null;
  }
  const len = a2.length;
  if (len !== b.length) {
    return false;
  }
  for (let i2 = 0; i2 < len; i2++) {
    if (a2[i2] !== b[i2] && !comparator?.(a2[i2], b[i2])) {
      return false;
    }
  }
  return true;
}
function _forAll(array2, callback) {
  if (!array2) {
    return;
  }
  for (const value2 of array2) {
    callback(value2);
  }
}
function _removeFromArray(array2, object2) {
  const index = array2.indexOf(object2);
  if (index >= 0) {
    array2.splice(index, 1);
  }
}
function _moveInArray(array2, objectsToMove, toIndex) {
  for (let i2 = 0; i2 < objectsToMove.length; i2++) {
    _removeFromArray(array2, objectsToMove[i2]);
  }
  for (let i2 = objectsToMove.length - 1; i2 >= 0; i2--) {
    array2.splice(toIndex, 0, objectsToMove[i2]);
  }
}
var GROUP_AUTO_COLUMN_ID = "ag-Grid-AutoColumn";
var SELECTION_COLUMN_ID = "ag-Grid-SelectionColumn";
var ROW_NUMBERS_COLUMN_ID = "ag-Grid-RowNumbersColumn";
function _getColumnsFromTree(rootColumns) {
  const result2 = [];
  const recursiveFindColumns = (childColumns) => {
    for (let i2 = 0; i2 < childColumns.length; i2++) {
      const child = childColumns[i2];
      if (isColumn(child)) {
        result2.push(child);
      } else if (isProvidedColumnGroup(child)) {
        recursiveFindColumns(child.getChildren());
      }
    }
  };
  recursiveFindColumns(rootColumns);
  return result2;
}
function getWidthOfColsInList(columnList) {
  return columnList.reduce((width, col) => width + col.getActualWidth(), 0);
}
function _destroyColumnTree(beans, oldTree, newTree) {
  const oldObjectsById = {};
  if (!oldTree) {
    return;
  }
  depthFirstOriginalTreeSearch(null, oldTree, (child) => {
    oldObjectsById[child.getInstanceId()] = child;
  });
  if (newTree) {
    depthFirstOriginalTreeSearch(null, newTree, (child) => {
      oldObjectsById[child.getInstanceId()] = null;
    });
  }
  const colsToDestroy = Object.values(oldObjectsById).filter((item2) => item2 != null);
  beans.context.destroyBeans(colsToDestroy);
}
function isColumnGroupAutoCol(col) {
  const colId = col.getId();
  return colId.startsWith(GROUP_AUTO_COLUMN_ID);
}
function isColumnSelectionCol(col) {
  const id2 = typeof col === "string" ? col : "getColId" in col ? col.getColId() : col.colId;
  return id2?.startsWith(SELECTION_COLUMN_ID) ?? false;
}
function isRowNumberCol(col) {
  const id2 = typeof col === "string" ? col : "getColId" in col ? col.getColId() : col.colId;
  return id2?.startsWith(ROW_NUMBERS_COLUMN_ID) ?? false;
}
function isSpecialCol(col) {
  return isColumnSelectionCol(col) || isRowNumberCol(col);
}
function convertColumnTypes(type) {
  let typeKeys = [];
  if (type instanceof Array) {
    typeKeys = type;
  } else if (typeof type === "string") {
    typeKeys = type.split(",");
  }
  return typeKeys;
}
function _areColIdsEqual(colsA, colsB) {
  return _areEqual(colsA, colsB, (a2, b) => a2.getColId() === b.getColId());
}
function _updateColsMap(cols) {
  cols.map = {};
  for (const col of cols.list) {
    cols.map[col.getId()] = col;
  }
}
function _convertColumnEventSourceType(source2) {
  return source2 === "optionsUpdated" ? "gridOptionsChanged" : source2;
}
function _columnsMatch(column2, key2) {
  const columnMatches = column2 === key2;
  const colDefMatches = column2.getColDef() === key2;
  const idMatches = column2.getColId() == key2;
  return columnMatches || colDefMatches || idMatches;
}
var getValueFactory = (stateItem, defaultState) => (key1, key2) => {
  const obj = {
    value1: void 0,
    value2: void 0
  };
  let calculated = false;
  if (stateItem) {
    if (stateItem[key1] !== void 0) {
      obj.value1 = stateItem[key1];
      calculated = true;
    }
    if (_exists(key2) && stateItem[key2] !== void 0) {
      obj.value2 = stateItem[key2];
      calculated = true;
    }
  }
  if (!calculated && defaultState) {
    if (defaultState[key1] !== void 0) {
      obj.value1 = defaultState[key1];
    }
    if (_exists(key2) && defaultState[key2] !== void 0) {
      obj.value2 = defaultState[key2];
    }
  }
  return obj;
};
var depthFirstCallback = (child, parent) => {
  if (isProvidedColumnGroup(child)) {
    child.setupExpandable();
  }
  child.originalParent = parent;
};
function _createColumnTree(beans, defs = null, primaryColumns, existingTree, source2) {
  const columnKeyCreator = new ColumnKeyCreator();
  const { existingCols, existingGroups, existingColKeys } = extractExistingTreeData(existingTree);
  columnKeyCreator.addExistingKeys(existingColKeys);
  const unbalancedTree = _recursivelyCreateColumns(
    beans,
    defs,
    0,
    primaryColumns,
    existingCols,
    columnKeyCreator,
    existingGroups,
    source2
  );
  const { colGroupSvc } = beans;
  const treeDepth = colGroupSvc?.findMaxDepth(unbalancedTree, 0) ?? 0;
  const columnTree = colGroupSvc ? colGroupSvc.balanceColumnTree(unbalancedTree, 0, treeDepth, columnKeyCreator) : unbalancedTree;
  depthFirstOriginalTreeSearch(null, columnTree, depthFirstCallback);
  return {
    columnTree,
    treeDepth
  };
}
function extractExistingTreeData(existingTree) {
  const existingCols = [];
  const existingGroups = [];
  const existingColKeys = [];
  if (existingTree) {
    depthFirstOriginalTreeSearch(null, existingTree, (item2) => {
      if (isProvidedColumnGroup(item2)) {
        const group = item2;
        existingGroups.push(group);
      } else {
        const col = item2;
        existingColKeys.push(col.getId());
        existingCols.push(col);
      }
    });
  }
  return { existingCols, existingGroups, existingColKeys };
}
function _recursivelyCreateColumns(beans, defs, level, primaryColumns, existingColsCopy, columnKeyCreator, existingGroups, source2) {
  if (!defs) {
    return [];
  }
  const { colGroupSvc } = beans;
  const result2 = new Array(defs.length);
  for (let i2 = 0; i2 < result2.length; i2++) {
    const def = defs[i2];
    if (colGroupSvc && isColumnGroupDef(def)) {
      result2[i2] = colGroupSvc.createProvidedColumnGroup(
        primaryColumns,
        def,
        level,
        existingColsCopy,
        columnKeyCreator,
        existingGroups,
        source2
      );
    } else {
      result2[i2] = createColumn(beans, primaryColumns, def, existingColsCopy, columnKeyCreator, source2);
    }
  }
  return result2;
}
function createColumn(beans, primaryColumns, colDef, existingColsCopy, columnKeyCreator, source2) {
  const existingColAndIndex = findExistingColumn(colDef, existingColsCopy);
  if (existingColAndIndex) {
    existingColsCopy?.splice(existingColAndIndex.idx, 1);
  }
  let column2 = existingColAndIndex?.column;
  if (!column2) {
    const colId = columnKeyCreator.getUniqueKey(colDef.colId, colDef.field);
    const colDefMerged = _addColumnDefaultAndTypes(beans, colDef, colId);
    column2 = new AgColumn(colDefMerged, colDef, colId, primaryColumns);
    beans.context.createBean(column2);
  } else {
    const colDefMerged = _addColumnDefaultAndTypes(beans, colDef, column2.getColId());
    column2.setColDef(colDefMerged, colDef, source2);
    _updateColumnState(beans, column2, colDefMerged, source2);
  }
  beans.dataTypeSvc?.addColumnListeners(column2);
  return column2;
}
function updateSomeColumnState(beans, column2, hide2, sort, sortIndex, pinned, flex2, source2) {
  const { sortSvc, pinnedCols, colFlex } = beans;
  if (hide2 !== void 0) {
    column2.setVisible(!hide2, source2);
  }
  if (sortSvc) {
    sortSvc.updateColSort(column2, sort, source2);
    if (sortIndex !== void 0) {
      sortSvc.setColSortIndex(column2, sortIndex);
    }
  }
  if (pinned !== void 0) {
    pinnedCols?.setColPinned(column2, pinned);
  }
  if (flex2 !== void 0) {
    colFlex?.setColFlex(column2, flex2);
  }
}
function _updateColumnState(beans, column2, colDef, source2) {
  updateSomeColumnState(
    beans,
    column2,
    colDef.hide,
    colDef.sort,
    colDef.sortIndex,
    colDef.pinned,
    colDef.flex,
    source2
  );
  const colFlex = column2.getFlex();
  if (colFlex != null && colFlex > 0) {
    return;
  }
  if (colDef.width != null) {
    column2.setActualWidth(colDef.width, source2);
  } else {
    const widthBeforeUpdate = column2.getActualWidth();
    column2.setActualWidth(widthBeforeUpdate, source2);
  }
}
function findExistingColumn(newColDef, existingColsCopy) {
  if (!existingColsCopy) {
    return void 0;
  }
  for (let i2 = 0; i2 < existingColsCopy.length; i2++) {
    const def = existingColsCopy[i2].getUserProvidedColDef();
    if (!def) {
      continue;
    }
    const newHasId = newColDef.colId != null;
    if (newHasId) {
      if (existingColsCopy[i2].getId() === newColDef.colId) {
        return { idx: i2, column: existingColsCopy[i2] };
      }
      continue;
    }
    const newHasField = newColDef.field != null;
    if (newHasField) {
      if (def.field === newColDef.field) {
        return { idx: i2, column: existingColsCopy[i2] };
      }
      continue;
    }
    if (def === newColDef) {
      return { idx: i2, column: existingColsCopy[i2] };
    }
  }
  return void 0;
}
function _addColumnDefaultAndTypes(beans, colDef, colId, isAutoCol) {
  const { gos, dataTypeSvc } = beans;
  const res = {};
  const defaultColDef = gos.get("defaultColDef");
  _mergeDeep(res, defaultColDef, false, true);
  const columnType = updateColDefAndGetColumnType(beans, res, colDef, colId);
  if (columnType) {
    assignColumnTypes(beans, columnType, res);
  }
  const cellDataType = res.cellDataType;
  _mergeDeep(res, colDef, false, true);
  if (cellDataType !== void 0) {
    res.cellDataType = cellDataType;
  }
  const autoGroupColDef = gos.get("autoGroupColumnDef");
  const isSortingCoupled = _isColumnsSortingCoupledToGroup(gos);
  if (colDef.rowGroup && autoGroupColDef && isSortingCoupled) {
    _mergeDeep(
      res,
      { sort: autoGroupColDef.sort, initialSort: autoGroupColDef.initialSort },
      false,
      true
    );
  }
  if (dataTypeSvc) {
    dataTypeSvc.postProcess(res);
    dataTypeSvc.validateColDef(res);
  }
  gos.validateColDef(res, colId, isAutoCol);
  return res;
}
function updateColDefAndGetColumnType(beans, colDef, userColDef, colId) {
  const dataTypeDefinitionColumnType = beans.dataTypeSvc?.updateColDefAndGetColumnType(colDef, userColDef, colId);
  const columnTypes = userColDef.type ?? dataTypeDefinitionColumnType ?? colDef.type;
  colDef.type = columnTypes;
  return columnTypes ? convertColumnTypes(columnTypes) : void 0;
}
function assignColumnTypes(beans, typeKeys, colDefMerged) {
  if (!typeKeys.length) {
    return;
  }
  const allColumnTypes = Object.assign({}, DefaultColumnTypes);
  const userTypes = beans.gos.get("columnTypes") || {};
  for (const key2 of Object.keys(userTypes)) {
    const value2 = userTypes[key2];
    if (key2 in allColumnTypes) {
      _warn(34, { key: key2 });
    } else {
      const colType = value2;
      if (colType.type) {
        _warn(35);
      }
      allColumnTypes[key2] = value2;
    }
  }
  for (const t2 of typeKeys) {
    const typeColDef = allColumnTypes[t2.trim()];
    if (typeColDef) {
      _mergeDeep(colDefMerged, typeColDef, false, true);
    } else {
      _warn(36, { t: t2 });
    }
  }
}
function isColumnGroupDef(abstractColDef) {
  return abstractColDef.children !== void 0;
}
function depthFirstOriginalTreeSearch(parent, tree, callback) {
  if (!tree) {
    return;
  }
  for (let i2 = 0; i2 < tree.length; i2++) {
    const child = tree[i2];
    if (isProvidedColumnGroup(child)) {
      depthFirstOriginalTreeSearch(child, child.getChildren(), callback);
    }
    callback(child, parent);
  }
}
function placeLockedColumns(cols, gos) {
  const left2 = [];
  const normal = [];
  const right2 = [];
  cols.forEach((col) => {
    const position = col.getColDef().lockPosition;
    if (position === "right") {
      right2.push(col);
    } else if (position === "left" || position === true) {
      left2.push(col);
    } else {
      normal.push(col);
    }
  });
  const isRtl = gos.get("enableRtl");
  if (isRtl) {
    return [...right2, ...normal, ...left2];
  }
  return [...left2, ...normal, ...right2];
}
function doesMovePassMarryChildren(allColumnsCopy, gridBalancedTree) {
  let rulePassed = true;
  depthFirstOriginalTreeSearch(null, gridBalancedTree, (child) => {
    if (!isProvidedColumnGroup(child)) {
      return;
    }
    const columnGroup = child;
    const colGroupDef = columnGroup.getColGroupDef();
    const marryChildren = colGroupDef?.marryChildren;
    if (!marryChildren) {
      return;
    }
    const newIndexes = [];
    for (const col of columnGroup.getLeafColumns()) {
      const newColIndex = allColumnsCopy.indexOf(col);
      newIndexes.push(newColIndex);
    }
    const maxIndex = Math.max.apply(Math, newIndexes);
    const minIndex = Math.min.apply(Math, newIndexes);
    const spread2 = maxIndex - minIndex;
    const maxSpread = columnGroup.getLeafColumns().length - 1;
    if (spread2 > maxSpread) {
      rulePassed = false;
    }
  });
  return rulePassed;
}
function getCommonValue(cols, valueGetter) {
  if (!cols || cols.length == 0) {
    return void 0;
  }
  const firstValue = valueGetter(cols[0]);
  for (let i2 = 1; i2 < cols.length; i2++) {
    if (firstValue !== valueGetter(cols[i2])) {
      return void 0;
    }
  }
  return firstValue;
}
function dispatchColumnPinnedEvent(eventSvc, changedColumns, source2) {
  if (!changedColumns.length) {
    return;
  }
  const column2 = changedColumns.length === 1 ? changedColumns[0] : null;
  const pinned = getCommonValue(changedColumns, (col) => col.getPinned());
  eventSvc.dispatchEvent({
    type: "columnPinned",
    // mistake in typing, 'undefined' should be allowed, as 'null' means 'not pinned'
    pinned: pinned != null ? pinned : null,
    columns: changedColumns,
    column: column2,
    source: source2
  });
}
function dispatchColumnVisibleEvent(eventSvc, changedColumns, source2) {
  if (!changedColumns.length) {
    return;
  }
  const column2 = changedColumns.length === 1 ? changedColumns[0] : null;
  const visible2 = getCommonValue(changedColumns, (col) => col.isVisible());
  eventSvc.dispatchEvent({
    type: "columnVisible",
    visible: visible2,
    columns: changedColumns,
    column: column2,
    source: source2
  });
}
function dispatchColumnChangedEvent(eventSvc, type, columns2, source2) {
  eventSvc.dispatchEvent({
    type,
    columns: columns2,
    column: columns2 && columns2.length == 1 ? columns2[0] : null,
    source: source2
  });
}
function dispatchColumnResizedEvent(eventSvc, columns2, finished, source2, flexColumns = null) {
  if (columns2?.length) {
    eventSvc.dispatchEvent({
      type: "columnResized",
      columns: columns2,
      column: columns2.length === 1 ? columns2[0] : null,
      flexColumns,
      finished,
      source: source2
    });
  }
}
function _applyColumnState(beans, params, source2) {
  const {
    colModel,
    rowGroupColsSvc,
    pivotColsSvc,
    autoColSvc,
    selectionColSvc,
    colAnimation,
    visibleCols,
    pivotResultCols,
    environment,
    valueColsSvc,
    eventSvc,
    gos
  } = beans;
  const providedCols = colModel.getColDefCols() ?? [];
  const selectionCols = selectionColSvc?.getColumns();
  if (!providedCols.length && !selectionCols?.length) {
    return false;
  }
  if (params?.state && !params.state.forEach) {
    _warn(32);
    return false;
  }
  const syncColumnWithStateItem = (column2, stateItem, rowGroupIndexes, pivotIndexes, autoCol) => {
    if (!column2) {
      return;
    }
    const getValue = getValueFactory(stateItem, params.defaultState);
    const flex2 = getValue("flex").value1;
    updateSomeColumnState(
      beans,
      column2,
      getValue("hide").value1,
      getValue("sort").value1,
      getValue("sortIndex").value1,
      getValue("pinned").value1,
      flex2,
      source2
    );
    if (flex2 == null) {
      const width = getValue("width").value1;
      if (width != null) {
        const minColWidth = column2.getColDef().minWidth ?? environment.getDefaultColumnMinWidth();
        if (minColWidth != null && width >= minColWidth) {
          column2.setActualWidth(width, source2);
        }
      }
    }
    if (autoCol || !column2.isPrimary()) {
      return;
    }
    valueColsSvc?.syncColumnWithState(column2, source2, getValue);
    rowGroupColsSvc?.syncColumnWithState(column2, source2, getValue, rowGroupIndexes);
    pivotColsSvc?.syncColumnWithState(column2, source2, getValue, pivotIndexes);
  };
  const applyStates = (states, existingColumns, getById2) => {
    const dispatchEventsFunc = _compareColumnStatesAndDispatchEvents(beans, source2);
    const columnsWithNoState = existingColumns.slice();
    const rowGroupIndexes = {};
    const pivotIndexes = {};
    const autoColStates = [];
    const selectionColStates = [];
    const unmatchedAndAutoStates2 = [];
    let unmatchedCount2 = 0;
    const previousRowGroupCols = rowGroupColsSvc?.columns.slice() ?? [];
    const previousPivotCols = pivotColsSvc?.columns.slice() ?? [];
    for (const state of states) {
      const colId = state.colId;
      const isAutoGroupColumn = colId.startsWith(GROUP_AUTO_COLUMN_ID);
      if (isAutoGroupColumn) {
        autoColStates.push(state);
        unmatchedAndAutoStates2.push(state);
        continue;
      }
      if (isColumnSelectionCol(colId)) {
        selectionColStates.push(state);
        unmatchedAndAutoStates2.push(state);
        continue;
      }
      const column2 = getById2(colId);
      if (!column2) {
        unmatchedAndAutoStates2.push(state);
        unmatchedCount2 += 1;
      } else {
        syncColumnWithStateItem(column2, state, rowGroupIndexes, pivotIndexes, false);
        _removeFromArray(columnsWithNoState, column2);
      }
    }
    const applyDefaultsFunc = (col) => syncColumnWithStateItem(col, null, rowGroupIndexes, pivotIndexes, false);
    columnsWithNoState.forEach(applyDefaultsFunc);
    rowGroupColsSvc?.sortColumns(comparatorByIndex.bind(rowGroupColsSvc, rowGroupIndexes, previousRowGroupCols));
    pivotColsSvc?.sortColumns(comparatorByIndex.bind(pivotColsSvc, pivotIndexes, previousPivotCols));
    colModel.refreshCols(false, source2);
    const syncColStates = (getCol, colStates, columns2 = []) => {
      for (const stateItem of colStates) {
        const col = getCol(stateItem.colId);
        _removeFromArray(columns2, col);
        syncColumnWithStateItem(col, stateItem, null, null, true);
      }
      columns2.forEach(applyDefaultsFunc);
    };
    syncColStates(
      (colId) => autoColSvc?.getColumn(colId) ?? null,
      autoColStates,
      autoColSvc?.getColumns()?.slice()
    );
    syncColStates(
      (colId) => selectionColSvc?.getColumn(colId) ?? null,
      selectionColStates,
      selectionColSvc?.getColumns()?.slice()
    );
    orderLiveColsLikeState(params, colModel, gos);
    visibleCols.refresh(source2);
    eventSvc.dispatchEvent({
      type: "columnEverythingChanged",
      source: source2
    });
    dispatchEventsFunc();
    return { unmatchedAndAutoStates: unmatchedAndAutoStates2, unmatchedCount: unmatchedCount2 };
  };
  colAnimation?.start();
  let { unmatchedAndAutoStates, unmatchedCount } = applyStates(
    params.state || [],
    providedCols,
    (id2) => colModel.getColDefCol(id2)
  );
  if (unmatchedAndAutoStates.length > 0 || _exists(params.defaultState)) {
    const pivotResultColsList = pivotResultCols?.getPivotResultCols()?.list ?? [];
    unmatchedCount = applyStates(
      unmatchedAndAutoStates,
      pivotResultColsList,
      (id2) => pivotResultCols?.getPivotResultCol(id2) ?? null
    ).unmatchedCount;
  }
  colAnimation?.finish();
  return unmatchedCount === 0;
}
function _resetColumnState(beans, source2) {
  const { colModel, autoColSvc, selectionColSvc, eventSvc, gos } = beans;
  const primaryCols = colModel.getColDefCols();
  if (!primaryCols?.length) {
    return;
  }
  const primaryColumnTree = colModel.getColDefColTree();
  const primaryColumns = _getColumnsFromTree(primaryColumnTree);
  const columnStates = [];
  let letRowGroupIndex = 1e3;
  let letPivotIndex = 1e3;
  const addColState = (col) => {
    const stateItem = getColumnStateFromColDef(col);
    if (_missing(stateItem.rowGroupIndex) && stateItem.rowGroup) {
      stateItem.rowGroupIndex = letRowGroupIndex++;
    }
    if (_missing(stateItem.pivotIndex) && stateItem.pivot) {
      stateItem.pivotIndex = letPivotIndex++;
    }
    columnStates.push(stateItem);
  };
  autoColSvc?.getColumns()?.forEach(addColState);
  selectionColSvc?.getColumns()?.forEach(addColState);
  primaryColumns?.forEach(addColState);
  _applyColumnState(beans, { state: columnStates }, source2);
  const autoCols = autoColSvc?.getColumns() ?? [];
  const selectionCols = selectionColSvc?.getColumns() ?? [];
  const orderedCols = [...selectionCols, ...autoCols, ...primaryCols];
  const orderedColState = orderedCols.map((col) => ({ colId: col.colId }));
  _applyColumnState(beans, { state: orderedColState, applyOrder: true }, source2);
  eventSvc.dispatchEvent(_addGridCommonParams(gos, { type: "columnsReset", source: source2 }));
}
function _compareColumnStatesAndDispatchEvents(beans, source2) {
  const { rowGroupColsSvc, pivotColsSvc, valueColsSvc, colModel, sortSvc, eventSvc } = beans;
  const startState = {
    rowGroupColumns: rowGroupColsSvc?.columns.slice() ?? [],
    pivotColumns: pivotColsSvc?.columns.slice() ?? [],
    valueColumns: valueColsSvc?.columns.slice() ?? []
  };
  const columnStateBefore = _getColumnState(beans);
  const columnStateBeforeMap = {};
  for (const col of columnStateBefore) {
    columnStateBeforeMap[col.colId] = col;
  }
  return () => {
    const dispatchWhenListsDifferent = (eventType, colsBefore, colsAfter, idMapper) => {
      const beforeList = colsBefore.map(idMapper);
      const afterList = colsAfter.map(idMapper);
      const unchanged2 = _areEqual(beforeList, afterList);
      if (unchanged2) {
        return;
      }
      const changes = new Set(colsBefore);
      for (const id2 of colsAfter) {
        if (!changes.delete(id2)) {
          changes.add(id2);
        }
      }
      const changesArr = [...changes];
      eventSvc.dispatchEvent({
        type: eventType,
        columns: changesArr,
        column: changesArr.length === 1 ? changesArr[0] : null,
        source: source2
      });
    };
    const getChangedColumns = (changedPredicate) => {
      const changedColumns2 = [];
      colModel.forAllCols((column2) => {
        const colStateBefore = columnStateBeforeMap[column2.getColId()];
        if (colStateBefore && changedPredicate(colStateBefore, column2)) {
          changedColumns2.push(column2);
        }
      });
      return changedColumns2;
    };
    const columnIdMapper = (c2) => c2.getColId();
    dispatchWhenListsDifferent(
      "columnRowGroupChanged",
      startState.rowGroupColumns,
      rowGroupColsSvc?.columns ?? [],
      columnIdMapper
    );
    dispatchWhenListsDifferent(
      "columnPivotChanged",
      startState.pivotColumns,
      pivotColsSvc?.columns ?? [],
      columnIdMapper
    );
    const valueChangePredicate = (cs, c2) => {
      const oldActive = cs.aggFunc != null;
      const activeChanged = oldActive != c2.isValueActive();
      const aggFuncChanged = oldActive && cs.aggFunc != c2.getAggFunc();
      return activeChanged || aggFuncChanged;
    };
    const changedValues = getChangedColumns(valueChangePredicate);
    if (changedValues.length > 0) {
      dispatchColumnChangedEvent(eventSvc, "columnValueChanged", changedValues, source2);
    }
    const resizeChangePredicate = (cs, c2) => cs.width != c2.getActualWidth();
    dispatchColumnResizedEvent(eventSvc, getChangedColumns(resizeChangePredicate), true, source2);
    const pinnedChangePredicate = (cs, c2) => cs.pinned != c2.getPinned();
    dispatchColumnPinnedEvent(eventSvc, getChangedColumns(pinnedChangePredicate), source2);
    const visibilityChangePredicate = (cs, c2) => cs.hide == c2.isVisible();
    dispatchColumnVisibleEvent(eventSvc, getChangedColumns(visibilityChangePredicate), source2);
    const sortChangePredicate = (cs, c2) => cs.sort != c2.getSort() || cs.sortIndex != c2.getSortIndex();
    const changedColumns = getChangedColumns(sortChangePredicate);
    if (changedColumns.length > 0) {
      sortSvc?.dispatchSortChangedEvents(source2, changedColumns);
    }
    const colStateAfter = _getColumnState(beans);
    normaliseColumnMovedEventForColumnState(columnStateBefore, colStateAfter, source2, colModel, eventSvc);
  };
}
function _getColumnState(beans) {
  const { colModel, rowGroupColsSvc, pivotColsSvc } = beans;
  const primaryCols = colModel.getColDefCols();
  if (_missing(primaryCols) || !colModel.isAlive()) {
    return [];
  }
  const rowGroupColumns = rowGroupColsSvc?.columns;
  const pivotColumns = pivotColsSvc?.columns;
  const res = [];
  const createStateItemFromColumn = (column2) => {
    const rowGroupIndex = column2.isRowGroupActive() && rowGroupColumns ? rowGroupColumns.indexOf(column2) : null;
    const pivotIndex = column2.isPivotActive() && pivotColumns ? pivotColumns.indexOf(column2) : null;
    const aggFunc = column2.isValueActive() ? column2.getAggFunc() : null;
    const sort = column2.getSort() != null ? column2.getSort() : null;
    const sortIndex = column2.getSortIndex() != null ? column2.getSortIndex() : null;
    res.push({
      colId: column2.getColId(),
      width: column2.getActualWidth(),
      hide: !column2.isVisible(),
      pinned: column2.getPinned(),
      sort,
      sortIndex,
      aggFunc,
      rowGroup: column2.isRowGroupActive(),
      rowGroupIndex,
      pivot: column2.isPivotActive(),
      pivotIndex,
      flex: column2.getFlex() ?? null
    });
  };
  colModel.forAllCols((col) => createStateItemFromColumn(col));
  const colIdToGridIndexMap = new Map(
    colModel.getCols().map((col, index) => [col.getColId(), index])
  );
  res.sort((itemA, itemB) => {
    const posA = colIdToGridIndexMap.has(itemA.colId) ? colIdToGridIndexMap.get(itemA.colId) : -1;
    const posB = colIdToGridIndexMap.has(itemB.colId) ? colIdToGridIndexMap.get(itemB.colId) : -1;
    return posA - posB;
  });
  return res;
}
function getColumnStateFromColDef(column2) {
  const getValueOrNull = (a2, b) => a2 != null ? a2 : b != null ? b : null;
  const colDef = column2.getColDef();
  const sort = getValueOrNull(colDef.sort, colDef.initialSort);
  const sortIndex = getValueOrNull(colDef.sortIndex, colDef.initialSortIndex);
  const hide2 = getValueOrNull(colDef.hide, colDef.initialHide);
  const pinned = getValueOrNull(colDef.pinned, colDef.initialPinned);
  const width = getValueOrNull(colDef.width, colDef.initialWidth);
  const flex2 = getValueOrNull(colDef.flex, colDef.initialFlex);
  let rowGroupIndex = getValueOrNull(colDef.rowGroupIndex, colDef.initialRowGroupIndex);
  let rowGroup = getValueOrNull(colDef.rowGroup, colDef.initialRowGroup);
  if (rowGroupIndex == null && !rowGroup) {
    rowGroupIndex = null;
    rowGroup = null;
  }
  let pivotIndex = getValueOrNull(colDef.pivotIndex, colDef.initialPivotIndex);
  let pivot2 = getValueOrNull(colDef.pivot, colDef.initialPivot);
  if (pivotIndex == null && !pivot2) {
    pivotIndex = null;
    pivot2 = null;
  }
  const aggFunc = getValueOrNull(colDef.aggFunc, colDef.initialAggFunc);
  return {
    colId: column2.getColId(),
    sort,
    sortIndex,
    hide: hide2,
    pinned,
    width,
    flex: flex2,
    rowGroup,
    rowGroupIndex,
    pivot: pivot2,
    pivotIndex,
    aggFunc
  };
}
function orderLiveColsLikeState(params, colModel, gos) {
  if (!params.applyOrder || !params.state) {
    return;
  }
  const colIds = [];
  for (const item2 of params.state) {
    if (item2.colId != null) {
      colIds.push(item2.colId);
    }
  }
  sortColsLikeKeys(colModel.cols, colIds, colModel, gos);
}
function sortColsLikeKeys(cols, colIds, colModel, gos) {
  if (cols == null) {
    return;
  }
  let newOrder = [];
  const processedColIds = {};
  for (const colId of colIds) {
    if (processedColIds[colId]) {
      continue;
    }
    const col = cols.map[colId];
    if (col) {
      newOrder.push(col);
      processedColIds[colId] = true;
    }
  }
  let autoGroupInsertIndex = 0;
  for (const col of cols.list) {
    const colId = col.getColId();
    const alreadyProcessed = processedColIds[colId] != null;
    if (alreadyProcessed) {
      continue;
    }
    const isAutoGroupCol = colId.startsWith(GROUP_AUTO_COLUMN_ID);
    if (isAutoGroupCol) {
      newOrder.splice(autoGroupInsertIndex++, 0, col);
    } else {
      newOrder.push(col);
    }
  }
  newOrder = placeLockedColumns(newOrder, gos);
  if (!doesMovePassMarryChildren(newOrder, colModel.getColTree())) {
    _warn(39);
    return;
  }
  cols.list = newOrder;
}
function normaliseColumnMovedEventForColumnState(colStateBefore, colStateAfter, source2, colModel, eventSvc) {
  const colStateAfterMapped = {};
  for (const s of colStateAfter) {
    colStateAfterMapped[s.colId] = s;
  }
  const colsIntersectIds = {};
  for (const s of colStateBefore) {
    if (colStateAfterMapped[s.colId]) {
      colsIntersectIds[s.colId] = true;
    }
  }
  const beforeFiltered = colStateBefore.filter((c2) => colsIntersectIds[c2.colId]);
  const afterFiltered = colStateAfter.filter((c2) => colsIntersectIds[c2.colId]);
  const movedColumns = [];
  afterFiltered.forEach((csAfter, index) => {
    const csBefore = beforeFiltered?.[index];
    if (csBefore && csBefore.colId !== csAfter.colId) {
      const gridCol = colModel.getCol(csBefore.colId);
      if (gridCol) {
        movedColumns.push(gridCol);
      }
    }
  });
  if (!movedColumns.length) {
    return;
  }
  eventSvc.dispatchEvent({
    type: "columnMoved",
    columns: movedColumns,
    column: movedColumns.length === 1 ? movedColumns[0] : null,
    finished: true,
    source: source2
  });
}
var comparatorByIndex = (indexes, oldList, colA, colB) => {
  const indexA = indexes[colA.getId()];
  const indexB = indexes[colB.getId()];
  const aHasIndex = indexA != null;
  const bHasIndex = indexB != null;
  if (aHasIndex && bHasIndex) {
    return indexA - indexB;
  }
  if (aHasIndex) {
    return -1;
  }
  if (bHasIndex) {
    return 1;
  }
  const oldIndexA = oldList.indexOf(colA);
  const oldIndexB = oldList.indexOf(colB);
  const aHasOldIndex = oldIndexA >= 0;
  const bHasOldIndex = oldIndexB >= 0;
  if (aHasOldIndex && bHasOldIndex) {
    return oldIndexA - oldIndexB;
  }
  if (aHasOldIndex) {
    return -1;
  }
  return 1;
};
var ColumnModel = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "colModel";
    this.pivotMode = false;
    this.ready = false;
    this.changeEventsDispatching = false;
  }
  postConstruct() {
    this.pivotMode = this.gos.get("pivotMode");
    this.addManagedPropertyListeners(
      [
        "groupDisplayType",
        "treeData",
        "treeDataDisplayType",
        "groupHideOpenParents",
        "rowNumbers",
        "hidePaddedHeaderRows"
      ],
      (event) => this.refreshAll(_convertColumnEventSourceType(event.source))
    );
    this.addManagedPropertyListeners(
      ["defaultColDef", "defaultColGroupDef", "columnTypes", "suppressFieldDotNotation"],
      this.recreateColumnDefs.bind(this)
    );
    this.addManagedPropertyListener(
      "pivotMode",
      (event) => this.setPivotMode(this.gos.get("pivotMode"), _convertColumnEventSourceType(event.source))
    );
  }
  // called from SyncService, when grid has finished initialising
  createColsFromColDefs(source2) {
    const { beans } = this;
    const {
      valueCache,
      colAutosize,
      rowGroupColsSvc,
      pivotColsSvc,
      valueColsSvc,
      visibleCols,
      eventSvc,
      groupHierarchyColSvc
    } = beans;
    const dispatchEventsFunc = this.colDefs ? _compareColumnStatesAndDispatchEvents(beans, source2) : void 0;
    valueCache?.expire();
    const oldCols = this.colDefCols?.list;
    const oldTree = this.colDefCols?.tree;
    const newTree = _createColumnTree(beans, this.colDefs, true, oldTree, source2);
    _destroyColumnTree(beans, this.colDefCols?.tree, newTree.columnTree);
    const tree = newTree.columnTree;
    const treeDepth = newTree.treeDepth;
    const list2 = _getColumnsFromTree(tree);
    const map2 = {};
    for (const col of list2) {
      map2[col.getId()] = col;
    }
    this.colDefCols = { tree, treeDepth, list: list2, map: map2 };
    this.createColumnsForService([groupHierarchyColSvc], this.colDefCols, source2);
    rowGroupColsSvc?.extractCols(source2, oldCols);
    pivotColsSvc?.extractCols(source2, oldCols);
    valueColsSvc?.extractCols(source2, oldCols);
    this.ready = true;
    this.refreshCols(true, source2);
    visibleCols.refresh(source2);
    eventSvc.dispatchEvent({
      type: "columnEverythingChanged",
      source: source2
    });
    if (dispatchEventsFunc) {
      this.changeEventsDispatching = true;
      dispatchEventsFunc();
      this.changeEventsDispatching = false;
    }
    eventSvc.dispatchEvent({
      type: "newColumnsLoaded",
      source: source2
    });
    if (source2 === "gridInitializing") {
      colAutosize?.applyAutosizeStrategy();
    }
  }
  // called from: buildAutoGroupColumns (events 'groupDisplayType', 'treeData', 'treeDataDisplayType', 'groupHideOpenParents')
  // createColsFromColDefs (recreateColumnDefs, setColumnsDefs),
  // setPivotMode, applyColumnState,
  // functionColsService.setPrimaryColList, functionColsService.updatePrimaryColList,
  // pivotResultCols.setPivotResultCols
  refreshCols(newColDefs, source2) {
    if (!this.colDefCols) {
      return;
    }
    const prevColTree = this.cols?.tree;
    this.saveColOrder();
    const {
      autoColSvc,
      selectionColSvc,
      rowNumbersSvc,
      quickFilter,
      pivotResultCols,
      showRowGroupCols,
      rowAutoHeight,
      visibleCols,
      colViewport,
      eventSvc
    } = this.beans;
    const cols = this.selectCols(pivotResultCols, this.colDefCols);
    this.createColumnsForService([autoColSvc, selectionColSvc, rowNumbersSvc], cols, source2);
    const shouldSortNewColDefs = _shouldMaintainColumnOrder(this.gos, this.showingPivotResult);
    if (!newColDefs || shouldSortNewColDefs) {
      this.restoreColOrder(cols);
    }
    this.positionLockedCols(cols);
    showRowGroupCols?.refresh();
    quickFilter?.refreshCols();
    this.setColSpanActive();
    rowAutoHeight?.setAutoHeightActive(cols);
    visibleCols.clear();
    colViewport.clear();
    const dispatchChangedEvent = !_areEqual(prevColTree, this.cols.tree);
    if (dispatchChangedEvent) {
      eventSvc.dispatchEvent({
        type: "gridColumnsChanged"
      });
    }
  }
  createColumnsForService(services, cols, source2) {
    for (const service of services) {
      if (!service) {
        continue;
      }
      service.createColumns(
        cols,
        (updateOrder) => {
          this.lastOrder = updateOrder(this.lastOrder);
          this.lastPivotOrder = updateOrder(this.lastPivotOrder);
        },
        source2
      );
      service.addColumns(cols);
    }
  }
  selectCols(pivotResultColsSvc, colDefCols) {
    const pivotResultCols = pivotResultColsSvc?.getPivotResultCols() ?? null;
    this.showingPivotResult = pivotResultCols != null;
    const { map: map2, list: list2, tree, treeDepth } = pivotResultCols ?? colDefCols;
    this.cols = {
      list: list2.slice(),
      map: { ...map2 },
      tree: tree.slice(),
      treeDepth
    };
    if (pivotResultCols) {
      const hasSameColumns = pivotResultCols.list.some((col) => this.cols?.map[col.getColId()] !== void 0);
      if (!hasSameColumns) {
        this.lastPivotOrder = null;
      }
    }
    return this.cols;
  }
  getColsToShow() {
    if (!this.cols) {
      return [];
    }
    const { valueColsSvc, selectionColSvc, gos } = this.beans;
    const showAutoGroupAndValuesOnly = this.isPivotMode() && !this.showingPivotResult;
    const showSelectionColumn = selectionColSvc?.isSelectionColumnEnabled();
    const showRowNumbers = gos.get("rowNumbers");
    const valueColumns = valueColsSvc?.columns;
    const res = this.cols.list.filter((col) => {
      const isAutoGroupCol = isColumnGroupAutoCol(col);
      if (showAutoGroupAndValuesOnly) {
        const isValueCol = valueColumns?.includes(col);
        return isAutoGroupCol || isValueCol || showSelectionColumn && isColumnSelectionCol(col) || showRowNumbers && isRowNumberCol(col);
      } else {
        return isAutoGroupCol || col.isVisible();
      }
    });
    return res;
  }
  // on events 'groupDisplayType', 'treeData', 'treeDataDisplayType', 'groupHideOpenParents'
  refreshAll(source2) {
    if (!this.ready) {
      return;
    }
    this.refreshCols(false, source2);
    this.beans.visibleCols.refresh(source2);
  }
  setColsVisible(keys2, visible2 = false, source2) {
    _applyColumnState(
      this.beans,
      {
        state: keys2.map((key2) => ({
          colId: typeof key2 === "string" ? key2 : key2.getColId(),
          hide: !visible2
        }))
      },
      source2
    );
  }
  /**
   * Restores provided columns order to the previous order in this.lastPivotOrder / this.lastOrder
   * If columns are not in the last order:
   *  - Check column groups, and apply column after the last column in the lowest shared group
   *  - If no sibling is found, apply the column at the end of the cols
   */
  restoreColOrder(cols) {
    const lastOrder = this.showingPivotResult ? this.lastPivotOrder : this.lastOrder;
    if (!lastOrder) {
      return;
    }
    const preservedOrder = lastOrder.filter((col) => cols.map[col.getId()] != null);
    if (preservedOrder.length === 0) {
      return;
    }
    if (preservedOrder.length === cols.list.length) {
      cols.list = preservedOrder;
      return;
    }
    const hasSiblings = (col) => {
      const ancestor = col.getOriginalParent();
      if (!ancestor) {
        return false;
      }
      const children2 = ancestor.getChildren();
      if (children2.length > 1) {
        return true;
      }
      return hasSiblings(ancestor);
    };
    if (!preservedOrder.some((col) => hasSiblings(col))) {
      const preservedOrderSet = new Set(preservedOrder);
      for (const col of cols.list) {
        if (!preservedOrderSet.has(col)) {
          preservedOrder.push(col);
        }
      }
      cols.list = preservedOrder;
      return;
    }
    const colPositionMap = /* @__PURE__ */ new Map();
    for (let i2 = 0; i2 < preservedOrder.length; i2++) {
      const col = preservedOrder[i2];
      colPositionMap.set(col, i2);
    }
    const additionalCols = cols.list.filter((col) => !colPositionMap.has(col));
    if (additionalCols.length === 0) {
      cols.list = preservedOrder;
      return;
    }
    const getPreviousSibling = (col, group) => {
      const parent = group ? group.getOriginalParent() : col.getOriginalParent();
      if (!parent) {
        return null;
      }
      let highestIdx = null;
      let highestSibling = null;
      for (const child of parent.getChildren()) {
        if (child === group || child === col) {
          continue;
        }
        if (child instanceof AgColumn) {
          const colIdx = colPositionMap.get(child);
          if (colIdx == null) {
            continue;
          }
          if (highestIdx == null || highestIdx < colIdx) {
            highestIdx = colIdx;
            highestSibling = child;
          }
          continue;
        }
        child.forEachLeafColumn((leafCol) => {
          const colIdx = colPositionMap.get(leafCol);
          if (colIdx == null) {
            return;
          }
          if (highestIdx == null || highestIdx < colIdx) {
            highestIdx = colIdx;
            highestSibling = leafCol;
          }
        });
      }
      if (highestSibling == null) {
        return getPreviousSibling(col, parent);
      }
      return highestSibling;
    };
    const noSiblingsAvailable = [];
    const previousSiblingPosMap = /* @__PURE__ */ new Map();
    for (const col of additionalCols) {
      const prevSiblingIdx = getPreviousSibling(col, null);
      if (prevSiblingIdx == null) {
        noSiblingsAvailable.push(col);
        continue;
      }
      const prev = previousSiblingPosMap.get(prevSiblingIdx);
      if (prev === void 0) {
        previousSiblingPosMap.set(prevSiblingIdx, col);
      } else if (Array.isArray(prev)) {
        prev.push(col);
      } else {
        previousSiblingPosMap.set(prevSiblingIdx, [prev, col]);
      }
    }
    const result2 = new Array(cols.list.length);
    let resultPointer = result2.length - 1;
    for (let i2 = noSiblingsAvailable.length - 1; i2 >= 0; i2--) {
      result2[resultPointer--] = noSiblingsAvailable[i2];
    }
    for (let i2 = preservedOrder.length - 1; i2 >= 0; i2--) {
      const nextCol = preservedOrder[i2];
      const extraCols = previousSiblingPosMap.get(nextCol);
      if (extraCols) {
        if (Array.isArray(extraCols)) {
          for (let x = extraCols.length - 1; x >= 0; x--) {
            const col = extraCols[x];
            result2[resultPointer--] = col;
          }
        } else {
          result2[resultPointer--] = extraCols;
        }
      }
      result2[resultPointer--] = nextCol;
    }
    cols.list = result2;
  }
  positionLockedCols(cols) {
    cols.list = placeLockedColumns(cols.list, this.gos);
  }
  saveColOrder() {
    if (this.showingPivotResult) {
      this.lastPivotOrder = this.cols?.list ?? null;
    } else {
      this.lastOrder = this.cols?.list ?? null;
    }
  }
  getColumnDefs(sorted) {
    return this.colDefCols && this.beans.colDefFactory?.getColumnDefs(
      this.colDefCols.list,
      this.showingPivotResult,
      this.lastOrder,
      this.cols?.list ?? [],
      sorted
    );
  }
  setColSpanActive() {
    this.colSpanActive = !!this.cols?.list.some((col) => col.getColDef().colSpan != null);
  }
  isPivotMode() {
    return this.pivotMode;
  }
  setPivotMode(pivotMode, source2) {
    if (pivotMode === this.pivotMode) {
      return;
    }
    this.pivotMode = pivotMode;
    if (!this.ready) {
      return;
    }
    this.refreshCols(false, source2);
    const { visibleCols, eventSvc } = this.beans;
    visibleCols.refresh(source2);
    eventSvc.dispatchEvent({
      type: "columnPivotModeChanged"
    });
  }
  // + clientSideRowModel
  isPivotActive() {
    const pivotColumns = this.beans.pivotColsSvc?.columns;
    return this.pivotMode && !!pivotColumns?.length;
  }
  // called when dataTypes change
  recreateColumnDefs(e) {
    if (!this.cols) {
      return;
    }
    this.beans.autoColSvc?.updateColumns(e);
    const source2 = _convertColumnEventSourceType(e.source);
    this.createColsFromColDefs(source2);
  }
  setColumnDefs(columnDefs, source2) {
    this.colDefs = columnDefs;
    this.createColsFromColDefs(source2);
  }
  destroy() {
    _destroyColumnTree(this.beans, this.colDefCols?.tree);
    super.destroy();
  }
  getColTree() {
    return this.cols?.tree ?? [];
  }
  // + columnSelectPanel
  getColDefColTree() {
    return this.colDefCols?.tree ?? [];
  }
  // + clientSideRowController -> sorting, building quick filter text
  // + headerRenderer -> sorting (clearing icon)
  getColDefCols() {
    return this.colDefCols?.list ?? null;
  }
  // + moveColumnController
  getCols() {
    return this.cols?.list ?? [];
  }
  forAllCols(callback) {
    const { pivotResultCols, autoColSvc, selectionColSvc, groupHierarchyColSvc } = this.beans;
    _forAll(this.colDefCols?.list, callback);
    _forAll(autoColSvc?.columns?.list, callback);
    _forAll(selectionColSvc?.columns?.list, callback);
    _forAll(groupHierarchyColSvc?.columns?.list, callback);
    _forAll(pivotResultCols?.getPivotResultCols()?.list, callback);
  }
  getColsForKeys(keys2) {
    if (!keys2) {
      return [];
    }
    return keys2.map((key2) => this.getCol(key2)).filter((col) => col != null);
  }
  getColDefCol(key2) {
    if (!this.colDefCols?.list) {
      return null;
    }
    return this.getColFromCollection(key2, this.colDefCols);
  }
  getCol(key2) {
    if (key2 == null) {
      return null;
    }
    return this.getColFromCollection(key2, this.cols);
  }
  /**
   * Get column exclusively by ID.
   *
   * Note getCol/getColFromCollection have poor performance when col has been removed.
   */
  getColById(key2) {
    return this.cols?.map[key2] ?? null;
  }
  getColFromCollection(key2, cols) {
    if (cols == null) {
      return null;
    }
    const { map: map2, list: list2 } = cols;
    if (typeof key2 == "string" && map2[key2]) {
      return map2[key2];
    }
    for (let i2 = 0; i2 < list2.length; i2++) {
      if (_columnsMatch(list2[i2], key2)) {
        return list2[i2];
      }
    }
    const { autoColSvc, selectionColSvc, groupHierarchyColSvc } = this.beans;
    return autoColSvc?.getColumn(key2) ?? selectionColSvc?.getColumn(key2) ?? groupHierarchyColSvc?.getColumn(key2) ?? null;
  }
};
var GroupInstanceIdCreator = class {
  constructor() {
    this.existingIds = {};
  }
  getInstanceIdForKey(key2) {
    const lastResult = this.existingIds[key2];
    let result2;
    if (typeof lastResult !== "number") {
      result2 = 0;
    } else {
      result2 = lastResult + 1;
    }
    this.existingIds[key2] = result2;
    return result2;
  }
};
var EmptyBean = class extends BeanStub {
};
function setupCompBean(ctrl, ctx, compBean) {
  if (compBean) {
    ctrl.addDestroyFunc(() => ctx.destroyBean(compBean));
  }
  return compBean ?? ctrl;
}
var RefPlaceholder = null;
function _isComponent(item2) {
  return typeof item2?.getGui === "function";
}
var CssClassManager = class {
  constructor(getGui) {
    this.cssClassStates = {};
    this.getGui = getGui;
  }
  toggleCss(className2, addOrRemove) {
    if (!className2) {
      return;
    }
    if (className2.indexOf(" ") >= 0) {
      const list2 = (className2 || "").split(" ");
      if (list2.length > 1) {
        for (const cls of list2) {
          this.toggleCss(cls, addOrRemove);
        }
        return;
      }
    }
    const updateNeeded = this.cssClassStates[className2] !== addOrRemove;
    if (updateNeeded && className2.length) {
      this.getGui()?.classList.toggle(className2, addOrRemove);
      this.cssClassStates[className2] = addOrRemove;
    }
  }
};
var compIdSequence = 0;
var AgComponentStub = class extends AgBeanStub {
  constructor(templateOrParams, componentSelectors) {
    super();
    this.suppressDataRefValidation = false;
    this.displayed = true;
    this.visible = true;
    this.compId = compIdSequence++;
    this.cssManager = new CssClassManager(() => this.eGui);
    this.componentSelectors = new Map((componentSelectors ?? []).map((comp) => [comp.selector, comp]));
    if (templateOrParams) {
      this.setTemplate(templateOrParams);
    }
  }
  preConstruct() {
    this.wireTemplate(this.getGui());
    const debugId = "component-" + Object.getPrototypeOf(this)?.constructor?.name;
    for (const css of this.css ?? []) {
      this.beans.environment.addGlobalCSS(css, debugId);
    }
  }
  wireTemplate(element, paramsMap) {
    if (element && this.gos) {
      this.applyElementsToComponent(element);
      this.createChildComponentsFromTags(element, paramsMap);
    }
  }
  getCompId() {
    return this.compId;
  }
  getDataRefAttribute(element) {
    if (element.getAttribute) {
      return element.getAttribute(DataRefAttribute);
    }
    return null;
  }
  applyElementsToComponent(element, elementRef, paramsMap, newComponent = null) {
    if (elementRef === void 0) {
      elementRef = this.getDataRefAttribute(element);
    }
    if (elementRef) {
      const current3 = this[elementRef];
      if (current3 === RefPlaceholder) {
        this[elementRef] = newComponent ?? element;
      } else {
        const usedAsParamRef = paramsMap?.[elementRef];
        if (!this.suppressDataRefValidation && !usedAsParamRef) {
          throw new Error(`data-ref: ${elementRef} on ${this.constructor.name} with ${current3}`);
        }
      }
    }
  }
  // for registered components only, eg creates AgCheckbox instance from ag-checkbox HTML tag
  createChildComponentsFromTags(parentNode, paramsMap) {
    const childNodeList = [];
    for (const childNode of parentNode.childNodes ?? []) {
      childNodeList.push(childNode);
    }
    for (const childNode of childNodeList) {
      if (!(childNode instanceof HTMLElement)) {
        continue;
      }
      const childComp = this.createComponentFromElement(
        childNode,
        (childComp2) => {
          const childGui = childComp2.getGui();
          if (childGui) {
            for (const attr of childNode.attributes ?? []) {
              childGui.setAttribute(attr.name, attr.value);
            }
          }
        },
        paramsMap
      );
      if (childComp) {
        if (childComp.addItems && childNode.children.length) {
          this.createChildComponentsFromTags(childNode, paramsMap);
          const items = Array.prototype.slice.call(childNode.children);
          childComp.addItems(items);
        }
        this.swapComponentForNode(childComp, parentNode, childNode);
      } else if (childNode.childNodes) {
        this.createChildComponentsFromTags(childNode, paramsMap);
      }
    }
  }
  createComponentFromElement(element, afterPreCreateCallback, paramsMap) {
    const key2 = element.nodeName;
    const elementRef = this.getDataRefAttribute(element);
    const isAgGridComponent = key2.indexOf("AG-") === 0;
    const componentSelector = isAgGridComponent ? this.componentSelectors.get(key2) : null;
    let newComponent = null;
    if (componentSelector) {
      const componentParams = paramsMap && elementRef ? paramsMap[elementRef] : void 0;
      newComponent = new componentSelector.component(componentParams);
      newComponent.setParentComponent(
        this
      );
      this.createBean(newComponent, null, afterPreCreateCallback);
    } else if (isAgGridComponent) {
      throw new Error(`selector: ${key2}`);
    }
    this.applyElementsToComponent(element, elementRef, paramsMap, newComponent);
    return newComponent;
  }
  swapComponentForNode(newComponent, parentNode, childNode) {
    const eComponent = newComponent.getGui();
    parentNode.replaceChild(eComponent, childNode);
    parentNode.insertBefore(document.createComment(childNode.nodeName), eComponent);
    this.addDestroyFunc(this.destroyBean.bind(this, newComponent));
  }
  activateTabIndex(elements) {
    const tabIndex = this.gos.get("tabIndex");
    if (!elements) {
      elements = [];
    }
    if (!elements.length) {
      elements.push(this.getGui());
    }
    for (const el of elements) {
      el.setAttribute("tabindex", tabIndex.toString());
    }
  }
  setTemplate(templateOrParams, componentSelectors, paramsMap) {
    let eGui;
    if (typeof templateOrParams === "string" || templateOrParams == null) {
      eGui = _loadTemplate(templateOrParams);
    } else {
      eGui = _createAgElement(templateOrParams);
    }
    this.setTemplateFromElement(eGui, componentSelectors, paramsMap);
  }
  setTemplateFromElement(element, components, paramsMap, suppressDataRefValidation = false) {
    this.eGui = element;
    this.suppressDataRefValidation = suppressDataRefValidation;
    if (components) {
      for (let i2 = 0; i2 < components.length; i2++) {
        const component = components[i2];
        this.componentSelectors.set(component.selector, component);
      }
    }
    this.wireTemplate(element, paramsMap);
  }
  getGui() {
    return this.eGui;
  }
  getFocusableElement() {
    return this.eGui;
  }
  getAriaElement() {
    return this.getFocusableElement();
  }
  setParentComponent(component) {
    this.parentComponent = component;
  }
  getParentComponent() {
    return this.parentComponent;
  }
  // this method is for older code, that wants to provide the gui element,
  // it is not intended for this to be in ag-Stack
  setGui(eGui) {
    this.eGui = eGui;
  }
  queryForHtmlElement(cssSelector) {
    return this.eGui.querySelector(cssSelector);
  }
  getContainerAndElement(newChild, container2) {
    let parent = container2;
    if (newChild == null) {
      return null;
    }
    if (!parent) {
      parent = this.eGui;
    }
    if (_isNodeOrElement(newChild)) {
      return {
        element: newChild,
        parent
      };
    }
    return {
      element: newChild.getGui(),
      parent
    };
  }
  prependChild(newChild, container2) {
    const { element, parent } = this.getContainerAndElement(newChild, container2) || {};
    if (!element || !parent) {
      return;
    }
    parent.insertAdjacentElement("afterbegin", element);
  }
  appendChild(newChild, container2) {
    const { element, parent } = this.getContainerAndElement(newChild, container2) || {};
    if (!element || !parent) {
      return;
    }
    parent.appendChild(element);
  }
  isDisplayed() {
    return this.displayed;
  }
  setVisible(visible2, options = {}) {
    if (visible2 !== this.visible) {
      this.visible = visible2;
      const { skipAriaHidden } = options;
      _setVisible(this.eGui, visible2, { skipAriaHidden });
    }
  }
  setDisplayed(displayed, options = {}) {
    if (displayed !== this.displayed) {
      this.displayed = displayed;
      const { skipAriaHidden } = options;
      _setDisplayed(this.eGui, displayed, { skipAriaHidden });
      const event = {
        type: "displayChanged",
        visible: this.displayed
      };
      this.dispatchLocalEvent(event);
    }
  }
  destroy() {
    if (this.parentComponent) {
      this.parentComponent = void 0;
    }
    super.destroy();
  }
  addGuiEventListener(event, listener, options) {
    this.eGui.addEventListener(event, listener, options);
    this.addDestroyFunc(() => this.eGui.removeEventListener(event, listener));
  }
  addCss(className2) {
    this.cssManager.toggleCss(className2, true);
  }
  removeCss(className2) {
    this.cssManager.toggleCss(className2, false);
  }
  toggleCss(className2, addOrRemove) {
    this.cssManager.toggleCss(className2, addOrRemove);
  }
  registerCSS(css) {
    this.css || (this.css = []);
    this.css.push(css);
  }
};
var Component = class extends AgComponentStub {
};
function isColumnFilterComp(filter2) {
  return typeof filter2 === "object" && !!filter2.component;
}
function _wrapInterval(action, timeout) {
  return new AgPromise((resolve2) => {
    resolve2(window.setInterval(action, timeout));
  });
}
var AgPromise = class _AgPromise {
  constructor(callback) {
    this.status = 0;
    this.resolution = null;
    this.waiters = [];
    callback(
      (value2) => this.onDone(value2),
      (params) => this.onReject(params)
    );
  }
  static all(promises) {
    return promises.length ? new _AgPromise((resolve2) => {
      let remainingToResolve = promises.length;
      const combinedValues = new Array(remainingToResolve);
      promises.forEach((promise, index) => {
        promise.then((value2) => {
          combinedValues[index] = value2;
          remainingToResolve--;
          if (remainingToResolve === 0) {
            resolve2(combinedValues);
          }
        });
      });
    }) : _AgPromise.resolve();
  }
  static resolve(value2 = null) {
    return new _AgPromise((resolve2) => resolve2(value2));
  }
  then(func2) {
    return new _AgPromise((resolve2) => {
      if (this.status === 1) {
        resolve2(func2(this.resolution));
      } else {
        this.waiters.push((value2) => resolve2(func2(value2)));
      }
    });
  }
  onDone(value2) {
    this.status = 1;
    this.resolution = value2;
    for (const waiter of this.waiters) {
      waiter(value2);
    }
  }
  onReject(_) {
  }
};
function doesImplementIComponent(candidate) {
  if (!candidate) {
    return false;
  }
  return candidate.prototype && "getGui" in candidate.prototype;
}
function _getUserCompKeys(frameworkOverrides, defObject, type, params) {
  const { name: name2 } = type;
  let compName;
  let jsComp;
  let fwComp;
  let paramsFromSelector;
  let popupFromSelector;
  let popupPositionFromSelector;
  if (defObject) {
    const defObjectAny = defObject;
    const selectorFunc = defObjectAny[name2 + "Selector"];
    const selectorRes = selectorFunc ? selectorFunc(params) : null;
    const assignComp = (providedJsComp) => {
      if (typeof providedJsComp === "string") {
        compName = providedJsComp;
      } else if (providedJsComp != null && providedJsComp !== true) {
        const isFwkComp = frameworkOverrides.isFrameworkComponent(providedJsComp);
        if (isFwkComp) {
          fwComp = providedJsComp;
        } else {
          jsComp = providedJsComp;
        }
      }
    };
    if (selectorRes) {
      assignComp(selectorRes.component);
      paramsFromSelector = selectorRes.params;
      popupFromSelector = selectorRes.popup;
      popupPositionFromSelector = selectorRes.popupPosition;
    } else {
      assignComp(defObjectAny[name2]);
    }
  }
  return { compName, jsComp, fwComp, paramsFromSelector, popupFromSelector, popupPositionFromSelector };
}
var UserComponentFactory = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "userCompFactory";
  }
  wireBeans(beans) {
    this.agCompUtils = beans.agCompUtils;
    this.registry = beans.registry;
    this.frameworkCompWrapper = beans.frameworkCompWrapper;
    this.gridOptions = beans.gridOptions;
  }
  getCompDetailsFromGridOptions(type, defaultName, params, mandatory = false) {
    return this.getCompDetails(this.gridOptions, type, defaultName, params, mandatory);
  }
  getCompDetails(defObject, type, defaultName, params, mandatory = false) {
    const { name: name2, cellRenderer } = type;
    let { compName, jsComp, fwComp, paramsFromSelector, popupFromSelector, popupPositionFromSelector } = _getUserCompKeys(this.beans.frameworkOverrides, defObject, type, params);
    let defaultCompParams;
    let defaultCompProcessParams;
    const lookupFromRegistry = (key2) => {
      const item2 = this.registry.getUserComponent(name2, key2);
      if (item2) {
        jsComp = !item2.componentFromFramework ? item2.component : void 0;
        fwComp = item2.componentFromFramework ? item2.component : void 0;
        defaultCompParams = item2.params;
        defaultCompProcessParams = item2.processParams;
      }
    };
    if (compName != null) {
      lookupFromRegistry(compName);
    }
    if (jsComp == null && fwComp == null && defaultName != null) {
      lookupFromRegistry(defaultName);
    }
    if (jsComp && cellRenderer && !doesImplementIComponent(jsComp)) {
      jsComp = this.agCompUtils?.adaptFunction(type, jsComp);
    }
    if (!jsComp && !fwComp) {
      const { validation: validation2 } = this.beans;
      if (mandatory && (compName !== defaultName || !defaultName)) {
        if (compName) {
          if (!validation2?.isProvidedUserComp(compName)) {
            _error(50, { compName });
          }
        } else if (defaultName) {
          if (!validation2) {
            _error(260, {
              ...this.gos.getModuleErrorParams(),
              propName: name2,
              compName: defaultName
            });
          }
        } else {
          _error(216, { name: name2 });
        }
      } else if (defaultName && !validation2) {
        _error(146, { comp: defaultName });
      }
      return;
    }
    const paramsMerged = this.mergeParams(
      defObject,
      type,
      params,
      paramsFromSelector,
      defaultCompParams,
      defaultCompProcessParams
    );
    const componentFromFramework = jsComp == null;
    const componentClass = jsComp ?? fwComp;
    return {
      componentFromFramework,
      componentClass,
      params: paramsMerged,
      type,
      popupFromSelector,
      popupPositionFromSelector,
      newAgStackInstance: () => this.newAgStackInstance(componentClass, componentFromFramework, paramsMerged, type)
    };
  }
  newAgStackInstance(ComponentClass, componentFromFramework, params, type) {
    const jsComponent = !componentFromFramework;
    let instance2;
    if (jsComponent) {
      instance2 = new ComponentClass();
    } else {
      instance2 = this.frameworkCompWrapper.wrap(
        ComponentClass,
        type.mandatoryMethods,
        type.optionalMethods,
        type
      );
    }
    this.createBean(instance2);
    const deferredInit = instance2.init?.(params);
    if (deferredInit == null) {
      return AgPromise.resolve(instance2);
    }
    return deferredInit.then(() => instance2);
  }
  /**
   * merges params with application provided params
   * used by Floating Filter
   */
  mergeParams(defObject, type, paramsFromGrid, paramsFromSelector = null, defaultCompParams, defaultCompProcessParams) {
    const params = { ...paramsFromGrid, ...defaultCompParams };
    const defObjectAny = defObject;
    const userParams = defObjectAny?.[type.name + "Params"];
    if (typeof userParams === "function") {
      const userParamsFromFunc = userParams(paramsFromGrid);
      _mergeDeep(params, userParamsFromFunc);
    } else if (typeof userParams === "object") {
      _mergeDeep(params, userParams);
    }
    _mergeDeep(params, paramsFromSelector);
    return defaultCompProcessParams ? defaultCompProcessParams(params) : params;
  }
};
var DateComponent = {
  name: "dateComponent",
  mandatoryMethods: ["getDate", "setDate"],
  optionalMethods: ["afterGuiAttached", "setInputPlaceholder", "setInputAriaLabel", "setDisabled", "refresh"]
};
var DragAndDropImageComponent = {
  name: "dragAndDropImageComponent",
  mandatoryMethods: ["setIcon", "setLabel"]
};
var HeaderComponent = { name: "headerComponent", optionalMethods: ["refresh"] };
var InnerHeaderComponent = { name: "innerHeaderComponent" };
var InnerHeaderGroupComponent = { name: "innerHeaderGroupComponent" };
var HeaderGroupComponent = { name: "headerGroupComponent" };
var CellRendererComponent = {
  name: "cellRenderer",
  optionalMethods: ["refresh", "afterGuiAttached"],
  cellRenderer: true
};
var LoadingCellRendererComponent = { name: "loadingCellRenderer", cellRenderer: true };
var CellEditorComponent = {
  name: "cellEditor",
  mandatoryMethods: ["getValue"],
  optionalMethods: [
    "isPopup",
    "isCancelBeforeStart",
    "isCancelAfterEnd",
    "getPopupPosition",
    "focusIn",
    "focusOut",
    "afterGuiAttached",
    "refresh"
  ]
};
var LoadingOverlayComponent = { name: "loadingOverlayComponent", optionalMethods: ["refresh"] };
var NoRowsOverlayComponent = { name: "noRowsOverlayComponent", optionalMethods: ["refresh"] };
var TooltipComponent = { name: "tooltipComponent" };
var FilterComponent = {
  name: "filter",
  mandatoryMethods: ["isFilterActive", "doesFilterPass", "getModel", "setModel"],
  optionalMethods: [
    "afterGuiAttached",
    "afterGuiDetached",
    "onNewRowsLoaded",
    "getModelAsString",
    "onFloatingFilterChanged",
    "onAnyFilterChanged",
    "refresh"
  ]
};
var FloatingFilterComponent = {
  name: "floatingFilterComponent",
  mandatoryMethods: ["onParentModelChanged"],
  optionalMethods: ["afterGuiAttached", "refresh"]
};
var FullWidth = {
  name: "fullWidthCellRenderer",
  optionalMethods: ["refresh", "afterGuiAttached"],
  cellRenderer: true
};
var FullWidthLoading = { name: "loadingCellRenderer", cellRenderer: true };
var FullWidthGroup = {
  name: "groupRowRenderer",
  optionalMethods: ["afterGuiAttached"],
  cellRenderer: true
};
var FullWidthDetail = { name: "detailCellRenderer", optionalMethods: ["refresh"], cellRenderer: true };
function _getDragAndDropImageCompDetails(userCompFactory, params) {
  return userCompFactory.getCompDetailsFromGridOptions(DragAndDropImageComponent, "agDragAndDropImage", params, true);
}
function _getHeaderCompDetails(userCompFactory, colDef, params) {
  return userCompFactory.getCompDetails(colDef, HeaderComponent, "agColumnHeader", params);
}
function _getInnerHeaderCompDetails(userCompFactory, headerCompParams, params) {
  return userCompFactory.getCompDetails(headerCompParams, InnerHeaderComponent, void 0, params);
}
function _getHeaderGroupCompDetails(userCompFactory, params) {
  const colGroupDef = params.columnGroup.getColGroupDef();
  return userCompFactory.getCompDetails(colGroupDef, HeaderGroupComponent, "agColumnGroupHeader", params);
}
function _getInnerHeaderGroupCompDetails(userCompFactory, headerGroupCompParams, params) {
  return userCompFactory.getCompDetails(headerGroupCompParams, InnerHeaderGroupComponent, void 0, params);
}
function _getFullWidthCellRendererDetails(userCompFactory, params) {
  return userCompFactory.getCompDetailsFromGridOptions(FullWidth, void 0, params, true);
}
function _getFullWidthLoadingCellRendererDetails(userCompFactory, params) {
  return userCompFactory.getCompDetailsFromGridOptions(FullWidthLoading, "agLoadingCellRenderer", params, true);
}
function _getFullWidthGroupCellRendererDetails(userCompFactory, params) {
  return userCompFactory.getCompDetailsFromGridOptions(FullWidthGroup, "agGroupRowRenderer", params, true);
}
function _getFullWidthDetailCellRendererDetails(userCompFactory, params) {
  return userCompFactory.getCompDetailsFromGridOptions(FullWidthDetail, "agDetailCellRenderer", params, true);
}
function _getCellRendererDetails(userCompFactory, def, params) {
  return userCompFactory.getCompDetails(def, CellRendererComponent, void 0, params);
}
function _getLoadingCellRendererDetails(userCompFactory, def, params) {
  return userCompFactory.getCompDetails(def, LoadingCellRendererComponent, "agSkeletonCellRenderer", params, true);
}
function _getCellEditorDetails(userCompFactory, def, params) {
  return userCompFactory.getCompDetails(def, CellEditorComponent, "agCellEditor", params, true);
}
function _getFilterDetails(userCompFactory, def, params, defaultFilter) {
  const filter2 = def.filter;
  if (isColumnFilterComp(filter2)) {
    def = {
      filter: filter2.component,
      filterParams: def.filterParams
    };
  }
  return userCompFactory.getCompDetails(def, FilterComponent, defaultFilter, params, true);
}
function _getDateCompDetails(userCompFactory, def, params) {
  return userCompFactory.getCompDetails(def, DateComponent, "agDateInput", params, true);
}
function _getLoadingOverlayCompDetails(userCompFactory, params) {
  return userCompFactory.getCompDetailsFromGridOptions(LoadingOverlayComponent, "agLoadingOverlay", params, true);
}
function _getNoRowsOverlayCompDetails(userCompFactory, params) {
  return userCompFactory.getCompDetailsFromGridOptions(NoRowsOverlayComponent, "agNoRowsOverlay", params, true);
}
function _getTooltipCompDetails(userCompFactory, params) {
  return userCompFactory.getCompDetails(params.colDef, TooltipComponent, "agTooltipComponent", params, true);
}
function _getFloatingFilterCompDetails(userCompFactory, def, params, defaultFloatingFilter) {
  return userCompFactory.getCompDetails(def, FloatingFilterComponent, defaultFloatingFilter, params);
}
function _getFilterCompKeys(frameworkOverrides, def) {
  return _getUserCompKeys(frameworkOverrides, def, FilterComponent);
}
function _mergeFilterParamsWithApplicationProvidedParams(userCompFactory, defObject, paramsFromGrid) {
  return userCompFactory.mergeParams(defObject, FilterComponent, paramsFromGrid);
}
function _unwrapUserComp(comp) {
  const compAsAny = comp;
  const isProxy = compAsAny?.getFrameworkComponentInstance != null;
  return isProxy ? compAsAny.getFrameworkComponentInstance() : comp;
}
function isComponentMetaFunc(componentMeta) {
  return typeof componentMeta === "object" && !!componentMeta.getComp;
}
var KeyCode = {
  BACKSPACE: "Backspace",
  TAB: "Tab",
  ENTER: "Enter",
  ESCAPE: "Escape",
  SPACE: " ",
  LEFT: "ArrowLeft",
  UP: "ArrowUp",
  RIGHT: "ArrowRight",
  DOWN: "ArrowDown",
  DELETE: "Delete",
  F2: "F2",
  PAGE_UP: "PageUp",
  PAGE_DOWN: "PageDown",
  PAGE_HOME: "Home",
  PAGE_END: "End",
  // these should be used with `event.code` instead of `event.key`
  // as `event.key` changes when non-latin keyboards are used
  A: "KeyA",
  C: "KeyC",
  D: "KeyD",
  V: "KeyV",
  X: "KeyX",
  Y: "KeyY",
  Z: "KeyZ"
};
var AgPopupComponent = class extends AgComponentStub {
  isPopup() {
    return true;
  }
  setParentComponent(container2) {
    container2.addCss("ag-has-popup");
    super.setParentComponent(container2);
  }
  destroy() {
    const parentComp = this.parentComponent;
    const hasParent = parentComp?.isAlive();
    if (hasParent) {
      parentComp.getGui().classList.remove("ag-has-popup");
    }
    super.destroy();
  }
};
var isSafari;
var isFirefox;
var isMacOs;
var isIOS;
var invisibleScrollbar;
var browserScrollbarWidth;
var maxDivHeight;
function _isBrowserSafari() {
  if (isSafari === void 0) {
    isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  }
  return isSafari;
}
function _isBrowserFirefox() {
  if (isFirefox === void 0) {
    isFirefox = /(firefox)/i.test(navigator.userAgent);
  }
  return isFirefox;
}
function _isMacOsUserAgent() {
  if (isMacOs === void 0) {
    isMacOs = /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);
  }
  return isMacOs;
}
function _isIOSUserAgent() {
  if (isIOS === void 0) {
    isIOS = /iPad|iPhone|iPod/.test(navigator.platform) || navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1;
  }
  return isIOS;
}
function _getTabIndex(el) {
  if (!el) {
    return null;
  }
  const numberTabIndex = el.tabIndex;
  const tabIndex = el.getAttribute("tabIndex");
  if (numberTabIndex === -1 && (tabIndex === null || tabIndex === "" && !_isBrowserFirefox())) {
    return null;
  }
  return numberTabIndex.toString();
}
function _getMaxDivHeight() {
  if (maxDivHeight !== void 0) {
    return maxDivHeight;
  }
  if (!document.body) {
    return -1;
  }
  let res = 1e6;
  const testUpTo = _isBrowserFirefox() ? 6e6 : 1e9;
  const div = document.createElement("div");
  document.body.appendChild(div);
  while (true) {
    const test2 = res * 2;
    div.style.height = test2 + "px";
    if (test2 > testUpTo || div.clientHeight !== test2) {
      break;
    } else {
      res = test2;
    }
  }
  div.remove();
  maxDivHeight = res;
  return res;
}
function _getScrollbarWidth() {
  if (browserScrollbarWidth == null) {
    initScrollbarWidthAndVisibility();
  }
  return browserScrollbarWidth;
}
function initScrollbarWidthAndVisibility() {
  const body = document.body;
  const div = document.createElement("div");
  div.style.width = div.style.height = "100px";
  div.style.opacity = "0";
  div.style.overflow = "scroll";
  div.style.msOverflowStyle = "scrollbar";
  div.style.position = "absolute";
  body.appendChild(div);
  let width = div.offsetWidth - div.clientWidth;
  if (width === 0 && div.clientWidth === 0) {
    width = null;
  }
  if (div.parentNode) {
    div.remove();
  }
  if (width != null) {
    browserScrollbarWidth = width;
    invisibleScrollbar = width === 0;
  }
}
function _isInvisibleScrollbar() {
  if (invisibleScrollbar == null) {
    initScrollbarWidthAndVisibility();
  }
  return invisibleScrollbar;
}
var DATE_TIME_SEPARATOR = "T";
var DATE_TIME_SEPARATOR_REGEXP = new RegExp(`[${DATE_TIME_SEPARATOR} ]`);
var DATE_TIME_REGEXP = new RegExp(`^\\d{4}-\\d{2}-\\d{2}(${DATE_TIME_SEPARATOR}\\d{2}:\\d{2}:\\d{2}\\D?)?`);
function _padStartWidthZeros(value2, totalStringSize) {
  return value2.toString().padStart(totalStringSize, "0");
}
function _serialiseDate(date2, includeTime = true, separator2 = DATE_TIME_SEPARATOR) {
  if (!date2) {
    return null;
  }
  let serialised = [date2.getFullYear(), date2.getMonth() + 1, date2.getDate()].map((part) => _padStartWidthZeros(part, 2)).join("-");
  if (includeTime) {
    serialised += separator2 + [date2.getHours(), date2.getMinutes(), date2.getSeconds()].map((part) => _padStartWidthZeros(part, 2)).join(":");
  }
  return serialised;
}
function _getDateParts(d, includeTime = true) {
  if (!d) {
    return null;
  }
  if (includeTime) {
    return [
      String(d.getFullYear()),
      String(d.getMonth() + 1),
      _padStartWidthZeros(d.getDate(), 2),
      _padStartWidthZeros(d.getHours(), 2),
      `:${_padStartWidthZeros(d.getMinutes(), 2)}`,
      `:${_padStartWidthZeros(d.getSeconds(), 2)}`
    ];
  }
  return [d.getFullYear(), d.getMonth() + 1, _padStartWidthZeros(d.getDate(), 2)].map(String);
}
var calculateOrdinal = (value2) => {
  if (value2 > 3 && value2 < 21) {
    return "th";
  }
  const remainder = value2 % 10;
  switch (remainder) {
    case 1:
      return "st";
    case 2:
      return "nd";
    case 3:
      return "rd";
  }
  return "th";
};
var MONTHS = [
  "January",
  "February",
  "March",
  "April",
  "May",
  "June",
  "July",
  "August",
  "September",
  "October",
  "November",
  "December"
];
var DAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
function _dateToFormattedString(date2, format2) {
  if (format2 == null) {
    return _serialiseDate(date2, false);
  }
  const fullYear = _padStartWidthZeros(date2.getFullYear(), 4);
  const replace2 = {
    YYYY: () => fullYear.slice(fullYear.length - 4, fullYear.length),
    YY: () => fullYear.slice(fullYear.length - 2, fullYear.length),
    Y: () => `${date2.getFullYear()}`,
    MMMM: () => MONTHS[date2.getMonth()],
    MMM: () => MONTHS[date2.getMonth()].slice(0, 3),
    MM: () => _padStartWidthZeros(date2.getMonth() + 1, 2),
    Mo: () => `${date2.getMonth() + 1}${calculateOrdinal(date2.getMonth() + 1)}`,
    M: () => `${date2.getMonth() + 1}`,
    Do: () => `${date2.getDate()}${calculateOrdinal(date2.getDate())}`,
    DD: () => _padStartWidthZeros(date2.getDate(), 2),
    D: () => `${date2.getDate()}`,
    dddd: () => DAYS[date2.getDay()],
    ddd: () => DAYS[date2.getDay()].slice(0, 3),
    dd: () => DAYS[date2.getDay()].slice(0, 2),
    do: () => `${date2.getDay()}${calculateOrdinal(date2.getDay())}`,
    d: () => `${date2.getDay()}`
  };
  const regexp = new RegExp(Object.keys(replace2).join("|"), "g");
  return format2.replace(regexp, (match3) => {
    if (match3 in replace2) {
      return replace2[match3]();
    }
    return match3;
  });
}
function _isValidDate(value2, bailIfInvalidTime = false) {
  return !!_parseDateTimeFromString(value2, bailIfInvalidTime);
}
function _isValidDateTime(value2) {
  return _isValidDate(value2, true);
}
function _parseDateTimeFromString(value2, bailIfInvalidTime = false, skipValidation) {
  if (!value2) {
    return null;
  }
  if (!skipValidation && !DATE_TIME_REGEXP.test(value2)) {
    return null;
  }
  const [dateStr, timeStr] = value2.split(DATE_TIME_SEPARATOR_REGEXP);
  if (!dateStr) {
    return null;
  }
  const fields = dateStr.split("-").map((f) => Number.parseInt(f, 10));
  if (fields.filter((f) => !isNaN(f)).length !== 3) {
    return null;
  }
  const [year2, month2, day] = fields;
  const date2 = new Date(year2, month2 - 1, day);
  if (date2.getFullYear() !== year2 || date2.getMonth() !== month2 - 1 || date2.getDate() !== day) {
    return null;
  }
  if (!timeStr && bailIfInvalidTime) {
    return null;
  }
  if (!timeStr || timeStr === "00:00:00") {
    return date2;
  }
  const [hours2, minutes2, seconds2] = timeStr.split(":").map((part) => Number.parseInt(part, 10));
  if (hours2 >= 0 && hours2 < 24) {
    date2.setHours(hours2);
  } else if (bailIfInvalidTime) {
    return null;
  }
  if (minutes2 >= 0 && minutes2 < 60) {
    date2.setMinutes(minutes2);
  } else if (bailIfInvalidTime) {
    return null;
  }
  if (seconds2 >= 0 && seconds2 < 60) {
    date2.setSeconds(seconds2);
  } else if (bailIfInvalidTime) {
    return null;
  }
  return date2;
}
function _fuzzySuggestions(params) {
  const { inputValue, allSuggestions, hideIrrelevant, filterByPercentageOfBestMatch } = params;
  let thisSuggestions = (allSuggestions ?? []).map(
    (text2, idx) => ({
      value: text2,
      relevance: _getLevenshteinSimilarityDistance(inputValue, text2),
      idx
    })
  );
  thisSuggestions.sort((a2, b) => a2.relevance - b.relevance);
  if (hideIrrelevant) {
    thisSuggestions = thisSuggestions.filter(
      (suggestion) => suggestion.relevance < Math.max(suggestion.value.length, inputValue.length)
    );
  }
  if (thisSuggestions.length > 0 && filterByPercentageOfBestMatch && filterByPercentageOfBestMatch > 0) {
    const bestMatch = thisSuggestions[0].relevance;
    const limit = bestMatch * filterByPercentageOfBestMatch;
    thisSuggestions = thisSuggestions.filter((suggestion) => limit - suggestion.relevance < 0);
  }
  const values2 = [];
  const indices = [];
  for (const suggestion of thisSuggestions) {
    values2.push(suggestion.value);
    indices.push(suggestion.idx);
  }
  return { values: values2, indices };
}
function _getLevenshteinSimilarityDistance(inputText, suggestion) {
  if (inputText.length < suggestion.length) {
    [inputText, suggestion] = [suggestion, inputText];
  }
  let previousRow = [];
  let currentRow = [];
  const sourceLength = inputText.length;
  const targetLength = suggestion.length;
  for (let j2 = 0; j2 <= targetLength; j2++) {
    previousRow[j2] = j2;
  }
  let secondaryScore = 0;
  for (let i2 = 1; i2 <= sourceLength; i2++) {
    currentRow[0] = i2;
    for (let j2 = 1; j2 <= targetLength; j2++) {
      const sourceChar = inputText[i2 - 1];
      const targetChar = suggestion[j2 - 1];
      if (sourceChar.toLocaleLowerCase() === targetChar.toLocaleLowerCase()) {
        ++secondaryScore;
        if (sourceChar === targetChar) {
          ++secondaryScore;
        }
        if (i2 > 1 && j2 > 1) {
          if (inputText[i2 - 2].toLocaleLowerCase() === suggestion[j2 - 2].toLocaleLowerCase()) {
            ++secondaryScore;
            if (inputText[i2 - 2] === suggestion[j2 - 2]) {
              ++secondaryScore;
            }
          }
        }
        if (i2 < sourceLength / 2 - 10) {
          ++secondaryScore;
        }
        currentRow[j2] = previousRow[j2 - 1];
      } else {
        const insertCost = currentRow[j2 - 1];
        const deleteCost = previousRow[j2];
        const replaceCost = previousRow[j2 - 1];
        currentRow[j2] = 1 + Math.min(insertCost, deleteCost, replaceCost);
      }
    }
    [previousRow, currentRow] = [currentRow, previousRow];
  }
  return previousRow[targetLength] / (secondaryScore + 1);
}
function _isEventFromPrintableCharacter(event) {
  if (event.altKey || event.ctrlKey || event.metaKey) {
    return false;
  }
  const printableCharacter = event.key?.length === 1;
  return printableCharacter;
}
var keyboardModeActive = false;
var instanceCount = 0;
function addKeyboardModeEvents(doc) {
  if (instanceCount > 0) {
    return;
  }
  doc.addEventListener("keydown", toggleKeyboardMode);
  doc.addEventListener("mousedown", toggleKeyboardMode);
}
function removeKeyboardModeEvents(doc) {
  if (instanceCount > 0) {
    return;
  }
  doc.removeEventListener("keydown", toggleKeyboardMode);
  doc.removeEventListener("mousedown", toggleKeyboardMode);
}
function toggleKeyboardMode(event) {
  const isKeyboardActive = keyboardModeActive;
  const isKeyboardEvent = event.type === "keydown";
  if (isKeyboardEvent) {
    if (event.ctrlKey || event.metaKey || event.altKey) {
      return;
    }
  }
  if (isKeyboardActive === isKeyboardEvent) {
    return;
  }
  keyboardModeActive = isKeyboardEvent;
}
function _registerKeyboardFocusEvents(beans) {
  const eDocument = _getDocument(beans);
  addKeyboardModeEvents(eDocument);
  instanceCount++;
  return () => {
    instanceCount--;
    removeKeyboardModeEvents(eDocument);
  };
}
function _isKeyboardMode() {
  return keyboardModeActive;
}
function _findFocusableElements(rootNode, exclude, onlyUnmanaged = false) {
  const focusableString = FOCUSABLE_SELECTOR;
  let excludeString = FOCUSABLE_EXCLUDE;
  if (exclude) {
    excludeString += ", " + exclude;
  }
  if (onlyUnmanaged) {
    excludeString += ', [tabindex="-1"]';
  }
  const nodes = Array.prototype.slice.apply(rootNode.querySelectorAll(focusableString)).filter((node2) => {
    return _isVisible(node2);
  });
  const excludeNodes = Array.prototype.slice.apply(rootNode.querySelectorAll(excludeString));
  if (!excludeNodes.length) {
    return nodes;
  }
  const diff2 = (a2, b) => a2.filter((element) => b.indexOf(element) === -1);
  return diff2(nodes, excludeNodes);
}
function _focusInto(rootNode, up = false, onlyUnmanaged = false, excludeTabGuards = false) {
  const focusableElements = _findFocusableElements(
    rootNode,
    excludeTabGuards ? ".ag-tab-guard" : null,
    onlyUnmanaged
  );
  const toFocus = up ? _last(focusableElements) : focusableElements[0];
  if (toFocus) {
    toFocus.focus({ preventScroll: true });
    return true;
  }
  return false;
}
function _findNextFocusableElement(beans, rootNode, onlyManaged, backwards) {
  const focusable = _findFocusableElements(rootNode, onlyManaged ? ':not([tabindex="-1"])' : null);
  const activeEl = _getActiveDomElement(beans);
  let currentIndex;
  if (onlyManaged) {
    currentIndex = focusable.findIndex((el) => el.contains(activeEl));
  } else {
    currentIndex = focusable.indexOf(activeEl);
  }
  const nextIndex2 = currentIndex + (backwards ? -1 : 1);
  if (nextIndex2 < 0 || nextIndex2 >= focusable.length) {
    return null;
  }
  return focusable[nextIndex2];
}
function _findTabbableParent(node2, limit = 5) {
  let counter2 = 0;
  while (node2 && _getTabIndex(node2) === null && ++counter2 <= limit) {
    node2 = node2.parentElement;
  }
  if (_getTabIndex(node2) === null) {
    return null;
  }
  return node2;
}
var agAbstractLabelCSS = (
  /*css*/
  `.ag-label{white-space:nowrap}:where(.ag-ltr) .ag-label{margin-right:var(--ag-spacing)}:where(.ag-rtl) .ag-label{margin-left:var(--ag-spacing)}:where(.ag-label-align-right) .ag-label{order:1}:where(.ag-ltr) :where(.ag-label-align-right) .ag-label{margin-left:var(--ag-spacing)}:where(.ag-rtl) :where(.ag-label-align-right) .ag-label{margin-right:var(--ag-spacing)}.ag-label-align-right>*{flex:none}.ag-label-align-top{align-items:flex-start;flex-direction:column;>*{align-self:stretch}}.ag-label-ellipsis{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}:where(.ag-label-align-top) .ag-label{margin-bottom:calc(var(--ag-spacing)*.5)}`
);
var AgAbstractLabel = class extends AgComponentStub {
  constructor(config2, template2, components) {
    super(template2, components);
    this.labelSeparator = "";
    this.labelAlignment = "left";
    this.disabled = false;
    this.label = "";
    this.config = config2 || {};
    this.registerCSS(agAbstractLabelCSS);
  }
  postConstruct() {
    this.addCss("ag-labeled");
    this.eLabel.classList.add("ag-label");
    const { labelSeparator, label: label2, labelWidth, labelAlignment, disabled: disabled2 } = this.config;
    if (disabled2 != null) {
      this.setDisabled(disabled2);
    }
    if (labelSeparator != null) {
      this.setLabelSeparator(labelSeparator);
    }
    if (label2 != null) {
      this.setLabel(label2);
    }
    if (labelWidth != null) {
      this.setLabelWidth(labelWidth);
    }
    this.setLabelAlignment(labelAlignment || this.labelAlignment);
    this.refreshLabel();
  }
  refreshLabel() {
    const { label: label2, eLabel } = this;
    _clearElement(eLabel);
    if (typeof label2 === "string") {
      eLabel.innerText = label2 + this.labelSeparator;
    } else if (label2) {
      eLabel.appendChild(label2);
    }
    if (label2 === "") {
      _setDisplayed(eLabel, false);
      _setAriaRole(eLabel, "presentation");
    } else {
      _setDisplayed(eLabel, true);
      _setAriaRole(eLabel, null);
    }
  }
  setLabelSeparator(labelSeparator) {
    if (this.labelSeparator === labelSeparator) {
      return this;
    }
    this.labelSeparator = labelSeparator;
    if (this.label != null) {
      this.refreshLabel();
    }
    return this;
  }
  getLabelId() {
    const eLabel = this.eLabel;
    eLabel.id = eLabel.id || `ag-${this.getCompId()}-label`;
    return eLabel.id;
  }
  getLabel() {
    return this.label;
  }
  setLabel(label2) {
    if (this.label === label2) {
      return this;
    }
    this.label = label2;
    this.refreshLabel();
    return this;
  }
  setLabelAlignment(alignment) {
    const eGui = this.getGui();
    const eGuiClassList = eGui.classList;
    eGuiClassList.toggle("ag-label-align-left", alignment === "left");
    eGuiClassList.toggle("ag-label-align-right", alignment === "right");
    eGuiClassList.toggle("ag-label-align-top", alignment === "top");
    return this;
  }
  setLabelEllipsis(hasEllipsis) {
    this.eLabel.classList.toggle("ag-label-ellipsis", hasEllipsis);
    return this;
  }
  setLabelWidth(width) {
    if (this.label == null) {
      return this;
    }
    _setElementWidth(this.eLabel, width);
    return this;
  }
  setDisabled(disabled2) {
    disabled2 = !!disabled2;
    const element = this.getGui();
    _setDisabled(element, disabled2);
    element.classList.toggle("ag-disabled", disabled2);
    this.disabled = disabled2;
    return this;
  }
  isDisabled() {
    return !!this.disabled;
  }
};
var AgAbstractField = class extends AgAbstractLabel {
  constructor(config2, template2, components, className2) {
    super(config2, template2, components);
    this.className = className2;
  }
  postConstruct() {
    super.postConstruct();
    const { width, value: value2, onValueChange } = this.config;
    if (width != null) {
      this.setWidth(width);
    }
    if (value2 != null) {
      this.setValue(value2);
    }
    if (onValueChange != null) {
      this.onValueChange(onValueChange);
    }
    if (this.className) {
      this.addCss(this.className);
    }
    this.refreshAriaLabelledBy();
  }
  setLabel(label2) {
    super.setLabel(label2);
    this.refreshAriaLabelledBy();
    return this;
  }
  refreshAriaLabelledBy() {
    const ariaEl = this.getAriaElement();
    const labelId = this.getLabelId();
    const label2 = this.getLabel();
    if (label2 == null || label2 == "" || _getAriaLabel(ariaEl) !== null) {
      _setAriaLabelledBy(ariaEl, "");
    } else {
      _setAriaLabelledBy(ariaEl, labelId ?? "");
    }
  }
  setAriaLabel(label2) {
    _setAriaLabel(this.getAriaElement(), label2);
    this.refreshAriaLabelledBy();
    return this;
  }
  onValueChange(callbackFn) {
    this.addManagedListeners(this, { fieldValueChanged: () => callbackFn(this.getValue()) });
    return this;
  }
  getWidth() {
    return this.getGui().clientWidth;
  }
  setWidth(width) {
    _setFixedWidth(this.getGui(), width);
    return this;
  }
  getPreviousValue() {
    return this.previousValue;
  }
  getValue() {
    return this.value;
  }
  setValue(value2, silent) {
    if (this.value === value2) {
      return this;
    }
    this.previousValue = this.value;
    this.value = value2;
    if (!silent) {
      this.dispatchLocalEvent({ type: "fieldValueChanged" });
    }
    return this;
  }
};
function buildTemplate(displayFieldTag) {
  return {
    tag: "div",
    role: "presentation",
    children: [
      { tag: "div", ref: "eLabel", cls: "ag-input-field-label" },
      {
        tag: "div",
        ref: "eWrapper",
        cls: "ag-wrapper ag-input-wrapper",
        role: "presentation",
        children: [{ tag: displayFieldTag, ref: "eInput", cls: "ag-input-field-input" }]
      }
    ]
  };
}
var AgAbstractInputField = class extends AgAbstractField {
  constructor(config2, className2, inputType = "text", displayFieldTag = "input") {
    super(config2, config2?.template ?? buildTemplate(displayFieldTag), [], className2);
    this.inputType = inputType;
    this.displayFieldTag = displayFieldTag;
    this.eLabel = RefPlaceholder;
    this.eWrapper = RefPlaceholder;
    this.eInput = RefPlaceholder;
  }
  postConstruct() {
    super.postConstruct();
    this.setInputType(this.inputType);
    const { eLabel, eWrapper, eInput, className: className2 } = this;
    eLabel.classList.add(`${className2}-label`);
    eWrapper.classList.add(`${className2}-input-wrapper`);
    eInput.classList.add(`${className2}-input`);
    this.addCss("ag-input-field");
    eInput.id = eInput.id || `ag-${this.getCompId()}-input`;
    const { inputName, inputWidth } = this.config;
    if (inputName != null) {
      this.setInputName(inputName);
    }
    if (inputWidth != null) {
      this.setInputWidth(inputWidth);
    }
    this.addInputListeners();
    this.activateTabIndex([eInput]);
  }
  addInputListeners() {
    this.addManagedElementListeners(this.eInput, {
      input: (e) => this.setValue(e.target.value)
    });
  }
  setInputType(inputType) {
    if (this.displayFieldTag === "input") {
      this.inputType = inputType;
      _addOrRemoveAttribute(this.eInput, "type", inputType);
    }
  }
  getInputElement() {
    return this.eInput;
  }
  setInputWidth(width) {
    _setElementWidth(this.eWrapper, width);
    return this;
  }
  setInputName(name2) {
    this.getInputElement().setAttribute("name", name2);
    return this;
  }
  getFocusableElement() {
    return this.eInput;
  }
  setMaxLength(length2) {
    const eInput = this.eInput;
    eInput.maxLength = length2;
    return this;
  }
  setInputPlaceholder(placeholder) {
    _addOrRemoveAttribute(this.eInput, "placeholder", placeholder);
    return this;
  }
  setInputAriaLabel(label2) {
    _setAriaLabel(this.eInput, label2);
    this.refreshAriaLabelledBy();
    return this;
  }
  setDisabled(disabled2) {
    _setDisabled(this.eInput, disabled2);
    return super.setDisabled(disabled2);
  }
  setAutoComplete(value2) {
    if (value2 === true) {
      _addOrRemoveAttribute(this.eInput, "autocomplete", null);
    } else {
      const autoCompleteValue = typeof value2 === "string" ? value2 : "off";
      _addOrRemoveAttribute(this.eInput, "autocomplete", autoCompleteValue);
    }
    return this;
  }
};
var AgCheckbox = class extends AgAbstractInputField {
  constructor(config2, className2 = "ag-checkbox", inputType = "checkbox") {
    super(config2, className2, inputType);
    this.labelAlignment = "right";
    this.selected = false;
    this.readOnly = false;
    this.passive = false;
  }
  postConstruct() {
    super.postConstruct();
    const { readOnly, passive: passive2 } = this.config;
    if (typeof readOnly === "boolean") {
      this.setReadOnly(readOnly);
    }
    if (typeof passive2 === "boolean") {
      this.setPassive(passive2);
    }
  }
  addInputListeners() {
    this.addManagedElementListeners(this.eInput, { click: this.onCheckboxClick.bind(this) });
    this.addManagedElementListeners(this.eLabel, { click: this.toggle.bind(this) });
  }
  getNextValue() {
    return this.selected === void 0 ? true : !this.selected;
  }
  setPassive(passive2) {
    this.passive = passive2;
  }
  isReadOnly() {
    return this.readOnly;
  }
  setReadOnly(readOnly) {
    this.eWrapper.classList.toggle("ag-disabled", readOnly);
    this.eInput.disabled = readOnly;
    this.readOnly = readOnly;
  }
  setDisabled(disabled2) {
    this.eWrapper.classList.toggle("ag-disabled", disabled2);
    return super.setDisabled(disabled2);
  }
  toggle() {
    if (this.eInput.disabled) {
      return;
    }
    const previousValue = this.isSelected();
    const nextValue = this.getNextValue();
    if (this.passive) {
      this.dispatchChange(nextValue, previousValue);
    } else {
      this.setValue(nextValue);
    }
  }
  getValue() {
    return this.isSelected();
  }
  setValue(value2, silent) {
    this.refreshSelectedClass(value2);
    this.setSelected(value2, silent);
    return this;
  }
  setName(name2) {
    const input2 = this.getInputElement();
    input2.name = name2;
    return this;
  }
  isSelected() {
    return this.selected;
  }
  setSelected(selected2, silent) {
    if (this.isSelected() === selected2) {
      return;
    }
    this.previousValue = this.isSelected();
    selected2 = this.selected = typeof selected2 === "boolean" ? selected2 : void 0;
    const eInput = this.eInput;
    eInput.checked = selected2;
    eInput.indeterminate = selected2 === void 0;
    if (!silent) {
      this.dispatchChange(this.selected, this.previousValue);
    }
  }
  dispatchChange(selected2, previousValue, event) {
    this.dispatchLocalEvent({ type: "fieldValueChanged", selected: selected2, previousValue, event });
    const input2 = this.getInputElement();
    this.eventSvc.dispatchEvent({
      type: "checkboxChanged",
      id: input2.id,
      name: input2.name,
      selected: selected2,
      previousValue
    });
  }
  onCheckboxClick(e) {
    if (this.passive || this.eInput.disabled) {
      return;
    }
    const previousValue = this.isSelected();
    const selected2 = this.selected = e.target.checked;
    this.refreshSelectedClass(selected2);
    this.dispatchChange(selected2, previousValue, e);
  }
  refreshSelectedClass(value2) {
    const classList = this.eWrapper.classList;
    classList.toggle("ag-checked", value2 === true);
    classList.toggle("ag-indeterminate", value2 == null);
  }
};
var AgCheckboxSelector = {
  selector: "AG-CHECKBOX",
  component: AgCheckbox
};
var AgRadioButton = class extends AgCheckbox {
  constructor(config2) {
    super(config2, "ag-radio-button", "radio");
  }
  isSelected() {
    return this.eInput.checked;
  }
  toggle() {
    if (this.eInput.disabled) {
      return;
    }
    if (!this.isSelected()) {
      this.setValue(true);
    }
  }
  addInputListeners() {
    super.addInputListeners();
    this.addManagedEventListeners({ checkboxChanged: this.onChange.bind(this) });
  }
  /**
   * This ensures that if another radio button in the same named group is selected, we deselect this radio button.
   * By default the browser does this for you, but we are managing classes ourselves in order to ensure input
   * elements are styled correctly in IE11, and the DOM 'changed' event is only fired when a button is selected,
   * not deselected, so we need to use our own event.
   */
  onChange(event) {
    const eInput = this.eInput;
    if (event.selected && event.name && eInput.name && eInput.name === event.name && event.id && eInput.id !== event.id) {
      this.setValue(false, true);
    }
  }
};
var AgInputTextField = class extends AgAbstractInputField {
  constructor(config2, className2 = "ag-text-field", inputType = "text") {
    super(config2, className2, inputType);
  }
  postConstruct() {
    super.postConstruct();
    if (this.config.allowedCharPattern) {
      this.preventDisallowedCharacters();
    }
  }
  setValue(value2, silent) {
    const eInput = this.eInput;
    if (eInput.value !== value2) {
      eInput.value = _exists(value2) ? value2 : "";
    }
    return super.setValue(value2, silent);
  }
  /** Used to set an initial value into the input without necessarily setting `this.value` or triggering events (e.g. to set an invalid value) */
  setStartValue(value2) {
    this.setValue(value2, true);
  }
  preventDisallowedCharacters() {
    const pattern = new RegExp(`[${this.config.allowedCharPattern}]`);
    const preventCharacters = (event) => {
      if (!_isEventFromPrintableCharacter(event)) {
        return;
      }
      if (event.key && !pattern.test(event.key)) {
        event.preventDefault();
      }
    };
    this.addManagedListeners(this.eInput, {
      keydown: preventCharacters,
      paste: (e) => {
        const text2 = e.clipboardData?.getData("text");
        if (text2?.split("").some((c2) => !pattern.test(c2))) {
          e.preventDefault();
        }
      }
    });
  }
};
var AgInputTextFieldSelector = {
  selector: "AG-INPUT-TEXT-FIELD",
  component: AgInputTextField
};
var AgInputTextArea = class extends AgAbstractInputField {
  constructor(config2) {
    super(config2, "ag-text-area", null, "textarea");
  }
  setValue(value2, silent) {
    const ret = super.setValue(value2, silent);
    this.eInput.value = value2;
    return ret;
  }
  setCols(cols) {
    this.eInput.cols = cols;
    return this;
  }
  setRows(rows) {
    this.eInput.rows = rows;
    return this;
  }
};
var AgInputTextAreaSelector = {
  selector: "AG-INPUT-TEXT-AREA",
  component: AgInputTextArea
};
var AgInputNumberField = class extends AgInputTextField {
  constructor(config2) {
    super(config2, "ag-number-field", "number");
  }
  postConstruct() {
    super.postConstruct();
    const eInput = this.eInput;
    this.addManagedListeners(eInput, {
      blur: () => {
        const floatedValue = Number.parseFloat(eInput.value);
        const value2 = isNaN(floatedValue) ? "" : this.normalizeValue(floatedValue.toString());
        if (this.value !== value2) {
          this.setValue(value2);
        }
      },
      wheel: this.onWheel.bind(this)
    });
    eInput.step = "any";
    const { precision, min: min2, max: max2, step } = this.config;
    if (typeof precision === "number") {
      this.setPrecision(precision);
    }
    if (typeof min2 === "number") {
      this.setMin(min2);
    }
    if (typeof max2 === "number") {
      this.setMax(max2);
    }
    if (typeof step === "number") {
      this.setStep(step);
    }
  }
  onWheel(e) {
    if (_getActiveDomElement(this.beans) === this.eInput) {
      e.preventDefault();
    }
  }
  normalizeValue(value2) {
    if (value2 === "") {
      return "";
    }
    if (this.precision != null) {
      value2 = this.adjustPrecision(value2);
    }
    return value2;
  }
  adjustPrecision(value2, isScientificNotation) {
    const precision = this.precision;
    if (precision == null) {
      return value2;
    }
    if (isScientificNotation) {
      const floatString = Number.parseFloat(value2).toFixed(precision);
      return Number.parseFloat(floatString).toString();
    }
    const parts = String(value2).split(".");
    if (parts.length > 1) {
      if (parts[1].length <= precision) {
        return value2;
      } else if (precision > 0) {
        return `${parts[0]}.${parts[1].slice(0, precision)}`;
      }
    }
    return parts[0];
  }
  setMin(min2) {
    if (this.min === min2) {
      return this;
    }
    this.min = min2;
    _addOrRemoveAttribute(this.eInput, "min", min2);
    return this;
  }
  setMax(max2) {
    if (this.max === max2) {
      return this;
    }
    this.max = max2;
    _addOrRemoveAttribute(this.eInput, "max", max2);
    return this;
  }
  setPrecision(precision) {
    this.precision = precision;
    return this;
  }
  setStep(step) {
    if (this.step === step) {
      return this;
    }
    this.step = step;
    _addOrRemoveAttribute(this.eInput, "step", step);
    return this;
  }
  setValue(value2, silent) {
    return this.setValueOrInputValue(
      (v) => super.setValue(v, silent),
      () => this,
      value2
    );
  }
  setStartValue(value2) {
    return this.setValueOrInputValue(
      (v) => super.setValue(v, true),
      (v) => {
        this.eInput.value = v;
      },
      value2
    );
  }
  setValueOrInputValue(setValueFunc, setInputValueOnlyFunc, value2) {
    if (_exists(value2)) {
      let setInputValueOnly = this.isScientificNotation(value2);
      if (setInputValueOnly && this.eInput.validity.valid) {
        return setValueFunc(value2);
      }
      if (!setInputValueOnly) {
        value2 = this.adjustPrecision(value2);
        const normalizedValue = this.normalizeValue(value2);
        setInputValueOnly = value2 != normalizedValue;
      }
      if (setInputValueOnly) {
        return setInputValueOnlyFunc(value2);
      }
    }
    return setValueFunc(value2);
  }
  getValue() {
    const eInput = this.eInput;
    if (!eInput.validity.valid) {
      return void 0;
    }
    const inputValue = eInput.value;
    if (this.isScientificNotation(inputValue)) {
      return this.adjustPrecision(inputValue, true);
    }
    return super.getValue();
  }
  isScientificNotation(value2) {
    return typeof value2 === "string" && value2.includes("e");
  }
};
var AgInputNumberFieldSelector = {
  selector: "AG-INPUT-NUMBER-FIELD",
  component: AgInputNumberField
};
var AgInputDateField = class extends AgInputTextField {
  constructor(config2) {
    super(config2, "ag-date-field", "date");
  }
  postConstruct() {
    super.postConstruct();
    const usingSafari = _isBrowserSafari();
    this.addManagedListeners(this.eInput, {
      wheel: this.onWheel.bind(this),
      mousedown: () => {
        if (this.isDisabled() || usingSafari) {
          return;
        }
        this.eInput.focus();
      }
    });
    this.eInput.step = "any";
  }
  onWheel(e) {
    if (_getActiveDomElement(this.beans) === this.eInput) {
      e.preventDefault();
    }
  }
  setMin(minDate) {
    const min2 = minDate instanceof Date ? _serialiseDate(minDate ?? null, !!this.includeTime) ?? void 0 : minDate;
    if (this.min === min2) {
      return this;
    }
    this.min = min2;
    _addOrRemoveAttribute(this.eInput, "min", min2);
    return this;
  }
  setMax(maxDate) {
    const max2 = maxDate instanceof Date ? _serialiseDate(maxDate ?? null, !!this.includeTime) ?? void 0 : maxDate;
    if (this.max === max2) {
      return this;
    }
    this.max = max2;
    _addOrRemoveAttribute(this.eInput, "max", max2);
    return this;
  }
  setStep(step) {
    if (this.step === step) {
      return this;
    }
    this.step = step;
    _addOrRemoveAttribute(this.eInput, "step", step);
    return this;
  }
  setIncludeTime(includeTime) {
    if (this.includeTime === includeTime) {
      return this;
    }
    this.includeTime = includeTime;
    super.setInputType(includeTime ? "datetime-local" : "date");
    if (includeTime) {
      this.setStep(1);
    }
    return this;
  }
  getDate() {
    if (!this.eInput.validity.valid) {
      return void 0;
    }
    return _parseDateTimeFromString(this.getValue()) ?? void 0;
  }
  setDate(date2, silent) {
    this.setValue(_serialiseDate(date2 ?? null, this.includeTime), silent);
  }
};
var AgInputDateFieldSelector = {
  selector: "AG-INPUT-DATE-FIELD",
  component: AgInputDateField
};
var agListCSS = (
  /*css*/
  `.ag-list-item{align-items:center;display:flex;height:var(--ag-list-item-height);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;&.ag-active-item{background-color:var(--ag-row-hover-color)}}`
);
var ACTIVE_CLASS = "ag-active-item";
var getAgListElement = (cssIdentifier, label2) => ({
  tag: "div",
  cls: `ag-list-item ag-${cssIdentifier}-list-item`,
  attrs: { role: "option" },
  children: [
    {
      tag: "span",
      ref: "eText",
      children: label2
    }
  ]
});
var AgListItem = class extends AgComponentStub {
  constructor(cssIdentifier, label2, value2) {
    super(getAgListElement(cssIdentifier, label2));
    this.label = label2;
    this.value = value2;
    this.eText = RefPlaceholder;
  }
  postConstruct() {
    this.createTooltip();
    this.addEventListeners();
  }
  setHighlighted(highlighted) {
    const eGui = this.getGui();
    eGui.classList.toggle(ACTIVE_CLASS, highlighted);
    _setAriaSelected(eGui, highlighted);
    this.dispatchLocalEvent({
      type: "itemHighlighted",
      highlighted
    });
  }
  getHeight() {
    return this.getGui().clientHeight;
  }
  setIndex(idx, setSize) {
    const eGui = this.getGui();
    _setAriaPosInSet(eGui, idx);
    _setAriaSetSize(eGui, setSize);
  }
  createTooltip() {
    const tooltipCtrl = {
      getTooltipValue: () => this.label,
      getGui: () => this.getGui(),
      getLocation: () => "UNKNOWN",
      // only show tooltips for items where the text cannot be fully displayed
      shouldDisplayTooltip: () => _isHorizontalScrollShowing(this.eText)
    };
    const tooltipFeature = this.createOptionalManagedBean(
      this.beans.registry.createDynamicBean(
        "highlightTooltipFeature",
        false,
        tooltipCtrl,
        this
      )
    );
    if (tooltipFeature) {
      this.tooltipFeature = tooltipFeature;
    }
  }
  addEventListeners() {
    const parentComponent = this.getParentComponent();
    if (!parentComponent) {
      return;
    }
    this.addGuiEventListener("mouseover", () => {
      parentComponent.highlightItem(this);
    });
    this.addGuiEventListener("mousedown", (e) => {
      e.preventDefault();
      e.stopPropagation();
      parentComponent.setValue(this.value);
    });
  }
};
var AgList = class extends AgComponentStub {
  constructor(cssIdentifier = "default") {
    super({ tag: "div", cls: `ag-list ag-${cssIdentifier}-list` });
    this.cssIdentifier = cssIdentifier;
    this.options = [];
    this.listItems = [];
    this.highlightedItem = null;
    this.registerCSS(agListCSS);
  }
  postConstruct() {
    const eGui = this.getGui();
    this.addManagedElementListeners(eGui, { mouseleave: () => this.clearHighlighted() });
  }
  handleKeyDown(e) {
    const key2 = e.key;
    switch (key2) {
      case KeyCode.ENTER:
        if (!this.highlightedItem) {
          this.setValue(this.getValue());
        } else {
          const pos2 = this.listItems.indexOf(this.highlightedItem);
          this.setValueByIndex(pos2);
        }
        break;
      case KeyCode.DOWN:
      case KeyCode.UP:
        e.preventDefault();
        this.navigate(key2);
        break;
      case KeyCode.PAGE_DOWN:
      case KeyCode.PAGE_UP:
      case KeyCode.PAGE_HOME:
      case KeyCode.PAGE_END:
        e.preventDefault();
        this.navigateToPage(key2);
        break;
    }
  }
  addOptions(listOptions) {
    for (const listOption of listOptions) {
      this.addOption(listOption);
    }
    return this;
  }
  addOption(listOption) {
    const { value: value2, text: text2 } = listOption;
    const valueToRender = text2 ?? value2;
    this.options.push({ value: value2, text: valueToRender });
    this.renderOption(value2, valueToRender);
    this.updateIndices();
    return this;
  }
  clearOptions() {
    this.options = [];
    this.reset(true);
    for (const item2 of this.listItems) {
      item2.destroy();
    }
    _clearElement(this.getGui());
    this.listItems = [];
    this.refreshAriaRole();
  }
  setValue(value2, silent) {
    if (this.value === value2) {
      this.fireItemSelected();
      return this;
    }
    if (value2 == null) {
      this.reset(silent);
      return this;
    }
    const idx = this.options.findIndex((option) => option.value === value2);
    if (idx !== -1) {
      const option = this.options[idx];
      this.value = option.value;
      this.displayValue = option.text;
      this.highlightItem(this.listItems[idx]);
      if (!silent) {
        this.fireChangeEvent();
      }
    }
    return this;
  }
  setValueByIndex(idx) {
    return this.setValue(this.options[idx].value);
  }
  getValue() {
    return this.value;
  }
  getDisplayValue() {
    return this.displayValue;
  }
  refreshHighlighted() {
    this.clearHighlighted();
    const idx = this.options.findIndex((option) => option.value === this.value);
    if (idx !== -1) {
      this.highlightItem(this.listItems[idx]);
    }
  }
  highlightItem(item2) {
    const itemEl = item2.getGui();
    if (!_isVisible(itemEl)) {
      return;
    }
    this.clearHighlighted();
    item2.setHighlighted(true);
    this.highlightedItem = item2;
    const eGui = this.getGui();
    const { scrollTop, clientHeight } = eGui;
    const { offsetTop, offsetHeight } = itemEl;
    if (offsetTop + offsetHeight > scrollTop + clientHeight || offsetTop < scrollTop) {
      itemEl.scrollIntoView({ block: "nearest" });
    }
  }
  hideItemTooltip() {
    this.highlightedItem?.tooltipFeature?.attemptToHideTooltip();
  }
  destroy() {
    this.hideItemTooltip();
    super.destroy();
  }
  reset(silent) {
    this.value = null;
    this.displayValue = null;
    this.clearHighlighted();
    if (!silent) {
      this.fireChangeEvent();
    }
  }
  clearHighlighted() {
    this.highlightedItem?.setHighlighted(false);
    this.highlightedItem = null;
  }
  renderOption(value2, text2) {
    const item2 = new AgListItem(this.cssIdentifier, text2, value2);
    item2.setParentComponent(this);
    const listItem = this.createManagedBean(item2);
    this.listItems.push(listItem);
    this.getGui().appendChild(listItem.getGui());
  }
  navigate(key2) {
    const isDown = key2 === KeyCode.DOWN;
    let itemToHighlight;
    const { listItems, highlightedItem } = this;
    if (!highlightedItem) {
      itemToHighlight = isDown ? listItems[0] : _last(listItems);
    } else {
      const currentIdx = listItems.indexOf(highlightedItem);
      let nextPos = currentIdx + (isDown ? 1 : -1);
      nextPos = Math.min(Math.max(nextPos, 0), listItems.length - 1);
      itemToHighlight = listItems[nextPos];
    }
    this.highlightItem(itemToHighlight);
  }
  navigateToPage(key2) {
    const { listItems, highlightedItem } = this;
    if (!highlightedItem || listItems.length === 0) {
      return;
    }
    const currentIdx = listItems.indexOf(highlightedItem);
    const rowCount = this.options.length - 1;
    const itemHeight = listItems[0].getHeight();
    const pageSize = Math.floor(this.getGui().clientHeight / itemHeight);
    let newIndex = -1;
    if (key2 === KeyCode.PAGE_HOME) {
      newIndex = 0;
    } else if (key2 === KeyCode.PAGE_END) {
      newIndex = rowCount;
    } else if (key2 === KeyCode.PAGE_DOWN) {
      newIndex = Math.min(currentIdx + pageSize, rowCount);
    } else if (key2 === KeyCode.PAGE_UP) {
      newIndex = Math.max(currentIdx - pageSize, 0);
    }
    if (newIndex === -1) {
      return;
    }
    this.highlightItem(listItems[newIndex]);
  }
  refreshAriaRole() {
    _setAriaRole(this.getGui(), this.options.length === 0 ? "presentation" : "listbox");
  }
  updateIndices() {
    this.refreshAriaRole();
    const listItems = this.listItems;
    const len = listItems.length;
    listItems.forEach((item2, idx) => {
      item2.setIndex(idx + 1, len);
    });
  }
  fireChangeEvent() {
    this.dispatchLocalEvent({ type: "fieldValueChanged" });
    this.fireItemSelected();
  }
  fireItemSelected() {
    this.dispatchLocalEvent({ type: "selectedItem" });
  }
};
var agPickerFieldCSS = (
  /*css*/
  `.ag-picker-field-display{flex:1 1 auto}.ag-picker-field{align-items:center;display:flex}.ag-picker-field-icon{border:0;cursor:pointer;display:flex;margin:0;padding:0}.ag-picker-field-wrapper{background-color:var(--ag-picker-button-background-color);border:var(--ag-picker-button-border);border-radius:5px;min-height:max(var(--ag-list-item-height),calc(var(--ag-spacing)*4));overflow:hidden;&:where(.ag-picker-has-focus),&:where(:focus-within){background-color:var(--ag-picker-button-focus-background-color);border:var(--ag-picker-button-focus-border);box-shadow:var(--ag-focus-shadow);&:where(.invalid){box-shadow:var(--ag-focus-error-shadow)}}&:where(.invalid){background-color:var(--ag-input-invalid-background-color);border:var(--ag-input-invalid-border);color:var(--ag-input-invalid-text-color)}&:disabled{opacity:.5}}`
);
var AgPickerFieldElement = {
  tag: "div",
  cls: "ag-picker-field",
  role: "presentation",
  children: [
    { tag: "div", ref: "eLabel" },
    {
      tag: "div",
      ref: "eWrapper",
      cls: "ag-wrapper ag-picker-field-wrapper ag-picker-collapsed",
      children: [
        { tag: "div", ref: "eDisplayField", cls: "ag-picker-field-display" },
        { tag: "div", ref: "eIcon", cls: "ag-picker-field-icon", attrs: { "aria-hidden": "true" } }
      ]
    }
  ]
};
var AgPickerField = class extends AgAbstractField {
  constructor(config2) {
    super(config2, config2?.template || AgPickerFieldElement, config2?.agComponents || [], config2?.className);
    this.isPickerDisplayed = false;
    this.skipClick = false;
    this.pickerGap = 4;
    this.hideCurrentPicker = null;
    this.eLabel = RefPlaceholder;
    this.eWrapper = RefPlaceholder;
    this.eDisplayField = RefPlaceholder;
    this.eIcon = RefPlaceholder;
    this.registerCSS(agPickerFieldCSS);
    this.ariaRole = config2?.ariaRole;
    this.onPickerFocusIn = this.onPickerFocusIn.bind(this);
    this.onPickerFocusOut = this.onPickerFocusOut.bind(this);
    if (!config2) {
      return;
    }
    const { pickerGap, maxPickerHeight, variableWidth, minPickerWidth, maxPickerWidth } = config2;
    if (pickerGap != null) {
      this.pickerGap = pickerGap;
    }
    this.variableWidth = !!variableWidth;
    if (maxPickerHeight != null) {
      this.setPickerMaxHeight(maxPickerHeight);
    }
    if (minPickerWidth != null) {
      this.setPickerMinWidth(minPickerWidth);
    }
    if (maxPickerWidth != null) {
      this.setPickerMaxWidth(maxPickerWidth);
    }
  }
  postConstruct() {
    super.postConstruct();
    this.setupAria();
    const displayId = `ag-${this.getCompId()}-display`;
    this.eDisplayField.setAttribute("id", displayId);
    const ariaEl = this.getAriaElement();
    this.addManagedElementListeners(ariaEl, { keydown: this.onKeyDown.bind(this) });
    this.addManagedElementListeners(this.eLabel, { mousedown: this.onLabelOrWrapperMouseDown.bind(this) });
    this.addManagedElementListeners(this.eWrapper, { mousedown: this.onLabelOrWrapperMouseDown.bind(this) });
    const { pickerIcon, inputWidth } = this.config;
    if (pickerIcon) {
      const icon2 = this.beans.iconSvc.createIconNoSpan(pickerIcon);
      if (icon2) {
        this.eIcon.appendChild(icon2);
      }
    }
    if (inputWidth != null) {
      this.setInputWidth(inputWidth);
    }
  }
  setupAria() {
    const ariaEl = this.getAriaElement();
    ariaEl.setAttribute("tabindex", this.gos.get("tabIndex").toString());
    _setAriaExpanded(ariaEl, false);
    if (this.ariaRole) {
      _setAriaRole(ariaEl, this.ariaRole);
    }
  }
  onLabelOrWrapperMouseDown(e) {
    if (e) {
      const focusableEl = this.getFocusableElement();
      if (focusableEl !== this.eWrapper && e?.target === focusableEl) {
        return;
      }
      e.preventDefault();
      this.getFocusableElement().focus();
    }
    if (this.skipClick) {
      this.skipClick = false;
      return;
    }
    if (this.isDisabled()) {
      return;
    }
    if (this.isPickerDisplayed) {
      this.hidePicker();
    } else {
      this.showPicker();
    }
  }
  onKeyDown(e) {
    switch (e.key) {
      case KeyCode.UP:
      case KeyCode.DOWN:
      case KeyCode.ENTER:
      case KeyCode.SPACE:
        e.preventDefault();
        this.onLabelOrWrapperMouseDown();
        break;
      case KeyCode.ESCAPE:
        if (this.isPickerDisplayed) {
          e.preventDefault();
          e.stopPropagation();
          if (this.hideCurrentPicker) {
            this.hideCurrentPicker();
          }
        }
        break;
    }
  }
  showPicker() {
    this.isPickerDisplayed = true;
    if (!this.pickerComponent) {
      this.pickerComponent = this.createPickerComponent();
    }
    const pickerGui = this.pickerComponent.getGui();
    pickerGui.addEventListener("focusin", this.onPickerFocusIn);
    pickerGui.addEventListener("focusout", this.onPickerFocusOut);
    this.hideCurrentPicker = this.renderAndPositionPicker();
    this.toggleExpandedStyles(true);
  }
  renderAndPositionPicker() {
    const ePicker = this.pickerComponent.getGui();
    if (!this.gos.get("suppressScrollWhenPopupsAreOpen")) {
      [this.destroyMouseWheelFunc] = this.addManagedEventListeners({
        bodyScroll: () => {
          this.hidePicker();
        }
      });
    }
    const translate = this.getLocaleTextFunc();
    const {
      config: { pickerAriaLabelKey, pickerAriaLabelValue, modalPicker = true },
      maxPickerHeight,
      minPickerWidth,
      maxPickerWidth,
      variableWidth,
      beans,
      eWrapper
    } = this;
    const popupParams = {
      modal: modalPicker,
      eChild: ePicker,
      closeOnEsc: true,
      closedCallback: () => {
        const shouldRestoreFocus = _isNothingFocused(beans);
        this.beforeHidePicker();
        if (shouldRestoreFocus && this.isAlive()) {
          this.getFocusableElement().focus();
        }
      },
      ariaLabel: translate(pickerAriaLabelKey, pickerAriaLabelValue),
      anchorToElement: eWrapper
    };
    ePicker.style.position = "absolute";
    const popupSvc = beans.popupSvc;
    const addPopupRes = popupSvc.addPopup(popupParams);
    if (variableWidth) {
      if (minPickerWidth) {
        ePicker.style.minWidth = minPickerWidth;
      }
      ePicker.style.width = _formatSize(_getAbsoluteWidth(eWrapper));
      if (maxPickerWidth) {
        ePicker.style.maxWidth = maxPickerWidth;
      }
    } else {
      _setElementWidth(ePicker, maxPickerWidth ?? _getAbsoluteWidth(eWrapper));
    }
    const maxHeight = maxPickerHeight ?? `${_getInnerHeight(popupSvc.getPopupParent())}px`;
    ePicker.style.setProperty("max-height", maxHeight);
    this.alignPickerToComponent();
    return addPopupRes.hideFunc;
  }
  alignPickerToComponent() {
    if (!this.pickerComponent) {
      return;
    }
    const {
      pickerGap,
      config: { pickerType },
      beans: { popupSvc, gos },
      eWrapper,
      pickerComponent
    } = this;
    const alignSide = gos.get("enableRtl") ? "right" : "left";
    popupSvc.positionPopupByComponent({
      type: pickerType,
      eventSource: eWrapper,
      ePopup: pickerComponent.getGui(),
      position: "under",
      alignSide,
      keepWithinBounds: true,
      nudgeY: pickerGap
    });
  }
  beforeHidePicker() {
    if (this.destroyMouseWheelFunc) {
      this.destroyMouseWheelFunc();
      this.destroyMouseWheelFunc = void 0;
    }
    this.toggleExpandedStyles(false);
    const pickerGui = this.pickerComponent.getGui();
    pickerGui.removeEventListener("focusin", this.onPickerFocusIn);
    pickerGui.removeEventListener("focusout", this.onPickerFocusOut);
    this.isPickerDisplayed = false;
    this.pickerComponent = void 0;
    this.hideCurrentPicker = null;
  }
  toggleExpandedStyles(expanded) {
    if (!this.isAlive()) {
      return;
    }
    const ariaEl = this.getAriaElement();
    _setAriaExpanded(ariaEl, expanded);
    const classList = this.eWrapper.classList;
    classList.toggle("ag-picker-expanded", expanded);
    classList.toggle("ag-picker-collapsed", !expanded);
  }
  onPickerFocusIn() {
    this.togglePickerHasFocus(true);
  }
  onPickerFocusOut(e) {
    if (!this.pickerComponent?.getGui().contains(e.relatedTarget)) {
      this.togglePickerHasFocus(false);
    }
  }
  togglePickerHasFocus(focused) {
    if (!this.pickerComponent) {
      return;
    }
    this.eWrapper.classList.toggle("ag-picker-has-focus", focused);
  }
  hidePicker() {
    if (this.hideCurrentPicker) {
      this.hideCurrentPicker();
      this.dispatchLocalEvent({
        type: "pickerHidden"
      });
    }
  }
  setInputWidth(width) {
    _setElementWidth(this.eWrapper, width);
    return this;
  }
  getFocusableElement() {
    return this.eWrapper;
  }
  setPickerGap(gap) {
    this.pickerGap = gap;
    return this;
  }
  setPickerMinWidth(width) {
    if (typeof width === "number") {
      width = `${width}px`;
    }
    this.minPickerWidth = width == null ? void 0 : width;
    return this;
  }
  setPickerMaxWidth(width) {
    if (typeof width === "number") {
      width = `${width}px`;
    }
    this.maxPickerWidth = width == null ? void 0 : width;
    return this;
  }
  setPickerMaxHeight(height) {
    if (typeof height === "number") {
      height = `${height}px`;
    }
    this.maxPickerHeight = height == null ? void 0 : height;
    return this;
  }
  destroy() {
    this.hidePicker();
    super.destroy();
  }
};
var agSelectCSS = (
  /*css*/
  `.ag-select{align-items:center;display:flex;&.ag-disabled{opacity:.5}}:where(.ag-select){.ag-picker-field-wrapper{cursor:default}&.ag-disabled .ag-picker-field-wrapper:focus{box-shadow:none}&:not(.ag-cell-editor,.ag-label-align-top){min-height:var(--ag-list-item-height)}.ag-picker-field-display{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.ag-picker-field-icon{align-items:center;display:flex}}:where(.ag-ltr) :where(.ag-select){.ag-picker-field-wrapper{padding-left:calc(var(--ag-cell-horizontal-padding)/2);padding-right:var(--ag-spacing)}}:where(.ag-rtl) :where(.ag-select){.ag-picker-field-wrapper{padding-left:var(--ag-spacing);padding-right:calc(var(--ag-cell-horizontal-padding)/2)}}.ag-select-list{background-color:var(--ag-picker-list-background-color);border:var(--ag-picker-list-border);border-radius:var(--ag-border-radius);box-shadow:var(--ag-dropdown-shadow);overflow:hidden auto}.ag-select-list-item{cursor:default;-webkit-user-select:none;-moz-user-select:none;user-select:none;:where(span){overflow:hidden;text-overflow:ellipsis;white-space:nowrap}}:where(.ag-ltr) .ag-select-list-item{padding-left:calc(var(--ag-cell-horizontal-padding)/2)}:where(.ag-rtl) .ag-select-list-item{padding-right:calc(var(--ag-cell-horizontal-padding)/2)}`
);
var AgSelect = class extends AgPickerField {
  constructor(config2) {
    super({
      pickerAriaLabelKey: "ariaLabelSelectField",
      pickerAriaLabelValue: "Select Field",
      pickerType: "ag-list",
      className: "ag-select",
      pickerIcon: "selectOpen",
      ariaRole: "combobox",
      ...config2
    });
    this.registerCSS(agSelectCSS);
  }
  postConstruct() {
    this.tooltipFeature = this.createOptionalManagedBean(
      this.beans.registry.createDynamicBean(
        "tooltipFeature",
        false,
        {
          shouldDisplayTooltip: _isElementOverflowingCallback(() => this.eDisplayField),
          getGui: () => this.getGui()
        }
      )
    );
    super.postConstruct();
    this.createListComponent();
    this.eWrapper.tabIndex = this.gos.get("tabIndex");
    const { options, value: value2, placeholder } = this.config;
    if (options != null) {
      this.addOptions(options);
    }
    if (value2 != null) {
      this.setValue(value2, true);
    }
    if (placeholder && value2 == null) {
      this.eDisplayField.textContent = placeholder;
    }
    this.addManagedElementListeners(this.eWrapper, { focusout: this.onWrapperFocusOut.bind(this) });
  }
  onWrapperFocusOut(e) {
    if (!this.eWrapper.contains(e.relatedTarget)) {
      this.hidePicker();
    }
  }
  createListComponent() {
    const listComponent = this.createBean(
      new AgList("select")
    );
    this.listComponent = listComponent;
    listComponent.setParentComponent(this);
    const eListAriaEl = listComponent.getAriaElement();
    const listId = `ag-select-list-${listComponent.getCompId()}`;
    eListAriaEl.setAttribute("id", listId);
    _setAriaControlsAndLabel(this.getAriaElement(), eListAriaEl);
    listComponent.addManagedElementListeners(listComponent.getGui(), {
      mousedown: (e) => {
        e?.preventDefault();
      }
    });
    listComponent.addManagedListeners(listComponent, {
      selectedItem: () => {
        this.hidePicker();
        this.dispatchLocalEvent({ type: "selectedItem" });
      },
      fieldValueChanged: () => {
        if (!this.listComponent) {
          return;
        }
        this.setValue(this.listComponent.getValue(), false, true);
        this.hidePicker();
      }
    });
  }
  createPickerComponent() {
    return this.listComponent;
  }
  beforeHidePicker() {
    this.listComponent?.hideItemTooltip();
    super.beforeHidePicker();
  }
  onKeyDown(e) {
    const { key: key2 } = e;
    if (key2 === KeyCode.TAB) {
      this.hidePicker();
    }
    switch (key2) {
      case KeyCode.ENTER:
      case KeyCode.UP:
      case KeyCode.DOWN:
      case KeyCode.PAGE_UP:
      case KeyCode.PAGE_DOWN:
      case KeyCode.PAGE_HOME:
      case KeyCode.PAGE_END:
        e.preventDefault();
        if (this.isPickerDisplayed) {
          this.listComponent?.handleKeyDown(e);
        } else {
          super.onKeyDown(e);
        }
        break;
      case KeyCode.ESCAPE:
        super.onKeyDown(e);
        break;
      case KeyCode.SPACE:
        if (this.isPickerDisplayed) {
          e.preventDefault();
        } else {
          super.onKeyDown(e);
        }
        break;
    }
  }
  showPicker() {
    const listComponent = this.listComponent;
    if (!listComponent) {
      return;
    }
    super.showPicker();
    listComponent.refreshHighlighted();
  }
  addOptions(options) {
    for (const option of options) {
      this.addOption(option);
    }
    return this;
  }
  addOption(option) {
    this.listComponent.addOption(option);
    return this;
  }
  clearOptions() {
    this.listComponent?.clearOptions();
    this.setValue(void 0, true);
    return this;
  }
  setValue(value2, silent, fromPicker) {
    const {
      listComponent,
      config: { placeholder },
      eDisplayField,
      tooltipFeature
    } = this;
    if (this.value === value2 || !listComponent) {
      return this;
    }
    if (!fromPicker) {
      listComponent.setValue(value2, true);
    }
    const newValue = listComponent.getValue();
    if (newValue === this.getValue()) {
      return this;
    }
    let displayValue = listComponent.getDisplayValue();
    if (displayValue == null && placeholder) {
      displayValue = placeholder;
    }
    eDisplayField.textContent = displayValue;
    tooltipFeature?.setTooltipAndRefresh(displayValue ?? null);
    return super.setValue(value2, silent);
  }
  destroy() {
    this.listComponent = this.destroyBean(this.listComponent);
    super.destroy();
  }
};
var AgSelectSelector = {
  selector: "AG-SELECT",
  component: AgSelect
};
var sharedCSS = (
  /*css*/
  `:where(.ag-root-wrapper,.ag-external,.ag-popup,.ag-dnd-ghost,.ag-chart),:where(.ag-root-wrapper,.ag-external,.ag-popup,.ag-dnd-ghost,.ag-chart) :where([class^=ag-]){box-sizing:border-box;&:after,&:before{box-sizing:border-box}&:where(div,span,label):focus-visible{box-shadow:inset var(--ag-focus-shadow);outline:none;&:where(.invalid){box-shadow:inset var(--ag-focus-error-shadow)}}&:where(button){color:inherit}}:where(.ag-root-wrapper,ag-external,.ag-popup,.ag-dnd-ghost,.ag-chart) :where([class^=ag-]) ::-ms-clear{display:none}.ag-hidden{display:none!important}.ag-invisible{visibility:hidden!important}.ag-popup-child{top:0;z-index:5;&:where(:not(.ag-tooltip-custom)){box-shadow:var(--ag-popup-shadow)}}.ag-input-wrapper,.ag-picker-field-wrapper{align-items:center;display:flex;flex:1 1 auto;line-height:normal;position:relative}.ag-input-field{align-items:center;display:flex;flex-direction:row}.ag-input-field-input:where(:not([type=checkbox],[type=radio])){flex:1 1 auto;min-width:0;width:100%}.ag-chart,.ag-dnd-ghost,.ag-external,.ag-popup,.ag-root-wrapper{cursor:default;line-height:normal;white-space:normal;-webkit-font-smoothing:antialiased;background-color:var(--ag-background-color);color:var(--ag-text-color);color-scheme:var(--ag-browser-color-scheme);font-family:var(--ag-font-family);font-size:var(--ag-font-size);--ag-indentation-level:0}:where(.ag-icon):before{align-items:center;background-color:currentcolor;color:inherit;content:"";display:flex;font-family:inherit;font-size:var(--ag-icon-size);font-style:normal;font-variant:normal;height:var(--ag-icon-size);justify-content:center;line-height:var(--ag-icon-size);-webkit-mask-size:contain;mask-size:contain;text-transform:none;width:var(--ag-icon-size)}.ag-icon{background-position:50%;background-repeat:no-repeat;background-size:contain;color:var(--ag-icon-color);display:block;height:var(--ag-icon-size);position:relative;-webkit-user-select:none;-moz-user-select:none;user-select:none;width:var(--ag-icon-size)}.ag-disabled,[disabled]{.ag-icon{opacity:.5}&.ag-icon-grip{opacity:.35}}.ag-resizer{pointer-events:none;position:absolute;-webkit-user-select:none;-moz-user-select:none;user-select:none;z-index:1}:where(.ag-resizer){&.ag-resizer-topLeft{cursor:nwse-resize;height:5px;left:0;top:0;width:5px}&.ag-resizer-top{cursor:ns-resize;height:5px;left:5px;right:5px;top:0}&.ag-resizer-topRight{cursor:nesw-resize;height:5px;right:0;top:0;width:5px}&.ag-resizer-right{bottom:5px;cursor:ew-resize;right:0;top:5px;width:5px}&.ag-resizer-bottomRight{bottom:0;cursor:nwse-resize;height:5px;right:0;width:5px}&.ag-resizer-bottom{bottom:0;cursor:ns-resize;height:5px;left:5px;right:5px}&.ag-resizer-bottomLeft{bottom:0;cursor:nesw-resize;height:5px;left:0;width:5px}&.ag-resizer-left{bottom:5px;cursor:ew-resize;left:0;top:5px;width:5px}}`
);
var IS_SSR = typeof window !== "object" || !window?.document?.fonts?.forEach;
var _injectGlobalCSS = (css, styleContainer, debugId, layer, priority, nonce) => {
  if (IS_SSR) {
    return;
  }
  if (layer) {
    css = `@layer ${CSS.escape(layer)} { ${css} }`;
  }
  let injections = injectionState.map.get(styleContainer);
  if (!injections) {
    injections = [];
    injectionState.map.set(styleContainer, injections);
  }
  if (injections.some((i2) => i2.css === css)) {
    return;
  }
  const el = document.createElement("style");
  if (nonce) {
    el.setAttribute("nonce", nonce);
  }
  el.dataset.agGlobalCss = debugId;
  el.textContent = css;
  const newInjection = { css, el, priority };
  let insertAfter;
  for (const injection of injections) {
    if (injection.priority > priority) {
      break;
    }
    insertAfter = injection;
  }
  if (insertAfter) {
    insertAfter.el.insertAdjacentElement("afterend", el);
    const index = injections.indexOf(insertAfter);
    injections.splice(index + 1, 0, newInjection);
  } else {
    styleContainer.insertBefore(el, styleContainer.querySelector(":not(title, meta)"));
    injections.push(newInjection);
  }
};
var _injectCoreAndModuleCSS = (styleContainer, layer, nonce, moduleCss) => {
  _injectGlobalCSS(sharedCSS, styleContainer, "shared", layer, 0, nonce);
  moduleCss?.forEach(
    (css, debugId) => css.forEach((singleCss) => _injectGlobalCSS(singleCss, styleContainer, debugId, layer, 0, nonce))
  );
};
var _registerInstanceUsingThemingAPI = (environment) => {
  injectionState.grids.add(environment);
};
var _unregisterInstanceUsingThemingAPI = (environment) => {
  injectionState.grids.delete(environment);
  if (injectionState.grids.size === 0) {
    injectionState.map = /* @__PURE__ */ new WeakMap();
    for (const style2 of document.head.querySelectorAll("style[data-ag-global-css]")) {
      style2.remove();
    }
  }
};
var _a;
var injectionState = (_a = typeof window === "object" ? window : {}).agStyleInjectionState ?? (_a.agStyleInjectionState = {
  map: /* @__PURE__ */ new WeakMap(),
  grids: /* @__PURE__ */ new Set()
});
var createPart = (args2) => {
  return new PartImpl(args2);
};
var defaultModeName = "$default";
var partCounter = 0;
var PartImpl = class {
  constructor({ feature, params, modeParams = {}, css, cssImports }) {
    this.feature = feature;
    this.css = css;
    this.cssImports = cssImports;
    this.modeParams = {
      // NOTE: it's important that default is defined first, putting it
      // first in iteration order, because when merging params the default
      // params override any prior modal params, so modal params in this
      // part need to come after default params to prevent them from being
      // immediately overridden.
      [defaultModeName]: {
        ...modeParams[defaultModeName] ?? {},
        ...params ?? {}
      },
      ...modeParams
    };
  }
  use(styleContainer, layer, nonce) {
    let inject = this._inject;
    if (inject == null) {
      let { css } = this;
      if (css) {
        const className2 = `ag-theme-${this.feature ?? "part"}-${++partCounter}`;
        if (typeof css === "function") {
          css = css();
        }
        css = `:where(.${className2}) {
${css}
}
`;
        for (const cssImport of this.cssImports ?? []) {
          css = `@import url(${JSON.stringify(cssImport)});
${css}`;
        }
        inject = { css, class: className2 };
      } else {
        inject = false;
      }
      this._inject = inject;
    }
    if (inject && styleContainer) {
      _injectGlobalCSS(inject.css, styleContainer, inject.class, layer, 1, nonce);
    }
    return inject ? inject.class : false;
  }
};
var kebabCase = (str) => str.replace(/[A-Z]/g, (m) => `-${m}`).toLowerCase();
var paramToVariableName = (paramName) => `--ag-${kebabCase(paramName)}`;
var paramToVariableExpression = (paramName) => `var(${paramToVariableName(paramName)})`;
var clamp = (value2, min2, max2) => Math.max(min2, Math.min(max2, value2));
var memoize = (fn3) => {
  const values2 = /* @__PURE__ */ new Map();
  return (a2) => {
    const key2 = a2;
    if (!values2.has(key2)) {
      values2.set(key2, fn3(a2));
    }
    return values2.get(key2);
  };
};
var accentMix = (mix) => ({ ref: "accentColor", mix });
var foregroundMix = (mix) => ({ ref: "foregroundColor", mix });
var foregroundBackgroundMix = (mix) => ({
  ref: "foregroundColor",
  mix,
  onto: "backgroundColor"
});
var foregroundHeaderBackgroundMix = (mix) => ({
  ref: "foregroundColor",
  mix,
  onto: "headerBackgroundColor"
});
var backgroundColor = { ref: "backgroundColor" };
var foregroundColor = { ref: "foregroundColor" };
var accentColor = { ref: "accentColor" };
var defaultLightColorSchemeParams = {
  backgroundColor: "#fff",
  foregroundColor: "#181d1f",
  borderColor: foregroundMix(0.15),
  chromeBackgroundColor: foregroundBackgroundMix(0.02),
  browserColorScheme: "light"
};
var sharedDefaults = {
  ...defaultLightColorSchemeParams,
  textColor: foregroundColor,
  accentColor: "#2196f3",
  invalidColor: "#e02525",
  fontFamily: [
    "-apple-system",
    "BlinkMacSystemFont",
    "Segoe UI",
    "Roboto",
    "Oxygen-Sans",
    "Ubuntu",
    "Cantarell",
    "Helvetica Neue",
    "sans-serif"
  ],
  subtleTextColor: {
    ref: "textColor",
    mix: 0.5
  },
  borderWidth: 1,
  borderRadius: 4,
  spacing: 8,
  fontSize: 14,
  focusShadow: {
    spread: 3,
    color: accentMix(0.5)
  },
  focusErrorShadow: {
    spread: 3,
    color: {
      ref: "invalidColor",
      onto: "backgroundColor",
      mix: 0.5
    }
  },
  popupShadow: "0 0 16px #00000026",
  cardShadow: "0 1px 4px 1px #00000018",
  dropdownShadow: { ref: "cardShadow" },
  listItemHeight: {
    calc: "max(iconSize, dataFontSize) + widgetVerticalSpacing"
  },
  dragAndDropImageBackgroundColor: backgroundColor,
  dragAndDropImageBorder: true,
  dragAndDropImageNotAllowedBorder: {
    color: {
      ref: "invalidColor",
      onto: "dragAndDropImageBackgroundColor",
      mix: 0.5
    }
  },
  dragAndDropImageShadow: {
    ref: "popupShadow"
  },
  iconSize: 16,
  iconColor: "inherit",
  toggleButtonWidth: 28,
  toggleButtonHeight: 18,
  toggleButtonOnBackgroundColor: accentColor,
  toggleButtonOffBackgroundColor: foregroundBackgroundMix(0.3),
  toggleButtonSwitchBackgroundColor: backgroundColor,
  toggleButtonSwitchInset: 2,
  tooltipBackgroundColor: {
    ref: "chromeBackgroundColor"
  },
  tooltipErrorBackgroundColor: {
    ref: "invalidColor",
    onto: "backgroundColor",
    mix: 0.1
  },
  tooltipTextColor: {
    ref: "textColor"
  },
  tooltipErrorTextColor: {
    ref: "invalidColor"
  },
  tooltipBorder: true,
  tooltipErrorBorder: {
    color: {
      ref: "invalidColor",
      onto: "backgroundColor",
      mix: 0.25
    }
  }
};
var paramTypes = [
  "colorScheme",
  "color",
  "length",
  "scale",
  "borderStyle",
  "border",
  "shadow",
  "image",
  "fontFamily",
  "fontWeight",
  "duration"
];
var getParamType = memoize((param) => {
  param = param.toLowerCase();
  return paramTypes.find((type) => param.endsWith(type.toLowerCase())) ?? "length";
});
var literalToCSS = (value2) => {
  if (typeof value2 === "object" && value2?.ref) {
    return paramToVariableExpression(value2.ref);
  }
  if (typeof value2 === "string") {
    return value2;
  }
  if (typeof value2 === "number") {
    return String(value2);
  }
  return false;
};
var colorValueToCss = (value2) => {
  if (typeof value2 === "string") {
    return value2;
  }
  if (value2 && "ref" in value2) {
    const colorExpr = paramToVariableExpression(value2.ref);
    if (value2.mix == null) {
      return colorExpr;
    }
    const backgroundExpr = value2.onto ? paramToVariableExpression(value2.onto) : "transparent";
    return `color-mix(in srgb, ${backgroundExpr}, ${colorExpr} ${clamp(value2.mix * 100, 0, 100)}%)`;
  }
  return false;
};
var colorSchemeValueToCss = literalToCSS;
var lengthValueToCss = (value2) => {
  if (typeof value2 === "string") {
    return value2;
  }
  if (typeof value2 === "number") {
    return `${value2}px`;
  }
  if (value2 && "calc" in value2) {
    const valueWithSpaces = value2.calc.replace(/ ?[*/+] ?/g, " $& ");
    return `calc(${valueWithSpaces.replace(/-?\b[a-z][a-z0-9]*\b(?![-(])/gi, (p) => p[0] === "-" ? p : " " + paramToVariableExpression(p) + " ")})`;
  }
  if (value2 && "ref" in value2) {
    return paramToVariableExpression(value2.ref);
  }
  return false;
};
var scaleValueToCss = literalToCSS;
var borderValueToCss = (value2, param) => {
  if (typeof value2 === "string") {
    return value2;
  }
  if (value2 === true) {
    return borderValueToCss({}, param);
  }
  if (value2 === false) {
    return param === "columnBorder" ? borderValueToCss({ color: "transparent" }, param) : "none";
  }
  if (value2 && "ref" in value2) {
    return paramToVariableExpression(value2.ref);
  }
  return borderStyleValueToCss(value2.style ?? "solid") + " " + lengthValueToCss(value2.width ?? { ref: "borderWidth" }) + " " + colorValueToCss(value2.color ?? { ref: "borderColor" });
};
var shadowValueToCss = (value2) => {
  if (typeof value2 === "string") {
    return value2;
  }
  if (value2 === false) {
    return "none";
  }
  if (value2 && "ref" in value2) {
    return paramToVariableExpression(value2.ref);
  }
  return [
    lengthValueToCss(value2.offsetX ?? 0),
    lengthValueToCss(value2.offsetY ?? 0),
    lengthValueToCss(value2.radius ?? 0),
    lengthValueToCss(value2.spread ?? 0),
    colorValueToCss(value2.color ?? { ref: "foregroundColor" })
  ].join(" ");
};
var borderStyleValueToCss = literalToCSS;
var fontFamilyValueToCss = (value2) => {
  if (typeof value2 === "string") {
    return value2.includes(",") ? value2 : quoteUnsafeChars(value2);
  }
  if (value2 && "googleFont" in value2) {
    return fontFamilyValueToCss(value2.googleFont);
  }
  if (value2 && "ref" in value2) {
    return paramToVariableExpression(value2.ref);
  }
  if (Array.isArray(value2)) {
    return value2.map((font) => {
      if (typeof font === "object" && "googleFont" in font) {
        font = font.googleFont;
      }
      return quoteUnsafeChars(font);
    }).join(", ");
  }
  return false;
};
var quoteUnsafeChars = (font) => (
  // don't quote var() expressions or quote safe identifier names, so that
  // people can specify fonts like sans-serif which are keywords not strings,
  // or var(--my-var)
  /^[\w-]+$|\w\(/.test(font) ? font : JSON.stringify(font)
);
var fontWeightValueToCss = literalToCSS;
var imageValueToCss = (value2) => {
  if (typeof value2 === "string") {
    return value2;
  }
  if (value2 && "url" in value2) {
    return `url(${JSON.stringify(value2.url)})`;
  }
  if (value2 && "svg" in value2) {
    return imageValueToCss({ url: `data:image/svg+xml,${encodeURIComponent(value2.svg)}` });
  }
  if (value2 && "ref" in value2) {
    return paramToVariableExpression(value2.ref);
  }
  return false;
};
var durationValueToCss = (value2, param, themeLogger) => {
  if (typeof value2 === "string") {
    return value2;
  }
  if (typeof value2 === "number") {
    if (value2 >= 10) {
      themeLogger.warn(104, { value: value2, param });
    }
    return `${value2}s`;
  }
  if (value2 && "ref" in value2) {
    return paramToVariableExpression(value2.ref);
  }
  return false;
};
var paramValidators = {
  color: colorValueToCss,
  colorScheme: colorSchemeValueToCss,
  length: lengthValueToCss,
  scale: scaleValueToCss,
  border: borderValueToCss,
  borderStyle: borderStyleValueToCss,
  shadow: shadowValueToCss,
  image: imageValueToCss,
  fontFamily: fontFamilyValueToCss,
  fontWeight: fontWeightValueToCss,
  duration: durationValueToCss
};
var paramValueToCss = (param, value2, themeLogger) => {
  const type = getParamType(param);
  return paramValidators[type](value2, param, themeLogger);
};
var createSharedTheme = (themeLogger) => new ThemeImpl(themeLogger);
var ThemeImpl = class _ThemeImpl {
  constructor(themeLogger, parts = []) {
    this.themeLogger = themeLogger;
    this.parts = parts;
  }
  withPart(part) {
    if (typeof part === "function") {
      part = part();
    }
    if (!(part instanceof PartImpl)) {
      this.themeLogger.preInitErr(259, "Invalid part", { part });
      return this;
    }
    return new _ThemeImpl(this.themeLogger, [...this.parts, part]);
  }
  withoutPart(feature) {
    return this.withPart(createPart({ feature }));
  }
  withParams(params, mode = defaultModeName) {
    return this.withPart(
      createPart({
        modeParams: { [mode]: params }
      })
    );
  }
  /**
   * Called by a grid instance when it starts using the theme. This installs
   * the theme's parts into document head, or the shadow DOM if the provided
   * container is within a shadow root.
   */
  _startUse({ styleContainer, cssLayer, nonce, loadThemeGoogleFonts, moduleCss }) {
    if (IS_SSR) {
      return;
    }
    uninstallLegacyCSS();
    _injectCoreAndModuleCSS(styleContainer, cssLayer, nonce, moduleCss);
    const googleFontsUsed = getGoogleFontsUsed(this);
    if (googleFontsUsed.length > 0) {
      for (const googleFont of googleFontsUsed) {
        if (loadThemeGoogleFonts) {
          loadGoogleFont(googleFont, nonce);
        }
      }
    }
    for (const part of this.parts) {
      part.use(styleContainer, cssLayer, nonce);
    }
  }
  /**
   * Return CSS that that applies the params of this theme to elements with
   * the provided class name
   */
  _getCssClass() {
    return this._cssClassCache ?? (this._cssClassCache = deduplicatePartsByFeature(this.parts).map((part) => part.use(void 0, void 0, void 0)).filter(Boolean).join(" "));
  }
  _getModeParams() {
    let paramsCache = this._paramsCache;
    if (!paramsCache) {
      const mergedModeParams = {
        // NOTE: defining the default mode here is important, it ensures
        // that the default mode is first in iteration order, which puts
        // it first in outputted CSS, allowing other modes to override it
        [defaultModeName]: { ...sharedDefaults }
      };
      for (const part of deduplicatePartsByFeature(this.parts)) {
        for (const partMode of Object.keys(part.modeParams)) {
          const partParams = part.modeParams[partMode];
          if (partParams) {
            const mergedParams = mergedModeParams[partMode] ?? (mergedModeParams[partMode] = {});
            const partParamNames = /* @__PURE__ */ new Set();
            for (const partParamName of Object.keys(partParams)) {
              const partParamValue = partParams[partParamName];
              if (partParamValue !== void 0) {
                mergedParams[partParamName] = partParamValue;
                partParamNames.add(partParamName);
              }
            }
            if (partMode === defaultModeName) {
              for (const mergedMode of Object.keys(mergedModeParams)) {
                const mergedParams2 = mergedModeParams[mergedMode];
                if (mergedMode !== defaultModeName) {
                  for (const partParamName of partParamNames) {
                    delete mergedParams2[partParamName];
                  }
                }
              }
            }
          }
        }
      }
      this._paramsCache = paramsCache = mergedModeParams;
    }
    return paramsCache;
  }
  /**
   * Return the CSS chunk that is inserted into the grid DOM, and will
   * therefore be removed automatically when the grid is destroyed or it
   * starts to use a new theme.
   *
   * @param className a unique class name on the grid wrapper used to scope the returned CSS to the grid instance
   */
  _getPerInstanceCss(className2) {
    const selectorPlaceholder = "##SELECTOR##";
    let innerParamsCss = this._paramsCssCache;
    if (!innerParamsCss) {
      let variablesCss = "";
      let inheritanceCss = "";
      const modeParams = this._getModeParams();
      for (const mode of Object.keys(modeParams)) {
        const params = modeParams[mode];
        if (mode !== defaultModeName) {
          const escapedMode = typeof CSS === "object" ? CSS.escape(mode) : mode;
          const wrapPrefix = `:where([data-ag-theme-mode="${escapedMode}"]) & {
`;
          variablesCss += wrapPrefix;
          inheritanceCss += wrapPrefix;
        }
        for (const key2 of Object.keys(params).sort()) {
          const value2 = params[key2];
          const cssValue = paramValueToCss(key2, value2, this.themeLogger);
          if (cssValue === false) {
            this.themeLogger.error(107, { key: key2, value: value2 });
          } else {
            const cssName = paramToVariableName(key2);
            const inheritedName = cssName.replace("--ag-", "--ag-inherited-");
            variablesCss += `	${cssName}: var(${inheritedName}, ${cssValue});
`;
            inheritanceCss += `	${inheritedName}: var(${cssName});
`;
          }
        }
        if (mode !== defaultModeName) {
          variablesCss += "}\n";
          inheritanceCss += "}\n";
        }
      }
      let css = `${selectorPlaceholder} {
${variablesCss}}
`;
      css += `:has(> ${selectorPlaceholder}):not(${selectorPlaceholder}) {
${inheritanceCss}}
`;
      this._paramsCssCache = innerParamsCss = css;
    }
    return innerParamsCss.replaceAll(selectorPlaceholder, `:where(.${className2})`);
  }
};
var deduplicatePartsByFeature = (parts) => {
  const lastPartByFeature = /* @__PURE__ */ new Map();
  for (const part of parts) {
    lastPartByFeature.set(part.feature, part);
  }
  const result2 = [];
  for (const part of parts) {
    if (!part.feature || lastPartByFeature.get(part.feature) === part) {
      result2.push(part);
    }
  }
  return result2;
};
var getGoogleFontsUsed = (theme) => {
  const googleFontsUsed = /* @__PURE__ */ new Set();
  const visitParamValue = (paramValue) => {
    if (Array.isArray(paramValue)) {
      paramValue.forEach(visitParamValue);
    } else {
      const googleFont = paramValue?.googleFont;
      if (typeof googleFont === "string") {
        googleFontsUsed.add(googleFont);
      }
    }
  };
  const allModeValues = Object.values(theme._getModeParams());
  const allValues = allModeValues.flatMap((mv) => Object.values(mv));
  allValues.forEach(visitParamValue);
  return Array.from(googleFontsUsed).sort();
};
var uninstalledLegacyCSS = false;
var uninstallLegacyCSS = () => {
  if (uninstalledLegacyCSS) {
    return;
  }
  uninstalledLegacyCSS = true;
  for (const style2 of Array.from(document.head.querySelectorAll('style[data-ag-scope="legacy"]'))) {
    style2.remove();
  }
};
var loadGoogleFont = async (font, nonce) => {
  const css = `@import url('https://${googleFontsDomain}/css2?family=${encodeURIComponent(font)}:wght@100;200;300;400;500;600;700;800;900&display=swap');
`;
  _injectGlobalCSS(css, document.head, `googleFont:${font}`, void 0, 0, nonce);
};
var googleFontsDomain = "fonts.googleapis.com";
var contextId = 1;
var AgContext = class {
  constructor(params) {
    this.beans = {};
    this.createdBeans = [];
    this.destroyed = false;
    this.instanceId = contextId++;
    if (!params?.beanClasses) {
      return;
    }
    this.beanDestroyComparator = params.beanDestroyComparator;
    this.init(params);
  }
  init(params) {
    this.id = params.id;
    this.beans.context = this;
    this.destroyCallback = params.destroyCallback;
    for (const beanName of Object.keys(params.providedBeanInstances)) {
      this.beans[beanName] = params.providedBeanInstances[beanName];
    }
    for (const BeanClass of params.beanClasses) {
      const instance2 = new BeanClass();
      if (instance2.beanName) {
        this.beans[instance2.beanName] = instance2;
      } else {
        console.error(`Bean ${BeanClass.name} is missing beanName`);
      }
      this.createdBeans.push(instance2);
    }
    for (const beanFunc of params.derivedBeans ?? []) {
      const { beanName, bean } = beanFunc(this);
      this.beans[beanName] = bean;
      this.createdBeans.push(bean);
    }
    if (params.beanInitComparator) {
      this.createdBeans.sort(params.beanInitComparator);
    }
    this.initBeans(this.createdBeans);
  }
  getBeanInstances() {
    return Object.values(this.beans);
  }
  createBean(bean, afterPreCreateCallback) {
    this.initBeans([bean], afterPreCreateCallback);
    return bean;
  }
  initBeans(beanInstances, afterPreCreateCallback) {
    const beans = this.beans;
    for (const instance2 of beanInstances) {
      instance2.preWireBeans?.(beans);
      instance2.wireBeans?.(beans);
    }
    for (const instance2 of beanInstances) {
      instance2.preConstruct?.();
    }
    if (afterPreCreateCallback) {
      beanInstances.forEach(afterPreCreateCallback);
    }
    for (const instance2 of beanInstances) {
      instance2.postConstruct?.();
    }
  }
  getBeans() {
    return this.beans;
  }
  getBean(name2) {
    return this.beans[name2];
  }
  getId() {
    return this.id;
  }
  destroy() {
    if (this.destroyed) {
      return;
    }
    this.destroyed = true;
    const beanInstances = this.getBeanInstances();
    if (this.beanDestroyComparator) {
      beanInstances.sort(this.beanDestroyComparator);
    }
    this.destroyBeans(beanInstances);
    this.beans = {};
    this.createdBeans = [];
    this.destroyCallback?.();
  }
  /**
   * Destroys a bean and returns undefined to support destruction and clean up in a single line.
   * this.dateComp = this.context.destroyBean(this.dateComp);
   */
  destroyBean(bean) {
    bean?.destroy?.();
  }
  /**
   * Destroys an array of beans and returns an empty array to support destruction and clean up in a single line.
   * this.dateComps = this.context.destroyBeans(this.dateComps);
   */
  destroyBeans(beans) {
    if (beans) {
      for (let i2 = 0; i2 < beans.length; i2++) {
        this.destroyBean(beans[i2]);
      }
    }
    return [];
  }
  isDestroyed() {
    return this.destroyed;
  }
};
var paramsId = 0;
var BaseEnvironment = class extends AgBeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "environment";
    this.paramsClass = `ag-theme-params-${++paramsId}`;
    this.globalCSS = [];
  }
  wireBeans(beans) {
    this.eRootDiv = beans.eRootDiv;
  }
  postConstruct() {
    const { gos, eRootDiv } = this;
    gos.setInstanceDomData(eRootDiv);
    this.eStyleContainer = gos.get("themeStyleContainer") ?? (eRootDiv.getRootNode() === document ? document.head : eRootDiv);
    this.cssLayer = gos.get("themeCssLayer");
    this.styleNonce = gos.get("styleNonce");
    this.addManagedPropertyListener("theme", () => this.handleThemeChange());
    this.handleThemeChange();
    this.initVariables();
    this.addDestroyFunc(() => _unregisterInstanceUsingThemingAPI(this));
    this.mutationObserver = new MutationObserver(() => {
      this.fireStylesChangedEvent("themeChanged");
    });
    this.addDestroyFunc(() => this.mutationObserver.disconnect());
  }
  applyThemeClasses(el, extraClasses = []) {
    const { theme } = this;
    let themeClass;
    if (theme) {
      themeClass = `${this.paramsClass} ${theme._getCssClass()}`;
    } else {
      themeClass = this.applyLegacyThemeClasses();
    }
    for (const className2 of Array.from(el.classList)) {
      if (className2.startsWith("ag-theme-")) {
        el.classList.remove(className2);
      }
    }
    if (themeClass) {
      const oldClass = el.className;
      el.className = `${oldClass}${oldClass ? " " : ""}${themeClass}${extraClasses?.length ? " " + extraClasses.join(" ") : ""}`;
    }
  }
  applyLegacyThemeClasses() {
    let themeClass = "";
    this.mutationObserver.disconnect();
    let node2 = this.eRootDiv;
    while (node2) {
      let isThemeEl = false;
      for (const className2 of Array.from(node2.classList)) {
        if (className2.startsWith("ag-theme-")) {
          isThemeEl = true;
          themeClass = themeClass ? `${themeClass} ${className2}` : className2;
        }
      }
      if (isThemeEl) {
        this.mutationObserver.observe(node2, {
          attributes: true,
          attributeFilter: ["class"]
        });
      }
      node2 = node2.parentElement;
    }
    return themeClass;
  }
  addGlobalCSS(css, debugId) {
    if (this.theme) {
      _injectGlobalCSS(css, this.eStyleContainer, debugId, this.cssLayer, 0, this.styleNonce);
    } else {
      this.globalCSS.push([css, debugId]);
    }
  }
  handleThemeChange() {
    const { gos, theme: oldTheme } = this;
    const themeProperty = gos.get("theme");
    let newTheme;
    if (themeProperty === "legacy") {
      newTheme = void 0;
    } else {
      const themeOrDefault = themeProperty ?? this.getDefaultTheme();
      if (themeOrDefault instanceof ThemeImpl) {
        newTheme = themeOrDefault;
      } else {
        this.themeError(themeOrDefault);
      }
    }
    if (newTheme !== oldTheme) {
      this.handleNewTheme(newTheme);
    }
    this.postProcessThemeChange(newTheme, themeProperty);
  }
  handleNewTheme(newTheme) {
    const { gos, eRootDiv, globalCSS } = this;
    const additionalCss = this.getAdditionalCss();
    if (newTheme) {
      _registerInstanceUsingThemingAPI(this);
      _injectCoreAndModuleCSS(this.eStyleContainer, this.cssLayer, this.styleNonce, additionalCss);
      for (const [css, debugId] of globalCSS) {
        _injectGlobalCSS(css, this.eStyleContainer, debugId, this.cssLayer, 0, this.styleNonce);
      }
      globalCSS.length = 0;
    }
    this.theme = newTheme;
    newTheme?._startUse({
      loadThemeGoogleFonts: gos.get("loadThemeGoogleFonts"),
      styleContainer: this.eStyleContainer,
      cssLayer: this.cssLayer,
      nonce: this.styleNonce,
      moduleCss: additionalCss
    });
    let eParamsStyle = this.eParamsStyle;
    if (!eParamsStyle) {
      eParamsStyle = this.eParamsStyle = _createAgElement({ tag: "style" });
      const styleNonce = gos.get("styleNonce");
      if (styleNonce) {
        eParamsStyle.setAttribute("nonce", styleNonce);
      }
      eRootDiv.appendChild(eParamsStyle);
    }
    if (!IS_SSR) {
      eParamsStyle.textContent = newTheme?._getPerInstanceCss(this.paramsClass) || "";
    }
    this.applyThemeClasses(eRootDiv);
    this.fireStylesChangedEvent("themeChanged");
  }
};
var BaseRegistry = class extends AgBeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "registry";
  }
  registerDynamicBeans(dynamicBeans) {
    if (dynamicBeans) {
      this.dynamicBeans ?? (this.dynamicBeans = {});
      for (const name2 of Object.keys(dynamicBeans)) {
        this.dynamicBeans[name2] = dynamicBeans[name2];
      }
    }
  }
  createDynamicBean(name2, mandatory, ...args2) {
    if (!this.dynamicBeans) {
      throw new Error(this.getDynamicError(name2, true));
    }
    const BeanClass = this.dynamicBeans[name2];
    if (BeanClass == null) {
      if (mandatory) {
        throw new Error(this.getDynamicError(name2, false));
      }
      return void 0;
    }
    return new BeanClass(...args2);
  }
};
var BaseEventService = class extends AgBeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "eventSvc";
    this.eventServiceType = "global";
    this.globalSvc = new LocalEventService();
  }
  addListener(eventType, listener, async) {
    this.globalSvc.addEventListener(eventType, listener, async);
  }
  removeListener(eventType, listener, async) {
    this.globalSvc.removeEventListener(eventType, listener, async);
  }
  addGlobalListener(listener, async = false) {
    this.globalSvc.addGlobalListener(listener, async);
  }
  removeGlobalListener(listener, async = false) {
    this.globalSvc.removeGlobalListener(listener, async);
  }
  dispatchEvent(event) {
    this.globalSvc.dispatchEvent(this.gos.addCommon(event));
  }
  dispatchEventOnce(event) {
    this.globalSvc.dispatchEventOnce(this.gos.addCommon(event));
  }
};
var AgTooltipFeature = class extends AgBeanStub {
  constructor(ctrl, beans) {
    super();
    this.ctrl = ctrl;
    if (beans) {
      this.beans = beans;
    }
  }
  postConstruct() {
    this.refreshTooltip();
  }
  /**
   *
   * @param tooltip The tooltip value
   * @param allowEmptyString Set it to true to allow the title to be set to `''`. This is necessary
   * when the browser adds a default tooltip the element and the tooltip service will be displayed
   * next to a browser tooltip causing confusion.
   */
  setBrowserTooltip(tooltip, allowEmptyString) {
    const name2 = "title";
    const eGui = this.ctrl.getGui();
    if (!eGui) {
      return;
    }
    if (tooltip != null && (tooltip != "" || allowEmptyString)) {
      eGui.setAttribute(name2, tooltip);
    } else {
      eGui.removeAttribute(name2);
    }
  }
  updateTooltipText() {
    const { getTooltipValue } = this.ctrl;
    if (getTooltipValue) {
      this.tooltip = getTooltipValue();
    }
  }
  createTooltipFeatureIfNeeded() {
    if (this.tooltipManager == null) {
      const tooltipManager = this.beans.registry.createDynamicBean("tooltipStateManager", true, this.ctrl, () => this.tooltip);
      if (tooltipManager) {
        this.tooltipManager = this.createBean(tooltipManager, this.beans.context);
      }
    }
  }
  attemptToShowTooltip() {
    this.tooltipManager?.prepareToShowTooltip();
  }
  attemptToHideTooltip() {
    this.tooltipManager?.hideTooltip();
  }
  setTooltipAndRefresh(tooltip) {
    this.tooltip = tooltip;
    this.refreshTooltip();
  }
  refreshTooltip(clearWithEmptyString) {
    this.browserTooltips = this.beans.gos.get("enableBrowserTooltips");
    this.updateTooltipText();
    if (this.browserTooltips) {
      this.setBrowserTooltip(this.tooltip);
      this.tooltipManager = this.destroyBean(this.tooltipManager, this.beans.context);
    } else {
      this.setBrowserTooltip(clearWithEmptyString ? "" : null, clearWithEmptyString);
      this.createTooltipFeatureIfNeeded();
    }
  }
  destroy() {
    this.tooltipManager = this.destroyBean(this.tooltipManager, this.beans.context);
    super.destroy();
  }
};
var SHOW_QUICK_TOOLTIP_DIFF = 1e3;
var FADE_OUT_TOOLTIP_TIMEOUT = 1e3;
var INTERACTIVE_HIDE_DELAY = 100;
var lastTooltipHideTime;
var isLocked = false;
var BaseTooltipStateManager = class extends AgBeanStub {
  constructor(tooltipCtrl, getTooltipValue) {
    super();
    this.tooltipCtrl = tooltipCtrl;
    this.getTooltipValue = getTooltipValue;
    this.interactionEnabled = false;
    this.isInteractingWithTooltip = false;
    this.state = 0;
    this.tooltipInstanceCount = 0;
    this.tooltipMouseTrack = false;
  }
  wireBeans(beans) {
    this.popupSvc = beans.popupSvc;
  }
  postConstruct() {
    if (this.gos.get("tooltipInteraction")) {
      this.interactionEnabled = true;
    }
    this.tooltipTrigger = this.getTooltipTrigger();
    this.tooltipMouseTrack = this.gos.get("tooltipMouseTrack");
    const el = this.tooltipCtrl.getGui();
    if (this.tooltipTrigger === 0) {
      this.addManagedListeners(el, {
        mouseenter: this.onMouseEnter.bind(this),
        mouseleave: this.onMouseLeave.bind(this)
      });
    }
    if (this.tooltipTrigger === 1) {
      this.addManagedListeners(el, {
        focusin: this.onFocusIn.bind(this),
        focusout: this.onFocusOut.bind(this)
      });
    }
    this.addManagedListeners(el, { mousemove: this.onMouseMove.bind(this) });
    if (!this.interactionEnabled) {
      this.addManagedListeners(el, {
        mousedown: this.onMouseDown.bind(this),
        keydown: this.onKeyDown.bind(this)
      });
    }
  }
  getGridOptionsTooltipDelay(delayOption) {
    const delay = this.gos.get(delayOption);
    return Math.max(200, delay);
  }
  getTooltipDelay(type) {
    if (type === "show") {
      return this.tooltipCtrl.getTooltipShowDelayOverride?.() ?? this.getGridOptionsTooltipDelay("tooltipShowDelay");
    }
    return this.tooltipCtrl.getTooltipHideDelayOverride?.() ?? this.getGridOptionsTooltipDelay("tooltipHideDelay");
  }
  destroy() {
    this.setToDoNothing();
    super.destroy();
  }
  getTooltipTrigger() {
    const trigger = this.gos.get("tooltipTrigger");
    if (!trigger || trigger === "hover") {
      return 0;
    }
    return 1;
  }
  onMouseEnter(e) {
    if (this.interactionEnabled && this.interactiveTooltipTimeoutId) {
      this.unlockService();
      this.startHideTimeout();
    }
    if (_isIOSUserAgent()) {
      return;
    }
    if (isLocked) {
      this.showTooltipTimeoutId = window.setTimeout(() => {
        this.prepareToShowTooltip(e);
      }, INTERACTIVE_HIDE_DELAY);
    } else {
      this.prepareToShowTooltip(e);
    }
  }
  onMouseMove(e) {
    if (this.lastMouseEvent) {
      this.lastMouseEvent = e;
    }
    if (this.tooltipMouseTrack && this.state === 2 && this.tooltipComp) {
      this.positionTooltip();
    }
  }
  onMouseDown() {
    this.setToDoNothing();
  }
  onMouseLeave() {
    if (this.interactionEnabled) {
      this.lockService();
    } else {
      this.setToDoNothing();
    }
  }
  onFocusIn() {
    this.prepareToShowTooltip();
  }
  onFocusOut(e) {
    const relatedTarget = e.relatedTarget;
    const parentCompGui = this.tooltipCtrl.getGui();
    const tooltipGui = this.tooltipComp?.getGui();
    if (this.isInteractingWithTooltip || parentCompGui.contains(relatedTarget) || this.interactionEnabled && tooltipGui?.contains(relatedTarget)) {
      return;
    }
    this.setToDoNothing();
  }
  onKeyDown() {
    if (this.isInteractingWithTooltip) {
      this.isInteractingWithTooltip = false;
    }
    this.setToDoNothing();
  }
  prepareToShowTooltip(mouseEvent) {
    if (this.state != 0 || isLocked) {
      return;
    }
    let delay = 0;
    if (mouseEvent) {
      delay = this.isLastTooltipHiddenRecently() ? 200 : this.getTooltipDelay("show");
    }
    this.lastMouseEvent = mouseEvent || null;
    this.showTooltipTimeoutId = window.setTimeout(this.showTooltip.bind(this), delay);
    this.state = 1;
  }
  isLastTooltipHiddenRecently() {
    const now2 = Date.now();
    const then = lastTooltipHideTime;
    return now2 - then < SHOW_QUICK_TOOLTIP_DIFF;
  }
  setToDoNothing(fromHideTooltip) {
    if (!fromHideTooltip && this.state === 2) {
      this.hideTooltip();
    }
    if (this.onBodyScrollEventCallback) {
      this.onBodyScrollEventCallback();
      this.onBodyScrollEventCallback = void 0;
    }
    this.clearEventHandlers();
    if (this.onDocumentKeyDownCallback) {
      this.onDocumentKeyDownCallback();
      this.onDocumentKeyDownCallback = void 0;
    }
    this.clearTimeouts();
    this.state = 0;
    this.lastMouseEvent = null;
  }
  showTooltip() {
    const value2 = this.getTooltipValue();
    const ctrl = this.tooltipCtrl;
    if (!_exists(value2) || ctrl.shouldDisplayTooltip && !ctrl.shouldDisplayTooltip()) {
      this.setToDoNothing();
      return;
    }
    const params = this.gos.addCommon({
      location: ctrl.getLocation?.() ?? "UNKNOWN",
      value: value2,
      hideTooltipCallback: () => this.hideTooltip(true),
      ...ctrl.getAdditionalParams?.()
    });
    this.state = 2;
    this.tooltipInstanceCount++;
    const callback = this.newTooltipComponentCallback.bind(this, this.tooltipInstanceCount);
    this.createTooltipComp(params, callback);
  }
  hideTooltip(forceHide) {
    if (!forceHide && this.isInteractingWithTooltip) {
      return;
    }
    if (this.tooltipComp) {
      this.destroyTooltipComp();
      lastTooltipHideTime = Date.now();
    }
    this.eventSvc.dispatchEvent({
      type: "tooltipHide",
      parentGui: this.tooltipCtrl.getGui()
    });
    if (forceHide) {
      this.isInteractingWithTooltip = false;
    }
    this.setToDoNothing(true);
  }
  newTooltipComponentCallback(tooltipInstanceCopy, tooltipComp) {
    const compNoLongerNeeded = this.state !== 2 || this.tooltipInstanceCount !== tooltipInstanceCopy;
    if (compNoLongerNeeded) {
      this.destroyBean(tooltipComp);
      return;
    }
    const eGui = tooltipComp.getGui();
    this.tooltipComp = tooltipComp;
    if (!eGui.classList.contains("ag-tooltip")) {
      eGui.classList.add("ag-tooltip-custom");
    }
    if (this.tooltipTrigger === 0) {
      eGui.classList.add("ag-tooltip-animate");
    }
    if (this.interactionEnabled) {
      eGui.classList.add("ag-tooltip-interactive");
    }
    const translate = this.getLocaleTextFunc();
    const addPopupRes = this.popupSvc?.addPopup({
      eChild: eGui,
      ariaLabel: translate("ariaLabelTooltip", "Tooltip")
    });
    if (addPopupRes) {
      this.tooltipPopupDestroyFunc = addPopupRes.hideFunc;
    }
    this.positionTooltip();
    if (this.tooltipTrigger === 1) {
      const listener = () => this.setToDoNothing();
      [this.onBodyScrollEventCallback] = this.addManagedEventListeners({
        bodyScroll: listener
      });
      this.setEventHandlers(listener);
    }
    if (this.interactionEnabled) {
      [this.tooltipMouseEnterListener, this.tooltipMouseLeaveListener] = this.addManagedElementListeners(eGui, {
        mouseenter: this.onTooltipMouseEnter.bind(this),
        mouseleave: this.onTooltipMouseLeave.bind(this)
      });
      [this.onDocumentKeyDownCallback] = this.addManagedElementListeners(_getDocument(this.beans), {
        keydown: (e) => {
          if (!eGui.contains(e?.target)) {
            this.onKeyDown();
          }
        }
      });
      if (this.tooltipTrigger === 1) {
        [this.tooltipFocusInListener, this.tooltipFocusOutListener] = this.addManagedElementListeners(eGui, {
          focusin: this.onTooltipFocusIn.bind(this),
          focusout: this.onTooltipFocusOut.bind(this)
        });
      }
    }
    this.eventSvc.dispatchEvent({
      type: "tooltipShow",
      tooltipGui: eGui,
      parentGui: this.tooltipCtrl.getGui()
    });
    this.startHideTimeout();
  }
  onTooltipMouseEnter() {
    this.isInteractingWithTooltip = true;
    this.unlockService();
  }
  onTooltipMouseLeave() {
    if (this.isTooltipFocused()) {
      return;
    }
    this.isInteractingWithTooltip = false;
    this.lockService();
  }
  onTooltipFocusIn() {
    this.isInteractingWithTooltip = true;
  }
  isTooltipFocused() {
    const tooltipGui = this.tooltipComp?.getGui();
    const activeEl = _getActiveDomElement(this.beans);
    return !!tooltipGui && tooltipGui.contains(activeEl);
  }
  onTooltipFocusOut(e) {
    const parentGui = this.tooltipCtrl.getGui();
    if (this.isTooltipFocused()) {
      return;
    }
    this.isInteractingWithTooltip = false;
    if (parentGui.contains(e.relatedTarget)) {
      this.startHideTimeout();
    } else {
      this.hideTooltip();
    }
  }
  positionTooltip() {
    const params = {
      type: "tooltip",
      ePopup: this.tooltipComp.getGui(),
      nudgeY: 18,
      skipObserver: this.tooltipMouseTrack
    };
    if (this.lastMouseEvent) {
      this.popupSvc?.positionPopupUnderMouseEvent({
        ...params,
        mouseEvent: this.lastMouseEvent
      });
    } else {
      this.popupSvc?.positionPopupByComponent({
        ...params,
        eventSource: this.tooltipCtrl.getGui(),
        position: "under",
        keepWithinBounds: true,
        nudgeY: 5
      });
    }
  }
  destroyTooltipComp() {
    this.tooltipComp.getGui().classList.add("ag-tooltip-hiding");
    const tooltipPopupDestroyFunc = this.tooltipPopupDestroyFunc;
    const tooltipComp = this.tooltipComp;
    const delay = this.tooltipTrigger === 0 ? FADE_OUT_TOOLTIP_TIMEOUT : 0;
    window.setTimeout(() => {
      tooltipPopupDestroyFunc();
      this.destroyBean(tooltipComp);
    }, delay);
    this.clearTooltipListeners();
    this.tooltipPopupDestroyFunc = void 0;
    this.tooltipComp = void 0;
  }
  clearTooltipListeners() {
    for (const listener of [
      this.tooltipMouseEnterListener,
      this.tooltipMouseLeaveListener,
      this.tooltipFocusInListener,
      this.tooltipFocusOutListener
    ]) {
      if (listener) {
        listener();
      }
    }
    this.tooltipMouseEnterListener = this.tooltipMouseLeaveListener = this.tooltipFocusInListener = this.tooltipFocusOutListener = null;
  }
  lockService() {
    isLocked = true;
    this.interactiveTooltipTimeoutId = window.setTimeout(() => {
      this.unlockService();
      this.setToDoNothing();
    }, INTERACTIVE_HIDE_DELAY);
  }
  unlockService() {
    isLocked = false;
    this.clearInteractiveTimeout();
  }
  startHideTimeout() {
    this.clearHideTimeout();
    this.hideTooltipTimeoutId = window.setTimeout(this.hideTooltip.bind(this), this.getTooltipDelay("hide"));
  }
  clearShowTimeout() {
    if (!this.showTooltipTimeoutId) {
      return;
    }
    window.clearTimeout(this.showTooltipTimeoutId);
    this.showTooltipTimeoutId = void 0;
  }
  clearHideTimeout() {
    if (!this.hideTooltipTimeoutId) {
      return;
    }
    window.clearTimeout(this.hideTooltipTimeoutId);
    this.hideTooltipTimeoutId = void 0;
  }
  clearInteractiveTimeout() {
    if (!this.interactiveTooltipTimeoutId) {
      return;
    }
    window.clearTimeout(this.interactiveTooltipTimeoutId);
    this.interactiveTooltipTimeoutId = void 0;
  }
  clearTimeouts() {
    this.clearShowTimeout();
    this.clearHideTimeout();
    this.clearInteractiveTimeout();
  }
};
var AgHighlightTooltipFeature = class extends AgTooltipFeature {
  constructor(ctrl, highlightTracker, beans) {
    super(ctrl, beans);
    this.highlightTracker = highlightTracker;
    this.onHighlight = this.onHighlight.bind(this);
  }
  postConstruct() {
    super.postConstruct();
    this.wireHighlightListeners();
  }
  wireHighlightListeners() {
    this.addManagedPropertyListener("tooltipTrigger", ({ currentValue }) => {
      this.setTooltipMode(currentValue);
    });
    this.setTooltipMode(this.gos.get("tooltipTrigger"));
    this.highlightTracker.addEventListener("itemHighlighted", this.onHighlight);
  }
  onHighlight(event) {
    if (this.tooltipMode !== 1) {
      return;
    }
    if (event.highlighted) {
      this.attemptToShowTooltip();
    } else {
      this.attemptToHideTooltip();
    }
  }
  setTooltipMode(tooltipTriggerMode = "focus") {
    this.tooltipMode = tooltipTriggerMode === "focus" ? 1 : 0;
  }
  destroy() {
    this.highlightTracker.removeEventListener("itemHighlighted", this.onHighlight);
    super.destroy();
  }
};
var instanceIdSeq = 0;
var WAIT_FOR_POPUP_CONTENT_RESIZE = 200;
var BasePopupService = class extends AgBeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "popupSvc";
    this.popupList = [];
  }
  getPopupParent() {
    const ePopupParent = this.gos.get("popupParent");
    if (ePopupParent) {
      return ePopupParent;
    }
    return this.getDefaultPopupParent();
  }
  positionPopupUnderMouseEvent(params) {
    const { ePopup, nudgeX, nudgeY, skipObserver } = params;
    this.positionPopup({
      ePopup,
      nudgeX,
      nudgeY,
      keepWithinBounds: true,
      skipObserver,
      updatePosition: () => this.calculatePointerAlign(params.mouseEvent),
      postProcessCallback: () => this.callPostProcessPopup(params, params.type, params.ePopup, null, params.mouseEvent)
    });
  }
  calculatePointerAlign(e) {
    const parentRect = this.getParentRect();
    return {
      x: e.clientX - parentRect.left,
      y: e.clientY - parentRect.top
    };
  }
  positionPopupByComponent(params) {
    const {
      ePopup,
      nudgeX,
      nudgeY,
      keepWithinBounds,
      eventSource,
      alignSide = "left",
      position = "over",
      type
    } = params;
    const sourceRect = eventSource.getBoundingClientRect();
    const parentRect = this.getParentRect();
    this.setAlignedTo(eventSource, ePopup);
    const updatePosition = () => {
      let x = sourceRect.left - parentRect.left;
      if (alignSide === "right") {
        x -= ePopup.offsetWidth - sourceRect.width;
      }
      let y;
      if (position === "over") {
        y = sourceRect.top - parentRect.top;
        this.setAlignedStyles(ePopup, "over");
      } else {
        this.setAlignedStyles(ePopup, "under");
        const alignSide2 = this.shouldRenderUnderOrAbove(ePopup, sourceRect, parentRect, params.nudgeY || 0);
        if (alignSide2 === "under") {
          y = sourceRect.top - parentRect.top + sourceRect.height;
        } else {
          y = sourceRect.top - ePopup.offsetHeight - (nudgeY || 0) * 2 - parentRect.top;
        }
      }
      return { x, y };
    };
    this.positionPopup({
      ePopup,
      nudgeX,
      nudgeY,
      keepWithinBounds,
      updatePosition,
      postProcessCallback: () => this.callPostProcessPopup(params, type, ePopup, eventSource, null)
    });
  }
  shouldRenderUnderOrAbove(ePopup, targetCompRect, parentRect, nudgeY) {
    const spaceAvailableUnder = parentRect.bottom - targetCompRect.bottom;
    const spaceAvailableAbove = targetCompRect.top - parentRect.top;
    const spaceRequired = ePopup.offsetHeight + nudgeY;
    if (spaceAvailableUnder > spaceRequired) {
      return "under";
    }
    if (spaceAvailableAbove > spaceRequired || spaceAvailableAbove > spaceAvailableUnder) {
      return "above";
    }
    return "under";
  }
  setAlignedStyles(ePopup, positioned) {
    const popupIdx = this.getPopupIndex(ePopup);
    if (popupIdx === -1) {
      return;
    }
    const popup = this.popupList[popupIdx];
    const { alignedToElement } = popup;
    if (!alignedToElement) {
      return;
    }
    const positions = ["right", "left", "over", "above", "under"];
    for (const position of positions) {
      alignedToElement.classList.remove(`ag-has-popup-positioned-${position}`);
      ePopup.classList.remove(`ag-popup-positioned-${position}`);
    }
    if (!positioned) {
      return;
    }
    alignedToElement.classList.add(`ag-has-popup-positioned-${positioned}`);
    ePopup.classList.add(`ag-popup-positioned-${positioned}`);
  }
  setAlignedTo(eventSource, ePopup) {
    const popupIdx = this.getPopupIndex(ePopup);
    if (popupIdx !== -1) {
      const popup = this.popupList[popupIdx];
      popup.alignedToElement = eventSource;
    }
  }
  positionPopup(params) {
    const { ePopup, keepWithinBounds, nudgeX, nudgeY, skipObserver, updatePosition } = params;
    const lastSize = { width: 0, height: 0 };
    const updatePopupPosition = (fromResizeObserver = false) => {
      let { x, y } = updatePosition();
      if (fromResizeObserver && ePopup.clientWidth === lastSize.width && ePopup.clientHeight === lastSize.height) {
        return;
      }
      lastSize.width = ePopup.clientWidth;
      lastSize.height = ePopup.clientHeight;
      if (nudgeX) {
        x += nudgeX;
      }
      if (nudgeY) {
        y += nudgeY;
      }
      if (keepWithinBounds) {
        x = this.keepXYWithinBounds(
          ePopup,
          x,
          1
          /* Horizontal */
        );
        y = this.keepXYWithinBounds(
          ePopup,
          y,
          0
          /* Vertical */
        );
      }
      ePopup.style.left = `${x}px`;
      ePopup.style.top = `${y}px`;
      if (params.postProcessCallback) {
        params.postProcessCallback();
      }
    };
    updatePopupPosition();
    if (!skipObserver) {
      const resizeObserverDestroyFunc = _observeResize(this.beans, ePopup, () => updatePopupPosition(true));
      setTimeout(() => resizeObserverDestroyFunc(), WAIT_FOR_POPUP_CONTENT_RESIZE);
    }
  }
  getParentRect() {
    const eDocument = _getDocument(this.beans);
    let popupParent = this.getPopupParent();
    if (popupParent === eDocument.body) {
      popupParent = eDocument.documentElement;
    } else if (getComputedStyle(popupParent).position === "static") {
      popupParent = popupParent.offsetParent;
    }
    return _getElementRectWithOffset(popupParent);
  }
  keepXYWithinBounds(ePopup, position, direction) {
    const isVertical = direction === 0;
    const sizeProperty = isVertical ? "clientHeight" : "clientWidth";
    const anchorProperty = isVertical ? "top" : "left";
    const offsetProperty = isVertical ? "height" : "width";
    const scrollPositionProperty = isVertical ? "scrollTop" : "scrollLeft";
    const eDocument = _getDocument(this.beans);
    const docElement = eDocument.documentElement;
    const popupParent = this.getPopupParent();
    const popupRect = ePopup.getBoundingClientRect();
    const parentRect = popupParent.getBoundingClientRect();
    const documentRect = eDocument.documentElement.getBoundingClientRect();
    const isBody = popupParent === eDocument.body;
    const offsetSize = Math.ceil(popupRect[offsetProperty]);
    const getSize2 = isVertical ? _getAbsoluteHeight : _getAbsoluteWidth;
    let sizeOfParent = isBody ? getSize2(docElement) + docElement[scrollPositionProperty] : popupParent[sizeProperty];
    if (isBody) {
      sizeOfParent -= Math.abs(documentRect[anchorProperty] - parentRect[anchorProperty]);
    }
    const max2 = sizeOfParent - offsetSize;
    return Math.min(Math.max(position, 0), Math.max(max2, 0));
  }
  addPopup(params) {
    const { eChild, ariaLabel, ariaOwns, alwaysOnTop, positionCallback, anchorToElement } = params;
    const pos2 = this.getPopupIndex(eChild);
    if (pos2 !== -1) {
      const popup = this.popupList[pos2];
      return { hideFunc: popup.hideFunc };
    }
    this.initialisePopupPosition(eChild);
    const wrapperEl = this.createPopupWrapper(eChild, !!alwaysOnTop, ariaLabel, ariaOwns);
    const removeListeners = this.addEventListenersToPopup({ ...params, wrapperEl });
    if (positionCallback) {
      positionCallback();
    }
    this.addPopupToPopupList(eChild, wrapperEl, removeListeners, anchorToElement);
    return {
      hideFunc: removeListeners
    };
  }
  initialisePopupPosition(element) {
    const ePopupParent = this.getPopupParent();
    const ePopupParentRect = ePopupParent.getBoundingClientRect();
    if (!_exists(element.style.top)) {
      element.style.top = `${ePopupParentRect.top * -1}px`;
    }
    if (!_exists(element.style.left)) {
      element.style.left = `${ePopupParentRect.left * -1}px`;
    }
  }
  createPopupWrapper(element, alwaysOnTop, ariaLabel, ariaOwns) {
    const ePopupParent = this.getPopupParent();
    const { environment, gos } = this.beans;
    const eWrapper = _createAgElement({ tag: "div" });
    environment.applyThemeClasses(eWrapper);
    eWrapper.classList.add("ag-popup");
    element.classList.add(gos.get("enableRtl") ? "ag-rtl" : "ag-ltr", "ag-popup-child");
    if (!element.hasAttribute("role")) {
      _setAriaRole(element, "dialog");
    }
    if (ariaLabel) {
      _setAriaLabel(element, ariaLabel);
    } else if (ariaOwns) {
      element.id || (element.id = `popup-component-${instanceIdSeq}`);
      _setAriaOwns(ariaOwns, element.id);
    }
    eWrapper.appendChild(element);
    ePopupParent.appendChild(eWrapper);
    if (alwaysOnTop) {
      this.setAlwaysOnTop(element, true);
    } else {
      this.bringPopupToFront(element);
    }
    return eWrapper;
  }
  addEventListenersToPopup(params) {
    const beans = this.beans;
    const eDocument = _getDocument(beans);
    const { wrapperEl, eChild: popupEl, closedCallback, afterGuiAttached, closeOnEsc, modal, ariaOwns } = params;
    let popupHidden = false;
    const hidePopupOnKeyboardEvent = (event) => {
      if (!wrapperEl.contains(_getActiveDomElement(beans))) {
        return;
      }
      const key2 = event.key;
      if (key2 === KeyCode.ESCAPE && !this.isStopPropagation(event)) {
        removeListeners({ keyboardEvent: event });
      }
    };
    const hidePopupOnMouseEvent = (event) => removeListeners({ mouseEvent: event });
    const hidePopupOnTouchEvent = (event) => removeListeners({ touchEvent: event });
    const removeListeners = (popupParams = {}) => {
      const { mouseEvent, touchEvent, keyboardEvent, forceHide } = popupParams;
      if (!forceHide && // we don't hide popup if the event was on the child, or any
      // children of this child
      (this.isEventFromCurrentPopup({ mouseEvent, touchEvent }, popupEl) || // this method should only be called once. the client can have different
      // paths, each one wanting to close, so this method may be called multiple times.
      popupHidden)) {
        return;
      }
      popupHidden = true;
      wrapperEl.remove();
      eDocument.removeEventListener("keydown", hidePopupOnKeyboardEvent);
      eDocument.removeEventListener("mousedown", hidePopupOnMouseEvent);
      eDocument.removeEventListener("touchstart", hidePopupOnTouchEvent);
      eDocument.removeEventListener("contextmenu", hidePopupOnMouseEvent);
      this.eventSvc.removeListener("dragStarted", hidePopupOnMouseEvent);
      if (closedCallback) {
        closedCallback(mouseEvent || touchEvent || keyboardEvent);
      }
      this.removePopupFromPopupList(popupEl, ariaOwns);
    };
    if (afterGuiAttached) {
      afterGuiAttached({ hidePopup: removeListeners });
    }
    window.setTimeout(() => {
      if (closeOnEsc) {
        eDocument.addEventListener("keydown", hidePopupOnKeyboardEvent);
      }
      if (modal) {
        eDocument.addEventListener("mousedown", hidePopupOnMouseEvent);
        this.eventSvc.addListener("dragStarted", hidePopupOnMouseEvent);
        eDocument.addEventListener("touchstart", hidePopupOnTouchEvent);
        eDocument.addEventListener("contextmenu", hidePopupOnMouseEvent);
      }
    }, 0);
    return removeListeners;
  }
  addPopupToPopupList(element, wrapperEl, removeListeners, anchorToElement) {
    this.popupList.push({
      element,
      wrapper: wrapperEl,
      hideFunc: removeListeners,
      instanceId: instanceIdSeq,
      isAnchored: !!anchorToElement
    });
    if (anchorToElement) {
      this.setPopupPositionRelatedToElement(element, anchorToElement);
    }
    instanceIdSeq = instanceIdSeq + 1;
  }
  getPopupIndex(el) {
    return this.popupList.findIndex((p) => p.element === el);
  }
  setPopupPositionRelatedToElement(popupEl, relativeElement) {
    const popupIndex = this.getPopupIndex(popupEl);
    if (popupIndex === -1) {
      return;
    }
    const popup = this.popupList[popupIndex];
    if (popup.stopAnchoringPromise) {
      popup.stopAnchoringPromise.then((destroyFunc) => destroyFunc && destroyFunc());
    }
    popup.stopAnchoringPromise = void 0;
    popup.isAnchored = false;
    if (!relativeElement) {
      return;
    }
    const destroyPositionTracker = this.keepPopupPositionedRelativeTo({
      element: relativeElement,
      ePopup: popupEl,
      hidePopup: popup.hideFunc
    });
    popup.stopAnchoringPromise = destroyPositionTracker;
    popup.isAnchored = true;
    return destroyPositionTracker;
  }
  removePopupFromPopupList(element, ariaOwns) {
    this.setAlignedStyles(element, null);
    this.setPopupPositionRelatedToElement(element, null);
    if (ariaOwns) {
      _setAriaOwns(ariaOwns, null);
    }
    this.popupList = this.popupList.filter((p) => p.element !== element);
  }
  keepPopupPositionedRelativeTo(params) {
    const eParent = this.getPopupParent();
    const parentRect = eParent.getBoundingClientRect();
    const { element, ePopup } = params;
    const sourceRect = element.getBoundingClientRect();
    const extractFromPixelValue = (pxSize) => Number.parseInt(pxSize.substring(0, pxSize.length - 1), 10);
    const createPosition = (prop, direction) => {
      const initialDiff = parentRect[prop] - sourceRect[prop];
      const initial = extractFromPixelValue(ePopup.style[prop]);
      return {
        initialDiff,
        lastDiff: initialDiff,
        initial,
        last: initial,
        direction
      };
    };
    const topPosition = createPosition(
      "top",
      0
      /* Vertical */
    );
    const leftPosition = createPosition(
      "left",
      1
      /* Horizontal */
    );
    const fwOverrides = this.beans.frameworkOverrides;
    return new AgPromise((resolve2) => {
      fwOverrides.wrapIncoming(() => {
        _wrapInterval(() => {
          const pRect = eParent.getBoundingClientRect();
          const sRect = element.getBoundingClientRect();
          const elementNotInDom = sRect.top == 0 && sRect.left == 0 && sRect.height == 0 && sRect.width == 0;
          if (elementNotInDom) {
            params.hidePopup();
            return;
          }
          const calculateNewPosition = (position, prop) => {
            const current3 = extractFromPixelValue(ePopup.style[prop]);
            if (position.last !== current3) {
              position.initial = current3;
              position.last = current3;
            }
            const currentDiff = pRect[prop] - sRect[prop];
            if (currentDiff != position.lastDiff) {
              const newValue = this.keepXYWithinBounds(
                ePopup,
                position.initial + position.initialDiff - currentDiff,
                position.direction
              );
              ePopup.style[prop] = `${newValue}px`;
              position.last = newValue;
            }
            position.lastDiff = currentDiff;
          };
          calculateNewPosition(topPosition, "top");
          calculateNewPosition(leftPosition, "left");
        }, 200).then((intervalId) => {
          const result2 = () => {
            if (intervalId != null) {
              window.clearInterval(intervalId);
            }
          };
          resolve2(result2);
        });
      }, "popupPositioning");
    });
  }
  isEventFromCurrentPopup(params, target) {
    const { mouseEvent, touchEvent } = params;
    const event = mouseEvent ? mouseEvent : touchEvent;
    if (!event) {
      return false;
    }
    const indexOfThisChild = this.getPopupIndex(target);
    if (indexOfThisChild === -1) {
      return false;
    }
    for (let i2 = indexOfThisChild; i2 < this.popupList.length; i2++) {
      const popup = this.popupList[i2];
      if (_isElementInEventPath(popup.element, event)) {
        return true;
      }
    }
    return this.isElementWithinCustomPopup(event.target);
  }
  isElementWithinCustomPopup(el) {
    const eDocument = _getDocument(this.beans);
    while (el && el !== eDocument.body) {
      if (el.classList.contains("ag-custom-component-popup") || el.parentElement === null) {
        return true;
      }
      el = el.parentElement;
    }
    return false;
  }
  getWrapper(ePopup) {
    while (!ePopup.classList.contains("ag-popup") && ePopup.parentElement) {
      ePopup = ePopup.parentElement;
    }
    return ePopup.classList.contains("ag-popup") ? ePopup : null;
  }
  setAlwaysOnTop(ePopup, alwaysOnTop) {
    const eWrapper = this.getWrapper(ePopup);
    if (!eWrapper) {
      return;
    }
    eWrapper.classList.toggle("ag-always-on-top", !!alwaysOnTop);
    if (alwaysOnTop) {
      this.bringPopupToFront(eWrapper);
    }
  }
  /** @returns true if moved */
  bringPopupToFront(ePopup) {
    const parent = this.getPopupParent();
    const popupList = Array.prototype.slice.call(parent.querySelectorAll(".ag-popup"));
    const popupLen = popupList.length;
    const eWrapper = this.getWrapper(ePopup);
    if (!eWrapper || popupLen <= 1 || !parent.contains(ePopup)) {
      return;
    }
    const standardPopupList = [];
    const alwaysOnTopList = [];
    for (const popup of popupList) {
      if (popup === eWrapper) {
        continue;
      }
      if (popup.classList.contains("ag-always-on-top")) {
        alwaysOnTopList.push(popup);
      } else {
        standardPopupList.push(popup);
      }
    }
    const innerElsScrollMap = [];
    const onTopLength = alwaysOnTopList.length;
    const isPopupAlwaysOnTop = eWrapper.classList.contains("ag-always-on-top");
    const shouldBeLast = isPopupAlwaysOnTop || !onTopLength;
    const targetList = shouldBeLast ? [...standardPopupList, ...alwaysOnTopList, eWrapper] : [...standardPopupList, eWrapper, ...alwaysOnTopList];
    for (let i2 = 0; i2 <= popupLen; i2++) {
      const currentPopup = targetList[i2];
      if (popupList[i2] === targetList[i2] || currentPopup === eWrapper) {
        continue;
      }
      const innerEls = currentPopup.querySelectorAll("div");
      for (const el of innerEls) {
        if (el.scrollTop !== 0) {
          innerElsScrollMap.push([el, el.scrollTop]);
        }
      }
      if (i2 === 0) {
        parent.insertAdjacentElement("afterbegin", currentPopup);
      } else {
        targetList[i2 - 1].insertAdjacentElement("afterend", currentPopup);
      }
    }
    while (innerElsScrollMap.length) {
      const currentEl = innerElsScrollMap.pop();
      currentEl[0].scrollTop = currentEl[1];
    }
  }
};
var AgTooltipComponent = class extends AgPopupComponent {
  constructor() {
    super({ tag: "div", cls: "ag-tooltip" });
  }
  // will need to type params
  init(params) {
    const { value: value2 } = params;
    const eGui = this.getGui();
    eGui.textContent = _toString(value2);
    const locationKebabCase = params.location.replace(/([a-z])([A-Z0-9])/g, "$1-$2").toLowerCase();
    eGui.classList.add(`ag-${locationKebabCase}-tooltip`);
  }
};
var tryPointerCapture = (eElement, pointerId) => {
  if (pointerId != null && eElement?.setPointerCapture) {
    try {
      eElement.setPointerCapture(pointerId);
      return eElement.hasPointerCapture(pointerId);
    } catch {
    }
  }
  return false;
};
var capturePointer = (eElement, mouseEvent) => {
  if (typeof PointerEvent === "undefined" || !(mouseEvent instanceof PointerEvent)) {
    return null;
  }
  const pointerId = mouseEvent.pointerId;
  if (!tryPointerCapture(eElement, pointerId)) {
    return null;
  }
  const capture = {
    eElement,
    pointerId,
    onLost(pointerEvent) {
      pointerLostHandler(capture, pointerEvent);
    }
  };
  eElement.addEventListener("lostpointercapture", capture.onLost);
  return capture;
};
var releasePointerCapture = (capture) => {
  if (!capture) {
    return;
  }
  removeLostHandler(capture);
  const { eElement, pointerId } = capture;
  if (!eElement) {
    return;
  }
  try {
    eElement.releasePointerCapture(pointerId);
  } catch {
  }
  capture.eElement = null;
};
var removeLostHandler = (capture) => {
  const { eElement, onLost } = capture;
  if (eElement && onLost) {
    eElement.removeEventListener("lostpointercapture", onLost);
    capture.onLost = null;
  }
};
var pointerLostHandler = (capture, pointerEvent) => {
  removeLostHandler(capture);
  const { eElement, pointerId } = capture;
  if (eElement && pointerEvent.pointerId === pointerId) {
    tryPointerCapture(eElement, pointerId);
  }
};
var activePointerDrags;
var handledDragEvents;
var addHandledDragEvent = (event) => {
  if (!handledDragEvents) {
    handledDragEvents = /* @__PURE__ */ new WeakSet();
  } else if (handledDragEvents.has(event)) {
    return false;
  }
  handledDragEvents.add(event);
  return true;
};
var BaseDragService = class extends AgBeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "dragSvc";
    this.dragging = false;
    this.drag = null;
    this.dragSources = [];
  }
  get startTarget() {
    return this.drag?.start.target ?? null;
  }
  /** True if there is at least one active pointer drag in any BaseDragService instance in the page */
  isPointer() {
    return !!activePointerDrags?.has(_getRootNode(this.beans));
  }
  hasPointerCapture() {
    const capture = this.drag?.pointerCapture;
    return !!(capture && this.beans.eRootDiv.hasPointerCapture?.(capture.pointerId));
  }
  destroy() {
    if (this.drag) {
      this.cancelDrag();
    }
    const dragSources = this.dragSources;
    for (const entry2 of dragSources) {
      destroyDragSourceEntry(entry2);
    }
    dragSources.length = 0;
    super.destroy();
  }
  removeDragSource(params) {
    const dragSources = this.dragSources;
    for (let i2 = 0, len = dragSources.length; i2 < len; ++i2) {
      const entry2 = dragSources[i2];
      if (entry2.params === params) {
        dragSources.splice(i2, 1);
        destroyDragSourceEntry(entry2);
        break;
      }
    }
  }
  addDragSource(params) {
    if (!this.isAlive()) {
      return;
    }
    const { eElement, includeTouch } = params;
    const handlers = [];
    let oldTouchAction;
    if (includeTouch) {
      const style2 = eElement.style;
      if (style2) {
        oldTouchAction = style2.touchAction;
        style2.touchAction = "none";
      }
    }
    const dragSource = { handlers, params, oldTouchAction };
    this.dragSources.push(dragSource);
    const pointerDownListener = (event) => this.onPointerDown(params, event);
    const mouseListener = (event) => this.onMouseDown(params, event);
    addTempEventHandlers(
      handlers,
      [eElement, "pointerdown", pointerDownListener, { passive: false }],
      [eElement, "mousedown", mouseListener]
    );
    const suppressTouch = this.gos.get("suppressTouch");
    if (includeTouch && !suppressTouch) {
      const touchListener = (touchEvent) => this.onTouchStart(params, touchEvent);
      addTempEventHandlers(handlers, [eElement, "touchstart", touchListener, { passive: false }]);
    }
  }
  cancelDrag(eElement) {
    const drag = this.drag;
    eElement ?? (eElement = drag?.eElement);
    if (eElement) {
      this.eventSvc.dispatchEvent({ type: "dragCancelled", target: eElement });
    }
    drag?.params.onDragCancel?.();
    this.destroyDrag();
  }
  shouldPreventMouseEvent(mouseEvent) {
    const type = mouseEvent.type;
    const isMouseMove = type === "mousemove" || type === "pointermove";
    return isMouseMove && mouseEvent.cancelable && _isEventFromThisInstance(this.beans, mouseEvent) && !_isFocusableFormField(getEventTargetElement(mouseEvent));
  }
  initDrag(drag, ...handlers) {
    this.drag = drag;
    const beans = this.beans;
    const onScroll = (event) => this.onScroll(event);
    const keydownEvent = (ev) => this.onKeyDown(ev);
    const rootEl = _getRootNode(beans);
    const eDocument = _getDocument(beans);
    addTempEventHandlers(
      drag.handlers,
      [rootEl, "contextmenu", preventEventDefault],
      [rootEl, "keydown", keydownEvent],
      [eDocument, "scroll", onScroll, { capture: true }],
      [eDocument.defaultView || window, "scroll", onScroll],
      ...handlers
    );
  }
  destroyDrag() {
    this.dragging = false;
    const drag = this.drag;
    if (drag) {
      const rootEl = drag.rootEl;
      if (activePointerDrags?.get(rootEl) === drag) {
        activePointerDrags?.delete(rootEl);
      }
      this.drag = null;
      releasePointerCapture(drag.pointerCapture);
      clearTempEventHandlers(drag.handlers);
    }
  }
  // Pointer Events path (preferred when supported)
  onPointerDown(params, pointerEvent) {
    if (this.isPointer()) {
      return;
    }
    const beans = this.beans;
    if (handledDragEvents?.has(pointerEvent)) {
      return;
    }
    const pointerType = pointerEvent.pointerType;
    if (pointerType === "touch") {
      if (beans.gos.get("suppressTouch") || !params.includeTouch) {
        return;
      }
      if (params.stopPropagationForTouch) {
        pointerEvent.stopPropagation();
      }
      if (_isFocusableFormField(getEventTargetElement(pointerEvent))) {
        return;
      }
    }
    if (!pointerEvent.isPrimary) {
      return;
    }
    if (pointerType === "mouse" && pointerEvent.button !== 0) {
      return;
    }
    this.destroyDrag();
    const rootEl = _getRootNode(beans);
    const eElement = params.eElement;
    const pointerId = pointerEvent.pointerId;
    const pointerDrag = new Dragging(rootEl, params, pointerEvent, pointerId);
    activePointerDrags ?? (activePointerDrags = /* @__PURE__ */ new WeakMap());
    activePointerDrags.set(rootEl, pointerDrag);
    const onPointerMove = (ev) => {
      if (ev.pointerId === pointerId) {
        this.onMouseOrPointerMove(ev);
      }
    };
    const onUp = (ev) => {
      if (ev.pointerId === pointerId) {
        this.onMouseOrPointerUp(ev);
      }
    };
    const onCancel = (ev) => {
      if (ev.pointerId === pointerId && addHandledDragEvent(ev)) {
        this.cancelDrag();
      }
    };
    this.initDrag(
      pointerDrag,
      [rootEl, "pointerup", onUp],
      [rootEl, "pointercancel", onCancel],
      [rootEl, "pointermove", onPointerMove, { passive: false }],
      [rootEl, "touchmove", preventEventDefault, { passive: false }],
      [eElement, "mousemove", preventEventDefault, { passive: false }]
    );
    if (params.dragStartPixels === 0) {
      this.onMouseOrPointerMove(pointerEvent);
    } else {
      addHandledDragEvent(pointerEvent);
    }
  }
  // gets called whenever mouse down on any drag source
  onTouchStart(params, touchEvent) {
    const suppressTouch = this.gos.get("suppressTouch");
    if (suppressTouch || !params.includeTouch) {
      return;
    }
    if (!addHandledDragEvent(touchEvent)) {
      return;
    }
    if (_isFocusableFormField(getEventTargetElement(touchEvent))) {
      return;
    }
    if (params.stopPropagationForTouch) {
      touchEvent.stopPropagation();
    }
    if (this.isPointer()) {
      preventEventDefault(touchEvent);
      return;
    }
    this.destroyDrag();
    const beans = this.beans;
    const rootEl = _getRootNode(beans);
    const touchDrag = new Dragging(rootEl, params, touchEvent.touches[0]);
    const touchMoveEvent = (e) => this.onTouchMove(e);
    const touchEndEvent = (e) => this.onTouchUp(e);
    const target = touchEvent.target ?? params.eElement;
    this.initDrag(
      touchDrag,
      [_getRootNode(beans), "touchmove", preventEventDefault, { passive: false }],
      [target, "touchmove", touchMoveEvent, { passive: true }],
      [target, "touchend", touchEndEvent, { passive: true }],
      [target, "touchcancel", touchEndEvent, { passive: true }]
    );
    if (params.dragStartPixels === 0) {
      this.onMove(touchDrag.start);
    }
  }
  // gets called whenever mouse down on any drag source
  onMouseDown(params, mouseEvent) {
    if (mouseEvent.button !== 0) {
      return;
    }
    if (handledDragEvents?.has(mouseEvent)) {
      return;
    }
    if (this.isPointer()) {
      return;
    }
    const beans = this.beans;
    this.destroyDrag();
    const mouseDrag = new Dragging(_getRootNode(beans), params, mouseEvent);
    const mouseMoveEvent = (event) => this.onMouseOrPointerMove(event);
    const mouseUpEvent = (event) => this.onMouseOrPointerUp(event);
    const target = _getRootNode(beans);
    this.initDrag(mouseDrag, [target, "mousemove", mouseMoveEvent], [target, "mouseup", mouseUpEvent]);
    if (params.dragStartPixels === 0) {
      this.onMouseOrPointerMove(mouseEvent);
    } else {
      addHandledDragEvent(mouseEvent);
    }
  }
  onScroll(event) {
    if (!addHandledDragEvent(event)) {
      return;
    }
    const drag = this.drag;
    const lastDrag = drag?.lastDrag;
    if (lastDrag && this.dragging) {
      drag.params?.onDragging(lastDrag);
    }
  }
  /** only gets called after a mouse down - as this is only added after mouseDown and is removed when mouseUp happens */
  onMouseOrPointerMove(mouseEvent) {
    if (!addHandledDragEvent(mouseEvent)) {
      return;
    }
    if (_isBrowserSafari()) {
      _getDocument(this.beans).getSelection()?.removeAllRanges();
    }
    if (this.shouldPreventMouseEvent(mouseEvent)) {
      preventEventDefault(mouseEvent);
    }
    this.onMove(mouseEvent);
  }
  onTouchMove(touchEvent) {
    const drag = this.drag;
    if (!drag || !addHandledDragEvent(touchEvent)) {
      return;
    }
    const touch = _getFirstActiveTouch(drag.start, touchEvent.touches);
    if (touch) {
      touchEvent.preventDefault();
      this.onMove(touch);
    }
  }
  onMove(currentEvent) {
    const drag = this.drag;
    if (!drag) {
      return;
    }
    drag.lastDrag = currentEvent;
    const dragSource = drag.params;
    if (!this.dragging) {
      const start2 = drag.start;
      const dragStartPixels = dragSource.dragStartPixels;
      const requiredPixelDiff = dragStartPixels ?? 4;
      if (_areEventsNear(currentEvent, start2, requiredPixelDiff)) {
        return;
      }
      this.dragging = true;
      if (dragSource.capturePointer) {
        drag.pointerCapture = capturePointer(this.beans.eRootDiv, currentEvent);
      }
      this.eventSvc.dispatchEvent({
        type: "dragStarted",
        target: dragSource.eElement
      });
      dragSource.onDragStart(start2);
      if (this.drag !== drag) {
        return;
      }
      dragSource.onDragging(start2);
      if (this.drag !== drag) {
        return;
      }
    }
    dragSource.onDragging(currentEvent);
  }
  onTouchUp(touchEvent) {
    const drag = this.drag;
    if (drag && addHandledDragEvent(touchEvent)) {
      this.onUp(_getFirstActiveTouch(drag.start, touchEvent.changedTouches));
    }
  }
  onMouseOrPointerUp(mouseEvent) {
    if (addHandledDragEvent(mouseEvent)) {
      this.onUp(mouseEvent);
    }
  }
  onUp(eventOrTouch) {
    const drag = this.drag;
    if (!drag) {
      return;
    }
    if (!eventOrTouch) {
      eventOrTouch = drag.lastDrag;
    }
    if (eventOrTouch && this.dragging) {
      this.dragging = false;
      drag.params.onDragStop(eventOrTouch);
      this.eventSvc.dispatchEvent({
        type: "dragStopped",
        target: drag.params.eElement
      });
    }
    this.destroyDrag();
  }
  // shared keydown handler to cancel current drag with ESC
  onKeyDown(event) {
    if (event.key === KeyCode.ESCAPE) {
      this.cancelDrag();
    }
  }
};
var destroyDragSourceEntry = (dragSource) => {
  clearTempEventHandlers(dragSource.handlers);
  const oldTouchAction = dragSource.oldTouchAction;
  if (oldTouchAction != null) {
    const style2 = dragSource.params.eElement.style;
    if (style2) {
      style2.touchAction = oldTouchAction;
    }
  }
};
var Dragging = class {
  constructor(rootEl, params, start2, pointerId = null) {
    this.rootEl = rootEl;
    this.params = params;
    this.start = start2;
    this.pointerId = pointerId;
    this.handlers = [];
    this.lastDrag = null;
    this.pointerCapture = null;
    this.eElement = params.eElement;
  }
};
var getEventTargetElement = (event) => {
  const target = event.target;
  return target instanceof Element ? target : null;
};
var BaseDragAndDropService = class extends AgBeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "dragAndDrop";
    this.dragSourceAndParamsList = [];
    this.dragItem = null;
    this.dragInitialSourcePointerOffsetX = 0;
    this.dragInitialSourcePointerOffsetY = 0;
    this.lastMouseEvent = null;
    this.lastDraggingEvent = null;
    this.dragSource = null;
    this.dragImageParent = null;
    this.dragImageCompPromise = null;
    this.dragImageComp = null;
    this.dragImageLastIcon = void 0;
    this.dragImageLastLabel = void 0;
    this.dropTargets = [];
    this.lastDropTarget = null;
  }
  addDragSource(dragSource, allowTouch = false) {
    const entry2 = {
      capturePointer: true,
      dragSource,
      eElement: dragSource.eElement,
      dragStartPixels: dragSource.dragStartPixels,
      onDragStart: (mouseEvent) => this.onDragStart(dragSource, mouseEvent),
      onDragStop: this.onDragStop.bind(this),
      onDragging: this.onDragging.bind(this),
      onDragCancel: this.onDragCancel.bind(this),
      includeTouch: allowTouch
    };
    this.dragSourceAndParamsList.push(entry2);
    this.beans.dragSvc.addDragSource(entry2);
  }
  setDragImageCompIcon(iconName, shake = false) {
    const component = this.dragImageComp;
    if (component && (shake || this.dragImageLastIcon !== iconName)) {
      this.dragImageLastIcon = iconName;
      component.setIcon(iconName, shake);
    }
  }
  removeDragSource(dragSource) {
    const { dragSourceAndParamsList, beans } = this;
    const sourceAndParams = dragSourceAndParamsList.find((item2) => item2.dragSource === dragSource);
    if (sourceAndParams) {
      beans.dragSvc?.removeDragSource(sourceAndParams);
      _removeFromArray(dragSourceAndParamsList, sourceAndParams);
    }
  }
  destroy() {
    const { dragSourceAndParamsList, dropTargets, beans } = this;
    const dragSvc = beans.dragSvc;
    for (const sourceAndParams of dragSourceAndParamsList) {
      dragSvc?.removeDragSource(sourceAndParams);
    }
    dragSourceAndParamsList.length = 0;
    dropTargets.length = 0;
    this.clearDragAndDropProperties();
    super.destroy();
  }
  nudge() {
    const lastMouseEvent = this.lastMouseEvent;
    if (lastMouseEvent) {
      this.onDragging(lastMouseEvent, true);
    }
  }
  onDragStart(dragSource, mouseEvent) {
    this.lastMouseEvent = mouseEvent;
    this.dragSource = dragSource;
    this.dragItem = dragSource.getDragItem();
    const rect = dragSource.eElement.getBoundingClientRect();
    this.dragInitialSourcePointerOffsetX = mouseEvent.clientX - rect.left;
    this.dragInitialSourcePointerOffsetY = mouseEvent.clientY - rect.top;
    dragSource.onDragStarted?.();
    this.createAndUpdateDragImageComp(dragSource);
  }
  onDragStop(mouseEvent) {
    const { dragSource, lastDropTarget } = this;
    dragSource?.onDragStopped?.();
    if (lastDropTarget) {
      const dragEndEvent = this.dropTargetEvent(lastDropTarget, mouseEvent, false);
      lastDropTarget.onDragStop?.(dragEndEvent);
    }
    this.clearDragAndDropProperties();
  }
  onDragCancel() {
    const { dragSource, lastDropTarget, lastMouseEvent } = this;
    dragSource?.onDragCancelled?.();
    if (lastDropTarget && lastMouseEvent) {
      const dragCancelEvent = this.dropTargetEvent(lastDropTarget, lastMouseEvent, false);
      lastDropTarget.onDragCancel?.(dragCancelEvent);
    }
    this.clearDragAndDropProperties();
  }
  onDragging(mouseEvent, fromNudge = false) {
    this.positionDragImageComp(mouseEvent);
    const dropTarget = this.findCurrentDropTarget(mouseEvent);
    const { lastDropTarget, dragSource, dragItem } = this;
    let needUpdate = false;
    if (dropTarget !== lastDropTarget) {
      needUpdate = true;
      if (lastDropTarget) {
        const dragLeaveEvent = this.dropTargetEvent(lastDropTarget, mouseEvent, fromNudge);
        lastDropTarget.onDragLeave?.(dragLeaveEvent);
      }
      if (lastDropTarget !== null && !dropTarget) {
        this.handleExit(dragSource, dragItem);
      } else if (lastDropTarget === null && dropTarget) {
        this.handleEnter(dragSource, dragItem);
      }
      if (dropTarget) {
        const dragEnterEvent = this.dropTargetEvent(dropTarget, mouseEvent, fromNudge);
        dropTarget.onDragEnter?.(dragEnterEvent);
      }
      this.lastDropTarget = dropTarget;
    } else if (dropTarget) {
      const dragMoveEvent = this.dropTargetEvent(dropTarget, mouseEvent, fromNudge);
      dropTarget.onDragging?.(dragMoveEvent);
      if (dragMoveEvent?.changed) {
        needUpdate = true;
      }
    }
    this.lastMouseEvent = mouseEvent;
    if (needUpdate) {
      this.updateDragImageComp();
    }
  }
  clearDragAndDropProperties() {
    this.removeDragImageComp(this.dragImageComp);
    this.dragImageCompPromise = null;
    this.dragImageParent = null;
    this.dragImageLastIcon = void 0;
    this.dragImageLastLabel = void 0;
    this.lastMouseEvent = null;
    this.lastDraggingEvent = null;
    this.lastDropTarget = null;
    this.dragItem = null;
    this.dragInitialSourcePointerOffsetX = 0;
    this.dragInitialSourcePointerOffsetY = 0;
    this.dragSource = null;
  }
  getAllContainersFromDropTarget(dropTarget) {
    const secondaryContainers = dropTarget.getSecondaryContainers ? dropTarget.getSecondaryContainers() : null;
    const containers = [[dropTarget.getContainer()]];
    return secondaryContainers ? containers.concat(secondaryContainers) : containers;
  }
  // checks if the mouse is on the drop target. it checks eContainer and eSecondaryContainers
  isMouseOnDropTarget(mouseEvent, dropTarget) {
    const allContainersFromDropTarget = this.getAllContainersFromDropTarget(dropTarget);
    let mouseOverTarget = false;
    const allContainersIntersect = (mouseEvent2, containers) => {
      for (const container2 of containers) {
        const { width, height, left: left2, right: right2, top: top2, bottom: bottom2 } = container2.getBoundingClientRect();
        if (width === 0 || height === 0) {
          return false;
        }
        const horizontalFit = mouseEvent2.clientX >= left2 && mouseEvent2.clientX < right2;
        const verticalFit = mouseEvent2.clientY >= top2 && mouseEvent2.clientY < bottom2;
        if (!horizontalFit || !verticalFit) {
          return false;
        }
      }
      return true;
    };
    for (const currentContainers of allContainersFromDropTarget) {
      if (allContainersIntersect(mouseEvent, currentContainers)) {
        mouseOverTarget = true;
        break;
      }
    }
    const { eElement, type } = this.dragSource;
    if (dropTarget.targetContainsSource && !dropTarget.getContainer().contains(eElement)) {
      return false;
    }
    return mouseOverTarget && dropTarget.isInterestedIn(type, eElement);
  }
  findCurrentDropTarget(mouseEvent) {
    const validDropTargets = this.dropTargets.filter((target) => this.isMouseOnDropTarget(mouseEvent, target));
    const len = validDropTargets.length;
    if (len === 0) {
      return null;
    }
    if (len === 1) {
      return validDropTargets[0];
    }
    const rootNode = _getRootNode(this.beans);
    const elementStack = rootNode.elementsFromPoint(mouseEvent.clientX, mouseEvent.clientY);
    for (const el of elementStack) {
      for (const dropTarget of validDropTargets) {
        const containers = this.getAllContainersFromDropTarget(dropTarget).flatMap((a2) => a2);
        if (containers.indexOf(el) !== -1) {
          return dropTarget;
        }
      }
    }
    return null;
  }
  addDropTarget(dropTarget) {
    this.dropTargets.push(dropTarget);
  }
  removeDropTarget(dropTarget) {
    this.dropTargets = this.dropTargets.filter((target) => target.getContainer() !== dropTarget.getContainer());
  }
  hasExternalDropZones() {
    return this.dropTargets.some((zones) => zones.external);
  }
  findExternalZone(container2) {
    return this.dropTargets.find((zone) => zone.external && zone.getContainer() === container2) || null;
  }
  dropTargetEvent(dropTarget, mouseEvent, fromNudge) {
    const {
      dragSource,
      dragItem,
      lastDraggingEvent,
      lastMouseEvent,
      dragInitialSourcePointerOffsetX,
      dragInitialSourcePointerOffsetY
    } = this;
    const dropZoneTarget = dropTarget.getContainer();
    const rect = dropZoneTarget.getBoundingClientRect();
    const { clientX, clientY } = mouseEvent;
    const xDir = clientX - (lastMouseEvent?.clientX || 0);
    const yDir = clientY - (lastMouseEvent?.clientY || 0);
    const draggingEvent = this.createEvent({
      event: mouseEvent,
      x: clientX - rect.left,
      // relative x
      y: clientY - rect.top,
      // relative y
      vDirection: yDir > 0 ? "down" : yDir < 0 ? "up" : null,
      hDirection: xDir < 0 ? "left" : xDir > 0 ? "right" : null,
      initialSourcePointerOffsetX: dragInitialSourcePointerOffsetX,
      initialSourcePointerOffsetY: dragInitialSourcePointerOffsetY,
      dragSource,
      fromNudge,
      dragItem,
      dropZoneTarget,
      dropTarget: lastDraggingEvent?.dropTarget ?? null,
      // updated by rowDragFeature
      changed: !!lastDraggingEvent?.changed
    });
    this.lastDraggingEvent = draggingEvent;
    return draggingEvent;
  }
  positionDragImageComp(event) {
    const gui = this.dragImageComp?.getGui();
    if (gui) {
      _anchorElementToMouseMoveEvent(gui, event, this.beans);
    }
  }
  removeDragImageComp(comp) {
    if (this.dragImageComp === comp) {
      this.dragImageComp = null;
    }
    if (comp) {
      comp.getGui()?.remove();
      this.destroyBean(comp);
    }
  }
  createAndUpdateDragImageComp(dragSource) {
    const promise = this.createDragImageComp(dragSource) ?? null;
    this.dragImageCompPromise = promise;
    promise?.then((dragImageComp) => {
      if (promise !== this.dragImageCompPromise || !this.lastMouseEvent || !this.isAlive()) {
        this.destroyBean(dragImageComp);
        return;
      }
      this.dragImageCompPromise = null;
      this.dragImageLastIcon = void 0;
      this.dragImageLastLabel = void 0;
      const oldDragImageComp = this.dragImageComp;
      if (oldDragImageComp !== dragImageComp) {
        this.dragImageComp = dragImageComp;
        this.removeDragImageComp(oldDragImageComp);
      }
      if (dragImageComp) {
        this.appendDragImageComp(dragImageComp);
        this.updateDragImageComp();
      }
    });
  }
  appendDragImageComp(component) {
    const eGui = component.getGui();
    const style2 = eGui.style;
    style2.position = "absolute";
    style2.zIndex = "9999";
    if (this.beans.dragSvc?.hasPointerCapture()) {
      style2.pointerEvents = "none";
    }
    this.gos.setInstanceDomData(eGui);
    this.beans.environment.applyThemeClasses(eGui);
    style2.top = "20px";
    style2.left = "20px";
    const targetEl = _getPageBody(this.beans);
    this.dragImageParent = targetEl;
    if (!targetEl) {
      this.warnNoBody();
    } else {
      targetEl.appendChild(eGui);
    }
  }
  updateDragImageComp() {
    const { dragImageComp, dragSource, lastDropTarget, lastDraggingEvent, dragImageLastLabel } = this;
    if (!dragImageComp) {
      return;
    }
    this.setDragImageCompIcon(lastDropTarget?.getIconName?.(lastDraggingEvent) ?? null);
    let label2 = dragSource?.dragItemName;
    if (typeof label2 === "function") {
      label2 = label2(lastDraggingEvent);
    }
    label2 || (label2 = "");
    if (dragImageLastLabel !== label2) {
      this.dragImageLastLabel = label2;
      dragImageComp.setLabel(label2);
    }
  }
};
var DragAndDropService = class extends BaseDragAndDropService {
  createEvent(event) {
    return _addGridCommonParams(this.gos, event);
  }
  createDragImageComp(dragSource) {
    const { gos, beans } = this;
    const userCompDetails = _getDragAndDropImageCompDetails(
      beans.userCompFactory,
      _addGridCommonParams(gos, {
        dragSource
      })
    );
    return userCompDetails?.newAgStackInstance();
  }
  handleEnter(dragSource, dragItem) {
    dragSource?.onGridEnter?.(dragItem);
  }
  handleExit(dragSource, dragItem) {
    dragSource?.onGridExit?.(dragItem);
  }
  warnNoBody() {
    _warn(54);
  }
  isDropZoneWithinThisGrid(draggingEvent) {
    return this.beans.ctrlsSvc.getGridBodyCtrl().eGridBody.contains(draggingEvent.dropZoneTarget);
  }
  registerGridDropTarget(elementFn, ctrl) {
    const dropTarget = {
      getContainer: elementFn,
      isInterestedIn: (type) => type === 1 || type === 0,
      getIconName: () => "notAllowed"
    };
    this.addDropTarget(dropTarget);
    ctrl.addDestroyFunc(() => this.removeDropTarget(dropTarget));
  }
};
function createUniqueColumnGroupId(groupId, instanceId) {
  return groupId + "_" + instanceId;
}
function isColumnGroup(col) {
  return col instanceof AgColumnGroup;
}
var AgColumnGroup = class extends BeanStub {
  constructor(providedColumnGroup, groupId, partId, pinned) {
    super();
    this.providedColumnGroup = providedColumnGroup;
    this.groupId = groupId;
    this.partId = partId;
    this.pinned = pinned;
    this.isColumn = false;
    this.displayedChildren = [];
    this.autoHeaderHeight = null;
    this.parent = null;
    this.colIdSanitised = _escapeString(this.getUniqueId());
  }
  // as the user is adding and removing columns, the groups are recalculated.
  // this reset clears out all children, ready for children to be added again
  reset() {
    this.parent = null;
    this.children = null;
    this.displayedChildren = null;
  }
  getParent() {
    return this.parent;
  }
  getUniqueId() {
    return createUniqueColumnGroupId(this.groupId, this.partId);
  }
  isEmptyGroup() {
    return this.displayedChildren.length === 0;
  }
  isMoving() {
    const allLeafColumns = this.getProvidedColumnGroup().getLeafColumns();
    if (!allLeafColumns || allLeafColumns.length === 0) {
      return false;
    }
    return allLeafColumns.every((col) => col.isMoving());
  }
  checkLeft() {
    for (const child of this.displayedChildren) {
      if (isColumnGroup(child)) {
        child.checkLeft();
      }
    }
    if (this.displayedChildren.length > 0) {
      if (this.gos.get("enableRtl")) {
        const lastChild = _last(this.displayedChildren);
        const lastChildLeft = lastChild.getLeft();
        this.setLeft(lastChildLeft);
      } else {
        const firstChildLeft = this.displayedChildren[0].getLeft();
        this.setLeft(firstChildLeft);
      }
    } else {
      this.setLeft(null);
    }
  }
  getLeft() {
    return this.left;
  }
  getOldLeft() {
    return this.oldLeft;
  }
  setLeft(left2) {
    this.oldLeft = this.left;
    if (this.left !== left2) {
      this.left = left2;
      this.dispatchLocalEvent({ type: "leftChanged" });
    }
  }
  getPinned() {
    return this.pinned;
  }
  getGroupId() {
    return this.groupId;
  }
  getPartId() {
    return this.partId;
  }
  getActualWidth() {
    let groupActualWidth = 0;
    for (const child of this.displayedChildren ?? []) {
      groupActualWidth += child.getActualWidth();
    }
    return groupActualWidth;
  }
  isResizable() {
    if (!this.displayedChildren) {
      return false;
    }
    let result2 = false;
    for (const child of this.displayedChildren) {
      if (child.isResizable()) {
        result2 = true;
      }
    }
    return result2;
  }
  getMinWidth() {
    let result2 = 0;
    for (const groupChild of this.displayedChildren) {
      result2 += groupChild.getMinWidth();
    }
    return result2;
  }
  addChild(child) {
    if (!this.children) {
      this.children = [];
    }
    this.children.push(child);
  }
  getDisplayedChildren() {
    return this.displayedChildren;
  }
  getLeafColumns() {
    const result2 = [];
    this.addLeafColumns(result2);
    return result2;
  }
  getDisplayedLeafColumns() {
    const result2 = [];
    this.addDisplayedLeafColumns(result2);
    return result2;
  }
  getDefinition() {
    return this.providedColumnGroup.getColGroupDef();
  }
  getColGroupDef() {
    return this.providedColumnGroup.getColGroupDef();
  }
  isPadding() {
    return this.providedColumnGroup.isPadding();
  }
  isExpandable() {
    return this.providedColumnGroup.isExpandable();
  }
  isExpanded() {
    return this.providedColumnGroup.isExpanded();
  }
  setExpanded(expanded) {
    this.providedColumnGroup.setExpanded(expanded);
  }
  isAutoHeaderHeight() {
    return !!this.getColGroupDef()?.autoHeaderHeight;
  }
  getAutoHeaderHeight() {
    return this.autoHeaderHeight;
  }
  /** Returns true if the header height has changed */
  setAutoHeaderHeight(height) {
    const changed = height !== this.autoHeaderHeight;
    this.autoHeaderHeight = height;
    return changed;
  }
  addDisplayedLeafColumns(leafColumns) {
    for (const child of this.displayedChildren ?? []) {
      if (isColumn(child)) {
        leafColumns.push(child);
      } else if (isColumnGroup(child)) {
        child.addDisplayedLeafColumns(leafColumns);
      }
    }
  }
  addLeafColumns(leafColumns) {
    for (const child of this.children ?? []) {
      if (isColumn(child)) {
        leafColumns.push(child);
      } else if (isColumnGroup(child)) {
        child.addLeafColumns(leafColumns);
      }
    }
  }
  getChildren() {
    return this.children;
  }
  getColumnGroupShow() {
    return this.providedColumnGroup.getColumnGroupShow();
  }
  getProvidedColumnGroup() {
    return this.providedColumnGroup;
  }
  getPaddingLevel() {
    const parent = this.getParent();
    if (!this.isPadding() || !parent?.isPadding()) {
      return 0;
    }
    return 1 + parent.getPaddingLevel();
  }
  calculateDisplayedColumns() {
    this.displayedChildren = [];
    let parentWithExpansion = this;
    while (parentWithExpansion?.isPadding()) {
      parentWithExpansion = parentWithExpansion.getParent();
    }
    const isExpandable = parentWithExpansion ? parentWithExpansion.getProvidedColumnGroup().isExpandable() : false;
    if (!isExpandable) {
      this.displayedChildren = this.children;
      this.dispatchLocalEvent({ type: "displayedChildrenChanged" });
      return;
    }
    for (const child of this.children ?? []) {
      const emptyGroup = isColumnGroup(child) && !child.displayedChildren?.length;
      if (emptyGroup) {
        continue;
      }
      const headerGroupShow = child.getColumnGroupShow();
      switch (headerGroupShow) {
        case "open":
          if (parentWithExpansion.getProvidedColumnGroup().isExpanded()) {
            this.displayedChildren.push(child);
          }
          break;
        case "closed":
          if (!parentWithExpansion.getProvidedColumnGroup().isExpanded()) {
            this.displayedChildren.push(child);
          }
          break;
        default:
          this.displayedChildren.push(child);
          break;
      }
    }
    this.dispatchLocalEvent({ type: "displayedChildrenChanged" });
  }
};
var ROW_ID_PREFIX_ROW_GROUP = "row-group-";
var ROW_ID_PREFIX_TOP_PINNED = "t-";
var ROW_ID_PREFIX_BOTTOM_PINNED = "b-";
var OBJECT_ID_SEQUENCE = 0;
var RowNode = class {
  constructor(beans) {
    this.master = false;
    this.detail = void 0;
    this.rowIndex = null;
    this.key = null;
    this.sourceRowIndex = -1;
    this._leafs = void 0;
    this.childrenMapped = null;
    this.treeParent = null;
    this.treeNodeFlags = 0;
    this.displayed = false;
    this.rowTop = null;
    this.oldRowTop = null;
    this.selectable = true;
    this.__objectId = OBJECT_ID_SEQUENCE++;
    this.alreadyRendered = false;
    this.hovered = false;
    this.__selected = false;
    this.beans = beans;
  }
  /** CSRM only - do not use this property internally, this is exposed to the end user only. Use `_leafs` instead. */
  get allLeafChildren() {
    const leafs = this._leafs;
    return leafs === void 0 ? this.beans.groupStage?.loadLeafs?.(this) ?? null : leafs;
  }
  set allLeafChildren(value2) {
    this._leafs = value2;
  }
  /**
   * Replaces the data on the `rowNode`. When this method is called, the grid refreshes the entire rendered row if it is displayed.
   */
  setData(data2) {
    this.setDataCommon(data2, false);
  }
  // similar to setRowData, however it is expected that the data is the same data item. this
  // is intended to be used with Redux type stores, where the whole data can be changed. we are
  // guaranteed that the data is the same entity (so grid doesn't need to worry about the id of the
  // underlying data changing, hence doesn't need to worry about selection). the grid, upon receiving
  // dataChanged event, refreshes the cells rather than rip them all out (so user can show transitions).
  /**
   * Updates the data on the `rowNode`. When this method is called, the grid refreshes the entire rendered row if it is displayed.
   */
  updateData(data2) {
    this.setDataCommon(data2, true);
  }
  setDataCommon(data2, update2) {
    const { valueCache, eventSvc } = this.beans;
    const oldData = this.data;
    this.data = data2;
    valueCache?.onDataChanged();
    this.updateDataOnDetailNode();
    this.resetQuickFilterAggregateText();
    const event = this.createDataChangedEvent(data2, oldData, update2);
    this.__localEventService?.dispatchEvent(event);
    if (this.sibling) {
      this.sibling.data = data2;
      const event2 = this.sibling.createDataChangedEvent(data2, oldData, update2);
      this.sibling.__localEventService?.dispatchEvent(event2);
    }
    eventSvc.dispatchEvent({ type: "rowNodeDataChanged", node: this });
    const pinnedSibling = this.pinnedSibling;
    if (pinnedSibling) {
      pinnedSibling.data = data2;
      pinnedSibling.__localEventService?.dispatchEvent(
        pinnedSibling.createDataChangedEvent(data2, oldData, update2)
      );
      eventSvc.dispatchEvent({ type: "rowNodeDataChanged", node: pinnedSibling });
    }
  }
  // when we are doing master / detail, the detail node is lazy created, but then kept around.
  // so if we show / hide the detail, the same detail rowNode is used. so we need to keep the data
  // in sync, otherwise expand/collapse of the detail would still show the old values.
  updateDataOnDetailNode() {
    const detailNode = this.detailNode;
    if (detailNode) {
      detailNode.data = this.data;
    }
  }
  createDataChangedEvent(newData, oldData, update2) {
    return {
      type: "dataChanged",
      node: this,
      oldData,
      newData,
      update: update2
    };
  }
  getRowIndexString() {
    if (this.rowIndex == null) {
      _error(13);
      return null;
    }
    if (this.rowPinned === "top") {
      return ROW_ID_PREFIX_TOP_PINNED + this.rowIndex;
    }
    if (this.rowPinned === "bottom") {
      return ROW_ID_PREFIX_BOTTOM_PINNED + this.rowIndex;
    }
    return this.rowIndex.toString();
  }
  setDataAndId(data2, id2) {
    const { selectionSvc } = this.beans;
    const oldNode = selectionSvc?.createDaemonNode?.(this);
    const oldData = this.data;
    this.data = data2;
    this.updateDataOnDetailNode();
    this.setId(id2);
    if (selectionSvc) {
      selectionSvc.updateRowSelectable(this);
      selectionSvc.syncInRowNode(this, oldNode);
    }
    const event = this.createDataChangedEvent(data2, oldData, false);
    this.__localEventService?.dispatchEvent(event);
  }
  setId(id2) {
    const getRowIdFunc = _getRowIdCallback(this.beans.gos);
    if (getRowIdFunc) {
      if (this.data) {
        const parentKeys = this.parent?.getRoute() ?? [];
        this.id = getRowIdFunc({
          data: this.data,
          parentKeys: parentKeys.length > 0 ? parentKeys : void 0,
          level: this.level,
          rowPinned: this.rowPinned
        });
        if (this.id.startsWith(ROW_ID_PREFIX_ROW_GROUP)) {
          _error(14, {
            groupPrefix: ROW_ID_PREFIX_ROW_GROUP
          });
        }
      } else {
        this.id = void 0;
      }
    } else {
      this.id = id2;
    }
  }
  setRowTop(rowTop) {
    this.oldRowTop = this.rowTop;
    if (this.rowTop === rowTop) {
      return;
    }
    this.rowTop = rowTop;
    this.dispatchRowEvent("topChanged");
    const displayed = rowTop !== null;
    if (this.displayed !== displayed) {
      this.displayed = displayed;
      this.dispatchRowEvent("displayedChanged");
    }
  }
  clearRowTopAndRowIndex() {
    this.oldRowTop = null;
    this.setRowTop(null);
    this.setRowIndex(null);
  }
  setHovered(hovered) {
    this.hovered = hovered;
  }
  isHovered() {
    return this.hovered;
  }
  /**
   * Sets the row height.
   * Call if you want to change the height initially assigned to the row.
   * After calling, you must call `api.onRowHeightChanged()` so the grid knows it needs to work out the placement of the rows. */
  setRowHeight(rowHeight, estimated = false) {
    this.rowHeight = rowHeight;
    this.rowHeightEstimated = estimated;
    this.dispatchRowEvent("heightChanged");
  }
  setExpanded(expanded, e, forceSync) {
    this.beans.expansionSvc?.setExpanded(this, expanded, e, forceSync);
  }
  /**
   * Replaces the value on the `rowNode` for the specified column. When complete,
   * the grid refreshes the rendered cell on the required row only.
   * **Note**: This method only fires `onCellEditRequest` when the Grid is in **Read Only** mode.
   * **Note**: This method defers to EditModule if available and batches the edit when `fullRow` or `batchEdit` is enabled.
   *
   * @param colKey The column where the value should be updated
   * @param newValue The new value
   * @param eventSource The source of the event
   * @returns `true` if the value was changed, otherwise `false`.
   */
  setDataValue(colKey, newValue, eventSource) {
    const { colModel, valueSvc, gos, editSvc } = this.beans;
    const column2 = typeof colKey !== "string" ? colKey : colModel.getCol(colKey) ?? colModel.getColDefCol(colKey);
    if (!column2) {
      return false;
    }
    const oldValue = valueSvc.getValueForDisplay(column2, this, void 0, void 0, "api").value;
    if (gos.get("readOnlyEdit")) {
      const {
        beans: { eventSvc },
        data: data2,
        rowIndex,
        rowPinned
      } = this;
      eventSvc.dispatchEvent({
        type: "cellEditRequest",
        event: null,
        rowIndex,
        rowPinned,
        column: column2,
        colDef: column2.colDef,
        data: data2,
        node: this,
        oldValue,
        newValue,
        value: newValue,
        source: eventSource
      });
      return false;
    }
    if (editSvc && !editSvc.committing) {
      const result2 = editSvc.setDataValue({ rowNode: this, column: column2 }, newValue, eventSource);
      if (result2 != null) {
        return result2;
      }
    }
    const valueChanged = valueSvc.setValue(this, column2, newValue, eventSource);
    this.dispatchCellChangedEvent(column2, newValue, oldValue);
    if (valueChanged) {
      this.pinnedSibling?.dispatchCellChangedEvent(column2, newValue, oldValue);
    }
    return valueChanged;
  }
  updateHasChildren() {
    let newValue = this.group && !this.footer || !!this.childrenAfterGroup?.length;
    const { rowChildrenSvc } = this.beans;
    if (rowChildrenSvc) {
      newValue = rowChildrenSvc.getHasChildrenValue(this);
    }
    if (newValue !== this.__hasChildren) {
      this.__hasChildren = !!newValue;
      this.dispatchRowEvent("hasChildrenChanged");
    }
  }
  hasChildren() {
    if (this.__hasChildren == null) {
      this.updateHasChildren();
    }
    return this.__hasChildren;
  }
  dispatchCellChangedEvent(column2, newValue, oldValue) {
    const cellChangedEvent = {
      type: "cellChanged",
      node: this,
      column: column2,
      newValue,
      oldValue
    };
    this.__localEventService?.dispatchEvent(cellChangedEvent);
  }
  /**
   * The first time `quickFilter` runs, the grid creates a one-off string representation of the row.
   * This string is then used for the quick filter instead of hitting each column separately.
   * When you edit, using grid editing, this string gets cleared down.
   * However, if you edit without using grid editing, you need to clear this string down for the row to be updated with the new values.
   * Otherwise, new values would not work with the `quickFilter`. */
  resetQuickFilterAggregateText() {
    this.quickFilterAggregateText = null;
  }
  /** Returns:
   * - `true` if the node can be expanded, i.e it is a group or master row.
   * - `false` if the node cannot be expanded
   */
  isExpandable() {
    return this.beans.expansionSvc?.isExpandable(this) ?? false;
  }
  /** Returns:
   * - `true` if node is selected,
   * - `false` if the node isn't selected
   * - `undefined` if it's partially selected (group where not all children are selected). */
  isSelected() {
    if (this.footer) {
      return this.sibling.isSelected();
    }
    const pinnedSibling = this.rowPinned && this.pinnedSibling;
    if (pinnedSibling) {
      return pinnedSibling.isSelected();
    }
    return this.__selected;
  }
  /** Perform a depth-first search of this node and its children. */
  depthFirstSearch(callback) {
    const childrenAfterGroup = this.childrenAfterGroup;
    if (childrenAfterGroup) {
      for (let i2 = 0, len = childrenAfterGroup.length; i2 < len; ++i2) {
        childrenAfterGroup[i2].depthFirstSearch(callback);
      }
    }
    callback(this);
  }
  dispatchRowEvent(type) {
    this.__localEventService?.dispatchEvent({
      type,
      node: this
    });
  }
  /**
   * Select (or deselect) the node.
   * @param newValue -`true` for selection, `false` for deselection.
   * @param clearSelection - If selecting, then passing `true` selects the node exclusively (i.e. NOT do multi select). If doing deselection, `clearSelection` has no impact.
   * @param source - Source property that appears in the `selectionChanged` event.
   */
  setSelected(newValue, clearSelection = false, source2 = "api") {
    this.beans.selectionSvc?.setNodesSelected({
      nodes: [this],
      newValue,
      clearSelection,
      source: source2
    });
  }
  /**
   * Returns:
   * - `true` if node is either pinned to the `top` or `bottom`
   * - `false` if the node isn't pinned
   */
  isRowPinned() {
    return !!this.rowPinned;
  }
  __addEventListener(eventType, listener) {
    const localEventService = this.__localEventService ?? (this.__localEventService = new LocalEventService());
    localEventService.addEventListener(eventType, listener);
  }
  __removeEventListener(eventType, listener) {
    this.removeLocalListener(eventType, listener);
  }
  /**
   * PUBLIC USE ONLY: for internal use within AG Grid use the `__addEventListener` and `__removeEventListener` methods.
   */
  addEventListener(eventType, userListener) {
    this.beans.validation?.checkRowEvents(eventType);
    const localEventService = this.__localEventService ?? (this.__localEventService = new LocalEventService());
    this.frameworkEventListenerService = this.beans.frameworkOverrides.createLocalEventListenerWrapper?.(
      this.frameworkEventListenerService,
      localEventService
    );
    const listener = this.frameworkEventListenerService?.wrap(eventType, userListener) ?? userListener;
    localEventService.addEventListener(eventType, listener);
  }
  /**
   * PUBLIC USE ONLY: for internal use within AG Grid use the `__addEventListener` and `__removeEventListener` methods.
   */
  removeEventListener(eventType, userListener) {
    const listener = this.frameworkEventListenerService?.unwrap(eventType, userListener) ?? userListener;
    this.removeLocalListener(eventType, listener);
  }
  removeLocalListener(eventType, listener) {
    const localEventService = this.__localEventService;
    if (localEventService) {
      localEventService.removeEventListener(eventType, listener);
      if (localEventService.noRegisteredListenersExist()) {
        this.__localEventService = null;
      }
    }
  }
  /**
   * @deprecated v32.2.0 Check `node.detail` then user provided callback `isFullWidthRow` instead.
   *
   * Returns:
   * - `true` if the node is a full width cell
   * - `false` if the node is not a full width cell
   */
  isFullWidthCell() {
    _warn(61);
    if (this.detail) {
      return true;
    }
    const isFullWidthCellFunc = this.beans.gos.getCallback("isFullWidthRow");
    return isFullWidthCellFunc ? isFullWidthCellFunc({ rowNode: this }) : false;
  }
  /**
   * Returns the route of keys to the row node. Returns undefined if the node has no key.
   */
  getRoute() {
    if (this.level === -1) {
      return [];
    }
    if (this.key == null) {
      return void 0;
    }
    const res = [];
    let pointer = this;
    while (pointer?.key != null) {
      res.push(pointer.key);
      pointer = pointer.parent;
    }
    return res.reverse();
  }
  setRowIndex(rowIndex) {
    if (this.rowIndex !== rowIndex) {
      this.rowIndex = rowIndex;
      this.dispatchRowEvent("rowIndexChanged");
    }
  }
  setAllChildrenCount(allChildrenCount) {
    if (this.allChildrenCount !== allChildrenCount) {
      this.allChildrenCount = allChildrenCount;
      this.dispatchRowEvent("allChildrenCountChanged");
    }
  }
  setUiLevel(uiLevel) {
    if (this.uiLevel !== uiLevel) {
      this.uiLevel = uiLevel;
      this.dispatchRowEvent("uiLevelChanged");
    }
  }
  getFirstChild() {
    const childStore = this.childStore;
    if (childStore) {
      return childStore.getFirstNode();
    }
    return this.childrenAfterSort?.[0] ?? null;
  }
};
function _createGlobalRowEvent(rowNode, gos, type) {
  return _addGridCommonParams(gos, {
    type,
    node: rowNode,
    data: rowNode.data,
    rowIndex: rowNode.rowIndex,
    rowPinned: rowNode.rowPinned
  });
}
var IGNORED_SIBLING_PROPERTIES = /* @__PURE__ */ new Set([
  "__autoHeights",
  "__checkAutoHeightsDebounced",
  "__localEventService",
  "__objectId",
  "_leafs",
  "childStore",
  "oldRowTop",
  "sticky",
  "treeNodeFlags",
  "treeParent"
]);
var _createRowNodeSibling = (rowNode, beans) => {
  const sibling2 = new RowNode(beans);
  for (const key2 of Object.keys(rowNode)) {
    if (IGNORED_SIBLING_PROPERTIES.has(key2)) {
      continue;
    }
    sibling2[key2] = rowNode[key2];
  }
  sibling2.oldRowTop = null;
  return sibling2;
};
var _firstLeaf = (childrenAfterGroup) => {
  while (childrenAfterGroup?.length) {
    const node2 = childrenAfterGroup[0];
    if (node2.data) {
      return node2;
    }
    childrenAfterGroup = node2.childrenAfterGroup;
  }
};
var FILTER_HANDLER_MAP = {
  agSetColumnFilter: "agSetColumnFilterHandler",
  agMultiColumnFilter: "agMultiColumnFilterHandler",
  agGroupColumnFilter: "agGroupColumnFilterHandler",
  agNumberColumnFilter: "agNumberColumnFilterHandler",
  agDateColumnFilter: "agDateColumnFilterHandler",
  agTextColumnFilter: "agTextColumnFilterHandler"
};
var FILTER_HANDLERS = new Set(Object.values(FILTER_HANDLER_MAP));
function getFilterUiFromWrapper(filterWrapper, skipCreate) {
  const filterUi = filterWrapper.filterUi;
  if (!filterUi) {
    return null;
  }
  if (filterUi.created) {
    return filterUi.promise;
  }
  if (skipCreate) {
    return null;
  }
  const promise = filterUi.create(filterUi.refreshed);
  const createdFilterUi = filterUi;
  createdFilterUi.created = true;
  createdFilterUi.promise = promise;
  return promise;
}
function _refreshHandlerAndUi(getFilterUi, handler, handlerParams, model2, state, source2, additionalEventAttributes) {
  handler.refresh?.({ ...handlerParams, model: model2, source: source2, additionalEventAttributes });
  return getFilterUi().then((filterUi) => {
    if (filterUi) {
      const { filter: filter2, filterParams } = filterUi;
      _refreshFilterUi(filter2, filterParams, model2, state, source2, additionalEventAttributes);
    }
  });
}
function _refreshFilterUi(filter2, filterParams, model2, state, source2, additionalEventAttributes) {
  filter2?.refresh?.({
    ...filterParams,
    model: model2,
    state,
    source: source2,
    additionalEventAttributes
  });
}
function getAndRefreshFilterUi(getFilterUi, getModel, getState2) {
  const filterUi = getFilterUi();
  if (filterUi?.created) {
    filterUi.promise.then((filter2) => {
      const model2 = getModel();
      _refreshFilterUi(filter2, filterUi.filterParams, model2, getState2() ?? { model: model2 }, "ui");
    });
  }
}
function _updateFilterModel(action, getFilterUi, getModel, getState2, updateState, updateModel, processModelToApply) {
  let state;
  let shouldUpdateModel = false;
  let model2;
  switch (action) {
    case "apply": {
      const oldState = getState2();
      model2 = oldState?.model ?? null;
      if (processModelToApply) {
        model2 = processModelToApply(model2);
      }
      state = {
        // keep the other UI state
        state: oldState?.state,
        model: model2
      };
      shouldUpdateModel = true;
      break;
    }
    case "clear": {
      state = {
        // wipe other UI state
        model: null
      };
      break;
    }
    case "reset": {
      state = {
        // wipe other UI state
        model: null
      };
      shouldUpdateModel = true;
      model2 = null;
      break;
    }
    case "cancel": {
      state = {
        // wipe other UI state
        model: getModel()
      };
      break;
    }
  }
  updateState(state);
  if (shouldUpdateModel) {
    updateModel(model2);
  } else {
    getAndRefreshFilterUi(getFilterUi, getModel, getState2);
  }
}
function _getFilterModel(model2, colId) {
  return model2[colId] ?? null;
}
function _createElement(params) {
  return _createAgElement(params);
}
function getElement(className2) {
  return {
    tag: "div",
    cls: className2
  };
}
var FilterButtonComp = class extends Component {
  constructor(config2) {
    const { className: className2 = "ag-filter-apply-panel" } = config2 ?? {};
    super(getElement(className2));
    this.listeners = [];
    this.validationMessage = null;
    this.className = className2;
  }
  updateButtons(buttons, useForm) {
    const oldButtons = this.buttons;
    this.buttons = buttons;
    if (oldButtons === buttons) {
      return;
    }
    const eGui = this.getGui();
    _clearElement(eGui);
    let eApplyButton;
    this.destroyListeners();
    const fragment = document.createDocumentFragment();
    const className2 = this.className;
    const addButton = ({ type, label: label2 }) => {
      const clickListener = (event) => {
        this.dispatchLocalEvent({
          type,
          event
        });
      };
      if (!["apply", "clear", "reset", "cancel"].includes(type)) {
        _warn(75);
      }
      const isApply = type === "apply";
      const buttonType = isApply && useForm ? "submit" : "button";
      const button = _createElement({
        tag: "button",
        attrs: { type: buttonType },
        ref: `${type}FilterButton`,
        cls: `ag-button ag-standard-button ${className2}-button${isApply ? " " + className2 + "-apply-button" : ""}`,
        children: label2
      });
      this.activateTabIndex([button]);
      if (isApply) {
        eApplyButton = button;
      }
      const keydownListener = (event) => {
        if (event.key === KeyCode.ENTER) {
          event.preventDefault();
          clickListener(event);
        }
      };
      const listeners = this.listeners;
      button.addEventListener("click", clickListener);
      listeners.push(() => button.removeEventListener("click", clickListener));
      button.addEventListener("keydown", keydownListener);
      listeners.push(() => button.removeEventListener("keydown", keydownListener));
      fragment.append(button);
    };
    for (const button of buttons) {
      addButton(button);
    }
    this.eApply = eApplyButton;
    const tooltip = this.validationTooltipFeature;
    if (eApplyButton && !tooltip) {
      this.validationTooltipFeature = this.createOptionalManagedBean(
        this.beans.registry.createDynamicBean("tooltipFeature", false, {
          getGui: () => this.eApply,
          getLocation: () => "advancedFilter",
          getTooltipShowDelayOverride: () => 1e3
        })
      );
    } else if (!eApplyButton && tooltip) {
      this.validationTooltipFeature = this.destroyBean(tooltip);
    }
    eGui.append(fragment);
  }
  getApplyButton() {
    return this.eApply;
  }
  updateValidity(valid, message2 = null) {
    const eApplyButton = this.eApply;
    if (!eApplyButton) {
      return;
    }
    _setDisabled(eApplyButton, valid === false);
    this.validationMessage = message2 ?? null;
    this.validationTooltipFeature?.setTooltipAndRefresh(this.validationMessage);
  }
  destroyListeners() {
    for (const destroyFunc of this.listeners) {
      destroyFunc();
    }
    this.listeners = [];
  }
  destroy() {
    this.destroyListeners();
    super.destroy();
  }
};
var FILTER_LOCALE_TEXT = {
  applyFilter: "Apply",
  clearFilter: "Clear",
  resetFilter: "Reset",
  cancelFilter: "Cancel",
  textFilter: "Text Filter",
  numberFilter: "Number Filter",
  dateFilter: "Date Filter",
  setFilter: "Set Filter",
  filterOoo: "Filter...",
  empty: "Choose one",
  equals: "Equals",
  notEqual: "Does not equal",
  lessThan: "Less than",
  greaterThan: "Greater than",
  inRange: "Between",
  inRangeStart: "From",
  inRangeEnd: "To",
  lessThanOrEqual: "Less than or equal to",
  greaterThanOrEqual: "Greater than or equal to",
  contains: "Contains",
  notContains: "Does not contain",
  startsWith: "Begins with",
  endsWith: "Ends with",
  blank: "Blank",
  notBlank: "Not blank",
  before: "Before",
  after: "After",
  andCondition: "AND",
  orCondition: "OR",
  dateFormatOoo: "yyyy-mm-dd",
  filterSummaryInactive: "is (All)",
  filterSummaryContains: "contains",
  filterSummaryNotContains: "does not contain",
  filterSummaryTextEquals: "equals",
  filterSummaryTextNotEqual: "does not equal",
  filterSummaryStartsWith: "begins with",
  filterSummaryEndsWith: "ends with",
  filterSummaryBlank: "is blank",
  filterSummaryNotBlank: "is not blank",
  filterSummaryEquals: "=",
  filterSummaryNotEqual: "!=",
  filterSummaryGreaterThan: ">",
  filterSummaryGreaterThanOrEqual: ">=",
  filterSummaryLessThan: "<",
  filterSummaryLessThanOrEqual: "<=",
  filterSummaryInRange: "between",
  filterSummaryInRangeValues: (variableValues) => `(${variableValues[0]}, ${variableValues[1]})`,
  filterSummaryTextQuote: (variableValues) => `"${variableValues[0]}"`
};
function translateForFilter(bean, key2, variableValues) {
  return _translate(bean, FILTER_LOCALE_TEXT, key2, variableValues);
}
function getDebounceMs(params, debounceDefault) {
  const { debounceMs } = params;
  if (_isUseApplyButton(params)) {
    if (debounceMs != null) {
      _warn(71);
    }
    return 0;
  }
  return debounceMs ?? debounceDefault;
}
function _isUseApplyButton(params) {
  return (params.buttons?.indexOf("apply") ?? -1) >= 0;
}
var FilterWrapperComp = class extends Component {
  constructor(column2, wrapper2, eventParent, updateModel, isGlobalButtons, enableGlobalButtonCheck) {
    super();
    this.column = column2;
    this.wrapper = wrapper2;
    this.eventParent = eventParent;
    this.updateModel = updateModel;
    this.isGlobalButtons = isGlobalButtons;
    this.enableGlobalButtonCheck = enableGlobalButtonCheck;
    this.hidePopup = null;
    this.applyActive = false;
  }
  postConstruct() {
    const { comp, params: originalParams } = this.wrapper;
    const params = originalParams;
    const useForm = params.useForm;
    const tag = useForm ? "form" : "div";
    this.setTemplate({
      tag,
      cls: "ag-filter-wrapper"
    });
    if (useForm) {
      this.addManagedElementListeners(this.getGui(), {
        submit: (e) => {
          e?.preventDefault();
        },
        keydown: this.handleKeyDown.bind(this)
      });
    }
    this.appendChild(comp.getGui());
    this.params = params;
    this.resetButtonsPanel(params);
    this.addManagedListeners(this.eventParent, {
      filterParamsChanged: ({ column: column2, params: eventParams }) => {
        if (column2 === this.column) {
          this.resetButtonsPanel(eventParams, this.params);
        }
      },
      filterStateChanged: ({ column: column2, state }) => {
        if (column2 === this.column) {
          this.eButtons?.updateValidity(state.valid !== false);
        }
      },
      filterAction: ({ column: column2, action, event: keyboardEvent }) => {
        if (column2 === this.column) {
          this.afterAction(action, keyboardEvent);
        }
      },
      ...this.enableGlobalButtonCheck ? {
        filterGlobalButtons: ({ isGlobal }) => {
          if (isGlobal !== this.isGlobalButtons) {
            this.isGlobalButtons = isGlobal;
            const currentParams = this.params;
            this.resetButtonsPanel(currentParams, currentParams, true);
          }
        }
      } : void 0
    });
  }
  afterGuiAttached(params) {
    if (params) {
      this.hidePopup = params.hidePopup;
    }
  }
  resetButtonsPanel(newParams, oldParams, forceUpdate) {
    const { buttons: oldButtons, readOnly: oldReadOnly } = oldParams ?? {};
    const { buttons: newButtons, readOnly, useForm } = newParams;
    if (!forceUpdate && oldReadOnly === readOnly && _jsonEquals(oldButtons, newButtons)) {
      return;
    }
    const hasButtons = newButtons && newButtons.length > 0 && !newParams.readOnly && !this.isGlobalButtons;
    let eButtonsPanel = this.eButtons;
    if (hasButtons) {
      const buttons = newButtons.map((type) => {
        const localeKey = `${type}Filter`;
        return { type, label: translateForFilter(this, localeKey) };
      });
      this.applyActive = _isUseApplyButton(this.params);
      if (!eButtonsPanel) {
        eButtonsPanel = this.createBean(new FilterButtonComp());
        this.appendChild(eButtonsPanel.getGui());
        const column2 = this.column;
        const getListener2 = (action) => ({ event }) => {
          this.updateModel(column2, action, { fromButtons: true });
          this.afterAction(action, event);
        };
        eButtonsPanel?.addManagedListeners(eButtonsPanel, {
          apply: getListener2("apply"),
          clear: getListener2("clear"),
          reset: getListener2("reset"),
          cancel: getListener2("cancel")
        });
        this.eButtons = eButtonsPanel;
      }
      eButtonsPanel.updateButtons(buttons, useForm);
    } else {
      this.applyActive = false;
      if (eButtonsPanel) {
        _removeFromParent(eButtonsPanel.getGui());
        this.eButtons = this.destroyBean(eButtonsPanel);
      }
    }
  }
  close(e) {
    const hidePopup = this.hidePopup;
    if (!hidePopup) {
      return;
    }
    const keyboardEvent = e;
    const key2 = keyboardEvent?.key;
    let params;
    if (key2 === KeyCode.ENTER || key2 === KeyCode.SPACE) {
      params = { keyboardEvent };
    }
    hidePopup(params);
    this.hidePopup = null;
  }
  afterAction(action, event) {
    const { params, applyActive } = this;
    const closeOnApply = params?.closeOnApply;
    switch (action) {
      case "apply": {
        event?.preventDefault();
        if (closeOnApply && applyActive) {
          this.close(event);
        }
        break;
      }
      case "reset": {
        if (closeOnApply && applyActive) {
          this.close();
        }
        break;
      }
      case "cancel": {
        if (closeOnApply) {
          this.close(event);
        }
        break;
      }
    }
  }
  handleKeyDown(event) {
    if (!event.defaultPrevented && event.key === KeyCode.ENTER && this.applyActive) {
      this.updateModel(this.column, "apply", { fromButtons: true });
      this.afterAction("apply", event);
    }
  }
  destroy() {
    this.hidePopup = null;
    this.eButtons = this.destroyBean(this.eButtons);
  }
};
var FilterElement = { tag: "div", cls: "ag-filter" };
var FilterComp = class extends Component {
  constructor(column2, source2, enableGlobalButtonCheck) {
    super(FilterElement);
    this.column = column2;
    this.source = source2;
    this.enableGlobalButtonCheck = enableGlobalButtonCheck;
    this.wrapper = null;
  }
  postConstruct() {
    this.beans.colFilter?.activeFilterComps.add(this);
    this.createFilter(true);
    this.addManagedEventListeners({ filterDestroyed: this.onFilterDestroyed.bind(this) });
  }
  hasFilter() {
    return this.wrapper != null;
  }
  getFilter() {
    return this.wrapper?.then((wrapper2) => wrapper2.comp) ?? null;
  }
  afterInit() {
    return this.wrapper?.then(() => {
    }) ?? AgPromise.resolve();
  }
  afterGuiAttached(params) {
    this.afterGuiAttachedParams = params;
    this.wrapper?.then((wrapper2) => {
      this.comp?.afterGuiAttached(params);
      wrapper2?.comp?.afterGuiAttached?.(params);
    });
  }
  afterGuiDetached() {
    this.wrapper?.then((wrapper2) => {
      wrapper2?.comp?.afterGuiDetached?.();
    });
  }
  createFilter(init) {
    const {
      column: column2,
      source: source2,
      beans: { colFilter }
    } = this;
    const filterPromise = colFilter.getFilterUiForDisplay(column2) ?? null;
    this.wrapper = filterPromise;
    filterPromise?.then((wrapper2) => {
      if (!wrapper2) {
        return;
      }
      const { isHandler, comp } = wrapper2;
      let filterGui;
      if (isHandler) {
        const enableGlobalButtonCheck = !!this.enableGlobalButtonCheck;
        const displayComp = this.createBean(
          new FilterWrapperComp(
            column2,
            wrapper2,
            colFilter,
            colFilter.updateModel.bind(colFilter),
            enableGlobalButtonCheck && colFilter.isGlobalButtons,
            enableGlobalButtonCheck
          )
        );
        this.comp = displayComp;
        filterGui = displayComp.getGui();
      } else {
        filterGui = comp.getGui();
        if (!_exists(filterGui)) {
          _warn(69, { guiFromFilter: filterGui });
        }
      }
      this.appendChild(filterGui);
      if (init) {
        this.eventSvc.dispatchEvent({
          type: "filterOpened",
          column: column2,
          source: source2,
          eGui: this.getGui()
        });
      } else {
        comp.afterGuiAttached?.(this.afterGuiAttachedParams);
      }
    });
  }
  onFilterDestroyed(event) {
    const { source: source2, column: column2 } = event;
    if ((source2 === "api" || source2 === "paramsUpdated") && column2.getId() === this.column.getId() && this.beans.colModel.getColDefCol(this.column)) {
      _clearElement(this.getGui());
      this.comp = this.destroyBean(this.comp);
      this.createFilter();
    }
  }
  destroy() {
    this.beans.colFilter?.activeFilterComps.delete(this);
    this.eventSvc.dispatchEvent({
      type: "filterClosed",
      column: this.column
    });
    this.wrapper = null;
    this.comp = this.destroyBean(this.comp);
    this.afterGuiAttachedParams = void 0;
    super.destroy();
  }
};
var MONTH_LOCALE_TEXT = {
  january: "January",
  february: "February",
  march: "March",
  april: "April",
  may: "May",
  june: "June",
  july: "July",
  august: "August",
  september: "September",
  october: "October",
  november: "November",
  december: "December"
};
var MONTH_KEYS = [
  "january",
  "february",
  "march",
  "april",
  "may",
  "june",
  "july",
  "august",
  "september",
  "october",
  "november",
  "december"
];
function setFilterNumberComparator(a2, b) {
  if (a2 == null) {
    return -1;
  }
  if (b == null) {
    return 1;
  }
  return Number.parseFloat(a2) - Number.parseFloat(b);
}
function isValidDate(value2) {
  return value2 instanceof Date && !isNaN(value2.getTime());
}
var filterParamsForEachDataType = {
  number: () => void 0,
  boolean: () => ({
    maxNumConditions: 1,
    debounceMs: 0,
    filterOptions: [
      "empty",
      {
        displayKey: "true",
        displayName: "True",
        predicate: (_filterValues, cellValue) => cellValue,
        numberOfInputs: 0
      },
      {
        displayKey: "false",
        displayName: "False",
        predicate: (_filterValues, cellValue) => cellValue === false,
        numberOfInputs: 0
      }
    ]
  }),
  date: () => ({ isValidDate }),
  dateString: ({ dataTypeDefinition }) => ({
    comparator: (filterDate, cellValue) => {
      const cellAsDate = dataTypeDefinition.dateParser(cellValue);
      if (cellValue == null || cellAsDate < filterDate) {
        return -1;
      }
      if (cellAsDate > filterDate) {
        return 1;
      }
      return 0;
    },
    isValidDate: (value2) => typeof value2 === "string" && isValidDate(dataTypeDefinition.dateParser(value2))
  }),
  dateTime: (args2) => filterParamsForEachDataType.date(args2),
  dateTimeString: (args2) => filterParamsForEachDataType.dateString(args2),
  object: () => void 0,
  text: () => void 0
};
var setFilterParamsForEachDataType = {
  number: () => ({ comparator: setFilterNumberComparator }),
  boolean: ({ t: t2 }) => ({
    valueFormatter: (params) => _exists(params.value) ? t2(String(params.value), params.value ? "True" : "False") : t2("blanks", "(Blanks)")
  }),
  date: ({ formatValue: formatValue2, t: t2 }) => ({
    valueFormatter: (params) => {
      const valueFormatted = formatValue2(params);
      return _exists(valueFormatted) ? valueFormatted : t2("blanks", "(Blanks)");
    },
    treeList: true,
    treeListFormatter: (pathKey, level) => {
      if (pathKey === "NaN") {
        return t2("invalidDate", "Invalid Date");
      }
      if (level === 1 && pathKey != null) {
        const monthKey = MONTH_KEYS[Number(pathKey) - 1];
        return t2(monthKey, MONTH_LOCALE_TEXT[monthKey]);
      }
      return pathKey ?? t2("blanks", "(Blanks)");
    },
    treeListPathGetter: (date2) => _getDateParts(date2, false)
  }),
  dateString: ({ formatValue: formatValue2, dataTypeDefinition, t: t2 }) => ({
    valueFormatter: (params) => {
      const valueFormatted = formatValue2(params);
      return _exists(valueFormatted) ? valueFormatted : t2("blanks", "(Blanks)");
    },
    treeList: true,
    treeListPathGetter: (value2) => _getDateParts(dataTypeDefinition.dateParser(value2 ?? void 0), false),
    treeListFormatter: (pathKey, level) => {
      if (level === 1 && pathKey != null) {
        const monthKey = MONTH_KEYS[Number(pathKey) - 1];
        return t2(monthKey, MONTH_LOCALE_TEXT[monthKey]);
      }
      return pathKey ?? t2("blanks", "(Blanks)");
    }
  }),
  dateTime: (args2) => {
    const params = setFilterParamsForEachDataType.date(args2);
    params.treeListPathGetter = _getDateParts;
    return params;
  },
  dateTimeString(args2) {
    const convertToDate = args2.dataTypeDefinition.dateParser;
    const params = setFilterParamsForEachDataType.dateString(args2);
    params.treeListPathGetter = (value2) => _getDateParts(convertToDate(value2 ?? void 0));
    return params;
  },
  object: ({ formatValue: formatValue2, t: t2 }) => ({
    valueFormatter: (params) => {
      const valueFormatted = formatValue2(params);
      return _exists(valueFormatted) ? valueFormatted : t2("blanks", "(Blanks)");
    }
  }),
  text: () => void 0
};
function _getFilterParamsForDataType(filter2, existingFilterParams, existingFilterValueGetter, dataTypeDefinition, formatValue2, beans, translate) {
  let filterParams = existingFilterParams;
  let filterValueGetter = existingFilterValueGetter;
  const usingSetFilter = filter2 === "agSetColumnFilter";
  if (!filterValueGetter && dataTypeDefinition.baseDataType === "object" && !usingSetFilter) {
    filterValueGetter = ({ column: column2, node: node2 }) => formatValue2({ column: column2, node: node2, value: beans.valueSvc.getValue(column2, node2) });
  }
  const filterParamsMap = usingSetFilter ? setFilterParamsForEachDataType : filterParamsForEachDataType;
  const filterParamsGetter = filterParamsMap[dataTypeDefinition.baseDataType];
  const newFilterParams = filterParamsGetter({ dataTypeDefinition, formatValue: formatValue2, t: translate });
  filterParams = typeof existingFilterParams === "object" ? {
    ...newFilterParams,
    ...existingFilterParams
  } : newFilterParams;
  return { filterParams, filterValueGetter };
}
var defaultFilters = {
  boolean: "agTextColumnFilter",
  date: "agDateColumnFilter",
  dateString: "agDateColumnFilter",
  dateTime: "agDateColumnFilter",
  dateTimeString: "agDateColumnFilter",
  number: "agNumberColumnFilter",
  object: "agTextColumnFilter",
  text: "agTextColumnFilter"
};
var defaultFloatingFilters = {
  boolean: "agTextColumnFloatingFilter",
  date: "agDateColumnFloatingFilter",
  dateString: "agDateColumnFloatingFilter",
  dateTime: "agDateColumnFloatingFilter",
  dateTimeString: "agDateColumnFloatingFilter",
  number: "agNumberColumnFloatingFilter",
  object: "agTextColumnFloatingFilter",
  text: "agTextColumnFloatingFilter"
};
function _getDefaultSimpleFilter(cellDataType, isFloating = false) {
  const filterSet = isFloating ? defaultFloatingFilters : defaultFilters;
  return filterSet[cellDataType ?? "text"];
}
var RESIZE_CONTAINER_STYLE = "ag-resizer-wrapper";
var makeDiv = (dataRefPrefix, classSuffix) => ({
  tag: "div",
  ref: `${dataRefPrefix}Resizer`,
  cls: `ag-resizer ag-resizer-${classSuffix}`
});
var RESIZE_TEMPLATE = {
  tag: "div",
  cls: RESIZE_CONTAINER_STYLE,
  children: [
    makeDiv("eTopLeft", "topLeft"),
    makeDiv("eTop", "top"),
    makeDiv("eTopRight", "topRight"),
    makeDiv("eRight", "right"),
    makeDiv("eBottomRight", "bottomRight"),
    makeDiv("eBottom", "bottom"),
    makeDiv("eBottomLeft", "bottomLeft"),
    makeDiv("eLeft", "left")
  ]
};
var PositionableFeature = class extends BeanStub {
  constructor(element, config2) {
    super();
    this.element = element;
    this.dragStartPosition = {
      x: 0,
      y: 0
    };
    this.position = {
      x: 0,
      y: 0
    };
    this.lastSize = {
      width: -1,
      height: -1
    };
    this.positioned = false;
    this.resizersAdded = false;
    this.resizeListeners = [];
    this.boundaryEl = null;
    this.isResizing = false;
    this.isMoving = false;
    this.resizable = {};
    this.movable = false;
    this.currentResizer = null;
    this.config = Object.assign({}, { popup: false }, config2);
  }
  wireBeans(beans) {
    this.popupSvc = beans.popupSvc;
    this.dragSvc = beans.dragSvc;
  }
  center(postProcessCallback) {
    const { clientHeight, clientWidth } = this.offsetParent;
    const x = clientWidth / 2 - this.getWidth() / 2;
    const y = clientHeight / 2 - this.getHeight() / 2;
    this.offsetElement(x, y, postProcessCallback);
  }
  initialisePosition(postProcessCallback) {
    if (this.positioned) {
      return;
    }
    const { centered, forcePopupParentAsOffsetParent, minWidth, width, minHeight, height, x, y } = this.config;
    if (!this.offsetParent) {
      this.setOffsetParent();
    }
    let computedMinHeight = 0;
    let computedMinWidth = 0;
    const isElementVisible = _isVisible(this.element);
    if (isElementVisible) {
      const boundaryEl = this.findBoundaryElement();
      const offsetParentComputedStyles = window.getComputedStyle(boundaryEl);
      if (offsetParentComputedStyles.minWidth != null) {
        const paddingWidth = boundaryEl.offsetWidth - this.element.offsetWidth;
        computedMinWidth = Number.parseInt(offsetParentComputedStyles.minWidth, 10) - paddingWidth;
      }
      if (offsetParentComputedStyles.minHeight != null) {
        const paddingHeight = boundaryEl.offsetHeight - this.element.offsetHeight;
        computedMinHeight = Number.parseInt(offsetParentComputedStyles.minHeight, 10) - paddingHeight;
      }
    }
    this.minHeight = minHeight || computedMinHeight;
    this.minWidth = minWidth || computedMinWidth;
    if (width) {
      this.setWidth(width);
    }
    if (height) {
      this.setHeight(height);
    }
    if (!width || !height) {
      this.refreshSize();
    }
    if (centered) {
      this.center(postProcessCallback);
    } else if (x || y) {
      this.offsetElement(x, y, postProcessCallback);
    } else if (isElementVisible && forcePopupParentAsOffsetParent) {
      let boundaryEl = this.boundaryEl;
      let initialisedDuringPositioning = true;
      if (!boundaryEl) {
        boundaryEl = this.findBoundaryElement();
        initialisedDuringPositioning = false;
      }
      if (boundaryEl) {
        const top2 = Number.parseFloat(boundaryEl.style.top);
        const left2 = Number.parseFloat(boundaryEl.style.left);
        if (initialisedDuringPositioning) {
          this.offsetElement(isNaN(left2) ? 0 : left2, isNaN(top2) ? 0 : top2, postProcessCallback);
        } else {
          this.setPosition(left2, top2);
        }
      }
    }
    this.positioned = !!this.offsetParent;
  }
  isPositioned() {
    return this.positioned;
  }
  getPosition() {
    return this.position;
  }
  setMovable(movable, moveElement) {
    if (!this.config.popup || movable === this.movable) {
      return;
    }
    this.movable = movable;
    const params = this.moveElementDragListener || {
      eElement: moveElement,
      onDragStart: this.onMoveStart.bind(this),
      onDragging: this.onMove.bind(this),
      onDragStop: this.onMoveEnd.bind(this)
    };
    if (movable) {
      this.dragSvc?.addDragSource(params);
      this.moveElementDragListener = params;
    } else {
      this.dragSvc?.removeDragSource(params);
      this.moveElementDragListener = void 0;
    }
  }
  setResizable(resizable) {
    this.clearResizeListeners();
    if (resizable) {
      this.addResizers();
    } else {
      this.removeResizers();
    }
    if (typeof resizable === "boolean") {
      if (resizable === false) {
        return;
      }
      resizable = {
        topLeft: resizable,
        top: resizable,
        topRight: resizable,
        right: resizable,
        bottomRight: resizable,
        bottom: resizable,
        bottomLeft: resizable,
        left: resizable
      };
    }
    Object.keys(resizable).forEach((side) => {
      const resizableStructure = resizable;
      const isSideResizable = !!resizableStructure[side];
      const resizerEl = this.getResizerElement(side);
      const params = {
        dragStartPixels: 0,
        eElement: resizerEl,
        onDragStart: (e) => this.onResizeStart(e, side),
        onDragging: this.onResize.bind(this),
        onDragStop: (e) => this.onResizeEnd(e, side)
      };
      if (isSideResizable || !this.isAlive() && !isSideResizable) {
        if (isSideResizable) {
          this.dragSvc?.addDragSource(params);
          this.resizeListeners.push(params);
          resizerEl.style.pointerEvents = "all";
        } else {
          resizerEl.style.pointerEvents = "none";
        }
        this.resizable[side] = isSideResizable;
      }
    });
  }
  removeSizeFromEl() {
    this.element.style.removeProperty("height");
    this.element.style.removeProperty("width");
    this.element.style.removeProperty("flex");
  }
  restoreLastSize() {
    this.element.style.flex = "0 0 auto";
    const { height, width } = this.lastSize;
    if (width !== -1) {
      this.element.style.width = `${width}px`;
    }
    if (height !== -1) {
      this.element.style.height = `${height}px`;
    }
  }
  getHeight() {
    return this.element.offsetHeight;
  }
  setHeight(height) {
    const { popup } = this.config;
    const eGui = this.element;
    let isPercent = false;
    if (typeof height === "string" && height.includes("%")) {
      _setFixedHeight(eGui, height);
      height = _getAbsoluteHeight(eGui);
      isPercent = true;
    } else {
      height = Math.max(this.minHeight, height);
      if (this.positioned) {
        const availableHeight = this.getAvailableHeight();
        if (availableHeight && height > availableHeight) {
          height = availableHeight;
        }
      }
    }
    if (this.getHeight() === height) {
      return;
    }
    if (!isPercent) {
      if (popup) {
        _setFixedHeight(eGui, height);
      } else {
        eGui.style.height = `${height}px`;
        eGui.style.flex = "0 0 auto";
        this.lastSize.height = typeof height === "number" ? height : Number.parseFloat(height);
      }
    } else {
      eGui.style.maxHeight = "unset";
      eGui.style.minHeight = "unset";
    }
  }
  getAvailableHeight() {
    const { popup, forcePopupParentAsOffsetParent } = this.config;
    if (!this.positioned) {
      this.initialisePosition();
    }
    const { clientHeight } = this.offsetParent;
    if (!clientHeight) {
      return null;
    }
    const elRect = this.element.getBoundingClientRect();
    const offsetParentRect = this.offsetParent.getBoundingClientRect();
    const yPosition = popup ? this.position.y : elRect.top;
    const parentTop = popup ? 0 : offsetParentRect.top;
    let additionalHeight = 0;
    if (forcePopupParentAsOffsetParent) {
      const parentEl = this.element.parentElement;
      if (parentEl) {
        const { bottom: bottom2 } = parentEl.getBoundingClientRect();
        additionalHeight = bottom2 - elRect.bottom;
      }
    }
    const availableHeight = clientHeight + parentTop - yPosition - additionalHeight;
    return availableHeight;
  }
  getWidth() {
    return this.element.offsetWidth;
  }
  setWidth(width) {
    const eGui = this.element;
    const { popup } = this.config;
    let isPercent = false;
    if (typeof width === "string" && width.includes("%")) {
      _setFixedWidth(eGui, width);
      width = _getAbsoluteWidth(eGui);
      isPercent = true;
    } else if (this.positioned) {
      width = Math.max(this.minWidth, width);
      const { clientWidth } = this.offsetParent;
      const xPosition = popup ? this.position.x : this.element.getBoundingClientRect().left;
      if (clientWidth && width + xPosition > clientWidth) {
        width = clientWidth - xPosition;
      }
    }
    if (this.getWidth() === width) {
      return;
    }
    if (!isPercent) {
      if (this.config.popup) {
        _setFixedWidth(eGui, width);
      } else {
        eGui.style.width = `${width}px`;
        eGui.style.flex = " unset";
        this.lastSize.width = typeof width === "number" ? width : Number.parseFloat(width);
      }
    } else {
      eGui.style.maxWidth = "unset";
      eGui.style.minWidth = "unset";
    }
  }
  offsetElement(x = 0, y = 0, postProcessCallback) {
    const { forcePopupParentAsOffsetParent } = this.config;
    const ePopup = forcePopupParentAsOffsetParent ? this.boundaryEl : this.element;
    if (!ePopup) {
      return;
    }
    this.popupSvc?.positionPopup({
      ePopup,
      keepWithinBounds: true,
      skipObserver: this.movable || this.isResizable(),
      updatePosition: () => ({ x, y }),
      postProcessCallback
    });
    this.setPosition(Number.parseFloat(ePopup.style.left), Number.parseFloat(ePopup.style.top));
  }
  constrainSizeToAvailableHeight(constrain) {
    if (!this.config.forcePopupParentAsOffsetParent) {
      return;
    }
    const applyMaxHeightToElement = () => {
      const availableHeight = this.getAvailableHeight();
      this.element.style.setProperty("max-height", `${availableHeight}px`);
    };
    if (constrain && this.popupSvc) {
      this.resizeObserverSubscriber?.();
      this.resizeObserverSubscriber = _observeResize(
        this.beans,
        this.popupSvc?.getPopupParent(),
        applyMaxHeightToElement
      );
    } else {
      this.element.style.removeProperty("max-height");
      if (this.resizeObserverSubscriber) {
        this.resizeObserverSubscriber();
        this.resizeObserverSubscriber = void 0;
      }
    }
  }
  setPosition(x, y) {
    this.position.x = x;
    this.position.y = y;
  }
  updateDragStartPosition(x, y) {
    this.dragStartPosition = { x, y };
  }
  calculateMouseMovement(params) {
    const { e, isLeft, isTop, anywhereWithin, topBuffer } = params;
    const xDiff = e.clientX - this.dragStartPosition.x;
    const yDiff = e.clientY - this.dragStartPosition.y;
    const movementX = this.shouldSkipX(e, !!isLeft, !!anywhereWithin, xDiff) ? 0 : xDiff;
    const movementY = this.shouldSkipY(e, !!isTop, topBuffer, yDiff) ? 0 : yDiff;
    return { movementX, movementY };
  }
  shouldSkipX(e, isLeft, anywhereWithin, diff2) {
    const elRect = this.element.getBoundingClientRect();
    const parentRect = this.offsetParent.getBoundingClientRect();
    const boundaryElRect = this.boundaryEl.getBoundingClientRect();
    const xPosition = this.config.popup ? this.position.x : elRect.left;
    let skipX = xPosition <= 0 && parentRect.left >= e.clientX || parentRect.right <= e.clientX && parentRect.right <= boundaryElRect.right;
    if (skipX) {
      return true;
    }
    if (isLeft) {
      skipX = // skip if we are moving to the left and the cursor
      // is positioned to the right of the left side anchor
      diff2 < 0 && e.clientX > xPosition + parentRect.left || // skip if we are moving to the right and the cursor
      // is positioned to the left of the dialog
      diff2 > 0 && e.clientX < xPosition + parentRect.left;
    } else if (anywhereWithin) {
      skipX = diff2 < 0 && e.clientX > boundaryElRect.right || diff2 > 0 && e.clientX < xPosition + parentRect.left;
    } else {
      skipX = // if the movement is bound to the right side of the dialog
      // we skip if we are moving to the left and the cursor
      // is to the right of the dialog
      diff2 < 0 && e.clientX > boundaryElRect.right || // or skip if we are moving to the right and the cursor
      // is to the left of the right side anchor
      diff2 > 0 && e.clientX < boundaryElRect.right;
    }
    return skipX;
  }
  shouldSkipY(e, isTop, topBuffer = 0, diff2) {
    const elRect = this.element.getBoundingClientRect();
    const parentRect = this.offsetParent.getBoundingClientRect();
    const boundaryElRect = this.boundaryEl.getBoundingClientRect();
    const yPosition = this.config.popup ? this.position.y : elRect.top;
    let skipY = yPosition <= 0 && parentRect.top >= e.clientY || parentRect.bottom <= e.clientY && parentRect.bottom <= boundaryElRect.bottom;
    if (skipY) {
      return true;
    }
    if (isTop) {
      skipY = // skip if we are moving to towards top and the cursor is
      // below the top anchor + topBuffer
      // note: topBuffer is used when moving the dialog using the title bar
      diff2 < 0 && e.clientY > yPosition + parentRect.top + topBuffer || // skip if we are moving to the bottom and the cursor is
      // above the top anchor
      diff2 > 0 && e.clientY < yPosition + parentRect.top;
    } else {
      skipY = // skip if we are moving towards the top and the cursor
      // is below the bottom anchor
      diff2 < 0 && e.clientY > boundaryElRect.bottom || // skip if we are moving towards the bottom and the cursor
      // is above the bottom anchor
      diff2 > 0 && e.clientY < boundaryElRect.bottom;
    }
    return skipY;
  }
  createResizeMap() {
    const getElement2 = (ref2) => ({
      element: this.element.querySelector(`[data-ref=${ref2}Resizer]`)
    });
    this.resizerMap = {
      topLeft: getElement2("eTopLeft"),
      top: getElement2("eTop"),
      topRight: getElement2("eTopRight"),
      right: getElement2("eRight"),
      bottomRight: getElement2("eBottomRight"),
      bottom: getElement2("eBottom"),
      bottomLeft: getElement2("eBottomLeft"),
      left: getElement2("eLeft")
    };
  }
  addResizers() {
    if (this.resizersAdded) {
      return;
    }
    const eGui = this.element;
    if (!eGui) {
      return;
    }
    eGui.appendChild(_createElement(RESIZE_TEMPLATE));
    this.createResizeMap();
    this.resizersAdded = true;
  }
  removeResizers() {
    this.resizerMap = void 0;
    const resizerEl = this.element.querySelector(`.${RESIZE_CONTAINER_STYLE}`);
    resizerEl?.remove();
    this.resizersAdded = false;
  }
  getResizerElement(side) {
    return this.resizerMap[side].element;
  }
  onResizeStart(e, side) {
    this.boundaryEl = this.findBoundaryElement();
    if (!this.positioned) {
      this.initialisePosition();
    }
    this.currentResizer = {
      isTop: !!side.match(/top/i),
      isRight: !!side.match(/right/i),
      isBottom: !!side.match(/bottom/i),
      isLeft: !!side.match(/left/i)
    };
    this.element.classList.add("ag-resizing");
    this.resizerMap[side].element.classList.add("ag-active");
    const { popup, forcePopupParentAsOffsetParent } = this.config;
    if (!popup && !forcePopupParentAsOffsetParent) {
      this.applySizeToSiblings(this.currentResizer.isBottom || this.currentResizer.isTop);
    }
    this.isResizing = true;
    this.updateDragStartPosition(e.clientX, e.clientY);
  }
  getSiblings() {
    const element = this.element;
    const parent = element.parentElement;
    if (!parent) {
      return null;
    }
    return Array.prototype.slice.call(parent.children).filter((el) => !el.classList.contains("ag-hidden"));
  }
  getMinSizeOfSiblings() {
    const siblings = this.getSiblings() || [];
    let height = 0;
    let width = 0;
    for (let i2 = 0; i2 < siblings.length; i2++) {
      const currentEl = siblings[i2];
      const isFlex = !!currentEl.style.flex && currentEl.style.flex !== "0 0 auto";
      if (currentEl === this.element) {
        continue;
      }
      let nextHeight = this.minHeight || 0;
      let nextWidth = this.minWidth || 0;
      if (isFlex) {
        const computedStyle = window.getComputedStyle(currentEl);
        if (computedStyle.minHeight) {
          nextHeight = Number.parseInt(computedStyle.minHeight, 10);
        }
        if (computedStyle.minWidth) {
          nextWidth = Number.parseInt(computedStyle.minWidth, 10);
        }
      } else {
        nextHeight = currentEl.offsetHeight;
        nextWidth = currentEl.offsetWidth;
      }
      height += nextHeight;
      width += nextWidth;
    }
    return { height, width };
  }
  applySizeToSiblings(vertical) {
    let containerToFlex = null;
    const siblings = this.getSiblings();
    if (!siblings) {
      return;
    }
    for (let i2 = 0; i2 < siblings.length; i2++) {
      const el = siblings[i2];
      if (el === containerToFlex) {
        continue;
      }
      if (vertical) {
        el.style.height = `${el.offsetHeight}px`;
      } else {
        el.style.width = `${el.offsetWidth}px`;
      }
      el.style.flex = "0 0 auto";
      if (el === this.element) {
        containerToFlex = siblings[i2 + 1];
      }
    }
    if (containerToFlex) {
      containerToFlex.style.removeProperty("height");
      containerToFlex.style.removeProperty("min-height");
      containerToFlex.style.removeProperty("max-height");
      containerToFlex.style.flex = "1 1 auto";
    }
  }
  isResizable() {
    return Object.values(this.resizable).some((value2) => value2);
  }
  onResize(e) {
    if (!this.isResizing || !this.currentResizer) {
      return;
    }
    const { popup, forcePopupParentAsOffsetParent } = this.config;
    const { isTop, isRight, isBottom, isLeft } = this.currentResizer;
    const isHorizontal = isRight || isLeft;
    const isVertical = isBottom || isTop;
    const { movementX, movementY } = this.calculateMouseMovement({ e, isLeft, isTop });
    const xPosition = this.position.x;
    const yPosition = this.position.y;
    let offsetLeft = 0;
    let offsetTop = 0;
    if (isHorizontal && movementX) {
      const direction = isLeft ? -1 : 1;
      const oldWidth = this.getWidth();
      const newWidth = oldWidth + movementX * direction;
      let skipWidth = false;
      if (isLeft) {
        offsetLeft = oldWidth - newWidth;
        if (xPosition + offsetLeft <= 0 || newWidth <= this.minWidth) {
          skipWidth = true;
          offsetLeft = 0;
        }
      }
      if (!skipWidth) {
        this.setWidth(newWidth);
      }
    }
    if (isVertical && movementY) {
      const direction = isTop ? -1 : 1;
      const oldHeight = this.getHeight();
      const newHeight = oldHeight + movementY * direction;
      let skipHeight = false;
      if (isTop) {
        offsetTop = oldHeight - newHeight;
        if (yPosition + offsetTop <= 0 || newHeight <= this.minHeight) {
          skipHeight = true;
          offsetTop = 0;
        }
      } else if (
        // do not let the size of all siblings be higher than the parent container
        !this.config.popup && !this.config.forcePopupParentAsOffsetParent && oldHeight < newHeight && this.getMinSizeOfSiblings().height + newHeight > this.element.parentElement.offsetHeight
      ) {
        skipHeight = true;
      }
      if (!skipHeight) {
        this.setHeight(newHeight);
      }
    }
    this.updateDragStartPosition(e.clientX, e.clientY);
    if ((popup || forcePopupParentAsOffsetParent) && offsetLeft || offsetTop) {
      this.offsetElement(xPosition + offsetLeft, yPosition + offsetTop);
    }
  }
  onResizeEnd(e, side) {
    this.isResizing = false;
    this.currentResizer = null;
    this.boundaryEl = null;
    this.element.classList.remove("ag-resizing");
    this.resizerMap[side].element.classList.remove("ag-active");
    this.dispatchLocalEvent({ type: "resize" });
  }
  refreshSize() {
    const eGui = this.element;
    if (this.config.popup) {
      if (!this.config.width) {
        this.setWidth(eGui.offsetWidth);
      }
      if (!this.config.height) {
        this.setHeight(eGui.offsetHeight);
      }
    }
  }
  onMoveStart(e) {
    this.boundaryEl = this.findBoundaryElement();
    if (!this.positioned) {
      this.initialisePosition();
    }
    this.isMoving = true;
    this.element.classList.add("ag-moving");
    this.updateDragStartPosition(e.clientX, e.clientY);
  }
  onMove(e) {
    if (!this.isMoving) {
      return;
    }
    const { x, y } = this.position;
    let topBuffer;
    if (this.config.calculateTopBuffer) {
      topBuffer = this.config.calculateTopBuffer();
    }
    const { movementX, movementY } = this.calculateMouseMovement({
      e,
      isTop: true,
      anywhereWithin: true,
      topBuffer
    });
    this.offsetElement(x + movementX, y + movementY);
    this.updateDragStartPosition(e.clientX, e.clientY);
  }
  onMoveEnd() {
    this.isMoving = false;
    this.boundaryEl = null;
    this.element.classList.remove("ag-moving");
  }
  setOffsetParent() {
    if (this.config.forcePopupParentAsOffsetParent && this.popupSvc) {
      this.offsetParent = this.popupSvc.getPopupParent();
    } else {
      this.offsetParent = this.element.offsetParent;
    }
  }
  findBoundaryElement() {
    let el = this.element;
    while (el) {
      if (window.getComputedStyle(el).position !== "static") {
        return el;
      }
      el = el.parentElement;
    }
    return this.element;
  }
  clearResizeListeners() {
    while (this.resizeListeners.length) {
      const params = this.resizeListeners.pop();
      this.dragSvc?.removeDragSource(params);
    }
  }
  destroy() {
    super.destroy();
    if (this.moveElementDragListener) {
      this.dragSvc?.removeDragSource(this.moveElementDragListener);
    }
    this.constrainSizeToAvailableHeight(false);
    this.clearResizeListeners();
    this.removeResizers();
  }
};
var AG_GRID_STOP_PROPAGATION = "__ag_Grid_Stop_Propagation";
function _stopPropagationForAgGrid(event) {
  event[AG_GRID_STOP_PROPAGATION] = true;
}
function _isStopPropagationForAgGrid(event) {
  return event[AG_GRID_STOP_PROPAGATION] === true;
}
var FOCUS_MANAGED_CLASS = "ag-focus-managed";
var ManagedFocusFeature = class extends BeanStub {
  constructor(eFocusable, callbacks = {}) {
    super();
    this.eFocusable = eFocusable;
    this.callbacks = callbacks;
    this.callbacks = {
      shouldStopEventPropagation: () => false,
      onTabKeyDown: (e) => {
        if (e.defaultPrevented) {
          return;
        }
        const nextRoot = _findNextFocusableElement(this.beans, this.eFocusable, false, e.shiftKey);
        if (!nextRoot) {
          return;
        }
        nextRoot.focus();
        e.preventDefault();
      },
      ...callbacks
    };
  }
  postConstruct() {
    const {
      eFocusable,
      callbacks: { onFocusIn, onFocusOut }
    } = this;
    eFocusable.classList.add(FOCUS_MANAGED_CLASS);
    this.addKeyDownListeners(eFocusable);
    if (onFocusIn) {
      this.addManagedElementListeners(eFocusable, { focusin: onFocusIn });
    }
    if (onFocusOut) {
      this.addManagedElementListeners(eFocusable, { focusout: onFocusOut });
    }
  }
  addKeyDownListeners(eGui) {
    this.addManagedElementListeners(eGui, {
      keydown: (e) => {
        if (e.defaultPrevented || _isStopPropagationForAgGrid(e)) {
          return;
        }
        const { callbacks } = this;
        if (callbacks.shouldStopEventPropagation(e)) {
          _stopPropagationForAgGrid(e);
          return;
        }
        if (e.key === KeyCode.TAB) {
          callbacks.onTabKeyDown(e);
        } else if (callbacks.handleKeyDown) {
          callbacks.handleKeyDown(e);
        }
      }
    });
  }
};
var ProvidedFilter = class extends Component {
  constructor(filterNameKey, cssIdentifier) {
    super();
    this.filterNameKey = filterNameKey;
    this.cssIdentifier = cssIdentifier;
    this.applyActive = false;
    this.debouncePending = false;
    this.defaultDebounceMs = 0;
  }
  postConstruct() {
    const element = {
      tag: "div",
      cls: `ag-filter-body-wrapper ag-${this.cssIdentifier}-body-wrapper`,
      children: [this.createBodyTemplate()]
    };
    this.setTemplate(element, this.getAgComponents());
    this.createManagedBean(
      new ManagedFocusFeature(this.getFocusableElement(), {
        handleKeyDown: this.handleKeyDown.bind(this)
      })
    );
    this.positionableFeature = this.createBean(
      new PositionableFeature(this.getPositionableElement(), {
        forcePopupParentAsOffsetParent: true
      })
    );
  }
  handleKeyDown(_e2) {
  }
  init(legacyParams) {
    const params = legacyParams;
    this.setParams(params);
    this.setModelIntoUi(params.state.model, true).then(() => this.updateUiVisibility());
  }
  refresh(legacyNewParams) {
    const newParams = legacyNewParams;
    const oldParams = this.params;
    this.params = newParams;
    const source2 = newParams.source;
    if (source2 === "colDef") {
      this.updateParams(newParams, oldParams);
    }
    const newState = newParams.state;
    const oldState = this.state;
    this.state = newState;
    if (newState.model !== oldState.model || newState.state !== oldState.state) {
      this.setModelIntoUi(newState.model);
    }
    return true;
  }
  /** Called on init only. Override in subclasses */
  setParams(params) {
    this.params = params;
    this.state = params.state;
    this.commonUpdateParams(params);
  }
  /** Called on refresh only. Override in subclasses */
  updateParams(newParams, oldParams) {
    this.commonUpdateParams(newParams, oldParams);
  }
  commonUpdateParams(newParams, _oldParams) {
    this.applyActive = _isUseApplyButton(newParams);
    this.setupApplyDebounced();
  }
  /**
   * @deprecated v34 Use the same method on the filter handler (`api.getColumnFilterHandler()`) instead.
   */
  doesFilterPass(params) {
    _warn(283);
    const { getHandler, model: model2, column: column2 } = this.params;
    return getHandler().doesFilterPass({
      ...params,
      model: model2,
      handlerParams: this.beans.colFilter.getHandlerParams(column2)
    });
  }
  getFilterTitle() {
    return this.translate(this.filterNameKey);
  }
  /**
   * @deprecated v34 Filters are active when they have a model. Use `api.getColumnFilterModel()` instead.
   */
  isFilterActive() {
    _warn(284);
    return this.params.model != null;
  }
  setupApplyDebounced() {
    const debounceMs = getDebounceMs(this.params, this.defaultDebounceMs);
    const debounceFunc = _debounce(this, this.checkApplyDebounce.bind(this), debounceMs);
    this.applyDebounced = () => {
      this.debouncePending = true;
      debounceFunc();
    };
  }
  checkApplyDebounce() {
    if (this.debouncePending) {
      this.debouncePending = false;
      this.doApplyModel();
    }
  }
  /**
   * @deprecated v34 Use (`api.getColumnFilterModel()`) instead.
   */
  getModel() {
    _warn(285);
    return this.params.model;
  }
  /**
   * @deprecated v34 Use (`api.setColumnFilterModel()`) instead.
   */
  setModel(model2) {
    _warn(286);
    const { beans, params } = this;
    return beans.colFilter.setModelForColumnLegacy(params.column, model2);
  }
  /**
   * Applies changes made in the UI to the filter, and returns true if the model has changed.
   */
  applyModel(_source = "api") {
    return this.doApplyModel();
  }
  canApply(_model) {
    return true;
  }
  doApplyModel(additionalEventAttributes) {
    const { params, state } = this;
    const changed = !this.areModelsEqual(params.model, state.model);
    if (changed) {
      params.onAction("apply", additionalEventAttributes);
    }
    return changed;
  }
  /**
   * @deprecated v34 Internal method - should only be called by the grid.
   */
  onNewRowsLoaded() {
  }
  /**
   * By default, if the change came from a floating filter it will be applied immediately, otherwise if there is no
   * apply button it will be applied after a debounce, otherwise it will not be applied at all. This behaviour can
   * be adjusted by using the apply parameter.
   */
  onUiChanged(apply, afterFloatingFilter = false) {
    this.updateUiVisibility();
    const model2 = this.getModelFromUi();
    const state = {
      model: model2,
      state: this.getState(),
      valid: this.canApply(model2)
    };
    this.state = state;
    const params = this.params;
    params.onStateChange(state);
    params.onUiChange(this.getUiChangeEventParams());
    if (!this.gos.get("enableFilterHandlers")) {
      this.eventSvc.dispatchEvent({
        type: "filterModified",
        column: params.column,
        filterInstance: this
      });
    }
    apply ?? (apply = this.applyActive ? void 0 : "debounce");
    if (apply === "immediately") {
      this.doApplyModel({ afterFloatingFilter, afterDataChange: false });
    } else if (apply === "debounce") {
      this.applyDebounced();
    }
  }
  getState() {
    return void 0;
  }
  getUiChangeEventParams() {
    return void 0;
  }
  afterGuiAttached(params) {
    this.lastContainerType = params?.container;
    this.refreshFilterResizer(params?.container);
  }
  refreshFilterResizer(containerType) {
    const { positionableFeature, gos } = this;
    if (!positionableFeature) {
      return;
    }
    const isResizable = containerType === "floatingFilter" || containerType === "columnFilter";
    if (isResizable) {
      positionableFeature.restoreLastSize();
      positionableFeature.setResizable(
        gos.get("enableRtl") ? { bottom: true, bottomLeft: true, left: true } : { bottom: true, bottomRight: true, right: true }
      );
    } else {
      positionableFeature.removeSizeFromEl();
      positionableFeature.setResizable(false);
    }
    positionableFeature.constrainSizeToAvailableHeight(isResizable);
  }
  afterGuiDetached() {
    this.checkApplyDebounce();
    this.positionableFeature?.constrainSizeToAvailableHeight(false);
  }
  destroy() {
    this.positionableFeature = this.destroyBean(this.positionableFeature);
    super.destroy();
  }
  translate(key2) {
    return translateForFilter(this, key2);
  }
  // override to control positionable feature
  getPositionableElement() {
    return this.getGui();
  }
  areModelsEqual(a2, b) {
    if (a2 === b || a2 == null && b == null) {
      return true;
    }
    if (a2 == null || b == null) {
      return false;
    }
    return this.areNonNullModelsEqual(a2, b);
  }
};
function isCombinedFilterModel(model2) {
  return !!model2.operator;
}
function _getDefaultFloatingFilterType(frameworkOverrides, def, getFromDefault) {
  if (def == null) {
    return null;
  }
  let defaultFloatingFilterType = null;
  const { compName, jsComp, fwComp } = _getFilterCompKeys(frameworkOverrides, def);
  if (compName) {
    const floatingFilterTypeMap = {
      agSetColumnFilter: "agSetColumnFloatingFilter",
      agMultiColumnFilter: "agMultiColumnFloatingFilter",
      agGroupColumnFilter: "agGroupColumnFloatingFilter",
      agNumberColumnFilter: "agNumberColumnFloatingFilter",
      agDateColumnFilter: "agDateColumnFloatingFilter",
      agTextColumnFilter: "agTextColumnFloatingFilter"
    };
    defaultFloatingFilterType = floatingFilterTypeMap[compName];
  } else {
    const usingDefaultFilter = jsComp == null && fwComp == null && def.filter === true;
    if (usingDefaultFilter) {
      defaultFloatingFilterType = getFromDefault();
    }
  }
  return defaultFloatingFilterType;
}
var LayoutCssClasses = {
  AUTO_HEIGHT: "ag-layout-auto-height",
  NORMAL: "ag-layout-normal",
  PRINT: "ag-layout-print"
};
var LayoutFeature = class extends BeanStub {
  constructor(view) {
    super();
    this.view = view;
  }
  postConstruct() {
    this.addManagedPropertyListener("domLayout", this.updateLayoutClasses.bind(this));
    this.updateLayoutClasses();
  }
  updateLayoutClasses() {
    const domLayout = this.gos.get("domLayout");
    const params = {
      autoHeight: domLayout === "autoHeight",
      normal: domLayout === "normal",
      print: domLayout === "print"
    };
    const cssClass = params.autoHeight ? LayoutCssClasses.AUTO_HEIGHT : params.print ? LayoutCssClasses.PRINT : LayoutCssClasses.NORMAL;
    this.view.updateLayoutClasses(cssClass, params);
  }
};
var VIEWPORT = "Viewport";
var FAKE_V_SCROLLBAR = "fakeVScrollComp";
var HORIZONTAL_SOURCES = [
  "fakeHScrollComp",
  "centerHeader",
  "topCenter",
  "bottomCenter",
  "stickyTopCenter",
  "stickyBottomCenter"
];
var SCROLL_DEBOUNCE_TIMEOUT = 100;
var SCROLL_END_TIMEOUT = 150;
var GridBodyScrollFeature = class extends BeanStub {
  constructor(eBodyViewport) {
    super();
    this.clearRetryListenerFncs = [];
    this.lastScrollSource = [null, null];
    this.scrollLeft = -1;
    this.nextScrollTop = -1;
    this.scrollTop = -1;
    this.lastOffsetHeight = -1;
    this.lastScrollTop = -1;
    this.lastIsHorizontalScrollShowing = false;
    this.scrollTimer = 0;
    this.isScrollActive = false;
    this.isVerticalPositionInvalidated = true;
    this.isHorizontalPositionInvalidated = true;
    this.eBodyViewport = eBodyViewport;
    this.resetLastHScrollDebounced = _debounce(
      this,
      () => this.lastScrollSource[
        1
        /* Horizontal */
      ] = null,
      SCROLL_END_TIMEOUT
    );
    this.resetLastVScrollDebounced = _debounce(
      this,
      () => this.lastScrollSource[
        0
        /* Vertical */
      ] = null,
      SCROLL_END_TIMEOUT
    );
  }
  wireBeans(beans) {
    this.ctrlsSvc = beans.ctrlsSvc;
    this.animationFrameSvc = beans.animationFrameSvc;
    this.visibleCols = beans.visibleCols;
  }
  destroy() {
    super.destroy();
    this.clearRetryListenerFncs = [];
    window.clearTimeout(this.scrollTimer);
  }
  postConstruct() {
    this.enableRtl = this.gos.get("enableRtl");
    const invalidateVerticalScroll = this.invalidateVerticalScroll.bind(this);
    const invalidateHorizontalScroll = this.invalidateHorizontalScroll.bind(this);
    this.addManagedEventListeners({
      displayedColumnsWidthChanged: this.onDisplayedColumnsWidthChanged.bind(this),
      bodyHeightChanged: invalidateVerticalScroll,
      // We only invalidate horizontal scrolling when the viewport switches
      // between scrollable and non-scrollable, avoiding unnecessary
      // invalidation on every gridSizeChanged event. If more properties
      // require invalidation, read/write DOM cycles may be needed.
      scrollGapChanged: invalidateHorizontalScroll
    });
    this.addManagedElementListeners(this.eBodyViewport, {
      scroll: invalidateVerticalScroll
    });
    this.ctrlsSvc.whenReady(this, (p) => {
      this.centerRowsCtrl = p.center;
      this.onDisplayedColumnsWidthChanged();
      this.addScrollListener();
    });
  }
  invalidateHorizontalScroll() {
    this.isHorizontalPositionInvalidated = true;
  }
  invalidateVerticalScroll() {
    this.isVerticalPositionInvalidated = true;
  }
  addScrollListener() {
    this.addHorizontalScrollListeners();
    this.addVerticalScrollListeners();
  }
  addHorizontalScrollListeners() {
    this.addManagedElementListeners(this.centerRowsCtrl.eViewport, {
      scroll: this.onHScroll.bind(this, VIEWPORT)
    });
    for (const source2 of HORIZONTAL_SOURCES) {
      const scrollPartner = this.ctrlsSvc.get(source2);
      this.registerScrollPartner(scrollPartner, this.onHScroll.bind(this, source2));
    }
  }
  addVerticalScrollListeners() {
    const fakeVScrollComp = this.ctrlsSvc.get("fakeVScrollComp");
    const isDebounce = this.gos.get("debounceVerticalScrollbar");
    const onVScroll = isDebounce ? _debounce(this, this.onVScroll.bind(this, VIEWPORT), SCROLL_DEBOUNCE_TIMEOUT) : this.onVScroll.bind(this, VIEWPORT);
    const onFakeVScroll = isDebounce ? _debounce(this, this.onVScroll.bind(this, FAKE_V_SCROLLBAR), SCROLL_DEBOUNCE_TIMEOUT) : this.onVScroll.bind(this, FAKE_V_SCROLLBAR);
    this.addManagedElementListeners(this.eBodyViewport, { scroll: onVScroll });
    this.registerScrollPartner(fakeVScrollComp, onFakeVScroll);
  }
  registerScrollPartner(comp, callback) {
    comp.onScrollCallback(callback);
  }
  onDisplayedColumnsWidthChanged() {
    if (this.enableRtl) {
      this.horizontallyScrollHeaderCenterAndFloatingCenter();
    }
  }
  horizontallyScrollHeaderCenterAndFloatingCenter(scrollLeft) {
    const notYetInitialised = this.centerRowsCtrl == null;
    if (notYetInitialised) {
      return;
    }
    if (scrollLeft === void 0) {
      scrollLeft = this.centerRowsCtrl.getCenterViewportScrollLeft();
    }
    this.setScrollLeftForAllContainersExceptCurrent(Math.abs(scrollLeft));
  }
  setScrollLeftForAllContainersExceptCurrent(scrollLeft) {
    for (const container2 of [...HORIZONTAL_SOURCES, VIEWPORT]) {
      if (this.lastScrollSource[
        1
        /* Horizontal */
      ] === container2) {
        continue;
      }
      const viewport2 = this.getViewportForSource(container2);
      _setScrollLeft(viewport2, scrollLeft, this.enableRtl);
    }
  }
  getViewportForSource(source2) {
    if (source2 === VIEWPORT) {
      return this.centerRowsCtrl.eViewport;
    }
    return this.ctrlsSvc.get(source2).eViewport;
  }
  isControllingScroll(source2, direction) {
    if (this.lastScrollSource[direction] == null) {
      if (direction === 0) {
        this.lastScrollSource[0] = source2;
      } else {
        this.lastScrollSource[1] = source2;
      }
      return true;
    }
    return this.lastScrollSource[direction] === source2;
  }
  onHScroll(source2) {
    if (!this.isControllingScroll(
      source2,
      1
      /* Horizontal */
    )) {
      return;
    }
    const centerContainerViewport = this.centerRowsCtrl.eViewport;
    const { scrollLeft } = centerContainerViewport;
    if (this.shouldBlockScrollUpdate(1, scrollLeft, true)) {
      return;
    }
    const newScrollLeft = _getScrollLeft(this.getViewportForSource(source2), this.enableRtl);
    this.doHorizontalScroll(newScrollLeft);
    this.resetLastHScrollDebounced();
  }
  onVScroll(source2) {
    if (!this.isControllingScroll(
      source2,
      0
      /* Vertical */
    )) {
      return;
    }
    let scrollTop;
    if (source2 === VIEWPORT) {
      scrollTop = this.eBodyViewport.scrollTop;
    } else {
      scrollTop = this.ctrlsSvc.get("fakeVScrollComp").getScrollPosition();
    }
    if (this.shouldBlockScrollUpdate(0, scrollTop, true)) {
      return;
    }
    const { animationFrameSvc } = this;
    animationFrameSvc?.setScrollTop(scrollTop);
    this.nextScrollTop = scrollTop;
    if (source2 === VIEWPORT) {
      this.ctrlsSvc.get("fakeVScrollComp").setScrollPosition(scrollTop);
    } else {
      this.eBodyViewport.scrollTop = scrollTop;
    }
    if (animationFrameSvc?.active) {
      animationFrameSvc.schedule();
    } else {
      this.scrollGridIfNeeded(true);
    }
    this.resetLastVScrollDebounced();
  }
  doHorizontalScroll(scrollLeft) {
    const fakeScrollLeft = this.ctrlsSvc.get("fakeHScrollComp").getScrollPosition();
    if (this.scrollLeft === scrollLeft && scrollLeft === fakeScrollLeft) {
      return;
    }
    this.scrollLeft = scrollLeft;
    this.fireScrollEvent(
      1
      /* Horizontal */
    );
    this.horizontallyScrollHeaderCenterAndFloatingCenter(scrollLeft);
    this.centerRowsCtrl.onHorizontalViewportChanged(true);
  }
  isScrolling() {
    return this.isScrollActive;
  }
  fireScrollEvent(direction) {
    const bodyScrollEvent = {
      type: "bodyScroll",
      direction: direction === 1 ? "horizontal" : "vertical",
      left: this.scrollLeft,
      top: this.scrollTop
    };
    this.isScrollActive = true;
    this.eventSvc.dispatchEvent(bodyScrollEvent);
    window.clearTimeout(this.scrollTimer);
    this.scrollTimer = window.setTimeout(() => {
      this.scrollTimer = 0;
      this.isScrollActive = false;
      this.eventSvc.dispatchEvent({
        ...bodyScrollEvent,
        type: "bodyScrollEnd"
      });
    }, SCROLL_END_TIMEOUT);
  }
  shouldBlockScrollUpdate(direction, scrollTo, touchOnly = false) {
    if (touchOnly && !_isIOSUserAgent()) {
      return false;
    }
    if (direction === 0) {
      return this.shouldBlockVerticalScroll(scrollTo);
    }
    return this.shouldBlockHorizontalScroll(scrollTo);
  }
  shouldBlockVerticalScroll(scrollTo) {
    const clientHeight = _getInnerHeight(this.eBodyViewport);
    const { scrollHeight } = this.eBodyViewport;
    return !!(scrollTo < 0 || scrollTo + clientHeight > scrollHeight);
  }
  shouldBlockHorizontalScroll(scrollTo) {
    const clientWidth = this.centerRowsCtrl.getCenterWidth();
    const { scrollWidth } = this.centerRowsCtrl.eViewport;
    if (this.enableRtl) {
      if (scrollTo > 0) {
        return true;
      }
    } else if (scrollTo < 0) {
      return true;
    }
    return Math.abs(scrollTo) + clientWidth > scrollWidth;
  }
  redrawRowsAfterScroll() {
    this.fireScrollEvent(
      0
      /* Vertical */
    );
  }
  // this is to cater for AG-3274, where grid is removed from the dom and then inserted back in again.
  // (which happens with some implementations of tabbing). this can result in horizontal scroll getting
  // reset back to the left, however no scroll event is fired. so we need to get header to also scroll
  // back to the left to be kept in sync.
  // adding and removing the grid from the DOM both resets the scroll position and
  // triggers a resize event, so notify listeners if the scroll position has changed
  checkScrollLeft() {
    const scrollLeft = this.scrollLeft;
    let hasHorizontalScrollersOutOfSync = false;
    for (const source2 of HORIZONTAL_SOURCES) {
      const viewport2 = this.getViewportForSource(source2);
      if (viewport2.scrollLeft !== scrollLeft) {
        hasHorizontalScrollersOutOfSync = true;
        break;
      }
    }
    if (hasHorizontalScrollersOutOfSync) {
      this.onHScroll(VIEWPORT);
    }
  }
  scrollGridIfNeeded(suppressedAnimationFrame = false) {
    const frameNeeded = this.scrollTop != this.nextScrollTop;
    if (frameNeeded) {
      this.scrollTop = this.nextScrollTop;
      if (suppressedAnimationFrame) {
        this.invalidateVerticalScroll();
      }
      this.redrawRowsAfterScroll();
    }
    return frameNeeded;
  }
  // called by scrollHorizontally method and alignedGridsService
  setHorizontalScrollPosition(hScrollPosition, fromAlignedGridsService = false) {
    const minScrollLeft = 0;
    const maxScrollLeft = this.centerRowsCtrl.eViewport.scrollWidth - this.centerRowsCtrl.getCenterWidth();
    if (!fromAlignedGridsService && this.shouldBlockScrollUpdate(1, hScrollPosition)) {
      if (this.enableRtl) {
        hScrollPosition = hScrollPosition > 0 ? 0 : maxScrollLeft;
      } else {
        hScrollPosition = Math.min(Math.max(hScrollPosition, minScrollLeft), maxScrollLeft);
      }
    }
    _setScrollLeft(this.centerRowsCtrl.eViewport, Math.abs(hScrollPosition), this.enableRtl);
    this.doHorizontalScroll(hScrollPosition);
  }
  setVerticalScrollPosition(vScrollPosition) {
    this.invalidateVerticalScroll();
    this.eBodyViewport.scrollTop = vScrollPosition;
  }
  getVScrollPosition() {
    if (!this.isVerticalPositionInvalidated) {
      const { lastOffsetHeight, lastScrollTop } = this;
      return {
        top: lastScrollTop,
        bottom: lastScrollTop + lastOffsetHeight
      };
    }
    this.isVerticalPositionInvalidated = false;
    const { scrollTop, offsetHeight } = this.eBodyViewport;
    this.lastScrollTop = scrollTop;
    this.lastOffsetHeight = offsetHeight;
    return {
      top: scrollTop,
      bottom: scrollTop + offsetHeight
    };
  }
  /** Get an approximate scroll position that returns the last real value read.
   * This is useful for avoiding repeated DOM reads that force the browser to recalculate styles.
   * This can have big performance improvements but may not be 100% accurate so only use if this is acceptable.
   */
  getApproximateVScollPosition() {
    if (this.lastScrollTop >= 0 && this.lastOffsetHeight >= 0) {
      return {
        top: this.scrollTop,
        bottom: this.scrollTop + this.lastOffsetHeight
      };
    }
    return this.getVScrollPosition();
  }
  getHScrollPosition() {
    return this.centerRowsCtrl.getHScrollPosition();
  }
  isHorizontalScrollShowing() {
    if (this.isHorizontalPositionInvalidated) {
      this.lastIsHorizontalScrollShowing = this.centerRowsCtrl.isHorizontalScrollShowing();
      this.isHorizontalPositionInvalidated = false;
    }
    return this.lastIsHorizontalScrollShowing;
  }
  // called by the headerRootComp and moveColumnController
  scrollHorizontally(pixels) {
    const oldScrollPosition = this.centerRowsCtrl.eViewport.scrollLeft;
    this.setHorizontalScrollPosition(oldScrollPosition + pixels);
    return this.centerRowsCtrl.eViewport.scrollLeft - oldScrollPosition;
  }
  // gets called by rowRenderer when new data loaded, as it will want to scroll to the top
  scrollToTop() {
    this.eBodyViewport.scrollTop = 0;
  }
  // Valid values for position are bottom, middle and top
  ensureNodeVisible(comparator, position = null) {
    const { rowModel } = this.beans;
    const rowCount = rowModel.getRowCount();
    let indexToSelect = -1;
    for (let i2 = 0; i2 < rowCount; i2++) {
      const node2 = rowModel.getRow(i2);
      if (typeof comparator === "function") {
        const predicate = comparator;
        if (node2 && predicate(node2)) {
          indexToSelect = i2;
          break;
        }
      } else if (comparator === node2 || comparator === node2.data) {
        indexToSelect = i2;
        break;
      }
    }
    if (indexToSelect >= 0) {
      this.ensureIndexVisible(indexToSelect, position);
    }
  }
  // Valid values for position are bottom, middle and top
  // position should be {'top','middle','bottom', or undefined/null}.
  // if undefined/null, then the grid will to the minimal amount of scrolling,
  // eg if grid needs to scroll up, it scrolls until row is on top,
  //    if grid needs to scroll down, it scrolls until row is on bottom,
  //    if row is already in view, grid does not scroll
  ensureIndexVisible(index, position, retry = 0) {
    if (_isDomLayout(this.gos, "print")) {
      return;
    }
    const { rowModel } = this.beans;
    const rowCount = rowModel.getRowCount();
    if (typeof index !== "number" || index < 0 || index >= rowCount) {
      _warn(88, { index });
      return;
    }
    this.clearRetryListeners();
    const { frameworkOverrides, pageBounds, rowContainerHeight: heightScaler, rowRenderer } = this.beans;
    frameworkOverrides.wrapIncoming(() => {
      const gridBodyCtrl = this.ctrlsSvc.getGridBodyCtrl();
      const rowNode = rowModel.getRow(index);
      let rowGotShiftedDuringOperation;
      let stickyHeightsChanged;
      let attempt = 0;
      this.invalidateVerticalScroll();
      do {
        const { stickyTopHeight, stickyBottomHeight } = gridBodyCtrl;
        const startingRowTop = rowNode.rowTop;
        const startingRowHeight = rowNode.rowHeight;
        const paginationOffset = pageBounds.getPixelOffset();
        const rowTopPixel = rowNode.rowTop - paginationOffset;
        const rowBottomPixel = rowTopPixel + rowNode.rowHeight;
        const scrollPosition = this.getVScrollPosition();
        const heightOffset = heightScaler.divStretchOffset;
        const vScrollTop = scrollPosition.top + heightOffset;
        const vScrollBottom = scrollPosition.bottom + heightOffset;
        const viewportHeight = vScrollBottom - vScrollTop;
        const pxTop = heightScaler.getScrollPositionForPixel(rowTopPixel);
        const pxBottom = heightScaler.getScrollPositionForPixel(rowBottomPixel - viewportHeight);
        const pxMiddle = Math.min((pxTop + pxBottom) / 2, rowTopPixel);
        const rowAboveViewport = vScrollTop + stickyTopHeight > rowTopPixel;
        const rowBelowViewport = vScrollBottom - stickyBottomHeight < rowBottomPixel;
        let newScrollPosition = null;
        if (position === "top") {
          newScrollPosition = pxTop - stickyTopHeight;
        } else if (position === "bottom") {
          newScrollPosition = pxBottom + stickyBottomHeight;
        } else if (position === "middle") {
          newScrollPosition = pxMiddle;
        } else if (rowAboveViewport) {
          newScrollPosition = pxTop - stickyTopHeight;
        } else if (rowBelowViewport) {
          if (pxBottom - pxTop > viewportHeight) {
            newScrollPosition = pxTop - stickyTopHeight;
          } else {
            newScrollPosition = pxBottom + stickyBottomHeight;
          }
        }
        if (newScrollPosition !== null) {
          this.setVerticalScrollPosition(newScrollPosition);
          rowRenderer.redraw({ afterScroll: true });
        }
        rowGotShiftedDuringOperation = startingRowTop !== rowNode.rowTop || startingRowHeight !== rowNode.rowHeight;
        stickyHeightsChanged = stickyTopHeight !== gridBodyCtrl.stickyTopHeight || stickyBottomHeight !== gridBodyCtrl.stickyBottomHeight;
        attempt++;
      } while ((rowGotShiftedDuringOperation || stickyHeightsChanged) && attempt < 10);
      this.animationFrameSvc?.flushAllFrames();
      if (retry < 10 && (rowNode?.stub || !this.beans.rowAutoHeight?.areRowsMeasured())) {
        const scrollTop = this.getVScrollPosition().top;
        this.clearRetryListenerFncs = this.addManagedEventListeners({
          bodyScroll: () => {
            const newScrollTop = this.getVScrollPosition().top;
            if (scrollTop === newScrollTop) {
              return;
            }
            this.clearRetryListeners();
          },
          modelUpdated: () => {
            this.clearRetryListeners();
            if (index >= rowModel.getRowCount()) {
              return;
            }
            this.ensureIndexVisible(index, position, retry + 1);
          }
        });
      }
    });
  }
  clearRetryListeners() {
    for (const callback of this.clearRetryListenerFncs) {
      callback();
    }
    this.clearRetryListenerFncs = [];
  }
  ensureColumnVisible(key2, position = "auto") {
    const { colModel, frameworkOverrides } = this.beans;
    const column2 = colModel.getCol(key2);
    if (!column2) {
      return;
    }
    if (column2.isPinned()) {
      return;
    }
    if (!this.visibleCols.isColDisplayed(column2)) {
      return;
    }
    const newHorizontalScroll = this.getPositionedHorizontalScroll(column2, position);
    frameworkOverrides.wrapIncoming(() => {
      if (newHorizontalScroll !== null) {
        this.centerRowsCtrl.setCenterViewportScrollLeft(newHorizontalScroll);
      }
      this.centerRowsCtrl.onHorizontalViewportChanged();
      this.animationFrameSvc?.flushAllFrames();
    });
  }
  getPositionedHorizontalScroll(column2, position) {
    const { columnBeforeStart, columnAfterEnd } = this.isColumnOutsideViewport(column2);
    const viewportTooSmallForColumn = this.centerRowsCtrl.getCenterWidth() < column2.getActualWidth();
    const viewportWidth = this.centerRowsCtrl.getCenterWidth();
    const isRtl = this.enableRtl;
    let alignColToStart = (isRtl ? columnBeforeStart : columnAfterEnd) || viewportTooSmallForColumn;
    let alignColToEnd = isRtl ? columnAfterEnd : columnBeforeStart;
    if (position !== "auto") {
      alignColToStart = position === "start";
      alignColToEnd = position === "end";
    }
    const isMiddle = position === "middle";
    if (alignColToStart || alignColToEnd || isMiddle) {
      const { colLeft, colMiddle, colRight } = this.getColumnBounds(column2);
      if (isMiddle) {
        return colMiddle - viewportWidth / 2;
      }
      if (alignColToStart) {
        return isRtl ? colRight : colLeft;
      }
      return isRtl ? colLeft - viewportWidth : colRight - viewportWidth;
    }
    return null;
  }
  isColumnOutsideViewport(column2) {
    const { start: viewportStart, end: viewportEnd } = this.getViewportBounds();
    const { colLeft, colRight } = this.getColumnBounds(column2);
    const isRtl = this.enableRtl;
    const columnBeforeStart = isRtl ? viewportStart > colRight : viewportEnd < colRight;
    const columnAfterEnd = isRtl ? viewportEnd < colLeft : viewportStart > colLeft;
    return { columnBeforeStart, columnAfterEnd };
  }
  getColumnBounds(column2) {
    const isRtl = this.enableRtl;
    const bodyWidth = this.visibleCols.bodyWidth;
    const colWidth = column2.getActualWidth();
    const colLeft = column2.getLeft();
    const multiplier = isRtl ? -1 : 1;
    const colLeftPixel = isRtl ? bodyWidth - colLeft : colLeft;
    const colRightPixel = colLeftPixel + colWidth * multiplier;
    const colMidPixel = colLeftPixel + colWidth / 2 * multiplier;
    return { colLeft: colLeftPixel, colMiddle: colMidPixel, colRight: colRightPixel };
  }
  getViewportBounds() {
    const viewportWidth = this.centerRowsCtrl.getCenterWidth();
    const scrollPosition = this.centerRowsCtrl.getCenterViewportScrollLeft();
    const viewportStartPixel = scrollPosition;
    const viewportEndPixel = viewportWidth + scrollPosition;
    return { start: viewportStartPixel, end: viewportEndPixel, width: viewportWidth };
  }
};
var CenterWidthFeature = class extends BeanStub {
  constructor(callback, addSpacer = false) {
    super();
    this.callback = callback;
    this.addSpacer = addSpacer;
  }
  postConstruct() {
    const listener = this.setWidth.bind(this);
    this.addManagedPropertyListener("domLayout", listener);
    this.addManagedEventListeners({
      columnContainerWidthChanged: listener,
      displayedColumnsChanged: listener,
      leftPinnedWidthChanged: listener
    });
    if (this.addSpacer) {
      this.addManagedEventListeners({
        rightPinnedWidthChanged: listener,
        scrollVisibilityChanged: listener,
        scrollbarWidthChanged: listener
      });
    }
    this.setWidth();
  }
  setWidth() {
    const printLayout = _isDomLayout(this.gos, "print");
    const { visibleCols, scrollVisibleSvc } = this.beans;
    const centerWidth = visibleCols.bodyWidth;
    const leftWidth = visibleCols.getColsLeftWidth();
    const rightWidth = visibleCols.getDisplayedColumnsRightWidth();
    let totalWidth;
    if (printLayout) {
      totalWidth = centerWidth + leftWidth + rightWidth;
    } else {
      totalWidth = centerWidth;
      if (this.addSpacer) {
        const relevantWidth = this.gos.get("enableRtl") ? leftWidth : rightWidth;
        if (relevantWidth === 0 && scrollVisibleSvc.verticalScrollShowing) {
          totalWidth += scrollVisibleSvc.getScrollbarWidth();
        }
      }
    }
    this.callback(totalWidth);
  }
};
var ViewportSizeFeature = class extends BeanStub {
  constructor(centerContainerCtrl) {
    super();
    this.centerContainerCtrl = centerContainerCtrl;
  }
  wireBeans(beans) {
    this.scrollVisibleSvc = beans.scrollVisibleSvc;
  }
  postConstruct() {
    this.beans.ctrlsSvc.whenReady(this, (p) => {
      this.gridBodyCtrl = p.gridBodyCtrl;
      this.listenForResize();
    });
    this.addManagedEventListeners({ scrollbarWidthChanged: this.onScrollbarWidthChanged.bind(this) });
    this.addManagedPropertyListeners(["alwaysShowHorizontalScroll", "alwaysShowVerticalScroll"], () => {
      this.checkViewportAndScrolls();
    });
  }
  listenForResize() {
    const { beans, centerContainerCtrl, gridBodyCtrl } = this;
    const listener = () => {
      _requestAnimationFrame(beans, () => {
        this.onCenterViewportResized();
      });
    };
    centerContainerCtrl.registerViewportResizeListener(listener);
    gridBodyCtrl.registerBodyViewportResizeListener(listener);
  }
  onScrollbarWidthChanged() {
    this.checkViewportAndScrolls();
  }
  onCenterViewportResized() {
    this.scrollVisibleSvc.updateScrollGap();
    if (this.centerContainerCtrl.isViewportInTheDOMTree()) {
      const { pinnedCols, colFlex } = this.beans;
      pinnedCols?.keepPinnedColumnsNarrowerThanViewport();
      this.checkViewportAndScrolls();
      const newWidth = this.centerContainerCtrl.getCenterWidth();
      if (newWidth !== this.centerWidth) {
        this.centerWidth = newWidth;
        colFlex?.refreshFlexedColumns({
          viewportWidth: this.centerWidth,
          updateBodyWidths: true,
          fireResizedEvent: true
        });
      }
    } else {
      this.bodyHeight = 0;
    }
  }
  // gets called every time the viewport size changes. we use this to check visibility of scrollbars
  // in the grid panel, and also to check size and position of viewport for row and column virtualisation.
  checkViewportAndScrolls() {
    this.updateScrollVisibleService();
    this.checkBodyHeight();
    this.onHorizontalViewportChanged();
    this.gridBodyCtrl.scrollFeature.checkScrollLeft();
  }
  getBodyHeight() {
    return this.bodyHeight;
  }
  checkBodyHeight() {
    const eBodyViewport = this.gridBodyCtrl.eBodyViewport;
    const bodyHeight = _getInnerHeight(eBodyViewport);
    if (this.bodyHeight !== bodyHeight) {
      this.bodyHeight = bodyHeight;
      this.eventSvc.dispatchEvent({
        type: "bodyHeightChanged"
      });
    }
  }
  updateScrollVisibleService() {
    this.updateScrollVisibleServiceImpl();
    setTimeout(this.updateScrollVisibleServiceImpl.bind(this), 500);
  }
  updateScrollVisibleServiceImpl() {
    if (!this.isAlive()) {
      return;
    }
    const params = {
      horizontalScrollShowing: this.centerContainerCtrl.isHorizontalScrollShowing(),
      verticalScrollShowing: this.gridBodyCtrl.isVerticalScrollShowing()
    };
    this.scrollVisibleSvc.setScrollsVisible(params);
  }
  // this gets called whenever a change in the viewport, so we can inform column controller it has to work
  // out the virtual columns again. gets called from following locations:
  // + ensureColVisible, scroll, init, layoutChanged, displayedColumnsChanged
  onHorizontalViewportChanged() {
    const scrollWidth = this.centerContainerCtrl.getCenterWidth();
    const scrollPosition = this.centerContainerCtrl.getViewportScrollLeft();
    this.beans.colViewport.setScrollPosition(scrollWidth, scrollPosition);
  }
};
function _suppressCellMouseEvent(gos, column2, node2, event) {
  const suppressMouseEventHandling = column2.getColDef().cellRendererParams?.suppressMouseEventHandling;
  return suppressMouseEvent(gos, column2, node2, event, suppressMouseEventHandling);
}
function _suppressFullWidthMouseEvent(gos, cellRendererParams, node2, event) {
  const suppressMouseEventHandling = cellRendererParams?.suppressMouseEventHandling;
  return suppressMouseEvent(gos, void 0, node2, event, suppressMouseEventHandling);
}
function suppressMouseEvent(gos, column2, node2, event, suppressMouseEventHandling) {
  if (!suppressMouseEventHandling) {
    return false;
  }
  return suppressMouseEventHandling(
    _addGridCommonParams(gos, {
      column: column2,
      node: node2,
      event
    })
  );
}
function _getCtrlForEventTarget(gos, eventTarget, type) {
  let sourceElement = eventTarget;
  while (sourceElement) {
    const renderedComp = _getDomData(gos, sourceElement, type);
    if (renderedComp) {
      return renderedComp;
    }
    sourceElement = sourceElement.parentElement;
  }
  return null;
}
var DOM_DATA_KEY_CELL_CTRL = "cellCtrl";
function _getCellCtrlForEventTarget(gos, eventTarget) {
  return _getCtrlForEventTarget(gos, eventTarget, DOM_DATA_KEY_CELL_CTRL);
}
var DOM_DATA_KEY_ROW_CTRL = "renderedRow";
function _getRowCtrlForEventTarget(gos, eventTarget) {
  return _getCtrlForEventTarget(gos, eventTarget, DOM_DATA_KEY_ROW_CTRL);
}
function _isUserSuppressingKeyboardEvent(gos, keyboardEvent, rowNode, column2, editing) {
  const colDefFunc = column2 ? column2.getColDef().suppressKeyboardEvent : void 0;
  if (!colDefFunc) {
    return false;
  }
  const params = _addGridCommonParams(gos, {
    event: keyboardEvent,
    editing,
    column: column2,
    node: rowNode,
    data: rowNode.data,
    colDef: column2.getColDef()
  });
  if (colDefFunc) {
    const colDefFuncResult = colDefFunc(params);
    if (colDefFuncResult) {
      return true;
    }
  }
  return false;
}
function _selectAllCells(beans) {
  const { pinnedRowModel, rowModel } = beans;
  const [isEmptyPinnedTop, isEmptyPinnedBottom] = [
    pinnedRowModel?.isEmpty("top") ?? true,
    pinnedRowModel?.isEmpty("bottom") ?? true
  ];
  const floatingStart = isEmptyPinnedTop ? null : "top";
  let floatingEnd;
  let rowEnd;
  if (isEmptyPinnedBottom) {
    floatingEnd = null;
    rowEnd = rowModel.getRowCount() - 1;
  } else {
    floatingEnd = "bottom";
    rowEnd = pinnedRowModel?.getPinnedBottomRowCount() ?? 0 - 1;
  }
  const { visibleCols, rangeSvc } = beans;
  const allDisplayedColumns = visibleCols.allCols;
  if (!rangeSvc || !allDisplayedColumns?.length) {
    return;
  }
  rangeSvc.setCellRange({
    rowStartIndex: 0,
    rowStartPinned: floatingStart,
    rowEndIndex: rowEnd,
    rowEndPinned: floatingEnd
  });
}
var A_KEYCODE = 65;
var C_KEYCODE = 67;
var V_KEYCODE = 86;
var D_KEYCODE = 68;
var Z_KEYCODE = 90;
var Y_KEYCODE = 89;
function _normaliseQwertyAzerty(keyboardEvent) {
  const { keyCode } = keyboardEvent;
  let code2;
  switch (keyCode) {
    case A_KEYCODE:
      code2 = KeyCode.A;
      break;
    case C_KEYCODE:
      code2 = KeyCode.C;
      break;
    case V_KEYCODE:
      code2 = KeyCode.V;
      break;
    case D_KEYCODE:
      code2 = KeyCode.D;
      break;
    case Z_KEYCODE:
      code2 = KeyCode.Z;
      break;
    case Y_KEYCODE:
      code2 = KeyCode.Y;
      break;
    default:
      code2 = keyboardEvent.code;
  }
  return code2;
}
var RowContainerEventsFeature = class extends BeanStub {
  constructor(element) {
    super();
    this.element = element;
  }
  postConstruct() {
    this.addKeyboardListeners();
    this.addMouseListeners();
    this.beans.touchSvc?.mockRowContextMenu(this);
    this.editSvc = this.beans.editSvc;
  }
  addKeyboardListeners() {
    const eventName = "keydown";
    const listener = this.processKeyboardEvent.bind(this, eventName);
    this.addManagedElementListeners(this.element, { [eventName]: listener });
  }
  addMouseListeners() {
    const mouseDownEvent = _isEventSupported("touchstart") ? "touchstart" : "mousedown";
    const eventNames = ["dblclick", "contextmenu", "mouseover", "mouseout", "click", mouseDownEvent];
    for (const eventName of eventNames) {
      const listener = this.processMouseEvent.bind(this, eventName);
      this.addManagedElementListeners(this.element, { [eventName]: listener });
    }
  }
  processMouseEvent(eventName, mouseEvent) {
    if (!_isEventFromThisInstance(this.beans, mouseEvent) || _isStopPropagationForAgGrid(mouseEvent)) {
      return;
    }
    const { cellCtrl, rowCtrl } = this.getControlsForEventTarget(mouseEvent.target);
    if (eventName === "contextmenu") {
      if (cellCtrl?.column) {
        cellCtrl.dispatchCellContextMenuEvent(mouseEvent);
      }
      this.beans.contextMenuSvc?.handleContextMenuMouseEvent(mouseEvent, void 0, rowCtrl, cellCtrl);
    } else {
      if (cellCtrl) {
        cellCtrl.onMouseEvent(eventName, mouseEvent);
      }
      if (rowCtrl) {
        rowCtrl.onMouseEvent(eventName, mouseEvent);
      }
    }
  }
  getControlsForEventTarget(target) {
    const { gos } = this;
    return {
      cellCtrl: _getCellCtrlForEventTarget(gos, target),
      rowCtrl: _getRowCtrlForEventTarget(gos, target)
    };
  }
  processKeyboardEvent(eventName, keyboardEvent) {
    const { cellCtrl, rowCtrl } = this.getControlsForEventTarget(keyboardEvent.target);
    if (keyboardEvent.defaultPrevented) {
      return;
    }
    if (cellCtrl) {
      this.processCellKeyboardEvent(cellCtrl, eventName, keyboardEvent);
    } else if (rowCtrl?.isFullWidth()) {
      this.processFullWidthRowKeyboardEvent(rowCtrl, eventName, keyboardEvent);
    }
  }
  processCellKeyboardEvent(cellCtrl, eventName, keyboardEvent) {
    const editing = this.editSvc?.isEditing(cellCtrl, { withOpenEditor: true }) ?? false;
    const gridProcessingAllowed = !_isUserSuppressingKeyboardEvent(
      this.gos,
      keyboardEvent,
      cellCtrl.rowNode,
      cellCtrl.column,
      editing
    );
    if (gridProcessingAllowed) {
      if (eventName === "keydown") {
        const wasScrollKey = !editing && this.beans.navigation?.handlePageScrollingKey(keyboardEvent);
        if (!wasScrollKey) {
          cellCtrl.onKeyDown(keyboardEvent);
        }
        this.doGridOperations(keyboardEvent, editing);
        if (_isEventFromPrintableCharacter(keyboardEvent)) {
          cellCtrl.processCharacter(keyboardEvent);
        }
      }
    }
    if (eventName === "keydown") {
      this.eventSvc.dispatchEvent(cellCtrl.createEvent(keyboardEvent, "cellKeyDown"));
    }
  }
  processFullWidthRowKeyboardEvent(rowCtrl, eventName, keyboardEvent) {
    const { rowNode } = rowCtrl;
    const { focusSvc, navigation: navigation2 } = this.beans;
    const focusedCell = focusSvc.getFocusedCell();
    const column2 = focusedCell?.column;
    const gridProcessingAllowed = !_isUserSuppressingKeyboardEvent(this.gos, keyboardEvent, rowNode, column2, false);
    if (gridProcessingAllowed) {
      const key2 = keyboardEvent.key;
      if (eventName === "keydown") {
        switch (key2) {
          case KeyCode.PAGE_HOME:
          case KeyCode.PAGE_END:
          case KeyCode.PAGE_UP:
          case KeyCode.PAGE_DOWN:
            navigation2?.handlePageScrollingKey(keyboardEvent, true);
            break;
          case KeyCode.LEFT:
          case KeyCode.RIGHT:
            if (!this.gos.get("embedFullWidthRows")) {
              break;
            }
          case KeyCode.UP:
          case KeyCode.DOWN:
            rowCtrl.onKeyboardNavigate(keyboardEvent);
            break;
          case KeyCode.TAB:
            rowCtrl.onTabKeyDown(keyboardEvent);
            break;
        }
      }
    }
    if (eventName === "keydown") {
      this.eventSvc.dispatchEvent(rowCtrl.createRowEvent("cellKeyDown", keyboardEvent));
    }
  }
  doGridOperations(keyboardEvent, editing) {
    if (!keyboardEvent.ctrlKey && !keyboardEvent.metaKey) {
      return;
    }
    if (editing) {
      return;
    }
    if (!_isEventFromThisInstance(this.beans, keyboardEvent)) {
      return;
    }
    const keyCode = _normaliseQwertyAzerty(keyboardEvent);
    const { clipboardSvc, undoRedo } = this.beans;
    if (keyCode === KeyCode.A) {
      return this.onCtrlAndA(keyboardEvent);
    }
    if (keyCode === KeyCode.C) {
      return this.onCtrlAndC(clipboardSvc, keyboardEvent);
    }
    if (keyCode === KeyCode.D) {
      return this.onCtrlAndD(clipboardSvc, keyboardEvent);
    }
    if (keyCode === KeyCode.V) {
      return this.onCtrlAndV(clipboardSvc, keyboardEvent);
    }
    if (keyCode === KeyCode.X) {
      return this.onCtrlAndX(clipboardSvc, keyboardEvent);
    }
    if (keyCode === KeyCode.Y) {
      return this.onCtrlAndY(undoRedo);
    }
    if (keyCode === KeyCode.Z) {
      return this.onCtrlAndZ(undoRedo, keyboardEvent);
    }
  }
  onCtrlAndA(event) {
    const {
      beans: { rowModel, rangeSvc, selectionSvc },
      gos
    } = this;
    if (rangeSvc && _isCellSelectionEnabled(gos) && !_getCtrlASelectsRows(gos) && rowModel.isRowsToRender()) {
      _selectAllCells(this.beans);
    } else if (selectionSvc) {
      selectionSvc.selectAllRowNodes({ source: "keyboardSelectAll", selectAll: _getSelectAll(gos) });
    }
    event.preventDefault();
  }
  onCtrlAndC(clipboardSvc, event) {
    if (!clipboardSvc || this.gos.get("enableCellTextSelection")) {
      return;
    }
    const { cellCtrl } = this.getControlsForEventTarget(event.target);
    if (this.editSvc?.isEditing(cellCtrl, { withOpenEditor: true })) {
      return;
    }
    event.preventDefault();
    clipboardSvc.copyToClipboard();
  }
  onCtrlAndX(clipboardSvc, event) {
    if (!clipboardSvc || this.gos.get("enableCellTextSelection") || this.gos.get("suppressCutToClipboard")) {
      return;
    }
    const { cellCtrl } = this.getControlsForEventTarget(event.target);
    if (this.editSvc?.isEditing(cellCtrl, { withOpenEditor: true })) {
      return;
    }
    event.preventDefault();
    clipboardSvc.cutToClipboard(void 0, "ui");
  }
  onCtrlAndV(clipboardSvc, event) {
    const { cellCtrl } = this.getControlsForEventTarget(event.target);
    if (this.editSvc?.isEditing(cellCtrl, { withOpenEditor: true })) {
      return;
    }
    if (clipboardSvc && !this.gos.get("suppressClipboardPaste")) {
      clipboardSvc.pasteFromClipboard();
    }
  }
  onCtrlAndD(clipboardSvc, event) {
    if (clipboardSvc && !this.gos.get("suppressClipboardPaste")) {
      clipboardSvc.copyRangeDown();
    }
    event.preventDefault();
  }
  onCtrlAndZ(undoRedo, event) {
    if (!this.gos.get("undoRedoCellEditing") || !undoRedo) {
      return;
    }
    event.preventDefault();
    if (event.shiftKey) {
      undoRedo.redo("ui");
    } else {
      undoRedo.undo("ui");
    }
  }
  onCtrlAndY(undoRedo) {
    undoRedo?.redo("ui");
  }
};
var SetHeightFeature = class extends BeanStub {
  constructor(eContainer, eViewport) {
    super();
    this.eContainer = eContainer;
    this.eViewport = eViewport;
  }
  postConstruct() {
    this.addManagedEventListeners({
      rowContainerHeightChanged: this.onHeightChanged.bind(this, this.beans.rowContainerHeight)
    });
  }
  onHeightChanged(maxDivHeightScaler) {
    const height = maxDivHeightScaler.uiContainerHeight;
    const heightString = height != null ? `${height}px` : ``;
    this.eContainer.style.height = heightString;
    if (this.eViewport) {
      this.eViewport.style.height = heightString;
    }
  }
};
var getTopRowCtrls = (r2) => r2.topRowCtrls;
var getStickyTopRowCtrls = (r2) => r2.getStickyTopRowCtrls();
var getStickyBottomRowCtrls = (r2) => r2.getStickyBottomRowCtrls();
var getBottomRowCtrls = (r2) => r2.bottomRowCtrls;
var getCentreRowCtrls = (r2) => r2.allRowCtrls;
var getSpannedTopRowCtrls = (r2) => r2.getCtrls("top");
var getSpannedCenterRowCtrls = (r2) => r2.getCtrls("center");
var getSpannedBottomRowCtrls = (r2) => r2.getCtrls("bottom");
var ContainerCssClasses = {
  center: {
    type: "center",
    name: "center-cols",
    getRowCtrls: getCentreRowCtrls,
    getSpannedRowCtrls: getSpannedCenterRowCtrls
  },
  left: {
    type: "left",
    name: "pinned-left-cols",
    pinnedType: "left",
    getRowCtrls: getCentreRowCtrls,
    getSpannedRowCtrls: getSpannedCenterRowCtrls
  },
  right: {
    type: "right",
    name: "pinned-right-cols",
    pinnedType: "right",
    getRowCtrls: getCentreRowCtrls,
    getSpannedRowCtrls: getSpannedCenterRowCtrls
  },
  fullWidth: {
    type: "fullWidth",
    name: "full-width",
    fullWidth: true,
    getRowCtrls: getCentreRowCtrls
  },
  topCenter: {
    type: "center",
    name: "floating-top",
    getRowCtrls: getTopRowCtrls,
    getSpannedRowCtrls: getSpannedTopRowCtrls
  },
  topLeft: {
    type: "left",
    name: "pinned-left-floating",
    container: "ag-pinned-left-floating-top",
    pinnedType: "left",
    getRowCtrls: getTopRowCtrls,
    getSpannedRowCtrls: getSpannedTopRowCtrls
  },
  topRight: {
    type: "right",
    name: "pinned-right-floating",
    container: "ag-pinned-right-floating-top",
    pinnedType: "right",
    getRowCtrls: getTopRowCtrls,
    getSpannedRowCtrls: getSpannedTopRowCtrls
  },
  topFullWidth: {
    type: "fullWidth",
    name: "floating-top-full-width",
    fullWidth: true,
    getRowCtrls: getTopRowCtrls
  },
  stickyTopCenter: {
    type: "center",
    name: "sticky-top",
    getRowCtrls: getStickyTopRowCtrls
  },
  stickyTopLeft: {
    type: "left",
    name: "pinned-left-sticky-top",
    container: "ag-pinned-left-sticky-top",
    pinnedType: "left",
    getRowCtrls: getStickyTopRowCtrls
  },
  stickyTopRight: {
    type: "right",
    name: "pinned-right-sticky-top",
    container: "ag-pinned-right-sticky-top",
    pinnedType: "right",
    getRowCtrls: getStickyTopRowCtrls
  },
  stickyTopFullWidth: {
    type: "fullWidth",
    name: "sticky-top-full-width",
    fullWidth: true,
    getRowCtrls: getStickyTopRowCtrls
  },
  stickyBottomCenter: {
    type: "center",
    name: "sticky-bottom",
    getRowCtrls: getStickyBottomRowCtrls
  },
  stickyBottomLeft: {
    type: "left",
    name: "pinned-left-sticky-bottom",
    container: "ag-pinned-left-sticky-bottom",
    pinnedType: "left",
    getRowCtrls: getStickyBottomRowCtrls
  },
  stickyBottomRight: {
    type: "right",
    name: "pinned-right-sticky-bottom",
    container: "ag-pinned-right-sticky-bottom",
    pinnedType: "right",
    getRowCtrls: getStickyBottomRowCtrls
  },
  stickyBottomFullWidth: {
    type: "fullWidth",
    name: "sticky-bottom-full-width",
    fullWidth: true,
    getRowCtrls: getStickyBottomRowCtrls
  },
  bottomCenter: {
    type: "center",
    name: "floating-bottom",
    getRowCtrls: getBottomRowCtrls,
    getSpannedRowCtrls: getSpannedBottomRowCtrls
  },
  bottomLeft: {
    type: "left",
    name: "pinned-left-floating-bottom",
    container: "ag-pinned-left-floating-bottom",
    pinnedType: "left",
    getRowCtrls: getBottomRowCtrls,
    getSpannedRowCtrls: getSpannedBottomRowCtrls
  },
  bottomRight: {
    type: "right",
    name: "pinned-right-floating-bottom",
    container: "ag-pinned-right-floating-bottom",
    pinnedType: "right",
    getRowCtrls: getBottomRowCtrls,
    getSpannedRowCtrls: getSpannedBottomRowCtrls
  },
  bottomFullWidth: {
    type: "fullWidth",
    name: "floating-bottom-full-width",
    fullWidth: true,
    getRowCtrls: getBottomRowCtrls
  }
};
function _getRowViewportClass(name2) {
  const options = _getRowContainerOptions(name2);
  return `ag-${options.name}-viewport`;
}
function _getRowContainerClass(name2) {
  const options = _getRowContainerOptions(name2);
  return options.container ?? `ag-${options.name}-container`;
}
function _getRowSpanContainerClass(name2) {
  const options = _getRowContainerOptions(name2);
  return `ag-${options.name}-spanned-cells-container`;
}
function _getRowContainerOptions(name2) {
  return ContainerCssClasses[name2];
}
var allTopNoFW = ["topCenter", "topLeft", "topRight"];
var allBottomNoFW = ["bottomCenter", "bottomLeft", "bottomRight"];
var allMiddleNoFW = ["center", "left", "right"];
var allMiddle = ["center", "left", "right", "fullWidth"];
var allCenter = ["stickyTopCenter", "stickyBottomCenter", "center", "topCenter", "bottomCenter"];
var allLeft = ["left", "bottomLeft", "topLeft", "stickyTopLeft", "stickyBottomLeft"];
var allRight = ["right", "bottomRight", "topRight", "stickyTopRight", "stickyBottomRight"];
var allStickyTopNoFW = ["stickyTopCenter", "stickyTopLeft", "stickyTopRight"];
var allStickyBottomNoFW = ["stickyBottomCenter", "stickyBottomLeft", "stickyBottomRight"];
var allStickyContainers = [
  ...allStickyTopNoFW,
  "stickyTopFullWidth",
  ...allStickyBottomNoFW,
  "stickyBottomFullWidth"
];
var allNoFW = [
  ...allTopNoFW,
  ...allBottomNoFW,
  ...allMiddleNoFW,
  ...allStickyTopNoFW,
  ...allStickyBottomNoFW
];
var RowContainerCtrl = class extends BeanStub {
  constructor(name2) {
    super();
    this.name = name2;
    this.visible = true;
    this.EMPTY_CTRLS = [];
    this.options = _getRowContainerOptions(name2);
  }
  postConstruct() {
    this.enableRtl = this.gos.get("enableRtl");
    this.forContainers(["center"], () => {
      this.viewportSizeFeature = this.createManagedBean(new ViewportSizeFeature(this));
      this.addManagedEventListeners({
        stickyTopOffsetChanged: this.onStickyTopOffsetChanged.bind(this)
      });
    });
  }
  onStickyTopOffsetChanged(event) {
    this.comp.setOffsetTop(`${event.offset}px`);
  }
  registerWithCtrlsService() {
    if (this.options.fullWidth) {
      return;
    }
    this.beans.ctrlsSvc.register(this.name, this);
  }
  forContainers(names, callback) {
    if (names.indexOf(this.name) >= 0) {
      callback();
    }
  }
  setComp(view, eContainer, eSpannedContainer, eViewport) {
    this.comp = view;
    this.eContainer = eContainer;
    this.eSpannedContainer = eSpannedContainer;
    this.eViewport = eViewport;
    this.createManagedBean(new RowContainerEventsFeature(this.eViewport ?? this.eContainer));
    this.addPreventScrollWhileDragging();
    this.listenOnDomOrder();
    const { pinnedCols, rangeSvc } = this.beans;
    const pinnedWidthChanged = () => this.onPinnedWidthChanged();
    this.forContainers(allLeft, () => {
      this.pinnedWidthFeature = this.createOptionalManagedBean(
        pinnedCols?.createPinnedWidthFeature(true, this.eContainer, this.eSpannedContainer)
      );
      this.addManagedEventListeners({ leftPinnedWidthChanged: pinnedWidthChanged });
    });
    this.forContainers(allRight, () => {
      this.pinnedWidthFeature = this.createOptionalManagedBean(
        pinnedCols?.createPinnedWidthFeature(false, this.eContainer, this.eSpannedContainer)
      );
      this.addManagedEventListeners({ rightPinnedWidthChanged: pinnedWidthChanged });
    });
    this.forContainers(
      allMiddle,
      () => this.createManagedBean(
        new SetHeightFeature(this.eContainer, this.name === "center" ? eViewport : void 0)
      )
    );
    if (rangeSvc) {
      this.forContainers(
        allNoFW,
        () => this.createManagedBean(rangeSvc.createDragListenerFeature(this.eContainer))
      );
    }
    this.forContainers(
      allCenter,
      () => this.createManagedBean(new CenterWidthFeature((width) => this.comp.setContainerWidth(`${width}px`)))
    );
    this.visible = this.isContainerVisible();
    this.addListeners();
    this.registerWithCtrlsService();
  }
  onScrollCallback(fn3) {
    this.addManagedElementListeners(this.eViewport, { scroll: fn3 });
  }
  addListeners() {
    const { spannedRowRenderer, gos } = this.beans;
    const onDisplayedColumnsChanged = this.onDisplayedColumnsChanged.bind(this);
    this.addManagedEventListeners({
      displayedColumnsChanged: onDisplayedColumnsChanged,
      displayedColumnsWidthChanged: onDisplayedColumnsChanged,
      displayedRowsChanged: (params) => this.onDisplayedRowsChanged(params.afterScroll)
    });
    onDisplayedColumnsChanged();
    this.onDisplayedRowsChanged();
    if (spannedRowRenderer && this.options.getSpannedRowCtrls && gos.get("enableCellSpan")) {
      this.addManagedListeners(spannedRowRenderer, {
        spannedRowsUpdated: () => {
          const spannedCtrls = this.options.getSpannedRowCtrls(spannedRowRenderer);
          if (!spannedCtrls) {
            return;
          }
          this.comp.setSpannedRowCtrls(spannedCtrls, false);
        }
      });
    }
  }
  listenOnDomOrder() {
    const isStickContainer = allStickyContainers.indexOf(this.name) >= 0;
    if (isStickContainer) {
      this.comp.setDomOrder(true);
      return;
    }
    const listener = () => {
      const isEnsureDomOrder = this.gos.get("ensureDomOrder");
      const isPrintLayout = _isDomLayout(this.gos, "print");
      this.comp.setDomOrder(isEnsureDomOrder || isPrintLayout);
    };
    this.addManagedPropertyListener("domLayout", listener);
    listener();
  }
  onDisplayedColumnsChanged() {
    this.forContainers(["center"], () => this.onHorizontalViewportChanged());
  }
  // this methods prevents the grid views from being scrolled while the dragService is being used
  // eg. the view should not scroll up and down while dragging rows using the rowDragComp.
  addPreventScrollWhileDragging() {
    const { dragSvc } = this.beans;
    if (!dragSvc) {
      return;
    }
    const preventScroll = (e) => {
      if (dragSvc.dragging) {
        if (e.cancelable) {
          e.preventDefault();
        }
      }
    };
    this.eContainer.addEventListener("touchmove", preventScroll, { passive: false });
    this.addDestroyFunc(() => this.eContainer.removeEventListener("touchmove", preventScroll));
  }
  // this gets called whenever a change in the viewport, so we can inform column controller it has to work
  // out the virtual columns again. gets called from following locations:
  // + ensureColVisible, scroll, init, layoutChanged, displayedColumnsChanged
  onHorizontalViewportChanged(afterScroll = false) {
    const scrollWidth = this.getCenterWidth();
    const scrollPosition = this.getCenterViewportScrollLeft();
    this.beans.colViewport.setScrollPosition(scrollWidth, scrollPosition, afterScroll);
  }
  hasHorizontalScrollGap() {
    return this.eContainer.clientWidth - this.eViewport.clientWidth < 0;
  }
  hasVerticalScrollGap() {
    return this.eContainer.clientHeight - this.eViewport.clientHeight < 0;
  }
  getCenterWidth() {
    return _getInnerWidth(this.eViewport);
  }
  getCenterViewportScrollLeft() {
    return _getScrollLeft(this.eViewport, this.enableRtl);
  }
  registerViewportResizeListener(listener) {
    const unsubscribeFromResize = _observeResize(this.beans, this.eViewport, listener);
    this.addDestroyFunc(() => unsubscribeFromResize());
  }
  isViewportInTheDOMTree() {
    return _isInDOM(this.eViewport);
  }
  getViewportScrollLeft() {
    return _getScrollLeft(this.eViewport, this.enableRtl);
  }
  isHorizontalScrollShowing() {
    const isAlwaysShowHorizontalScroll = this.gos.get("alwaysShowHorizontalScroll");
    return isAlwaysShowHorizontalScroll || _isHorizontalScrollShowing(this.eViewport);
  }
  setHorizontalScroll(offset3) {
    this.comp.setHorizontalScroll(offset3);
  }
  getHScrollPosition() {
    const res = {
      left: this.eViewport.scrollLeft,
      right: this.eViewport.scrollLeft + this.eViewport.offsetWidth
    };
    return res;
  }
  setCenterViewportScrollLeft(value2) {
    _setScrollLeft(this.eViewport, value2, this.enableRtl);
  }
  isContainerVisible() {
    const pinned = this.options.pinnedType != null;
    return !pinned || !!this.pinnedWidthFeature && this.pinnedWidthFeature.getWidth() > 0;
  }
  onPinnedWidthChanged() {
    const visible2 = this.isContainerVisible();
    if (this.visible != visible2) {
      this.visible = visible2;
      this.onDisplayedRowsChanged();
    }
  }
  onDisplayedRowsChanged(afterScroll = false) {
    const rows = this.options.getRowCtrls(this.beans.rowRenderer);
    if (!this.visible || rows.length === 0) {
      this.comp.setRowCtrls({ rowCtrls: this.EMPTY_CTRLS });
      return;
    }
    const printLayout = _isDomLayout(this.gos, "print");
    const embedFullWidthRows = this.gos.get("embedFullWidthRows");
    const embedFW = embedFullWidthRows || printLayout;
    const rowsThisContainer = rows.filter((rowCtrl) => {
      const fullWidthRow = rowCtrl.isFullWidth();
      const match3 = this.options.fullWidth ? !embedFW && fullWidthRow : embedFW || !fullWidthRow;
      return match3;
    });
    this.comp.setRowCtrls({ rowCtrls: rowsThisContainer, useFlushSync: afterScroll });
  }
};
var CSS_CLASS_FORCE_VERTICAL_SCROLL = "ag-force-vertical-scroll";
var CSS_CLASS_CELL_SELECTABLE = "ag-selectable";
var CSS_CLASS_COLUMN_MOVING = "ag-column-moving";
var GridBodyCtrl = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.stickyTopHeight = 0;
    this.stickyBottomHeight = 0;
  }
  wireBeans(beans) {
    this.ctrlsSvc = beans.ctrlsSvc;
    this.colModel = beans.colModel;
    this.scrollVisibleSvc = beans.scrollVisibleSvc;
    this.pinnedRowModel = beans.pinnedRowModel;
    this.filterManager = beans.filterManager;
    this.rowGroupColsSvc = beans.rowGroupColsSvc;
  }
  setComp(comp, eGridBody, eBodyViewport, eTop, eBottom, eStickyTop, eStickyBottom) {
    this.comp = comp;
    this.eGridBody = eGridBody;
    this.eBodyViewport = eBodyViewport;
    this.eTop = eTop;
    this.eBottom = eBottom;
    this.eStickyTop = eStickyTop;
    this.eStickyBottom = eStickyBottom;
    this.eCenterColsViewport = eBodyViewport.querySelector(`.${_getRowViewportClass("center")}`);
    this.eFullWidthContainer = eBodyViewport.querySelector(`.${_getRowContainerClass("fullWidth")}`);
    this.eStickyTopFullWidthContainer = eStickyTop.querySelector(
      `.${_getRowContainerClass("stickyTopFullWidth")}`
    );
    this.eStickyBottomFullWidthContainer = eStickyBottom.querySelector(
      `.${_getRowContainerClass("stickyBottomFullWidth")}`
    );
    this.setCellTextSelection(this.gos.get("enableCellTextSelection"));
    this.addManagedPropertyListener(
      "enableCellTextSelection",
      (props) => this.setCellTextSelection(props.currentValue)
    );
    this.createManagedBean(new LayoutFeature(this.comp));
    this.scrollFeature = this.createManagedBean(new GridBodyScrollFeature(eBodyViewport));
    this.beans.rowDragSvc?.setupRowDrag(eBodyViewport, this);
    this.setupRowAnimationCssClass();
    this.addEventListeners();
    this.addFocusListeners([eTop, eBodyViewport, eBottom, eStickyTop, eStickyBottom]);
    this.setGridRootRole();
    this.onGridColumnsChanged();
    this.addBodyViewportListener();
    this.setFloatingHeights();
    this.disableBrowserDragging();
    this.addStopEditingWhenGridLosesFocus();
    this.updateScrollingClasses();
    this.filterManager?.setupAdvFilterHeaderComp(eTop);
    this.ctrlsSvc.register("gridBodyCtrl", this);
  }
  addEventListeners() {
    const setFloatingHeights = this.setFloatingHeights.bind(this);
    const setGridRootRole = this.setGridRootRole.bind(this);
    const toggleRowResizeStyle = this.toggleRowResizeStyles.bind(this);
    this.addManagedEventListeners({
      gridColumnsChanged: this.onGridColumnsChanged.bind(this),
      scrollVisibilityChanged: this.onScrollVisibilityChanged.bind(this),
      scrollGapChanged: this.updateScrollingClasses.bind(this),
      pinnedRowDataChanged: setFloatingHeights,
      pinnedHeightChanged: setFloatingHeights,
      pinnedRowsChanged: setFloatingHeights,
      headerHeightChanged: this.setStickyTopOffsetTop.bind(this),
      columnRowGroupChanged: setGridRootRole,
      columnPivotChanged: setGridRootRole,
      rowResizeStarted: toggleRowResizeStyle,
      rowResizeEnded: toggleRowResizeStyle
    });
    this.addManagedPropertyListener("treeData", setGridRootRole);
  }
  toggleRowResizeStyles(params) {
    const isResizingRow = params.type === "rowResizeStarted";
    this.eBodyViewport.classList.toggle("ag-prevent-animation", isResizingRow);
  }
  onGridColumnsChanged() {
    const columns2 = this.beans.colModel.getCols();
    this.comp.setColumnCount(columns2.length);
  }
  onScrollVisibilityChanged() {
    const { scrollVisibleSvc } = this;
    const visible2 = scrollVisibleSvc.verticalScrollShowing;
    this.setVerticalScrollPaddingVisible(visible2);
    this.setStickyWidth(visible2);
    this.setStickyBottomOffsetBottom();
    const scrollbarWidth = visible2 ? scrollVisibleSvc.getScrollbarWidth() || 0 : 0;
    const pad3 = _isInvisibleScrollbar() ? 16 : 0;
    const width = `calc(100% + ${scrollbarWidth + pad3}px)`;
    _requestAnimationFrame(this.beans, () => this.comp.setBodyViewportWidth(width));
    this.updateScrollingClasses();
  }
  setGridRootRole() {
    const { rowGroupColsSvc, colModel } = this;
    let isTreeGrid = this.gos.get("treeData");
    if (!isTreeGrid) {
      const isPivotActive = colModel.isPivotMode();
      const rowGroupColumnLen = !rowGroupColsSvc ? 0 : rowGroupColsSvc.columns.length;
      const columnsNeededForGrouping = isPivotActive ? 2 : 1;
      isTreeGrid = rowGroupColumnLen >= columnsNeededForGrouping;
    }
    this.comp.setGridRootRole(isTreeGrid ? "treegrid" : "grid");
  }
  addFocusListeners(elements) {
    for (const element of elements) {
      this.addManagedElementListeners(element, {
        focusin: (e) => {
          const { target } = e;
          const isFocusedElementNested = _isElementChildOfClass(target, "ag-root", element);
          element.classList.toggle("ag-has-focus", !isFocusedElementNested);
        },
        focusout: (e) => {
          const { target, relatedTarget } = e;
          const gridContainRelatedTarget = element.contains(relatedTarget);
          const isNestedRelatedTarget = _isElementChildOfClass(
            relatedTarget,
            "ag-root",
            element
          );
          const isNestedTarget = _isElementChildOfClass(target, "ag-root", element);
          if (isNestedTarget) {
            return;
          }
          if (!gridContainRelatedTarget || isNestedRelatedTarget) {
            element.classList.remove("ag-has-focus");
          }
        }
      });
    }
  }
  // used by ColumnAnimationService
  setColumnMovingCss(moving) {
    this.comp.setColumnMovingCss(CSS_CLASS_COLUMN_MOVING, moving);
  }
  setCellTextSelection(selectable = false) {
    this.comp.setCellSelectableCss(CSS_CLASS_CELL_SELECTABLE, selectable);
  }
  updateScrollingClasses() {
    const {
      eGridBody: { classList },
      scrollVisibleSvc
    } = this;
    classList.toggle("ag-body-vertical-content-no-gap", !scrollVisibleSvc.verticalScrollGap);
    classList.toggle("ag-body-horizontal-content-no-gap", !scrollVisibleSvc.horizontalScrollGap);
  }
  // if we do not do this, then the user can select a pic in the grid (eg an image in a custom cell renderer)
  // and then that will start the browser native drag n' drop, which messes up with our own drag and drop.
  disableBrowserDragging() {
    this.addManagedElementListeners(this.eGridBody, {
      dragstart: (event) => {
        if (event.target instanceof HTMLImageElement) {
          event.preventDefault();
          return false;
        }
      }
    });
  }
  addStopEditingWhenGridLosesFocus() {
    this.beans.editSvc?.addStopEditingWhenGridLosesFocus([
      this.eBodyViewport,
      this.eBottom,
      this.eTop,
      this.eStickyTop,
      this.eStickyBottom
    ]);
  }
  updateRowCount() {
    const headerCount = (this.ctrlsSvc.getHeaderRowContainerCtrl()?.getRowCount() ?? 0) + (this.filterManager?.getHeaderRowCount() ?? 0);
    const { rowModel } = this.beans;
    const rowCount = rowModel.isLastRowIndexKnown() ? rowModel.getRowCount() : -1;
    const total = rowCount === -1 ? -1 : headerCount + rowCount;
    this.comp.setRowCount(total);
  }
  registerBodyViewportResizeListener(listener) {
    this.comp.registerBodyViewportResizeListener(listener);
  }
  setVerticalScrollPaddingVisible(visible2) {
    const overflowY = visible2 ? "scroll" : "hidden";
    this.comp.setPinnedTopBottomOverflowY(overflowY);
  }
  isVerticalScrollShowing() {
    const show = this.gos.get("alwaysShowVerticalScroll");
    const cssClass = show ? CSS_CLASS_FORCE_VERTICAL_SCROLL : null;
    const allowVerticalScroll = _isDomLayout(this.gos, "normal");
    this.comp.setAlwaysVerticalScrollClass(cssClass, show);
    return show || allowVerticalScroll && _isVerticalScrollShowing(this.eBodyViewport);
  }
  setupRowAnimationCssClass() {
    const { rowContainerHeight, environment } = this.beans;
    let initialSizeMeasurementComplete = environment.sizesMeasured;
    const updateAnimationClass = () => {
      const animateRows = initialSizeMeasurementComplete && _isAnimateRows(this.gos) && !rowContainerHeight.stretching;
      const animateRowsCssClass = animateRows ? "ag-row-animation" : "ag-row-no-animation";
      this.comp.setRowAnimationCssOnBodyViewport(animateRowsCssClass, animateRows);
    };
    updateAnimationClass();
    this.addManagedEventListeners({ heightScaleChanged: updateAnimationClass });
    this.addManagedPropertyListener("animateRows", updateAnimationClass);
    this.addManagedEventListeners({
      gridStylesChanged: () => {
        if (!initialSizeMeasurementComplete && environment.sizesMeasured) {
          initialSizeMeasurementComplete = true;
          updateAnimationClass();
        }
      }
    });
  }
  addBodyViewportListener() {
    const {
      eBodyViewport,
      eStickyTop,
      eStickyBottom,
      eTop,
      eBottom,
      beans: { popupSvc, touchSvc }
    } = this;
    const listener = this.onBodyViewportContextMenu.bind(this);
    this.addManagedElementListeners(eBodyViewport, { contextmenu: listener });
    touchSvc?.mockBodyContextMenu(this, listener);
    this.addManagedElementListeners(eBodyViewport, {
      wheel: this.onBodyViewportWheel.bind(this, popupSvc)
    });
    const onStickyWheel = this.onStickyWheel.bind(this);
    for (const container2 of [eStickyTop, eStickyBottom, eTop, eBottom]) {
      this.addManagedElementListeners(container2, { wheel: onStickyWheel });
    }
    const onHorizontalWheel = this.onHorizontalWheel.bind(this);
    for (const container2 of ["left", "right", "topLeft", "topRight", "bottomLeft", "bottomRight"]) {
      this.addManagedElementListeners(this.ctrlsSvc.get(container2).eContainer, {
        wheel: onHorizontalWheel
      });
    }
    this.addFullWidthContainerWheelListener();
  }
  addFullWidthContainerWheelListener() {
    this.addManagedElementListeners(this.eFullWidthContainer, {
      wheel: (e) => this.onFullWidthContainerWheel(e)
    });
  }
  onFullWidthContainerWheel(e) {
    const { deltaX, deltaY, shiftKey } = e;
    const isHorizontalScroll = shiftKey || Math.abs(deltaX) > Math.abs(deltaY);
    if (isHorizontalScroll && _isEventFromThisInstance(this.beans, e)) {
      this.scrollGridBodyToMatchEvent(e);
    }
  }
  onStickyWheel(e) {
    const { deltaY } = e;
    const scrolled = this.scrollVertically(deltaY);
    if (scrolled > 0) {
      e.preventDefault();
    }
  }
  onHorizontalWheel(e) {
    const { deltaX, deltaY, shiftKey } = e;
    const isHorizontalScroll = shiftKey || Math.abs(deltaX) > Math.abs(deltaY);
    if (!isHorizontalScroll) {
      return;
    }
    this.scrollGridBodyToMatchEvent(e);
  }
  scrollGridBodyToMatchEvent(e) {
    const { deltaX, deltaY } = e;
    e.preventDefault();
    this.eCenterColsViewport.scrollBy({ left: deltaX || deltaY });
  }
  onBodyViewportContextMenu(mouseEvent, touch, touchEvent) {
    if (!mouseEvent && !touchEvent) {
      return;
    }
    if (this.gos.get("preventDefaultOnContextMenu")) {
      const event = mouseEvent || touchEvent;
      event.preventDefault();
    }
    const { target } = mouseEvent || touch;
    if (target === this.eBodyViewport || target === this.ctrlsSvc.get("center").eViewport) {
      this.beans.contextMenuSvc?.showContextMenu({
        mouseEvent,
        touchEvent,
        value: null,
        anchorToElement: this.eGridBody,
        source: "ui"
      });
    }
  }
  onBodyViewportWheel(popupSvc, e) {
    if (!this.gos.get("suppressScrollWhenPopupsAreOpen")) {
      return;
    }
    if (popupSvc?.hasAnchoredPopup()) {
      e.preventDefault();
    }
  }
  // called by rowDragFeature
  scrollVertically(pixels) {
    const oldScrollPosition = this.eBodyViewport.scrollTop;
    this.scrollFeature.setVerticalScrollPosition(oldScrollPosition + pixels);
    return this.eBodyViewport.scrollTop - oldScrollPosition;
  }
  setFloatingHeights() {
    const {
      pinnedRowModel,
      beans: { environment }
    } = this;
    const floatingTopHeight = pinnedRowModel?.getPinnedTopTotalHeight();
    const floatingBottomHeight = pinnedRowModel?.getPinnedBottomTotalHeight();
    const pinnedBorderWidth = environment.getPinnedRowBorderWidth();
    const rowBorderWidth = environment.getRowBorderWidth();
    const additionalHeight = pinnedBorderWidth - rowBorderWidth;
    const normalisedFloatingTopHeight = !floatingTopHeight ? 0 : additionalHeight + floatingTopHeight;
    const normalisedFloatingBottomHeight = !floatingBottomHeight ? 0 : additionalHeight + floatingBottomHeight;
    this.comp.setTopHeight(normalisedFloatingTopHeight);
    this.comp.setBottomHeight(normalisedFloatingBottomHeight);
    this.comp.setTopInvisible(normalisedFloatingTopHeight <= 0);
    this.comp.setBottomInvisible(normalisedFloatingBottomHeight <= 0);
    this.setStickyTopOffsetTop();
    this.setStickyBottomOffsetBottom();
  }
  setStickyTopHeight(height = 0) {
    this.comp.setStickyTopHeight(`${height}px`);
    this.stickyTopHeight = height;
  }
  setStickyBottomHeight(height = 0) {
    this.comp.setStickyBottomHeight(`${height}px`);
    this.stickyBottomHeight = height;
  }
  setStickyWidth(vScrollVisible) {
    if (!vScrollVisible) {
      this.comp.setStickyTopWidth("100%");
      this.comp.setStickyBottomWidth("100%");
    } else {
      const scrollbarWidth = this.scrollVisibleSvc.getScrollbarWidth();
      this.comp.setStickyTopWidth(`calc(100% - ${scrollbarWidth}px)`);
      this.comp.setStickyBottomWidth(`calc(100% - ${scrollbarWidth}px)`);
    }
  }
  setStickyTopOffsetTop() {
    const headerCtrl = this.ctrlsSvc.get("gridHeaderCtrl");
    const headerHeight = headerCtrl.headerHeight + (this.filterManager?.getHeaderHeight() ?? 0);
    const pinnedTopHeight = this.pinnedRowModel?.getPinnedTopTotalHeight() ?? 0;
    let height = 0;
    if (headerHeight > 0) {
      height += headerHeight;
    }
    if (pinnedTopHeight > 0) {
      height += pinnedTopHeight;
    }
    if (height > 0) {
      height += 1;
    }
    this.comp.setStickyTopTop(`${height}px`);
  }
  setStickyBottomOffsetBottom() {
    const { pinnedRowModel, scrollVisibleSvc, comp } = this;
    const pinnedBottomHeight = pinnedRowModel?.getPinnedBottomTotalHeight() ?? 0;
    const hScrollShowing = scrollVisibleSvc.horizontalScrollShowing;
    const scrollbarWidth = hScrollShowing ? scrollVisibleSvc.getScrollbarWidth() || 0 : 0;
    const height = pinnedBottomHeight + scrollbarWidth;
    comp.setStickyBottomBottom(`${height}px`);
  }
};
function _getCellPositionForEvent(gos, event) {
  return _getCellCtrlForEventTarget(gos, event.target)?.getFocusedCellPosition() ?? null;
}
function _getNormalisedMousePosition(beans, event) {
  const gridPanelHasScrolls = _isDomLayout(beans.gos, "normal");
  const e = event;
  let x;
  let y;
  if (e.clientX != null || e.clientY != null) {
    x = e.clientX;
    y = e.clientY;
  } else {
    x = e.x;
    y = e.y;
  }
  const { pageFirstPixel } = beans.pageBounds.getCurrentPagePixelRange();
  y += pageFirstPixel;
  if (gridPanelHasScrolls) {
    const scrollFeature = beans.ctrlsSvc.getScrollFeature();
    const vRange = scrollFeature.getVScrollPosition();
    const hRange = scrollFeature.getHScrollPosition();
    x += hRange.left;
    y += vRange.top;
  }
  return { x, y };
}
var AbstractFakeScrollComp = class extends Component {
  constructor(template2, direction) {
    super();
    this.direction = direction;
    this.eViewport = RefPlaceholder;
    this.eContainer = RefPlaceholder;
    this.hideTimeout = 0;
    this.setTemplate(template2);
  }
  postConstruct() {
    this.addManagedEventListeners({
      scrollVisibilityChanged: this.onScrollVisibilityChanged.bind(this)
    });
    this.onScrollVisibilityChanged();
    this.toggleCss("ag-apple-scrollbar", _isMacOsUserAgent() || _isIOSUserAgent());
  }
  destroy() {
    super.destroy();
    window.clearTimeout(this.hideTimeout);
  }
  initialiseInvisibleScrollbar() {
    if (this.invisibleScrollbar !== void 0) {
      return;
    }
    this.invisibleScrollbar = _isInvisibleScrollbar();
    if (this.invisibleScrollbar) {
      this.hideAndShowInvisibleScrollAsNeeded();
      this.addActiveListenerToggles();
    }
  }
  addActiveListenerToggles() {
    const eGui = this.getGui();
    const onActivate = () => this.toggleCss("ag-scrollbar-active", true);
    const onDeactivate = () => this.toggleCss("ag-scrollbar-active", false);
    this.addManagedListeners(eGui, {
      mouseenter: onActivate,
      mousedown: onActivate,
      touchstart: onActivate,
      mouseleave: onDeactivate,
      touchend: onDeactivate
    });
  }
  onScrollVisibilityChanged() {
    if (this.invisibleScrollbar === void 0) {
      this.initialiseInvisibleScrollbar();
    }
    _requestAnimationFrame(this.beans, () => this.setScrollVisible());
  }
  hideAndShowInvisibleScrollAsNeeded() {
    this.addManagedEventListeners({
      bodyScroll: (params) => {
        if (params.direction === this.direction) {
          if (this.hideTimeout) {
            window.clearTimeout(this.hideTimeout);
            this.hideTimeout = 0;
          }
          this.toggleCss("ag-scrollbar-scrolling", true);
        }
      },
      bodyScrollEnd: () => {
        this.hideTimeout = window.setTimeout(() => {
          this.toggleCss("ag-scrollbar-scrolling", false);
          this.hideTimeout = 0;
        }, 400);
      }
    });
  }
  attemptSettingScrollPosition(value2) {
    const viewport2 = this.eViewport;
    _waitUntil(
      this,
      () => _isVisible(viewport2),
      () => this.setScrollPosition(value2),
      100
    );
  }
  onScrollCallback(fn3) {
    this.addManagedElementListeners(this.eViewport, { scroll: fn3 });
  }
};
var FakeHScrollElement = {
  tag: "div",
  cls: "ag-body-horizontal-scroll",
  attrs: { "aria-hidden": "true" },
  children: [
    { tag: "div", ref: "eLeftSpacer", cls: "ag-horizontal-left-spacer" },
    {
      tag: "div",
      ref: "eViewport",
      cls: "ag-body-horizontal-scroll-viewport",
      children: [{ tag: "div", ref: "eContainer", cls: "ag-body-horizontal-scroll-container" }]
    },
    { tag: "div", ref: "eRightSpacer", cls: "ag-horizontal-right-spacer" }
  ]
};
var FakeHScrollComp = class extends AbstractFakeScrollComp {
  constructor() {
    super(FakeHScrollElement, "horizontal");
    this.eLeftSpacer = RefPlaceholder;
    this.eRightSpacer = RefPlaceholder;
    this.setScrollVisibleDebounce = 0;
  }
  wireBeans(beans) {
    this.visibleCols = beans.visibleCols;
    this.scrollVisibleSvc = beans.scrollVisibleSvc;
  }
  postConstruct() {
    super.postConstruct();
    const spacerWidthsListener = this.setFakeHScrollSpacerWidths.bind(this);
    this.addManagedEventListeners({
      displayedColumnsChanged: spacerWidthsListener,
      displayedColumnsWidthChanged: spacerWidthsListener,
      pinnedRowDataChanged: this.refreshCompBottom.bind(this)
    });
    this.addManagedPropertyListener("domLayout", spacerWidthsListener);
    this.beans.ctrlsSvc.register("fakeHScrollComp", this);
    this.createManagedBean(new CenterWidthFeature((width) => this.eContainer.style.width = `${width}px`));
    this.addManagedPropertyListeners(["suppressHorizontalScroll"], this.onScrollVisibilityChanged.bind(this));
  }
  destroy() {
    window.clearTimeout(this.setScrollVisibleDebounce);
    super.destroy();
  }
  initialiseInvisibleScrollbar() {
    if (this.invisibleScrollbar !== void 0) {
      return;
    }
    this.enableRtl = this.gos.get("enableRtl");
    super.initialiseInvisibleScrollbar();
    if (this.invisibleScrollbar) {
      this.refreshCompBottom();
    }
  }
  refreshCompBottom() {
    if (!this.invisibleScrollbar) {
      return;
    }
    const bottomPinnedHeight = this.beans.pinnedRowModel?.getPinnedBottomTotalHeight() ?? 0;
    this.getGui().style.bottom = `${bottomPinnedHeight}px`;
  }
  onScrollVisibilityChanged() {
    super.onScrollVisibilityChanged();
    this.setFakeHScrollSpacerWidths();
  }
  setFakeHScrollSpacerWidths() {
    const vScrollShowing = this.scrollVisibleSvc.verticalScrollShowing;
    let rightSpacing = this.visibleCols.getDisplayedColumnsRightWidth();
    const scrollOnRight = !this.enableRtl && vScrollShowing;
    const scrollbarWidth = this.scrollVisibleSvc.getScrollbarWidth();
    if (scrollOnRight) {
      rightSpacing += scrollbarWidth;
    }
    _setFixedWidth(this.eRightSpacer, rightSpacing);
    this.eRightSpacer.classList.toggle("ag-scroller-corner", rightSpacing <= scrollbarWidth);
    let leftSpacing = this.visibleCols.getColsLeftWidth();
    const scrollOnLeft = this.enableRtl && vScrollShowing;
    if (scrollOnLeft) {
      leftSpacing += scrollbarWidth;
    }
    _setFixedWidth(this.eLeftSpacer, leftSpacing);
    this.eLeftSpacer.classList.toggle("ag-scroller-corner", leftSpacing <= scrollbarWidth);
  }
  setScrollVisible() {
    const hScrollShowing = this.scrollVisibleSvc.horizontalScrollShowing;
    const invisibleScrollbar2 = this.invisibleScrollbar;
    const isSuppressHorizontalScroll = this.gos.get("suppressHorizontalScroll");
    const scrollbarWidth = hScrollShowing ? this.scrollVisibleSvc.getScrollbarWidth() || 0 : 0;
    const adjustedScrollbarWidth = scrollbarWidth === 0 && invisibleScrollbar2 ? 16 : scrollbarWidth;
    const scrollContainerSize = !isSuppressHorizontalScroll ? adjustedScrollbarWidth : 0;
    const apply = () => {
      this.setScrollVisibleDebounce = 0;
      this.toggleCss("ag-scrollbar-invisible", invisibleScrollbar2);
      _setFixedHeight(this.getGui(), scrollContainerSize);
      _setFixedHeight(this.eViewport, scrollContainerSize);
      _setFixedHeight(this.eContainer, scrollContainerSize);
      if (!scrollContainerSize) {
        this.eContainer.style.setProperty("min-height", "1px");
      }
      this.setVisible(hScrollShowing, { skipAriaHidden: true });
    };
    window.clearTimeout(this.setScrollVisibleDebounce);
    if (!hScrollShowing) {
      apply();
    } else {
      this.setScrollVisibleDebounce = window.setTimeout(apply, 100);
    }
  }
  getScrollPosition() {
    return _getScrollLeft(this.eViewport, this.enableRtl);
  }
  setScrollPosition(value2) {
    if (!_isVisible(this.eViewport)) {
      this.attemptSettingScrollPosition(value2);
    }
    _setScrollLeft(this.eViewport, value2, this.enableRtl);
  }
};
var FakeVScrollElement = {
  tag: "div",
  cls: "ag-body-vertical-scroll",
  attrs: { "aria-hidden": "true" },
  children: [
    {
      tag: "div",
      ref: "eViewport",
      cls: "ag-body-vertical-scroll-viewport",
      children: [{ tag: "div", ref: "eContainer", cls: "ag-body-vertical-scroll-container" }]
    }
  ]
};
var FakeVScrollComp = class extends AbstractFakeScrollComp {
  constructor() {
    super(FakeVScrollElement, "vertical");
  }
  postConstruct() {
    super.postConstruct();
    this.createManagedBean(new SetHeightFeature(this.eContainer));
    const { ctrlsSvc } = this.beans;
    ctrlsSvc.register("fakeVScrollComp", this);
    this.addManagedEventListeners({
      rowContainerHeightChanged: this.onRowContainerHeightChanged.bind(this, ctrlsSvc)
    });
  }
  setScrollVisible() {
    const { scrollVisibleSvc } = this.beans;
    const vScrollShowing = scrollVisibleSvc.verticalScrollShowing;
    const invisibleScrollbar2 = this.invisibleScrollbar;
    const scrollbarWidth = vScrollShowing ? scrollVisibleSvc.getScrollbarWidth() || 0 : 0;
    const adjustedScrollbarWidth = scrollbarWidth === 0 && invisibleScrollbar2 ? 16 : scrollbarWidth;
    this.toggleCss("ag-scrollbar-invisible", invisibleScrollbar2);
    _setFixedWidth(this.getGui(), adjustedScrollbarWidth);
    _setFixedWidth(this.eViewport, adjustedScrollbarWidth);
    _setFixedWidth(this.eContainer, adjustedScrollbarWidth);
    this.setDisplayed(vScrollShowing, { skipAriaHidden: true });
  }
  onRowContainerHeightChanged(ctrlsSvc) {
    const gridBodyCtrl = ctrlsSvc.getGridBodyCtrl();
    const gridBodyViewportEl = gridBodyCtrl.eBodyViewport;
    const eViewportScrollTop = this.getScrollPosition();
    const gridBodyViewportScrollTop = gridBodyViewportEl.scrollTop;
    if (eViewportScrollTop != gridBodyViewportScrollTop) {
      this.setScrollPosition(gridBodyViewportScrollTop, true);
    }
  }
  getScrollPosition() {
    return this.eViewport.scrollTop;
  }
  setScrollPosition(value2, force) {
    if (!force && !_isVisible(this.eViewport)) {
      this.attemptSettingScrollPosition(value2);
    }
    this.eViewport.scrollTop = value2;
  }
};
var CSS_FIRST_COLUMN = "ag-column-first";
var CSS_LAST_COLUMN = "ag-column-last";
function _getHeaderClassesFromColDef(abstractColDef, gos, column2, columnGroup) {
  if (_missing(abstractColDef)) {
    return [];
  }
  return getColumnClassesFromCollDef(abstractColDef.headerClass, abstractColDef, gos, column2, columnGroup);
}
function refreshFirstAndLastStyles(comp, column2, presentedColsService) {
  comp.toggleCss(CSS_FIRST_COLUMN, presentedColsService.isColAtEdge(column2, "first"));
  comp.toggleCss(CSS_LAST_COLUMN, presentedColsService.isColAtEdge(column2, "last"));
}
function getClassParams(abstractColDef, gos, column2, columnGroup) {
  return _addGridCommonParams(gos, {
    // bad naming, as colDef here can be a group or a column,
    // however most people won't appreciate the difference,
    // so keeping it as colDef to avoid confusion.
    colDef: abstractColDef,
    column: column2,
    columnGroup
  });
}
function getColumnClassesFromCollDef(classesOrFunc, abstractColDef, gos, column2, columnGroup) {
  if (_missing(classesOrFunc)) {
    return [];
  }
  let classToUse;
  if (typeof classesOrFunc === "function") {
    const params = getClassParams(abstractColDef, gos, column2, columnGroup);
    classToUse = classesOrFunc(params);
  } else {
    classToUse = classesOrFunc;
  }
  if (typeof classToUse === "string") {
    return [classToUse];
  }
  if (Array.isArray(classToUse)) {
    return [...classToUse];
  }
  return [];
}
function _addFocusableContainerListener(beans, comp, eGui) {
  comp.addManagedElementListeners(eGui, {
    keydown: (e) => {
      if (!e.defaultPrevented && e.key === KeyCode.TAB) {
        const backwards = e.shiftKey;
        if (!_findNextFocusableElement(beans, eGui, false, backwards)) {
          if (_focusNextGridCoreContainer(beans, backwards)) {
            e.preventDefault();
          }
        }
      }
    }
  });
}
function _focusGridInnerElement(beans, fromBottom) {
  return beans.ctrlsSvc.get("gridCtrl").focusInnerElement(fromBottom);
}
function _isHeaderFocusSuppressed(beans) {
  return beans.gos.get("suppressHeaderFocus") || !!beans.overlays?.isExclusive();
}
function _isCellFocusSuppressed(beans) {
  return beans.gos.get("suppressCellFocus") || !!beans.overlays?.isExclusive();
}
function _focusNextGridCoreContainer(beans, backwards, forceOut = false) {
  const gridCtrl = beans.ctrlsSvc.get("gridCtrl");
  if (!forceOut && gridCtrl.focusNextInnerContainer(backwards)) {
    return true;
  }
  if (forceOut || !backwards && !gridCtrl.isDetailGrid()) {
    gridCtrl.forceFocusOutOfContainer(backwards);
  }
  return false;
}
function getFocusHeaderRowCount(beans) {
  return beans.ctrlsSvc.getHeaderRowContainerCtrl()?.getRowCount() ?? 0;
}
function getGroupRowsHeight(beans) {
  const heights = [];
  const headerRowContainerCtrls = beans.ctrlsSvc.getHeaderRowContainerCtrls();
  for (const headerRowContainerCtrl of headerRowContainerCtrls) {
    if (!headerRowContainerCtrl) {
      continue;
    }
    const groupRowCount = headerRowContainerCtrl.getGroupRowCount() || 0;
    for (let i2 = 0; i2 < groupRowCount; i2++) {
      const headerRowCtrl = headerRowContainerCtrl.getGroupRowCtrlAtIndex(i2);
      const currentHeightAtPos = heights[i2];
      if (headerRowCtrl) {
        const newHeight = getColumnGroupHeaderRowHeight(beans, headerRowCtrl);
        if (currentHeightAtPos == null || newHeight > currentHeightAtPos) {
          heights[i2] = newHeight;
        }
      }
    }
  }
  return heights;
}
function getColumnGroupHeaderRowHeight(beans, headerRowCtrl) {
  const defaultHeight = beans.colModel.isPivotMode() ? getPivotGroupHeaderHeight(beans) : getGroupHeaderHeight(beans);
  let maxDisplayedHeight = defaultHeight;
  const headerRowCellCtrls = headerRowCtrl.getHeaderCellCtrls();
  for (const headerCellCtrl of headerRowCellCtrls) {
    const { column: column2 } = headerCellCtrl;
    const height = column2.getAutoHeaderHeight();
    if (height != null && height > maxDisplayedHeight && column2.isAutoHeaderHeight()) {
      maxDisplayedHeight = height;
    }
  }
  return maxDisplayedHeight;
}
function getColumnHeaderRowHeight(beans) {
  const defaultHeight = beans.colModel.isPivotMode() ? getPivotHeaderHeight(beans) : getHeaderHeight(beans);
  let maxDisplayedHeight = defaultHeight;
  beans.colModel.forAllCols((col) => {
    const height = col.getAutoHeaderHeight();
    if (height != null && height > maxDisplayedHeight && col.isAutoHeaderHeight()) {
      maxDisplayedHeight = height;
    }
  });
  return maxDisplayedHeight;
}
function getHeaderHeight(beans) {
  return beans.gos.get("headerHeight") ?? beans.environment.getDefaultHeaderHeight();
}
function getFloatingFiltersHeight(beans) {
  return beans.gos.get("floatingFiltersHeight") ?? getHeaderHeight(beans);
}
function getGroupHeaderHeight(beans) {
  return beans.gos.get("groupHeaderHeight") ?? getHeaderHeight(beans);
}
function getPivotHeaderHeight(beans) {
  return beans.gos.get("pivotHeaderHeight") ?? getHeaderHeight(beans);
}
function getPivotGroupHeaderHeight(beans) {
  return beans.gos.get("pivotGroupHeaderHeight") ?? getGroupHeaderHeight(beans);
}
function isHeaderPositionEqual(headerPosA, headerPosB) {
  return headerPosA.headerRowIndex === headerPosB.headerRowIndex && headerPosA.column === headerPosB.column;
}
var GridHeaderCtrl = class extends BeanStub {
  setComp(comp, eGui, eFocusableElement) {
    this.comp = comp;
    this.eGui = eGui;
    const { beans } = this;
    const { headerNavigation, touchSvc, ctrlsSvc } = beans;
    if (headerNavigation) {
      this.createManagedBean(
        new ManagedFocusFeature(eFocusableElement, {
          onTabKeyDown: this.onTabKeyDown.bind(this),
          handleKeyDown: this.handleKeyDown.bind(this),
          onFocusOut: this.onFocusOut.bind(this)
        })
      );
    }
    this.addManagedEventListeners({
      columnPivotModeChanged: this.onPivotModeChanged.bind(this, beans),
      displayedColumnsChanged: this.onDisplayedColumnsChanged.bind(this, beans)
    });
    this.onPivotModeChanged(beans);
    this.setupHeaderHeight();
    const listener = this.onHeaderContextMenu.bind(this);
    this.addManagedElementListeners(this.eGui, { contextmenu: listener });
    touchSvc?.mockHeaderContextMenu(this, listener);
    ctrlsSvc.register("gridHeaderCtrl", this);
  }
  setupHeaderHeight() {
    const listener = this.setHeaderHeight.bind(this);
    listener();
    this.addManagedPropertyListeners(
      [
        "headerHeight",
        "pivotHeaderHeight",
        "groupHeaderHeight",
        "pivotGroupHeaderHeight",
        "floatingFiltersHeight"
      ],
      listener
    );
    this.addManagedEventListeners({
      headerRowsChanged: listener,
      columnHeaderHeightChanged: listener,
      // add this to the animation frame to avoid a feedback loop
      columnGroupHeaderHeightChanged: () => _requestAnimationFrame(this.beans, () => listener()),
      gridStylesChanged: listener,
      advancedFilterEnabledChanged: listener
    });
  }
  setHeaderHeight() {
    const { beans } = this;
    let totalHeaderHeight = 0;
    const groupHeight = getGroupRowsHeight(beans).reduce((prev, curr) => prev + curr, 0);
    const headerHeight = getColumnHeaderRowHeight(beans);
    if (beans.filterManager?.hasFloatingFilters()) {
      totalHeaderHeight += getFloatingFiltersHeight(beans);
    }
    totalHeaderHeight += groupHeight;
    totalHeaderHeight += headerHeight;
    if (this.headerHeight === totalHeaderHeight) {
      return;
    }
    this.headerHeight = totalHeaderHeight;
    const px = `${totalHeaderHeight + 1}px`;
    this.comp.setHeightAndMinHeight(px);
    this.eventSvc.dispatchEvent({
      type: "headerHeightChanged"
    });
  }
  onPivotModeChanged(beans) {
    const pivotMode = beans.colModel.isPivotMode();
    this.comp.toggleCss("ag-pivot-on", pivotMode);
    this.comp.toggleCss("ag-pivot-off", !pivotMode);
  }
  onDisplayedColumnsChanged(beans) {
    const columns2 = beans.visibleCols.allCols;
    const shouldAllowOverflow = columns2.some((col) => col.isSpanHeaderHeight());
    this.comp.toggleCss("ag-header-allow-overflow", shouldAllowOverflow);
  }
  onTabKeyDown(e) {
    const isRtl = this.gos.get("enableRtl");
    const backwards = e.shiftKey;
    const direction = backwards !== isRtl ? "LEFT" : "RIGHT";
    const { beans } = this;
    const { headerNavigation, focusSvc } = beans;
    if (headerNavigation.navigateHorizontally(direction, true, e) || !backwards && focusSvc.focusOverlay(false) || _focusNextGridCoreContainer(beans, backwards, true)) {
      e.preventDefault();
    }
  }
  handleKeyDown(e) {
    let direction = null;
    const { headerNavigation } = this.beans;
    switch (e.key) {
      case KeyCode.LEFT:
        direction = "LEFT";
      case KeyCode.RIGHT: {
        if (!_exists(direction)) {
          direction = "RIGHT";
        }
        if (headerNavigation.navigateHorizontally(direction, false, e)) {
          e.preventDefault();
        }
        break;
      }
      case KeyCode.UP:
        direction = "UP";
      case KeyCode.DOWN: {
        if (!_exists(direction)) {
          direction = "DOWN";
        }
        if (headerNavigation.navigateVertically(direction, e)) {
          e.preventDefault();
        }
        break;
      }
      default:
        return;
    }
  }
  onFocusOut(e) {
    const { relatedTarget } = e;
    const { eGui, beans } = this;
    if (!relatedTarget && eGui.contains(_getActiveDomElement(beans))) {
      return;
    }
    if (!eGui.contains(relatedTarget)) {
      beans.focusSvc.focusedHeader = null;
    }
  }
  onHeaderContextMenu(mouseEvent, touch, touchEvent) {
    const { menuSvc, ctrlsSvc } = this.beans;
    if (!mouseEvent && !touchEvent || !menuSvc?.isHeaderContextMenuEnabled()) {
      return;
    }
    const { target } = mouseEvent ?? touch;
    if (target === this.eGui || target === ctrlsSvc.getHeaderRowContainerCtrl()?.eViewport) {
      menuSvc.showHeaderContextMenu(void 0, mouseEvent, touchEvent);
    }
  }
};
var SetLeftFeature = class extends BeanStub {
  constructor(columnOrGroup, eCell, beans, colsSpanning) {
    super();
    this.columnOrGroup = columnOrGroup;
    this.eCell = eCell;
    this.colsSpanning = colsSpanning;
    this.columnOrGroup = columnOrGroup;
    this.ariaEl = eCell.querySelector("[role=columnheader]") || eCell;
    this.beans = beans;
  }
  setColsSpanning(colsSpanning) {
    this.colsSpanning = colsSpanning;
    this.onLeftChanged();
  }
  getColumnOrGroup() {
    const { beans, colsSpanning } = this;
    if (beans.gos.get("enableRtl") && colsSpanning) {
      return _last(colsSpanning);
    }
    return this.columnOrGroup;
  }
  postConstruct() {
    const onLeftChanged = this.onLeftChanged.bind(this);
    this.addManagedListeners(this.columnOrGroup, { leftChanged: onLeftChanged });
    this.setLeftFirstTime();
    this.addManagedEventListeners({ displayedColumnsWidthChanged: onLeftChanged });
    this.addManagedPropertyListener("domLayout", onLeftChanged);
  }
  setLeftFirstTime() {
    const { gos, colAnimation } = this.beans;
    const suppressMoveAnimation = gos.get("suppressColumnMoveAnimation");
    const oldLeftExists = _exists(this.columnOrGroup.getOldLeft());
    const animateColumnMove = colAnimation?.isActive() && oldLeftExists && !suppressMoveAnimation;
    if (animateColumnMove) {
      this.animateInLeft();
    } else {
      this.onLeftChanged();
    }
  }
  animateInLeft() {
    const colOrGroup = this.getColumnOrGroup();
    const oldActualLeft = this.modifyLeftForPrintLayout(colOrGroup, colOrGroup.getOldLeft());
    const actualLeft = this.modifyLeftForPrintLayout(colOrGroup, colOrGroup.getLeft());
    this.setLeft(oldActualLeft);
    this.actualLeft = actualLeft;
    this.beans.colAnimation.executeNextVMTurn(() => {
      if (this.actualLeft === actualLeft) {
        this.setLeft(actualLeft);
      }
    });
  }
  onLeftChanged() {
    const colOrGroup = this.getColumnOrGroup();
    const left2 = colOrGroup.getLeft();
    this.actualLeft = this.modifyLeftForPrintLayout(colOrGroup, left2);
    this.setLeft(this.actualLeft);
  }
  modifyLeftForPrintLayout(colOrGroup, leftPosition) {
    const { gos, visibleCols } = this.beans;
    const printLayout = _isDomLayout(gos, "print");
    if (!printLayout) {
      return leftPosition;
    }
    if (colOrGroup.getPinned() === "left") {
      return leftPosition;
    }
    const leftWidth = visibleCols.getColsLeftWidth();
    if (colOrGroup.getPinned() === "right") {
      const bodyWidth = visibleCols.bodyWidth;
      return leftWidth + bodyWidth + leftPosition;
    }
    return leftWidth + leftPosition;
  }
  setLeft(value2) {
    if (_exists(value2)) {
      this.eCell.style.left = `${value2}px`;
    }
    if (isColumnGroup(this.columnOrGroup)) {
      const children2 = this.columnOrGroup.getLeafColumns();
      if (!children2.length) {
        return;
      }
      if (children2.length > 1) {
        _setAriaColSpan(this.ariaEl, children2.length);
      }
    }
  }
};
var instanceIdSequence2 = 0;
var DOM_DATA_KEY_HEADER_CTRL = "headerCtrl";
var AbstractHeaderCellCtrl = class extends BeanStub {
  constructor(column2, rowCtrl) {
    super();
    this.column = column2;
    this.rowCtrl = rowCtrl;
    this.resizeToggleTimeout = 0;
    this.resizeMultiplier = 1;
    this.resizeFeature = null;
    this.lastFocusEvent = null;
    this.dragSource = null;
    this.reAttemptToFocus = false;
    this.instanceId = column2.getUniqueId() + "-" + instanceIdSequence2++;
  }
  postConstruct() {
    const refreshTabIndex = this.refreshTabIndex.bind(this);
    this.addManagedPropertyListeners(["suppressHeaderFocus"], refreshTabIndex);
    this.addManagedEventListeners({
      overlayExclusiveChanged: refreshTabIndex
    });
  }
  setComp(comp, eGui, eResize, eHeaderCompWrapper, compBean) {
    eGui.setAttribute("col-id", this.column.colIdSanitised);
    this.wireComp(comp, eGui, eResize, eHeaderCompWrapper, compBean);
    if (this.reAttemptToFocus) {
      this.reAttemptToFocus = false;
      this.focus(this.lastFocusEvent ?? void 0);
    }
  }
  shouldStopEventPropagation(event) {
    const { headerRowIndex, column: column2 } = this.beans.focusSvc.focusedHeader;
    const colDef = column2.getDefinition();
    const colDefFunc = colDef?.suppressHeaderKeyboardEvent;
    if (!_exists(colDefFunc)) {
      return false;
    }
    const params = _addGridCommonParams(this.gos, {
      colDef,
      column: column2,
      headerRowIndex,
      event
    });
    return !!colDefFunc(params);
  }
  getWrapperHasFocus() {
    const activeEl = _getActiveDomElement(this.beans);
    return activeEl === this.eGui;
  }
  setGui(eGui, compBean) {
    this.eGui = eGui;
    this.addDomData(compBean);
    compBean.addManagedListeners(this.beans.eventSvc, {
      displayedColumnsChanged: this.onDisplayedColumnsChanged.bind(this)
    });
    compBean.addManagedElementListeners(this.eGui, {
      focus: this.onGuiFocus.bind(this)
    });
    this.onDisplayedColumnsChanged();
    this.refreshTabIndex();
  }
  refreshHeaderStyles() {
    const colDef = this.column.getDefinition();
    if (!colDef) {
      return;
    }
    const { headerStyle } = colDef;
    let styles2;
    if (typeof headerStyle === "function") {
      const cellStyleParams = this.getHeaderClassParams();
      styles2 = headerStyle(cellStyleParams);
    } else {
      styles2 = headerStyle;
    }
    if (styles2) {
      this.comp.setUserStyles(styles2);
    }
  }
  onGuiFocus() {
    this.eventSvc.dispatchEvent({
      type: "headerFocused",
      column: this.column
    });
  }
  setupAutoHeight(params) {
    const { wrapperElement, checkMeasuringCallback, compBean } = params;
    const { beans } = this;
    const measureHeight = (timesCalled) => {
      if (!this.isAlive() || !compBean.isAlive()) {
        return;
      }
      const { paddingTop, paddingBottom, borderBottomWidth, borderTopWidth } = _getElementSize(this.eGui);
      const extraHeight = paddingTop + paddingBottom + borderBottomWidth + borderTopWidth;
      const wrapperHeight = wrapperElement.offsetHeight;
      const autoHeight = wrapperHeight + extraHeight;
      if (timesCalled < 5) {
        const doc = _getDocument(beans);
        const notYetInDom = !doc?.contains(wrapperElement);
        const possiblyNoContentYet = autoHeight == 0;
        if (notYetInDom || possiblyNoContentYet) {
          _batchCall(() => measureHeight(timesCalled + 1), "raf", beans);
          return;
        }
      }
      this.setColHeaderHeight(this.column, autoHeight);
    };
    let isMeasuring = false;
    let stopResizeObserver;
    const checkMeasuring = () => {
      const newValue = this.column.isAutoHeaderHeight();
      if (newValue && !isMeasuring) {
        startMeasuring();
      }
      if (!newValue && isMeasuring) {
        stopMeasuring();
      }
    };
    const startMeasuring = () => {
      isMeasuring = true;
      this.comp.toggleCss("ag-header-cell-auto-height", true);
      measureHeight(0);
      stopResizeObserver = _observeResize(this.beans, wrapperElement, () => measureHeight(0));
    };
    const stopMeasuring = () => {
      isMeasuring = false;
      if (stopResizeObserver) {
        stopResizeObserver();
      }
      this.comp.toggleCss("ag-header-cell-auto-height", false);
      stopResizeObserver = void 0;
    };
    checkMeasuring();
    compBean.addDestroyFunc(() => stopMeasuring());
    compBean.addManagedListeners(this.column, { widthChanged: () => isMeasuring && measureHeight(0) });
    compBean.addManagedEventListeners({
      sortChanged: () => {
        if (isMeasuring) {
          window.setTimeout(() => measureHeight(0));
        }
      }
    });
    if (checkMeasuringCallback) {
      checkMeasuringCallback(checkMeasuring);
    }
  }
  onDisplayedColumnsChanged() {
    const { comp, column: column2, beans, eGui } = this;
    if (!comp || !column2 || !eGui) {
      return;
    }
    refreshFirstAndLastStyles(comp, column2, beans.visibleCols);
    _setAriaColIndex(eGui, beans.visibleCols.getAriaColIndex(column2));
  }
  addResizeAndMoveKeyboardListeners(compBean) {
    compBean.addManagedListeners(this.eGui, {
      keydown: this.onGuiKeyDown.bind(this),
      keyup: this.onGuiKeyUp.bind(this)
    });
  }
  refreshTabIndex() {
    const suppressHeaderFocus = _isHeaderFocusSuppressed(this.beans);
    if (this.eGui) {
      _addOrRemoveAttribute(this.eGui, "tabindex", suppressHeaderFocus ? null : "-1");
    }
  }
  onGuiKeyDown(e) {
    const activeEl = _getActiveDomElement(this.beans);
    const isLeftOrRight = e.key === KeyCode.LEFT || e.key === KeyCode.RIGHT;
    if (this.isResizing) {
      e.preventDefault();
      e.stopImmediatePropagation();
    }
    if (
      // if elements within the header are focused, we don't process the event
      activeEl !== this.eGui || // if shiftKey and altKey are not pressed, it's cell navigation so we don't process the event
      !e.shiftKey && !e.altKey
    ) {
      return;
    }
    if (this.isResizing || isLeftOrRight) {
      e.preventDefault();
      e.stopImmediatePropagation();
    }
    if (!isLeftOrRight) {
      return;
    }
    const isLeft = e.key === KeyCode.LEFT !== this.gos.get("enableRtl");
    const direction = isLeft ? "left" : "right";
    if (e.altKey) {
      this.isResizing = true;
      this.resizeMultiplier += 1;
      const diff2 = this.getViewportAdjustedResizeDiff(e);
      this.resizeHeader(diff2, e.shiftKey);
      this.resizeFeature?.toggleColumnResizing(true);
    } else {
      this.moveHeader(direction);
    }
  }
  moveHeader(hDirection) {
    this.beans.colMoves?.moveHeader(hDirection, this.eGui, this.column, this.rowCtrl.pinned, this);
  }
  getViewportAdjustedResizeDiff(e) {
    const diff2 = this.getResizeDiff(e);
    const { pinnedCols } = this.beans;
    return pinnedCols ? pinnedCols.getHeaderResizeDiff(diff2, this.column) : diff2;
  }
  getResizeDiff(e) {
    const { gos, column: column2 } = this;
    let isLeft = e.key === KeyCode.LEFT !== gos.get("enableRtl");
    const pinned = column2.getPinned();
    const isRtl = gos.get("enableRtl");
    if (pinned) {
      if (isRtl !== (pinned === "right")) {
        isLeft = !isLeft;
      }
    }
    return (isLeft ? -1 : 1) * this.resizeMultiplier;
  }
  onGuiKeyUp() {
    if (!this.isResizing) {
      return;
    }
    if (this.resizeToggleTimeout) {
      window.clearTimeout(this.resizeToggleTimeout);
      this.resizeToggleTimeout = 0;
    }
    this.isResizing = false;
    this.resizeMultiplier = 1;
    this.resizeToggleTimeout = window.setTimeout(() => {
      this.resizeFeature?.toggleColumnResizing(false);
    }, 150);
  }
  handleKeyDown(e) {
    const wrapperHasFocus = this.getWrapperHasFocus();
    switch (e.key) {
      case KeyCode.PAGE_DOWN:
      case KeyCode.PAGE_UP:
      case KeyCode.PAGE_HOME:
      case KeyCode.PAGE_END:
        if (wrapperHasFocus) {
          e.preventDefault();
        }
    }
  }
  addDomData(compBean) {
    const key2 = DOM_DATA_KEY_HEADER_CTRL;
    const { eGui, gos } = this;
    _setDomData(gos, eGui, key2, this);
    compBean.addDestroyFunc(() => _setDomData(gos, eGui, key2, null));
  }
  focus(event) {
    if (!this.isAlive()) {
      return false;
    }
    const { eGui } = this;
    if (!eGui) {
      this.reAttemptToFocus = true;
    } else {
      eGui.focus();
      this.lastFocusEvent = event || null;
    }
    return true;
  }
  focusThis() {
    this.beans.focusSvc.focusedHeader = { headerRowIndex: this.rowCtrl.rowIndex, column: this.column };
  }
  removeDragSource() {
    if (this.dragSource) {
      this.beans.dragAndDrop?.removeDragSource(this.dragSource);
      this.dragSource = null;
    }
  }
  handleContextMenuMouseEvent(mouseEvent, touchEvent, column2) {
    const event = mouseEvent ?? touchEvent;
    const { menuSvc, gos } = this.beans;
    if (gos.get("preventDefaultOnContextMenu")) {
      event.preventDefault();
    }
    if (menuSvc?.isHeaderContextMenuEnabled(column2)) {
      menuSvc.showHeaderContextMenu(column2, mouseEvent, touchEvent);
    }
    this.dispatchColumnMouseEvent("columnHeaderContextMenu", column2);
  }
  dispatchColumnMouseEvent(eventType, column2) {
    this.eventSvc.dispatchEvent({
      type: eventType,
      column: column2
    });
  }
  setColHeaderHeight(col, height) {
    if (!col.setAutoHeaderHeight(height)) {
      return;
    }
    const { eventSvc } = this;
    if (col.isColumn) {
      eventSvc.dispatchEvent({
        type: "columnHeaderHeightChanged",
        column: col,
        columns: [col],
        source: "autosizeColumnHeaderHeight"
      });
    } else {
      eventSvc.dispatchEvent({
        type: "columnGroupHeaderHeightChanged",
        columnGroup: col,
        source: "autosizeColumnGroupHeaderHeight"
      });
    }
  }
  clearComponent() {
    this.removeDragSource();
    this.resizeFeature = null;
    this.comp = null;
    this.eGui = null;
  }
  destroy() {
    super.destroy();
    this.column = null;
    this.lastFocusEvent = null;
    this.rowCtrl = null;
  }
};
var HeaderCellCtrl = class extends AbstractHeaderCellCtrl {
  constructor() {
    super(...arguments);
    this.refreshFunctions = {};
    this.userHeaderClasses = /* @__PURE__ */ new Set();
    this.ariaDescriptionProperties = /* @__PURE__ */ new Map();
  }
  wireComp(comp, eGui, eResize, eHeaderCompWrapper, compBeanInput) {
    this.comp = comp;
    const { rowCtrl, column: column2, beans } = this;
    const { colResize, context, colHover, rangeSvc } = beans;
    const compBean = setupCompBean(this, context, compBeanInput);
    this.setGui(eGui, compBean);
    this.updateState();
    this.setupWidth(compBean);
    this.setupMovingCss(compBean);
    this.setupMenuClass(compBean);
    this.setupSortableClass(compBean);
    this.setupWrapTextClass();
    this.refreshSpanHeaderHeight();
    this.setupAutoHeight({
      wrapperElement: eHeaderCompWrapper,
      checkMeasuringCallback: (checkMeasuring) => this.setRefreshFunction("measuring", checkMeasuring),
      compBean
    });
    this.addColumnHoverListener(compBean);
    this.setupFilterClass(compBean);
    this.setupStylesFromColDef();
    this.setupClassesFromColDef();
    this.setupTooltip();
    this.addActiveHeaderMouseListeners(compBean);
    this.setupSelectAll(compBean);
    this.setupUserComp();
    this.refreshAria();
    if (colResize) {
      this.resizeFeature = compBean.createManagedBean(
        colResize.createResizeFeature(rowCtrl.pinned, column2, eResize, comp, this)
      );
    } else {
      _setDisplayed(eResize, false);
    }
    colHover?.createHoverFeature(compBean, [column2], eGui);
    rangeSvc?.createRangeHighlightFeature(compBean, column2, comp);
    compBean.createManagedBean(new SetLeftFeature(column2, eGui, beans));
    compBean.createManagedBean(
      new ManagedFocusFeature(eGui, {
        shouldStopEventPropagation: (e) => this.shouldStopEventPropagation(e),
        onTabKeyDown: () => null,
        handleKeyDown: this.handleKeyDown.bind(this),
        onFocusIn: this.onFocusIn.bind(this),
        onFocusOut: this.onFocusOut.bind(this)
      })
    );
    this.addResizeAndMoveKeyboardListeners(compBean);
    compBean.addManagedPropertyListeners(
      ["suppressMovableColumns", "suppressMenuHide", "suppressAggFuncInHeader", "enableAdvancedFilter"],
      () => this.refresh()
    );
    compBean.addManagedListeners(column2, { colDefChanged: () => this.refresh() });
    compBean.addManagedListeners(column2, { headerHighlightChanged: this.onHeaderHighlightChanged.bind(this) });
    const listener = () => this.checkDisplayName();
    compBean.addManagedEventListeners({
      columnValueChanged: listener,
      columnRowGroupChanged: listener,
      columnPivotChanged: listener,
      headerHeightChanged: this.onHeaderHeightChanged.bind(this)
    });
    compBean.addDestroyFunc(() => {
      this.refreshFunctions = {};
      this.selectAllFeature = null;
      this.dragSourceElement = void 0;
      this.userCompDetails = null;
      this.userHeaderClasses.clear();
      this.ariaDescriptionProperties.clear();
      this.clearComponent();
    });
  }
  resizeHeader(delta, shiftKey) {
    this.beans.colResize?.resizeHeader(this.column, delta, shiftKey);
  }
  getHeaderClassParams() {
    const { column: column2, beans } = this;
    const colDef = column2.colDef;
    return _addGridCommonParams(beans.gos, {
      colDef,
      column: column2,
      floatingFilter: false
    });
  }
  setupUserComp() {
    const compDetails = this.lookupUserCompDetails();
    if (compDetails) {
      this.setCompDetails(compDetails);
    }
  }
  setCompDetails(compDetails) {
    this.userCompDetails = compDetails;
    this.comp.setUserCompDetails(compDetails);
  }
  lookupUserCompDetails() {
    const params = this.createParams();
    const colDef = this.column.getColDef();
    return _getHeaderCompDetails(this.beans.userCompFactory, colDef, params);
  }
  createParams() {
    const { menuSvc, sortSvc, colFilter, gos } = this.beans;
    const params = _addGridCommonParams(gos, {
      column: this.column,
      displayName: this.displayName,
      enableSorting: this.column.isSortable(),
      enableMenu: this.menuEnabled,
      enableFilterButton: this.openFilterEnabled && !!menuSvc?.isHeaderFilterButtonEnabled(this.column),
      enableFilterIcon: !!colFilter && (!this.openFilterEnabled || _isLegacyMenuEnabled(this.gos)),
      showColumnMenu: (buttonElement, onClosedCallback) => {
        menuSvc?.showColumnMenu({
          column: this.column,
          buttonElement,
          positionBy: "button",
          onClosedCallback
        });
      },
      showColumnMenuAfterMouseClick: (mouseEvent, onClosedCallback) => {
        menuSvc?.showColumnMenu({
          column: this.column,
          mouseEvent,
          positionBy: "mouse",
          onClosedCallback
        });
      },
      showFilter: (buttonElement) => {
        menuSvc?.showFilterMenu({
          column: this.column,
          buttonElement,
          containerType: "columnFilter",
          positionBy: "button"
        });
      },
      progressSort: (multiSort) => {
        sortSvc?.progressSort(this.column, !!multiSort, "uiColumnSorted");
      },
      setSort: (sort, multiSort) => {
        sortSvc?.setSortForColumn(this.column, sort, !!multiSort, "uiColumnSorted");
      },
      eGridHeader: this.eGui,
      setTooltip: (value2, shouldDisplayTooltip) => {
        gos.assertModuleRegistered("Tooltip", 3);
        this.setupTooltip(value2, shouldDisplayTooltip);
      }
    });
    return params;
  }
  setupSelectAll(compBean) {
    const { selectionSvc } = this.beans;
    if (!selectionSvc) {
      return;
    }
    this.selectAllFeature = compBean.createOptionalManagedBean(selectionSvc.createSelectAllFeature(this.column));
    this.selectAllFeature?.setComp(this);
    compBean.addManagedPropertyListener("rowSelection", () => {
      const selectAllFeature = selectionSvc.createSelectAllFeature(this.column);
      if (selectAllFeature && !this.selectAllFeature) {
        this.selectAllFeature = compBean.createManagedBean(selectAllFeature);
        this.selectAllFeature?.setComp(this);
        this.comp.refreshSelectAllGui();
      } else if (this.selectAllFeature && !selectAllFeature) {
        this.comp.removeSelectAllGui();
        this.selectAllFeature = this.destroyBean(this.selectAllFeature);
      }
    });
  }
  getSelectAllGui() {
    return this.selectAllFeature?.getCheckboxGui();
  }
  handleKeyDown(e) {
    super.handleKeyDown(e);
    if (e.key === KeyCode.SPACE) {
      this.selectAllFeature?.onSpaceKeyDown(e);
    }
    if (e.key === KeyCode.ENTER) {
      this.onEnterKeyDown(e);
    }
    if (e.key === KeyCode.DOWN && e.altKey) {
      this.showMenuOnKeyPress(e, false);
    }
  }
  onEnterKeyDown(e) {
    if (e.ctrlKey || e.metaKey) {
      this.showMenuOnKeyPress(e, true);
    } else if (this.sortable) {
      this.beans.sortSvc?.progressSort(this.column, e.shiftKey, "uiColumnSorted");
    }
  }
  showMenuOnKeyPress(e, isFilterShortcut) {
    const headerComp = this.comp.getUserCompInstance();
    if (!isHeaderComp(headerComp)) {
      return;
    }
    if (headerComp.onMenuKeyboardShortcut(isFilterShortcut)) {
      e.preventDefault();
    }
  }
  onFocusIn(e) {
    if (!this.eGui.contains(e.relatedTarget)) {
      this.focusThis();
      this.announceAriaDescription();
    }
    if (_isKeyboardMode()) {
      this.setActiveHeader(true);
    }
  }
  onFocusOut(e) {
    if (this.eGui.contains(e.relatedTarget)) {
      return;
    }
    this.setActiveHeader(false);
  }
  setupTooltip(value2, shouldDisplayTooltip) {
    this.tooltipFeature = this.beans.tooltipSvc?.setupHeaderTooltip(
      this.tooltipFeature,
      this,
      value2,
      shouldDisplayTooltip
    );
  }
  setupStylesFromColDef() {
    this.setRefreshFunction("headerStyles", this.refreshHeaderStyles.bind(this));
    this.refreshHeaderStyles();
  }
  setupClassesFromColDef() {
    const refreshHeaderClasses = () => {
      const colDef = this.column.getColDef();
      const classes = _getHeaderClassesFromColDef(colDef, this.gos, this.column, null);
      const oldClasses = this.userHeaderClasses;
      this.userHeaderClasses = new Set(classes);
      for (const c2 of classes) {
        if (oldClasses.has(c2)) {
          oldClasses.delete(c2);
        } else {
          this.comp.toggleCss(c2, true);
        }
      }
      for (const c2 of oldClasses) {
        this.comp.toggleCss(c2, false);
      }
    };
    this.setRefreshFunction("headerClasses", refreshHeaderClasses);
    refreshHeaderClasses();
  }
  setDragSource(eSource) {
    this.dragSourceElement = eSource;
    this.removeDragSource();
    if (!eSource || !this.draggable) {
      return;
    }
    this.dragSource = this.beans.colMoves?.setDragSourceForHeader(eSource, this.column, this.displayName) ?? null;
  }
  updateState() {
    const { menuSvc } = this.beans;
    this.menuEnabled = !!menuSvc?.isColumnMenuInHeaderEnabled(this.column);
    this.openFilterEnabled = !!menuSvc?.isFilterMenuInHeaderEnabled(this.column);
    this.sortable = this.column.isSortable();
    this.displayName = this.calculateDisplayName();
    this.draggable = this.workOutDraggable();
  }
  setRefreshFunction(name2, func2) {
    this.refreshFunctions[name2] = func2;
  }
  refresh() {
    this.updateState();
    this.refreshHeaderComp();
    this.refreshAria();
    for (const f of Object.values(this.refreshFunctions)) {
      f();
    }
  }
  refreshHeaderComp() {
    const newCompDetails = this.lookupUserCompDetails();
    if (!newCompDetails) {
      return;
    }
    const compInstance = this.comp.getUserCompInstance();
    const attemptRefresh = compInstance != null && this.userCompDetails.componentClass == newCompDetails.componentClass;
    const headerCompRefreshed = attemptRefresh ? this.attemptHeaderCompRefresh(newCompDetails.params) : false;
    if (headerCompRefreshed) {
      this.setDragSource(this.dragSourceElement);
    } else {
      this.setCompDetails(newCompDetails);
    }
  }
  attemptHeaderCompRefresh(params) {
    const headerComp = this.comp.getUserCompInstance();
    if (!headerComp) {
      return false;
    }
    if (!headerComp.refresh) {
      return false;
    }
    const res = headerComp.refresh(params);
    return res;
  }
  calculateDisplayName() {
    return this.beans.colNames.getDisplayNameForColumn(this.column, "header", true);
  }
  checkDisplayName() {
    if (this.displayName !== this.calculateDisplayName()) {
      this.refresh();
    }
  }
  workOutDraggable() {
    const colDef = this.column.getColDef();
    const isSuppressMovableColumns = this.gos.get("suppressMovableColumns");
    const colCanMove = !isSuppressMovableColumns && !colDef.suppressMovable && !colDef.lockPosition;
    return !!colCanMove || !!colDef.enableRowGroup || !!colDef.enablePivot;
  }
  setupWidth(compBean) {
    const listener = () => {
      const columnWidth = this.column.getActualWidth();
      this.comp.setWidth(`${columnWidth}px`);
    };
    compBean.addManagedListeners(this.column, { widthChanged: listener });
    listener();
  }
  setupMovingCss(compBean) {
    const listener = () => {
      this.comp.toggleCss("ag-header-cell-moving", this.column.isMoving());
    };
    compBean.addManagedListeners(this.column, { movingChanged: listener });
    listener();
  }
  setupMenuClass(compBean) {
    const listener = () => {
      this.comp?.toggleCss("ag-column-menu-visible", this.column.isMenuVisible());
    };
    compBean.addManagedListeners(this.column, { menuVisibleChanged: listener });
    listener();
  }
  setupSortableClass(compBean) {
    const updateSortableCssClass = () => {
      this.comp.toggleCss("ag-header-cell-sortable", !!this.sortable);
    };
    updateSortableCssClass();
    this.setRefreshFunction("updateSortable", updateSortableCssClass);
    compBean.addManagedEventListeners({ sortChanged: this.refreshAriaSort.bind(this) });
  }
  setupFilterClass(compBean) {
    const listener = () => {
      const isFilterActive = this.column.isFilterActive();
      this.comp.toggleCss("ag-header-cell-filtered", isFilterActive);
      this.refreshAria();
    };
    compBean.addManagedListeners(this.column, { filterActiveChanged: listener });
    listener();
  }
  setupWrapTextClass() {
    const listener = () => {
      const wrapText = !!this.column.getColDef().wrapHeaderText;
      this.comp.toggleCss("ag-header-cell-wrap-text", wrapText);
    };
    listener();
    this.setRefreshFunction("wrapText", listener);
  }
  onHeaderHighlightChanged() {
    const highlighted = this.column.getHighlighted();
    const beforeOn = highlighted === 0;
    const afterOn = highlighted === 1;
    this.comp.toggleCss("ag-header-highlight-before", beforeOn);
    this.comp.toggleCss("ag-header-highlight-after", afterOn);
  }
  onDisplayedColumnsChanged() {
    super.onDisplayedColumnsChanged();
    if (!this.isAlive()) {
      return;
    }
    this.onHeaderHeightChanged();
  }
  onHeaderHeightChanged() {
    this.refreshSpanHeaderHeight();
  }
  refreshSpanHeaderHeight() {
    const { eGui, column: column2, comp, beans } = this;
    const groupHeaderHeight = getGroupRowsHeight(this.beans);
    const isZeroGroupHeight = groupHeaderHeight.reduce((total, next) => total + next, 0) === 0;
    comp.toggleCss("ag-header-parent-hidden", isZeroGroupHeight);
    if (!column2.isSpanHeaderHeight()) {
      eGui.style.removeProperty("top");
      eGui.style.removeProperty("height");
      comp.toggleCss("ag-header-span-height", false);
      comp.toggleCss("ag-header-span-total", false);
      return;
    }
    const { numberOfParents, isSpanningTotal } = this.column.getColumnGroupPaddingInfo();
    comp.toggleCss("ag-header-span-height", numberOfParents > 0);
    const headerHeight = getColumnHeaderRowHeight(beans);
    if (numberOfParents === 0) {
      comp.toggleCss("ag-header-span-total", false);
      eGui.style.setProperty("top", `0px`);
      eGui.style.setProperty("height", `${headerHeight}px`);
      return;
    }
    comp.toggleCss("ag-header-span-total", isSpanningTotal);
    const indexToStartSpanning = (this.column.getFirstRealParent()?.getLevel() ?? -1) + 1;
    const rowsToSpan = groupHeaderHeight.length - indexToStartSpanning;
    let extraHeight = 0;
    for (let i2 = 0; i2 < rowsToSpan; i2++) {
      extraHeight += groupHeaderHeight[groupHeaderHeight.length - 1 - i2];
    }
    eGui.style.setProperty("top", `${-extraHeight}px`);
    eGui.style.setProperty("height", `${headerHeight + extraHeight}px`);
  }
  refreshAriaSort() {
    if (this.sortable) {
      const translate = this.getLocaleTextFunc();
      const sort = this.beans.sortSvc?.getDisplaySortForColumn(this.column) || null;
      this.comp.setAriaSort(_getAriaSortState(sort));
      this.setAriaDescriptionProperty("sort", translate("ariaSortableColumn", "Press ENTER to sort"));
    } else {
      this.comp.setAriaSort();
      this.setAriaDescriptionProperty("sort", null);
    }
  }
  refreshAriaMenu() {
    if (this.menuEnabled) {
      const translate = this.getLocaleTextFunc();
      this.setAriaDescriptionProperty("menu", translate("ariaMenuColumn", "Press ALT DOWN to open column menu"));
    } else {
      this.setAriaDescriptionProperty("menu", null);
    }
  }
  refreshAriaFilterButton() {
    if (this.openFilterEnabled && !_isLegacyMenuEnabled(this.gos)) {
      const translate = this.getLocaleTextFunc();
      this.setAriaDescriptionProperty(
        "filterButton",
        translate("ariaFilterColumn", "Press CTRL ENTER to open filter")
      );
    } else {
      this.setAriaDescriptionProperty("filterButton", null);
    }
  }
  refreshAriaFiltered() {
    const translate = this.getLocaleTextFunc();
    const isFilterActive = this.column.isFilterActive();
    if (isFilterActive) {
      this.setAriaDescriptionProperty("filter", translate("ariaColumnFiltered", "Column Filtered"));
    } else {
      this.setAriaDescriptionProperty("filter", null);
    }
  }
  setAriaDescriptionProperty(property, value2) {
    if (value2 != null) {
      this.ariaDescriptionProperties.set(property, value2);
    } else {
      this.ariaDescriptionProperties.delete(property);
    }
  }
  announceAriaDescription() {
    if (!this.eGui.contains(_getActiveDomElement(this.beans))) {
      return;
    }
    const ariaDescription = Array.from(this.ariaDescriptionProperties.keys()).sort((a2, b) => a2 === "filter" ? -1 : b.charCodeAt(0) - a2.charCodeAt(0)).map((key2) => this.ariaDescriptionProperties.get(key2)).join(". ");
    this.beans.ariaAnnounce?.announceValue(ariaDescription, "columnHeader");
  }
  refreshAria() {
    this.refreshAriaSort();
    this.refreshAriaMenu();
    this.refreshAriaFilterButton();
    this.refreshAriaFiltered();
  }
  addColumnHoverListener(compBean) {
    this.beans.colHover?.addHeaderColumnHoverListener(compBean, this.comp, this.column);
  }
  addActiveHeaderMouseListeners(compBean) {
    const listener = (e) => this.handleMouseOverChange(e.type === "mouseenter");
    const clickListener = () => {
      this.setActiveHeader(true);
      this.dispatchColumnMouseEvent("columnHeaderClicked", this.column);
    };
    const contextMenuListener = (event) => this.handleContextMenuMouseEvent(event, void 0, this.column);
    compBean.addManagedListeners(this.eGui, {
      mouseenter: listener,
      mouseleave: listener,
      click: clickListener,
      contextmenu: contextMenuListener
    });
  }
  handleMouseOverChange(isMouseOver) {
    this.setActiveHeader(isMouseOver);
    this.eventSvc.dispatchEvent({
      type: isMouseOver ? "columnHeaderMouseOver" : "columnHeaderMouseLeave",
      column: this.column
    });
  }
  setActiveHeader(active) {
    this.comp.toggleCss("ag-header-active", active);
  }
  getAnchorElementForMenu(isFilter) {
    const headerComp = this.comp.getUserCompInstance();
    if (isHeaderComp(headerComp)) {
      return headerComp.getAnchorElementForMenu(isFilter);
    }
    return this.eGui;
  }
  destroy() {
    this.tooltipFeature = this.destroyBean(this.tooltipFeature);
    super.destroy();
  }
};
function isHeaderComp(headerComp) {
  return typeof headerComp?.getAnchorElementForMenu === "function" && typeof headerComp.onMenuKeyboardShortcut === "function";
}
var instanceIdSequence3 = 0;
var HeaderRowCtrl = class extends BeanStub {
  constructor(rowIndex, pinned, type) {
    super();
    this.rowIndex = rowIndex;
    this.pinned = pinned;
    this.type = type;
    this.instanceId = instanceIdSequence3++;
    this.comp = null;
    this.allCtrls = [];
    let typeClass = "ag-header-row-column";
    if (type === "group") {
      typeClass = "ag-header-row-group";
    } else if (type === "filter") {
      typeClass = "ag-header-row-filter";
    }
    this.headerRowClass = `ag-header-row ${typeClass}`;
  }
  setRowIndex(rowIndex) {
    this.rowIndex = rowIndex;
    this.comp?.setRowIndex(this.getAriaRowIndex());
    this.onRowHeightChanged();
  }
  postConstruct() {
    this.isPrintLayout = _isDomLayout(this.gos, "print");
    this.isEnsureDomOrder = this.gos.get("ensureDomOrder");
  }
  /** Checks that every header cell that is currently visible has been rendered.
   * Can only be false under some circumstances when using React
   */
  areCellsRendered() {
    if (!this.comp) {
      return false;
    }
    return this.allCtrls.every((ctrl) => ctrl.eGui != null);
  }
  /**
   *
   * @param comp Proxy to the actual component
   * @param initCompState Should the component be initialised with the current state of the controller. Default: true
   */
  setComp(comp, compBean, initCompState = true) {
    this.comp = comp;
    compBean = setupCompBean(this, this.beans.context, compBean);
    if (initCompState) {
      this.setRowIndex(this.rowIndex);
      this.onVirtualColumnsChanged();
    }
    this.setWidth();
    this.addEventListeners(compBean);
  }
  getAriaRowIndex() {
    return this.rowIndex + 1;
  }
  addEventListeners(compBean) {
    const onHeightChanged = this.onRowHeightChanged.bind(this);
    const onDisplayedColumnsChanged = this.onDisplayedColumnsChanged.bind(this);
    compBean.addManagedEventListeners({
      columnResized: this.setWidth.bind(this),
      displayedColumnsChanged: onDisplayedColumnsChanged,
      virtualColumnsChanged: (params) => this.onVirtualColumnsChanged(params.afterScroll),
      columnGroupHeaderHeightChanged: onHeightChanged,
      columnHeaderHeightChanged: onHeightChanged,
      gridStylesChanged: onHeightChanged,
      advancedFilterEnabledChanged: onHeightChanged
    });
    compBean.addManagedPropertyListener("domLayout", onDisplayedColumnsChanged);
    compBean.addManagedPropertyListener("ensureDomOrder", (e) => this.isEnsureDomOrder = e.currentValue);
    compBean.addManagedPropertyListeners(
      [
        "headerHeight",
        "pivotHeaderHeight",
        "groupHeaderHeight",
        "pivotGroupHeaderHeight",
        "floatingFiltersHeight"
      ],
      onHeightChanged
    );
  }
  onDisplayedColumnsChanged() {
    this.isPrintLayout = _isDomLayout(this.gos, "print");
    this.onVirtualColumnsChanged();
    this.setWidth();
    this.onRowHeightChanged();
  }
  setWidth() {
    if (!this.comp) {
      return;
    }
    const width = this.getWidthForRow();
    this.comp.setWidth(`${width}px`);
  }
  getWidthForRow() {
    const { visibleCols } = this.beans;
    if (this.isPrintLayout) {
      const pinned = this.pinned != null;
      if (pinned) {
        return 0;
      }
      return visibleCols.getContainerWidth("right") + visibleCols.getContainerWidth("left") + visibleCols.getContainerWidth(null);
    }
    return visibleCols.getContainerWidth(this.pinned);
  }
  onRowHeightChanged() {
    if (!this.comp) {
      return;
    }
    const { topOffset, rowHeight } = this.getTopAndHeight();
    this.comp.setTop(topOffset + "px");
    this.comp.setHeight(rowHeight + "px");
  }
  getTopAndHeight() {
    let topOffset = 0;
    const groupHeadersHeight = getGroupRowsHeight(this.beans);
    for (let i2 = 0; i2 < groupHeadersHeight.length; i2++) {
      if (i2 === this.rowIndex && this.type === "group") {
        return { topOffset, rowHeight: groupHeadersHeight[i2] };
      }
      topOffset += groupHeadersHeight[i2];
    }
    const headerHeight = getColumnHeaderRowHeight(this.beans);
    if (this.type === "column") {
      return { topOffset, rowHeight: headerHeight };
    }
    topOffset += headerHeight;
    const filterHeight = getFloatingFiltersHeight(this.beans);
    return { topOffset, rowHeight: filterHeight };
  }
  onVirtualColumnsChanged(afterScroll = false) {
    if (!this.comp) {
      return;
    }
    const ctrlsToDisplay = this.getUpdatedHeaderCtrls();
    const forceOrder = this.isEnsureDomOrder || this.isPrintLayout;
    this.comp.setHeaderCtrls(ctrlsToDisplay, forceOrder, afterScroll);
  }
  /**
   * Recycles the header cell ctrls and creates new ones for the columns in the viewport
   * @returns The updated header cell ctrls
   */
  getUpdatedHeaderCtrls() {
    const oldCtrls = this.ctrlsById;
    this.ctrlsById = /* @__PURE__ */ new Map();
    const columns2 = this.getColumnsInViewport();
    for (const child of columns2) {
      this.recycleAndCreateHeaderCtrls(child, this.ctrlsById, oldCtrls);
    }
    const isFocusedAndDisplayed = (ctrl) => {
      const { focusSvc, visibleCols } = this.beans;
      const isFocused = focusSvc.isHeaderWrapperFocused(ctrl);
      if (!isFocused) {
        return false;
      }
      const isDisplayed = visibleCols.isVisible(ctrl.column);
      return isDisplayed;
    };
    if (oldCtrls) {
      for (const [id2, oldCtrl] of oldCtrls) {
        const keepCtrl = isFocusedAndDisplayed(oldCtrl);
        if (keepCtrl) {
          this.ctrlsById.set(id2, oldCtrl);
        } else {
          this.destroyBean(oldCtrl);
        }
      }
    }
    this.allCtrls = Array.from(this.ctrlsById.values());
    return this.allCtrls;
  }
  /** Get the current header cell ctrls */
  getHeaderCellCtrls() {
    return this.allCtrls;
  }
  recycleAndCreateHeaderCtrls(headerColumn, currCtrls, oldCtrls) {
    if (headerColumn.isEmptyGroup()) {
      return;
    }
    const idOfChild = headerColumn.getUniqueId();
    let headerCtrl;
    if (oldCtrls) {
      headerCtrl = oldCtrls.get(idOfChild);
      oldCtrls.delete(idOfChild);
    }
    const forOldColumn = headerCtrl && headerCtrl.column != headerColumn;
    if (forOldColumn) {
      this.destroyBean(headerCtrl);
      headerCtrl = void 0;
    }
    if (headerCtrl == null) {
      switch (this.type) {
        case "filter": {
          headerCtrl = this.createBean(
            this.beans.registry.createDynamicBean(
              "headerFilterCellCtrl",
              true,
              headerColumn,
              this
            )
          );
          break;
        }
        case "group":
          headerCtrl = this.createBean(
            this.beans.registry.createDynamicBean(
              "headerGroupCellCtrl",
              true,
              headerColumn,
              this
            )
          );
          break;
        default:
          headerCtrl = this.createBean(new HeaderCellCtrl(headerColumn, this));
          break;
      }
    }
    currCtrls.set(idOfChild, headerCtrl);
  }
  getColumnsInViewport() {
    if (!this.isPrintLayout) {
      return this.getComponentsToRender();
    }
    if (this.pinned) {
      return [];
    }
    const viewportColumns = [];
    for (const pinned of ["left", null, "right"]) {
      viewportColumns.push(...this.getComponentsToRender(pinned));
    }
    return viewportColumns;
  }
  getComponentsToRender(pinned = this.pinned) {
    if (this.type === "group") {
      return this.beans.colViewport.getHeadersToRender(pinned, this.rowIndex);
    }
    return this.beans.colViewport.getColumnHeadersToRender(pinned);
  }
  focusHeader(column2, event) {
    const ctrl = this.allCtrls.find((ctrl2) => ctrl2.column == column2);
    if (!ctrl) {
      return false;
    }
    const focused = ctrl.focus(event);
    return focused;
  }
  destroy() {
    this.allCtrls = this.destroyBeans(this.allCtrls);
    this.ctrlsById = void 0;
    this.comp = null;
    super.destroy();
  }
};
var HeaderRowContainerCtrl = class extends BeanStub {
  constructor(pinned) {
    super();
    this.pinned = pinned;
    this.hidden = false;
    this.includeFloatingFilter = false;
    this.groupsRowCtrls = [];
  }
  setComp(comp, eGui) {
    this.comp = comp;
    this.eViewport = eGui;
    const { pinnedCols, ctrlsSvc, colModel, colMoves } = this.beans;
    this.setupCenterWidth();
    pinnedCols?.setupHeaderPinnedWidth(this);
    this.setupDragAndDrop(colMoves, this.eViewport);
    const onDisplayedColsChanged = this.refresh.bind(this, true);
    this.addManagedEventListeners({
      displayedColumnsChanged: onDisplayedColsChanged,
      advancedFilterEnabledChanged: onDisplayedColsChanged
    });
    const headerType = `${typeof this.pinned === "string" ? this.pinned : "center"}Header`;
    ctrlsSvc.register(headerType, this);
    if (colModel.ready) {
      this.refresh();
    }
  }
  getAllCtrls() {
    const res = [...this.groupsRowCtrls];
    if (this.columnsRowCtrl) {
      res.push(this.columnsRowCtrl);
    }
    if (this.filtersRowCtrl) {
      res.push(this.filtersRowCtrl);
    }
    return res;
  }
  refresh(keepColumns = false) {
    const { focusSvc, filterManager, visibleCols } = this.beans;
    let sequence2 = 0;
    const focusedHeaderPosition = focusSvc.getFocusHeaderToUseAfterRefresh();
    const refreshColumnGroups = () => {
      const groupRowCount = visibleCols.headerGroupRowCount;
      sequence2 = groupRowCount;
      if (!keepColumns) {
        this.groupsRowCtrls = this.destroyBeans(this.groupsRowCtrls);
      }
      const currentGroupCount = this.groupsRowCtrls.length;
      if (currentGroupCount === groupRowCount) {
        return;
      }
      if (currentGroupCount > groupRowCount) {
        for (let i2 = groupRowCount; i2 < currentGroupCount; i2++) {
          this.destroyBean(this.groupsRowCtrls[i2]);
        }
        this.groupsRowCtrls.length = groupRowCount;
        return;
      }
      for (let i2 = currentGroupCount; i2 < groupRowCount; i2++) {
        const ctrl = this.createBean(new HeaderRowCtrl(i2, this.pinned, "group"));
        this.groupsRowCtrls.push(ctrl);
      }
    };
    const refreshColumns = () => {
      const rowIndex = sequence2++;
      if (this.hidden) {
        this.columnsRowCtrl = this.destroyBean(this.columnsRowCtrl);
        return;
      }
      if (this.columnsRowCtrl == null || !keepColumns) {
        this.columnsRowCtrl = this.destroyBean(this.columnsRowCtrl);
        this.columnsRowCtrl = this.createBean(new HeaderRowCtrl(rowIndex, this.pinned, "column"));
      } else if (this.columnsRowCtrl.rowIndex !== rowIndex) {
        this.columnsRowCtrl.setRowIndex(rowIndex);
      }
    };
    const refreshFilters = () => {
      this.includeFloatingFilter = !!filterManager?.hasFloatingFilters() && !this.hidden;
      const destroyPreviousComp = () => {
        this.filtersRowCtrl = this.destroyBean(this.filtersRowCtrl);
      };
      if (!this.includeFloatingFilter) {
        destroyPreviousComp();
        return;
      }
      if (!keepColumns) {
        destroyPreviousComp();
      }
      const rowIndex = sequence2++;
      if (this.filtersRowCtrl) {
        const rowIndexMismatch = this.filtersRowCtrl.rowIndex !== rowIndex;
        if (rowIndexMismatch) {
          this.filtersRowCtrl.setRowIndex(rowIndex);
        }
      } else {
        this.filtersRowCtrl = this.createBean(new HeaderRowCtrl(rowIndex, this.pinned, "filter"));
      }
    };
    const oldCtrls = this.getAllCtrls();
    refreshColumnGroups();
    refreshColumns();
    refreshFilters();
    const allCtrls = this.getAllCtrls();
    this.comp.setCtrls(allCtrls);
    this.restoreFocusOnHeader(focusSvc, focusedHeaderPosition);
    if (oldCtrls.length !== allCtrls.length) {
      this.beans.eventSvc.dispatchEvent({
        type: "headerRowsChanged"
      });
    }
  }
  getHeaderCtrlForColumn(column2) {
    const findCtrl = (ctrl) => ctrl?.getHeaderCellCtrls().find((ctrl2) => ctrl2.column === column2);
    if (isColumn(column2)) {
      return findCtrl(this.columnsRowCtrl);
    }
    if (this.groupsRowCtrls.length === 0) {
      return;
    }
    for (let i2 = 0; i2 < this.groupsRowCtrls.length; i2++) {
      const ctrl = findCtrl(this.groupsRowCtrls[i2]);
      if (ctrl) {
        return ctrl;
      }
    }
  }
  getHtmlElementForColumnHeader(column2) {
    return this.getHeaderCtrlForColumn(column2)?.eGui ?? null;
  }
  getRowType(rowIndex) {
    return this.getAllCtrls()[rowIndex]?.type;
  }
  focusHeader(rowIndex, column2, event) {
    const allCtrls = this.getAllCtrls();
    const ctrl = allCtrls[rowIndex];
    if (!ctrl) {
      return false;
    }
    return ctrl.focusHeader(column2, event);
  }
  getGroupRowCount() {
    return this.groupsRowCtrls.length;
  }
  getGroupRowCtrlAtIndex(index) {
    return this.groupsRowCtrls[index];
  }
  getRowCount() {
    return this.groupsRowCtrls.length + (this.columnsRowCtrl ? 1 : 0) + (this.filtersRowCtrl ? 1 : 0);
  }
  setHorizontalScroll(offset3) {
    this.comp.setViewportScrollLeft(offset3);
  }
  onScrollCallback(fn3) {
    this.addManagedElementListeners(this.eViewport, { scroll: fn3 });
  }
  destroy() {
    this.filtersRowCtrl = this.destroyBean(this.filtersRowCtrl);
    this.columnsRowCtrl = this.destroyBean(this.columnsRowCtrl);
    this.groupsRowCtrls = this.destroyBeans(this.groupsRowCtrls);
    super.destroy();
  }
  setupDragAndDrop(colMoves, dropContainer) {
    const bodyDropTarget = colMoves?.createBodyDropTarget(this.pinned, dropContainer);
    if (bodyDropTarget) {
      this.createManagedBean(bodyDropTarget);
    }
  }
  restoreFocusOnHeader(focusSvc, position) {
    if (!position) {
      return;
    }
    const { column: column2 } = position;
    if (column2.getPinned() != this.pinned) {
      return;
    }
    focusSvc.focusHeaderPosition({ headerPosition: position, scroll: false });
  }
  setupCenterWidth() {
    if (this.pinned != null) {
      return;
    }
    this.createManagedBean(new CenterWidthFeature((width) => this.comp.setCenterWidth(`${width}px`), true));
  }
};
var MenuService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "menuSvc";
  }
  postConstruct() {
    const { enterpriseMenuFactory, filterMenuFactory } = this.beans;
    this.activeMenuFactory = enterpriseMenuFactory ?? filterMenuFactory;
  }
  showColumnMenu(params) {
    this.showColumnMenuCommon(this.activeMenuFactory, params, "columnMenu");
  }
  showFilterMenu(params) {
    this.showColumnMenuCommon(getFilterMenuFactory(this.beans), params, params.containerType, true);
  }
  showHeaderContextMenu(column2, mouseEvent, touchEvent) {
    this.activeMenuFactory?.showMenuAfterContextMenuEvent(column2, mouseEvent, touchEvent);
  }
  hidePopupMenu() {
    this.beans.contextMenuSvc?.hideActiveMenu();
    this.activeMenuFactory?.hideActiveMenu();
  }
  hideFilterMenu() {
    getFilterMenuFactory(this.beans)?.hideActiveMenu();
  }
  isColumnMenuInHeaderEnabled(column2) {
    const { suppressHeaderMenuButton } = column2.getColDef();
    return !suppressHeaderMenuButton && !!this.activeMenuFactory?.isMenuEnabled(column2) && (_isLegacyMenuEnabled(this.gos) || !!this.beans.enterpriseMenuFactory);
  }
  isFilterMenuInHeaderEnabled(column2) {
    return !column2.getColDef().suppressHeaderFilterButton && !!this.beans.filterManager?.isFilterAllowed(column2);
  }
  isHeaderContextMenuEnabled(column2) {
    const colDef = column2 && isColumn(column2) ? column2.getColDef() : column2?.getColGroupDef();
    return !colDef?.suppressHeaderContextMenu && this.gos.get("columnMenu") === "new";
  }
  isHeaderMenuButtonAlwaysShowEnabled() {
    return this.isSuppressMenuHide();
  }
  isHeaderMenuButtonEnabled() {
    const menuHides = !this.isSuppressMenuHide();
    const onIpadAndMenuHides = _isIOSUserAgent() && menuHides;
    return !onIpadAndMenuHides;
  }
  isHeaderFilterButtonEnabled(column2) {
    return this.isFilterMenuInHeaderEnabled(column2) && !_isLegacyMenuEnabled(this.gos) && !this.isFloatingFilterButtonDisplayed(column2);
  }
  isFilterMenuItemEnabled(column2) {
    return !!this.beans.filterManager?.isFilterAllowed(column2) && !_isLegacyMenuEnabled(this.gos) && !this.isFilterMenuInHeaderEnabled(column2) && !this.isFloatingFilterButtonDisplayed(column2);
  }
  isFloatingFilterButtonEnabled(column2) {
    return !column2.getColDef().suppressFloatingFilterButton;
  }
  isFloatingFilterButtonDisplayed(column2) {
    return !!column2.getColDef().floatingFilter && this.isFloatingFilterButtonEnabled(column2);
  }
  isSuppressMenuHide() {
    const gos = this.gos;
    const suppressMenuHide = gos.get("suppressMenuHide");
    if (_isLegacyMenuEnabled(gos)) {
      return gos.exists("suppressMenuHide") ? suppressMenuHide : false;
    }
    return suppressMenuHide;
  }
  showColumnMenuCommon(menuFactory, params, containerType, filtersOnly) {
    const { positionBy, onClosedCallback } = params;
    const column2 = params.column;
    if (positionBy === "button") {
      const { buttonElement } = params;
      menuFactory?.showMenuAfterButtonClick(column2, buttonElement, containerType, onClosedCallback, filtersOnly);
    } else if (positionBy === "mouse") {
      const { mouseEvent } = params;
      menuFactory?.showMenuAfterMouseEvent(column2, mouseEvent, containerType, onClosedCallback, filtersOnly);
    } else if (column2) {
      const beans = this.beans;
      const ctrlsSvc = beans.ctrlsSvc;
      ctrlsSvc.getScrollFeature().ensureColumnVisible(column2, "auto");
      _requestAnimationFrame(beans, () => {
        const headerCellCtrl = ctrlsSvc.getHeaderRowContainerCtrl(column2.getPinned())?.getHeaderCtrlForColumn(column2);
        if (headerCellCtrl) {
          menuFactory?.showMenuAfterButtonClick(
            column2,
            headerCellCtrl.getAnchorElementForMenu(filtersOnly),
            containerType,
            onClosedCallback,
            filtersOnly
          );
        }
      });
    }
  }
};
function _setColMenuVisible(column2, visible2, source2) {
  if (column2.menuVisible !== visible2) {
    column2.menuVisible = visible2;
    column2.dispatchColEvent("menuVisibleChanged", source2);
  }
}
function getFilterMenuFactory(beans) {
  const { enterpriseMenuFactory, filterMenuFactory, gos } = beans;
  return enterpriseMenuFactory && _isLegacyMenuEnabled(gos) ? enterpriseMenuFactory : filterMenuFactory;
}
var AgAbstractCellEditor = class extends AgPopupComponent {
  constructor() {
    super(...arguments);
    this.errorMessages = null;
  }
  init(params) {
    this.params = params;
    this.initialiseEditor(params);
    this.eEditor.onValueChange(() => params.validate());
  }
  destroy() {
    this.errorMessages = null;
  }
};
var OverlayComponent = class extends Component {
  constructor() {
    super();
  }
};
var LoadingOverlayElement = {
  tag: "span",
  cls: "ag-overlay-loading-center"
};
var LoadingOverlayComponent2 = class extends OverlayComponent {
  init() {
    const customTemplate = _makeNull(this.gos.get("overlayLoadingTemplate")?.trim());
    this.setTemplate(customTemplate ?? LoadingOverlayElement);
    if (!customTemplate) {
      const localeTextFunc = this.getLocaleTextFunc();
      const loadingText = localeTextFunc("loadingOoo", "Loading...");
      this.getGui().textContent = loadingText;
      this.beans.ariaAnnounce.announceValue(loadingText, "overlay");
    }
  }
};
var NoRowsOverlayElement = { tag: "span", cls: "ag-overlay-no-rows-center" };
var NoRowsOverlayComponent2 = class extends OverlayComponent {
  init() {
    const customTemplate = _makeNull(this.gos.get("overlayNoRowsTemplate")?.trim());
    this.setTemplate(customTemplate ?? NoRowsOverlayElement);
    if (!customTemplate) {
      const localeTextFunc = this.getLocaleTextFunc();
      const noRowsText = localeTextFunc("noRowsToShow", "No Rows To Show");
      this.getGui().textContent = noRowsText;
      this.beans.ariaAnnounce.announceValue(noRowsText, "overlay");
    }
  }
};
function _createIcon(iconName, beans, column2) {
  const iconContents = _createIconNoSpan(iconName, beans, column2);
  if (iconContents) {
    const { className: className2 } = iconContents;
    if (typeof className2 === "string" && className2.includes("ag-icon") || typeof className2 === "object" && className2["ag-icon"]) {
      return iconContents;
    }
  }
  const eResult = _createElement({ tag: "span" });
  eResult.appendChild(iconContents);
  return eResult;
}
function _createIconNoSpan(iconName, beans, column2) {
  let userProvidedIcon = null;
  if (iconName === "smallDown") {
    _warn(262);
  } else if (iconName === "smallLeft") {
    _warn(263);
  } else if (iconName === "smallRight") {
    _warn(264);
  }
  const icons = column2?.getColDef().icons;
  if (icons) {
    userProvidedIcon = icons[iconName];
  }
  if (beans.gos && !userProvidedIcon) {
    const optionsIcons = beans.gos.get("icons");
    if (optionsIcons) {
      userProvidedIcon = optionsIcons[iconName];
    }
  }
  if (userProvidedIcon) {
    let rendererResult;
    if (typeof userProvidedIcon === "function") {
      rendererResult = userProvidedIcon();
    } else if (typeof userProvidedIcon === "string") {
      rendererResult = userProvidedIcon;
    } else {
      _warn(38, { iconName });
      return void 0;
    }
    if (typeof rendererResult === "string") {
      return _loadTemplate(rendererResult);
    }
    if (_isNodeOrElement(rendererResult)) {
      return rendererResult;
    }
    _warn(133, { iconName });
    return void 0;
  } else {
    const iconValue = beans.registry.getIcon(iconName);
    if (!iconValue) {
      beans.validation?.validateIcon(iconName);
    }
    return _createElement({
      tag: "span",
      cls: `ag-icon ag-icon-${iconValue ?? iconName}`,
      role: "presentation",
      attrs: { unselectable: "on" }
    });
  }
}
var dragAndDropImageComponentCSS = (
  /*css*/
  `.ag-dnd-ghost{align-items:center;background-color:var(--ag-drag-and-drop-image-background-color);border:var(--ag-drag-and-drop-image-border);border-radius:var(--ag-border-radius);box-shadow:var(--ag-drag-and-drop-image-shadow);color:var(--ag-text-color);cursor:move;display:flex;font-weight:500;gap:var(--ag-cell-widget-spacing);height:var(--ag-header-height);overflow:hidden;padding-left:var(--ag-cell-horizontal-padding);padding-right:var(--ag-cell-horizontal-padding);text-overflow:ellipsis;transform:translateY(calc(var(--ag-spacing)*2));white-space:nowrap}.ag-dnd-ghost-not-allowed{border:var(--ag-drag-and-drop-image-not-allowed-border)}`
);
var DragAndDropElement = {
  tag: "div",
  children: [
    {
      tag: "div",
      ref: "eGhost",
      cls: "ag-dnd-ghost ag-unselectable",
      children: [
        { tag: "span", ref: "eIcon", cls: "ag-dnd-ghost-icon ag-shake-left-to-right" },
        { tag: "div", ref: "eLabel", cls: "ag-dnd-ghost-label" }
      ]
    }
  ]
};
var DragAndDropImageComponent2 = class extends Component {
  constructor() {
    super();
    this.dragSource = null;
    this.eIcon = RefPlaceholder;
    this.eLabel = RefPlaceholder;
    this.eGhost = RefPlaceholder;
    this.registerCSS(dragAndDropImageComponentCSS);
  }
  postConstruct() {
    const create2 = (iconName) => _createIcon(iconName, this.beans, null);
    this.dropIconMap = {
      pinned: create2("columnMovePin"),
      hide: create2("columnMoveHide"),
      move: create2("columnMoveMove"),
      left: create2("columnMoveLeft"),
      right: create2("columnMoveRight"),
      group: create2("columnMoveGroup"),
      aggregate: create2("columnMoveValue"),
      pivot: create2("columnMovePivot"),
      notAllowed: create2("dropNotAllowed")
    };
  }
  init(params) {
    this.dragSource = params.dragSource;
    this.setTemplate(DragAndDropElement);
    this.beans.environment.applyThemeClasses(this.eGhost);
  }
  destroy() {
    this.dragSource = null;
    super.destroy();
  }
  setIcon(iconName, shake) {
    const { eGhost, eIcon, dragSource, dropIconMap, gos } = this;
    _clearElement(eIcon);
    let eIconChild = null;
    if (!iconName) {
      iconName = dragSource?.getDefaultIconName ? dragSource.getDefaultIconName() : "notAllowed";
    }
    eIconChild = dropIconMap[iconName];
    eGhost.classList.toggle("ag-dnd-ghost-not-allowed", iconName === "notAllowed");
    eIcon.classList.toggle("ag-shake-left-to-right", shake);
    if (eIconChild === dropIconMap["hide"] && gos.get("suppressDragLeaveHidesColumns")) {
      return;
    }
    if (eIconChild) {
      eIcon.appendChild(eIconChild);
    }
  }
  setLabel(label2) {
    this.eLabel.textContent = label2;
  }
};
var checkboxCellRendererCSS = (
  /*css*/
  `.ag-checkbox-cell{height:100%}`
);
var CheckboxCellRendererElement = {
  tag: "div",
  cls: "ag-cell-wrapper ag-checkbox-cell",
  role: "presentation",
  children: [
    {
      tag: "ag-checkbox",
      ref: "eCheckbox",
      role: "presentation"
    }
  ]
};
var CheckboxCellRenderer = class extends Component {
  constructor() {
    super(CheckboxCellRendererElement, [AgCheckboxSelector]);
    this.eCheckbox = RefPlaceholder;
    this.registerCSS(checkboxCellRendererCSS);
  }
  init(params) {
    this.refresh(params);
    const { eCheckbox, beans } = this;
    const inputEl = eCheckbox.getInputElement();
    inputEl.setAttribute("tabindex", "-1");
    _setAriaLive(inputEl, "polite");
    this.addManagedListeners(inputEl, {
      click: (event) => {
        _stopPropagationForAgGrid(event);
        if (eCheckbox.isDisabled()) {
          return;
        }
        const isSelected = eCheckbox.getValue();
        this.onCheckboxChanged(isSelected);
      },
      dblclick: (event) => {
        _stopPropagationForAgGrid(event);
      }
    });
    this.addManagedElementListeners(params.eGridCell, {
      keydown: (event) => {
        if (event.key === KeyCode.SPACE && !eCheckbox.isDisabled()) {
          if (params.eGridCell === _getActiveDomElement(beans)) {
            eCheckbox.toggle();
          }
          const isSelected = eCheckbox.getValue();
          this.onCheckboxChanged(isSelected);
          event.preventDefault();
        }
      }
    });
  }
  refresh(params) {
    this.params = params;
    this.updateCheckbox(params);
    return true;
  }
  updateCheckbox(params) {
    let isSelected;
    let displayed = true;
    const { value: value2, column: column2, node: node2 } = params;
    if (node2.group && column2) {
      if (typeof value2 === "boolean") {
        isSelected = value2;
      } else {
        const colId = column2.getColId();
        if (colId.startsWith(GROUP_AUTO_COLUMN_ID)) {
          isSelected = value2 == null || value2 === "" ? void 0 : value2 === "true";
        } else if (node2.aggData && node2.aggData[colId] !== void 0) {
          isSelected = value2 ?? void 0;
        } else if (node2.sourceRowIndex >= 0) {
          isSelected = value2 ?? void 0;
        } else {
          displayed = false;
        }
      }
    } else {
      isSelected = value2 ?? void 0;
    }
    const { eCheckbox } = this;
    if (!displayed) {
      eCheckbox.setDisplayed(false);
      return;
    }
    eCheckbox.setValue(isSelected);
    const disabled2 = params.disabled ?? !column2?.isCellEditable(node2);
    eCheckbox.setDisabled(disabled2);
    const translate = this.getLocaleTextFunc();
    const stateName = _getAriaCheckboxStateName(translate, isSelected);
    const ariaLabel = disabled2 ? stateName : `${translate("ariaToggleCellValue", "Press SPACE to toggle cell value")} (${stateName})`;
    eCheckbox.setInputAriaLabel(ariaLabel);
  }
  onCheckboxChanged(isSelected) {
    const { params } = this;
    const { column: column2, node: node2, value: value2 } = params;
    this.beans?.editSvc?.setEditingCells(
      [
        {
          column: column2,
          colId: column2.getColId(),
          rowIndex: node2.rowIndex,
          rowPinned: node2.rowPinned,
          state: "changed",
          oldValue: value2,
          newValue: value2
        }
      ],
      { update: true, forceRefreshOfEditCellsOnly: true }
    );
    const valueChanged = node2.setDataValue(column2, isSelected, "renderer");
    this.beans.editSvc?.stopEditing(
      {
        rowNode: node2,
        column: column2
      },
      { source: this.beans.editSvc?.isBatchEditing() ? "ui" : "api" }
    );
    if (!valueChanged) {
      this.updateCheckbox(params);
    }
  }
};
var PinnedRows = class {
  constructor(beans, floating) {
    this.beans = beans;
    this.floating = floating;
    this.all = /* @__PURE__ */ new Set();
    this.visible = /* @__PURE__ */ new Set();
    this.order = [];
    this.queued = /* @__PURE__ */ new Set();
  }
  size() {
    return this.visible.size;
  }
  add(node2) {
    const { all: all2, visible: visible2, order: order2 } = this;
    if (all2.has(node2)) {
      return;
    }
    all2.add(node2);
    visible2.add(node2);
    order2.push(node2);
    this.sort();
  }
  delete(item2) {
    this.all.delete(item2);
    this.visible.delete(item2);
    this.queued.delete(item2.id);
    _removeFromArray(this.order, item2);
  }
  has(item2) {
    return this.visible.has(item2);
  }
  forEach(fn3) {
    this.order.forEach(fn3);
  }
  getByIndex(i2) {
    return this.order[i2];
  }
  getById(id2) {
    for (const node2 of this.visible) {
      if (node2.id == id2) {
        return node2;
      }
    }
  }
  clear() {
    const { all: all2, visible: visible2, order: order2, queued } = this;
    all2.clear();
    queued.clear();
    visible2.clear();
    order2.length = 0;
  }
  sort() {
    const { sortSvc, rowNodeSorter, gos } = this.beans;
    const sortOptions = sortSvc?.getSortOptions() ?? [];
    const grandTotalNode = _removeGrandTotalRow(this.order);
    this.order.sort((a2, b) => (a2.pinnedSibling?.rowIndex ?? 0) - (b.pinnedSibling?.rowIndex ?? 0));
    this.order = rowNodeSorter?.doFullSort(this.order, sortOptions) ?? this.order;
    if (!grandTotalNode) {
      return;
    }
    const grandTotalRow = _getGrandTotalRow(gos);
    if (grandTotalRow === "bottom" || grandTotalRow === "pinnedBottom") {
      this.order.push(grandTotalNode);
    } else {
      this.order.unshift(grandTotalNode);
    }
  }
  hide(shouldHide) {
    const { all: all2, visible: visible2 } = this;
    all2.forEach((node2) => shouldHide(node2) ? visible2.delete(node2) : visible2.add(node2));
    this.order = Array.from(visible2);
    this.sort();
  }
  queue(id2) {
    this.queued.add(id2);
  }
  unqueue(id2) {
    this.queued.delete(id2);
  }
  forEachQueued(fn3) {
    this.queued.forEach(fn3);
  }
};
function _isDisplayedAfterFilterCSRM(node2) {
  if (node2.level === -1) {
    return true;
  }
  const parent = node2.parent;
  if (parent?.childrenAfterSort?.some((child) => child == node2)) {
    return _isDisplayedAfterFilterCSRM(parent);
  }
  return false;
}
function _shouldHidePinnedRows(beans, node2) {
  const { gos, rowModel, filterManager } = beans;
  if (_isServerSideRowModel(gos)) {
    return !rowModel.getRowNode(node2.id);
  }
  if (filterManager?.isAnyFilterPresent()) {
    return !_isDisplayedAfterFilterCSRM(node2);
  }
  if (gos.get("pivotMode")) {
    return !node2.group;
  }
  return false;
}
function _isNodeGrandTotal(node2) {
  return !!node2.footer && node2.level === -1;
}
function _isPinnedNodeGrandTotal(node2) {
  return !!node2.pinnedSibling && _isNodeGrandTotal(node2.pinnedSibling);
}
function _removeGrandTotalRow(order2) {
  const index = order2.findIndex(_isPinnedNodeGrandTotal);
  if (index > -1) {
    return order2.splice(index, 1)?.[0];
  }
}
var ManualPinnedRowModel = class extends BeanStub {
  postConstruct() {
    const { gos, beans } = this;
    this.top = new PinnedRows(beans, "top");
    this.bottom = new PinnedRows(beans, "bottom");
    const shouldHide = (node2) => _shouldHidePinnedRows(beans, node2.pinnedSibling);
    const runIsRowPinned = () => {
      const isRowPinned = gos.get("isRowPinned");
      if (isRowPinned && gos.get("enableRowPinning")) {
        beans.rowModel.forEachNode((node2) => this.pinRow(node2, isRowPinned(node2)), true);
      }
      this.refreshRowPositions();
      this.dispatchRowPinnedEvents();
    };
    this.addManagedEventListeners({
      gridStylesChanged: this.onGridStylesChanges.bind(this),
      modelUpdated: ({ keepRenderedRows }) => {
        this.tryToEmptyQueues();
        this.pinGrandTotalRow();
        this.forContainers((container2) => container2.hide(shouldHide));
        const positionsChanged = this.refreshRowPositions();
        if (!keepRenderedRows || positionsChanged) {
          this.dispatchRowPinnedEvents();
        }
      },
      columnRowGroupChanged: () => {
        this.forContainers(removeGroupRows);
        this.refreshRowPositions();
      },
      rowNodeDataChanged: ({ node: node2 }) => {
        const isRowPinnable = gos.get("isRowPinnable");
        const pinnable = isRowPinnable?.(node2) ?? true;
        if (!pinnable) {
          this.pinRow(node2, null);
        }
      },
      firstDataRendered: runIsRowPinned
    });
    this.addManagedPropertyListener("pivotMode", () => {
      this.forContainers((container2) => container2.hide(shouldHide));
      this.dispatchRowPinnedEvents();
    });
    this.addManagedPropertyListener("grandTotalRow", ({ currentValue }) => {
      this._grandTotalPinned = currentValue === "pinnedBottom" ? "bottom" : currentValue === "pinnedTop" ? "top" : null;
    });
    this.addManagedPropertyListener("isRowPinned", runIsRowPinned);
  }
  destroy() {
    this.reset(false);
    super.destroy();
  }
  reset(dispatch = true) {
    this.forContainers((container2) => {
      const nodesToUnpin = [];
      container2.forEach((n2) => nodesToUnpin.push(n2));
      nodesToUnpin.forEach((n2) => this.pinRow(n2, null));
      container2.clear();
    });
    if (dispatch) {
      this.dispatchRowPinnedEvents();
    }
  }
  pinRow(rowNode, float2, column2) {
    if (rowNode.footer && rowNode.level > -1) {
      return;
    }
    if (rowNode.footer && rowNode.level === -1) {
      this._grandTotalPinned = float2;
      refreshCSRM(this.beans);
      return;
    }
    const currentFloat = rowNode.rowPinned ?? rowNode.pinnedSibling?.rowPinned;
    const switching = currentFloat != null && float2 != null && float2 != currentFloat;
    if (switching) {
      const pinned = rowNode.rowPinned ? rowNode : rowNode.pinnedSibling;
      const source2 = rowNode.rowPinned ? rowNode.pinnedSibling : rowNode;
      this.pinRow(pinned, null, column2);
      this.pinRow(source2, float2, column2);
      return;
    }
    const spannedRows = column2 && getSpannedRows(this.beans, rowNode, column2);
    if (spannedRows) {
      spannedRows.forEach((node2) => this.pinRow(node2, float2));
      return;
    }
    if (float2 == null) {
      const node2 = rowNode.rowPinned ? rowNode : rowNode.pinnedSibling;
      const found = this.findPinnedRowNode(node2);
      if (!found) {
        return;
      }
      found.delete(node2);
      const source2 = node2.pinnedSibling;
      _destroyRowNodeSibling(node2);
      this.refreshRowPositions(float2);
      this.dispatchRowPinnedEvents(source2);
    } else {
      const sibling2 = _createPinnedSibling(this.beans, rowNode, float2);
      const container2 = this.getContainer(float2);
      container2.add(sibling2);
      if (_shouldHidePinnedRows(this.beans, rowNode)) {
        container2.hide((node2) => _shouldHidePinnedRows(this.beans, node2.pinnedSibling));
      }
      this.refreshRowPositions(float2);
      this.dispatchRowPinnedEvents(rowNode);
    }
  }
  isManual() {
    return true;
  }
  isEmpty(floating) {
    return this.getContainer(floating).size() === 0;
  }
  isRowsToRender(floating) {
    return !this.isEmpty(floating);
  }
  ensureRowHeightsValid() {
    let anyChange = false;
    let rowTop = 0;
    const updateRowHeight = (rowNode) => {
      if (rowNode.rowHeightEstimated) {
        const rowHeight = _getRowHeightForNode(this.beans, rowNode);
        rowNode.setRowTop(rowTop);
        rowNode.setRowHeight(rowHeight.height);
        rowTop += rowHeight.height;
        anyChange = true;
      }
    };
    this.bottom.forEach(updateRowHeight);
    rowTop = 0;
    this.top.forEach(updateRowHeight);
    this.eventSvc.dispatchEvent({
      type: "pinnedHeightChanged"
    });
    return anyChange;
  }
  getPinnedTopTotalHeight() {
    return getTotalHeight(this.top);
  }
  getPinnedBottomTotalHeight() {
    return getTotalHeight(this.bottom);
  }
  getPinnedTopRowCount() {
    return this.top.size();
  }
  getPinnedBottomRowCount() {
    return this.bottom.size();
  }
  getPinnedTopRow(index) {
    return this.top.getByIndex(index);
  }
  getPinnedBottomRow(index) {
    return this.bottom.getByIndex(index);
  }
  getPinnedRowById(id2, floating) {
    return this.getContainer(floating).getById(id2);
  }
  forEachPinnedRow(floating, callback) {
    this.getContainer(floating).forEach(callback);
  }
  getPinnedState() {
    const buildState = (floating) => {
      const list2 = [];
      this.forEachPinnedRow(floating, (node2) => list2.push(node2.pinnedSibling.id));
      return list2;
    };
    return {
      top: buildState("top"),
      bottom: buildState("bottom")
    };
  }
  setPinnedState(state) {
    this.forContainers((pinned, floating) => {
      for (const id2 of state[floating]) {
        const node2 = this.beans.rowModel.getRowNode(id2);
        if (node2) {
          this.pinRow(node2, floating);
        } else {
          pinned.queue(id2);
        }
      }
    });
  }
  getGrandTotalPinned() {
    return this._grandTotalPinned;
  }
  setGrandTotalPinned(value2) {
    this._grandTotalPinned = value2;
  }
  tryToEmptyQueues() {
    this.forContainers((pinned, container2) => {
      const nodesToPin = /* @__PURE__ */ new Set();
      pinned.forEachQueued((id2) => {
        const node2 = this.beans.rowModel.getRowNode(id2);
        if (node2) {
          nodesToPin.add(node2);
        }
      });
      for (const node2 of nodesToPin) {
        pinned.unqueue(node2.id);
        this.pinRow(node2, container2);
      }
    });
  }
  pinGrandTotalRow() {
    const { gos, beans, _grandTotalPinned: float2 } = this;
    const rowModel = beans.rowModel;
    if (!_isClientSideRowModel(gos)) {
      return;
    }
    const sibling2 = rowModel.rootNode?.sibling;
    if (!sibling2) {
      return;
    }
    const pinnedSibling = sibling2.pinnedSibling;
    const container2 = pinnedSibling && this.findPinnedRowNode(pinnedSibling);
    if (!float2) {
      if (!container2) {
        return;
      }
      container2.delete(pinnedSibling);
      _destroyRowNodeSibling(pinnedSibling);
    } else {
      if (container2 && container2.floating !== float2) {
        container2.delete(pinnedSibling);
        _destroyRowNodeSibling(pinnedSibling);
      }
      if (!container2 || container2.floating !== float2) {
        const newPinnedSibling = _createPinnedSibling(beans, sibling2, float2);
        this.getContainer(float2).add(newPinnedSibling);
      }
    }
  }
  onGridStylesChanges(e) {
    if (e.rowHeightChanged) {
      this.forContainers(
        (container2) => container2.forEach((rowNode) => rowNode.setRowHeight(rowNode.rowHeight, true))
      );
    }
  }
  getContainer(floating) {
    return floating === "top" ? this.top : this.bottom;
  }
  findPinnedRowNode(node2) {
    if (this.top.has(node2)) {
      return this.top;
    }
    if (this.bottom.has(node2)) {
      return this.bottom;
    }
  }
  refreshRowPositions(floating) {
    const refreshAll = (pinned) => refreshRowPositions(this.beans, pinned);
    if (floating) {
      return refreshAll(this.getContainer(floating));
    }
    let changed = false;
    this.forContainers((container2) => {
      const updated = refreshAll(container2);
      changed || (changed = updated);
    });
    return changed;
  }
  forContainers(fn3) {
    fn3(this.top, "top");
    fn3(this.bottom, "bottom");
  }
  dispatchRowPinnedEvents(node2) {
    this.eventSvc.dispatchEvent({ type: "pinnedRowsChanged" });
    node2?.dispatchRowEvent("rowPinned");
  }
};
function refreshRowPositions(beans, container2) {
  let rowTop = 0;
  let changed = false;
  container2.forEach((node2, index) => {
    changed || (changed = node2.rowTop !== rowTop);
    node2.setRowTop(rowTop);
    if (node2.rowHeightEstimated || node2.rowHeight == null) {
      const rowHeight = _getRowHeightForNode(beans, node2).height;
      changed || (changed = node2.rowHeight !== rowHeight);
      node2.setRowHeight(rowHeight);
    }
    node2.setRowIndex(index);
    rowTop += node2.rowHeight;
  });
  return changed;
}
function _createPinnedSibling(beans, rowNode, floating) {
  if (rowNode.pinnedSibling) {
    return rowNode.pinnedSibling;
  }
  const sibling2 = _createRowNodeSibling(rowNode, beans);
  sibling2.setRowTop(null);
  sibling2.setRowIndex(null);
  sibling2.rowPinned = floating;
  const prefix = floating === "top" ? ROW_ID_PREFIX_TOP_PINNED : ROW_ID_PREFIX_BOTTOM_PINNED;
  sibling2.id = `${prefix}${floating}-${rowNode.id}`;
  sibling2.pinnedSibling = rowNode;
  rowNode.pinnedSibling = sibling2;
  return sibling2;
}
function _destroyRowNodeSibling(rowNode) {
  if (!rowNode.pinnedSibling) {
    return;
  }
  rowNode.rowPinned = null;
  rowNode.setRowTop(null);
  rowNode.setRowIndex(null);
  const mainNode = rowNode.pinnedSibling;
  rowNode.pinnedSibling = void 0;
  if (mainNode) {
    mainNode.pinnedSibling = void 0;
    mainNode.rowPinned = null;
  }
}
function removeGroupRows(set3) {
  const rowsToRemove = /* @__PURE__ */ new Set();
  set3.forEach((node2) => {
    if (node2.group) {
      rowsToRemove.add(node2);
    }
  });
  rowsToRemove.forEach((node2) => set3.delete(node2));
}
function getSpannedRows(beans, rowNode, column2) {
  const { rowSpanSvc } = beans;
  const isCellSpanning = (column2 && rowSpanSvc?.isCellSpanning(column2, rowNode)) ?? false;
  if (column2 && isCellSpanning) {
    return rowSpanSvc?.getCellSpan(column2, rowNode)?.spannedNodes;
  }
}
function getTotalHeight(container2) {
  const size = container2.size();
  if (size === 0) {
    return 0;
  }
  const node2 = container2.getByIndex(size - 1);
  if (node2 === void 0) {
    return 0;
  }
  return node2.rowTop + node2.rowHeight;
}
function refreshCSRM({ gos, rowModel }) {
  if (_isClientSideRowModel(gos)) {
    rowModel.refreshModel({ step: "map" });
  }
}
var StaticPinnedRowModel = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.nextId = 0;
    this.pinnedTopRows = { cache: {}, order: [] };
    this.pinnedBottomRows = { cache: {}, order: [] };
  }
  postConstruct() {
    const gos = this.gos;
    this.setPinnedRowData(gos.get("pinnedTopRowData"), "top");
    this.setPinnedRowData(gos.get("pinnedBottomRowData"), "bottom");
    this.addManagedPropertyListener("pinnedTopRowData", (e) => this.setPinnedRowData(e.currentValue, "top"));
    this.addManagedPropertyListener("pinnedBottomRowData", (e) => this.setPinnedRowData(e.currentValue, "bottom"));
    this.addManagedEventListeners({ gridStylesChanged: this.onGridStylesChanges.bind(this) });
  }
  reset() {
  }
  isEmpty(floating) {
    return this.getCache(floating).order.length === 0;
  }
  isRowsToRender(floating) {
    return !this.isEmpty(floating);
  }
  isManual() {
    return false;
  }
  pinRow(_node, _container) {
  }
  onGridStylesChanges(e) {
    if (e.rowHeightChanged) {
      const estimateRowHeight = (rowNode) => {
        rowNode.setRowHeight(rowNode.rowHeight, true);
      };
      forEach(this.pinnedBottomRows, estimateRowHeight);
      forEach(this.pinnedTopRows, estimateRowHeight);
    }
  }
  ensureRowHeightsValid() {
    let anyChange = false;
    let rowTop = 0;
    const updateRowHeight = (rowNode) => {
      if (rowNode.rowHeightEstimated) {
        const rowHeight = _getRowHeightForNode(this.beans, rowNode);
        rowNode.setRowTop(rowTop);
        rowNode.setRowHeight(rowHeight.height);
        rowTop += rowHeight.height;
        anyChange = true;
      }
    };
    forEach(this.pinnedBottomRows, updateRowHeight);
    rowTop = 0;
    forEach(this.pinnedTopRows, updateRowHeight);
    this.eventSvc.dispatchEvent({
      type: "pinnedHeightChanged"
    });
    return anyChange;
  }
  setPinnedRowData(rowData, floating) {
    this.updateNodesFromRowData(rowData, floating);
    this.eventSvc.dispatchEvent({
      type: "pinnedRowDataChanged"
    });
  }
  /**
   * Updates existing RowNode instances and creates new ones if necessary
   *
   * Setting data as `undefined` will clear row nodes
   */
  updateNodesFromRowData(allData, floating) {
    const nodes = this.getCache(floating);
    if (allData === void 0) {
      nodes.order.length = 0;
      nodes.cache = {};
      return;
    }
    const getRowId = _getRowIdCallback(this.gos);
    const idPrefix = floating === "top" ? ROW_ID_PREFIX_TOP_PINNED : ROW_ID_PREFIX_BOTTOM_PINNED;
    const nodesToRemove = new Set(nodes.order);
    const newOrder = [];
    const dataIds = /* @__PURE__ */ new Set();
    let nextRowTop = 0;
    let i2 = -1;
    for (const data2 of allData) {
      const id2 = getRowId?.({ data: data2, level: 0, rowPinned: floating }) ?? idPrefix + this.nextId++;
      if (dataIds.has(id2)) {
        _warn(96, { id: id2, data: data2 });
        continue;
      }
      i2++;
      dataIds.add(id2);
      newOrder.push(id2);
      const existingNode = getById(nodes, id2);
      if (existingNode !== void 0) {
        if (existingNode.data !== data2) {
          existingNode.updateData(data2);
        }
        nextRowTop += this.setRowTopAndRowIndex(existingNode, nextRowTop, i2);
        nodesToRemove.delete(id2);
      } else {
        const rowNode = new RowNode(this.beans);
        rowNode.id = id2;
        rowNode.data = data2;
        rowNode.rowPinned = floating;
        nextRowTop += this.setRowTopAndRowIndex(rowNode, nextRowTop, i2);
        nodes.cache[id2] = rowNode;
        nodes.order.push(id2);
      }
    }
    for (const id2 of nodesToRemove) {
      getById(nodes, id2)?.clearRowTopAndRowIndex();
      delete nodes.cache[id2];
    }
    nodes.order = newOrder;
  }
  setRowTopAndRowIndex(rowNode, rowTop, rowIndex) {
    rowNode.setRowTop(rowTop);
    rowNode.setRowHeight(_getRowHeightForNode(this.beans, rowNode).height);
    rowNode.setRowIndex(rowIndex);
    return rowNode.rowHeight;
  }
  getPinnedTopTotalHeight() {
    return getTotalHeight2(this.pinnedTopRows);
  }
  getPinnedBottomTotalHeight() {
    return getTotalHeight2(this.pinnedBottomRows);
  }
  getPinnedTopRowCount() {
    return getSize(this.pinnedTopRows);
  }
  getPinnedBottomRowCount() {
    return getSize(this.pinnedBottomRows);
  }
  getPinnedTopRow(index) {
    return getByIndex(this.pinnedTopRows, index);
  }
  getPinnedBottomRow(index) {
    return getByIndex(this.pinnedBottomRows, index);
  }
  getPinnedRowById(id2, floating) {
    return getById(this.getCache(floating), id2);
  }
  forEachPinnedRow(floating, callback) {
    return forEach(this.getCache(floating), callback);
  }
  getCache(floating) {
    return floating === "top" ? this.pinnedTopRows : this.pinnedBottomRows;
  }
  getPinnedState() {
    return { top: [], bottom: [] };
  }
  setPinnedState() {
  }
  getGrandTotalPinned() {
    return;
  }
  setGrandTotalPinned() {
  }
};
function getTotalHeight2(rowNodes) {
  const size = getSize(rowNodes);
  if (size === 0) {
    return 0;
  }
  const node2 = getByIndex(rowNodes, size - 1);
  if (node2 === void 0) {
    return 0;
  }
  return node2.rowTop + node2.rowHeight;
}
function getById(cache, id2) {
  return cache.cache[id2];
}
function getByIndex(cache, i2) {
  return getById(cache, cache.order[i2]);
}
function forEach(cache, callback) {
  cache.order.forEach((id2, index) => {
    const node2 = getById(cache, id2);
    node2 && callback(node2, index);
  });
}
function getSize(cache) {
  return cache.order.length;
}
var PinnedRowModel = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "pinnedRowModel";
  }
  postConstruct() {
    const { gos } = this;
    const initialiseRowModel = () => {
      const enableRowPinning = gos.get("enableRowPinning");
      const grandTotalRow = _getGrandTotalRow(gos);
      const isGrandTotalRowPinned = grandTotalRow === "pinnedBottom" || grandTotalRow === "pinnedTop";
      const useManualPinnedRowModel = !!enableRowPinning || isGrandTotalRowPinned;
      const shouldDestroy = useManualPinnedRowModel ? this.inner instanceof StaticPinnedRowModel : this.inner instanceof ManualPinnedRowModel;
      if (this.inner && shouldDestroy) {
        this.destroyBean(this.inner);
      }
      if (shouldDestroy || !this.inner) {
        this.inner = this.createManagedBean(
          useManualPinnedRowModel ? new ManualPinnedRowModel() : new StaticPinnedRowModel()
        );
      }
    };
    this.addManagedPropertyListeners(["enableRowPinning", "grandTotalRow"], initialiseRowModel);
    initialiseRowModel();
  }
  reset() {
    return this.inner.reset();
  }
  isEmpty(container2) {
    return this.inner.isEmpty(container2);
  }
  isManual() {
    return this.inner.isManual();
  }
  isRowsToRender(container2) {
    return this.inner.isRowsToRender(container2);
  }
  pinRow(node2, container2, column2) {
    return this.inner.pinRow(node2, container2, column2);
  }
  ensureRowHeightsValid() {
    return this.inner.ensureRowHeightsValid();
  }
  getPinnedRowById(id2, container2) {
    return this.inner.getPinnedRowById(id2, container2);
  }
  getPinnedTopTotalHeight() {
    return this.inner.getPinnedTopTotalHeight();
  }
  getPinnedBottomTotalHeight() {
    return this.inner.getPinnedBottomTotalHeight();
  }
  getPinnedTopRowCount() {
    return this.inner.getPinnedTopRowCount();
  }
  getPinnedBottomRowCount() {
    return this.inner.getPinnedBottomRowCount();
  }
  getPinnedTopRow(index) {
    return this.inner.getPinnedTopRow(index);
  }
  getPinnedBottomRow(index) {
    return this.inner.getPinnedBottomRow(index);
  }
  forEachPinnedRow(container2, callback) {
    return this.inner.forEachPinnedRow(container2, callback);
  }
  getPinnedState() {
    return this.inner.getPinnedState();
  }
  setPinnedState(state) {
    return this.inner.setPinnedState(state);
  }
  setGrandTotalPinned(value2) {
    return this.inner.setGrandTotalPinned(value2);
  }
  getGrandTotalPinned() {
    return this.inner.getGrandTotalPinned();
  }
};
function _isManualPinnedRow(rowNode) {
  return !!(rowNode.rowPinned && rowNode.pinnedSibling);
}
function _getNodesInRangeForSelection(rowModel, float2, start2, end2) {
  const isTop = float2 === "top";
  if (!start2) {
    return _getNodesInRangeForSelection(
      rowModel,
      float2,
      isTop ? rowModel.getPinnedTopRow(0) : rowModel.getPinnedBottomRow(0),
      end2
    );
  }
  if (!end2) {
    const count2 = isTop ? rowModel.getPinnedTopRowCount() : rowModel.getPinnedBottomRowCount();
    return _getNodesInRangeForSelection(
      rowModel,
      float2,
      start2,
      isTop ? rowModel.getPinnedTopRow(count2 - 1) : rowModel.getPinnedBottomRow(count2 - 1)
    );
  }
  let started = false;
  let finished = false;
  const range = [];
  rowModel.forEachPinnedRow(float2, (node2) => {
    if (node2 === start2 && !started) {
      started = true;
      range.push(node2);
      return;
    }
    if (started && node2 === end2) {
      finished = true;
      range.push(node2);
      return;
    }
    if (started && !finished) {
      range.push(node2);
    }
  });
  return range;
}
var CheckboxSelectionComponentElement = {
  tag: "div",
  cls: "ag-selection-checkbox",
  role: "presentation",
  children: [
    {
      tag: "ag-checkbox",
      ref: "eCheckbox",
      role: "presentation"
    }
  ]
};
var CheckboxSelectionComponent = class extends Component {
  constructor() {
    super(CheckboxSelectionComponentElement, [AgCheckboxSelector]);
    this.eCheckbox = RefPlaceholder;
  }
  postConstruct() {
    this.eCheckbox.setPassive(true);
  }
  onDataChanged() {
    this.onSelectionChanged();
  }
  onSelectableChanged() {
    this.showOrHideSelect();
  }
  onSelectionChanged() {
    const translate = this.getLocaleTextFunc();
    const { rowNode, eCheckbox } = this;
    const state = rowNode.isSelected();
    const stateName = _getAriaCheckboxStateName(translate, state);
    const [ariaKey, ariaLabel] = rowNode.selectable ? ["ariaRowToggleSelection", "Press Space to toggle row selection"] : ["ariaRowSelectionDisabled", "Row Selection is disabled for this row"];
    const translatedLabel = translate(ariaKey, ariaLabel);
    eCheckbox.setValue(state, true);
    eCheckbox.setInputAriaLabel(`${translatedLabel} (${stateName})`);
  }
  init(params) {
    this.rowNode = params.rowNode;
    this.column = params.column;
    this.overrides = params.overrides;
    this.onSelectionChanged();
    this.addManagedListeners(this.eCheckbox.getInputElement(), {
      // we don't want double click on this icon to open a group
      dblclick: _stopPropagationForAgGrid,
      click: (event) => {
        _stopPropagationForAgGrid(event);
        this.beans.selectionSvc?.handleSelectionEvent(event, this.rowNode, "checkboxSelected");
      }
    });
    this.addManagedListeners(this.rowNode, {
      rowSelected: this.onSelectionChanged.bind(this),
      dataChanged: this.onDataChanged.bind(this),
      selectableChanged: this.onSelectableChanged.bind(this)
    });
    this.addManagedPropertyListener("rowSelection", ({ currentValue, previousValue }) => {
      const curr = typeof currentValue === "object" ? _getHideDisabledCheckboxes(currentValue) : void 0;
      const prev = typeof previousValue === "object" ? _getHideDisabledCheckboxes(previousValue) : void 0;
      if (curr !== prev) {
        this.onSelectableChanged();
      }
    });
    const isRowSelectableFunc = _getIsRowSelectable(this.gos);
    const checkboxVisibleIsDynamic = isRowSelectableFunc || typeof this.getIsVisible() === "function";
    if (checkboxVisibleIsDynamic) {
      const showOrHideSelectListener = this.showOrHideSelect.bind(this);
      this.addManagedEventListeners({ displayedColumnsChanged: showOrHideSelectListener });
      this.addManagedListeners(this.rowNode, {
        dataChanged: showOrHideSelectListener,
        cellChanged: showOrHideSelectListener
      });
      this.showOrHideSelect();
    }
    this.eCheckbox.getInputElement().setAttribute("tabindex", "-1");
  }
  showOrHideSelect() {
    const { column: column2, rowNode, overrides, gos } = this;
    const selectable = rowNode.selectable;
    const isVisible = this.getIsVisible();
    let checkboxes = void 0;
    if (typeof isVisible === "function") {
      const extraParams = overrides?.callbackParams;
      if (!column2) {
        checkboxes = isVisible({ ...extraParams, node: rowNode, data: rowNode.data });
      } else {
        const params = column2.createColumnFunctionCallbackParams(rowNode);
        checkboxes = isVisible({ ...extraParams, ...params });
      }
    } else {
      checkboxes = isVisible ?? false;
    }
    const disabled2 = selectable && !checkboxes || !selectable && checkboxes;
    const visible2 = selectable || checkboxes;
    const so2 = gos.get("rowSelection");
    const showDisabledCheckboxes = so2 && typeof so2 !== "string" ? !_getHideDisabledCheckboxes(so2) : !!column2?.getColDef().showDisabledCheckboxes;
    this.setVisible(visible2 && (disabled2 ? showDisabledCheckboxes : true));
    this.setDisplayed(visible2 && (disabled2 ? showDisabledCheckboxes : true));
    if (visible2) {
      this.eCheckbox.setDisabled(disabled2);
    }
    if (overrides?.removeHidden) {
      this.setDisplayed(visible2);
    }
  }
  getIsVisible() {
    const overrides = this.overrides;
    if (overrides) {
      return overrides.isVisible;
    }
    const so2 = this.gos.get("rowSelection");
    if (so2 && typeof so2 !== "string") {
      return _getCheckboxes(so2);
    }
    return this.column?.getColDef()?.checkboxSelection;
  }
};
var RowRangeSelectionContext = class {
  constructor(rowModel, pinnedRowModel) {
    this.rowModel = rowModel;
    this.pinnedRowModel = pinnedRowModel;
    this.selectAll = false;
    this.rootId = null;
    this.endId = null;
    this.cachedRange = [];
  }
  reset() {
    this.rootId = null;
    this.endId = null;
    this.cachedRange.length = 0;
  }
  setRoot(node2) {
    this.rootId = node2.id;
    this.endId = null;
    this.cachedRange.length = 0;
  }
  setEndRange(end2) {
    this.endId = end2.id;
    this.cachedRange.length = 0;
  }
  getRange() {
    if (this.cachedRange.length === 0) {
      const root2 = this.getRoot();
      const end2 = this.getEnd();
      if (root2 == null || end2 == null) {
        return this.cachedRange;
      }
      this.cachedRange = this.getNodesInRange(root2, end2) ?? [];
    }
    return this.cachedRange;
  }
  isInRange(node2) {
    if (this.rootId === null) {
      return false;
    }
    return this.getRange().some((nodeInRange) => nodeInRange.id === node2.id);
  }
  getRoot(fallback) {
    if (this.rootId) {
      return this.getRowNode(this.rootId);
    }
    if (fallback) {
      this.setRoot(fallback);
      return fallback;
    }
  }
  getEnd() {
    if (this.endId) {
      return this.getRowNode(this.endId);
    }
  }
  getRowNode(id2) {
    let node2;
    const { rowModel, pinnedRowModel } = this;
    node2 ?? (node2 = rowModel.getRowNode(id2));
    if (pinnedRowModel?.isManual()) {
      node2 ?? (node2 = pinnedRowModel.getPinnedRowById(id2, "top"));
      node2 ?? (node2 = pinnedRowModel.getPinnedRowById(id2, "bottom"));
    }
    return node2;
  }
  /**
   * Truncates the range to the given node (assumed to be within the current range).
   * Returns nodes that remain in the current range and those that should be removed
   *
   * @param node - Node at which to truncate the range
   * @returns Object of nodes to either keep or discard (i.e. deselect) from the range
   */
  truncate(node2) {
    const range = this.getRange();
    if (range.length === 0) {
      return { keep: [], discard: [] };
    }
    const discardAfter = range[0].id === this.rootId;
    const idx = range.findIndex((rowNode) => rowNode.id === node2.id);
    if (idx > -1) {
      const above = range.slice(0, idx);
      const below = range.slice(idx + 1);
      this.setEndRange(node2);
      return discardAfter ? { keep: above, discard: below } : { keep: below, discard: above };
    } else {
      return { keep: range, discard: [] };
    }
  }
  /**
   * Extends the range to the given node. Returns nodes that remain in the current range
   * and those that should be removed.
   *
   * @param node - Node marking the new end of the range
   * @returns Object of nodes to either keep or discard (i.e. deselect) from the range
   */
  extend(node2, groupSelectsChildren = false) {
    const root2 = this.getRoot();
    if (root2 == null) {
      const keep = this.getRange().slice();
      if (groupSelectsChildren) {
        node2.depthFirstSearch((node22) => !node22.group && keep.push(node22));
      }
      keep.push(node2);
      this.setRoot(node2);
      return { keep, discard: [] };
    }
    const newRange = this.getNodesInRange(root2, node2);
    if (!newRange) {
      this.setRoot(node2);
      return { keep: [node2], discard: [] };
    }
    if (newRange.find((newRangeNode) => newRangeNode.id === this.endId)) {
      this.setEndRange(node2);
      return { keep: this.getRange(), discard: [] };
    } else {
      const discard = this.getRange().slice();
      this.setEndRange(node2);
      return { keep: this.getRange(), discard };
    }
  }
  getNodesInRange(start2, end2) {
    const { pinnedRowModel, rowModel } = this;
    if (!pinnedRowModel?.isManual()) {
      return rowModel.getNodesInRangeForSelection(start2, end2);
    }
    if (start2.rowPinned === "top" && !end2.rowPinned) {
      const pinnedRange = _getNodesInRangeForSelection(pinnedRowModel, "top", start2, void 0);
      return pinnedRange.concat(rowModel.getNodesInRangeForSelection(rowModel.getRow(0), end2) ?? []);
    }
    if (start2.rowPinned === "bottom" && !end2.rowPinned) {
      const pinnedRange = _getNodesInRangeForSelection(pinnedRowModel, "bottom", void 0, start2);
      const count2 = rowModel.getRowCount();
      const lastMain = rowModel.getRow(count2 - 1);
      return (rowModel.getNodesInRangeForSelection(end2, lastMain) ?? []).concat(pinnedRange);
    }
    if (!start2.rowPinned && !end2.rowPinned) {
      return rowModel.getNodesInRangeForSelection(start2, end2);
    }
    if (start2.rowPinned === "top" && end2.rowPinned === "top") {
      return _getNodesInRangeForSelection(pinnedRowModel, "top", start2, end2);
    }
    if (start2.rowPinned === "bottom" && end2.rowPinned === "top") {
      const top2 = _getNodesInRangeForSelection(pinnedRowModel, "top", end2, void 0);
      const bottom2 = _getNodesInRangeForSelection(pinnedRowModel, "bottom", void 0, start2);
      const first2 = rowModel.getRow(0);
      const last2 = rowModel.getRow(rowModel.getRowCount() - 1);
      return top2.concat(rowModel.getNodesInRangeForSelection(first2, last2) ?? []).concat(bottom2);
    }
    if (!start2.rowPinned && end2.rowPinned === "top") {
      const pinned = _getNodesInRangeForSelection(pinnedRowModel, "top", end2, void 0);
      return pinned.concat(rowModel.getNodesInRangeForSelection(rowModel.getRow(0), start2) ?? []);
    }
    if (start2.rowPinned === "top" && end2.rowPinned === "bottom") {
      const top2 = _getNodesInRangeForSelection(pinnedRowModel, "top", start2, void 0);
      const bottom2 = _getNodesInRangeForSelection(pinnedRowModel, "bottom", void 0, end2);
      const first2 = rowModel.getRow(0);
      const last2 = rowModel.getRow(rowModel.getRowCount() - 1);
      return top2.concat(rowModel.getNodesInRangeForSelection(first2, last2) ?? []).concat(bottom2);
    }
    if (start2.rowPinned === "bottom" && end2.rowPinned === "bottom") {
      return _getNodesInRangeForSelection(pinnedRowModel, "bottom", start2, end2);
    }
    if (!start2.rowPinned && end2.rowPinned === "bottom") {
      const pinned = _getNodesInRangeForSelection(pinnedRowModel, "bottom", void 0, end2);
      const last2 = rowModel.getRow(rowModel.getRowCount());
      return (rowModel.getNodesInRangeForSelection(start2, last2) ?? []).concat(pinned);
    }
    return null;
  }
};
var SelectAllFeature = class extends BeanStub {
  constructor(column2) {
    super();
    this.column = column2;
    this.cbSelectAllVisible = false;
    this.processingEventFromCheckbox = false;
  }
  onSpaceKeyDown(e) {
    const checkbox = this.cbSelectAll;
    if (checkbox.isDisplayed() && !checkbox.getGui().contains(_getActiveDomElement(this.beans))) {
      e.preventDefault();
      checkbox.setValue(!checkbox.getValue());
    }
  }
  getCheckboxGui() {
    return this.cbSelectAll.getGui();
  }
  setComp(ctrl) {
    this.headerCellCtrl = ctrl;
    const cbSelectAll = this.createManagedBean(new AgCheckbox());
    this.cbSelectAll = cbSelectAll;
    cbSelectAll.addCss("ag-header-select-all");
    _setAriaRole(cbSelectAll.getGui(), "presentation");
    this.showOrHideSelectAll();
    const updateStateOfCheckbox = this.updateStateOfCheckbox.bind(this);
    this.addManagedEventListeners({
      newColumnsLoaded: () => this.showOrHideSelectAll(),
      displayedColumnsChanged: this.onDisplayedColumnsChanged.bind(this),
      selectionChanged: updateStateOfCheckbox,
      paginationChanged: updateStateOfCheckbox,
      modelUpdated: updateStateOfCheckbox
    });
    this.addManagedPropertyListener("rowSelection", ({ currentValue, previousValue }) => {
      const getSelectAll = (rowSelection) => typeof rowSelection === "string" || !rowSelection || rowSelection.mode === "singleRow" ? void 0 : rowSelection.selectAll;
      if (getSelectAll(currentValue) !== getSelectAll(previousValue)) {
        this.showOrHideSelectAll();
      }
      this.updateStateOfCheckbox();
    });
    this.addManagedListeners(cbSelectAll, { fieldValueChanged: this.onCbSelectAll.bind(this) });
    cbSelectAll.getInputElement().setAttribute("tabindex", "-1");
    this.refreshSelectAllLabel();
  }
  onDisplayedColumnsChanged(e) {
    if (!this.isAlive()) {
      return;
    }
    this.showOrHideSelectAll(e.source === "uiColumnMoved");
  }
  showOrHideSelectAll(fromColumnMoved = false) {
    const cbSelectAllVisible = this.isCheckboxSelection();
    this.cbSelectAllVisible = cbSelectAllVisible;
    this.cbSelectAll.setDisplayed(cbSelectAllVisible);
    if (cbSelectAllVisible) {
      this.checkRightRowModelType("selectAllCheckbox");
      this.checkSelectionType("selectAllCheckbox");
      this.updateStateOfCheckbox();
    }
    this.refreshSelectAllLabel(fromColumnMoved);
  }
  updateStateOfCheckbox() {
    if (!this.cbSelectAllVisible || this.processingEventFromCheckbox) {
      return;
    }
    this.processingEventFromCheckbox = true;
    const selectAllMode = this.getSelectAllMode();
    const selectionSvc = this.beans.selectionSvc;
    const cbSelectAll = this.cbSelectAll;
    const allSelected = selectionSvc.getSelectAllState(selectAllMode);
    cbSelectAll.setValue(allSelected);
    const hasNodesToSelect = selectionSvc.hasNodesToSelect(selectAllMode);
    cbSelectAll.setDisabled(!hasNodesToSelect);
    this.refreshSelectAllLabel();
    this.processingEventFromCheckbox = false;
  }
  refreshSelectAllLabel(fromColumnMoved = false) {
    const translate = this.getLocaleTextFunc();
    const { headerCellCtrl, cbSelectAll, cbSelectAllVisible } = this;
    const checked = cbSelectAll.getValue();
    const ariaStatus = _getAriaCheckboxStateName(translate, checked);
    const ariaLabel = translate("ariaRowSelectAll", "Press Space to toggle all rows selection");
    headerCellCtrl.setAriaDescriptionProperty(
      "selectAll",
      cbSelectAllVisible ? `${ariaLabel} (${ariaStatus})` : null
    );
    cbSelectAll.setInputAriaLabel(translate("ariaHeaderSelection", "Column with Header Selection"));
    if (!fromColumnMoved) {
      headerCellCtrl.announceAriaDescription();
    }
  }
  checkSelectionType(feature) {
    const isMultiSelect = _isMultiRowSelection(this.gos);
    if (!isMultiSelect) {
      _warn(128, { feature });
      return false;
    }
    return true;
  }
  checkRightRowModelType(feature) {
    const { gos, rowModel } = this.beans;
    const rowModelMatches = _isClientSideRowModel(gos) || _isServerSideRowModel(gos);
    if (!rowModelMatches) {
      _warn(129, { feature, rowModel: rowModel.getType() });
      return false;
    }
    return true;
  }
  onCbSelectAll() {
    if (this.processingEventFromCheckbox) {
      return;
    }
    if (!this.cbSelectAllVisible) {
      return;
    }
    const value2 = this.cbSelectAll.getValue();
    const selectAll2 = this.getSelectAllMode();
    let source2 = "uiSelectAll";
    if (selectAll2 === "currentPage") {
      source2 = "uiSelectAllCurrentPage";
    } else if (selectAll2 === "filtered") {
      source2 = "uiSelectAllFiltered";
    }
    const params = { source: source2, selectAll: selectAll2 };
    const selectionSvc = this.beans.selectionSvc;
    if (value2) {
      selectionSvc.selectAllRowNodes(params);
    } else {
      selectionSvc.deselectAllRowNodes(params);
    }
  }
  /**
   * Checkbox is enabled when either the `headerCheckbox` option is enabled in the new selection API
   * or `headerCheckboxSelection` is enabled in the legacy API.
   */
  isCheckboxSelection() {
    const { column: column2, gos, beans } = this;
    const rowSelection = gos.get("rowSelection");
    const newHeaderCheckbox = typeof rowSelection === "object";
    const featureName = newHeaderCheckbox ? "headerCheckbox" : "headerCheckboxSelection";
    return isCheckboxSelection(beans, column2) && this.checkRightRowModelType(featureName) && this.checkSelectionType(featureName);
  }
  getSelectAllMode() {
    const selectAll2 = _getSelectAll(this.gos, false);
    if (selectAll2) {
      return selectAll2;
    }
    const { headerCheckboxSelectionCurrentPageOnly, headerCheckboxSelectionFilteredOnly } = this.column.getColDef();
    if (headerCheckboxSelectionCurrentPageOnly) {
      return "currentPage";
    }
    if (headerCheckboxSelectionFilteredOnly) {
      return "filtered";
    }
    return "all";
  }
  destroy() {
    super.destroy();
    this.cbSelectAll = void 0;
    this.headerCellCtrl = void 0;
  }
};
function isCheckboxSelection({ gos, selectionColSvc }, column2) {
  const rowSelection = gos.get("rowSelection");
  const colDef = column2.getColDef();
  const { headerCheckboxSelection } = colDef;
  let result2 = false;
  const newHeaderCheckbox = typeof rowSelection === "object";
  if (newHeaderCheckbox) {
    const isSelectionCol = isColumnSelectionCol(column2);
    const isAutoCol = isColumnGroupAutoCol(column2);
    const location = _getCheckboxLocation(rowSelection);
    if (location === "autoGroupColumn" && isAutoCol || isSelectionCol && selectionColSvc?.isSelectionColumnEnabled()) {
      result2 = _getHeaderCheckbox(rowSelection);
    }
  } else if (typeof headerCheckboxSelection === "function") {
    result2 = headerCheckboxSelection(_addGridCommonParams(gos, { column: column2, colDef }));
  } else {
    result2 = !!headerCheckboxSelection;
  }
  return result2;
}
var BaseSelectionService = class extends BeanStub {
  postConstruct() {
    const { gos, beans } = this;
    this.selectionCtx = new RowRangeSelectionContext(beans.rowModel, beans.pinnedRowModel);
    this.addManagedPropertyListeners(["isRowSelectable", "rowSelection"], () => {
      const callback = _getIsRowSelectable(gos);
      if (callback !== this.isRowSelectable) {
        this.isRowSelectable = callback;
        this.updateSelectable();
      }
    });
    this.isRowSelectable = _getIsRowSelectable(gos);
    this.addManagedEventListeners({
      cellValueChanged: (e) => this.updateRowSelectable(e.node),
      rowNodeDataChanged: (e) => this.updateRowSelectable(e.node)
    });
  }
  destroy() {
    super.destroy();
    this.selectionCtx.reset();
  }
  createCheckboxSelectionComponent() {
    return new CheckboxSelectionComponent();
  }
  createSelectAllFeature(column2) {
    if (isCheckboxSelection(this.beans, column2)) {
      return new SelectAllFeature(column2);
    }
  }
  isMultiSelect() {
    return _isMultiRowSelection(this.gos);
  }
  onRowCtrlSelected(rowCtrl, hasFocusFunc, gui) {
    const selected2 = !!rowCtrl.rowNode.isSelected();
    rowCtrl.forEachGui(gui, (gui2) => {
      gui2.rowComp.toggleCss("ag-row-selected", selected2);
      const element = gui2.element;
      _setAriaSelected(element, selected2);
      const hasFocus = element.contains(_getActiveDomElement(this.beans));
      if (hasFocus) {
        hasFocusFunc(gui2);
      }
    });
  }
  announceAriaRowSelection(rowNode) {
    if (this.isRowSelectionBlocked(rowNode)) {
      return;
    }
    const selected2 = rowNode.isSelected();
    const isEditing2 = this.beans.editSvc?.isEditing({ rowNode });
    if (!rowNode.selectable || isEditing2) {
      return;
    }
    const translate = this.getLocaleTextFunc();
    const label2 = translate(
      selected2 ? "ariaRowDeselect" : "ariaRowSelect",
      `Press SPACE to ${selected2 ? "deselect" : "select"} this row`
    );
    this.beans.ariaAnnounce?.announceValue(label2, "rowSelection");
  }
  isRowSelectionBlocked(rowNode) {
    return !rowNode.selectable || rowNode.rowPinned && !_isManualPinnedRow(rowNode) || !_isRowSelection(this.gos);
  }
  updateRowSelectable(rowNode, suppressSelectionUpdate) {
    const selectable = rowNode.rowPinned && rowNode.pinnedSibling ? (
      // If row node is pinned sibling, copy selectable status over from sibling row node
      rowNode.pinnedSibling.selectable
    ) : (
      // otherwise calculate selectable state directly
      this.isRowSelectable?.(rowNode) ?? true
    );
    this.setRowSelectable(rowNode, selectable, suppressSelectionUpdate);
    return selectable;
  }
  setRowSelectable(rowNode, newVal, suppressSelectionUpdate) {
    if (rowNode.selectable !== newVal) {
      rowNode.selectable = newVal;
      rowNode.dispatchRowEvent("selectableChanged");
      if (suppressSelectionUpdate) {
        return;
      }
      const isGroupSelectsChildren = _getGroupSelectsDescendants(this.gos);
      if (isGroupSelectsChildren) {
        const selected2 = this.calculateSelectedFromChildren(rowNode);
        this.setNodesSelected({ nodes: [rowNode], newValue: selected2 ?? false, source: "selectableChanged" });
        return;
      }
      if (rowNode.isSelected() && !rowNode.selectable) {
        this.setNodesSelected({ nodes: [rowNode], newValue: false, source: "selectableChanged" });
      }
    }
  }
  calculateSelectedFromChildren(rowNode) {
    let atLeastOneSelected = false;
    let atLeastOneDeSelected = false;
    if (!rowNode.childrenAfterGroup?.length) {
      return rowNode.selectable ? rowNode.__selected : null;
    }
    for (let i2 = 0; i2 < rowNode.childrenAfterGroup.length; i2++) {
      const child = rowNode.childrenAfterGroup[i2];
      let childState = child.isSelected();
      if (!child.selectable) {
        const selectable = this.calculateSelectedFromChildren(child);
        if (selectable === null) {
          continue;
        }
        childState = selectable;
      }
      switch (childState) {
        case true:
          atLeastOneSelected = true;
          break;
        case false:
          atLeastOneDeSelected = true;
          break;
        default:
          return void 0;
      }
    }
    if (atLeastOneSelected && atLeastOneDeSelected) {
      return void 0;
    }
    if (atLeastOneSelected) {
      return true;
    }
    if (atLeastOneDeSelected) {
      return false;
    }
    if (!rowNode.selectable) {
      return null;
    }
    return rowNode.__selected;
  }
  selectRowNode(rowNode, newValue, e, source2 = "api") {
    const selectionNotAllowed = !rowNode.selectable && newValue;
    const selectionNotChanged = rowNode.__selected === newValue;
    if (selectionNotAllowed || selectionNotChanged) {
      return false;
    }
    rowNode.__selected = newValue;
    rowNode.dispatchRowEvent("rowSelected");
    const sibling2 = rowNode.sibling;
    if (sibling2 && sibling2.footer && sibling2.__localEventService) {
      sibling2.dispatchRowEvent("rowSelected");
    }
    const pinnedSibling = rowNode.pinnedSibling;
    if (pinnedSibling?.rowPinned && pinnedSibling.__localEventService) {
      pinnedSibling.dispatchRowEvent("rowSelected");
    }
    this.eventSvc.dispatchEvent({
      ..._createGlobalRowEvent(rowNode, this.gos, "rowSelected"),
      event: e || null,
      source: source2
    });
    return true;
  }
  isCellCheckboxSelection(column2, rowNode) {
    const so2 = this.gos.get("rowSelection");
    if (so2 && typeof so2 !== "string") {
      const checkbox = isColumnSelectionCol(column2) && _getCheckboxes(so2);
      return column2.isColumnFunc(rowNode, checkbox);
    } else {
      return column2.isColumnFunc(rowNode, column2.colDef.checkboxSelection);
    }
  }
  inferNodeSelections(node2, shiftKey, metaKey, source2) {
    const { gos, selectionCtx } = this;
    const currentSelection = node2.isSelected();
    const groupSelectsDescendants = _getGroupSelectsDescendants(gos);
    const enableClickSelection = _getEnableSelection(gos);
    const enableDeselection = _getEnableDeselection(gos);
    const isMultiSelect = this.isMultiSelect();
    const isRowClicked = source2 === "rowClicked";
    if (isRowClicked && !(enableClickSelection || enableDeselection)) {
      return null;
    }
    if (shiftKey && metaKey && isMultiSelect) {
      const root2 = selectionCtx.getRoot();
      if (!root2) {
        return null;
      } else if (!root2.isSelected()) {
        const partition = selectionCtx.extend(node2, groupSelectsDescendants);
        return {
          select: [],
          deselect: partition.keep,
          reset: false
        };
      } else {
        const partition = selectionCtx.isInRange(node2) ? selectionCtx.truncate(node2) : selectionCtx.extend(node2, groupSelectsDescendants);
        return {
          deselect: partition.discard,
          select: partition.keep,
          reset: false
        };
      }
    } else if (shiftKey && isMultiSelect) {
      const fallback = selectionCtx.selectAll ? this.beans.rowModel.getRow(0) : void 0;
      const root2 = selectionCtx.getRoot(fallback);
      const partition = selectionCtx.isInRange(node2) ? selectionCtx.truncate(node2) : selectionCtx.extend(node2, groupSelectsDescendants);
      return {
        select: partition.keep,
        deselect: partition.discard,
        reset: selectionCtx.selectAll || !!(root2 && !root2.isSelected())
      };
    } else if (metaKey) {
      if (isRowClicked) {
        const newValue = !currentSelection;
        const selectingWhenDisabled = newValue && !enableClickSelection;
        const deselectingWhenDisabled = !newValue && !enableDeselection;
        if (selectingWhenDisabled || deselectingWhenDisabled) {
          return null;
        }
        selectionCtx.setRoot(node2);
        return {
          node: node2,
          newValue,
          clearSelection: false
        };
      }
      selectionCtx.setRoot(node2);
      return {
        node: node2,
        newValue: !currentSelection,
        clearSelection: !isMultiSelect
      };
    } else {
      selectionCtx.setRoot(node2);
      const enableSelectionWithoutKeys = _getEnableSelectionWithoutKeys(gos);
      const groupSelectsFiltered = _getGroupSelection(gos) === "filteredDescendants";
      const shouldClear = isRowClicked && (!enableSelectionWithoutKeys || !enableClickSelection);
      if (groupSelectsFiltered && currentSelection === void 0 && _isClientSideRowModel(gos)) {
        return {
          node: node2,
          newValue: false,
          checkFilteredNodes: true,
          clearSelection: !isMultiSelect || shouldClear
        };
      }
      if (isRowClicked) {
        const newValue = currentSelection ? !enableSelectionWithoutKeys : enableClickSelection;
        const selectingWhenDisabled = newValue && !enableClickSelection;
        const deselectingWhenDisabled = !newValue && !enableDeselection;
        const wouldStateBeUnchanged = newValue === currentSelection && !shouldClear;
        if (wouldStateBeUnchanged || selectingWhenDisabled || deselectingWhenDisabled) {
          return null;
        }
        return {
          node: node2,
          newValue,
          clearSelection: !isMultiSelect || shouldClear,
          keepDescendants: node2.group && groupSelectsDescendants
        };
      }
      return {
        node: node2,
        newValue: !currentSelection,
        clearSelection: !isMultiSelect || shouldClear
      };
    }
  }
};
var TabGuardClassNames = {
  TAB_GUARD: "ag-tab-guard",
  TAB_GUARD_TOP: "ag-tab-guard-top",
  TAB_GUARD_BOTTOM: "ag-tab-guard-bottom"
};
var TabGuardCtrl = class extends BeanStub {
  constructor(params) {
    super();
    this.skipTabGuardFocus = false;
    this.forcingFocusOut = false;
    this.allowFocus = false;
    const {
      comp,
      eTopGuard,
      eBottomGuard,
      focusTrapActive,
      forceFocusOutWhenTabGuardsAreEmpty,
      isFocusableContainer,
      focusInnerElement,
      onFocusIn,
      onFocusOut,
      shouldStopEventPropagation,
      onTabKeyDown,
      handleKeyDown,
      isEmpty: isEmpty2,
      eFocusableElement
    } = params;
    this.comp = comp;
    this.eTopGuard = eTopGuard;
    this.eBottomGuard = eBottomGuard;
    this.providedFocusInnerElement = focusInnerElement;
    this.eFocusableElement = eFocusableElement;
    this.focusTrapActive = !!focusTrapActive;
    this.forceFocusOutWhenTabGuardsAreEmpty = !!forceFocusOutWhenTabGuardsAreEmpty;
    this.isFocusableContainer = !!isFocusableContainer;
    this.providedFocusIn = onFocusIn;
    this.providedFocusOut = onFocusOut;
    this.providedShouldStopEventPropagation = shouldStopEventPropagation;
    this.providedOnTabKeyDown = onTabKeyDown;
    this.providedHandleKeyDown = handleKeyDown;
    this.providedIsEmpty = isEmpty2;
  }
  postConstruct() {
    this.createManagedBean(
      new ManagedFocusFeature(this.eFocusableElement, {
        shouldStopEventPropagation: () => this.shouldStopEventPropagation(),
        onTabKeyDown: (e) => this.onTabKeyDown(e),
        handleKeyDown: (e) => this.handleKeyDown(e),
        onFocusIn: (e) => this.onFocusIn(e),
        onFocusOut: (e) => this.onFocusOut(e)
      })
    );
    this.activateTabGuards();
    for (const guard of [this.eTopGuard, this.eBottomGuard]) {
      this.addManagedElementListeners(guard, { focus: this.onFocus.bind(this) });
    }
  }
  handleKeyDown(e) {
    if (this.providedHandleKeyDown) {
      this.providedHandleKeyDown(e);
    }
  }
  tabGuardsAreActive() {
    return !!this.eTopGuard && this.eTopGuard.hasAttribute("tabIndex");
  }
  shouldStopEventPropagation() {
    if (this.providedShouldStopEventPropagation) {
      return this.providedShouldStopEventPropagation();
    }
    return false;
  }
  activateTabGuards() {
    if (this.forcingFocusOut) {
      return;
    }
    const tabIndex = this.gos.get("tabIndex");
    this.comp.setTabIndex(tabIndex.toString());
  }
  deactivateTabGuards() {
    this.comp.setTabIndex();
  }
  onFocus(e) {
    if (this.isFocusableContainer && !this.eFocusableElement.contains(e.relatedTarget)) {
      if (!this.allowFocus) {
        this.findNextElementOutsideAndFocus(e.target === this.eBottomGuard);
        return;
      }
    }
    if (this.skipTabGuardFocus) {
      this.skipTabGuardFocus = false;
      return;
    }
    if (this.forceFocusOutWhenTabGuardsAreEmpty) {
      const isEmpty2 = this.providedIsEmpty ? this.providedIsEmpty() : _findFocusableElements(this.eFocusableElement, ".ag-tab-guard").length === 0;
      if (isEmpty2) {
        this.findNextElementOutsideAndFocus(e.target === this.eBottomGuard);
        return;
      }
    }
    if (this.isFocusableContainer && this.eFocusableElement.contains(e.relatedTarget)) {
      return;
    }
    const fromBottom = e.target === this.eBottomGuard;
    const hasFocusedInnerElement = this.providedFocusInnerElement ? this.providedFocusInnerElement(fromBottom) : this.focusInnerElement(fromBottom);
    if (!hasFocusedInnerElement && this.forceFocusOutWhenTabGuardsAreEmpty) {
      this.findNextElementOutsideAndFocus(e.target === this.eBottomGuard);
    }
  }
  findNextElementOutsideAndFocus(up) {
    const eDocument = _getDocument(this.beans);
    const focusableEls = _findFocusableElements(eDocument.body, null, true);
    const index = focusableEls.indexOf(up ? this.eTopGuard : this.eBottomGuard);
    if (index === -1) {
      return;
    }
    let start2;
    let end2;
    if (up) {
      start2 = 0;
      end2 = index;
    } else {
      start2 = index + 1;
      end2 = focusableEls.length;
    }
    const focusableRange = focusableEls.slice(start2, end2);
    const targetTabIndex = this.gos.get("tabIndex");
    focusableRange.sort((a2, b) => {
      const indexA = Number.parseInt(a2.getAttribute("tabindex") || "0");
      const indexB = Number.parseInt(b.getAttribute("tabindex") || "0");
      if (indexB === targetTabIndex) {
        return 1;
      }
      if (indexA === targetTabIndex) {
        return -1;
      }
      if (indexA === 0) {
        return 1;
      }
      if (indexB === 0) {
        return -1;
      }
      return indexA - indexB;
    });
    focusableRange[up ? focusableRange.length - 1 : 0]?.focus();
  }
  onFocusIn(e) {
    if (this.focusTrapActive || this.forcingFocusOut) {
      return;
    }
    if (this.providedFocusIn) {
      this.providedFocusIn(e);
    }
    if (!this.isFocusableContainer) {
      this.deactivateTabGuards();
    }
  }
  onFocusOut(e) {
    if (this.focusTrapActive) {
      return;
    }
    if (this.providedFocusOut) {
      this.providedFocusOut(e);
    }
    if (!this.eFocusableElement.contains(e.relatedTarget)) {
      this.activateTabGuards();
    }
  }
  onTabKeyDown(e) {
    if (this.providedOnTabKeyDown) {
      this.providedOnTabKeyDown(e);
      return;
    }
    if (this.focusTrapActive) {
      return;
    }
    if (e.defaultPrevented) {
      return;
    }
    const tabGuardsAreActive = this.tabGuardsAreActive();
    if (tabGuardsAreActive) {
      this.deactivateTabGuards();
    }
    const nextRoot = this.getNextFocusableElement(e.shiftKey);
    if (tabGuardsAreActive) {
      setTimeout(() => this.activateTabGuards(), 0);
    }
    if (!nextRoot) {
      return;
    }
    nextRoot.focus();
    e.preventDefault();
  }
  focusInnerElement(fromBottom = false) {
    const focusable = _findFocusableElements(this.eFocusableElement);
    if (this.tabGuardsAreActive()) {
      focusable.splice(0, 1);
      focusable.splice(focusable.length - 1, 1);
    }
    if (!focusable.length) {
      return false;
    }
    focusable[fromBottom ? focusable.length - 1 : 0].focus({ preventScroll: true });
    return true;
  }
  getNextFocusableElement(backwards) {
    return _findNextFocusableElement(this.beans, this.eFocusableElement, false, backwards);
  }
  forceFocusOutOfContainer(up = false) {
    if (this.forcingFocusOut) {
      return;
    }
    const tabGuardToFocus = up ? this.eTopGuard : this.eBottomGuard;
    this.activateTabGuards();
    this.skipTabGuardFocus = true;
    this.forcingFocusOut = true;
    tabGuardToFocus.focus();
    window.setTimeout(() => {
      this.forcingFocusOut = false;
      this.activateTabGuards();
    });
  }
  isTabGuard(element, bottom2) {
    return element === this.eTopGuard && !bottom2 || element === this.eBottomGuard && (bottom2 ?? true);
  }
  setAllowFocus(allowFocus) {
    this.allowFocus = allowFocus;
  }
};
var TabGuardFeature = class extends BeanStub {
  constructor(comp) {
    super();
    this.comp = comp;
  }
  initialiseTabGuard(params) {
    this.eTopGuard = this.createTabGuard("top");
    this.eBottomGuard = this.createTabGuard("bottom");
    this.eFocusableElement = this.comp.getFocusableElement();
    const { eTopGuard, eBottomGuard, eFocusableElement } = this;
    const tabGuards = [eTopGuard, eBottomGuard];
    const compProxy = {
      setTabIndex: (tabIndex) => {
        for (const tabGuard of tabGuards) {
          tabIndex != null ? tabGuard.setAttribute("tabindex", tabIndex) : tabGuard.removeAttribute("tabindex");
        }
      }
    };
    this.addTabGuards(eTopGuard, eBottomGuard);
    const {
      focusTrapActive = false,
      onFocusIn,
      onFocusOut,
      focusInnerElement,
      handleKeyDown,
      onTabKeyDown,
      shouldStopEventPropagation,
      isEmpty: isEmpty2,
      forceFocusOutWhenTabGuardsAreEmpty,
      isFocusableContainer
    } = params;
    this.tabGuardCtrl = this.createManagedBean(
      new TabGuardCtrl({
        comp: compProxy,
        focusTrapActive,
        eTopGuard,
        eBottomGuard,
        eFocusableElement,
        onFocusIn,
        onFocusOut,
        focusInnerElement,
        handleKeyDown,
        onTabKeyDown,
        shouldStopEventPropagation,
        isEmpty: isEmpty2,
        forceFocusOutWhenTabGuardsAreEmpty,
        isFocusableContainer
      })
    );
  }
  getTabGuardCtrl() {
    return this.tabGuardCtrl;
  }
  createTabGuard(side) {
    const tabGuard = _getDocument(this.beans).createElement("div");
    const cls = side === "top" ? TabGuardClassNames.TAB_GUARD_TOP : TabGuardClassNames.TAB_GUARD_BOTTOM;
    tabGuard.classList.add(TabGuardClassNames.TAB_GUARD, cls);
    _setAriaRole(tabGuard, "presentation");
    return tabGuard;
  }
  addTabGuards(topTabGuard, bottomTabGuard) {
    const eFocusableElement = this.eFocusableElement;
    eFocusableElement.insertAdjacentElement("afterbegin", topTabGuard);
    eFocusableElement.insertAdjacentElement("beforeend", bottomTabGuard);
  }
  removeAllChildrenExceptTabGuards() {
    const tabGuards = [this.eTopGuard, this.eBottomGuard];
    _clearElement(this.comp.getFocusableElement());
    this.addTabGuards(...tabGuards);
  }
  forceFocusOutOfContainer(up = false) {
    this.tabGuardCtrl.forceFocusOutOfContainer(up);
  }
  appendChild(appendChild, newChild, container2) {
    if (!_isNodeOrElement(newChild)) {
      newChild = newChild.getGui();
    }
    const { eBottomGuard: bottomTabGuard } = this;
    if (bottomTabGuard) {
      bottomTabGuard.insertAdjacentElement("beforebegin", newChild);
    } else {
      appendChild(newChild, container2);
    }
  }
  destroy() {
    const { eTopGuard, eBottomGuard } = this;
    _removeFromParent(eTopGuard);
    _removeFromParent(eBottomGuard);
    super.destroy();
  }
};
var TabGuardComp$1 = class TabGuardComp extends Component {
  initialiseTabGuard(params) {
    this.tabGuardFeature = this.createManagedBean(new TabGuardFeature(this));
    this.tabGuardFeature.initialiseTabGuard(params);
  }
  forceFocusOutOfContainer(up = false) {
    this.tabGuardFeature.forceFocusOutOfContainer(up);
  }
  appendChild(newChild, container2) {
    this.tabGuardFeature.appendChild(super.appendChild.bind(this), newChild, container2);
  }
};
var DOUBLE_TAP_MILLISECONDS = 500;
var LONG_PRESS_MILLISECONDS = 550;
var handledTouchEvents;
var addHandledTouchEvent = (event) => {
  if (!handledTouchEvents) {
    handledTouchEvents = /* @__PURE__ */ new WeakSet();
  } else if (handledTouchEvents.has(event)) {
    return false;
  }
  handledTouchEvents.add(event);
  return true;
};
var TouchListener = class {
  constructor(eElement, preventClick = false) {
    this.eElement = eElement;
    this.preventClick = preventClick;
    this.startListener = null;
    this.handlers = [];
    this.eventSvc = void 0;
    this.touchStart = null;
    this.lastTapTime = null;
    this.longPressTimer = 0;
    this.moved = false;
  }
  addEventListener(eventType, listener) {
    let eventSvc = this.eventSvc;
    if (!eventSvc) {
      if (eventSvc === null) {
        return;
      }
      this.eventSvc = eventSvc = new LocalEventService();
      const startListener = this.onTouchStart.bind(this);
      this.startListener = startListener;
      this.eElement.addEventListener("touchstart", startListener, { passive: true });
    }
    eventSvc.addEventListener(eventType, listener);
  }
  removeEventListener(eventType, listener) {
    this.eventSvc?.removeEventListener(eventType, listener);
  }
  onTouchStart(touchEvent) {
    if (this.touchStart || !addHandledTouchEvent(touchEvent)) {
      return;
    }
    const touchStart = touchEvent.touches[0];
    this.touchStart = touchStart;
    const handlers = this.handlers;
    if (!handlers.length) {
      const eElement = this.eElement;
      const doc = eElement.ownerDocument;
      const touchMove = this.onTouchMove.bind(this);
      const touchEnd = this.onTouchEnd.bind(this);
      const touchCancel = this.onTouchCancel.bind(this);
      const passiveTrue = { passive: true };
      const passiveFalse = { passive: false };
      addTempEventHandlers(
        handlers,
        [eElement, "touchmove", touchMove, passiveTrue],
        [doc, "touchcancel", touchCancel, passiveTrue],
        // we set passive=false, as we want to prevent default on this event
        [doc, "touchend", touchEnd, passiveFalse],
        [doc, "contextmenu", preventEventDefault, passiveFalse]
      );
    }
    this.clearLongPress();
    this.longPressTimer = window.setTimeout(() => {
      this.longPressTimer = 0;
      if (this.touchStart === touchStart && !this.moved) {
        this.moved = true;
        this.eventSvc?.dispatchEvent({ type: "longTap", touchStart, touchEvent });
      }
    }, LONG_PRESS_MILLISECONDS);
  }
  onTouchMove(touchEvent) {
    const { moved, touchStart } = this;
    if (!moved && touchStart) {
      const touch = _getFirstActiveTouch(touchStart, touchEvent.touches);
      const eventIsFarAway = touch && !_areEventsNear(touch, touchStart, 4);
      if (eventIsFarAway) {
        this.clearLongPress();
        this.moved = true;
      }
    }
  }
  onTouchEnd(touchEvent) {
    const touchStart = this.touchStart;
    if (!touchStart || !_getFirstActiveTouch(touchStart, touchEvent.changedTouches)) {
      return;
    }
    if (!this.moved) {
      this.eventSvc?.dispatchEvent({ type: "tap", touchStart });
      this.checkDoubleTap(touchStart);
    }
    if (this.preventClick) {
      preventEventDefault(touchEvent);
    }
    this.cancel();
  }
  onTouchCancel(touchEvent) {
    const touchStart = this.touchStart;
    if (!touchStart || !_getFirstActiveTouch(touchStart, touchEvent.changedTouches)) {
      return;
    }
    this.lastTapTime = null;
    this.cancel();
  }
  checkDoubleTap(touchStart) {
    let now2 = Date.now();
    const lastTapTime = this.lastTapTime;
    if (lastTapTime) {
      const interval2 = now2 - lastTapTime;
      if (interval2 > DOUBLE_TAP_MILLISECONDS) {
        this.eventSvc?.dispatchEvent({ type: "doubleTap", touchStart });
        now2 = null;
      }
    }
    this.lastTapTime = now2;
  }
  cancel() {
    this.clearLongPress();
    clearTempEventHandlers(this.handlers);
    this.touchStart = null;
  }
  clearLongPress() {
    window.clearTimeout(this.longPressTimer);
    this.longPressTimer = 0;
    this.moved = false;
  }
  destroy() {
    const startListener = this.startListener;
    if (startListener) {
      this.startListener = null;
      this.eElement.removeEventListener("touchstart", startListener);
    }
    this.cancel();
    this.eElement = null;
    this.eventSvc = null;
  }
};
var AutoScrollService = class {
  constructor(params) {
    this.tickingInterval = null;
    this.onScrollCallback = null;
    this.scrollContainer = params.scrollContainer;
    this.scrollHorizontally = params.scrollAxis.includes("x");
    this.scrollVertically = params.scrollAxis.includes("y");
    this.scrollByTick = params.scrollByTick != null ? params.scrollByTick : 20;
    if (params.onScrollCallback) {
      this.onScrollCallback = params.onScrollCallback;
    }
    if (this.scrollVertically) {
      this.getVerticalPosition = params.getVerticalPosition;
      this.setVerticalPosition = params.setVerticalPosition;
    }
    if (this.scrollHorizontally) {
      this.getHorizontalPosition = params.getHorizontalPosition;
      this.setHorizontalPosition = params.setHorizontalPosition;
    }
    this.shouldSkipVerticalScroll = params.shouldSkipVerticalScroll || (() => false);
    this.shouldSkipHorizontalScroll = params.shouldSkipHorizontalScroll || (() => false);
  }
  /** True while auto-scrolling */
  get scrolling() {
    return this.tickingInterval !== null;
  }
  check(mouseEvent, forceSkipVerticalScroll = false) {
    const skipVerticalScroll = forceSkipVerticalScroll || this.shouldSkipVerticalScroll();
    if (skipVerticalScroll && this.shouldSkipHorizontalScroll()) {
      return;
    }
    const rect = this.scrollContainer.getBoundingClientRect();
    const scrollTick = this.scrollByTick;
    this.tickLeft = mouseEvent.clientX < rect.left + scrollTick;
    this.tickRight = mouseEvent.clientX > rect.right - scrollTick;
    this.tickUp = mouseEvent.clientY < rect.top + scrollTick && !skipVerticalScroll;
    this.tickDown = mouseEvent.clientY > rect.bottom - scrollTick && !skipVerticalScroll;
    if (this.tickLeft || this.tickRight || this.tickUp || this.tickDown) {
      this.ensureTickingStarted();
    } else {
      this.ensureCleared();
    }
  }
  ensureTickingStarted() {
    if (this.tickingInterval === null) {
      this.tickingInterval = window.setInterval(this.doTick.bind(this), 100);
      this.tickCount = 0;
    }
  }
  doTick() {
    this.tickCount++;
    const tickAmount = this.tickCount > 20 ? 200 : this.tickCount > 10 ? 80 : 40;
    if (this.scrollVertically) {
      const vScrollPosition = this.getVerticalPosition();
      if (this.tickUp) {
        this.setVerticalPosition(vScrollPosition - tickAmount);
      }
      if (this.tickDown) {
        this.setVerticalPosition(vScrollPosition + tickAmount);
      }
    }
    if (this.scrollHorizontally) {
      const hScrollPosition = this.getHorizontalPosition();
      if (this.tickLeft) {
        this.setHorizontalPosition(hScrollPosition - tickAmount);
      }
      if (this.tickRight) {
        this.setHorizontalPosition(hScrollPosition + tickAmount);
      }
    }
    if (this.onScrollCallback) {
      this.onScrollCallback();
    }
  }
  ensureCleared() {
    if (this.tickingInterval) {
      window.clearInterval(this.tickingInterval);
      this.tickingInterval = null;
    }
  }
};
var VanillaFrameworkOverrides = class {
  constructor(frameworkName = "javascript") {
    this.frameworkName = frameworkName;
    this.renderingEngine = "vanilla";
    this.batchFrameworkComps = false;
    this.wrapIncoming = (callback) => callback();
    this.wrapOutgoing = (callback) => callback();
    this.baseDocLink = `${BASE_URL}/${this.frameworkName}-data-grid`;
    setValidationDocLink(this.baseDocLink);
  }
  frameworkComponent(_) {
    return null;
  }
  isFrameworkComponent(_) {
    return false;
  }
  getDocLink(path) {
    return this.baseDocLink + (path ? "/" + path : "");
  }
};
function createGridApi(context) {
  return {
    beanName: "gridApi",
    bean: context.getBean("apiFunctionSvc").api
  };
}
var orderedCoreBeans = [
  // Validate license first
  "licenseManager",
  // core beans only
  "environment",
  "eventSvc",
  "gos",
  "paginationAutoPageSizeSvc",
  "apiFunctionSvc",
  "gridApi",
  "registry",
  "agCompUtils",
  "userCompFactory",
  "rowContainerHeight",
  "horizontalResizeSvc",
  "localeSvc",
  "pinnedRowModel",
  "dragSvc",
  "colGroupSvc",
  "visibleCols",
  "popupSvc",
  "selectionSvc",
  "colFilter",
  "quickFilter",
  "filterManager",
  "colModel",
  "headerNavigation",
  "pageBounds",
  "pagination",
  "pageBoundsListener",
  "rowSpanSvc",
  "stickyRowSvc",
  "rowRenderer",
  "expressionSvc",
  "alignedGridsSvc",
  "navigation",
  "valueCache",
  "valueSvc",
  "autoWidthCalc",
  "filterMenuFactory",
  "dragAndDrop",
  "focusSvc",
  "cellNavigation",
  "cellStyles",
  "scrollVisibleSvc",
  "sortSvc",
  "colHover",
  "colAnimation",
  "autoColSvc",
  "selectionColSvc",
  "changeDetectionSvc",
  "animationFrameSvc",
  "undoRedo",
  "colDefFactory",
  "rowStyleSvc",
  "rowNodeBlockLoader",
  "rowNodeSorter",
  "ctrlsSvc",
  "pinnedCols",
  "dataTypeSvc",
  "syncSvc",
  "overlays",
  "stateSvc",
  "expansionSvc",
  "apiEventSvc",
  "ariaAnnounce",
  "menuSvc",
  "colMoves",
  "colAutosize",
  "colFlex",
  "colResize",
  "pivotColsSvc",
  "valueColsSvc",
  "rowGroupColsSvc",
  "colNames",
  "colViewport",
  "pivotResultCols",
  "showRowGroupCols",
  "validation"
  // Have validations run last
];
var beanNamePosition = Object.fromEntries(
  orderedCoreBeans.map((beanName, index) => [beanName, index])
);
function gridBeanInitComparator(bean1, bean2) {
  const index1 = (bean1.beanName ? beanNamePosition[bean1.beanName] : void 0) ?? Number.MAX_SAFE_INTEGER;
  const index2 = (bean2.beanName ? beanNamePosition[bean2.beanName] : void 0) ?? Number.MAX_SAFE_INTEGER;
  return index1 - index2;
}
function gridBeanDestroyComparator(bean1, bean2) {
  if (bean1?.beanName === "gridDestroySvc") {
    return -1;
  }
  if (bean2?.beanName === "gridDestroySvc") {
    return 1;
  }
  return 0;
}
var GridCtrl = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.additionalFocusableContainers = /* @__PURE__ */ new Set();
  }
  setComp(view, eGridDiv, eGui) {
    this.view = view;
    this.eGridHostDiv = eGridDiv;
    this.eGui = eGui;
    this.eGui.setAttribute("grid-id", this.beans.context.getId());
    const { dragAndDrop, ctrlsSvc } = this.beans;
    dragAndDrop?.registerGridDropTarget(() => this.eGui, this);
    this.createManagedBean(new LayoutFeature(this.view));
    this.view.setRtlClass(this.gos.get("enableRtl") ? "ag-rtl" : "ag-ltr");
    const unsubscribeFromResize = _observeResize(this.beans, this.eGridHostDiv, this.onGridSizeChanged.bind(this));
    this.addDestroyFunc(() => unsubscribeFromResize());
    ctrlsSvc.register("gridCtrl", this);
  }
  isDetailGrid() {
    const el = _findTabbableParent(this.getGui());
    return el?.getAttribute("row-id")?.startsWith("detail") || false;
  }
  getOptionalSelectors() {
    const beans = this.beans;
    return {
      paginationSelector: beans.pagination?.getPaginationSelector(),
      gridHeaderDropZonesSelector: beans.registry?.getSelector("AG-GRID-HEADER-DROP-ZONES"),
      sideBarSelector: beans.sideBar?.getSelector(),
      statusBarSelector: beans.registry?.getSelector("AG-STATUS-BAR"),
      watermarkSelector: beans.licenseManager?.getWatermarkSelector()
    };
  }
  onGridSizeChanged() {
    this.eventSvc.dispatchEvent({
      type: "gridSizeChanged",
      clientWidth: this.eGridHostDiv.clientWidth,
      clientHeight: this.eGridHostDiv.clientHeight
    });
  }
  destroyGridUi() {
    this.view.destroyGridUi();
  }
  getGui() {
    return this.eGui;
  }
  setResizeCursor(direction) {
    const { view } = this;
    if (direction === false) {
      view.setCursor(null);
    } else {
      const cursor = direction === 1 ? "ew-resize" : "ns-resize";
      view.setCursor(cursor);
    }
  }
  disableUserSelect(on) {
    this.view.setUserSelect(on ? "none" : null);
  }
  focusNextInnerContainer(backwards) {
    const focusableContainers = this.getFocusableContainers();
    const { indexWithFocus, nextIndex: nextIndex2 } = this.getNextFocusableIndex(focusableContainers, backwards);
    if (nextIndex2 < 0 || nextIndex2 >= focusableContainers.length) {
      return false;
    }
    if (nextIndex2 === 0) {
      if (indexWithFocus > 0) {
        const { visibleCols, focusSvc } = this.beans;
        const allColumns = visibleCols.allCols;
        const lastColumn = _last(allColumns);
        if (focusSvc.focusGridView({ column: lastColumn, backwards: true })) {
          return true;
        }
      }
      return false;
    }
    return this.focusContainer(focusableContainers[nextIndex2], backwards);
  }
  focusInnerElement(fromBottom) {
    const userCallbackFunction = this.gos.getCallback("focusGridInnerElement");
    if (userCallbackFunction?.({ fromBottom: !!fromBottom })) {
      return true;
    }
    const focusableContainers = this.getFocusableContainers();
    const { focusSvc, visibleCols } = this.beans;
    const allColumns = visibleCols.allCols;
    if (fromBottom) {
      if (focusableContainers.length > 1) {
        return this.focusContainer(_last(focusableContainers), fromBottom);
      }
      const lastColumn = _last(allColumns);
      if (focusSvc.focusGridView({ column: lastColumn, backwards: fromBottom })) {
        return true;
      }
    }
    if (this.gos.get("headerHeight") === 0 || _isHeaderFocusSuppressed(this.beans)) {
      if (focusSvc.focusGridView({ column: allColumns[0], backwards: fromBottom })) {
        return true;
      }
      for (let i2 = 1; i2 < focusableContainers.length; i2++) {
        if (_focusInto(focusableContainers[i2].getGui(), fromBottom)) {
          return true;
        }
      }
      return false;
    }
    return focusSvc.focusFirstHeader();
  }
  forceFocusOutOfContainer(up = false) {
    this.view.forceFocusOutOfContainer(up);
  }
  addFocusableContainer(container2) {
    this.additionalFocusableContainers.add(container2);
  }
  removeFocusableContainer(container2) {
    this.additionalFocusableContainers.delete(container2);
  }
  allowFocusForNextCoreContainer(up) {
    const coreContainers = this.view.getFocusableContainers();
    const { nextIndex: nextIndex2, indexWithFocus } = this.getNextFocusableIndex(coreContainers, up);
    if (indexWithFocus === -1 || nextIndex2 < 0 || nextIndex2 >= coreContainers.length) {
      return;
    }
    const comp = coreContainers[nextIndex2];
    comp.setAllowFocus?.(true);
    setTimeout(() => {
      comp.setAllowFocus?.(false);
    });
  }
  isFocusable() {
    const beans = this.beans;
    return !_isCellFocusSuppressed(beans) || !_isHeaderFocusSuppressed(beans) || !!beans.sideBar?.comp?.isDisplayed();
  }
  getNextFocusableIndex(focusableContainers, backwards) {
    const activeEl = _getActiveDomElement(this.beans);
    const indexWithFocus = focusableContainers.findIndex((container2) => container2.getGui().contains(activeEl));
    const nextIndex2 = indexWithFocus + (backwards ? -1 : 1);
    return {
      indexWithFocus,
      nextIndex: nextIndex2
    };
  }
  focusContainer(comp, up) {
    comp.setAllowFocus?.(true);
    const result2 = _focusInto(comp.getGui(), up, false, true);
    comp.setAllowFocus?.(false);
    return result2;
  }
  getFocusableContainers() {
    return [...this.view.getFocusableContainers(), ...this.additionalFocusableContainers];
  }
  destroy() {
    this.additionalFocusableContainers.clear();
    super.destroy();
  }
};
var mod = (moduleName, input2) => {
  for (const key2 of Object.keys(input2)) {
    input2[key2] = moduleName;
  }
  return input2;
};
var gridApiFunctionsMap = {
  dispatchEvent: "CommunityCore",
  // this is always registered
  ...mod("CommunityCore", {
    destroy: 0,
    getGridId: 0,
    getGridOption: 0,
    isDestroyed: 0,
    setGridOption: 0,
    updateGridOptions: 0,
    isModuleRegistered: 0
  }),
  ...mod("GridState", {
    getState: 0,
    setState: 0
  }),
  ...mod("SharedRowSelection", {
    setNodesSelected: 0,
    selectAll: 0,
    deselectAll: 0,
    selectAllFiltered: 0,
    deselectAllFiltered: 0,
    selectAllOnCurrentPage: 0,
    deselectAllOnCurrentPage: 0,
    getSelectedNodes: 0,
    getSelectedRows: 0
  }),
  ...mod("RowApi", {
    redrawRows: 0,
    setRowNodeExpanded: 0,
    getRowNode: 0,
    addRenderedRowListener: 0,
    getRenderedNodes: 0,
    forEachNode: 0,
    getFirstDisplayedRowIndex: 0,
    getLastDisplayedRowIndex: 0,
    getDisplayedRowAtIndex: 0,
    getDisplayedRowCount: 0
  }),
  ...mod("ScrollApi", {
    getVerticalPixelRange: 0,
    getHorizontalPixelRange: 0,
    ensureColumnVisible: 0,
    ensureIndexVisible: 0,
    ensureNodeVisible: 0
  }),
  ...mod("KeyboardNavigation", {
    getFocusedCell: 0,
    clearFocusedCell: 0,
    setFocusedCell: 0,
    tabToNextCell: 0,
    tabToPreviousCell: 0,
    setFocusedHeader: 0
  }),
  ...mod("EventApi", {
    addEventListener: 0,
    addGlobalListener: 0,
    removeEventListener: 0,
    removeGlobalListener: 0
  }),
  ...mod("ValueCache", {
    expireValueCache: 0
  }),
  ...mod("CellApi", {
    getCellValue: 0
  }),
  ...mod("SharedMenu", {
    showColumnMenu: 0,
    hidePopupMenu: 0
  }),
  ...mod("Sort", {
    onSortChanged: 0
  }),
  ...mod("PinnedRow", {
    getPinnedTopRowCount: 0,
    getPinnedBottomRowCount: 0,
    getPinnedTopRow: 0,
    getPinnedBottomRow: 0,
    forEachPinnedRow: 0
  }),
  ...mod("Overlay", {
    showLoadingOverlay: 0,
    showNoRowsOverlay: 0,
    hideOverlay: 0
  }),
  ...mod("RenderApi", {
    setGridAriaProperty: 0,
    refreshCells: 0,
    refreshHeader: 0,
    isAnimationFrameQueueEmpty: 0,
    flushAllAnimationFrames: 0,
    getSizesForCurrentTheme: 0,
    getCellRendererInstances: 0
  }),
  ...mod("HighlightChanges", {
    flashCells: 0
  }),
  ...mod("RowDrag", {
    addRowDropZone: 0,
    removeRowDropZone: 0,
    getRowDropZoneParams: 0,
    getRowDropPositionIndicator: 0,
    setRowDropPositionIndicator: 0
  }),
  ...mod("ColumnApi", {
    getColumnDefs: 0,
    getColumnDef: 0,
    getDisplayNameForColumn: 0,
    getColumn: 0,
    getColumns: 0,
    applyColumnState: 0,
    getColumnState: 0,
    resetColumnState: 0,
    isPinning: 0,
    isPinningLeft: 0,
    isPinningRight: 0,
    getDisplayedColAfter: 0,
    getDisplayedColBefore: 0,
    setColumnsVisible: 0,
    setColumnsPinned: 0,
    getAllGridColumns: 0,
    getDisplayedLeftColumns: 0,
    getDisplayedCenterColumns: 0,
    getDisplayedRightColumns: 0,
    getAllDisplayedColumns: 0,
    getAllDisplayedVirtualColumns: 0
  }),
  ...mod("ColumnAutoSize", {
    sizeColumnsToFit: 0,
    autoSizeColumns: 0,
    autoSizeAllColumns: 0
  }),
  ...mod("ColumnGroup", {
    setColumnGroupOpened: 0,
    getColumnGroup: 0,
    getProvidedColumnGroup: 0,
    getDisplayNameForColumnGroup: 0,
    getColumnGroupState: 0,
    setColumnGroupState: 0,
    resetColumnGroupState: 0,
    getLeftDisplayedColumnGroups: 0,
    getCenterDisplayedColumnGroups: 0,
    getRightDisplayedColumnGroups: 0,
    getAllDisplayedColumnGroups: 0
  }),
  ...mod("ColumnMove", {
    moveColumnByIndex: 0,
    moveColumns: 0
  }),
  ...mod("ColumnResize", {
    setColumnWidths: 0
  }),
  ...mod("ColumnHover", {
    isColumnHovered: 0
  }),
  ...mod("EditCore", {
    getCellEditorInstances: 0,
    getEditingCells: 0,
    getEditRowValues: 0,
    stopEditing: 0,
    startEditingCell: 0,
    isEditing: 0,
    validateEdit: 0
  }),
  ...mod("BatchEdit", {
    startBatchEdit: 0,
    cancelBatchEdit: 0,
    commitBatchEdit: 0,
    isBatchEditing: 0
  }),
  ...mod("UndoRedoEdit", {
    undoCellEditing: 0,
    redoCellEditing: 0,
    getCurrentUndoSize: 0,
    getCurrentRedoSize: 0
  }),
  ...mod("FilterCore", {
    isAnyFilterPresent: 0,
    onFilterChanged: 0
  }),
  ...mod("ColumnFilter", {
    isColumnFilterPresent: 0,
    getColumnFilterInstance: 0,
    destroyFilter: 0,
    setFilterModel: 0,
    getFilterModel: 0,
    getColumnFilterModel: 0,
    setColumnFilterModel: 0,
    showColumnFilter: 0,
    hideColumnFilter: 0,
    getColumnFilterHandler: 0,
    doFilterAction: 0
  }),
  ...mod("QuickFilter", {
    isQuickFilterPresent: 0,
    getQuickFilter: 0,
    resetQuickFilter: 0
  }),
  ...mod("Find", {
    findGetActiveMatch: 0,
    findGetTotalMatches: 0,
    findGoTo: 0,
    findNext: 0,
    findPrevious: 0,
    findGetNumMatches: 0,
    findGetParts: 0,
    findClearActive: 0,
    findRefresh: 0
  }),
  ...mod("Pagination", {
    paginationIsLastPageFound: 0,
    paginationGetPageSize: 0,
    paginationGetCurrentPage: 0,
    paginationGetTotalPages: 0,
    paginationGetRowCount: 0,
    paginationGoToNextPage: 0,
    paginationGoToPreviousPage: 0,
    paginationGoToFirstPage: 0,
    paginationGoToLastPage: 0,
    paginationGoToPage: 0
  }),
  ...mod("CsrmSsrmSharedApi", {
    expandAll: 0,
    collapseAll: 0
  }),
  ...mod("SsrmInfiniteSharedApi", {
    setRowCount: 0,
    getCacheBlockState: 0,
    isLastRowIndexKnown: 0
  }),
  ...mod("ClientSideRowModelApi", {
    onGroupExpandedOrCollapsed: 0,
    refreshClientSideRowModel: 0,
    isRowDataEmpty: 0,
    forEachLeafNode: 0,
    forEachNodeAfterFilter: 0,
    forEachNodeAfterFilterAndSort: 0,
    applyTransaction: 0,
    applyTransactionAsync: 0,
    flushAsyncTransactions: 0,
    getBestCostNodeSelection: 0,
    onRowHeightChanged: 0,
    resetRowHeights: 0
  }),
  ...mod("CsvExport", {
    getDataAsCsv: 0,
    exportDataAsCsv: 0
  }),
  ...mod("InfiniteRowModel", {
    refreshInfiniteCache: 0,
    purgeInfiniteCache: 0,
    getInfiniteRowCount: 0
  }),
  ...mod("AdvancedFilter", {
    getAdvancedFilterModel: 0,
    setAdvancedFilterModel: 0,
    showAdvancedFilterBuilder: 0,
    hideAdvancedFilterBuilder: 0
  }),
  ...mod("IntegratedCharts", {
    getChartModels: 0,
    getChartRef: 0,
    getChartImageDataURL: 0,
    downloadChart: 0,
    openChartToolPanel: 0,
    closeChartToolPanel: 0,
    createRangeChart: 0,
    createPivotChart: 0,
    createCrossFilterChart: 0,
    updateChart: 0,
    restoreChart: 0
  }),
  ...mod("Clipboard", {
    copyToClipboard: 0,
    cutToClipboard: 0,
    copySelectedRowsToClipboard: 0,
    copySelectedRangeToClipboard: 0,
    copySelectedRangeDown: 0,
    pasteFromClipboard: 0
  }),
  ...mod("ExcelExport", {
    getDataAsExcel: 0,
    exportDataAsExcel: 0,
    getSheetDataForExcel: 0,
    getMultipleSheetsAsExcel: 0,
    exportMultipleSheetsAsExcel: 0
  }),
  ...mod("SharedMasterDetail", {
    addDetailGridInfo: 0,
    removeDetailGridInfo: 0,
    getDetailGridInfo: 0,
    forEachDetailGridInfo: 0
  }),
  ...mod("ContextMenu", {
    showContextMenu: 0
  }),
  ...mod("ColumnMenu", {
    showColumnChooser: 0,
    hideColumnChooser: 0
  }),
  ...mod("CellSelection", {
    getCellRanges: 0,
    addCellRange: 0,
    clearRangeSelection: 0,
    clearCellSelection: 0
  }),
  ...mod("SharedRowGrouping", {
    setRowGroupColumns: 0,
    removeRowGroupColumns: 0,
    addRowGroupColumns: 0,
    getRowGroupColumns: 0,
    moveRowGroupColumn: 0
  }),
  ...mod("SharedAggregation", {
    addAggFuncs: 0,
    clearAggFuncs: 0,
    setColumnAggFunc: 0
  }),
  ...mod("SharedPivot", {
    isPivotMode: 0,
    getPivotResultColumn: 0,
    setValueColumns: 0,
    getValueColumns: 0,
    removeValueColumns: 0,
    addValueColumns: 0,
    setPivotColumns: 0,
    removePivotColumns: 0,
    addPivotColumns: 0,
    getPivotColumns: 0,
    setPivotResultColumns: 0,
    getPivotResultColumns: 0
  }),
  ...mod("ServerSideRowModelApi", {
    getServerSideSelectionState: 0,
    setServerSideSelectionState: 0,
    applyServerSideTransaction: 0,
    applyServerSideTransactionAsync: 0,
    applyServerSideRowData: 0,
    retryServerSideLoads: 0,
    flushServerSideAsyncTransactions: 0,
    refreshServerSide: 0,
    getServerSideGroupLevelState: 0,
    onRowHeightChanged: 0,
    resetRowHeights: 0
  }),
  ...mod("SideBar", {
    isSideBarVisible: 0,
    setSideBarVisible: 0,
    setSideBarPosition: 0,
    openToolPanel: 0,
    closeToolPanel: 0,
    getOpenedToolPanel: 0,
    refreshToolPanel: 0,
    isToolPanelShowing: 0,
    getToolPanelInstance: 0,
    getSideBar: 0
  }),
  ...mod("StatusBar", {
    getStatusPanel: 0
  }),
  ...mod("AiToolkit", {
    getStructuredSchema: 0
  })
};
var defaultFns = {
  isDestroyed: () => true,
  destroy() {
  },
  preConstruct() {
  },
  postConstruct() {
  },
  preWireBeans() {
  },
  wireBeans() {
  }
};
var dispatchEvent = (beans, event) => beans.eventSvc.dispatchEvent(event);
var GridApiClass = class {
};
Reflect.defineProperty(GridApiClass, "name", { value: "GridApi" });
var ApiFunctionService = class extends BeanStub {
  constructor() {
    super();
    this.beanName = "apiFunctionSvc";
    this.api = new GridApiClass();
    this.fns = {
      ...defaultFns,
      // dispatchEvent is used by frameworks, also used by aligned grids to identify a grid api instance
      dispatchEvent
    };
    this.preDestroyLink = "";
    const { api: api2 } = this;
    for (const key2 of Object.keys(gridApiFunctionsMap)) {
      api2[key2] = this.makeApi(key2)[key2];
    }
  }
  postConstruct() {
    this.preDestroyLink = this.beans.frameworkOverrides.getDocLink("grid-lifecycle/#grid-pre-destroyed");
  }
  addFunction(functionName2, func2) {
    const { fns, beans } = this;
    if (fns !== defaultFns) {
      fns[functionName2] = beans?.validation?.validateApiFunction(functionName2, func2) ?? func2;
    }
  }
  makeApi(apiName) {
    return {
      [apiName]: (...args2) => {
        const {
          beans,
          fns: { [apiName]: fn3 }
        } = this;
        return fn3 ? fn3(beans, ...args2) : this.apiNotFound(apiName);
      }
    };
  }
  apiNotFound(fnName) {
    const { beans, gos, preDestroyLink } = this;
    if (!beans) {
      _warn(26, { fnName, preDestroyLink });
    } else {
      const module = gridApiFunctionsMap[fnName];
      if (gos.assertModuleRegistered(module, `api.${fnName}`)) {
        _warn(27, { fnName, module });
      }
    }
  }
  destroy() {
    super.destroy();
    this.fns = defaultFns;
    this.beans = null;
  }
};
function getGridId(beans) {
  return beans.context.getId();
}
function destroy(beans) {
  beans.gridDestroySvc.destroy();
}
function isDestroyed(beans) {
  return beans.gridDestroySvc.destroyCalled;
}
function getGridOption(beans, key2) {
  return beans.gos.get(key2);
}
function setGridOption(beans, key2, value2) {
  updateGridOptions(beans, { [key2]: value2 });
}
function updateGridOptions(beans, options) {
  beans.gos.updateGridOptions({ options });
}
function isModuleRegistered(beans, moduleName) {
  const withoutSuffix = moduleName.replace(/Module$/, "");
  return beans.gos.isModuleRegistered(withoutSuffix);
}
var DndSourceElement = { tag: "div", cls: "ag-drag-handle ag-row-drag", attrs: { draggable: "true" } };
var DndSourceComp = class extends Component {
  constructor(rowNode, column2, eCell) {
    super(DndSourceElement);
    this.rowNode = rowNode;
    this.column = column2;
    this.eCell = eCell;
  }
  postConstruct() {
    const eGui = this.getGui();
    eGui.appendChild(_createIconNoSpan("rowDrag", this.beans, null));
    this.addGuiEventListener("mousedown", (e) => {
      e.stopPropagation();
    });
    this.addDragSource();
    this.checkVisibility();
  }
  addDragSource() {
    this.addGuiEventListener("dragstart", this.onDragStart.bind(this));
  }
  onDragStart(dragEvent) {
    const { rowNode, column: column2, eCell, gos } = this;
    const providedOnRowDrag = column2.getColDef().dndSourceOnRowDrag;
    const dataTransfer = dragEvent.dataTransfer;
    dataTransfer.setDragImage(eCell, 0, 0);
    if (providedOnRowDrag) {
      const params = _addGridCommonParams(gos, {
        rowNode,
        dragEvent
      });
      providedOnRowDrag(params);
    } else {
      try {
        const jsonData = JSON.stringify(rowNode.data);
        dataTransfer.setData("application/json", jsonData);
        dataTransfer.setData("text/plain", jsonData);
      } catch (e) {
      }
    }
  }
  checkVisibility() {
    const visible2 = this.column.isDndSource(this.rowNode);
    this.setDisplayed(visible2);
  }
};
function addRowDropZone(beans, params) {
  beans.rowDragSvc?.rowDragFeature?.addRowDropZone(params);
}
function removeRowDropZone(beans, params) {
  const activeDropTarget = beans.dragAndDrop?.findExternalZone(params.getContainer());
  if (activeDropTarget) {
    beans.dragAndDrop?.removeDropTarget(activeDropTarget);
  }
}
function getRowDropZoneParams(beans, events) {
  return beans.rowDragSvc?.rowDragFeature?.getRowDropZone(events);
}
function getRowDropPositionIndicator(beans) {
  const rowDropHighlightSvc = beans.rowDropHighlightSvc;
  return rowDropHighlightSvc ? { row: rowDropHighlightSvc.row, dropIndicatorPosition: rowDropHighlightSvc.position } : { row: null, dropIndicatorPosition: "none" };
}
function setRowDropPositionIndicator(beans, params) {
  const rowDropHighlightSvc = beans.rowDropHighlightSvc;
  if (!rowDropHighlightSvc) {
    return;
  }
  const rowNode = params?.row;
  let position = params?.dropIndicatorPosition;
  if (position !== "above" && position !== "below" && position !== "inside") {
    position = "none";
  }
  const rowIndex = rowNode?.rowIndex;
  if (rowIndex === null || rowIndex === void 0 || position === "none") {
    rowDropHighlightSvc.clear();
  } else {
    rowDropHighlightSvc.set(rowNode, position);
  }
}
var DragService = class extends BaseDragService {
  shouldPreventMouseEvent(mouseEvent) {
    const isEnableCellTextSelect = this.gos.get("enableCellTextSelection");
    return isEnableCellTextSelect && super.shouldPreventMouseEvent(mouseEvent);
  }
};
var HorizontalResizeService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "horizontalResizeSvc";
  }
  addResizeBar(params) {
    const dragSource = {
      dragStartPixels: params.dragStartPixels || 0,
      eElement: params.eResizeBar,
      onDragStart: this.onDragStart.bind(this, params),
      onDragStop: this.onDragStop.bind(this, params),
      onDragging: this.onDragging.bind(this, params),
      onDragCancel: this.onDragStop.bind(this, params),
      includeTouch: true,
      stopPropagationForTouch: true
    };
    const { dragSvc } = this.beans;
    dragSvc.addDragSource(dragSource);
    const finishedWithResizeFunc = () => dragSvc.removeDragSource(dragSource);
    return finishedWithResizeFunc;
  }
  onDragStart(params, mouseEvent) {
    this.dragStartX = mouseEvent.clientX;
    this.setResizeIcons();
    const shiftKey = mouseEvent instanceof MouseEvent && mouseEvent.shiftKey === true;
    params.onResizeStart(shiftKey);
  }
  setResizeIcons() {
    const ctrl = this.beans.ctrlsSvc.get("gridCtrl");
    ctrl.setResizeCursor(
      1
      /* Horizontal */
    );
    ctrl.disableUserSelect(true);
  }
  onDragStop(params) {
    params.onResizeEnd(this.resizeAmount);
    this.resetIcons();
  }
  resetIcons() {
    const ctrl = this.beans.ctrlsSvc.get("gridCtrl");
    ctrl.setResizeCursor(false);
    ctrl.disableUserSelect(false);
  }
  onDragging(params, mouseEvent) {
    this.resizeAmount = mouseEvent.clientX - this.dragStartX;
    params.onResizing(this.resizeAmount);
  }
};
var RowDragElement = {
  tag: "div",
  cls: "ag-drag-handle ag-row-drag",
  attrs: { "aria-hidden": "true" }
};
var RowDragComp = class extends Component {
  constructor(cellValueFn, rowNode, column2, customGui, dragStartPixels, alwaysVisible = false) {
    super();
    this.cellValueFn = cellValueFn;
    this.rowNode = rowNode;
    this.column = column2;
    this.customGui = customGui;
    this.dragStartPixels = dragStartPixels;
    this.alwaysVisible = alwaysVisible;
    this.dragSource = null;
  }
  isCustomGui() {
    return this.customGui != null;
  }
  postConstruct() {
    const { beans, customGui } = this;
    if (customGui) {
      this.setDragElement(customGui, this.dragStartPixels);
    } else {
      this.setTemplate(RowDragElement);
      this.getGui().appendChild(_createIconNoSpan("rowDrag", beans, null));
      this.addDragSource();
    }
    if (!this.alwaysVisible) {
      this.initCellDrag();
    }
  }
  initCellDrag() {
    const { beans, gos, rowNode } = this;
    const refreshVisibility = this.refreshVisibility.bind(this);
    this.addManagedPropertyListener("suppressRowDrag", refreshVisibility);
    this.addManagedListeners(rowNode, {
      dataChanged: refreshVisibility,
      cellChanged: refreshVisibility
    });
    this.addManagedListeners(
      beans.eventSvc,
      // For managed row drag, we do not show the component if sort, filter or grouping is active
      gos.get("rowDragManaged") ? {
        sortChanged: refreshVisibility,
        filterChanged: refreshVisibility,
        columnRowGroupChanged: refreshVisibility,
        newColumnsLoaded: refreshVisibility
      } : { newColumnsLoaded: refreshVisibility }
    );
  }
  setDragElement(dragElement, dragStartPixels) {
    this.setTemplateFromElement(dragElement, void 0, void 0, true);
    this.addDragSource(dragStartPixels);
  }
  refreshVisibility() {
    if (this.alwaysVisible) {
      return;
    }
    const displayedOptions = { skipAriaHidden: true };
    if (this.isNeverDisplayed()) {
      this.setDisplayed(false, displayedOptions);
      return;
    }
    const column2 = this.column;
    let shownSometimes = typeof column2?.getColDef().rowDrag === "function";
    let visible2 = !column2 || this.isCustomGui() || column2.isRowDrag(this.rowNode);
    if (visible2 && this.rowNode.footer && this.gos.get("rowDragManaged")) {
      visible2 = false;
      shownSometimes = true;
    }
    this.setDisplayed(shownSometimes || visible2, displayedOptions);
    this.setVisible(visible2, displayedOptions);
  }
  isNeverDisplayed() {
    const { gos, beans } = this;
    if (gos.get("suppressRowDrag")) {
      return true;
    }
    if (gos.get("rowDragManaged") && !!beans.rowDragSvc.rowDragFeature?.shouldPreventRowMove() && !beans.dragAndDrop?.hasExternalDropZones()) {
      return true;
    }
    return false;
  }
  getSelectedNodes() {
    const rowNode = this.rowNode;
    const isRowDragMultiRow = this.gos.get("rowDragMultiRow");
    if (!isRowDragMultiRow) {
      return [rowNode];
    }
    const selection = this.beans.selectionSvc?.getSelectedNodes() ?? [];
    return selection.indexOf(rowNode) !== -1 ? selection : [rowNode];
  }
  getDragItem() {
    const { column: column2, rowNode } = this;
    return {
      rowNode,
      rowNodes: this.getSelectedNodes(),
      columns: column2 ? [column2] : void 0,
      defaultTextValue: this.cellValueFn()
    };
  }
  getRowDragText(column2) {
    if (column2) {
      const colDef = column2.getColDef();
      if (colDef.rowDragText) {
        return colDef.rowDragText;
      }
    }
    return this.gos.get("rowDragText");
  }
  addDragSource(dragStartPixels = 4) {
    if (this.dragSource) {
      this.removeDragSource();
    }
    if (this.gos.get("rowDragManaged") && this.rowNode.footer) {
      return;
    }
    const eGui = this.getGui();
    if (this.gos.get("enableCellTextSelection")) {
      this.removeMouseDownListener();
      this.mouseDownListener = this.addManagedElementListeners(eGui, {
        mousedown: (e) => {
          e?.preventDefault();
        }
      })[0];
    }
    const translate = this.getLocaleTextFunc();
    this.dragSource = {
      type: 2,
      eElement: eGui,
      dragItemName: (draggingEvent) => {
        const dragItem = draggingEvent?.dragItem || this.getDragItem();
        const dragItemCount = (draggingEvent?.dropTarget?.rows.length ?? dragItem.rowNodes?.length) || 1;
        const rowDragText = this.getRowDragText(this.column);
        if (rowDragText) {
          return rowDragText(dragItem, dragItemCount);
        }
        return dragItemCount === 1 ? this.cellValueFn() : `${dragItemCount} ${translate("rowDragRows", "rows")}`;
      },
      getDragItem: () => this.getDragItem(),
      dragStartPixels,
      dragSourceDomDataKey: this.gos.getDomDataKey()
    };
    this.beans.dragAndDrop.addDragSource(this.dragSource, true);
  }
  destroy() {
    this.removeDragSource();
    this.removeMouseDownListener();
    super.destroy();
  }
  removeDragSource() {
    if (!this.dragSource) {
      return;
    }
    this.beans.dragAndDrop.removeDragSource(this.dragSource);
    this.dragSource = null;
  }
  removeMouseDownListener() {
    if (!this.mouseDownListener) {
      return;
    }
    this.mouseDownListener();
    this.mouseDownListener = void 0;
  }
};
var ChangedRowNodes = class {
  constructor() {
    this.reordered = false;
    this.removals = /* @__PURE__ */ new Set();
    this.updates = /* @__PURE__ */ new Set();
    this.adds = /* @__PURE__ */ new Set();
  }
};
function _createCellId(cellPosition) {
  const { rowIndex, rowPinned, column: column2 } = cellPosition;
  return `${rowIndex}.${rowPinned == null ? "null" : rowPinned}.${column2.getId()}`;
}
function _areCellsEqual(cellA, cellB) {
  const colsMatch = cellA.column === cellB.column;
  const floatingMatch = cellA.rowPinned === cellB.rowPinned;
  const indexMatch = cellA.rowIndex === cellB.rowIndex;
  return colsMatch && floatingMatch && indexMatch;
}
function _isRowBefore(rowA, rowB) {
  switch (rowA.rowPinned) {
    case "top":
      if (rowB.rowPinned !== "top") {
        return true;
      }
      break;
    case "bottom":
      if (rowB.rowPinned !== "bottom") {
        return false;
      }
      break;
    default:
      if (_exists(rowB.rowPinned)) {
        return rowB.rowPinned !== "top";
      }
      break;
  }
  return rowA.rowIndex < rowB.rowIndex;
}
function _isSameRow(rowA, rowB) {
  if (!rowA && !rowB) {
    return true;
  }
  if (rowA && !rowB || !rowA && rowB) {
    return false;
  }
  return rowA.rowIndex === rowB.rowIndex && rowA.rowPinned == rowB.rowPinned;
}
function _getFirstRow(beans) {
  let rowIndex = 0;
  let rowPinned;
  const { pinnedRowModel, rowModel, pageBounds } = beans;
  if (pinnedRowModel?.getPinnedTopRowCount()) {
    rowPinned = "top";
  } else if (rowModel.getRowCount()) {
    rowPinned = null;
    rowIndex = pageBounds.getFirstRow();
  } else if (pinnedRowModel?.getPinnedBottomRowCount()) {
    rowPinned = "bottom";
  }
  return rowPinned === void 0 ? null : { rowIndex, rowPinned };
}
function _getLastRow(beans) {
  let rowIndex;
  let rowPinned = null;
  const { pinnedRowModel, pageBounds } = beans;
  const pinnedBottomCount = pinnedRowModel?.getPinnedBottomRowCount();
  const pinnedTopCount = pinnedRowModel?.getPinnedTopRowCount();
  if (pinnedBottomCount) {
    rowPinned = "bottom";
    rowIndex = pinnedBottomCount - 1;
  } else if (beans.rowModel.getRowCount()) {
    rowIndex = pageBounds.getLastRow();
  } else if (pinnedTopCount) {
    rowPinned = "top";
    rowIndex = pinnedTopCount - 1;
  }
  return rowIndex === void 0 ? null : { rowIndex, rowPinned };
}
function _getRowNode(beans, gridRow) {
  switch (gridRow.rowPinned) {
    case "top":
      return beans.pinnedRowModel?.getPinnedTopRow(gridRow.rowIndex);
    case "bottom":
      return beans.pinnedRowModel?.getPinnedBottomRow(gridRow.rowIndex);
    default:
      return beans.rowModel.getRow(gridRow.rowIndex);
  }
}
function _getCellByPosition(beans, cellPosition) {
  const spannedCellCtrl = beans.spannedRowRenderer?.getCellByPosition(cellPosition);
  if (spannedCellCtrl) {
    return spannedCellCtrl;
  }
  const rowCtrl = beans.rowRenderer.getRowByPosition(cellPosition);
  if (!rowCtrl) {
    return null;
  }
  return rowCtrl.getCellCtrl(cellPosition.column);
}
function _getRowById(beans, rowId, rowPinned) {
  const { rowModel: rm, pinnedRowModel: prm } = beans;
  let node2;
  node2 ?? (node2 = rm?.getRowNode(rowId));
  if (rowPinned) {
    node2 ?? (node2 = prm?.getPinnedRowById(rowId, rowPinned));
  } else {
    node2 ?? (node2 = prm?.getPinnedRowById(rowId, "top"));
    node2 ?? (node2 = prm?.getPinnedRowById(rowId, "bottom"));
  }
  return node2;
}
function _getRowAbove(beans, rowPosition, checkSticky = false) {
  const { rowIndex: index, rowPinned: pinned } = rowPosition;
  const { pageBounds, pinnedRowModel, rowModel } = beans;
  if (index === 0) {
    if (pinned === "top") {
      return null;
    }
    if (pinned === "bottom" && rowModel.isRowsToRender()) {
      return { rowIndex: pageBounds.getLastRow(), rowPinned: null };
    }
    return pinnedRowModel?.isRowsToRender("top") ? { rowIndex: pinnedRowModel.getPinnedTopRowCount() - 1, rowPinned: "top" } : null;
  }
  if (checkSticky) {
    const rowNode = pinned ? void 0 : rowModel.getRow(index);
    return getNextStickyPosition(beans, rowNode, true) ?? { rowIndex: index - 1, rowPinned: pinned };
  }
  return { rowIndex: index - 1, rowPinned: pinned };
}
function _getRowBelow(beans, rowPosition, checkSticky = false) {
  const { rowIndex: index, rowPinned: pinned } = rowPosition;
  const { pageBounds, pinnedRowModel, rowModel } = beans;
  if (isLastRowInContainer(beans, rowPosition)) {
    if (pinned === "bottom") {
      return null;
    }
    if (pinned === "top" && rowModel.isRowsToRender()) {
      return { rowIndex: pageBounds.getFirstRow(), rowPinned: null };
    }
    return pinnedRowModel?.isRowsToRender("bottom") ? { rowIndex: 0, rowPinned: "bottom" } : null;
  }
  if (checkSticky) {
    const rowNode = pinned ? void 0 : rowModel.getRow(index);
    return getNextStickyPosition(beans, rowNode) ?? { rowIndex: index + 1, rowPinned: pinned };
  }
  return { rowIndex: index + 1, rowPinned: pinned };
}
function getNextStickyPosition(beans, rowNode, up = false) {
  const { gos, rowRenderer } = beans;
  if (!rowNode?.sticky || !_isGroupRowsSticky(gos)) {
    return;
  }
  const stickyTopCtrls = rowRenderer.getStickyTopRowCtrls();
  const stickyBottomCtrls = rowRenderer.getStickyBottomRowCtrls();
  const isStickyTop = !stickyBottomCtrls.some((ctrl) => ctrl.rowNode.rowIndex === rowNode.rowIndex);
  const stickyRowCtrls = isStickyTop ? stickyTopCtrls : stickyBottomCtrls;
  const increment = (up ? -1 : 1) * (isStickyTop ? -1 : 1);
  let nextCtrl;
  for (let i2 = 0; i2 < stickyRowCtrls.length; i2++) {
    if (stickyRowCtrls[i2].rowNode.rowIndex === rowNode.rowIndex) {
      nextCtrl = stickyRowCtrls[i2 + increment];
      break;
    }
  }
  return nextCtrl ? { rowIndex: nextCtrl.rowNode.rowIndex, rowPinned: null } : void 0;
}
function isLastRowInContainer(beans, rowPosition) {
  const { rowPinned, rowIndex } = rowPosition;
  const { pinnedRowModel, pageBounds } = beans;
  if (rowPinned === "top") {
    const lastTopIndex = (pinnedRowModel?.getPinnedTopRowCount() ?? 0) - 1;
    return lastTopIndex <= rowIndex;
  }
  if (rowPinned === "bottom") {
    const lastBottomIndex = (pinnedRowModel?.getPinnedBottomRowCount() ?? 0) - 1;
    return lastBottomIndex <= rowIndex;
  }
  const lastBodyIndex = pageBounds.getLastRow();
  return lastBodyIndex <= rowIndex;
}
var ChangedPath = class {
  constructor(keepingColumns, rootNode) {
    this.active = true;
    this.nodeIdsToColumns = {};
    this.mapToItems = {};
    this.keepingColumns = keepingColumns;
    this.pathRoot = {
      rowNode: rootNode,
      children: null
    };
    this.mapToItems[rootNode.id] = this.pathRoot;
  }
  depthFirstSearchChangedPath(pathItem, callback) {
    const { rowNode, children: children2 } = pathItem;
    if (children2) {
      for (let i2 = 0; i2 < children2.length; ++i2) {
        this.depthFirstSearchChangedPath(children2[i2], callback);
      }
    }
    callback(rowNode);
  }
  depthFirstSearchEverything(rowNode, callback, traverseEverything) {
    const childrenAfterGroup = rowNode.childrenAfterGroup;
    if (childrenAfterGroup) {
      for (let i2 = 0, len = childrenAfterGroup.length; i2 < len; ++i2) {
        const childNode = childrenAfterGroup[i2];
        if (childNode.childrenAfterGroup) {
          this.depthFirstSearchEverything(childNode, callback, traverseEverything);
        } else if (traverseEverything) {
          callback(childNode);
        }
      }
    }
    callback(rowNode);
  }
  // traverseLeafNodes -> used when NOT doing changed path, ie traversing everything. the callback
  // will be called for child nodes in addition to parent nodes.
  forEachChangedNodeDepthFirst(callback, traverseLeafNodes = false, includeUnchangedNodes = false) {
    if (this.active && !includeUnchangedNodes) {
      this.depthFirstSearchChangedPath(this.pathRoot, callback);
    } else {
      this.depthFirstSearchEverything(this.pathRoot.rowNode, callback, traverseLeafNodes);
    }
  }
  executeFromRootNode(callback) {
    callback(this.pathRoot.rowNode);
  }
  createPathItems(rowNode) {
    let pointer = rowNode;
    let newEntryCount = 0;
    while (!this.mapToItems[pointer.id]) {
      const newEntry = {
        rowNode: pointer,
        children: null
      };
      this.mapToItems[pointer.id] = newEntry;
      newEntryCount++;
      pointer = pointer.parent;
    }
    return newEntryCount;
  }
  populateColumnsMap(rowNode, columns2) {
    if (!this.keepingColumns || !columns2) {
      return;
    }
    let pointer = rowNode;
    while (pointer) {
      if (!this.nodeIdsToColumns[pointer.id]) {
        this.nodeIdsToColumns[pointer.id] = {};
      }
      for (const col of columns2) {
        this.nodeIdsToColumns[pointer.id][col.getId()] = true;
      }
      pointer = pointer.parent;
    }
  }
  linkPathItems(rowNode, newEntryCount) {
    let pointer = rowNode;
    for (let i2 = 0; i2 < newEntryCount; i2++) {
      const thisItem = this.mapToItems[pointer.id];
      const parentItem = this.mapToItems[pointer.parent.id];
      if (!parentItem.children) {
        parentItem.children = [];
      }
      parentItem.children.push(thisItem);
      pointer = pointer.parent;
    }
  }
  // called by
  // 1) change detection (provides cols) and
  // 2) groupStage if doing transaction update (doesn't provide cols)
  addParentNode(rowNode, columns2) {
    if (!rowNode || rowNode.isRowPinned()) {
      return;
    }
    const newEntryCount = this.createPathItems(rowNode);
    this.linkPathItems(rowNode, newEntryCount);
    this.populateColumnsMap(rowNode, columns2);
  }
  canSkip(rowNode) {
    return this.active && !this.mapToItems[rowNode.id];
  }
  getValueColumnsForNode(rowNode, valueColumns) {
    if (!this.keepingColumns) {
      return valueColumns;
    }
    const colsForThisNode = this.nodeIdsToColumns[rowNode.id];
    const result2 = valueColumns.filter((col) => colsForThisNode[col.getId()]);
    return result2;
  }
  getNotValueColumnsForNode(rowNode, valueColumns) {
    if (!this.keepingColumns) {
      return null;
    }
    const colsForThisNode = this.nodeIdsToColumns[rowNode.id];
    const result2 = valueColumns.filter((col) => !colsForThisNode[col.getId()]);
    return result2;
  }
};
var RowDragFeatureNudger = class {
  constructor(beans, gridBodyCtrl) {
    this.beans = beans;
    this.groupThrottled = false;
    this.scrollChanged = false;
    this.scrollChanging = false;
    this.oldVScroll = null;
    this.groupTimer = null;
    this.groupTarget = null;
    this.onGroupThrottle = () => {
      this.groupTimer = null;
      this.groupThrottled = true;
      this.beans.dragAndDrop?.nudge();
    };
    const getScrollY = () => gridBodyCtrl.scrollFeature.getVScrollPosition().top;
    this.autoScroll = new AutoScrollService({
      scrollContainer: gridBodyCtrl.eBodyViewport,
      scrollAxis: "y",
      getVerticalPosition: getScrollY,
      setVerticalPosition: (position) => gridBodyCtrl.scrollFeature.setVerticalScrollPosition(position),
      onScrollCallback: () => {
        const newVScroll = getScrollY();
        if (this.oldVScroll !== newVScroll) {
          this.oldVScroll = newVScroll;
          this.scrollChanging = true;
          return;
        }
        const scrollChanged = this.scrollChanging;
        this.scrollChanged = scrollChanged;
        this.scrollChanging = false;
        if (scrollChanged) {
          this.beans.dragAndDrop?.nudge();
          this.scrollChanged = false;
        }
      }
    });
  }
  updateGroup(target, canExpand) {
    if (this.groupTarget && this.groupTarget !== target) {
      this.clearGroup();
    }
    if (target) {
      if (canExpand && this.groupThrottled && !target.expanded && target.childrenAfterSort?.length && target.isExpandable()) {
        target.setExpanded(true, void 0, true);
      }
      if (target.expanded && target.childrenAfterSort?.length) {
        this.groupThrottled = true;
        this.groupTarget = target;
      }
    }
  }
  startGroup(target) {
    this.groupTarget = target;
    if (this.groupTimer === null) {
      this.groupTimer = window.setTimeout(this.onGroupThrottle, this.beans.gos.get("rowDragInsertDelay"));
    }
  }
  clearGroup() {
    this.groupThrottled = false;
    this.groupTarget = null;
    const timer = this.groupTimer;
    if (timer !== null) {
      this.groupTimer = null;
      window.clearTimeout(timer);
    }
  }
  clear() {
    this.clearGroup();
    this.autoScroll.ensureCleared();
    this.oldVScroll = null;
    this.scrollChanged = false;
    this.scrollChanging = false;
  }
};
var RowDragFeature = class extends BeanStub {
  constructor(eContainer) {
    super();
    this.eContainer = eContainer;
    this.lastDraggingEvent = null;
    this.nudger = null;
  }
  postConstruct() {
    const beans = this.beans;
    beans.ctrlsSvc.whenReady(this, (p) => {
      this.nudger = new RowDragFeatureNudger(beans, p.gridBodyCtrl);
    });
  }
  destroy() {
    super.destroy();
    this.nudger?.clear();
    this.nudger = null;
    this.lastDraggingEvent = null;
    this.eContainer = null;
  }
  getContainer() {
    return this.eContainer;
  }
  isInterestedIn(type) {
    return type === 2;
  }
  getIconName(draggingEvent) {
    if (draggingEvent?.dropTarget?.allowed === false) {
      return "notAllowed";
    }
    if (this.gos.get("rowDragManaged") && this.shouldPreventRowMove()) {
      return "notAllowed";
    }
    return "move";
  }
  shouldPreventRowMove() {
    const { rowGroupColsSvc, filterManager, sortSvc } = this.beans;
    const rowGroupCols = rowGroupColsSvc?.columns ?? [];
    if (rowGroupCols.length) {
      return true;
    }
    const isFilterPresent = filterManager?.isAnyFilterPresent();
    if (isFilterPresent) {
      return true;
    }
    const isSortActive = sortSvc?.isSortActive();
    if (isSortActive) {
      return true;
    }
    return false;
  }
  getRowNodes(draggingEvent) {
    if (!this.isFromThisGrid(draggingEvent)) {
      return draggingEvent.dragItem.rowNodes || [];
    }
    const currentNode = draggingEvent.dragItem.rowNode;
    if (this.gos.get("rowDragMultiRow")) {
      const selectedNodes = this.beans.selectionSvc?.getSelectedNodes();
      if (selectedNodes && selectedNodes.indexOf(currentNode) >= 0) {
        return selectedNodes.slice().sort(compareRowIndex);
      }
    }
    return [currentNode];
  }
  onDragEnter(draggingEvent) {
    this.dragging(draggingEvent, true);
  }
  onDragging(draggingEvent) {
    this.dragging(draggingEvent, false);
  }
  dragging(draggingEvent, enter) {
    const { lastDraggingEvent, beans } = this;
    if (enter) {
      const rowNodes = this.getRowNodes(draggingEvent);
      draggingEvent.dragItem.rowNodes = rowNodes;
      setRowNodesDragging(rowNodes, true);
    }
    this.lastDraggingEvent = draggingEvent;
    const fromNudge = draggingEvent.fromNudge;
    const rowsDrop = this.makeRowsDrop(lastDraggingEvent, draggingEvent, fromNudge, false);
    beans.rowDropHighlightSvc?.fromDrag(draggingEvent);
    if (enter) {
      this.dispatchGridEvent("rowDragEnter", draggingEvent);
    }
    this.dispatchGridEvent("rowDragMove", draggingEvent);
    if (rowsDrop?.rowDragManaged && rowsDrop.moved && rowsDrop.allowed && rowsDrop.sameGrid && !rowsDrop.suppressMoveWhenRowDragging && // Avoid flickering by only dropping while auto-scrolling is not happening
    (!fromNudge && !this.nudger?.autoScroll.scrolling || this.nudger?.scrollChanged)) {
      this.dropRows(rowsDrop);
    }
    this.nudger?.autoScroll.check(draggingEvent.event);
  }
  isFromThisGrid(draggingEvent) {
    return draggingEvent.dragSource.dragSourceDomDataKey === this.gos.getDomDataKey();
  }
  makeRowsDrop(lastDraggingEvent, draggingEvent, moving, dropping) {
    const { beans, gos } = this;
    const rowsDrop = this.newRowsDrop(draggingEvent, dropping);
    const rowModel = beans.rowModel;
    draggingEvent.dropTarget = rowsDrop;
    draggingEvent.changed = false;
    if (!rowsDrop) {
      return null;
    }
    let { sameGrid, rootNode, source: source2, target, rows } = rowsDrop;
    target ?? (target = rowModel.getRow(rowModel.getRowCount() - 1) ?? null);
    const canSetParent = (
      // We don't yet support drag and drop with grouping
      !!this.beans.groupStage?.treeData && // We don't yet support moving tree rows from a different grid in a structured way
      sameGrid
    );
    let newParent = null;
    if (target?.footer) {
      const found = getPrevOrNext(rowModel, -1, target) ?? getPrevOrNext(rowModel, 1, target);
      newParent = target.sibling ?? rootNode;
      target = found ?? null;
    }
    if (target?.detail) {
      target = target.parent;
    }
    rowsDrop.moved && (rowsDrop.moved = source2 !== target);
    let yDelta = 0.5;
    if (target) {
      if (sameGrid && rowsDrop.moved && (newParent || !canSetParent)) {
        yDelta = source2.rowIndex > target.rowIndex ? -0.5 : 0.5;
      } else {
        yDelta = (rowsDrop.y - target.rowTop - target.rowHeight / 2) / target.rowHeight || 0;
      }
    }
    if (!canSetParent && sameGrid && target && rowsDrop.moved && _isClientSideRowModel(gos)) {
      const newTarget = deltaDraggingTarget(rowModel, rowsDrop);
      if (newTarget) {
        yDelta = source2.rowIndex > newTarget.rowIndex ? -0.5 : 0.5;
        target = newTarget;
        rowsDrop.moved && (rowsDrop.moved = source2 !== target);
      }
    }
    const nudger = this.nudger;
    nudger?.updateGroup(target, moving);
    if (canSetParent && !newParent && nudger) {
      if (!target || yDelta >= 0.5 && target.rowIndex === beans.pageBounds.getLastRow()) {
        newParent = rootNode;
      } else if (rowsDrop.moved && this.targetShouldBeParent(target, yDelta, rows)) {
        if (nudger.groupThrottled) {
          newParent = target;
        }
        if (!moving && (!newParent || target && !target.expanded && !!target.childrenAfterSort?.length)) {
          nudger.startGroup(target);
        }
      }
      newParent ?? (newParent = target?.parent ?? rootNode);
    }
    let inside = false;
    if (newParent) {
      if (newParent === target && newParent !== rootNode) {
        const firstRow = newParent.expanded ? getPrevOrNext(rowModel, 1, target) : null;
        if (firstRow?.parent === newParent) {
          target = firstRow;
          yDelta = -0.5;
        } else {
          inside = true;
        }
      }
      if (target && !inside) {
        let current3 = target;
        while (current3 && current3 !== rootNode && current3 !== newParent) {
          target = current3;
          current3 = current3.parent;
        }
      }
    }
    rowsDrop.target = target;
    rowsDrop.newParent = newParent;
    rowsDrop.moved && (rowsDrop.moved = source2 !== target);
    const aboveOrBelow = yDelta < 0 ? "above" : "below";
    rowsDrop.position = rowsDrop.moved ? inside ? "inside" : aboveOrBelow : "none";
    this.validateRowsDrop(rowsDrop, canSetParent, aboveOrBelow, dropping);
    draggingEvent.changed || (draggingEvent.changed = rowsDropChanged(lastDraggingEvent?.dropTarget, rowsDrop));
    return rowsDrop;
  }
  newRowsDrop(draggingEvent, dropping) {
    const { beans, gos } = this;
    const rootNode = beans.rowModel.rootNode;
    const rowDragManaged = _isClientSideRowModel(gos) ? gos.get("rowDragManaged") : false;
    const suppressMoveWhenRowDragging = gos.get("suppressMoveWhenRowDragging");
    const sameGrid = this.isFromThisGrid(draggingEvent);
    let { rowNode: source2, rowNodes: rows } = draggingEvent.dragItem;
    rows || (rows = source2 ? [source2] : []);
    source2 || (source2 = rows[0]);
    if (!source2 || !rootNode) {
      return null;
    }
    const withinGrid = this.beans.dragAndDrop.isDropZoneWithinThisGrid(draggingEvent);
    let allowed = true;
    if (rowDragManaged && (!rows.length || this.shouldPreventRowMove() || (suppressMoveWhenRowDragging || !sameGrid) && !withinGrid)) {
      allowed = false;
    }
    const y = _getNormalisedMousePosition(beans, draggingEvent).y;
    const overNode = this.getOverNode(y);
    return {
      api: beans.gridApi,
      context: beans.gridOptions.context,
      draggingEvent,
      rowDragManaged,
      suppressMoveWhenRowDragging,
      sameGrid,
      withinGrid,
      rootNode,
      moved: source2 !== overNode,
      y,
      overNode,
      overIndex: overNode?.rowIndex ?? -1,
      position: "none",
      source: source2,
      target: overNode ?? null,
      newParent: null,
      rows,
      allowed,
      highlight: !dropping && rowDragManaged && suppressMoveWhenRowDragging && (withinGrid || !sameGrid)
    };
  }
  validateRowsDrop(rowsDrop, canSetParent, aboveOrBelow, dropping) {
    const { rowDragManaged, suppressMoveWhenRowDragging } = rowsDrop;
    if (!canSetParent) {
      rowsDrop.newParent = null;
    }
    if (suppressMoveWhenRowDragging && !rowsDrop.moved) {
      rowsDrop.allowed = false;
    }
    const isRowValidDropPosition = (!rowDragManaged || rowsDrop.allowed) && this.gos.get("isRowValidDropPosition");
    if (isRowValidDropPosition) {
      if (canSetParent && rowsDrop.newParent && rowsHaveSameParent(rowsDrop.rows, rowsDrop.newParent)) {
        rowsDrop.newParent = null;
      }
      const canDropResult = isRowValidDropPosition(rowsDrop);
      if (!canDropResult) {
        rowsDrop.allowed = false;
      } else if (typeof canDropResult === "object") {
        if (canDropResult.rows !== void 0) {
          rowsDrop.rows = canDropResult.rows ?? [];
        }
        if (canSetParent && canDropResult.newParent !== void 0) {
          rowsDrop.newParent = canDropResult.newParent;
        }
        if (canDropResult.target !== void 0) {
          rowsDrop.target = canDropResult.target;
        }
        if (canDropResult.position) {
          rowsDrop.position = canDropResult.position;
        }
        if (canDropResult.allowed !== void 0) {
          rowsDrop.allowed = canDropResult.allowed;
        } else if (!rowDragManaged) {
          rowsDrop.allowed = true;
        }
        const draggingEvent = rowsDrop.draggingEvent;
        if (canDropResult.changed && draggingEvent) {
          draggingEvent.changed = true;
        }
        if (!dropping && canDropResult.highlight !== void 0) {
          rowsDrop.highlight = canDropResult.highlight;
        }
      }
    }
    if (rowDragManaged) {
      rowsDrop.rows = this.filterRows(rowsDrop);
    }
    if (canSetParent && rowsDrop.newParent && rowsHaveSameParent(rowsDrop.rows, rowsDrop.newParent)) {
      rowsDrop.newParent = null;
    }
    if (suppressMoveWhenRowDragging && (!rowsDrop.rows.length || rowsDrop.position === "none")) {
      rowsDrop.allowed = false;
    }
    if ((!rowsDrop.allowed || !rowsDrop.newParent) && rowsDrop.position === "inside") {
      rowsDrop.position = aboveOrBelow;
    }
  }
  targetShouldBeParent(target, yDelta, rows) {
    const targetRowIndex = target.rowIndex;
    const INSIDE_THRESHOLD = 0.25;
    if (yDelta < -0.5 + INSIDE_THRESHOLD) {
      return false;
    }
    if (yDelta < 0.5 - INSIDE_THRESHOLD) {
      return true;
    }
    let nextRow;
    let nextRowIndex = targetRowIndex + 1;
    const rowModel = this.beans.rowModel;
    do {
      nextRow = rowModel.getRow(nextRowIndex++);
    } while (nextRow?.footer);
    const childrenAfterGroup = target.childrenAfterGroup;
    if (nextRow && nextRow.parent === target && childrenAfterGroup?.length) {
      const rowsSet = new Set(rows);
      for (const child of childrenAfterGroup) {
        if (child.rowIndex !== null && !rowsSet.has(child)) {
          return true;
        }
      }
    }
    return false;
  }
  addRowDropZone(params) {
    if (!params.getContainer()) {
      _warn(55);
      return;
    }
    const dragAndDrop = this.beans.dragAndDrop;
    if (dragAndDrop.findExternalZone(params.getContainer())) {
      _warn(56);
      return;
    }
    const processedParams = params.fromGrid ? params : {
      getContainer: params.getContainer,
      onDragEnter: params.onDragEnter && ((e) => params.onDragEnter(this.rowDragEvent("rowDragEnter", e))),
      onDragLeave: params.onDragLeave && ((e) => params.onDragLeave(this.rowDragEvent("rowDragLeave", e))),
      onDragging: params.onDragging && ((e) => params.onDragging(this.rowDragEvent("rowDragMove", e))),
      onDragStop: params.onDragStop && ((e) => params.onDragStop(this.rowDragEvent("rowDragEnd", e))),
      onDragCancel: params.onDragCancel && ((e) => params.onDragCancel(this.rowDragEvent("rowDragCancel", e)))
    };
    const dropTarget = {
      isInterestedIn: (type) => type === 2,
      getIconName: () => "move",
      external: true,
      ...processedParams
    };
    dragAndDrop.addDropTarget(dropTarget);
    this.addDestroyFunc(() => dragAndDrop.removeDropTarget(dropTarget));
  }
  getRowDropZone(events) {
    const result2 = {
      getContainer: this.getContainer.bind(this),
      onDragEnter: (e) => {
        this.onDragEnter(e);
        events?.onDragEnter?.(this.rowDragEvent("rowDragEnter", e));
      },
      onDragLeave: (e) => {
        this.onDragLeave(e);
        events?.onDragLeave?.(this.rowDragEvent("rowDragLeave", e));
      },
      onDragging: (e) => {
        this.onDragging(e);
        events?.onDragging?.(this.rowDragEvent("rowDragMove", e));
      },
      onDragStop: (e) => {
        this.onDragStop(e);
        events?.onDragStop?.(this.rowDragEvent("rowDragEnd", e));
      },
      onDragCancel: (e) => {
        this.onDragCancel(e);
        events?.onDragCancel?.(this.rowDragEvent("rowDragCancel", e));
      },
      fromGrid: true
    };
    return result2;
  }
  getOverNode(y) {
    const { pageBounds, rowModel } = this.beans;
    const mouseIsPastLastRow = y > pageBounds.getCurrentPagePixelRange().pageLastPixel;
    const overIndex = mouseIsPastLastRow ? -1 : rowModel.getRowIndexAtPixel(y);
    return overIndex >= 0 ? rowModel.getRow(overIndex) : void 0;
  }
  rowDragEvent(type, draggingEvent) {
    const beans = this.beans;
    const { dragItem, dropTarget: rowsDrop, event, vDirection } = draggingEvent;
    const withRowsDrop = rowsDrop?.rootNode === beans.rowModel.rootNode;
    const y = withRowsDrop ? rowsDrop.y : _getNormalisedMousePosition(beans, draggingEvent).y;
    const overNode = withRowsDrop ? rowsDrop.overNode : this.getOverNode(y);
    const overIndex = withRowsDrop ? rowsDrop.overIndex : overNode?.rowIndex ?? -1;
    return {
      api: beans.gridApi,
      context: beans.gridOptions.context,
      type,
      event,
      node: dragItem.rowNode,
      nodes: dragItem.rowNodes,
      overIndex,
      overNode,
      y,
      vDirection,
      rowsDrop
    };
  }
  dispatchGridEvent(type, draggingEvent) {
    const event = this.rowDragEvent(type, draggingEvent);
    this.eventSvc.dispatchEvent(event);
  }
  onDragLeave(draggingEvent) {
    this.dispatchGridEvent("rowDragLeave", draggingEvent);
    this.stopDragging(draggingEvent);
  }
  onDragStop(draggingEvent) {
    const rowsDrop = this.makeRowsDrop(this.lastDraggingEvent, draggingEvent, false, true);
    this.dispatchGridEvent("rowDragEnd", draggingEvent);
    if (rowsDrop?.allowed && rowsDrop.rowDragManaged && (rowsDrop.suppressMoveWhenRowDragging || !rowsDrop.sameGrid || this.nudger?.autoScroll.scrolling)) {
      this.dropRows(rowsDrop);
    }
    this.stopDragging(draggingEvent);
  }
  onDragCancel(draggingEvent) {
    this.dispatchGridEvent("rowDragCancel", draggingEvent);
    this.stopDragging(draggingEvent);
  }
  stopDragging(draggingEvent) {
    this.nudger?.clear();
    this.beans.rowDropHighlightSvc?.fromDrag(null);
    setRowNodesDragging(draggingEvent.dragItem.rowNodes, false);
  }
  /** Drag and drop. Returns false if at least a row was moved, otherwise true */
  dropRows(rowsDrop) {
    return rowsDrop.sameGrid ? this.csrmMoveRows(rowsDrop) : this.csrmAddRows(rowsDrop);
  }
  csrmAddRows({ position, target, rows }) {
    const getRowIdFunc = _getRowIdCallback(this.gos);
    const clientSideRowModel = this.beans.rowModel;
    const add2 = rows.filter(
      ({ data: data2, rowPinned }) => !clientSideRowModel.getRowNode(getRowIdFunc?.({ data: data2, level: 0, rowPinned }) ?? data2.id)
    ).map(({ data: data2 }) => data2);
    if (add2.length === 0) {
      return false;
    }
    const addIndex = target ? getLeafSourceRowIndex(target) + (position === "above" ? 0 : 1) : void 0;
    clientSideRowModel.updateRowData({ add: add2, addIndex });
    return true;
  }
  filterRows({ newParent, rows }) {
    let filtered;
    for (let i2 = 0, len = rows.length; i2 < len; ++i2) {
      let valid = true;
      const row2 = rows[i2];
      if (!row2 || row2.footer || row2.rowTop === null && row2 !== this.beans.rowModel.getRowNode(row2.id) || // This row cannot be dragged, not in allLeafChildren and not a filler
      newParent && row2.parent !== newParent && wouldFormCycle(row2, newParent) || // Cannot move to a parent that would create a cycle
      !getLeafRow(row2)) {
        valid = false;
      }
      if (valid) {
        filtered?.push(row2);
      } else {
        filtered ?? (filtered = rows.slice(0, i2));
      }
    }
    return filtered ?? rows;
  }
  csrmMoveRows({ position, target, rows, newParent, rootNode }) {
    let changed = false;
    const leafs = /* @__PURE__ */ new Set();
    for (const row2 of rows) {
      if (newParent && row2.parent !== newParent) {
        row2.treeParent = newParent;
        changed = true;
      }
      const leafRow = getLeafRow(row2);
      if (leafRow) {
        leafs.add(leafRow);
      }
    }
    if (!changed && leafs.size === 0) {
      return false;
    }
    const focusSvc = this.beans.focusSvc;
    const cellPosition = focusSvc.getFocusedCell();
    const cellCtrl = cellPosition && _getCellByPosition(this.beans, cellPosition);
    if (leafs.size && this.reorderLeafChildren(leafs, ...this.getMoveRowsBounds(leafs, target, position === "above"))) {
      changed = true;
    }
    if (!changed) {
      return false;
    }
    const clientSideRowModel = this.beans.rowModel;
    const changedRowNodes = new ChangedRowNodes();
    changedRowNodes.reordered = true;
    clientSideRowModel.refreshModel({
      step: "group",
      keepRenderedRows: true,
      animate: !this.gos.get("suppressAnimationFrame"),
      changedPath: new ChangedPath(false, rootNode),
      changedRowNodes
    });
    if (cellCtrl) {
      cellCtrl.focusCell();
    } else {
      focusSvc.clearFocusedCell();
    }
    return true;
  }
  /** For reorderLeafChildren, returns min index of the rows to move, the target index and the max index of the rows to move. */
  getMoveRowsBounds(leafs, target, above) {
    const totalRows = this.beans.rowModel.rootNode?._leafs?.length ?? 0;
    let targetPositionIdx = target ? getLeafSourceRowIndex(target) : -1;
    if (targetPositionIdx < 0 || targetPositionIdx >= totalRows) {
      targetPositionIdx = totalRows;
    } else if (!above) {
      ++targetPositionIdx;
    }
    let firstAffectedLeafIdx = targetPositionIdx;
    let lastAffectedLeafIndex = Math.min(targetPositionIdx, totalRows - 1);
    for (const row2 of leafs) {
      const sourceRowIndex = row2.sourceRowIndex;
      if (sourceRowIndex < firstAffectedLeafIdx) {
        firstAffectedLeafIdx = sourceRowIndex;
      }
      if (sourceRowIndex > lastAffectedLeafIndex) {
        lastAffectedLeafIndex = sourceRowIndex;
      }
    }
    return [firstAffectedLeafIdx, targetPositionIdx, lastAffectedLeafIndex];
  }
  /** Reorders the children of the root node, so that the rows to move are in the correct order.
   * @param leafs The valid set of rows to move, as returned by getValidRowsToMove
   * @param firstAffectedLeafIdx The first index of the rows to move
   * @param targetPositionIdx The target index, where the rows will be moved
   * @param lastAffectedLeafIndex The last index of the rows to move
   * @returns True if the order of the rows changed, false otherwise
   */
  reorderLeafChildren(leafs, firstAffectedLeafIdx, targetPositionIdx, lastAffectedLeafIndex) {
    let orderChanged = false;
    const allLeafs = this.beans.rowModel.rootNode?._leafs;
    if (!leafs.size || !allLeafs) {
      return false;
    }
    let writeIdxLeft = firstAffectedLeafIdx;
    for (let readIdx = firstAffectedLeafIdx; readIdx < targetPositionIdx; ++readIdx) {
      const row2 = allLeafs[readIdx];
      if (!leafs.has(row2)) {
        if (row2.sourceRowIndex !== writeIdxLeft) {
          row2.sourceRowIndex = writeIdxLeft;
          allLeafs[writeIdxLeft] = row2;
          orderChanged = true;
        }
        ++writeIdxLeft;
      }
    }
    let writeIdxRight = lastAffectedLeafIndex;
    for (let readIdx = lastAffectedLeafIndex; readIdx >= targetPositionIdx; --readIdx) {
      const row2 = allLeafs[readIdx];
      if (!leafs.has(row2)) {
        if (row2.sourceRowIndex !== writeIdxRight) {
          row2.sourceRowIndex = writeIdxRight;
          allLeafs[writeIdxRight] = row2;
          orderChanged = true;
        }
        --writeIdxRight;
      }
    }
    for (const row2 of leafs) {
      if (row2.sourceRowIndex !== writeIdxLeft) {
        row2.sourceRowIndex = writeIdxLeft;
        allLeafs[writeIdxLeft] = row2;
        orderChanged = true;
      }
      ++writeIdxLeft;
    }
    return orderChanged;
  }
};
var getPrevOrNext = (rowModel, direction, initial) => {
  if (initial) {
    const rowCount = rowModel.getRowCount();
    let rowIndex = initial.rowIndex + direction;
    while (rowIndex >= 0 && rowIndex < rowCount) {
      const row2 = rowModel.getRow(rowIndex);
      if (!row2 || !row2.footer && !row2.detail) {
        return row2;
      }
      rowIndex += direction;
    }
  }
  return void 0;
};
var wouldFormCycle = (row2, newParent) => {
  let parent = newParent;
  while (parent) {
    if (parent === row2) {
      return true;
    }
    parent = parent.parent;
  }
  return false;
};
var rowsHaveSameParent = (rows, newParent) => {
  for (let i2 = 0, len = rows.length; i2 < len; ++i2) {
    if (rows[i2].parent !== newParent) {
      return false;
    }
  }
  return true;
};
var getLeafSourceRowIndex = (row2) => {
  const leaf = getLeafRow(row2);
  return leaf !== void 0 ? leaf.sourceRowIndex : -1;
};
var getLeafRow = (row2) => row2.data ? row2 : _firstLeaf(row2.childrenAfterGroup);
var rowsDropChanged = (a2, b) => a2 !== b && (!a2 || a2.sameGrid !== b.sameGrid || a2.allowed !== b.allowed || a2.position !== b.position || a2.target !== b.target || a2.source !== b.source || a2.newParent !== b.newParent || !_areEqual(a2.rows, b.rows));
var compareRowIndex = ({ rowIndex: a2 }, { rowIndex: b }) => a2 !== null && b !== null ? a2 - b : 0;
var setRowNodesDragging = (rowNodes, dragging) => {
  for (let i2 = 0, len = rowNodes?.length || 0; i2 < len; ++i2) {
    const rowNode = rowNodes[i2];
    if (rowNode.dragging !== dragging) {
      rowNode.dragging = dragging;
      rowNode.dispatchRowEvent("draggingChanged");
    }
  }
};
var deltaDraggingTarget = (rowModel, rowsDrop) => {
  let bestTarget = null;
  let current3 = rowsDrop.target;
  if (current3 && rowsDrop.rows.indexOf(current3) < 0) {
    return null;
  }
  const source2 = rowsDrop.source;
  if (!current3 || !source2) {
    return null;
  }
  let count2 = current3.rowIndex - source2.rowIndex;
  const increment = count2 < 0 ? -1 : 1;
  count2 = rowsDrop.suppressMoveWhenRowDragging ? Math.abs(count2) : 1;
  const rowsSet = new Set(rowsDrop.rows);
  do {
    const candidate = getPrevOrNext(rowModel, increment, current3);
    if (!candidate) {
      break;
    }
    if (!rowsSet.has(candidate)) {
      bestTarget = candidate;
      --count2;
    }
    current3 = candidate;
  } while (count2 > 0);
  return bestTarget;
};
var RowDragService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "rowDragSvc";
  }
  setupRowDrag(element, ctrl) {
    const rowDragFeature = ctrl.createManagedBean(new RowDragFeature(element));
    const dragAndDrop = this.beans.dragAndDrop;
    dragAndDrop.addDropTarget(rowDragFeature);
    ctrl.addDestroyFunc(() => dragAndDrop.removeDropTarget(rowDragFeature));
    this.rowDragFeature = rowDragFeature;
  }
  createRowDragComp(cellValueFn, rowNode, column2, customGui, dragStartPixels, alwaysVisible) {
    return new RowDragComp(cellValueFn, rowNode, column2, customGui, dragStartPixels, alwaysVisible);
  }
  createRowDragCompForRow(rowNode, element) {
    if (_isCellSelectionEnabled(this.gos)) {
      return void 0;
    }
    const translate = this.getLocaleTextFunc();
    return this.createRowDragComp(
      () => `1 ${translate("rowDragRow", "row")}`,
      rowNode,
      void 0,
      element,
      void 0,
      true
    );
  }
  createRowDragCompForCell(rowNode, column2, cellValueFn, element, dragStartPixels, alwaysVisible) {
    const gos = this.gos;
    if (gos.get("rowDragManaged")) {
      if (!_isClientSideRowModel(gos) || gos.get("pagination")) {
        return void 0;
      }
    }
    const rowDragComp = this.createRowDragComp(
      cellValueFn,
      rowNode,
      column2,
      element,
      dragStartPixels,
      alwaysVisible
    );
    return rowDragComp;
  }
};
var RowDropHighlightService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "rowDropHighlightSvc";
    this.uiLevel = 0;
    this.dragging = false;
    this.row = null;
    this.position = "none";
  }
  postConstruct() {
    this.addManagedEventListeners({
      modelUpdated: this.onModelUpdated.bind(this)
    });
  }
  onModelUpdated() {
    const row2 = this.row;
    const oldDragging = this.dragging;
    if (!row2 || row2?.rowIndex === null || this.position === "none") {
      this.clear();
    } else {
      this.set(row2, this.position);
    }
    this.dragging = oldDragging;
  }
  destroy() {
    this.clear();
    super.destroy();
  }
  clear() {
    const last2 = this.row;
    this.dragging = false;
    if (last2) {
      this.uiLevel = 0;
      this.position = "none";
      this.row = null;
      last2.dispatchRowEvent("rowHighlightChanged");
    }
  }
  set(row2, dropIndicatorPosition) {
    const nodeChanged = row2 !== this.row;
    const uiLevel = row2.uiLevel;
    const highlightChanged = dropIndicatorPosition !== this.position;
    const uiLevelChanged = uiLevel !== this.uiLevel;
    this.dragging = false;
    if (nodeChanged || highlightChanged || uiLevelChanged) {
      if (nodeChanged) {
        this.clear();
      }
      this.uiLevel = uiLevel;
      this.position = dropIndicatorPosition;
      this.row = row2;
      row2.dispatchRowEvent("rowHighlightChanged");
    }
  }
  fromDrag(draggingEvent) {
    const rowsDrop = draggingEvent?.dropTarget;
    if (rowsDrop) {
      const { highlight: highlight2, target, position } = rowsDrop;
      if (highlight2 && target && position !== "none") {
        this.set(target, position);
        this.dragging = true;
        return;
      }
    }
    if (this.dragging) {
      this.clear();
    }
  }
};
var DragModule = {
  moduleName: "Drag",
  version: VERSION,
  beans: [DragService]
};
var DragAndDropModule = {
  moduleName: "DragAndDrop",
  version: VERSION,
  dynamicBeans: {
    dndSourceComp: DndSourceComp
  },
  icons: {
    // drag handle used to pick up draggable rows
    rowDrag: "grip"
  }
};
var SharedDragAndDropModule = {
  moduleName: "SharedDragAndDrop",
  version: VERSION,
  beans: [DragAndDropService],
  dependsOn: [DragModule],
  userComponents: {
    agDragAndDropImage: DragAndDropImageComponent2
  },
  icons: {
    // shown on drag and drop image component icon while dragging column to the side of the grid to pin
    columnMovePin: "pin",
    // shown on drag and drop image component icon while dragging over part of the page that is not a drop zone
    columnMoveHide: "eye-slash",
    // shown on drag and drop image component icon while dragging columns to reorder
    columnMoveMove: "arrows",
    // animating icon shown when dragging a column to the right of the grid causes horizontal scrolling
    columnMoveLeft: "left",
    // animating icon shown when dragging a column to the left of the grid causes horizontal scrolling
    columnMoveRight: "right",
    // shown on drag and drop image component icon while dragging over Row Groups drop zone
    columnMoveGroup: "group",
    // shown on drag and drop image component icon while dragging over Values drop zone
    columnMoveValue: "aggregation",
    // shown on drag and drop image component icon while dragging over pivot drop zone
    columnMovePivot: "pivot",
    // shown on drag and drop image component icon while dragging over drop zone that doesn't support it, e.g.
    // string column over aggregation drop zone
    dropNotAllowed: "not-allowed",
    // drag handle used to pick up draggable rows
    rowDrag: "grip"
  }
};
var RowDragModule = {
  moduleName: "RowDrag",
  version: VERSION,
  beans: [RowDropHighlightService, RowDragService],
  apiFunctions: {
    addRowDropZone,
    removeRowDropZone,
    getRowDropZoneParams,
    getRowDropPositionIndicator,
    setRowDropPositionIndicator
  },
  dependsOn: [SharedDragAndDropModule]
};
var HorizontalResizeModule = {
  moduleName: "HorizontalResize",
  version: VERSION,
  beans: [HorizontalResizeService],
  dependsOn: [DragModule]
};
var columnMovingCSS = (
  /*css*/
  `:where(.ag-ltr) :where(.ag-column-moving){.ag-cell,.ag-header-cell,.ag-spanned-cell-wrapper{transition:left .2s}.ag-header-group-cell{transition:left .2s,width .2s}}:where(.ag-rtl) :where(.ag-column-moving){.ag-cell,.ag-header-cell,.ag-spanned-cell-wrapper{transition:right .2s}.ag-header-group-cell{transition:right .2s,width .2s}}`
);
var ColumnAnimationService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "colAnimation";
    this.executeNextFuncs = [];
    this.executeLaterFuncs = [];
    this.active = false;
    this.activeNext = false;
    this.suppressAnimation = false;
    this.animationThreadCount = 0;
  }
  postConstruct() {
    this.beans.ctrlsSvc.whenReady(this, (p) => this.gridBodyCtrl = p.gridBodyCtrl);
  }
  isActive() {
    return this.active && !this.suppressAnimation;
  }
  setSuppressAnimation(suppress) {
    this.suppressAnimation = suppress;
  }
  start() {
    if (this.active) {
      return;
    }
    const { gos } = this;
    if (gos.get("suppressColumnMoveAnimation")) {
      return;
    }
    if (gos.get("enableRtl")) {
      return;
    }
    this.ensureAnimationCssClassPresent();
    this.active = true;
    this.activeNext = true;
  }
  finish() {
    if (!this.active) {
      return;
    }
    this.flush(
      () => this.activeNext = false,
      () => this.active = false
    );
  }
  executeNextVMTurn(func2) {
    if (this.activeNext) {
      this.executeNextFuncs.push(func2);
    } else {
      func2();
    }
  }
  executeLaterVMTurn(func2) {
    if (this.active) {
      this.executeLaterFuncs.push(func2);
    } else {
      func2();
    }
  }
  ensureAnimationCssClassPresent() {
    this.animationThreadCount++;
    const animationThreadCountCopy = this.animationThreadCount;
    const { gridBodyCtrl } = this;
    gridBodyCtrl.setColumnMovingCss(true);
    this.executeLaterFuncs.push(() => {
      if (this.animationThreadCount === animationThreadCountCopy) {
        gridBodyCtrl.setColumnMovingCss(false);
      }
    });
  }
  flush(callbackNext, callbackLater) {
    const { executeNextFuncs, executeLaterFuncs } = this;
    if (executeNextFuncs.length === 0 && executeLaterFuncs.length === 0) {
      callbackNext();
      callbackLater();
      return;
    }
    const runFuncs = (queue) => {
      while (queue.length) {
        const func2 = queue.pop();
        if (func2) {
          func2();
        }
      }
    };
    this.beans.frameworkOverrides.wrapIncoming(() => {
      window.setTimeout(() => {
        callbackNext();
        runFuncs(executeNextFuncs);
      }, 0);
      window.setTimeout(() => {
        callbackLater();
        runFuncs(executeLaterFuncs);
      }, 200);
    });
  }
};
function moveColumnByIndex(beans, fromIndex, toIndex) {
  beans.colMoves?.moveColumnByIndex(fromIndex, toIndex, "api");
}
function moveColumns(beans, columnsToMoveKeys, toIndex) {
  beans.colMoves?.moveColumns(columnsToMoveKeys, toIndex, "api");
}
var BodyDropPivotTarget = class extends BeanStub {
  constructor(pinned) {
    super();
    this.pinned = pinned;
    this.columnsToAggregate = [];
    this.columnsToGroup = [];
    this.columnsToPivot = [];
  }
  /** Callback for when drag enters */
  onDragEnter(draggingEvent) {
    this.clearColumnsList();
    if (this.gos.get("functionsReadOnly")) {
      return;
    }
    const dragColumns = draggingEvent.dragItem.columns;
    if (!dragColumns) {
      return;
    }
    for (const column2 of dragColumns) {
      if (!column2.isPrimary()) {
        continue;
      }
      if (column2.isAnyFunctionActive()) {
        continue;
      }
      if (column2.isAllowValue()) {
        this.columnsToAggregate.push(column2);
      } else if (column2.isAllowRowGroup()) {
        this.columnsToGroup.push(column2);
      } else if (column2.isAllowPivot()) {
        this.columnsToPivot.push(column2);
      }
    }
  }
  getIconName() {
    const totalColumns = this.columnsToAggregate.length + this.columnsToGroup.length + this.columnsToPivot.length;
    if (totalColumns > 0) {
      return this.pinned ? "pinned" : "move";
    }
    return null;
  }
  /** Callback for when drag leaves */
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  onDragLeave(draggingEvent) {
    this.clearColumnsList();
  }
  clearColumnsList() {
    this.columnsToAggregate.length = 0;
    this.columnsToGroup.length = 0;
    this.columnsToPivot.length = 0;
  }
  /** Callback for when dragging */
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  onDragging(draggingEvent) {
  }
  /** Callback for when drag stops */
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  onDragStop(draggingEvent) {
    const { valueColsSvc, rowGroupColsSvc, pivotColsSvc } = this.beans;
    if (this.columnsToAggregate.length > 0) {
      valueColsSvc?.addColumns(this.columnsToAggregate, "toolPanelDragAndDrop");
    }
    if (this.columnsToGroup.length > 0) {
      rowGroupColsSvc?.addColumns(this.columnsToGroup, "toolPanelDragAndDrop");
    }
    if (this.columnsToPivot.length > 0) {
      pivotColsSvc?.addColumns(this.columnsToPivot, "toolPanelDragAndDrop");
    }
  }
  onDragCancel() {
    this.clearColumnsList();
  }
};
function sortColsLikeCols(colsList, cols) {
  if (!cols || cols.length <= 1) {
    return;
  }
  const notAllColsPresent = cols.filter((c2) => colsList.indexOf(c2) < 0).length > 0;
  if (notAllColsPresent) {
    return;
  }
  cols.sort((a2, b) => {
    const indexA = colsList.indexOf(a2);
    const indexB = colsList.indexOf(b);
    return indexA - indexB;
  });
}
function getColsToMove(allMovingColumns) {
  const newCols = [...allMovingColumns];
  for (const col of allMovingColumns) {
    let movingGroup = null;
    let parent = col.getParent();
    while (parent != null && parent.getDisplayedLeafColumns().length === 1) {
      movingGroup = parent;
      parent = parent.getParent();
    }
    if (movingGroup != null) {
      const isMarryChildren = !!movingGroup.getColGroupDef()?.marryChildren;
      const columnsToMove = isMarryChildren ? (
        // when marry children is true, we also have to move hidden
        // columns within the group, so grab them from the `providedColumnGroup`
        movingGroup.getProvidedColumnGroup().getLeafColumns()
      ) : movingGroup.getLeafColumns();
      for (const newCol of columnsToMove) {
        if (!newCols.includes(newCol)) {
          newCols.push(newCol);
        }
      }
    }
  }
  return newCols;
}
function getLowestFragMove(validMoves, allMovingColumnsOrdered, colMoves, visibleCols) {
  const displayedCols = visibleCols.allCols;
  let lowestFragMove = null;
  let targetOrder = null;
  for (let i2 = 0; i2 < validMoves.length; i2++) {
    const move = validMoves[i2];
    const order2 = colMoves.getProposedColumnOrder(allMovingColumnsOrdered, move);
    if (!colMoves.doesOrderPassRules(order2)) {
      continue;
    }
    const displayedOrder = order2.filter((col) => displayedCols.includes(col));
    if (targetOrder === null) {
      targetOrder = displayedOrder;
    } else if (!_areEqual(displayedOrder, targetOrder)) {
      break;
    }
    const fragCount = groupFragCount(order2);
    if (lowestFragMove === null || fragCount < lowestFragMove.fragCount) {
      lowestFragMove = { move, fragCount };
    }
  }
  return lowestFragMove;
}
function getBestColumnMoveIndexFromXPosition(params) {
  const { isFromHeader, fromLeft, xPosition, fromEnter, fakeEvent, pinned, gos, colModel, colMoves, visibleCols } = params;
  let { allMovingColumns } = params;
  if (isFromHeader) {
    allMovingColumns = getColsToMove(allMovingColumns);
  }
  const allMovingColumnsOrdered = allMovingColumns.slice();
  sortColsLikeCols(colModel.getCols(), allMovingColumnsOrdered);
  const validMoves = calculateValidMoves({
    movingCols: allMovingColumnsOrdered,
    draggingRight: fromLeft,
    xPosition,
    pinned,
    gos,
    colModel,
    visibleCols
  });
  const oldIndex = calculateOldIndex(allMovingColumnsOrdered, colModel);
  if (validMoves.length === 0) {
    return;
  }
  const firstValidMove = validMoves[0];
  const constrainDirection = oldIndex !== null && (isFromHeader || !fromEnter);
  if (constrainDirection && !fakeEvent) {
    if (!fromLeft && firstValidMove >= oldIndex) {
      return;
    }
    if (fromLeft && firstValidMove <= oldIndex) {
      return;
    }
  }
  const lowestFragMove = getLowestFragMove(validMoves, allMovingColumnsOrdered, colMoves, visibleCols);
  if (!lowestFragMove) {
    return;
  }
  const toIndex = lowestFragMove.move;
  if (toIndex > colModel.getCols().length - allMovingColumnsOrdered.length) {
    return;
  }
  return { columns: allMovingColumnsOrdered, toIndex };
}
function attemptMoveColumns(params) {
  const { columns: columns2, toIndex } = getBestColumnMoveIndexFromXPosition(params) || {};
  const { finished, colMoves } = params;
  if (!columns2 || toIndex == null) {
    return null;
  }
  colMoves.moveColumns(columns2, toIndex, "uiColumnMoved", finished);
  return finished ? null : { columns: columns2, toIndex };
}
function calculateOldIndex(movingCols, colModel) {
  const gridCols = colModel.getCols();
  const indexes = movingCols.map((col) => gridCols.indexOf(col)).sort((a2, b) => a2 - b);
  const firstIndex = indexes[0];
  const lastIndex = _last(indexes);
  const spread2 = lastIndex - firstIndex;
  const gapsExist = spread2 !== indexes.length - 1;
  return gapsExist ? null : firstIndex;
}
function groupFragCount(columns2) {
  function parents(col) {
    const result2 = [];
    let parent = col.getOriginalParent();
    while (parent != null) {
      result2.push(parent);
      parent = parent.getOriginalParent();
    }
    return result2;
  }
  let count2 = 0;
  for (let i2 = 0; i2 < columns2.length - 1; i2++) {
    let a2 = parents(columns2[i2]);
    let b = parents(columns2[i2 + 1]);
    [a2, b] = a2.length > b.length ? [a2, b] : [b, a2];
    for (const parent of a2) {
      if (b.indexOf(parent) === -1) {
        count2++;
      }
    }
  }
  return count2;
}
function getDisplayedColumns(visibleCols, type) {
  switch (type) {
    case "left":
      return visibleCols.leftCols;
    case "right":
      return visibleCols.rightCols;
    default:
      return visibleCols.centerCols;
  }
}
function calculateValidMoves(params) {
  const { movingCols, draggingRight, xPosition, pinned, gos, colModel, visibleCols } = params;
  const isMoveBlocked = gos.get("suppressMovableColumns") || movingCols.some((col) => col.getColDef().suppressMovable);
  if (isMoveBlocked) {
    return [];
  }
  const allDisplayedCols = getDisplayedColumns(visibleCols, pinned);
  const allGridCols = colModel.getCols();
  const movingDisplayedCols = allDisplayedCols.filter((col) => movingCols.includes(col));
  const otherDisplayedCols = allDisplayedCols.filter((col) => !movingCols.includes(col));
  const otherGridCols = allGridCols.filter((col) => !movingCols.includes(col));
  let displayIndex = 0;
  let availableWidth = xPosition;
  if (draggingRight) {
    let widthOfMovingDisplayedCols = 0;
    for (const col of movingDisplayedCols) {
      widthOfMovingDisplayedCols += col.getActualWidth();
    }
    availableWidth -= widthOfMovingDisplayedCols;
  }
  if (availableWidth > 0) {
    for (let i2 = 0; i2 < otherDisplayedCols.length; i2++) {
      const col = otherDisplayedCols[i2];
      availableWidth -= col.getActualWidth();
      if (availableWidth < 0) {
        break;
      }
      displayIndex++;
    }
    if (draggingRight) {
      displayIndex++;
    }
  }
  let firstValidMove;
  if (displayIndex > 0) {
    const leftColumn2 = otherDisplayedCols[displayIndex - 1];
    firstValidMove = otherGridCols.indexOf(leftColumn2) + 1;
  } else {
    firstValidMove = otherGridCols.indexOf(otherDisplayedCols[0]);
    if (firstValidMove === -1) {
      firstValidMove = 0;
    }
  }
  const validMoves = [firstValidMove];
  const numberComparator = (a2, b) => a2 - b;
  if (draggingRight) {
    let pointer = firstValidMove + 1;
    const lastIndex = allGridCols.length - 1;
    while (pointer <= lastIndex) {
      validMoves.push(pointer);
      pointer++;
    }
    validMoves.sort(numberComparator);
  } else {
    let pointer = firstValidMove;
    const lastIndex = allGridCols.length - 1;
    let displacedCol = allGridCols[pointer];
    while (pointer <= lastIndex && allDisplayedCols.indexOf(displacedCol) < 0) {
      pointer++;
      validMoves.push(pointer);
      displacedCol = allGridCols[pointer];
    }
    pointer = firstValidMove - 1;
    const firstDisplayIndex = 0;
    while (pointer >= firstDisplayIndex) {
      validMoves.push(pointer);
      pointer--;
    }
    validMoves.sort(numberComparator).reverse();
  }
  return validMoves;
}
function normaliseX(params) {
  const { pinned, fromKeyboard, gos, ctrlsSvc, useHeaderRow, skipScrollPadding } = params;
  let eViewport = ctrlsSvc.getHeaderRowContainerCtrl(pinned)?.eViewport;
  let { x } = params;
  if (!eViewport) {
    return 0;
  }
  if (fromKeyboard) {
    x -= eViewport.getBoundingClientRect().left;
  }
  if (gos.get("enableRtl")) {
    if (useHeaderRow) {
      eViewport = eViewport.querySelector(".ag-header-row");
    }
    x = eViewport.clientWidth - x;
  }
  if (pinned == null && !skipScrollPadding) {
    x += ctrlsSvc.get("center").getCenterViewportScrollLeft();
  }
  return x;
}
function setColumnsMoving(columns2, isMoving) {
  for (const column2 of columns2) {
    column2.moving = isMoving;
    column2.dispatchColEvent("movingChanged", "uiColumnMoved");
  }
}
var MOVE_FAIL_THRESHOLD = 7;
var SCROLL_MOVE_WIDTH = 100;
var SCROLL_GAP_NEEDED_BEFORE_MOVE = SCROLL_MOVE_WIDTH / 2;
var SCROLL_ACCELERATION_RATE = 5;
var SCROLL_TIME_INTERVAL = 100;
var MoveColumnFeature = class extends BeanStub {
  constructor(pinned) {
    super();
    this.pinned = pinned;
    this.needToMoveLeft = false;
    this.needToMoveRight = false;
    this.lastMovedInfo = null;
    this.isCenterContainer = !_exists(pinned);
  }
  postConstruct() {
    this.beans.ctrlsSvc.whenReady(this, (p) => {
      this.gridBodyCon = p.gridBodyCtrl;
    });
  }
  getIconName() {
    const { pinned, lastDraggingEvent } = this;
    const { dragItem } = lastDraggingEvent || {};
    const columns2 = dragItem?.columns ?? [];
    for (const col of columns2) {
      const colPinned = col.getPinned();
      if (col.getColDef().lockPinned) {
        if (colPinned == pinned) {
          return "move";
        }
        continue;
      }
      const initialPinnedState = dragItem?.containerType;
      if (initialPinnedState === pinned || !pinned) {
        return "move";
      }
      if (pinned && (!colPinned || initialPinnedState !== pinned)) {
        return "pinned";
      }
    }
    return "notAllowed";
  }
  onDragEnter(draggingEvent) {
    const dragItem = draggingEvent.dragItem;
    const columns2 = dragItem.columns;
    const dragCameFromToolPanel = draggingEvent.dragSource.type === 0;
    if (dragCameFromToolPanel) {
      this.setColumnsVisible(columns2, true, "uiColumnDragged");
    } else {
      const visibleState = dragItem.visibleState;
      const visibleColumns = (columns2 || []).filter(
        (column2) => visibleState[column2.getId()] && !column2.isVisible()
      );
      this.setColumnsVisible(visibleColumns, true, "uiColumnDragged");
    }
    if (!this.gos.get("suppressMoveWhenColumnDragging")) {
      this.attemptToPinColumns(columns2, this.pinned);
    }
    this.onDragging(draggingEvent, true, true);
  }
  onDragging(draggingEvent = this.lastDraggingEvent, fromEnter = false, fakeEvent = false, finished = false) {
    const { gos, ctrlsSvc } = this.beans;
    const isSuppressMoveWhenDragging = gos.get("suppressMoveWhenColumnDragging");
    if (finished && !isSuppressMoveWhenDragging) {
      this.finishColumnMoving();
      return;
    }
    this.lastDraggingEvent = draggingEvent;
    if (!draggingEvent || !finished && _missing(draggingEvent.hDirection)) {
      return;
    }
    const mouseX = normaliseX({
      x: draggingEvent.x,
      pinned: this.pinned,
      gos,
      ctrlsSvc
    });
    if (!fromEnter) {
      this.checkCenterForScrolling(mouseX);
    }
    if (isSuppressMoveWhenDragging) {
      this.handleColumnDragWhileSuppressingMovement(draggingEvent, fromEnter, fakeEvent, mouseX, finished);
    } else {
      this.handleColumnDragWhileAllowingMovement(draggingEvent, fromEnter, fakeEvent, mouseX, finished);
    }
  }
  onDragLeave() {
    this.ensureIntervalCleared();
    this.clearHighlighted();
    this.updateDragItemContainerType();
    this.lastMovedInfo = null;
  }
  onDragStop() {
    this.onDragging(this.lastDraggingEvent, false, true, true);
    this.ensureIntervalCleared();
    this.lastMovedInfo = null;
  }
  onDragCancel() {
    this.clearHighlighted();
    this.ensureIntervalCleared();
    this.lastMovedInfo = null;
  }
  setColumnsVisible(columns2, visible2, source2) {
    if (!columns2?.length) {
      return;
    }
    const allowedCols = columns2.filter((c2) => !c2.getColDef().lockVisible);
    if (!allowedCols.length) {
      return;
    }
    this.beans.colModel.setColsVisible(allowedCols, visible2, source2);
  }
  finishColumnMoving() {
    this.clearHighlighted();
    const lastMovedInfo = this.lastMovedInfo;
    if (!lastMovedInfo) {
      return;
    }
    const { columns: columns2, toIndex } = lastMovedInfo;
    this.beans.colMoves.moveColumns(columns2, toIndex, "uiColumnMoved", true);
  }
  updateDragItemContainerType() {
    const { lastDraggingEvent } = this;
    if (this.gos.get("suppressMoveWhenColumnDragging") || !lastDraggingEvent) {
      return;
    }
    const dragItem = lastDraggingEvent.dragItem;
    if (!dragItem) {
      return;
    }
    dragItem.containerType = this.pinned;
  }
  handleColumnDragWhileSuppressingMovement(draggingEvent, fromEnter, fakeEvent, mouseX, finished) {
    const allMovingColumns = this.getAllMovingColumns(draggingEvent, true);
    if (finished) {
      const isAttemptingToPin = this.isAttemptingToPin(allMovingColumns);
      if (isAttemptingToPin) {
        this.attemptToPinColumns(allMovingColumns, void 0, true);
      }
      const { fromLeft, xPosition } = this.getNormalisedXPositionInfo(allMovingColumns, isAttemptingToPin) || {};
      if (fromLeft == null || xPosition == null) {
        this.finishColumnMoving();
        return;
      }
      this.moveColumnsAfterHighlight({
        allMovingColumns,
        xPosition,
        fromEnter,
        fakeEvent,
        fromLeft
      });
    } else {
      if (!this.beans.dragAndDrop.isDropZoneWithinThisGrid(draggingEvent)) {
        return;
      }
      this.highlightHoveredColumn(allMovingColumns, mouseX);
    }
  }
  handleColumnDragWhileAllowingMovement(draggingEvent, fromEnter, fakeEvent, mouseX, finished) {
    const allMovingColumns = this.getAllMovingColumns(draggingEvent);
    const fromLeft = this.normaliseDirection(draggingEvent.hDirection) === "right";
    const isFromHeader = draggingEvent.dragSource.type === 1;
    const params = this.getMoveColumnParams({
      allMovingColumns,
      isFromHeader,
      xPosition: mouseX,
      fromLeft,
      fromEnter,
      fakeEvent
    });
    const lastMovedInfo = attemptMoveColumns({ ...params, finished });
    if (lastMovedInfo) {
      this.lastMovedInfo = lastMovedInfo;
    }
  }
  getAllMovingColumns(draggingEvent, useSplit = false) {
    const dragItem = draggingEvent.dragSource.getDragItem();
    let columns2 = null;
    if (useSplit) {
      columns2 = dragItem.columnsInSplit;
      if (!columns2) {
        columns2 = dragItem.columns;
      }
    } else {
      columns2 = dragItem.columns;
    }
    const conditionCallback = (col) => col.getColDef().lockPinned ? col.getPinned() == this.pinned : true;
    if (!columns2) {
      return [];
    }
    return columns2.filter(conditionCallback);
  }
  getMoveColumnParams(params) {
    const { allMovingColumns, isFromHeader, xPosition, fromLeft, fromEnter, fakeEvent } = params;
    const { gos, colModel, colMoves, visibleCols } = this.beans;
    return {
      allMovingColumns,
      isFromHeader,
      fromLeft,
      xPosition,
      pinned: this.pinned,
      fromEnter,
      fakeEvent,
      gos,
      colModel,
      colMoves,
      visibleCols
    };
  }
  highlightHoveredColumn(movingColumns, mouseX) {
    const { gos, colModel } = this.beans;
    const isRtl = gos.get("enableRtl");
    const consideredColumns = colModel.getCols().filter((col) => col.isVisible() && col.getPinned() === this.pinned);
    let start2 = null;
    let width = null;
    let targetColumn = null;
    for (const col of consideredColumns) {
      width = col.getActualWidth();
      start2 = this.getNormalisedColumnLeft(col, 0, isRtl);
      if (start2 != null) {
        const end2 = start2 + width;
        if (start2 <= mouseX && end2 >= mouseX) {
          targetColumn = col;
          break;
        }
      }
      start2 = null;
      width = null;
    }
    if (!targetColumn) {
      for (let i2 = consideredColumns.length - 1; i2 >= 0; i2--) {
        const currentColumn = consideredColumns[i2];
        const parent = consideredColumns[i2].getParent();
        if (!parent) {
          targetColumn = currentColumn;
          break;
        }
        const leafDisplayedCols = parent?.getDisplayedLeafColumns();
        if (leafDisplayedCols.length) {
          targetColumn = _last(leafDisplayedCols);
          break;
        }
      }
      if (!targetColumn) {
        return;
      }
      start2 = this.getNormalisedColumnLeft(targetColumn, 0, isRtl);
      width = targetColumn.getActualWidth();
    } else if (movingColumns.indexOf(targetColumn) !== -1) {
      targetColumn = null;
    }
    if (this.lastHighlightedColumn?.column !== targetColumn) {
      this.clearHighlighted();
    }
    if (targetColumn == null || start2 == null || width == null) {
      return;
    }
    let position;
    if (mouseX - start2 < width / 2 !== isRtl) {
      position = 0;
    } else {
      position = 1;
    }
    setColumnHighlighted(targetColumn, position);
    this.lastHighlightedColumn = { column: targetColumn, position };
  }
  getNormalisedXPositionInfo(allMovingColumns, isAttemptingToPin) {
    const { gos, visibleCols } = this.beans;
    const isRtl = gos.get("enableRtl");
    const { firstMovingCol, column: column2, position } = this.getColumnMoveAndTargetInfo(
      allMovingColumns,
      isAttemptingToPin,
      isRtl
    );
    if (!firstMovingCol || !column2 || position == null) {
      return;
    }
    const visibleColumns = visibleCols.allCols;
    const movingColIndex = visibleColumns.indexOf(firstMovingCol);
    const targetIndex = visibleColumns.indexOf(column2);
    const isBefore = position === 0 !== isRtl;
    const fromLeft = movingColIndex < targetIndex || movingColIndex === targetIndex && !isBefore;
    let diff2 = 0;
    if (isBefore) {
      if (fromLeft) {
        diff2 -= 1;
      }
    } else if (!fromLeft) {
      diff2 += 1;
    }
    if (targetIndex + diff2 === movingColIndex) {
      return;
    }
    const targetColumn = visibleColumns[targetIndex + diff2];
    if (!targetColumn) {
      return;
    }
    const xPosition = this.getNormalisedColumnLeft(targetColumn, 20, isRtl);
    return { fromLeft, xPosition };
  }
  getColumnMoveAndTargetInfo(allMovingColumns, isAttemptingToPin, isRtl) {
    const lastHighlightedColumn = this.lastHighlightedColumn || {};
    const { firstMovingCol, lastMovingCol } = findFirstAndLastMovingColumns(allMovingColumns);
    if (!firstMovingCol || !lastMovingCol || lastHighlightedColumn.column || !isAttemptingToPin) {
      return {
        firstMovingCol,
        ...lastHighlightedColumn
      };
    }
    const pinned = this.getPinDirection();
    const isLeft = pinned === "left";
    return {
      firstMovingCol,
      position: isLeft ? 1 : 0,
      column: isLeft !== isRtl ? firstMovingCol : lastMovingCol
    };
  }
  normaliseDirection(hDirection) {
    if (this.gos.get("enableRtl")) {
      switch (hDirection) {
        case "left":
          return "right";
        case "right":
          return "left";
      }
    }
    return hDirection;
  }
  getNormalisedColumnLeft(col, padding, isRtl) {
    const { gos, ctrlsSvc } = this.beans;
    const left2 = col.getLeft();
    if (left2 == null) {
      return null;
    }
    const width = col.getActualWidth();
    return normaliseX({
      x: isRtl ? left2 + width - padding : left2 + padding,
      pinned: col.getPinned(),
      useHeaderRow: isRtl,
      skipScrollPadding: true,
      gos,
      ctrlsSvc
    });
  }
  isAttemptingToPin(columns2) {
    const isMovingHorizontally = this.needToMoveLeft || this.needToMoveRight;
    const isFailedMoreThanThreshold = this.failedMoveAttempts > MOVE_FAIL_THRESHOLD;
    return isMovingHorizontally && isFailedMoreThanThreshold || columns2.some((col) => col.getPinned() !== this.pinned);
  }
  moveColumnsAfterHighlight(params) {
    const { allMovingColumns, xPosition, fromEnter, fakeEvent, fromLeft } = params;
    const columnMoveParams = this.getMoveColumnParams({
      allMovingColumns,
      isFromHeader: true,
      xPosition,
      fromLeft,
      fromEnter,
      fakeEvent
    });
    const { columns: columns2, toIndex } = getBestColumnMoveIndexFromXPosition(columnMoveParams) || {};
    if (columns2 && toIndex != null) {
      this.lastMovedInfo = {
        columns: columns2,
        toIndex
      };
    }
    this.finishColumnMoving();
  }
  clearHighlighted() {
    const { lastHighlightedColumn } = this;
    if (!lastHighlightedColumn) {
      return;
    }
    setColumnHighlighted(lastHighlightedColumn.column, null);
    this.lastHighlightedColumn = null;
  }
  checkCenterForScrolling(xAdjustedForScroll) {
    if (!this.isCenterContainer) {
      return;
    }
    const centerCtrl = this.beans.ctrlsSvc.get("center");
    const firstVisiblePixel = centerCtrl.getCenterViewportScrollLeft();
    const lastVisiblePixel = firstVisiblePixel + centerCtrl.getCenterWidth();
    let needToMoveRight;
    let needToMoveLeft;
    if (this.gos.get("enableRtl")) {
      needToMoveRight = xAdjustedForScroll < firstVisiblePixel + SCROLL_GAP_NEEDED_BEFORE_MOVE;
      needToMoveLeft = xAdjustedForScroll > lastVisiblePixel - SCROLL_GAP_NEEDED_BEFORE_MOVE;
    } else {
      needToMoveLeft = xAdjustedForScroll < firstVisiblePixel + SCROLL_GAP_NEEDED_BEFORE_MOVE;
      needToMoveRight = xAdjustedForScroll > lastVisiblePixel - SCROLL_GAP_NEEDED_BEFORE_MOVE;
    }
    this.needToMoveRight = needToMoveRight;
    this.needToMoveLeft = needToMoveLeft;
    if (needToMoveLeft || needToMoveRight) {
      this.ensureIntervalStarted();
    } else {
      this.ensureIntervalCleared();
    }
  }
  ensureIntervalStarted() {
    if (this.movingIntervalId) {
      return;
    }
    this.intervalCount = 0;
    this.failedMoveAttempts = 0;
    this.movingIntervalId = window.setInterval(this.moveInterval.bind(this), SCROLL_TIME_INTERVAL);
    this.beans.dragAndDrop.setDragImageCompIcon(this.needToMoveLeft ? "left" : "right", true);
  }
  ensureIntervalCleared() {
    if (!this.movingIntervalId) {
      return;
    }
    window.clearInterval(this.movingIntervalId);
    this.movingIntervalId = null;
    this.failedMoveAttempts = 0;
    this.beans.dragAndDrop.setDragImageCompIcon(this.getIconName());
  }
  moveInterval() {
    let pixelsToMove;
    this.intervalCount++;
    pixelsToMove = 10 + this.intervalCount * SCROLL_ACCELERATION_RATE;
    if (pixelsToMove > SCROLL_MOVE_WIDTH) {
      pixelsToMove = SCROLL_MOVE_WIDTH;
    }
    let pixelsMoved = null;
    const scrollFeature = this.gridBodyCon.scrollFeature;
    if (this.needToMoveLeft) {
      pixelsMoved = scrollFeature.scrollHorizontally(-pixelsToMove);
    } else if (this.needToMoveRight) {
      pixelsMoved = scrollFeature.scrollHorizontally(pixelsToMove);
    }
    if (pixelsMoved !== 0) {
      this.onDragging(this.lastDraggingEvent);
      this.failedMoveAttempts = 0;
    } else {
      this.failedMoveAttempts++;
      const { pinnedCols, dragAndDrop, gos } = this.beans;
      if (this.failedMoveAttempts <= MOVE_FAIL_THRESHOLD + 1 || !pinnedCols) {
        return;
      }
      dragAndDrop.setDragImageCompIcon("pinned");
      if (!gos.get("suppressMoveWhenColumnDragging")) {
        const columns2 = this.lastDraggingEvent?.dragItem.columns;
        this.attemptToPinColumns(columns2, void 0, true);
      }
    }
  }
  getPinDirection() {
    if (this.needToMoveLeft || this.pinned === "left") {
      return "left";
    }
    if (this.needToMoveRight || this.pinned === "right") {
      return "right";
    }
  }
  attemptToPinColumns(columns2, pinned, fromMoving = false) {
    const allowedCols = (columns2 || []).filter((c2) => !c2.getColDef().lockPinned);
    if (!allowedCols.length) {
      return 0;
    }
    if (fromMoving) {
      pinned = this.getPinDirection();
    }
    const { pinnedCols, dragAndDrop } = this.beans;
    pinnedCols?.setColsPinned(allowedCols, pinned, "uiColumnDragged");
    if (fromMoving) {
      dragAndDrop.nudge();
    }
    return allowedCols.length;
  }
  destroy() {
    super.destroy();
    this.lastDraggingEvent = null;
    this.clearHighlighted();
    this.lastMovedInfo = null;
  }
};
function setColumnHighlighted(column2, highlighted) {
  if (column2.highlighted === highlighted) {
    return;
  }
  column2.highlighted = highlighted;
  column2.dispatchColEvent("headerHighlightChanged", "uiColumnMoved");
}
function findFirstAndLastMovingColumns(allMovingColumns) {
  const moveLen = allMovingColumns.length;
  let firstMovingCol;
  let lastMovingCol;
  for (let i2 = 0; i2 < moveLen; i2++) {
    if (!firstMovingCol) {
      const leftCol = allMovingColumns[i2];
      if (leftCol.getLeft() != null) {
        firstMovingCol = leftCol;
      }
    }
    if (!lastMovingCol) {
      const rightCol = allMovingColumns[moveLen - 1 - i2];
      if (rightCol.getLeft() != null) {
        lastMovingCol = rightCol;
      }
    }
    if (firstMovingCol && lastMovingCol) {
      break;
    }
  }
  return { firstMovingCol, lastMovingCol };
}
var BodyDropTarget = class extends BeanStub {
  constructor(pinned, eContainer) {
    super();
    this.pinned = pinned;
    this.eContainer = eContainer;
  }
  postConstruct() {
    const { ctrlsSvc, dragAndDrop } = this.beans;
    const pinned = this.pinned;
    ctrlsSvc.whenReady(this, (p) => {
      let eSecondaryContainers;
      const eBodyViewport = p.gridBodyCtrl.eBodyViewport;
      switch (pinned) {
        case "left":
          eSecondaryContainers = [
            [eBodyViewport, p.left.eContainer],
            [p.bottomLeft.eContainer],
            [p.topLeft.eContainer]
          ];
          break;
        case "right":
          eSecondaryContainers = [
            [eBodyViewport, p.right.eContainer],
            [p.bottomRight.eContainer],
            [p.topRight.eContainer]
          ];
          break;
        default:
          eSecondaryContainers = [
            [eBodyViewport, p.center.eViewport],
            [p.bottomCenter.eViewport],
            [p.topCenter.eViewport]
          ];
          break;
      }
      this.eSecondaryContainers = eSecondaryContainers;
    });
    this.moveColumnFeature = this.createManagedBean(new MoveColumnFeature(pinned));
    this.bodyDropPivotTarget = this.createManagedBean(new BodyDropPivotTarget(pinned));
    dragAndDrop.addDropTarget(this);
    this.addDestroyFunc(() => dragAndDrop.removeDropTarget(this));
  }
  isInterestedIn(type) {
    return type === 1 || type === 0 && this.gos.get("allowDragFromColumnsToolPanel");
  }
  getSecondaryContainers() {
    return this.eSecondaryContainers;
  }
  getContainer() {
    return this.eContainer;
  }
  getIconName() {
    return this.currentDropListener.getIconName();
  }
  // we want to use the bodyPivotTarget if the user is dragging columns in from the toolPanel
  // and we are in pivot mode, as it has to logic to set pivot/value/group on the columns when
  // dropped into the grid's body.
  isDropColumnInPivotMode(draggingEvent) {
    return this.beans.colModel.isPivotMode() && draggingEvent.dragSource.type === 0;
  }
  onDragEnter(draggingEvent) {
    this.currentDropListener = this.isDropColumnInPivotMode(draggingEvent) ? this.bodyDropPivotTarget : this.moveColumnFeature;
    this.currentDropListener.onDragEnter(draggingEvent);
  }
  onDragLeave(params) {
    this.currentDropListener.onDragLeave(params);
  }
  onDragging(params) {
    this.currentDropListener.onDragging(params);
  }
  onDragStop(params) {
    this.currentDropListener.onDragStop(params);
  }
  onDragCancel() {
    this.currentDropListener.onDragCancel();
  }
};
var ColumnMoveService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "colMoves";
  }
  moveColumnByIndex(fromIndex, toIndex, source2) {
    const gridColumns = this.beans.colModel.getCols();
    if (!gridColumns) {
      return;
    }
    const column2 = gridColumns[fromIndex];
    this.moveColumns([column2], toIndex, source2);
  }
  moveColumns(columnsToMoveKeys, toIndex, source2, finished = true) {
    const { colModel, colAnimation, visibleCols, eventSvc } = this.beans;
    const gridColumns = colModel.getCols();
    if (!gridColumns) {
      return;
    }
    if (toIndex > gridColumns.length - columnsToMoveKeys.length) {
      _warn(30, { toIndex });
      return;
    }
    colAnimation?.start();
    const movedColumns = colModel.getColsForKeys(columnsToMoveKeys);
    if (this.doesMovePassRules(movedColumns, toIndex)) {
      _moveInArray(colModel.getCols(), movedColumns, toIndex);
      visibleCols.refresh(source2);
      eventSvc.dispatchEvent({
        type: "columnMoved",
        columns: movedColumns,
        column: movedColumns.length === 1 ? movedColumns[0] : null,
        toIndex,
        finished,
        source: source2
      });
    }
    colAnimation?.finish();
  }
  doesMovePassRules(columnsToMove, toIndex) {
    const proposedColumnOrder = this.getProposedColumnOrder(columnsToMove, toIndex);
    return this.doesOrderPassRules(proposedColumnOrder);
  }
  doesOrderPassRules(gridOrder) {
    const { colModel, gos } = this.beans;
    if (!doesMovePassMarryChildren(gridOrder, colModel.getColTree())) {
      return false;
    }
    const doesMovePassLockedPositions = (proposedColumnOrder) => {
      const lockPositionToPlacement = (position) => {
        if (!position) {
          return 0;
        }
        return position === "left" || position === true ? -1 : 1;
      };
      const isRtl = gos.get("enableRtl");
      let lastPlacement = isRtl ? 1 : -1;
      let rulePassed = true;
      for (const col of proposedColumnOrder) {
        const placement = lockPositionToPlacement(col.getColDef().lockPosition);
        if (isRtl) {
          if (placement > lastPlacement) {
            rulePassed = false;
          }
        } else if (placement < lastPlacement) {
          rulePassed = false;
        }
        lastPlacement = placement;
      }
      return rulePassed;
    };
    if (!doesMovePassLockedPositions(gridOrder)) {
      return false;
    }
    return true;
  }
  getProposedColumnOrder(columnsToMove, toIndex) {
    const gridColumns = this.beans.colModel.getCols();
    const proposedColumnOrder = gridColumns.slice();
    _moveInArray(proposedColumnOrder, columnsToMove, toIndex);
    return proposedColumnOrder;
  }
  createBodyDropTarget(pinned, dropContainer) {
    return new BodyDropTarget(pinned, dropContainer);
  }
  moveHeader(hDirection, eGui, column2, pinned, bean) {
    const { ctrlsSvc, gos, colModel, visibleCols, focusSvc } = this.beans;
    const rect = eGui.getBoundingClientRect();
    const left2 = rect.left;
    const isGroup = isColumnGroup(column2);
    const width = isGroup ? rect.width : column2.getActualWidth();
    const isLeft = hDirection === "left" !== gos.get("enableRtl");
    const xPosition = normaliseX({
      x: isLeft ? left2 - 20 : left2 + width + 20,
      pinned,
      fromKeyboard: true,
      gos,
      ctrlsSvc
    });
    const headerPosition = focusSvc.focusedHeader;
    attemptMoveColumns({
      allMovingColumns: isGroup ? column2.getLeafColumns() : [column2],
      isFromHeader: true,
      fromLeft: hDirection === "right",
      xPosition,
      pinned,
      fromEnter: false,
      fakeEvent: false,
      gos,
      colModel,
      colMoves: this,
      visibleCols,
      finished: true
    });
    let targetColumn;
    if (isGroup) {
      const displayedLeafColumns = column2.getDisplayedLeafColumns();
      targetColumn = isLeft ? displayedLeafColumns[0] : _last(displayedLeafColumns);
    } else {
      targetColumn = column2;
    }
    ctrlsSvc.getScrollFeature().ensureColumnVisible(targetColumn, "auto");
    if ((!bean.isAlive() || gos.get("ensureDomOrder")) && headerPosition) {
      let restoreFocusColumn;
      if (isGroup) {
        const groupId = column2.getGroupId();
        const leafCols = column2.getLeafColumns();
        if (!leafCols.length) {
          return;
        }
        const parent = leafCols[0].getParent();
        if (!parent) {
          return;
        }
        restoreFocusColumn = findGroupWidthId(parent, groupId);
      } else {
        restoreFocusColumn = column2;
      }
      if (restoreFocusColumn) {
        focusSvc.focusHeaderPosition({
          headerPosition: {
            ...headerPosition,
            column: restoreFocusColumn
          }
        });
      }
    }
  }
  setDragSourceForHeader(eSource, column2, displayName) {
    const { gos, colModel, dragAndDrop, visibleCols } = this.beans;
    let hideColumnOnExit = !gos.get("suppressDragLeaveHidesColumns");
    const isGroup = isColumnGroup(column2);
    const columns2 = isGroup ? column2.getProvidedColumnGroup().getLeafColumns() : [column2];
    const getDragItem = isGroup ? () => createDragItemForGroup(column2, visibleCols.allCols) : () => createDragItem(column2);
    const dragSource = {
      type: 1,
      eElement: eSource,
      getDefaultIconName: () => hideColumnOnExit ? "hide" : "notAllowed",
      getDragItem,
      dragItemName: displayName,
      onDragStarted: () => {
        hideColumnOnExit = !gos.get("suppressDragLeaveHidesColumns");
        setColumnsMoving(columns2, true);
      },
      onDragStopped: () => setColumnsMoving(columns2, false),
      onDragCancelled: () => setColumnsMoving(columns2, false),
      onGridEnter: (dragItem) => {
        if (hideColumnOnExit) {
          const { columns: columns22 = [], visibleState } = dragItem ?? {};
          const hasVisibleState = isGroup ? (col) => !visibleState || visibleState[col.getColId()] : () => true;
          const unlockedColumns = columns22.filter(
            (col) => !col.getColDef().lockVisible && hasVisibleState(col)
          );
          colModel.setColsVisible(unlockedColumns, true, "uiColumnMoved");
        }
      },
      onGridExit: (dragItem) => {
        if (hideColumnOnExit) {
          const unlockedColumns = dragItem?.columns?.filter((col) => !col.getColDef().lockVisible) || [];
          colModel.setColsVisible(unlockedColumns, false, "uiColumnMoved");
        }
      }
    };
    dragAndDrop.addDragSource(dragSource, true);
    return dragSource;
  }
};
function findGroupWidthId(columnGroup, id2) {
  while (columnGroup) {
    if (columnGroup.getGroupId() === id2) {
      return columnGroup;
    }
    columnGroup = columnGroup.getParent();
  }
  return void 0;
}
function createDragItem(column2) {
  const visibleState = {};
  visibleState[column2.getId()] = column2.isVisible();
  return {
    columns: [column2],
    visibleState,
    containerType: column2.pinned
  };
}
function createDragItemForGroup(columnGroup, allCols) {
  const allColumnsOriginalOrder = columnGroup.getProvidedColumnGroup().getLeafColumns();
  const visibleState = {};
  for (const column2 of allColumnsOriginalOrder) {
    visibleState[column2.getId()] = column2.isVisible();
  }
  const allColumnsCurrentOrder = [];
  for (const column2 of allCols) {
    if (allColumnsOriginalOrder.indexOf(column2) >= 0) {
      allColumnsCurrentOrder.push(column2);
      _removeFromArray(allColumnsOriginalOrder, column2);
    }
  }
  for (const column2 of allColumnsOriginalOrder) {
    allColumnsCurrentOrder.push(column2);
  }
  const columnsInSplit = [];
  const columnGroupColumns = columnGroup.getLeafColumns();
  for (const col of allColumnsCurrentOrder) {
    if (columnGroupColumns.indexOf(col) !== -1) {
      columnsInSplit.push(col);
    }
  }
  return {
    columns: allColumnsCurrentOrder,
    columnsInSplit,
    visibleState,
    containerType: columnsInSplit[0]?.pinned
  };
}
var ColumnMoveModule = {
  moduleName: "ColumnMove",
  version: VERSION,
  beans: [ColumnMoveService, ColumnAnimationService],
  apiFunctions: {
    moveColumnByIndex,
    moveColumns
  },
  dependsOn: [SharedDragAndDropModule],
  css: [columnMovingCSS]
};
var AutoWidthCalculator = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "autoWidthCalc";
  }
  postConstruct() {
    this.beans.ctrlsSvc.whenReady(this, (p) => {
      this.centerRowContainerCtrl = p.center;
    });
  }
  // this is the trick: we create a dummy container and clone all the cells
  // into the dummy, then check the dummy's width. then destroy the dummy
  // as we don't need it any more.
  // drawback: only the cells visible on the screen are considered
  getPreferredWidthForColumn(column2, skipHeader) {
    const eHeaderCell = this.getHeaderCellForColumn(column2);
    if (!eHeaderCell) {
      return -1;
    }
    const elements = this.beans.rowRenderer.getAllCellsNotSpanningForColumn(column2);
    if (!skipHeader) {
      elements.push(eHeaderCell);
    }
    return this.getPreferredWidthForElements(elements);
  }
  getPreferredWidthForColumnGroup(columnGroup) {
    const eHeaderCell = this.getHeaderCellForColumn(columnGroup);
    if (!eHeaderCell) {
      return -1;
    }
    return this.getPreferredWidthForElements([eHeaderCell]);
  }
  getPreferredWidthForElements(elements, extraPadding) {
    const eDummyContainer = document.createElement("form");
    eDummyContainer.style.position = "fixed";
    const eBodyContainer = this.centerRowContainerCtrl.eContainer;
    for (const el of elements) {
      this.cloneItemIntoDummy(el, eDummyContainer);
    }
    eBodyContainer.appendChild(eDummyContainer);
    const dummyContainerWidth = eDummyContainer.offsetWidth;
    eDummyContainer.remove();
    extraPadding = extraPadding ?? this.gos.get("autoSizePadding");
    return dummyContainerWidth + extraPadding;
  }
  getHeaderCellForColumn(column2) {
    let element = null;
    for (const container2 of this.beans.ctrlsSvc.getHeaderRowContainerCtrls()) {
      const res = container2.getHtmlElementForColumnHeader(column2);
      if (res != null) {
        element = res;
      }
    }
    return element;
  }
  cloneItemIntoDummy(eCell, eDummyContainer) {
    const eCellClone = eCell.cloneNode(true);
    eCellClone.style.width = "";
    eCellClone.style.position = "static";
    eCellClone.style.left = "";
    const eCloneParent = document.createElement("div");
    const eCloneParentClassList = eCloneParent.classList;
    const isHeader = ["ag-header-cell", "ag-header-group-cell"].some((cls) => eCellClone.classList.contains(cls));
    if (isHeader) {
      eCloneParentClassList.add("ag-header", "ag-header-row");
      eCloneParent.style.position = "static";
    } else {
      eCloneParentClassList.add("ag-row");
    }
    let pointer = eCell.parentElement;
    while (pointer) {
      const isRow = ["ag-header-row", "ag-row"].some((cls) => pointer.classList.contains(cls));
      if (isRow) {
        for (let i2 = 0; i2 < pointer.classList.length; i2++) {
          const item2 = pointer.classList[i2];
          if (item2 != "ag-row-position-absolute") {
            eCloneParentClassList.add(item2);
          }
        }
        break;
      }
      pointer = pointer.parentElement;
    }
    eCloneParent.appendChild(eCellClone);
    eDummyContainer.appendChild(eCloneParent);
  }
};
var AutoWidthModule = {
  moduleName: "AutoWidth",
  version: VERSION,
  beans: [AutoWidthCalculator]
};
function setColumnWidths(beans, columnWidths, finished = true, source2 = "api") {
  beans.colResize?.setColumnWidths(columnWidths, false, finished, source2);
}
var GroupResizeFeature = class extends BeanStub {
  constructor(comp, eResize, pinned, columnGroup) {
    super();
    this.comp = comp;
    this.eResize = eResize;
    this.pinned = pinned;
    this.columnGroup = columnGroup;
  }
  postConstruct() {
    if (!this.columnGroup.isResizable()) {
      this.comp.setResizableDisplayed(false);
      return;
    }
    const { horizontalResizeSvc, gos, colAutosize } = this.beans;
    const finishedWithResizeFunc = horizontalResizeSvc.addResizeBar({
      eResizeBar: this.eResize,
      onResizeStart: this.onResizeStart.bind(this),
      onResizing: this.onResizing.bind(this, false),
      onResizeEnd: this.onResizing.bind(this, true)
    });
    this.addDestroyFunc(finishedWithResizeFunc);
    if (!gos.get("suppressAutoSize") && colAutosize) {
      this.addDestroyFunc(
        colAutosize.addColumnGroupResize(
          this.eResize,
          this.columnGroup,
          () => this.resizeLeafColumnsToFit("uiColumnResized")
        )
      );
    }
  }
  onResizeStart(shiftKey) {
    const {
      columnsToResize,
      resizeStartWidth,
      resizeRatios,
      groupAfterColumns,
      groupAfterStartWidth,
      groupAfterRatios
    } = this.getInitialValues(shiftKey);
    this.resizeCols = columnsToResize;
    this.resizeStartWidth = resizeStartWidth;
    this.resizeRatios = resizeRatios;
    this.resizeTakeFromCols = groupAfterColumns;
    this.resizeTakeFromStartWidth = groupAfterStartWidth;
    this.resizeTakeFromRatios = groupAfterRatios;
    this.toggleColumnResizing(true);
  }
  onResizing(finished, resizeAmount, source2 = "uiColumnResized") {
    const resizeAmountNormalised = this.normaliseDragChange(resizeAmount);
    const width = this.resizeStartWidth + resizeAmountNormalised;
    this.resizeColumnsFromLocalValues(width, source2, finished);
  }
  getInitialValues(shiftKey) {
    const getInitialSizeOfColumns = (columns2) => columns2.reduce((totalWidth, column2) => totalWidth + column2.getActualWidth(), 0);
    const getSizeRatiosOfColumns = (columns2, initialSizeOfColumns) => columns2.map((column2) => column2.getActualWidth() / initialSizeOfColumns);
    const columnsToResize = this.getColumnsToResize();
    const resizeStartWidth = getInitialSizeOfColumns(columnsToResize);
    const resizeRatios = getSizeRatiosOfColumns(columnsToResize, resizeStartWidth);
    const columnSizeAndRatios = {
      columnsToResize,
      resizeStartWidth,
      resizeRatios
    };
    let groupAfter = null;
    if (shiftKey) {
      groupAfter = this.beans.colGroupSvc?.getGroupAtDirection(this.columnGroup, "After") ?? null;
    }
    if (groupAfter) {
      const takeFromLeafCols = groupAfter.getDisplayedLeafColumns();
      const groupAfterColumns = columnSizeAndRatios.groupAfterColumns = takeFromLeafCols.filter(
        (col) => col.isResizable()
      );
      const groupAfterStartWidth = columnSizeAndRatios.groupAfterStartWidth = getInitialSizeOfColumns(groupAfterColumns);
      columnSizeAndRatios.groupAfterRatios = getSizeRatiosOfColumns(groupAfterColumns, groupAfterStartWidth);
    } else {
      columnSizeAndRatios.groupAfterColumns = void 0;
      columnSizeAndRatios.groupAfterStartWidth = void 0;
      columnSizeAndRatios.groupAfterRatios = void 0;
    }
    return columnSizeAndRatios;
  }
  resizeLeafColumnsToFit(source2) {
    const preferredSize = this.beans.autoWidthCalc.getPreferredWidthForColumnGroup(this.columnGroup);
    const initialValues = this.getInitialValues();
    if (preferredSize > initialValues.resizeStartWidth) {
      this.resizeColumns(initialValues, preferredSize, source2, true);
    }
  }
  resizeColumnsFromLocalValues(totalWidth, source2, finished = true) {
    if (!this.resizeCols || !this.resizeRatios) {
      return;
    }
    const initialValues = {
      columnsToResize: this.resizeCols,
      resizeStartWidth: this.resizeStartWidth,
      resizeRatios: this.resizeRatios,
      groupAfterColumns: this.resizeTakeFromCols,
      groupAfterStartWidth: this.resizeTakeFromStartWidth,
      groupAfterRatios: this.resizeTakeFromRatios
    };
    this.resizeColumns(initialValues, totalWidth, source2, finished);
  }
  resizeColumns(initialValues, totalWidth, source2, finished = true) {
    const {
      columnsToResize,
      resizeStartWidth,
      resizeRatios,
      groupAfterColumns,
      groupAfterStartWidth,
      groupAfterRatios
    } = initialValues;
    const resizeSets = [];
    resizeSets.push({
      columns: columnsToResize,
      ratios: resizeRatios,
      width: totalWidth
    });
    if (groupAfterColumns) {
      const diff2 = totalWidth - resizeStartWidth;
      resizeSets.push({
        columns: groupAfterColumns,
        ratios: groupAfterRatios,
        width: groupAfterStartWidth - diff2
      });
    }
    this.beans.colResize?.resizeColumnSets({
      resizeSets,
      finished,
      source: source2
    });
    if (finished) {
      this.toggleColumnResizing(false);
    }
  }
  toggleColumnResizing(resizing) {
    this.comp.toggleCss("ag-column-resizing", resizing);
  }
  getColumnsToResize() {
    const leafCols = this.columnGroup.getDisplayedLeafColumns();
    return leafCols.filter((col) => col.isResizable());
  }
  // optionally inverts the drag, depending on pinned and RTL
  // note - this method is duplicated in RenderedHeaderCell - should refactor out?
  normaliseDragChange(dragChange) {
    let result2 = dragChange;
    if (this.gos.get("enableRtl")) {
      if (this.pinned !== "left") {
        result2 *= -1;
      }
    } else if (this.pinned === "right") {
      result2 *= -1;
    }
    return result2;
  }
  destroy() {
    super.destroy();
    this.resizeCols = void 0;
    this.resizeRatios = void 0;
    this.resizeTakeFromCols = void 0;
    this.resizeTakeFromRatios = void 0;
  }
};
var ResizeFeature = class extends BeanStub {
  constructor(pinned, column2, eResize, comp, ctrl) {
    super();
    this.pinned = pinned;
    this.column = column2;
    this.eResize = eResize;
    this.comp = comp;
    this.ctrl = ctrl;
  }
  postConstruct() {
    const destroyResizeFuncs = [];
    let canResize;
    let canAutosize;
    const addResize = () => {
      _setDisplayed(this.eResize, canResize);
      if (!canResize) {
        return;
      }
      const { horizontalResizeSvc, colAutosize } = this.beans;
      const finishedWithResizeFunc = horizontalResizeSvc.addResizeBar({
        eResizeBar: this.eResize,
        onResizeStart: this.onResizeStart.bind(this),
        onResizing: this.onResizing.bind(this, false),
        onResizeEnd: this.onResizing.bind(this, true)
      });
      destroyResizeFuncs.push(finishedWithResizeFunc);
      if (canAutosize && colAutosize) {
        destroyResizeFuncs.push(colAutosize.addColumnAutosizeListeners(this.eResize, this.column));
      }
    };
    const removeResize = () => {
      for (const f of destroyResizeFuncs) {
        f();
      }
      destroyResizeFuncs.length = 0;
    };
    const refresh = () => {
      const resize2 = this.column.isResizable();
      const autoSize = !this.gos.get("suppressAutoSize") && !this.column.getColDef().suppressAutoSize;
      const propertyChange = resize2 !== canResize || autoSize !== canAutosize;
      if (propertyChange) {
        canResize = resize2;
        canAutosize = autoSize;
        removeResize();
        addResize();
      }
    };
    refresh();
    this.addDestroyFunc(removeResize);
    this.ctrl.setRefreshFunction("resize", refresh);
  }
  onResizing(finished, resizeAmount) {
    const { column: key2, lastResizeAmount, resizeStartWidth, beans } = this;
    const resizeAmountNormalised = this.normaliseResizeAmount(resizeAmount);
    const newWidth = resizeStartWidth + resizeAmountNormalised;
    const columnWidths = [{ key: key2, newWidth }];
    const { pinnedCols, ctrlsSvc, colResize } = beans;
    if (this.column.getPinned()) {
      const leftWidth = pinnedCols?.leftWidth ?? 0;
      const rightWidth = pinnedCols?.rightWidth ?? 0;
      const bodyWidth = _getInnerWidth(ctrlsSvc.getGridBodyCtrl().eBodyViewport) - 50;
      if (leftWidth + rightWidth + (resizeAmountNormalised - lastResizeAmount) > bodyWidth) {
        return;
      }
    }
    this.lastResizeAmount = resizeAmountNormalised;
    colResize?.setColumnWidths(columnWidths, this.resizeWithShiftKey, finished, "uiColumnResized");
    if (finished) {
      this.toggleColumnResizing(false);
    }
  }
  onResizeStart(shiftKey) {
    this.resizeStartWidth = this.column.getActualWidth();
    this.lastResizeAmount = 0;
    this.resizeWithShiftKey = shiftKey;
    this.toggleColumnResizing(true);
  }
  toggleColumnResizing(resizing) {
    this.column.resizing = resizing;
    this.comp.toggleCss("ag-column-resizing", resizing);
  }
  // optionally inverts the drag, depending on pinned and RTL
  // note - this method is duplicated in RenderedHeaderGroupCell - should refactor out?
  normaliseResizeAmount(dragChange) {
    let result2 = dragChange;
    const notPinningLeft = this.pinned !== "left";
    const pinningRight = this.pinned === "right";
    if (this.gos.get("enableRtl")) {
      if (notPinningLeft) {
        result2 *= -1;
      }
    } else if (pinningRight) {
      result2 *= -1;
    }
    return result2;
  }
};
var ColumnResizeService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "colResize";
  }
  setColumnWidths(columnWidths, shiftKey, finished, source2) {
    const sets = [];
    const { colModel, gos, visibleCols } = this.beans;
    for (const columnWidth of columnWidths) {
      const col = colModel.getColDefCol(columnWidth.key) || colModel.getCol(columnWidth.key);
      if (!col) {
        continue;
      }
      sets.push({
        width: columnWidth.newWidth,
        ratios: [1],
        columns: [col]
      });
      const defaultIsShift = gos.get("colResizeDefault") === "shift";
      if (defaultIsShift) {
        shiftKey = !shiftKey;
      }
      if (shiftKey) {
        const otherCol = visibleCols.getColAfter(col);
        if (!otherCol) {
          continue;
        }
        const widthDiff = col.getActualWidth() - columnWidth.newWidth;
        const otherColWidth = otherCol.getActualWidth() + widthDiff;
        sets.push({
          width: otherColWidth,
          ratios: [1],
          columns: [otherCol]
        });
      }
    }
    if (sets.length === 0) {
      return;
    }
    this.resizeColumnSets({
      resizeSets: sets,
      finished,
      source: source2
    });
  }
  // method takes sets of columns and resizes them. either all sets will be resized, or nothing
  // be resized. this is used for example when user tries to resize a group and holds shift key,
  // then both the current group (grows), and the adjacent group (shrinks), will get resized,
  // so that's two sets for this method.
  resizeColumnSets(params) {
    const { resizeSets, finished, source: source2 } = params;
    const passMinMaxCheck = !resizeSets || resizeSets.every((columnResizeSet) => checkMinAndMaxWidthsForSet(columnResizeSet));
    if (!passMinMaxCheck) {
      if (finished) {
        const columns2 = resizeSets && resizeSets.length > 0 ? resizeSets[0].columns : null;
        dispatchColumnResizedEvent(this.eventSvc, columns2, finished, source2);
      }
      return;
    }
    const changedCols = [];
    const allResizedCols = [];
    for (const set3 of resizeSets) {
      const { width, columns: columns2, ratios } = set3;
      const newWidths = {};
      const finishedCols = {};
      for (const col of columns2) {
        allResizedCols.push(col);
      }
      let finishedColsGrew = true;
      let loopCount = 0;
      while (finishedColsGrew) {
        loopCount++;
        if (loopCount > 1e3) {
          _error(31);
          break;
        }
        finishedColsGrew = false;
        const subsetCols = [];
        let subsetRatioTotal = 0;
        let pixelsToDistribute = width;
        columns2.forEach((col, index) => {
          const thisColFinished = finishedCols[col.getId()];
          if (thisColFinished) {
            pixelsToDistribute -= newWidths[col.getId()];
          } else {
            subsetCols.push(col);
            const ratioThisCol = ratios[index];
            subsetRatioTotal += ratioThisCol;
          }
        });
        const ratioScale = 1 / subsetRatioTotal;
        subsetCols.forEach((col, index) => {
          const lastCol = index === subsetCols.length - 1;
          let colNewWidth;
          if (lastCol) {
            colNewWidth = pixelsToDistribute;
          } else {
            colNewWidth = Math.round(ratios[index] * width * ratioScale);
            pixelsToDistribute -= colNewWidth;
          }
          const minWidth = col.getMinWidth();
          const maxWidth = col.getMaxWidth();
          if (colNewWidth < minWidth) {
            colNewWidth = minWidth;
            finishedCols[col.getId()] = true;
            finishedColsGrew = true;
          } else if (maxWidth > 0 && colNewWidth > maxWidth) {
            colNewWidth = maxWidth;
            finishedCols[col.getId()] = true;
            finishedColsGrew = true;
          }
          newWidths[col.getId()] = colNewWidth;
        });
      }
      for (const col of columns2) {
        const newWidth = newWidths[col.getId()];
        const actualWidth = col.getActualWidth();
        if (actualWidth !== newWidth) {
          col.setActualWidth(newWidth, source2);
          changedCols.push(col);
        }
      }
    }
    const atLeastOneColChanged = changedCols.length > 0;
    let flexedCols = [];
    if (atLeastOneColChanged) {
      const { colFlex, visibleCols, colViewport } = this.beans;
      flexedCols = colFlex?.refreshFlexedColumns({
        resizingCols: allResizedCols,
        skipSetLeft: true
      }) ?? [];
      visibleCols.setLeftValues(source2);
      visibleCols.updateBodyWidths();
      colViewport.checkViewportColumns();
    }
    const colsForEvent = allResizedCols.concat(flexedCols);
    if (atLeastOneColChanged || finished) {
      dispatchColumnResizedEvent(this.eventSvc, colsForEvent, finished, source2, flexedCols);
    }
  }
  resizeHeader(column2, delta, shiftKey) {
    if (!column2.isResizable()) {
      return;
    }
    const actualWidth = column2.getActualWidth();
    const minWidth = column2.getMinWidth();
    const maxWidth = column2.getMaxWidth();
    const newWidth = Math.min(Math.max(actualWidth + delta, minWidth), maxWidth);
    this.setColumnWidths([{ key: column2, newWidth }], shiftKey, true, "uiColumnResized");
  }
  createResizeFeature(pinned, column2, eResize, comp, ctrl) {
    return new ResizeFeature(pinned, column2, eResize, comp, ctrl);
  }
  createGroupResizeFeature(comp, eResize, pinned, columnGroup) {
    return new GroupResizeFeature(comp, eResize, pinned, columnGroup);
  }
};
function checkMinAndMaxWidthsForSet(columnResizeSet) {
  const { columns: columns2, width } = columnResizeSet;
  let minWidthAccumulated = 0;
  let maxWidthAccumulated = 0;
  let maxWidthActive = true;
  for (const col of columns2) {
    const minWidth = col.getMinWidth();
    minWidthAccumulated += minWidth || 0;
    const maxWidth = col.getMaxWidth();
    if (maxWidth > 0) {
      maxWidthAccumulated += maxWidth;
    } else {
      maxWidthActive = false;
    }
  }
  const minWidthPasses = width >= minWidthAccumulated;
  const maxWidthPasses = !maxWidthActive || width <= maxWidthAccumulated;
  return minWidthPasses && maxWidthPasses;
}
var ColumnResizeModule = {
  moduleName: "ColumnResize",
  version: VERSION,
  beans: [ColumnResizeService],
  apiFunctions: {
    setColumnWidths
  },
  dependsOn: [HorizontalResizeModule, AutoWidthModule]
};
var GroupWidthFeature = class extends BeanStub {
  constructor(comp, columnGroup) {
    super();
    this.removeChildListenersFuncs = [];
    this.columnGroup = columnGroup;
    this.comp = comp;
  }
  postConstruct() {
    this.addListenersToChildrenColumns();
    this.addManagedListeners(this.columnGroup, {
      displayedChildrenChanged: this.onDisplayedChildrenChanged.bind(this)
    });
    this.onWidthChanged();
    this.addDestroyFunc(this.removeListenersOnChildrenColumns.bind(this));
  }
  addListenersToChildrenColumns() {
    this.removeListenersOnChildrenColumns();
    const widthChangedListener = this.onWidthChanged.bind(this);
    for (const column2 of this.columnGroup.getLeafColumns()) {
      column2.__addEventListener("widthChanged", widthChangedListener);
      column2.__addEventListener("visibleChanged", widthChangedListener);
      this.removeChildListenersFuncs.push(() => {
        column2.__removeEventListener("widthChanged", widthChangedListener);
        column2.__removeEventListener("visibleChanged", widthChangedListener);
      });
    }
  }
  removeListenersOnChildrenColumns() {
    for (const func2 of this.removeChildListenersFuncs) {
      func2();
    }
    this.removeChildListenersFuncs = [];
  }
  onDisplayedChildrenChanged() {
    this.addListenersToChildrenColumns();
    this.onWidthChanged();
  }
  onWidthChanged() {
    const columnWidth = this.columnGroup.getActualWidth();
    this.comp.setWidth(`${columnWidth}px`);
    this.comp.toggleCss("ag-hidden", columnWidth === 0);
  }
};
var HeaderGroupCellCtrl = class extends AbstractHeaderCellCtrl {
  constructor() {
    super(...arguments);
    this.onSuppressColMoveChange = () => {
      if (!this.isAlive() || this.isSuppressMoving()) {
        this.removeDragSource();
      } else if (!this.dragSource) {
        this.setDragSource(this.eGui);
      }
    };
  }
  wireComp(comp, eGui, eResize, eHeaderCompWrapper, compBean) {
    const { column: column2, beans } = this;
    const { context, colNames, colHover, rangeSvc, colResize } = beans;
    this.comp = comp;
    compBean = setupCompBean(this, context, compBean);
    this.setGui(eGui, compBean);
    this.displayName = colNames.getDisplayNameForColumnGroup(column2, "header");
    this.refreshHeaderStyles();
    this.addClasses();
    this.setupMovingCss(compBean);
    this.setupExpandable(compBean);
    this.setupTooltip();
    this.setupAutoHeight({
      wrapperElement: eHeaderCompWrapper,
      compBean
    });
    this.setupUserComp();
    this.addHeaderMouseListeners(compBean);
    this.addManagedPropertyListener("groupHeaderHeight", this.refreshMaxHeaderHeight.bind(this));
    this.refreshMaxHeaderHeight();
    const pinned = this.rowCtrl.pinned;
    const leafCols = column2.getProvidedColumnGroup().getLeafColumns();
    colHover?.createHoverFeature(compBean, leafCols, eGui);
    rangeSvc?.createRangeHighlightFeature(compBean, column2, comp);
    compBean.createManagedBean(new SetLeftFeature(column2, eGui, beans));
    compBean.createManagedBean(new GroupWidthFeature(comp, column2));
    if (colResize) {
      this.resizeFeature = compBean.createManagedBean(
        colResize.createGroupResizeFeature(comp, eResize, pinned, column2)
      );
    } else {
      comp.setResizableDisplayed(false);
    }
    compBean.createManagedBean(
      new ManagedFocusFeature(eGui, {
        shouldStopEventPropagation: this.shouldStopEventPropagation.bind(this),
        onTabKeyDown: () => void 0,
        handleKeyDown: this.handleKeyDown.bind(this),
        onFocusIn: this.onFocusIn.bind(this)
      })
    );
    this.addHighlightListeners(compBean, leafCols);
    compBean.addManagedPropertyListener("suppressMovableColumns", this.onSuppressColMoveChange);
    this.addResizeAndMoveKeyboardListeners(compBean);
    compBean.addDestroyFunc(() => this.clearComponent());
  }
  getHeaderClassParams() {
    const { column: column2, beans } = this;
    const colDef = column2.getDefinition();
    return _addGridCommonParams(beans.gos, {
      colDef,
      columnGroup: column2,
      floatingFilter: false
    });
  }
  refreshMaxHeaderHeight() {
    const { gos, comp } = this;
    const groupHeaderHeight = gos.get("groupHeaderHeight");
    if (groupHeaderHeight != null) {
      if (groupHeaderHeight === 0) {
        comp.setHeaderWrapperHidden(true);
      } else {
        comp.setHeaderWrapperMaxHeight(groupHeaderHeight);
      }
    } else {
      comp.setHeaderWrapperHidden(false);
      comp.setHeaderWrapperMaxHeight(null);
    }
  }
  addHighlightListeners(compBean, columns2) {
    if (!this.beans.gos.get("suppressMoveWhenColumnDragging")) {
      return;
    }
    for (const column2 of columns2) {
      compBean.addManagedListeners(column2, {
        headerHighlightChanged: this.onLeafColumnHighlightChanged.bind(this, column2)
      });
    }
  }
  onLeafColumnHighlightChanged(column2) {
    const displayedColumns = this.column.getDisplayedLeafColumns();
    const isFirst = displayedColumns[0] === column2;
    const isLast = _last(displayedColumns) === column2;
    if (!isFirst && !isLast) {
      return;
    }
    const highlighted = column2.getHighlighted();
    const isColumnMoveAtThisLevel = !!this.rowCtrl.getHeaderCellCtrls().find((ctrl) => {
      return ctrl.column.isMoving();
    });
    let beforeOn = false;
    let afterOn = false;
    if (isColumnMoveAtThisLevel) {
      const isRtl = this.beans.gos.get("enableRtl");
      const isHighlightAfter = highlighted === 1;
      const isHighlightBefore = highlighted === 0;
      if (isFirst) {
        if (isRtl) {
          afterOn = isHighlightAfter;
        } else {
          beforeOn = isHighlightBefore;
        }
      }
      if (isLast) {
        if (isRtl) {
          beforeOn = isHighlightBefore;
        } else {
          afterOn = isHighlightAfter;
        }
      }
    }
    this.comp.toggleCss("ag-header-highlight-before", beforeOn);
    this.comp.toggleCss("ag-header-highlight-after", afterOn);
  }
  resizeHeader(delta, shiftKey) {
    const { resizeFeature } = this;
    if (!resizeFeature) {
      return;
    }
    const initialValues = resizeFeature.getInitialValues(shiftKey);
    resizeFeature.resizeColumns(initialValues, initialValues.resizeStartWidth + delta, "uiColumnResized", true);
  }
  resizeLeafColumnsToFit(source2) {
    this.resizeFeature?.resizeLeafColumnsToFit(source2);
  }
  setupUserComp() {
    const { colGroupSvc, userCompFactory, gos, enterpriseMenuFactory } = this.beans;
    const columnGroup = this.column;
    const providedColumnGroup = columnGroup.getProvidedColumnGroup();
    const params = _addGridCommonParams(gos, {
      displayName: this.displayName,
      columnGroup,
      setExpanded: (expanded) => {
        colGroupSvc.setColumnGroupOpened(providedColumnGroup, expanded, "gridInitializing");
      },
      setTooltip: (value2, shouldDisplayTooltip) => {
        gos.assertModuleRegistered("Tooltip", 3);
        this.setupTooltip(value2, shouldDisplayTooltip);
      },
      showColumnMenu: (buttonElement, onClosedCallback) => enterpriseMenuFactory?.showMenuAfterButtonClick(
        providedColumnGroup,
        buttonElement,
        "columnMenu",
        onClosedCallback
      ),
      showColumnMenuAfterMouseClick: (mouseEvent, onClosedCallback) => enterpriseMenuFactory?.showMenuAfterMouseEvent(
        providedColumnGroup,
        mouseEvent,
        "columnMenu",
        onClosedCallback
      ),
      eGridHeader: this.eGui
    });
    const compDetails = _getHeaderGroupCompDetails(userCompFactory, params);
    if (compDetails) {
      this.comp.setUserCompDetails(compDetails);
    }
  }
  addHeaderMouseListeners(compBean) {
    const listener = (e) => this.handleMouseOverChange(e.type === "mouseenter");
    const clickListener = () => this.dispatchColumnMouseEvent("columnHeaderClicked", this.column.getProvidedColumnGroup());
    const contextMenuListener = (event) => this.handleContextMenuMouseEvent(event, void 0, this.column.getProvidedColumnGroup());
    compBean.addManagedListeners(this.eGui, {
      mouseenter: listener,
      mouseleave: listener,
      click: clickListener,
      contextmenu: contextMenuListener
    });
  }
  handleMouseOverChange(isMouseOver) {
    this.eventSvc.dispatchEvent({
      type: isMouseOver ? "columnHeaderMouseOver" : "columnHeaderMouseLeave",
      column: this.column.getProvidedColumnGroup()
    });
  }
  setupTooltip(value2, shouldDisplayTooltip) {
    this.tooltipFeature = this.beans.tooltipSvc?.setupHeaderGroupTooltip(
      this.tooltipFeature,
      this,
      value2,
      shouldDisplayTooltip
    );
  }
  setupExpandable(compBean) {
    const providedColGroup = this.column.getProvidedColumnGroup();
    this.refreshExpanded();
    const listener = this.refreshExpanded.bind(this);
    compBean.addManagedListeners(providedColGroup, {
      expandedChanged: listener,
      expandableChanged: listener
    });
  }
  refreshExpanded() {
    const { column: column2 } = this;
    this.expandable = column2.isExpandable();
    const expanded = column2.isExpanded();
    if (this.expandable) {
      this.comp.setAriaExpanded(expanded ? "true" : "false");
    } else {
      this.comp.setAriaExpanded(void 0);
    }
    this.refreshHeaderStyles();
  }
  addClasses() {
    const { column: column2 } = this;
    const colGroupDef = column2.getColGroupDef();
    const classes = _getHeaderClassesFromColDef(colGroupDef, this.gos, null, column2);
    if (column2.isPadding()) {
      classes.push("ag-header-group-cell-no-group");
      const leafCols = column2.getLeafColumns();
      if (leafCols.every((col) => col.isSpanHeaderHeight())) {
        classes.push("ag-header-span-height");
      }
    } else {
      classes.push("ag-header-group-cell-with-group");
      if (colGroupDef?.wrapHeaderText) {
        classes.push("ag-header-cell-wrap-text");
      }
    }
    for (const c2 of classes) {
      this.comp.toggleCss(c2, true);
    }
  }
  setupMovingCss(compBean) {
    const { column: column2 } = this;
    const providedColumnGroup = column2.getProvidedColumnGroup();
    const leafColumns = providedColumnGroup.getLeafColumns();
    const listener = () => this.comp.toggleCss("ag-header-cell-moving", column2.isMoving());
    for (const col of leafColumns) {
      compBean.addManagedListeners(col, { movingChanged: listener });
    }
    listener();
  }
  onFocusIn(e) {
    if (!this.eGui.contains(e.relatedTarget)) {
      this.focusThis();
    }
  }
  handleKeyDown(e) {
    super.handleKeyDown(e);
    const wrapperHasFocus = this.getWrapperHasFocus();
    if (!this.expandable || !wrapperHasFocus) {
      return;
    }
    if (e.key === KeyCode.ENTER) {
      const column2 = this.column;
      const newExpandedValue = !column2.isExpanded();
      this.beans.colGroupSvc.setColumnGroupOpened(
        column2.getProvidedColumnGroup(),
        newExpandedValue,
        "uiColumnExpanded"
      );
    }
  }
  // unlike columns, this will only get called once, as we don't react on props on column groups
  // (we will always destroy and recreate this comp if something changes)
  setDragSource(eHeaderGroup) {
    if (!this.isAlive() || this.isSuppressMoving()) {
      return;
    }
    this.removeDragSource();
    if (!eHeaderGroup) {
      return;
    }
    this.dragSource = this.beans.colMoves?.setDragSourceForHeader(eHeaderGroup, this.column, this.displayName) ?? null;
  }
  isSuppressMoving() {
    return this.gos.get("suppressMovableColumns") || this.column.getLeafColumns().some((column2) => column2.getColDef().suppressMovable || column2.getColDef().lockPosition);
  }
  destroy() {
    this.tooltipFeature = this.destroyBean(this.tooltipFeature);
    super.destroy();
  }
};
function setColumnGroupOpened(beans, group, newValue) {
  beans.colGroupSvc?.setColumnGroupOpened(group, newValue, "api");
}
function getColumnGroup(beans, name2, instanceId) {
  return beans.colGroupSvc?.getColumnGroup(name2, instanceId) ?? null;
}
function getProvidedColumnGroup(beans, name2) {
  return beans.colGroupSvc?.getProvidedColGroup(name2) ?? null;
}
function getDisplayNameForColumnGroup(beans, columnGroup, location) {
  return beans.colNames.getDisplayNameForColumnGroup(columnGroup, location) || "";
}
function getColumnGroupState(beans) {
  return beans.colGroupSvc?.getColumnGroupState() ?? [];
}
function setColumnGroupState(beans, stateItems) {
  beans.colGroupSvc?.setColumnGroupState(stateItems, "api");
}
function resetColumnGroupState(beans) {
  beans.colGroupSvc?.resetColumnGroupState("api");
}
function getLeftDisplayedColumnGroups(beans) {
  return beans.visibleCols.treeLeft;
}
function getCenterDisplayedColumnGroups(beans) {
  return beans.visibleCols.treeCenter;
}
function getRightDisplayedColumnGroups(beans) {
  return beans.visibleCols.treeRight;
}
function getAllDisplayedColumnGroups(beans) {
  return beans.visibleCols.getAllTrees();
}
function _removeAllFromUnorderedArray(array2, toRemove) {
  for (let i2 = 0; i2 < toRemove.length; i2++) {
    const index = array2.indexOf(toRemove[i2]);
    if (index >= 0) {
      array2[index] = array2[array2.length - 1];
      array2.pop();
    }
  }
}
var VisibleColsService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "visibleCols";
    this.colsAndGroupsMap = {};
    this.leftCols = [];
    this.rightCols = [];
    this.centerCols = [];
    this.allCols = [];
    this.headerGroupRowCount = 0;
    this.bodyWidth = 0;
    this.leftWidth = 0;
    this.rightWidth = 0;
    this.isBodyWidthDirty = true;
  }
  refresh(source2, skipTreeBuild = false) {
    const { colFlex, colModel, colGroupSvc, colViewport, selectionColSvc } = this.beans;
    if (!skipTreeBuild) {
      this.buildTrees(colModel, colGroupSvc);
    }
    colGroupSvc?.updateOpenClosedVisibility();
    this.leftCols = pickDisplayedCols(this.treeLeft);
    this.centerCols = pickDisplayedCols(this.treeCenter);
    this.rightCols = pickDisplayedCols(this.treeRight);
    selectionColSvc?.refreshVisibility(this.leftCols, this.centerCols, this.rightCols);
    this.joinColsAriaOrder(colModel);
    this.joinCols();
    this.headerGroupRowCount = this.getHeaderRowCount();
    this.setLeftValues(source2);
    this.autoHeightCols = this.allCols.filter((col) => col.isAutoHeight());
    colFlex?.refreshFlexedColumns();
    this.updateBodyWidths();
    this.setFirstRightAndLastLeftPinned(colModel, this.leftCols, this.rightCols, source2);
    colViewport.checkViewportColumns(false);
    this.eventSvc.dispatchEvent({
      type: "displayedColumnsChanged",
      source: source2
    });
  }
  getHeaderRowCount() {
    if (!this.gos.get("hidePaddedHeaderRows")) {
      return this.beans.colModel.cols.treeDepth;
    }
    let headerGroupRowCount = 0;
    for (const col of this.allCols) {
      let parent = col.getParent();
      while (parent) {
        if (!parent.isPadding()) {
          const level = parent.getProvidedColumnGroup().getLevel() + 1;
          if (level > headerGroupRowCount) {
            headerGroupRowCount = level;
          }
          break;
        }
        parent = parent.getParent();
      }
    }
    return headerGroupRowCount;
  }
  // after setColumnWidth or updateGroupsAndPresentedCols
  updateBodyWidths() {
    const newBodyWidth = getWidthOfColsInList(this.centerCols);
    const newLeftWidth = getWidthOfColsInList(this.leftCols);
    const newRightWidth = getWidthOfColsInList(this.rightCols);
    this.isBodyWidthDirty = this.bodyWidth !== newBodyWidth;
    const atLeastOneChanged = this.bodyWidth !== newBodyWidth || this.leftWidth !== newLeftWidth || this.rightWidth !== newRightWidth;
    if (atLeastOneChanged) {
      this.bodyWidth = newBodyWidth;
      this.leftWidth = newLeftWidth;
      this.rightWidth = newRightWidth;
      this.eventSvc.dispatchEvent({
        type: "columnContainerWidthChanged"
      });
      this.eventSvc.dispatchEvent({
        type: "displayedColumnsWidthChanged"
      });
    }
  }
  // sets the left pixel position of each column
  setLeftValues(source2) {
    this.setLeftValuesOfCols(source2);
    this.setLeftValuesOfGroups();
  }
  setFirstRightAndLastLeftPinned(colModel, leftCols, rightCols, source2) {
    let lastLeft;
    let firstRight;
    if (this.gos.get("enableRtl")) {
      lastLeft = leftCols ? leftCols[0] : null;
      firstRight = rightCols ? _last(rightCols) : null;
    } else {
      lastLeft = leftCols ? _last(leftCols) : null;
      firstRight = rightCols ? rightCols[0] : null;
    }
    for (const col of colModel.getCols()) {
      col.setLastLeftPinned(col === lastLeft, source2);
      col.setFirstRightPinned(col === firstRight, source2);
    }
  }
  buildTrees(colModel, columnGroupSvc) {
    const cols = colModel.getColsToShow();
    const leftCols = cols.filter((col) => col.getPinned() == "left");
    const rightCols = cols.filter((col) => col.getPinned() == "right");
    const centerCols = cols.filter((col) => col.getPinned() != "left" && col.getPinned() != "right");
    const idCreator = new GroupInstanceIdCreator();
    const createGroups2 = (params) => {
      return columnGroupSvc ? columnGroupSvc.createColumnGroups(params) : params.columns;
    };
    this.treeLeft = createGroups2({
      columns: leftCols,
      idCreator,
      pinned: "left",
      oldDisplayedGroups: this.treeLeft
    });
    this.treeRight = createGroups2({
      columns: rightCols,
      idCreator,
      pinned: "right",
      oldDisplayedGroups: this.treeRight
    });
    this.treeCenter = createGroups2({
      columns: centerCols,
      idCreator,
      pinned: null,
      oldDisplayedGroups: this.treeCenter
    });
    this.updateColsAndGroupsMap();
  }
  clear() {
    this.leftCols = [];
    this.rightCols = [];
    this.centerCols = [];
    this.allCols = [];
    this.ariaOrderColumns = [];
  }
  joinColsAriaOrder(colModel) {
    const allColumns = colModel.getCols();
    const pinnedLeft = [];
    const center2 = [];
    const pinnedRight = [];
    for (const col of allColumns) {
      const pinned = col.getPinned();
      if (!pinned) {
        center2.push(col);
      } else if (pinned === true || pinned === "left") {
        pinnedLeft.push(col);
      } else {
        pinnedRight.push(col);
      }
    }
    this.ariaOrderColumns = pinnedLeft.concat(center2).concat(pinnedRight);
  }
  getAriaColIndex(colOrGroup) {
    let col;
    if (isColumnGroup(colOrGroup)) {
      col = colOrGroup.getLeafColumns()[0];
    } else {
      col = colOrGroup;
    }
    return this.ariaOrderColumns.indexOf(col) + 1;
  }
  setLeftValuesOfGroups() {
    for (const columns2 of [this.treeLeft, this.treeRight, this.treeCenter]) {
      for (const column2 of columns2) {
        if (isColumnGroup(column2)) {
          const columnGroup = column2;
          columnGroup.checkLeft();
        }
      }
    }
  }
  setLeftValuesOfCols(source2) {
    const { colModel } = this.beans;
    const primaryCols = colModel.getColDefCols();
    if (!primaryCols) {
      return;
    }
    const allColumns = colModel.getCols().slice(0);
    const doingRtl = this.gos.get("enableRtl");
    for (const columns2 of [this.leftCols, this.rightCols, this.centerCols]) {
      if (doingRtl) {
        let left2 = getWidthOfColsInList(columns2);
        for (const column2 of columns2) {
          left2 -= column2.getActualWidth();
          column2.setLeft(left2, source2);
        }
      } else {
        let left2 = 0;
        for (const column2 of columns2) {
          column2.setLeft(left2, source2);
          left2 += column2.getActualWidth();
        }
      }
      _removeAllFromUnorderedArray(allColumns, columns2);
    }
    for (const column2 of allColumns) {
      column2.setLeft(null, source2);
    }
  }
  joinCols() {
    if (this.gos.get("enableRtl")) {
      this.allCols = this.rightCols.concat(this.centerCols).concat(this.leftCols);
    } else {
      this.allCols = this.leftCols.concat(this.centerCols).concat(this.rightCols);
    }
  }
  getAllTrees() {
    if (this.treeLeft && this.treeRight && this.treeCenter) {
      return this.treeLeft.concat(this.treeCenter).concat(this.treeRight);
    }
    return null;
  }
  // gridPanel -> ensureColumnVisible
  isColDisplayed(column2) {
    return this.allCols.indexOf(column2) >= 0;
  }
  getLeftColsForRow(rowNode) {
    const {
      leftCols,
      beans: { colModel }
    } = this;
    const colSpanActive = colModel.colSpanActive;
    if (!colSpanActive) {
      return leftCols;
    }
    return this.getColsForRow(rowNode, leftCols);
  }
  getRightColsForRow(rowNode) {
    const {
      rightCols,
      beans: { colModel }
    } = this;
    const colSpanActive = colModel.colSpanActive;
    if (!colSpanActive) {
      return rightCols;
    }
    return this.getColsForRow(rowNode, rightCols);
  }
  getColsForRow(rowNode, displayedColumns, filterCallback, emptySpaceBeforeColumn) {
    const result2 = [];
    let lastConsideredCol = null;
    for (let i2 = 0; i2 < displayedColumns.length; i2++) {
      const col = displayedColumns[i2];
      const maxAllowedColSpan = displayedColumns.length - i2;
      const colSpan = Math.min(col.getColSpan(rowNode), maxAllowedColSpan);
      const columnsToCheckFilter = [col];
      if (colSpan > 1) {
        const colsToRemove = colSpan - 1;
        for (let j2 = 1; j2 <= colsToRemove; j2++) {
          columnsToCheckFilter.push(displayedColumns[i2 + j2]);
        }
        i2 += colsToRemove;
      }
      let filterPasses;
      if (filterCallback) {
        filterPasses = false;
        for (const colForFilter of columnsToCheckFilter) {
          if (filterCallback(colForFilter)) {
            filterPasses = true;
          }
        }
      } else {
        filterPasses = true;
      }
      if (filterPasses) {
        if (result2.length === 0 && lastConsideredCol) {
          const gapBeforeColumn = emptySpaceBeforeColumn ? emptySpaceBeforeColumn(col) : false;
          if (gapBeforeColumn) {
            result2.push(lastConsideredCol);
          }
        }
        result2.push(col);
      }
      lastConsideredCol = col;
    }
    return result2;
  }
  getContainerWidth(pinned) {
    switch (pinned) {
      case "left":
        return this.leftWidth;
      case "right":
        return this.rightWidth;
      default:
        return this.bodyWidth;
    }
  }
  getColBefore(col) {
    const allDisplayedColumns = this.allCols;
    const oldIndex = allDisplayedColumns.indexOf(col);
    if (oldIndex > 0) {
      return allDisplayedColumns[oldIndex - 1];
    }
    return null;
  }
  isPinningLeft() {
    return this.leftCols.length > 0;
  }
  isPinningRight() {
    return this.rightCols.length > 0;
  }
  updateColsAndGroupsMap() {
    this.colsAndGroupsMap = {};
    const func2 = (child) => {
      this.colsAndGroupsMap[child.getUniqueId()] = child;
    };
    depthFirstAllColumnTreeSearch(this.treeCenter, false, func2);
    depthFirstAllColumnTreeSearch(this.treeLeft, false, func2);
    depthFirstAllColumnTreeSearch(this.treeRight, false, func2);
  }
  isVisible(item2) {
    const fromMap = this.colsAndGroupsMap[item2.getUniqueId()];
    return fromMap === item2;
  }
  getFirstColumn() {
    const isRtl = this.gos.get("enableRtl");
    const queryOrder = ["leftCols", "centerCols", "rightCols"];
    if (isRtl) {
      queryOrder.reverse();
    }
    for (let i2 = 0; i2 < queryOrder.length; i2++) {
      const container2 = this[queryOrder[i2]];
      if (container2.length) {
        return isRtl ? _last(container2) : container2[0];
      }
    }
    return null;
  }
  // used by:
  // + rowRenderer -> for navigation
  getColAfter(col) {
    const allDisplayedColumns = this.allCols;
    const oldIndex = allDisplayedColumns.indexOf(col);
    if (oldIndex < allDisplayedColumns.length - 1) {
      return allDisplayedColumns[oldIndex + 1];
    }
    return null;
  }
  // used by:
  // + angularGrid -> setting pinned body width
  // note: this should be cached
  getColsLeftWidth() {
    return getWidthOfColsInList(this.leftCols);
  }
  // note: this should be cached
  getDisplayedColumnsRightWidth() {
    return getWidthOfColsInList(this.rightCols);
  }
  isColAtEdge(col, edge) {
    const allColumns = this.allCols;
    if (!allColumns.length) {
      return false;
    }
    const isFirst = edge === "first";
    let columnToCompare;
    if (isColumnGroup(col)) {
      const leafColumns = col.getDisplayedLeafColumns();
      if (!leafColumns.length) {
        return false;
      }
      columnToCompare = isFirst ? leafColumns[0] : _last(leafColumns);
    } else {
      columnToCompare = col;
    }
    return (isFirst ? allColumns[0] : _last(allColumns)) === columnToCompare;
  }
};
function depthFirstAllColumnTreeSearch(tree, useDisplayedChildren, callback) {
  if (!tree) {
    return;
  }
  for (let i2 = 0; i2 < tree.length; i2++) {
    const child = tree[i2];
    if (isColumnGroup(child)) {
      const childTree = useDisplayedChildren ? child.getDisplayedChildren() : child.getChildren();
      depthFirstAllColumnTreeSearch(childTree, useDisplayedChildren, callback);
    }
    callback(child);
  }
}
function pickDisplayedCols(tree) {
  const res = [];
  depthFirstAllColumnTreeSearch(tree, true, (child) => {
    if (isColumn(child)) {
      res.push(child);
    }
  });
  return res;
}
var ColumnGroupService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "colGroupSvc";
  }
  getColumnGroupState() {
    const columnGroupState = [];
    const gridBalancedTree = this.beans.colModel.getColTree();
    depthFirstOriginalTreeSearch(null, gridBalancedTree, (node2) => {
      if (isProvidedColumnGroup(node2)) {
        columnGroupState.push({
          groupId: node2.getGroupId(),
          open: node2.isExpanded()
        });
      }
    });
    return columnGroupState;
  }
  resetColumnGroupState(source2) {
    const primaryColumnTree = this.beans.colModel.getColDefColTree();
    if (!primaryColumnTree) {
      return;
    }
    const stateItems = [];
    depthFirstOriginalTreeSearch(null, primaryColumnTree, (child) => {
      if (isProvidedColumnGroup(child)) {
        const colGroupDef = child.getColGroupDef();
        const groupState = {
          groupId: child.getGroupId(),
          open: !colGroupDef ? void 0 : colGroupDef.openByDefault
        };
        stateItems.push(groupState);
      }
    });
    this.setColumnGroupState(stateItems, source2);
  }
  setColumnGroupState(stateItems, source2) {
    const { colModel, colAnimation, visibleCols, eventSvc } = this.beans;
    const gridBalancedTree = colModel.getColTree();
    if (!gridBalancedTree.length) {
      return;
    }
    colAnimation?.start();
    const impactedGroups = [];
    for (const stateItem of stateItems) {
      const groupKey = stateItem.groupId;
      const newValue = stateItem.open;
      const providedColumnGroup = this.getProvidedColGroup(groupKey);
      if (!providedColumnGroup) {
        continue;
      }
      if (providedColumnGroup.isExpanded() === newValue) {
        continue;
      }
      providedColumnGroup.setExpanded(newValue);
      impactedGroups.push(providedColumnGroup);
    }
    visibleCols.refresh(source2, true);
    if (impactedGroups.length) {
      eventSvc.dispatchEvent({
        type: "columnGroupOpened",
        columnGroup: impactedGroups.length === 1 ? impactedGroups[0] : void 0,
        columnGroups: impactedGroups
      });
    }
    colAnimation?.finish();
  }
  // called by headerRenderer - when a header is opened or closed
  setColumnGroupOpened(key2, newValue, source2) {
    let keyAsString;
    if (isProvidedColumnGroup(key2)) {
      keyAsString = key2.getId();
    } else {
      keyAsString = key2 || "";
    }
    this.setColumnGroupState([{ groupId: keyAsString, open: newValue }], source2);
  }
  getProvidedColGroup(key2) {
    let res = null;
    depthFirstOriginalTreeSearch(null, this.beans.colModel.getColTree(), (node2) => {
      if (isProvidedColumnGroup(node2)) {
        if (node2.getId() === key2) {
          res = node2;
        }
      }
    });
    return res;
  }
  getGroupAtDirection(columnGroup, direction) {
    const requiredLevel = columnGroup.getProvidedColumnGroup().getLevel() + columnGroup.getPaddingLevel();
    const colGroupLeafColumns = columnGroup.getDisplayedLeafColumns();
    const col = direction === "After" ? _last(colGroupLeafColumns) : colGroupLeafColumns[0];
    const getDisplayColMethod = `getCol${direction}`;
    while (true) {
      const column2 = this.beans.visibleCols[getDisplayColMethod](col);
      if (!column2) {
        return null;
      }
      const groupPointer = this.getColGroupAtLevel(column2, requiredLevel);
      if (groupPointer !== columnGroup) {
        return groupPointer;
      }
    }
  }
  getColGroupAtLevel(column2, level) {
    let groupPointer = column2.getParent();
    let originalGroupLevel;
    let groupPointerLevel;
    while (true) {
      const groupPointerProvidedColumnGroup = groupPointer.getProvidedColumnGroup();
      originalGroupLevel = groupPointerProvidedColumnGroup.getLevel();
      groupPointerLevel = groupPointer.getPaddingLevel();
      if (originalGroupLevel + groupPointerLevel <= level) {
        break;
      }
      groupPointer = groupPointer.getParent();
    }
    return groupPointer;
  }
  updateOpenClosedVisibility() {
    const allColumnGroups = this.beans.visibleCols.getAllTrees();
    depthFirstAllColumnTreeSearch(allColumnGroups, false, (child) => {
      if (isColumnGroup(child)) {
        child.calculateDisplayedColumns();
      }
    });
  }
  // returns the group with matching colId and instanceId. If instanceId is missing,
  // matches only on the colId.
  getColumnGroup(colId, partId) {
    if (!colId) {
      return null;
    }
    if (isColumnGroup(colId)) {
      return colId;
    }
    const allColumnGroups = this.beans.visibleCols.getAllTrees();
    const checkPartId = typeof partId === "number";
    let result2 = null;
    depthFirstAllColumnTreeSearch(allColumnGroups, false, (child) => {
      if (isColumnGroup(child)) {
        const columnGroup = child;
        let matched;
        if (checkPartId) {
          matched = colId === columnGroup.getGroupId() && partId === columnGroup.getPartId();
        } else {
          matched = colId === columnGroup.getGroupId();
        }
        if (matched) {
          result2 = columnGroup;
        }
      }
    });
    return result2;
  }
  createColumnGroups(params) {
    const { columns: columns2, idCreator, pinned, oldDisplayedGroups, isStandaloneStructure } = params;
    const oldColumnsMapped = this.mapOldGroupsById(oldDisplayedGroups);
    const topLevelResultCols = [];
    let groupsOrColsAtCurrentLevel = columns2;
    while (groupsOrColsAtCurrentLevel.length) {
      const currentlyIterating = groupsOrColsAtCurrentLevel;
      groupsOrColsAtCurrentLevel = [];
      let lastGroupedColIdx = 0;
      const createGroupToIndex = (to2) => {
        const from2 = lastGroupedColIdx;
        lastGroupedColIdx = to2;
        const previousNode = currentlyIterating[from2];
        const previousNodeProvided = isColumnGroup(previousNode) ? previousNode.getProvidedColumnGroup() : previousNode;
        const previousNodeParent = previousNodeProvided.getOriginalParent();
        if (previousNodeParent == null) {
          for (let i2 = from2; i2 < to2; i2++) {
            topLevelResultCols.push(currentlyIterating[i2]);
          }
          return;
        }
        const newGroup = this.createColumnGroup(
          previousNodeParent,
          idCreator,
          oldColumnsMapped,
          pinned,
          isStandaloneStructure
        );
        for (let i2 = from2; i2 < to2; i2++) {
          newGroup.addChild(currentlyIterating[i2]);
        }
        groupsOrColsAtCurrentLevel.push(newGroup);
      };
      for (let i2 = 1; i2 < currentlyIterating.length; i2++) {
        const thisNode = currentlyIterating[i2];
        const thisNodeProvided = isColumnGroup(thisNode) ? thisNode.getProvidedColumnGroup() : thisNode;
        const thisNodeParent = thisNodeProvided.getOriginalParent();
        const previousNode = currentlyIterating[lastGroupedColIdx];
        const previousNodeProvided = isColumnGroup(previousNode) ? previousNode.getProvidedColumnGroup() : previousNode;
        const previousNodeParent = previousNodeProvided.getOriginalParent();
        if (thisNodeParent !== previousNodeParent) {
          createGroupToIndex(i2);
        }
      }
      if (lastGroupedColIdx < currentlyIterating.length) {
        createGroupToIndex(currentlyIterating.length);
      }
    }
    if (!isStandaloneStructure) {
      this.setupParentsIntoCols(topLevelResultCols, null);
    }
    return topLevelResultCols;
  }
  createProvidedColumnGroup(primaryColumns, colGroupDef, level, existingColumns, columnKeyCreator, existingGroups, source2) {
    const groupId = columnKeyCreator.getUniqueKey(colGroupDef.groupId || null, null);
    const colGroupDefMerged = createMergedColGroupDef(this.beans, colGroupDef, groupId);
    const providedGroup = new AgProvidedColumnGroup(colGroupDefMerged, groupId, false, level);
    this.createBean(providedGroup);
    const existingGroupAndIndex = this.findExistingGroup(colGroupDef, existingGroups);
    if (existingGroupAndIndex) {
      existingGroups.splice(existingGroupAndIndex.idx, 1);
    }
    const existingGroup = existingGroupAndIndex?.group;
    if (existingGroup) {
      providedGroup.setExpanded(existingGroup.isExpanded());
    }
    const children2 = _recursivelyCreateColumns(
      this.beans,
      colGroupDefMerged.children,
      level + 1,
      primaryColumns,
      existingColumns,
      columnKeyCreator,
      existingGroups,
      source2
    );
    providedGroup.setChildren(children2);
    return providedGroup;
  }
  balanceColumnTree(unbalancedTree, currentDepth, columnDepth, columnKeyCreator) {
    const result2 = [];
    for (let i2 = 0; i2 < unbalancedTree.length; i2++) {
      const child = unbalancedTree[i2];
      if (isProvidedColumnGroup(child)) {
        const originalGroup = child;
        const newChildren = this.balanceColumnTree(
          originalGroup.getChildren(),
          currentDepth + 1,
          columnDepth,
          columnKeyCreator
        );
        originalGroup.setChildren(newChildren);
        result2.push(originalGroup);
      } else {
        let firstPaddedGroup;
        let currentPaddedGroup;
        for (let j2 = currentDepth; j2 < columnDepth; j2++) {
          const newColId = columnKeyCreator.getUniqueKey(null, null);
          const colGroupDefMerged = createMergedColGroupDef(this.beans, null, newColId);
          const paddedGroup = new AgProvidedColumnGroup(colGroupDefMerged, newColId, true, j2);
          this.createBean(paddedGroup);
          if (currentPaddedGroup) {
            currentPaddedGroup.setChildren([paddedGroup]);
          }
          currentPaddedGroup = paddedGroup;
          if (!firstPaddedGroup) {
            firstPaddedGroup = currentPaddedGroup;
          }
        }
        if (firstPaddedGroup && currentPaddedGroup) {
          result2.push(firstPaddedGroup);
          const hasGroups = unbalancedTree.some((leaf) => isProvidedColumnGroup(leaf));
          if (hasGroups) {
            currentPaddedGroup.setChildren([child]);
            continue;
          } else {
            currentPaddedGroup.setChildren(unbalancedTree);
            break;
          }
        }
        result2.push(child);
      }
    }
    return result2;
  }
  findDepth(balancedColumnTree) {
    let depth = 0;
    let pointer = balancedColumnTree;
    while (pointer?.[0] && isProvidedColumnGroup(pointer[0])) {
      depth++;
      pointer = pointer[0].getChildren();
    }
    return depth;
  }
  findMaxDepth(treeChildren, depth) {
    let maxDepthThisLevel = depth;
    for (let i2 = 0; i2 < treeChildren.length; i2++) {
      const abstractColumn = treeChildren[i2];
      if (isProvidedColumnGroup(abstractColumn)) {
        const originalGroup = abstractColumn;
        const newDepth = this.findMaxDepth(originalGroup.getChildren(), depth + 1);
        if (maxDepthThisLevel < newDepth) {
          maxDepthThisLevel = newDepth;
        }
      }
    }
    return maxDepthThisLevel;
  }
  /**
   * Inserts dummy group columns in the hierarchy above auto-generated columns
   * in order to ensure auto-generated columns are leaf nodes (and therefore are
   * displayed correctly)
   */
  balanceTreeForAutoCols(autoCols, depth) {
    const tree = [];
    for (const col of autoCols) {
      let nextChild = col;
      for (let i2 = depth - 1; i2 >= 0; i2--) {
        const autoGroup = new AgProvidedColumnGroup(null, `FAKE_PATH_${col.getId()}}_${i2}`, true, i2);
        this.createBean(autoGroup);
        autoGroup.setChildren([nextChild]);
        nextChild.originalParent = autoGroup;
        nextChild = autoGroup;
      }
      if (depth === 0) {
        col.originalParent = null;
      }
      tree.push(nextChild);
    }
    return tree;
  }
  findExistingGroup(newGroupDef, existingGroups) {
    const newHasId = newGroupDef.groupId != null;
    if (!newHasId) {
      return void 0;
    }
    for (let i2 = 0; i2 < existingGroups.length; i2++) {
      const existingGroup = existingGroups[i2];
      const existingDef = existingGroup.getColGroupDef();
      if (!existingDef) {
        continue;
      }
      if (existingGroup.getId() === newGroupDef.groupId) {
        return { idx: i2, group: existingGroup };
      }
    }
    return void 0;
  }
  createColumnGroup(providedGroup, groupInstanceIdCreator, oldColumnsMapped, pinned, isStandaloneStructure) {
    const groupId = providedGroup.getGroupId();
    const instanceId = groupInstanceIdCreator.getInstanceIdForKey(groupId);
    const uniqueId = createUniqueColumnGroupId(groupId, instanceId);
    let columnGroup = oldColumnsMapped[uniqueId];
    if (columnGroup && columnGroup.getProvidedColumnGroup() !== providedGroup) {
      columnGroup = null;
    }
    if (_exists(columnGroup)) {
      columnGroup.reset();
    } else {
      columnGroup = new AgColumnGroup(providedGroup, groupId, instanceId, pinned);
      if (!isStandaloneStructure) {
        this.createBean(columnGroup);
      }
    }
    return columnGroup;
  }
  // returns back a 2d map of ColumnGroup as follows: groupId -> instanceId -> ColumnGroup
  mapOldGroupsById(displayedGroups) {
    const result2 = {};
    const recursive = (columnsOrGroups) => {
      for (const columnOrGroup of columnsOrGroups) {
        if (isColumnGroup(columnOrGroup)) {
          const columnGroup = columnOrGroup;
          result2[columnOrGroup.getUniqueId()] = columnGroup;
          recursive(columnGroup.getChildren());
        }
      }
    };
    if (displayedGroups) {
      recursive(displayedGroups);
    }
    return result2;
  }
  setupParentsIntoCols(columnsOrGroups, parent) {
    for (const columnsOrGroup of columnsOrGroups ?? []) {
      if (columnsOrGroup.parent !== parent) {
        this.beans.colViewport.colsWithinViewportHash = "";
      }
      columnsOrGroup.parent = parent;
      if (isColumnGroup(columnsOrGroup)) {
        const columnGroup = columnsOrGroup;
        this.setupParentsIntoCols(columnGroup.getChildren(), columnGroup);
      }
    }
  }
};
var ColumnGroupModule = {
  moduleName: "ColumnGroup",
  version: VERSION,
  dynamicBeans: { headerGroupCellCtrl: HeaderGroupCellCtrl },
  beans: [ColumnGroupService],
  apiFunctions: {
    getAllDisplayedColumnGroups,
    getCenterDisplayedColumnGroups,
    getColumnGroup,
    getColumnGroupState,
    getDisplayNameForColumnGroup,
    getLeftDisplayedColumnGroups,
    getProvidedColumnGroup,
    getRightDisplayedColumnGroups,
    resetColumnGroupState,
    setColumnGroupOpened,
    setColumnGroupState
  }
};
var SkeletonCellRendererElement = { tag: "div", cls: "ag-skeleton-container" };
var SkeletonCellRenderer$1 = class SkeletonCellRenderer extends Component {
  constructor() {
    super(SkeletonCellRendererElement);
  }
  init(params) {
    const id2 = `ag-cell-skeleton-renderer-${this.getCompId()}`;
    this.getGui().setAttribute("id", id2);
    this.addDestroyFunc(() => _setAriaLabelledBy(params.eParentOfValue));
    _setAriaLabelledBy(params.eParentOfValue, id2);
    if (params.deferRender) {
      this.setupLoading(params);
    } else {
      params.node.failedLoad ? this.setupFailed() : this.setupLoading(params);
    }
  }
  setupFailed() {
    const localeTextFunc = this.getLocaleTextFunc();
    this.getGui().textContent = localeTextFunc("loadingError", "ERR");
    const ariaFailed = localeTextFunc("ariaSkeletonCellLoadingFailed", "Row failed to load");
    _setAriaLabel(this.getGui(), ariaFailed);
  }
  setupLoading(params) {
    const skeletonEffect = _createElement({
      tag: "div",
      cls: "ag-skeleton-effect"
    });
    const rowIndex = params.node.rowIndex;
    if (rowIndex != null) {
      const width = 75 + 25 * (rowIndex % 2 === 0 ? Math.sin(rowIndex) : Math.cos(rowIndex));
      skeletonEffect.style.width = `${width}%`;
    }
    this.getGui().appendChild(skeletonEffect);
    const localeTextFunc = this.getLocaleTextFunc();
    const ariaLoading = params.deferRender ? localeTextFunc("ariaDeferSkeletonCellLoading", "Cell is loading") : localeTextFunc("ariaSkeletonCellLoading", "Row data is loading");
    _setAriaLabel(this.getGui(), ariaLoading);
  }
  refresh(_params) {
    return false;
  }
};
var CheckboxCellRendererModule = {
  moduleName: "CheckboxCellRenderer",
  version: VERSION,
  userComponents: {
    agCheckboxCellRenderer: CheckboxCellRenderer
  }
};
var SkeletonCellRendererModule = {
  moduleName: "SkeletonCellRenderer",
  version: VERSION,
  userComponents: {
    agSkeletonCellRenderer: SkeletonCellRenderer$1
  }
};
function getColumnDef(beans, key2) {
  const column2 = beans.colModel.getColDefCol(key2);
  if (column2) {
    return column2.getColDef();
  }
  return null;
}
function getColumnDefs(beans) {
  return beans.colModel.getColumnDefs(true);
}
function getDisplayNameForColumn(beans, column2, location) {
  return beans.colNames.getDisplayNameForColumn(column2, location) || "";
}
function getColumn(beans, key2) {
  return beans.colModel.getColDefCol(key2);
}
function getColumns(beans) {
  return beans.colModel.getColDefCols();
}
function applyColumnState(beans, params) {
  return _applyColumnState(beans, params, "api");
}
function getColumnState(beans) {
  return _getColumnState(beans);
}
function resetColumnState(beans) {
  _resetColumnState(beans, "api");
}
function isPinning(beans) {
  return beans.visibleCols.isPinningLeft() || beans.visibleCols.isPinningRight();
}
function isPinningLeft(beans) {
  return beans.visibleCols.isPinningLeft();
}
function isPinningRight(beans) {
  return beans.visibleCols.isPinningRight();
}
function getDisplayedColAfter(beans, col) {
  return beans.visibleCols.getColAfter(col);
}
function getDisplayedColBefore(beans, col) {
  return beans.visibleCols.getColBefore(col);
}
function setColumnsVisible(beans, keys2, visible2) {
  beans.colModel.setColsVisible(keys2, visible2, "api");
}
function setColumnsPinned(beans, keys2, pinned) {
  beans.pinnedCols?.setColsPinned(keys2, pinned, "api");
}
function getAllGridColumns(beans) {
  return beans.colModel.getCols();
}
function getDisplayedLeftColumns(beans) {
  return beans.visibleCols.leftCols;
}
function getDisplayedCenterColumns(beans) {
  return beans.visibleCols.centerCols;
}
function getDisplayedRightColumns(beans) {
  return beans.visibleCols.rightCols;
}
function getAllDisplayedColumns(beans) {
  return beans.visibleCols.allCols;
}
function getAllDisplayedVirtualColumns(beans) {
  return beans.colViewport.getViewportColumns();
}
function _deepCloneDefinition(object2, keysToSkip) {
  if (!object2) {
    return;
  }
  const obj = object2;
  const res = {};
  for (const key2 of Object.keys(obj)) {
    if (keysToSkip && keysToSkip.indexOf(key2) >= 0 || SKIP_JS_BUILTINS.has(key2)) {
      continue;
    }
    const value2 = obj[key2];
    const sourceIsSimpleObject = typeof value2 === "object" && value2 !== null && value2.constructor === Object;
    if (sourceIsSimpleObject) {
      res[key2] = _deepCloneDefinition(value2);
    } else {
      res[key2] = value2;
    }
  }
  return res;
}
var ColumnDefFactory = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "colDefFactory";
  }
  wireBeans(beans) {
    this.rowGroupColsSvc = beans.rowGroupColsSvc;
    this.pivotColsSvc = beans.pivotColsSvc;
  }
  getColumnDefs(colDefColsList, showingPivotResult, lastOrder, colsList, sorted = false) {
    const cols = colDefColsList.slice();
    if (showingPivotResult) {
      cols.sort((a2, b) => lastOrder.indexOf(a2) - lastOrder.indexOf(b));
    } else if (lastOrder || sorted) {
      cols.sort((a2, b) => colsList.indexOf(a2) - colsList.indexOf(b));
    }
    const rowGroupColumns = this.rowGroupColsSvc?.columns;
    const pivotColumns = this.pivotColsSvc?.columns;
    return this.buildColumnDefs(cols, rowGroupColumns, pivotColumns);
  }
  buildColumnDefs(cols, rowGroupColumns = [], pivotColumns = []) {
    const res = [];
    const colGroupDefs = {};
    for (const col of cols) {
      const colDef = this.createDefFromColumn(col, rowGroupColumns, pivotColumns);
      let addToResult = true;
      let childDef = colDef;
      let pointer = col.getOriginalParent();
      let lastPointer = null;
      while (pointer) {
        let parentDef = null;
        if (pointer.isPadding()) {
          pointer = pointer.getOriginalParent();
          continue;
        }
        const existingParentDef = colGroupDefs[pointer.getGroupId()];
        if (existingParentDef) {
          existingParentDef.children.push(childDef);
          addToResult = false;
          break;
        }
        parentDef = this.createDefFromGroup(pointer);
        if (parentDef) {
          parentDef.children = [childDef];
          colGroupDefs[parentDef.groupId] = parentDef;
          childDef = parentDef;
          pointer = pointer.getOriginalParent();
        }
        if (pointer != null && lastPointer === pointer) {
          addToResult = false;
          break;
        }
        lastPointer = pointer;
      }
      if (addToResult) {
        res.push(childDef);
      }
    }
    return res;
  }
  createDefFromGroup(group) {
    const defCloned = _deepCloneDefinition(group.getColGroupDef(), ["children"]);
    if (defCloned) {
      defCloned.groupId = group.getGroupId();
    }
    return defCloned;
  }
  createDefFromColumn(col, rowGroupColumns, pivotColumns) {
    const colDefCloned = _deepCloneDefinition(col.getColDef());
    colDefCloned.colId = col.getColId();
    colDefCloned.width = col.getActualWidth();
    colDefCloned.rowGroup = col.isRowGroupActive();
    colDefCloned.rowGroupIndex = col.isRowGroupActive() ? rowGroupColumns.indexOf(col) : null;
    colDefCloned.pivot = col.isPivotActive();
    colDefCloned.pivotIndex = col.isPivotActive() ? pivotColumns.indexOf(col) : null;
    colDefCloned.aggFunc = col.isValueActive() ? col.getAggFunc() : null;
    colDefCloned.hide = col.isVisible() ? void 0 : true;
    colDefCloned.pinned = col.isPinned() ? col.getPinned() : null;
    colDefCloned.sort = col.getSort() ? col.getSort() : null;
    colDefCloned.sortIndex = col.getSortIndex() != null ? col.getSortIndex() : null;
    return colDefCloned;
  }
};
var ColumnFlexService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "colFlex";
    this.columnsHidden = false;
  }
  refreshFlexedColumns(params = {}) {
    const source2 = params.source ?? "flex";
    if (params.viewportWidth != null) {
      this.flexViewportWidth = params.viewportWidth;
    }
    const totalSpace = this.flexViewportWidth;
    const { visibleCols, colDelayRenderSvc } = this.beans;
    const visibleCenterCols = visibleCols.centerCols;
    let flexAfterDisplayIndex = -1;
    if (params.resizingCols) {
      const allResizingCols = new Set(params.resizingCols);
      for (let i2 = visibleCenterCols.length - 1; i2 >= 0; i2--) {
        if (allResizingCols.has(visibleCenterCols[i2])) {
          flexAfterDisplayIndex = i2;
          break;
        }
      }
    }
    let hasFlexItems = false;
    const items = visibleCenterCols.map((col, i2) => {
      const flex2 = col.getFlex();
      const isFlex = flex2 != null && flex2 > 0 && i2 > flexAfterDisplayIndex;
      hasFlexItems || (hasFlexItems = isFlex);
      return {
        col,
        isFlex,
        flex: Math.max(0, flex2 ?? 0),
        initialSize: col.getActualWidth(),
        min: col.getMinWidth(),
        max: col.getMaxWidth(),
        targetSize: 0
      };
    });
    if (hasFlexItems) {
      colDelayRenderSvc?.hideColumns("colFlex");
      this.columnsHidden = true;
    } else if (this.columnsHidden) {
      this.revealColumns(colDelayRenderSvc);
    }
    if (!totalSpace || !hasFlexItems) {
      return [];
    }
    let unfrozenItemCount = items.length;
    let unfrozenFlex = items.reduce((acc, item2) => acc + item2.flex, 0);
    let unfrozenSpace = totalSpace;
    const freeze2 = (item2, width) => {
      item2.frozenSize = width;
      item2.col.setActualWidth(width, source2);
      unfrozenSpace -= width;
      unfrozenFlex -= item2.flex;
      unfrozenItemCount -= 1;
    };
    const isFrozen2 = (item2) => item2.frozenSize != null;
    for (const item2 of items) {
      if (!item2.isFlex) {
        freeze2(item2, item2.initialSize);
      }
    }
    while (unfrozenItemCount > 0) {
      const spaceToFill = Math.round(unfrozenFlex < 1 ? unfrozenSpace * unfrozenFlex : unfrozenSpace);
      let lastUnfrozenItem;
      let actualLeft = 0;
      let idealRight = 0;
      for (const item2 of items) {
        if (isFrozen2(item2)) {
          continue;
        }
        lastUnfrozenItem = item2;
        idealRight += spaceToFill * (item2.flex / unfrozenFlex);
        const idealSize = idealRight - actualLeft;
        const roundedSize = Math.round(idealSize);
        item2.targetSize = roundedSize;
        actualLeft += roundedSize;
      }
      if (lastUnfrozenItem) {
        lastUnfrozenItem.targetSize += spaceToFill - actualLeft;
      }
      let totalViolation = 0;
      for (const item2 of items) {
        if (isFrozen2(item2)) {
          continue;
        }
        const unclampedSize = item2.targetSize;
        const clampedSize = Math.min(Math.max(unclampedSize, item2.min), item2.max);
        totalViolation += clampedSize - unclampedSize;
        item2.violationType = clampedSize === unclampedSize ? void 0 : clampedSize < unclampedSize ? "max" : "min";
        item2.targetSize = clampedSize;
      }
      const freezeType = totalViolation === 0 ? "all" : totalViolation > 0 ? "min" : "max";
      for (const item2 of items) {
        if (isFrozen2(item2)) {
          continue;
        }
        if (freezeType === "all" || item2.violationType === freezeType) {
          freeze2(item2, item2.targetSize);
        }
      }
    }
    if (!params.skipSetLeft) {
      visibleCols.setLeftValues(source2);
    }
    if (params.updateBodyWidths) {
      visibleCols.updateBodyWidths();
    }
    const unconstrainedFlexColumns = items.filter((item2) => item2.isFlex && !item2.violationType).map((item2) => item2.col);
    if (params.fireResizedEvent) {
      const changedColumns = items.filter((item2) => item2.initialSize !== item2.frozenSize).map((item2) => item2.col);
      const flexingColumns = items.filter((item2) => item2.flex).map((item2) => item2.col);
      dispatchColumnResizedEvent(this.eventSvc, changedColumns, true, source2, flexingColumns);
    }
    this.revealColumns(colDelayRenderSvc);
    return unconstrainedFlexColumns;
  }
  revealColumns(colDelayRenderSvc) {
    if (this.columnsHidden) {
      colDelayRenderSvc?.revealColumns("colFlex");
      this.columnsHidden = false;
    }
  }
  initCol(column2) {
    const { flex: flex2, initialFlex } = column2.colDef;
    if (flex2 !== void 0) {
      column2.flex = flex2;
    } else if (initialFlex !== void 0) {
      column2.flex = initialFlex;
    }
  }
  // this method should only be used by the colModel to
  // change flex when required by the applyColumnState method.
  setColFlex(column2, flex2) {
    column2.flex = flex2 ?? null;
    column2.dispatchStateUpdatedEvent("flex");
  }
};
function _getValueUsingField(data2, field2, fieldContainsDots) {
  if (!field2 || !data2) {
    return;
  }
  if (!fieldContainsDots) {
    return data2[field2];
  }
  const fields = field2.split(".");
  let currentObject = data2;
  for (let i2 = 0; i2 < fields.length; i2++) {
    if (currentObject == null) {
      return void 0;
    }
    currentObject = currentObject[fields[i2]];
  }
  return currentObject;
}
var SORTED_CELL_DATA_TYPES_FOR_MATCHING = [
  "dateTimeString",
  "dateString",
  "text",
  "number",
  "boolean",
  "date"
];
var DataTypeService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "dataTypeSvc";
    this.dataTypeDefinitions = {};
    this.isPendingInference = false;
    this.isColumnTypeOverrideInDataTypeDefinitions = false;
    this.columnStateUpdatesPendingInference = {};
    this.columnStateUpdateListenerDestroyFuncs = [];
    this.columnDefinitionPropsPerDataType = {
      number() {
        return { cellEditor: "agNumberCellEditor" };
      },
      boolean() {
        return {
          cellEditor: "agCheckboxCellEditor",
          cellRenderer: "agCheckboxCellRenderer",
          getFindText: () => null,
          suppressKeyboardEvent: (params) => !!params.colDef.editable && params.event.key === KeyCode.SPACE
        };
      },
      date({ formatValue: formatValue2 }) {
        return { cellEditor: "agDateCellEditor", keyCreator: formatValue2 };
      },
      dateString({ formatValue: formatValue2 }) {
        return { cellEditor: "agDateStringCellEditor", keyCreator: formatValue2 };
      },
      dateTime(args2) {
        return this.date(args2);
      },
      dateTimeString(args2) {
        return this.dateString(args2);
      },
      object({ formatValue: formatValue2, colModel, colId }) {
        return {
          cellEditorParams: {
            useFormatter: true
          },
          comparator: (a2, b) => {
            const column2 = colModel.getColDefCol(colId);
            const colDef = column2?.getColDef();
            if (!column2 || !colDef) {
              return 0;
            }
            const valA = a2 == null ? "" : formatValue2({ column: column2, node: null, value: a2 });
            const valB = b == null ? "" : formatValue2({ column: column2, node: null, value: b });
            if (valA === valB) {
              return 0;
            }
            return valA > valB ? 1 : -1;
          },
          keyCreator: formatValue2
        };
      },
      text() {
        return {};
      }
    };
  }
  wireBeans(beans) {
    this.colModel = beans.colModel;
  }
  postConstruct() {
    this.processDataTypeDefinitions();
    this.addManagedPropertyListener("dataTypeDefinitions", (event) => {
      this.processDataTypeDefinitions();
      this.colModel.recreateColumnDefs(event);
    });
  }
  processDataTypeDefinitions() {
    const defaultDataTypes = this.getDefaultDataTypes();
    const newDataTypeDefinitions = {};
    const newFormatValueFuncs = {};
    const generateFormatValueFunc = (dataTypeDefinition) => {
      return (params) => {
        const { column: column2, node: node2, value: value2 } = params;
        let valueFormatter = column2.getColDef().valueFormatter;
        if (valueFormatter === dataTypeDefinition.groupSafeValueFormatter) {
          valueFormatter = dataTypeDefinition.valueFormatter;
        }
        return this.beans.valueSvc.formatValue(column2, node2, value2, valueFormatter);
      };
    };
    for (const cellDataType of Object.keys(defaultDataTypes)) {
      const defaultDataTypeDef = defaultDataTypes[cellDataType];
      const mergedDataTypeDefinition = {
        ...defaultDataTypeDef,
        groupSafeValueFormatter: createGroupSafeValueFormatter(defaultDataTypeDef, this.gos)
      };
      newDataTypeDefinitions[cellDataType] = mergedDataTypeDefinition;
      newFormatValueFuncs[cellDataType] = generateFormatValueFunc(mergedDataTypeDefinition);
    }
    const userDataTypeDefs = this.gos.get("dataTypeDefinitions") ?? {};
    const newDataTypeMatchers = {};
    for (const cellDataType of Object.keys(userDataTypeDefs)) {
      const userDataTypeDef = userDataTypeDefs[cellDataType];
      const mergedDataTypeDefinition = this.processDataTypeDefinition(
        userDataTypeDef,
        userDataTypeDefs,
        [cellDataType],
        defaultDataTypes
      );
      if (mergedDataTypeDefinition) {
        newDataTypeDefinitions[cellDataType] = mergedDataTypeDefinition;
        if (userDataTypeDef.dataTypeMatcher) {
          newDataTypeMatchers[cellDataType] = userDataTypeDef.dataTypeMatcher;
        }
        newFormatValueFuncs[cellDataType] = generateFormatValueFunc(mergedDataTypeDefinition);
      }
    }
    const { valueParser: defaultValueParser, valueFormatter: defaultValueFormatter } = defaultDataTypes.object;
    const { valueParser: userValueParser, valueFormatter: userValueFormatter } = newDataTypeDefinitions.object;
    this.hasObjectValueParser = userValueParser !== defaultValueParser;
    this.hasObjectValueFormatter = userValueFormatter !== defaultValueFormatter;
    this.formatValueFuncs = newFormatValueFuncs;
    this.dataTypeDefinitions = newDataTypeDefinitions;
    this.dataTypeMatchers = this.sortKeysInMatchers(newDataTypeMatchers, defaultDataTypes);
  }
  /**
   * Sorts the keys in the matchers object.
   * Does not mutate the original object, creates a copy of it with sorted keys instead.
   */
  sortKeysInMatchers(matchers, dataTypes) {
    const sortedMatchers = { ...matchers };
    for (const cellDataType of SORTED_CELL_DATA_TYPES_FOR_MATCHING) {
      delete sortedMatchers[cellDataType];
      sortedMatchers[cellDataType] = matchers[cellDataType] ?? dataTypes[cellDataType].dataTypeMatcher;
    }
    return sortedMatchers;
  }
  processDataTypeDefinition(userDataTypeDef, userDataTypeDefs, alreadyProcessedDataTypes, defaultDataTypes) {
    let mergedDataTypeDefinition;
    const extendsCellDataType = userDataTypeDef.extendsDataType;
    if (userDataTypeDef.columnTypes) {
      this.isColumnTypeOverrideInDataTypeDefinitions = true;
    }
    if (userDataTypeDef.extendsDataType === userDataTypeDef.baseDataType) {
      let baseDataTypeDefinition = defaultDataTypes[extendsCellDataType];
      const overriddenBaseDataTypeDefinition = userDataTypeDefs[extendsCellDataType];
      if (baseDataTypeDefinition && overriddenBaseDataTypeDefinition) {
        baseDataTypeDefinition = overriddenBaseDataTypeDefinition;
      }
      if (!validateDataTypeDefinition(userDataTypeDef, baseDataTypeDefinition, extendsCellDataType)) {
        return void 0;
      }
      mergedDataTypeDefinition = mergeDataTypeDefinitions(baseDataTypeDefinition, userDataTypeDef);
    } else {
      if (alreadyProcessedDataTypes.includes(extendsCellDataType)) {
        _warn(44);
        return void 0;
      }
      const extendedDataTypeDefinition = userDataTypeDefs[extendsCellDataType];
      if (!validateDataTypeDefinition(userDataTypeDef, extendedDataTypeDefinition, extendsCellDataType)) {
        return void 0;
      }
      const mergedExtendedDataTypeDefinition = this.processDataTypeDefinition(
        extendedDataTypeDefinition,
        userDataTypeDefs,
        [...alreadyProcessedDataTypes, extendsCellDataType],
        defaultDataTypes
      );
      if (!mergedExtendedDataTypeDefinition) {
        return void 0;
      }
      mergedDataTypeDefinition = mergeDataTypeDefinitions(mergedExtendedDataTypeDefinition, userDataTypeDef);
    }
    return {
      ...mergedDataTypeDefinition,
      groupSafeValueFormatter: createGroupSafeValueFormatter(mergedDataTypeDefinition, this.gos)
    };
  }
  updateColDefAndGetColumnType(colDef, userColDef, colId) {
    let { cellDataType } = userColDef;
    const { field: field2 } = userColDef;
    if (cellDataType === void 0) {
      cellDataType = colDef.cellDataType;
    }
    if (cellDataType == null || cellDataType === true) {
      cellDataType = this.canInferCellDataType(colDef, userColDef) ? this.inferCellDataType(field2, colId) : false;
    }
    if (!cellDataType) {
      colDef.cellDataType = false;
      return void 0;
    }
    const dataTypeDefinition = this.dataTypeDefinitions[cellDataType];
    if (!dataTypeDefinition) {
      _warn(47, { cellDataType });
      return void 0;
    }
    colDef.cellDataType = cellDataType;
    if (dataTypeDefinition.groupSafeValueFormatter) {
      colDef.valueFormatter = dataTypeDefinition.groupSafeValueFormatter;
    }
    if (dataTypeDefinition.valueParser) {
      colDef.valueParser = dataTypeDefinition.valueParser;
    }
    if (!dataTypeDefinition.suppressDefaultProperties) {
      this.setColDefPropertiesForBaseDataType(colDef, cellDataType, dataTypeDefinition, colId);
    }
    return dataTypeDefinition.columnTypes;
  }
  addColumnListeners(column2) {
    if (!this.isPendingInference) {
      return;
    }
    const columnStateUpdates = this.columnStateUpdatesPendingInference[column2.getColId()];
    if (!columnStateUpdates) {
      return;
    }
    const columnListener = (event) => {
      columnStateUpdates.add(event.key);
    };
    column2.__addEventListener("columnStateUpdated", columnListener);
    this.columnStateUpdateListenerDestroyFuncs.push(
      () => column2.__removeEventListener("columnStateUpdated", columnListener)
    );
  }
  canInferCellDataType(colDef, userColDef) {
    const { gos } = this;
    if (!_isClientSideRowModel(gos)) {
      return false;
    }
    const propsToCheckForInference = { cellRenderer: true, valueGetter: true, valueParser: true, refData: true };
    if (doColDefPropsPreventInference(userColDef, propsToCheckForInference)) {
      return false;
    }
    const columnTypes = userColDef.type === null ? colDef.type : userColDef.type;
    if (columnTypes) {
      const columnTypeDefs = gos.get("columnTypes") ?? {};
      const hasPropsPreventingInference = convertColumnTypes(columnTypes).some((columnType) => {
        const columnTypeDef = columnTypeDefs[columnType.trim()];
        return columnTypeDef && doColDefPropsPreventInference(columnTypeDef, propsToCheckForInference);
      });
      if (hasPropsPreventingInference) {
        return false;
      }
    }
    return !doColDefPropsPreventInference(colDef, propsToCheckForInference);
  }
  inferCellDataType(field2, colId) {
    if (!field2) {
      return void 0;
    }
    let value2;
    const initialData = this.getInitialData();
    if (initialData) {
      const fieldContainsDots = field2.includes(".") && !this.gos.get("suppressFieldDotNotation");
      value2 = _getValueUsingField(initialData, field2, fieldContainsDots);
    } else {
      this.initWaitForRowData(colId);
    }
    if (value2 == null) {
      return void 0;
    }
    const matchedType = Object.keys(this.dataTypeMatchers).find(
      (_cellDataType) => this.dataTypeMatchers[_cellDataType](value2)
    );
    return matchedType ?? "object";
  }
  getInitialData() {
    const rowData = this.gos.get("rowData");
    if (rowData?.length) {
      return rowData[0];
    } else if (this.initialData) {
      return this.initialData;
    } else {
      const rowNodes = this.beans.rowModel.rootNode?._leafs;
      if (rowNodes?.length) {
        return rowNodes[0].data;
      }
    }
    return null;
  }
  initWaitForRowData(colId) {
    this.columnStateUpdatesPendingInference[colId] = /* @__PURE__ */ new Set();
    if (this.isPendingInference) {
      return;
    }
    this.isPendingInference = true;
    const columnTypeOverridesExist = this.isColumnTypeOverrideInDataTypeDefinitions;
    const { colAutosize, eventSvc } = this.beans;
    if (columnTypeOverridesExist && colAutosize) {
      colAutosize.shouldQueueResizeOperations = true;
    }
    const [destroyFunc] = this.addManagedEventListeners({
      rowDataUpdateStarted: (event) => {
        const { firstRowData } = event;
        if (!firstRowData) {
          return;
        }
        destroyFunc?.();
        this.isPendingInference = false;
        this.processColumnsPendingInference(firstRowData, columnTypeOverridesExist);
        this.columnStateUpdatesPendingInference = {};
        if (columnTypeOverridesExist) {
          colAutosize?.processResizeOperations();
        }
        eventSvc.dispatchEvent({
          type: "dataTypesInferred"
        });
      }
    });
  }
  processColumnsPendingInference(firstRowData, columnTypeOverridesExist) {
    this.initialData = firstRowData;
    const state = [];
    this.destroyColumnStateUpdateListeners();
    const newRowGroupColumnStateWithoutIndex = {};
    const newPivotColumnStateWithoutIndex = {};
    for (const colId of Object.keys(this.columnStateUpdatesPendingInference)) {
      const columnStateUpdates = this.columnStateUpdatesPendingInference[colId];
      const column2 = this.colModel.getCol(colId);
      if (!column2) {
        return;
      }
      const oldColDef = column2.getColDef();
      if (!this.resetColDefIntoCol(column2, "cellDataTypeInferred")) {
        return;
      }
      const newColDef = column2.getColDef();
      if (columnTypeOverridesExist && newColDef.type && newColDef.type !== oldColDef.type) {
        const updatedColumnState = getUpdatedColumnState(column2, columnStateUpdates);
        if (updatedColumnState.rowGroup && updatedColumnState.rowGroupIndex == null) {
          newRowGroupColumnStateWithoutIndex[colId] = updatedColumnState;
        }
        if (updatedColumnState.pivot && updatedColumnState.pivotIndex == null) {
          newPivotColumnStateWithoutIndex[colId] = updatedColumnState;
        }
        state.push(updatedColumnState);
      }
    }
    if (columnTypeOverridesExist) {
      state.push(
        ...this.generateColumnStateForRowGroupAndPivotIndexes(
          newRowGroupColumnStateWithoutIndex,
          newPivotColumnStateWithoutIndex
        )
      );
    }
    if (state.length) {
      _applyColumnState(this.beans, { state }, "cellDataTypeInferred");
    }
    this.initialData = null;
  }
  generateColumnStateForRowGroupAndPivotIndexes(updatedRowGroupColumnState, updatedPivotColumnState) {
    const existingColumnStateUpdates = {};
    const { rowGroupColsSvc, pivotColsSvc } = this.beans;
    rowGroupColsSvc?.restoreColumnOrder(existingColumnStateUpdates, updatedRowGroupColumnState);
    pivotColsSvc?.restoreColumnOrder(existingColumnStateUpdates, updatedPivotColumnState);
    return Object.values(existingColumnStateUpdates);
  }
  resetColDefIntoCol(column2, source2) {
    const userColDef = column2.getUserProvidedColDef();
    if (!userColDef) {
      return false;
    }
    const newColDef = _addColumnDefaultAndTypes(this.beans, userColDef, column2.getColId());
    column2.setColDef(newColDef, userColDef, source2);
    return true;
  }
  getDateStringTypeDefinition(column2) {
    const { dateString } = this.dataTypeDefinitions;
    if (!column2) {
      return dateString;
    }
    return this.getDataTypeDefinition(column2) ?? dateString;
  }
  getDateParserFunction(column2) {
    return this.getDateStringTypeDefinition(column2).dateParser;
  }
  getDateFormatterFunction(column2) {
    return this.getDateStringTypeDefinition(column2).dateFormatter;
  }
  getDateIncludesTimeFlag(cellDataType) {
    return cellDataType === "dateTime" || cellDataType === "dateTimeString";
  }
  getDataTypeDefinition(column2) {
    const colDef = column2.getColDef();
    if (!colDef.cellDataType) {
      return void 0;
    }
    return this.dataTypeDefinitions[colDef.cellDataType];
  }
  getBaseDataType(column2) {
    return this.getDataTypeDefinition(column2)?.baseDataType;
  }
  checkType(column2, value2) {
    if (value2 == null) {
      return true;
    }
    const dataTypeMatcher = this.getDataTypeDefinition(column2)?.dataTypeMatcher;
    if (!dataTypeMatcher) {
      return true;
    }
    return dataTypeMatcher(value2);
  }
  validateColDef(colDef) {
    const warning2 = (property) => _warn(48, { property });
    if (colDef.cellDataType === "object") {
      const { object: object2 } = this.dataTypeDefinitions;
      if (colDef.valueFormatter === object2.groupSafeValueFormatter && !this.hasObjectValueFormatter) {
        warning2("Formatter");
      }
      if (colDef.editable && colDef.valueParser === object2.valueParser && !this.hasObjectValueParser) {
        warning2("Parser");
      }
    }
  }
  postProcess(colDef) {
    const cellDataType = colDef.cellDataType;
    if (!cellDataType || typeof cellDataType !== "string") {
      return;
    }
    const { dataTypeDefinitions, beans, formatValueFuncs } = this;
    const dataTypeDefinition = dataTypeDefinitions[cellDataType];
    if (!dataTypeDefinition) {
      return;
    }
    beans.colFilter?.setColDefPropsForDataType(colDef, dataTypeDefinition, formatValueFuncs[cellDataType]);
  }
  // noinspection JSUnusedGlobalSymbols
  getFormatValue(cellDataType) {
    return this.formatValueFuncs[cellDataType];
  }
  isColPendingInference(colId) {
    return this.isPendingInference && !!this.columnStateUpdatesPendingInference[colId];
  }
  setColDefPropertiesForBaseDataType(colDef, cellDataType, dataTypeDefinition, colId) {
    const formatValue2 = this.formatValueFuncs[cellDataType];
    const partialColDef = this.columnDefinitionPropsPerDataType[dataTypeDefinition.baseDataType]({
      colDef,
      cellDataType,
      colModel: this.colModel,
      dataTypeDefinition,
      colId,
      formatValue: formatValue2
    });
    Object.assign(colDef, partialColDef);
  }
  getDateObjectTypeDef(baseDataType) {
    const translate = this.getLocaleTextFunc();
    const includeTime = this.getDateIncludesTimeFlag(baseDataType);
    return {
      baseDataType,
      valueParser: (params) => _parseDateTimeFromString(params.newValue && String(params.newValue)),
      valueFormatter: (params) => {
        if (params.value == null) {
          return "";
        }
        if (!(params.value instanceof Date) || isNaN(params.value.getTime())) {
          return translate("invalidDate", "Invalid Date");
        }
        return _serialiseDate(params.value, includeTime) ?? "";
      },
      dataTypeMatcher: (value2) => value2 instanceof Date
    };
  }
  getDateStringTypeDef(baseDataType) {
    const includeTime = this.getDateIncludesTimeFlag(baseDataType);
    return {
      baseDataType,
      dateParser: (value2) => _parseDateTimeFromString(value2) ?? void 0,
      dateFormatter: (value2) => _serialiseDate(value2 ?? null, includeTime) ?? void 0,
      valueParser: (params) => _isValidDate(String(params.newValue)) ? params.newValue : null,
      valueFormatter: (params) => _isValidDate(String(params.value)) ? String(params.value) : "",
      dataTypeMatcher: (value2) => typeof value2 === "string" && _isValidDate(value2)
    };
  }
  getDefaultDataTypes() {
    const translate = this.getLocaleTextFunc();
    return {
      number: {
        baseDataType: "number",
        // can be empty space with legacy copy
        valueParser: (params) => params.newValue?.trim?.() === "" ? null : Number(params.newValue),
        valueFormatter: (params) => {
          if (params.value == null) {
            return "";
          }
          if (typeof params.value !== "number" || isNaN(params.value)) {
            return translate("invalidNumber", "Invalid Number");
          }
          return String(params.value);
        },
        dataTypeMatcher: (value2) => typeof value2 === "number"
      },
      text: {
        baseDataType: "text",
        valueParser: (params) => params.newValue === "" ? null : _toStringOrNull(params.newValue),
        dataTypeMatcher: (value2) => typeof value2 === "string"
      },
      boolean: {
        baseDataType: "boolean",
        valueParser: (params) => {
          if (params.newValue == null) {
            return params.newValue;
          }
          return params.newValue?.trim?.() === "" ? null : String(params.newValue).toLowerCase() === "true";
        },
        valueFormatter: (params) => params.value == null ? "" : String(params.value),
        dataTypeMatcher: (value2) => typeof value2 === "boolean"
      },
      date: this.getDateObjectTypeDef("date"),
      dateString: this.getDateStringTypeDef("dateString"),
      dateTime: this.getDateObjectTypeDef("dateTime"),
      dateTimeString: {
        ...this.getDateStringTypeDef("dateTimeString"),
        dataTypeMatcher: (value2) => typeof value2 === "string" && _isValidDateTime(value2)
      },
      object: {
        baseDataType: "object",
        valueParser: () => null,
        valueFormatter: (params) => _toStringOrNull(params.value) ?? ""
      }
    };
  }
  destroyColumnStateUpdateListeners() {
    for (const destroyFunc of this.columnStateUpdateListenerDestroyFuncs) {
      destroyFunc();
    }
    this.columnStateUpdateListenerDestroyFuncs = [];
  }
  destroy() {
    this.dataTypeDefinitions = {};
    this.dataTypeMatchers = {};
    this.formatValueFuncs = {};
    this.columnStateUpdatesPendingInference = {};
    this.destroyColumnStateUpdateListeners();
    super.destroy();
  }
};
function mergeDataTypeDefinitions(parentDataTypeDefinition, childDataTypeDefinition) {
  const mergedDataTypeDefinition = {
    ...parentDataTypeDefinition,
    ...childDataTypeDefinition
  };
  if (parentDataTypeDefinition.columnTypes && childDataTypeDefinition.columnTypes && childDataTypeDefinition.appendColumnTypes) {
    mergedDataTypeDefinition.columnTypes = [
      ...convertColumnTypes(parentDataTypeDefinition.columnTypes),
      ...convertColumnTypes(childDataTypeDefinition.columnTypes)
    ];
  }
  return mergedDataTypeDefinition;
}
function validateDataTypeDefinition(dataTypeDefinition, parentDataTypeDefinition, parentCellDataType) {
  if (!parentDataTypeDefinition) {
    _warn(45, { parentCellDataType });
    return false;
  }
  if (parentDataTypeDefinition.baseDataType !== dataTypeDefinition.baseDataType) {
    _warn(46);
    return false;
  }
  return true;
}
function createGroupSafeValueFormatter(dataTypeDefinition, gos) {
  if (!dataTypeDefinition.valueFormatter) {
    return void 0;
  }
  return (params) => {
    if (params.node?.group) {
      const aggFunc = (params.colDef.pivotValueColumn ?? params.column).getAggFunc();
      if (aggFunc) {
        if (aggFunc === "first" || aggFunc === "last") {
          return dataTypeDefinition.valueFormatter(params);
        }
        if (dataTypeDefinition.baseDataType === "number" && aggFunc !== "count") {
          if (typeof params.value === "number") {
            return dataTypeDefinition.valueFormatter(params);
          }
          if (typeof params.value === "object") {
            if (!params.value) {
              return void 0;
            }
            if ("toNumber" in params.value) {
              return dataTypeDefinition.valueFormatter({
                ...params,
                value: params.value.toNumber()
              });
            }
            if ("value" in params.value) {
              return dataTypeDefinition.valueFormatter({
                ...params,
                value: params.value.value
              });
            }
          }
        }
        return void 0;
      }
    } else if (gos.get("groupHideOpenParents") && params.column.isRowGroupActive()) {
      if (typeof params.value === "string" && !dataTypeDefinition.dataTypeMatcher?.(params.value)) {
        return void 0;
      }
    }
    return dataTypeDefinition.valueFormatter(params);
  };
}
function doesColDefPropPreventInference(colDef, checkProps, prop, comparisonValue) {
  if (!checkProps[prop]) {
    return false;
  }
  const value2 = colDef[prop];
  if (value2 === null) {
    checkProps[prop] = false;
    return false;
  } else {
    return comparisonValue === void 0 ? !!value2 : value2 === comparisonValue;
  }
}
function doColDefPropsPreventInference(colDef, propsToCheckForInference) {
  return [
    ["cellRenderer", "agSparklineCellRenderer"],
    ["valueGetter", void 0],
    ["valueParser", void 0],
    ["refData", void 0]
  ].some(
    ([prop, comparisonValue]) => doesColDefPropPreventInference(colDef, propsToCheckForInference, prop, comparisonValue)
  );
}
function getUpdatedColumnState(column2, columnStateUpdates) {
  const columnState = getColumnStateFromColDef(column2);
  for (const key2 of columnStateUpdates) {
    delete columnState[key2];
    if (key2 === "rowGroup") {
      delete columnState.rowGroupIndex;
    } else if (key2 === "pivot") {
      delete columnState.pivotIndex;
    }
  }
  return columnState;
}
var DataTypeModule = {
  moduleName: "DataType",
  version: VERSION,
  beans: [DataTypeService],
  dependsOn: [CheckboxCellRendererModule]
};
var ColumnFlexModule = {
  moduleName: "ColumnFlex",
  version: VERSION,
  beans: [ColumnFlexService]
};
var ColumnApiModule = {
  moduleName: "ColumnApi",
  version: VERSION,
  beans: [ColumnDefFactory],
  apiFunctions: {
    getColumnDef,
    getDisplayNameForColumn,
    getColumn,
    getColumns,
    applyColumnState,
    getColumnState,
    resetColumnState,
    isPinning,
    isPinningLeft,
    isPinningRight,
    getDisplayedColAfter,
    getDisplayedColBefore,
    setColumnsVisible,
    setColumnsPinned,
    getAllGridColumns,
    getDisplayedLeftColumns,
    getDisplayedCenterColumns,
    getDisplayedRightColumns,
    getAllDisplayedColumns,
    getAllDisplayedVirtualColumns,
    getColumnDefs
  }
};
function _camelCaseToHumanText(camelCase) {
  if (!camelCase || camelCase == null) {
    return null;
  }
  const rex = /([a-z])([A-Z])/g;
  const rexCaps = /([A-Z]+)([A-Z])([a-z])/g;
  const words = camelCase.replace(rex, "$1 $2").replace(rexCaps, "$1 $2$3").replace(/\./g, " ").split(" ");
  return words.map((word) => word.substring(0, 1).toUpperCase() + (word.length > 1 ? word.substring(1, word.length) : "")).join(" ");
}
var ColumnNameService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "colNames";
  }
  getDisplayNameForColumn(column2, location, includeAggFunc = false) {
    if (!column2) {
      return null;
    }
    const headerName = this.getHeaderName(column2.getColDef(), column2, null, null, location);
    const { aggColNameSvc } = this.beans;
    if (includeAggFunc && aggColNameSvc) {
      return aggColNameSvc.getHeaderName(column2, headerName);
    }
    return headerName;
  }
  getDisplayNameForProvidedColumnGroup(columnGroup, providedColumnGroup, location) {
    const colGroupDef = providedColumnGroup?.getColGroupDef();
    if (colGroupDef) {
      return this.getHeaderName(colGroupDef, null, columnGroup, providedColumnGroup, location);
    }
    return null;
  }
  getDisplayNameForColumnGroup(columnGroup, location) {
    return this.getDisplayNameForProvidedColumnGroup(columnGroup, columnGroup.getProvidedColumnGroup(), location);
  }
  // location is where the column is going to appear, ie who is calling us
  getHeaderName(colDef, column2, columnGroup, providedColumnGroup, location) {
    const headerValueGetter = colDef.headerValueGetter;
    if (headerValueGetter) {
      const params = _addGridCommonParams(this.gos, {
        colDef,
        column: column2,
        columnGroup,
        providedColumnGroup,
        location
      });
      if (typeof headerValueGetter === "function") {
        return headerValueGetter(params);
      } else if (typeof headerValueGetter === "string") {
        return this.beans.expressionSvc?.evaluate(headerValueGetter, params) ?? null;
      }
      return "";
    } else if (colDef.headerName != null) {
      return colDef.headerName;
    } else if (colDef.field) {
      return _camelCaseToHumanText(colDef.field);
    }
    return "";
  }
};
var ColumnViewportService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "colViewport";
    this.colsWithinViewport = [];
    this.headerColsWithinViewport = [];
    this.colsWithinViewportHash = "";
    this.rowsOfHeadersToRenderLeft = {};
    this.rowsOfHeadersToRenderRight = {};
    this.rowsOfHeadersToRenderCenter = {};
    this.columnsToRenderLeft = [];
    this.columnsToRenderRight = [];
    this.columnsToRenderCenter = [];
  }
  wireBeans(beans) {
    this.visibleCols = beans.visibleCols;
    this.colModel = beans.colModel;
  }
  postConstruct() {
    this.suppressColumnVirtualisation = this.gos.get("suppressColumnVirtualisation");
  }
  setScrollPosition(scrollWidth, scrollPosition, afterScroll = false) {
    const { visibleCols } = this;
    const bodyWidthDirty = visibleCols.isBodyWidthDirty;
    const noChange = scrollWidth === this.scrollWidth && scrollPosition === this.scrollPosition && !bodyWidthDirty;
    if (noChange) {
      return;
    }
    this.scrollWidth = scrollWidth;
    this.scrollPosition = scrollPosition;
    visibleCols.isBodyWidthDirty = true;
    if (this.gos.get("enableRtl")) {
      const bodyWidth = visibleCols.bodyWidth;
      this.viewportLeft = bodyWidth - scrollPosition - scrollWidth;
      this.viewportRight = bodyWidth - scrollPosition;
    } else {
      this.viewportLeft = scrollPosition;
      this.viewportRight = scrollWidth + scrollPosition;
    }
    if (this.colModel.ready) {
      this.checkViewportColumns(afterScroll);
    }
  }
  /**
   * Returns the columns that are currently rendered in the viewport.
   */
  getColumnHeadersToRender(type) {
    switch (type) {
      case "left":
        return this.columnsToRenderLeft;
      case "right":
        return this.columnsToRenderRight;
      default:
        return this.columnsToRenderCenter;
    }
  }
  /**
   * Returns the column groups that are currently rendered in the viewport at a specific header row index.
   */
  getHeadersToRender(type, depth) {
    let result2;
    switch (type) {
      case "left":
        result2 = this.rowsOfHeadersToRenderLeft[depth];
        break;
      case "right":
        result2 = this.rowsOfHeadersToRenderRight[depth];
        break;
      default:
        result2 = this.rowsOfHeadersToRenderCenter[depth];
        break;
    }
    return result2 ?? [];
  }
  extractViewportColumns() {
    const displayedColumnsCenter = this.visibleCols.centerCols;
    if (this.isColumnVirtualisationSuppressed()) {
      this.colsWithinViewport = displayedColumnsCenter;
      this.headerColsWithinViewport = displayedColumnsCenter;
    } else {
      this.colsWithinViewport = displayedColumnsCenter.filter(this.isColumnInRowViewport.bind(this));
      this.headerColsWithinViewport = displayedColumnsCenter.filter(this.isColumnInHeaderViewport.bind(this));
    }
  }
  isColumnVirtualisationSuppressed() {
    return this.suppressColumnVirtualisation || this.viewportRight === 0;
  }
  clear() {
    this.rowsOfHeadersToRenderLeft = {};
    this.rowsOfHeadersToRenderRight = {};
    this.rowsOfHeadersToRenderCenter = {};
    this.colsWithinViewportHash = "";
  }
  isColumnInHeaderViewport(col) {
    if (col.isAutoHeaderHeight() || isAnyParentAutoHeaderHeight(col)) {
      return true;
    }
    return this.isColumnInRowViewport(col);
  }
  isColumnInRowViewport(col) {
    if (col.isAutoHeight()) {
      return true;
    }
    const columnLeft = col.getLeft() || 0;
    const columnRight = columnLeft + col.getActualWidth();
    const leftBounds = this.viewportLeft - 200;
    const rightBounds = this.viewportRight + 200;
    const columnToMuchLeft = columnLeft < leftBounds && columnRight < leftBounds;
    const columnToMuchRight = columnLeft > rightBounds && columnRight > rightBounds;
    return !columnToMuchLeft && !columnToMuchRight;
  }
  // used by Grid API only
  getViewportColumns() {
    const { leftCols, rightCols } = this.visibleCols;
    const res = this.colsWithinViewport.concat(leftCols).concat(rightCols);
    return res;
  }
  // + rowRenderer
  // if we are not column spanning, this just returns back the virtual centre columns,
  // however if we are column spanning, then different rows can have different virtual
  // columns, so we have to work out the list for each individual row.
  getColsWithinViewport(rowNode) {
    if (!this.colModel.colSpanActive) {
      return this.colsWithinViewport;
    }
    const emptySpaceBeforeColumn = (col) => {
      const left2 = col.getLeft();
      return _exists(left2) && left2 > this.viewportLeft;
    };
    const inViewportCallback = this.isColumnVirtualisationSuppressed() ? void 0 : this.isColumnInRowViewport.bind(this);
    const { visibleCols } = this;
    const displayedColumnsCenter = visibleCols.centerCols;
    return visibleCols.getColsForRow(rowNode, displayedColumnsCenter, inViewportCallback, emptySpaceBeforeColumn);
  }
  // checks what columns are currently displayed due to column virtualisation. dispatches an event
  // if the list of columns has changed.
  // + setColumnWidth(), setViewportPosition(), setColumnDefs(), sizeColumnsToFit()
  checkViewportColumns(afterScroll = false) {
    const viewportColumnsChanged = this.extractViewport();
    if (viewportColumnsChanged) {
      this.eventSvc.dispatchEvent({
        type: "virtualColumnsChanged",
        afterScroll
      });
    }
  }
  calculateHeaderRows() {
    const { leftCols, rightCols } = this.visibleCols;
    this.columnsToRenderLeft = leftCols;
    this.columnsToRenderRight = rightCols;
    this.columnsToRenderCenter = this.colsWithinViewport;
    const workOutGroupsToRender = (cols) => {
      const groupsToRenderSet = /* @__PURE__ */ new Set();
      const groupsToRender = {};
      for (const col of cols) {
        let group = col.getParent();
        const skipFillers = col.isSpanHeaderHeight();
        while (group) {
          if (groupsToRenderSet.has(group)) {
            break;
          }
          const skipFillerGroup = skipFillers && group.isPadding();
          if (skipFillerGroup) {
            group = group.getParent();
            continue;
          }
          const level = group.getProvidedColumnGroup().getLevel();
          groupsToRender[level] ?? (groupsToRender[level] = []);
          groupsToRender[level].push(group);
          groupsToRenderSet.add(group);
          group = group.getParent();
        }
      }
      return groupsToRender;
    };
    this.rowsOfHeadersToRenderLeft = workOutGroupsToRender(leftCols);
    this.rowsOfHeadersToRenderRight = workOutGroupsToRender(rightCols);
    this.rowsOfHeadersToRenderCenter = workOutGroupsToRender(this.headerColsWithinViewport);
  }
  extractViewport() {
    const hashColumn = (c2) => `${c2.getId()}-${c2.getPinned() || "normal"}`;
    this.extractViewportColumns();
    const newHash = this.getViewportColumns().map(hashColumn).join("#");
    const changed = this.colsWithinViewportHash !== newHash;
    if (changed) {
      this.colsWithinViewportHash = newHash;
      this.calculateHeaderRows();
    }
    return changed;
  }
};
function isAnyParentAutoHeaderHeight(col) {
  while (col) {
    if (col.isAutoHeaderHeight()) {
      return true;
    }
    col = col.getParent();
  }
  return false;
}
var AgComponentUtils = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "agCompUtils";
  }
  adaptFunction(type, jsCompFunc) {
    if (!type.cellRenderer) {
      return null;
    }
    class Adapter {
      refresh() {
        return false;
      }
      getGui() {
        return this.eGui;
      }
      init(params) {
        const callbackResult = jsCompFunc(params);
        const type2 = typeof callbackResult;
        if (type2 === "string" || type2 === "number" || type2 === "boolean") {
          this.eGui = _loadTemplate("<span>" + callbackResult + "</span>");
          return;
        }
        if (callbackResult == null) {
          this.eGui = _createElement({ tag: "span" });
          return;
        }
        this.eGui = callbackResult;
      }
    }
    return Adapter;
  }
};
var CellRendererFunctionModule = {
  moduleName: "CellRendererFunction",
  version: VERSION,
  beans: [AgComponentUtils]
};
var Registry = class extends BaseRegistry {
  constructor() {
    super(...arguments);
    this.agGridDefaults = {};
    this.agGridDefaultOverrides = {};
    this.jsComps = {};
    this.selectors = {};
    this.icons = {};
  }
  postConstruct() {
    const comps = this.gos.get("components");
    if (comps != null) {
      for (const key2 of Object.keys(comps)) {
        this.jsComps[key2] = comps[key2];
      }
    }
  }
  registerModule(module) {
    const { icons, userComponents, dynamicBeans, selectors } = module;
    if (userComponents) {
      const registerUserComponent = (name2, component, params, processParams) => {
        this.agGridDefaults[name2] = component;
        if (params || processParams) {
          this.agGridDefaultOverrides[name2] = { params, processParams };
        }
      };
      for (const name2 of Object.keys(userComponents)) {
        let comp = userComponents[name2];
        if (isComponentMetaFunc(comp)) {
          comp = comp.getComp(this.beans);
        }
        if (typeof comp === "object") {
          const { classImp, params, processParams } = comp;
          registerUserComponent(name2, classImp, params, processParams);
        } else {
          registerUserComponent(name2, comp);
        }
      }
    }
    this.registerDynamicBeans(dynamicBeans);
    for (const selector of selectors ?? []) {
      this.selectors[selector.selector] = selector;
    }
    if (icons) {
      for (const name2 of Object.keys(icons)) {
        this.icons[name2] = icons[name2];
      }
    }
  }
  getUserComponent(propertyName, name2) {
    const createResult = (component, componentFromFramework, params, processParams) => ({
      componentFromFramework,
      component,
      params,
      processParams
    });
    const { frameworkOverrides } = this.beans;
    const registeredViaFrameworkComp = frameworkOverrides.frameworkComponent(name2, this.gos.get("components"));
    if (registeredViaFrameworkComp != null) {
      return createResult(registeredViaFrameworkComp, true);
    }
    const jsComponent = this.jsComps[name2];
    if (jsComponent) {
      const isFwkComp = frameworkOverrides.isFrameworkComponent(jsComponent);
      return createResult(jsComponent, isFwkComp);
    }
    const defaultComponent = this.agGridDefaults[name2];
    if (defaultComponent) {
      const overrides = this.agGridDefaultOverrides[name2];
      return createResult(defaultComponent, false, overrides?.params, overrides?.processParams);
    }
    this.beans.validation?.missingUserComponent(propertyName, name2, this.agGridDefaults, this.jsComps);
    return null;
  }
  getSelector(name2) {
    return this.selectors[name2];
  }
  getIcon(name2) {
    return this.icons[name2];
  }
  getDynamicError(name2, init) {
    if (init) {
      return _errMsg(279, { name: name2 });
    }
    return this.beans.validation?.missingDynamicBean(name2) ?? _errMsg(256);
  }
};
var NUM_CTRLS = 23;
var CtrlsService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "ctrlsSvc";
    this.params = {};
    this.ready = false;
    this.readyCallbacks = [];
  }
  postConstruct() {
    this.addEventListener(
      "ready",
      () => {
        this.updateReady();
        if (this.ready) {
          for (const callback of this.readyCallbacks) {
            callback(this.params);
          }
          this.readyCallbacks.length = 0;
        }
      },
      this.beans.frameworkOverrides.runWhenReadyAsync?.() ?? false
    );
  }
  updateReady() {
    const values2 = Object.values(this.params);
    this.ready = values2.length === NUM_CTRLS && values2.every((ctrl) => {
      return ctrl?.isAlive() ?? false;
    });
  }
  whenReady(caller, callback) {
    if (this.ready) {
      callback(this.params);
    } else {
      this.readyCallbacks.push(callback);
    }
    caller.addDestroyFunc(() => {
      const index = this.readyCallbacks.indexOf(callback);
      if (index >= 0) {
        this.readyCallbacks.splice(index, 1);
      }
    });
  }
  register(ctrlType, ctrl) {
    this.params[ctrlType] = ctrl;
    this.updateReady();
    if (this.ready) {
      this.dispatchLocalEvent({ type: "ready" });
    }
    ctrl.addDestroyFunc(() => {
      this.updateReady();
    });
  }
  get(ctrlType) {
    return this.params[ctrlType];
  }
  getGridBodyCtrl() {
    return this.params.gridBodyCtrl;
  }
  getHeaderRowContainerCtrls() {
    const { leftHeader, centerHeader, rightHeader } = this.params;
    return [leftHeader, rightHeader, centerHeader];
  }
  getHeaderRowContainerCtrl(pinned) {
    const params = this.params;
    switch (pinned) {
      case "left":
        return params.leftHeader;
      case "right":
        return params.rightHeader;
      default:
        return params.centerHeader;
    }
  }
  getScrollFeature() {
    return this.getGridBodyCtrl().scrollFeature;
  }
};
var coreCSS = (
  /*css*/
  `.ag-aria-description-container{border:0;z-index:9999;clip:rect(1px,1px,1px,1px);height:1px;overflow:hidden;padding:0;position:absolute;white-space:nowrap;width:1px}.ag-unselectable{-webkit-user-select:none;-moz-user-select:none;user-select:none}.ag-selectable{-webkit-user-select:text;-moz-user-select:text;user-select:text}.ag-tab-guard{display:block;height:0;position:absolute;width:0}:where(.ag-virtual-list-viewport) .ag-tab-guard{position:sticky}.ag-tab-guard-top{top:1px}.ag-tab-guard-bottom{bottom:1px}.ag-shake-left-to-right{animation-direction:alternate;animation-duration:.2s;animation-iteration-count:infinite;animation-name:ag-shake-left-to-right}@keyframes ag-shake-left-to-right{0%{padding-left:6px;padding-right:2px}to{padding-left:2px;padding-right:6px}}.ag-body-horizontal-scroll-viewport,.ag-body-vertical-scroll-viewport,.ag-body-viewport,.ag-center-cols-viewport,.ag-floating-bottom-viewport,.ag-floating-top-viewport,.ag-header-viewport,.ag-sticky-bottom-viewport,.ag-sticky-top-viewport,.ag-virtual-list-viewport{flex:1 1 auto;height:100%;min-width:0;overflow:hidden;position:relative}.ag-viewport{position:relative}.ag-spanning-container{position:absolute;top:0;z-index:1}.ag-body-viewport,.ag-center-cols-viewport,.ag-floating-bottom-viewport,.ag-floating-top-viewport,.ag-header-viewport,.ag-sticky-bottom-viewport,.ag-sticky-top-viewport{overflow-x:auto;-ms-overflow-style:none!important;scrollbar-width:none!important;&::-webkit-scrollbar{display:none!important}}.ag-body-viewport{display:flex;overflow-x:hidden;&:where(.ag-layout-normal){overflow-y:auto;-webkit-overflow-scrolling:touch}}.ag-floating-bottom-container,.ag-floating-top-container,.ag-sticky-bottom-container,.ag-sticky-top-container{min-height:1px}.ag-center-cols-viewport{min-height:100%;width:100%}.ag-body-horizontal-scroll-viewport{overflow-x:scroll}.ag-body-vertical-scroll-viewport{overflow-y:scroll}.ag-virtual-list-viewport{overflow:auto;width:100%}.ag-body-container,.ag-body-horizontal-scroll-container,.ag-body-vertical-scroll-container,.ag-center-cols-container,.ag-floating-bottom-container,.ag-floating-bottom-full-width-container,.ag-floating-top-container,.ag-full-width-container,.ag-header-container,.ag-pinned-left-cols-container,.ag-pinned-right-cols-container,.ag-sticky-bottom-container,.ag-sticky-top-container,.ag-virtual-list-container{position:relative}.ag-floating-bottom-container,.ag-floating-top-container,.ag-header-container,.ag-pinned-left-floating-bottom,.ag-pinned-left-floating-top,.ag-pinned-right-floating-bottom,.ag-pinned-right-floating-top,.ag-sticky-bottom-container,.ag-sticky-top-container{height:100%;white-space:nowrap}.ag-center-cols-container,.ag-pinned-right-cols-container{display:block}.ag-body-horizontal-scroll-container{height:100%}.ag-body-vertical-scroll-container{width:100%}.ag-floating-bottom-full-width-container,.ag-floating-top-full-width-container,.ag-full-width-container,.ag-sticky-bottom-full-width-container,.ag-sticky-top-full-width-container{pointer-events:none;position:absolute;top:0}:where(.ag-ltr) .ag-floating-bottom-full-width-container,:where(.ag-ltr) .ag-floating-top-full-width-container,:where(.ag-ltr) .ag-full-width-container,:where(.ag-ltr) .ag-sticky-bottom-full-width-container,:where(.ag-ltr) .ag-sticky-top-full-width-container{left:0}:where(.ag-rtl) .ag-floating-bottom-full-width-container,:where(.ag-rtl) .ag-floating-top-full-width-container,:where(.ag-rtl) .ag-full-width-container,:where(.ag-rtl) .ag-sticky-bottom-full-width-container,:where(.ag-rtl) .ag-sticky-top-full-width-container{right:0}.ag-full-width-container{width:100%}.ag-floating-bottom-full-width-container,.ag-floating-top-full-width-container{display:inline-block;height:100%;overflow:hidden;width:100%}.ag-virtual-list-container{overflow:hidden}.ag-body{display:flex;flex:1 1 auto;flex-direction:row!important;min-height:0;position:relative}.ag-body-horizontal-scroll,.ag-body-vertical-scroll{display:flex;min-height:0;min-width:0;position:relative;&:where(.ag-scrollbar-invisible){bottom:0;position:absolute;&:where(.ag-apple-scrollbar){opacity:0;transition:opacity .4s;visibility:hidden;&:where(.ag-scrollbar-scrolling,.ag-scrollbar-active){opacity:1;visibility:visible}}}}.ag-body-horizontal-scroll{width:100%;&:where(.ag-scrollbar-invisible){left:0;right:0}}.ag-body-vertical-scroll{height:100%;&:where(.ag-scrollbar-invisible){top:0;z-index:10}}:where(.ag-ltr) .ag-body-vertical-scroll{&:where(.ag-scrollbar-invisible){right:0}}:where(.ag-rtl) .ag-body-vertical-scroll{&:where(.ag-scrollbar-invisible){left:0}}.ag-force-vertical-scroll{overflow-y:scroll!important}.ag-horizontal-left-spacer,.ag-horizontal-right-spacer{height:100%;min-width:0;overflow-x:scroll;&:where(.ag-scroller-corner){overflow-x:hidden}}:where(.ag-row-animation) .ag-row{transition:transform .4s,top .4s,opacity .2s;&:where(.ag-after-created){transition:transform .4s,top .4s,height .4s,opacity .2s}}:where(.ag-row-animation.ag-prevent-animation) .ag-row{transition:none!important;&:where(.ag-row.ag-after-created){transition:none!important}}:where(.ag-row-no-animation) .ag-row{transition:none}.ag-row-loading{align-items:center;display:flex}.ag-row-position-absolute{position:absolute}.ag-row-position-relative{position:relative}.ag-full-width-row{overflow:hidden;pointer-events:all}.ag-row-inline-editing{z-index:1}.ag-row-dragging{z-index:2}.ag-stub-cell{align-items:center;display:flex}.ag-cell{display:inline-block;height:100%;position:absolute;white-space:nowrap;&:focus-visible{box-shadow:none}}.ag-cell-value{flex:1 1 auto}.ag-cell-value:not(.ag-allow-overflow),.ag-group-value{overflow:hidden;text-overflow:ellipsis}.ag-cell-wrap-text{white-space:normal;word-break:break-word}:where(.ag-cell) .ag-icon{display:inline-block;vertical-align:middle}.ag-floating-top{display:flex;overflow:hidden;position:relative;white-space:nowrap;width:100%}:where(.ag-floating-top:not(.ag-invisible)){border-bottom:var(--ag-pinned-row-border)}.ag-floating-bottom{display:flex;overflow:hidden;position:relative;white-space:nowrap;width:100%}:where(.ag-floating-bottom:not(.ag-invisible)){border-top:var(--ag-pinned-row-border)}.ag-sticky-bottom,.ag-sticky-top{background-color:var(--ag-data-background-color);display:flex;height:0;overflow:hidden;position:absolute;width:100%;z-index:1}.ag-opacity-zero{opacity:0!important}.ag-cell-label-container{align-items:center;display:flex;flex-direction:row-reverse;height:100%;justify-content:space-between;width:100%}:where(.ag-right-aligned-header){.ag-cell-label-container{flex-direction:row}.ag-header-cell-text{text-align:end}}.ag-column-group-icons{display:block;>*{cursor:pointer}}:where(.ag-ltr){direction:ltr;.ag-body,.ag-body-horizontal-scroll,.ag-body-viewport,.ag-floating-bottom,.ag-floating-top,.ag-header,.ag-sticky-bottom,.ag-sticky-top{flex-direction:row}}:where(.ag-rtl){direction:rtl;text-align:right;.ag-body,.ag-body-horizontal-scroll,.ag-body-viewport,.ag-floating-bottom,.ag-floating-top,.ag-header,.ag-sticky-bottom,.ag-sticky-top{flex-direction:row-reverse}.ag-icon-contracted,.ag-icon-expanded,.ag-icon-tree-closed{display:block}}:where(.ag-rtl){.ag-icon-contracted,.ag-icon-expanded,.ag-icon-tree-closed{transform:rotate(180deg)}}:where(.ag-rtl){.ag-icon-contracted,.ag-icon-expanded,.ag-icon-tree-closed{transform:rotate(-180deg)}}.ag-measurement-container{height:0;overflow:hidden;visibility:hidden;width:0}.ag-measurement-element-border{display:inline-block;&:before{border-left:var(--ag-internal-measurement-border);content:"";display:block}}.ag-group{position:relative;width:100%}.ag-group-title-bar{align-items:center;display:flex;padding:var(--ag-spacing)}.ag-group-title{display:inline;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}:where(.ag-group-title-bar) .ag-group-title{cursor:default}.ag-group-toolbar{align-items:center;display:flex;padding:var(--ag-spacing)}.ag-group-container{display:flex}.ag-disabled .ag-group-container{pointer-events:none}.ag-disabled-group-container,.ag-disabled-group-title-bar{opacity:.5}.ag-group-container-horizontal{flex-flow:row wrap}.ag-group-container-vertical{flex-direction:column}.ag-group-title-bar-icon{cursor:pointer;flex:none}:where(.ag-ltr) .ag-group-title-bar-icon{margin-right:var(--ag-spacing)}:where(.ag-rtl) .ag-group-title-bar-icon{margin-left:var(--ag-spacing)}:where(.ag-group-item-alignment-stretch) .ag-group-item{align-items:stretch}:where(.ag-group-item-alignment-start) .ag-group-item{align-items:flex-start}:where(.ag-group-item-alignment-end) .ag-group-item{align-items:flex-end}:where(.ag-ltr) .ag-row:not(.ag-row-level-0) .ag-pivot-leaf-group{margin-left:var(--ag-row-group-indent-size)}:where(.ag-rtl) .ag-row:not(.ag-row-level-0) .ag-pivot-leaf-group{margin-right:var(--ag-row-group-indent-size)}:where(.ag-ltr) .ag-row-group-leaf-indent{margin-left:calc(var(--ag-cell-widget-spacing) + var(--ag-icon-size))}:where(.ag-rtl) .ag-row-group-leaf-indent{margin-right:calc(var(--ag-cell-widget-spacing) + var(--ag-icon-size))}.ag-value-change-delta{padding:0 2px}.ag-value-change-delta-up{color:var(--ag-value-change-delta-up-color)}.ag-value-change-delta-down{color:var(--ag-value-change-delta-down-color)}.ag-value-change-value{background-color:transparent;border-radius:1px;padding-left:1px;padding-right:1px;transition:background-color 1s}.ag-value-change-value-highlight{background-color:var(--ag-value-change-value-highlight-background-color);transition:background-color .1s}.ag-cell-data-changed{background-color:var(--ag-value-change-value-highlight-background-color)!important}.ag-cell-data-changed-animation{background-color:transparent}.ag-cell-highlight{background-color:var(--ag-range-selection-highlight-color)!important}.ag-row,.ag-spanned-row{color:var(--ag-cell-text-color);font-family:var(--ag-cell-font-family);font-size:var(--ag-data-font-size);white-space:nowrap;--ag-internal-content-line-height:calc(min(var(--ag-row-height), var(--ag-line-height, 1000px)) - var(--ag-internal-row-border-width, 1px) - 2px)}.ag-row{background-color:var(--ag-data-background-color);border-bottom:var(--ag-row-border);height:var(--ag-row-height);width:100%;&.ag-row-editing-invalid{background-color:var(--ag-full-row-edit-invalid-background-color)}}:where(.ag-body-vertical-content-no-gap>div>div>div,.ag-body-vertical-content-no-gap>div>div>div>div)>.ag-row-last{border-bottom-color:transparent}.ag-sticky-bottom{border-top:var(--ag-row-border);box-sizing:content-box!important}.ag-group-contracted,.ag-group-expanded{cursor:pointer}.ag-cell,.ag-full-width-row .ag-cell-wrapper.ag-row-group{border:1px solid transparent;line-height:var(--ag-internal-content-line-height);-webkit-font-smoothing:subpixel-antialiased}:where(.ag-ltr) .ag-cell{border-right:var(--ag-column-border)}:where(.ag-rtl) .ag-cell{border-left:var(--ag-column-border)}.ag-spanned-cell-wrapper{background-color:var(--ag-data-background-color);position:absolute}.ag-spanned-cell-wrapper>.ag-spanned-cell{display:block;position:relative}:where(.ag-ltr) :where(.ag-body-horizontal-content-no-gap) .ag-column-last{border-right-color:transparent}:where(.ag-rtl) :where(.ag-body-horizontal-content-no-gap) .ag-column-last{border-left-color:transparent}.ag-cell-wrapper{align-items:center;display:flex;>:where(:not(.ag-cell-value,.ag-group-value)){align-items:center;display:flex;height:var(--ag-internal-content-line-height)}&:where(.ag-row-group){align-items:flex-start}:where(.ag-full-width-row) &:where(.ag-row-group){align-items:center;height:100%}}:where(.ag-ltr) .ag-cell-wrapper{padding-left:calc(var(--ag-indentation-level)*var(--ag-row-group-indent-size))}:where(.ag-rtl) .ag-cell-wrapper{padding-right:calc(var(--ag-indentation-level)*var(--ag-row-group-indent-size))}:where(.ag-cell-wrap-text:not(.ag-cell-auto-height)) .ag-cell-wrapper{align-items:normal;height:100%;:where(.ag-cell-value){height:100%}}:where(.ag-ltr) .ag-row>.ag-cell-wrapper.ag-row-group{padding-left:calc(var(--ag-cell-horizontal-padding) + var(--ag-row-group-indent-size)*var(--ag-indentation-level))}:where(.ag-rtl) .ag-row>.ag-cell-wrapper.ag-row-group{padding-right:calc(var(--ag-cell-horizontal-padding) + var(--ag-row-group-indent-size)*var(--ag-indentation-level))}.ag-cell-focus:not(.ag-cell-range-selected):focus-within,.ag-cell-range-single-cell,.ag-cell-range-single-cell.ag-cell-range-handle,.ag-context-menu-open .ag-cell-focus:not(.ag-cell-range-selected),.ag-context-menu-open .ag-full-width-row.ag-row-focus .ag-cell-wrapper.ag-row-group,.ag-full-width-row.ag-row-focus:focus .ag-cell-wrapper.ag-row-group{border:1px solid;border-color:var(--ag-range-selection-border-color);border-style:var(--ag-range-selection-border-style);outline:initial}.ag-full-width-row.ag-row-focus:focus{box-shadow:none}:where(.ag-ltr) .ag-group-contracted,:where(.ag-ltr) .ag-group-expanded,:where(.ag-ltr) .ag-row-drag,:where(.ag-ltr) .ag-selection-checkbox{margin-right:var(--ag-cell-widget-spacing)}:where(.ag-rtl) .ag-group-contracted,:where(.ag-rtl) .ag-group-expanded,:where(.ag-rtl) .ag-row-drag,:where(.ag-rtl) .ag-selection-checkbox{margin-left:var(--ag-cell-widget-spacing)}:where(.ag-ltr) .ag-group-child-count{margin-left:3px}:where(.ag-rtl) .ag-group-child-count{margin-right:3px}.ag-row-highlight-above:after,.ag-row-highlight-below:after,.ag-row-highlight-inside:after{background-color:var(--ag-range-selection-border-color);content:"";height:1px;pointer-events:none;position:absolute;width:calc(100% - 1px)}:where(.ag-ltr) .ag-row-highlight-above:after,:where(.ag-ltr) .ag-row-highlight-below:after,:where(.ag-ltr) .ag-row-highlight-inside:after{left:1px}:where(.ag-rtl) .ag-row-highlight-above:after,:where(.ag-rtl) .ag-row-highlight-below:after,:where(.ag-rtl) .ag-row-highlight-inside:after{right:1px}.ag-row-highlight-above:after{top:0}.ag-row-highlight-below:after{bottom:0}.ag-row-highlight-indent:after{display:block;width:auto}:where(.ag-ltr) .ag-row-highlight-indent:after{left:calc((var(--ag-cell-widget-spacing) + var(--ag-icon-size))*2 + var(--ag-cell-horizontal-padding) + var(--ag-row-highlight-level)*var(--ag-row-group-indent-size));right:1px}:where(.ag-rtl) .ag-row-highlight-indent:after{left:1px;right:calc((var(--ag-cell-widget-spacing) + var(--ag-icon-size))*2 + var(--ag-cell-horizontal-padding) + var(--ag-row-highlight-level)*var(--ag-row-group-indent-size))}.ag-row-highlight-inside:after{background-color:var(--ag-selected-row-background-color);border:1px solid var(--ag-range-selection-border-color);display:block;height:auto;inset:0;width:auto}.ag-body,.ag-floating-bottom,.ag-floating-top{background-color:var(--ag-data-background-color)}.ag-row-odd{background-color:var(--ag-odd-row-background-color)}.ag-row-selected:before{background-color:var(--ag-selected-row-background-color);content:"";display:block;inset:0;pointer-events:none;position:absolute}.ag-row-hover.ag-full-width-row.ag-row-group:before,.ag-row-hover:not(.ag-full-width-row):before{background-color:var(--ag-row-hover-color);content:"";display:block;inset:0;pointer-events:none;position:absolute}.ag-row-hover.ag-row-selected:before{background-color:var(--ag-row-hover-color);background-image:linear-gradient(var(--ag-selected-row-background-color),var(--ag-selected-row-background-color))}.ag-row.ag-full-width-row.ag-row-group>*{position:relative}.ag-column-hover{background-color:var(--ag-column-hover-color)}.ag-header-range-highlight{background-color:var(--ag-range-header-highlight-color)}.ag-right-aligned-cell{font-variant-numeric:tabular-nums}:where(.ag-ltr) .ag-right-aligned-cell{text-align:right}:where(.ag-rtl) .ag-right-aligned-cell{text-align:left}.ag-right-aligned-cell .ag-cell-value,.ag-right-aligned-cell .ag-group-value{margin-left:auto}:where(.ag-ltr) .ag-cell:not(.ag-cell-inline-editing),:where(.ag-ltr) .ag-full-width-row .ag-cell-wrapper.ag-row-group{padding-left:calc(var(--ag-cell-horizontal-padding) - 1px + var(--ag-row-group-indent-size)*var(--ag-indentation-level));padding-right:calc(var(--ag-cell-horizontal-padding) - 1px)}:where(.ag-rtl) .ag-cell:not(.ag-cell-inline-editing),:where(.ag-rtl) .ag-full-width-row .ag-cell-wrapper.ag-row-group{padding-left:calc(var(--ag-cell-horizontal-padding) - 1px);padding-right:calc(var(--ag-cell-horizontal-padding) - 1px + var(--ag-row-group-indent-size)*var(--ag-indentation-level))}.ag-row>.ag-cell-wrapper{padding-left:calc(var(--ag-cell-horizontal-padding) - 1px);padding-right:calc(var(--ag-cell-horizontal-padding) - 1px)}.ag-row-dragging{cursor:move;opacity:.5}.ag-details-row{background-color:var(--ag-data-background-color);padding:calc(var(--ag-spacing)*3.75)}.ag-layout-auto-height,.ag-layout-print{.ag-center-cols-container,.ag-center-cols-viewport{min-height:150px}}.ag-overlay-loading-wrapper{background-color:var(--ag-modal-overlay-background-color)}.ag-skeleton-container{align-content:center;height:100%;width:100%}.ag-skeleton-effect{animation:ag-skeleton-loading 1.5s ease-in-out .5s infinite;background-color:var(--ag-row-loading-skeleton-effect-color);border-radius:.25rem;height:1em;width:100%}:where(.ag-ltr) .ag-right-aligned-cell .ag-skeleton-effect{margin-left:auto}:where(.ag-rtl) .ag-right-aligned-cell .ag-skeleton-effect{margin-right:auto}@keyframes ag-skeleton-loading{0%{background-color:var(--ag-row-loading-skeleton-effect-color)}50%{background-color:color-mix(in srgb,transparent,var(--ag-row-loading-skeleton-effect-color) 40%)}to{background-color:var(--ag-row-loading-skeleton-effect-color)}}.ag-loading{align-items:center;display:flex;height:100%}:where(.ag-ltr) .ag-loading{padding-left:var(--ag-cell-horizontal-padding)}:where(.ag-rtl) .ag-loading{padding-right:var(--ag-cell-horizontal-padding)}:where(.ag-ltr) .ag-loading-icon{padding-right:var(--ag-cell-widget-spacing)}:where(.ag-rtl) .ag-loading-icon{padding-left:var(--ag-cell-widget-spacing)}.ag-icon-loading{animation-duration:1s;animation-iteration-count:infinite;animation-name:spin;animation-timing-function:linear}@keyframes spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}.ag-header{background-color:var(--ag-header-background-color);border-bottom:var(--ag-header-row-border);color:var(--ag-header-text-color);display:flex;font-family:var(--ag-header-font-family);font-size:var(--ag-header-font-size);font-weight:var(--ag-header-font-weight);overflow:hidden;white-space:nowrap;width:100%}.ag-header-row{height:var(--ag-header-height);position:absolute}.ag-floating-filter-button-button,.ag-header-cell-filter-button,.ag-header-cell-menu-button,.ag-header-expand-icon,.ag-panel-title-bar-button,:where(.ag-header-cell-sortable) .ag-header-cell-label{cursor:pointer}:where(.ag-ltr) .ag-header-expand-icon{margin-left:4px}:where(.ag-rtl) .ag-header-expand-icon{margin-right:4px}.ag-header-row:where(:not(:first-child)){:where(.ag-header-cell:not(.ag-header-span-height.ag-header-span-total,.ag-header-parent-hidden),.ag-header-group-cell.ag-header-group-cell-with-group){border-top:var(--ag-header-row-border)}}.ag-header-row:where(:not(.ag-header-row-column-group)){overflow:hidden}:where(.ag-header.ag-header-allow-overflow) .ag-header-row{overflow:visible}.ag-header-cell{display:inline-flex;overflow:hidden}.ag-header-group-cell{contain:paint;display:flex}.ag-header-cell,.ag-header-group-cell{align-items:center;gap:var(--ag-cell-widget-spacing);height:100%;padding:0 var(--ag-cell-horizontal-padding);position:absolute}@property --ag-internal-moving-color{syntax:"<color>";inherits:false;initial-value:transparent}@property --ag-internal-hover-color{syntax:"<color>";inherits:false;initial-value:transparent}.ag-header-cell:where(:not(.ag-floating-filter)),.ag-header-group-cell{&:before{background-image:linear-gradient(var(--ag-internal-hover-color),var(--ag-internal-hover-color)),linear-gradient(var(--ag-internal-moving-color),var(--ag-internal-moving-color));content:"";inset:0;position:absolute;--ag-internal-moving-color:transparent;--ag-internal-hover-color:transparent;transition:--ag-internal-moving-color var(--ag-header-cell-background-transition-duration),--ag-internal-hover-color var(--ag-header-cell-background-transition-duration)}&:where(:hover):before{--ag-internal-hover-color:var(--ag-header-cell-hover-background-color)}&:where(.ag-header-cell-moving):before{--ag-internal-moving-color:var(--ag-header-cell-moving-background-color);--ag-internal-hover-color:var(--ag-header-cell-hover-background-color)}}:where(.ag-header-cell:not(.ag-floating-filter) *,.ag-header-group-cell *){position:relative;z-index:1}.ag-header-cell-menu-button:where(:not(.ag-header-menu-always-show)){opacity:0;transition:opacity .2s}.ag-header-cell-filter-button,:where(.ag-header-cell.ag-header-active) .ag-header-cell-menu-button{opacity:1}.ag-header-cell-label,.ag-header-group-cell-label{align-items:center;align-self:stretch;display:flex;flex:1 1 auto;overflow:hidden;padding:5px 0}:where(.ag-ltr) .ag-sort-indicator-icon{padding-left:var(--ag-spacing)}:where(.ag-rtl) .ag-sort-indicator-icon{padding-right:var(--ag-spacing)}.ag-header-cell-label{text-overflow:ellipsis}.ag-header-group-cell-label.ag-sticky-label{flex:none;max-width:100%;overflow:visible;position:sticky}:where(.ag-ltr) .ag-header-group-cell-label.ag-sticky-label{left:var(--ag-cell-horizontal-padding)}:where(.ag-rtl) .ag-header-group-cell-label.ag-sticky-label{right:var(--ag-cell-horizontal-padding)}.ag-header-cell-text,.ag-header-group-text{overflow:hidden;text-overflow:ellipsis}.ag-header-cell-text{word-break:break-word}.ag-header-cell-comp-wrapper{width:100%}:where(.ag-header-group-cell) .ag-header-cell-comp-wrapper{display:flex}:where(.ag-header-cell:not(.ag-header-cell-auto-height)) .ag-header-cell-comp-wrapper{align-items:center;display:flex;height:100%}.ag-header-cell-wrap-text .ag-header-cell-comp-wrapper{white-space:normal}.ag-header-cell-comp-wrapper-limited-height>*{overflow:hidden}:where(.ag-right-aligned-header) .ag-header-cell-label{flex-direction:row-reverse}:where(.ag-ltr) :where(.ag-header-cell:not(.ag-right-aligned-header)){.ag-header-label-icon,.ag-header-menu-icon{margin-left:var(--ag-spacing)}}:where(.ag-rtl) :where(.ag-header-cell:not(.ag-right-aligned-header)){.ag-header-label-icon,.ag-header-menu-icon{margin-right:var(--ag-spacing)}}:where(.ag-ltr) :where(.ag-header-cell.ag-right-aligned-header){.ag-header-label-icon,.ag-header-menu-icon{margin-right:var(--ag-spacing)}}:where(.ag-rtl) :where(.ag-header-cell.ag-right-aligned-header){.ag-header-label-icon,.ag-header-menu-icon{margin-left:var(--ag-spacing)}}.ag-header-cell:after,.ag-header-group-cell:where(:not(.ag-header-span-height.ag-header-group-cell-no-group)):after{content:"";height:var(--ag-header-column-border-height);position:absolute;top:calc(50% - var(--ag-header-column-border-height)*.5);z-index:1}:where(.ag-ltr) .ag-header-cell:after,:where(.ag-ltr) .ag-header-group-cell:where(:not(.ag-header-span-height.ag-header-group-cell-no-group)):after{border-right:var(--ag-header-column-border);right:0}:where(.ag-rtl) .ag-header-cell:after,:where(.ag-rtl) .ag-header-group-cell:where(:not(.ag-header-span-height.ag-header-group-cell-no-group)):after{border-left:var(--ag-header-column-border);left:0}.ag-header-highlight-after:after,.ag-header-highlight-before:after{background-color:var(--ag-accent-color);content:"";height:100%;position:absolute;width:1px}:where(.ag-ltr) .ag-header-highlight-before:after{left:0}:where(.ag-rtl) .ag-header-highlight-before:after{right:0}:where(.ag-ltr) .ag-header-highlight-after:after{right:0;:where(.ag-pinned-left-header) &{right:1px}}:where(.ag-rtl) .ag-header-highlight-after:after{left:0;:where(.ag-pinned-left-header) &{left:1px}}.ag-header-cell-resize{align-items:center;cursor:ew-resize;display:flex;height:100%;position:absolute;top:0;width:8px;z-index:2;&:after{background-color:var(--ag-header-column-resize-handle-color);content:"";height:var(--ag-header-column-resize-handle-height);position:absolute;top:calc(50% - var(--ag-header-column-resize-handle-height)*.5);width:var(--ag-header-column-resize-handle-width);z-index:1}}:where(.ag-ltr) .ag-header-cell-resize{right:-3px;&:after{left:calc(50% - var(--ag-header-column-resize-handle-width))}}:where(.ag-rtl) .ag-header-cell-resize{left:-3px;&:after{right:calc(50% - var(--ag-header-column-resize-handle-width))}}:where(.ag-header-cell.ag-header-span-height) .ag-header-cell-resize:after{height:calc(100% - var(--ag-spacing)*4);top:calc(var(--ag-spacing)*2)}.ag-header-group-cell-no-group:where(.ag-header-span-height){display:none}.ag-sort-indicator-container{display:flex;gap:var(--ag-spacing)}.ag-layout-print{&.ag-body{display:block;height:unset}&.ag-root-wrapper{display:inline-block}.ag-body-horizontal-scroll,.ag-body-vertical-scroll{display:none}&.ag-force-vertical-scroll{overflow-y:visible!important}}@media print{.ag-root-wrapper.ag-layout-print{display:table;.ag-body-horizontal-scroll-viewport,.ag-body-viewport,.ag-center-cols-container,.ag-center-cols-viewport,.ag-root,.ag-root-wrapper-body,.ag-virtual-list-viewport{display:block!important;height:auto!important;overflow:hidden!important}.ag-cell,.ag-row{-moz-column-break-inside:avoid;break-inside:avoid}}}ag-grid,ag-grid-angular{display:block}.ag-root-wrapper{border:var(--ag-wrapper-border);border-radius:var(--ag-wrapper-border-radius);display:flex;flex-direction:column;overflow:hidden;position:relative;&.ag-layout-normal{height:100%}}.ag-root-wrapper-body{display:flex;flex-direction:row;&.ag-layout-normal{flex:1 1 auto;height:0;min-height:0}}.ag-root{display:flex;flex-direction:column;position:relative;&.ag-layout-auto-height,&.ag-layout-normal{flex:1 1 auto;overflow:hidden;width:0}&.ag-layout-normal{height:100%}}.ag-virtual-list-item{height:var(--ag-list-item-height);position:absolute;width:100%}.ag-list-item-hovered:after{background-color:var(--ag-accent-color);content:"";height:1px;left:0;position:absolute;right:0}.ag-item-highlight-top:after{top:0}.ag-item-highlight-bottom:after{bottom:0}.ag-drag-handle{color:var(--ag-drag-handle-color);cursor:grab;:where(.ag-icon){color:var(--ag-drag-handle-color)}}.ag-chart-menu-icon,.ag-chart-settings-next,.ag-chart-settings-prev,.ag-column-group-icons,.ag-column-select-header-icon,.ag-filter-toolpanel-expand,.ag-floating-filter-button-button,.ag-group-title-bar-icon,.ag-header-cell-filter-button,.ag-header-cell-menu-button,.ag-header-expand-icon,.ag-panel-title-bar-button,.ag-panel-title-bar-button-icon,.ag-set-filter-group-icons,:where(.ag-group-contracted) .ag-icon,:where(.ag-group-expanded) .ag-icon{background-color:var(--ag-icon-button-background-color);border-radius:var(--ag-icon-button-border-radius);box-shadow:0 0 0 var(--ag-icon-button-background-spread) var(--ag-icon-button-background-color);color:var(--ag-icon-button-color);&:hover{background-color:var(--ag-icon-button-hover-background-color);box-shadow:0 0 0 var(--ag-icon-button-background-spread) var(--ag-icon-button-hover-background-color);color:var(--ag-icon-button-hover-color)}}.ag-filter-active{background-image:linear-gradient(var(--ag-icon-button-active-background-color),var(--ag-icon-button-active-background-color));border-radius:1px;outline:solid var(--ag-icon-button-background-spread) var(--ag-icon-button-active-background-color);position:relative;&:after{background-color:var(--ag-icon-button-active-indicator-color);border-radius:50%;content:"";height:6px;position:absolute;top:-1px;width:6px}:where(.ag-icon-filter){clip-path:path("M8,0C8,4.415 11.585,8 16,8L16,16L0,16L0,0L8,0Z");color:var(--ag-icon-button-active-color)}}:where(.ag-ltr) .ag-filter-active{&:after{right:-1px}}:where(.ag-rtl) .ag-filter-active{&:after{left:-1px}}.ag-menu{background-color:var(--ag-menu-background-color);border:var(--ag-menu-border);border-radius:var(--ag-border-radius);box-shadow:var(--ag-menu-shadow);color:var(--ag-menu-text-color);max-height:100%;overflow-y:auto;position:absolute;-webkit-user-select:none;-moz-user-select:none;user-select:none}`
);
var coreDefaults = {
  wrapperBorder: true,
  rowBorder: true,
  headerRowBorder: true,
  footerRowBorder: {
    ref: "rowBorder"
  },
  columnBorder: {
    style: "solid",
    width: 1,
    color: "transparent"
  },
  headerColumnBorder: false,
  headerColumnBorderHeight: "100%",
  pinnedColumnBorder: true,
  pinnedRowBorder: true,
  sidePanelBorder: true,
  sideBarPanelWidth: 250,
  sideBarBackgroundColor: {
    ref: "chromeBackgroundColor"
  },
  sideButtonBarBackgroundColor: {
    ref: "sideBarBackgroundColor"
  },
  sideButtonBarTopPadding: 0,
  sideButtonSelectedUnderlineWidth: 2,
  sideButtonSelectedUnderlineColor: "transparent",
  sideButtonSelectedUnderlineTransitionDuration: 0,
  sideButtonBackgroundColor: "transparent",
  sideButtonTextColor: { ref: "textColor" },
  sideButtonHoverBackgroundColor: { ref: "sideButtonBackgroundColor" },
  sideButtonHoverTextColor: { ref: "sideButtonTextColor" },
  sideButtonSelectedBackgroundColor: backgroundColor,
  sideButtonSelectedTextColor: { ref: "sideButtonTextColor" },
  sideButtonBorder: "solid 1px transparent",
  sideButtonSelectedBorder: true,
  sideButtonLeftPadding: { ref: "spacing" },
  sideButtonRightPadding: { ref: "spacing" },
  sideButtonVerticalPadding: { calc: "spacing * 3" },
  headerBackgroundColor: {
    ref: "chromeBackgroundColor"
  },
  headerFontFamily: {
    ref: "fontFamily"
  },
  cellFontFamily: {
    ref: "fontFamily"
  },
  headerFontWeight: 500,
  headerFontSize: {
    ref: "fontSize"
  },
  dataFontSize: {
    ref: "fontSize"
  },
  headerTextColor: {
    ref: "textColor"
  },
  headerCellHoverBackgroundColor: "transparent",
  headerCellMovingBackgroundColor: { ref: "headerCellHoverBackgroundColor" },
  headerCellBackgroundTransitionDuration: "0.2s",
  cellTextColor: {
    ref: "textColor"
  },
  rangeSelectionBorderStyle: "solid",
  rangeSelectionBorderColor: accentColor,
  rangeSelectionBackgroundColor: accentMix(0.2),
  rangeSelectionChartBackgroundColor: "#0058FF1A",
  rangeSelectionChartCategoryBackgroundColor: "#00FF841A",
  rangeSelectionHighlightColor: accentMix(0.5),
  rangeHeaderHighlightColor: foregroundHeaderBackgroundMix(0.08),
  rowNumbersSelectedColor: accentMix(0.5),
  rowHoverColor: accentMix(0.08),
  columnHoverColor: accentMix(0.05),
  selectedRowBackgroundColor: accentMix(0.12),
  modalOverlayBackgroundColor: {
    ref: "backgroundColor",
    mix: 0.66
  },
  dataBackgroundColor: backgroundColor,
  oddRowBackgroundColor: { ref: "dataBackgroundColor" },
  wrapperBorderRadius: 8,
  cellHorizontalPadding: {
    calc: "spacing * 2 * cellHorizontalPaddingScale"
  },
  cellWidgetSpacing: {
    calc: "spacing * 1.5"
  },
  cellHorizontalPaddingScale: 1,
  rowGroupIndentSize: {
    calc: "cellWidgetSpacing + iconSize"
  },
  valueChangeDeltaUpColor: "#43a047",
  valueChangeDeltaDownColor: "#e53935",
  valueChangeValueHighlightBackgroundColor: "#16a08580",
  rowHeight: {
    calc: "max(iconSize, dataFontSize) + spacing * 3.25 * rowVerticalPaddingScale"
  },
  rowVerticalPaddingScale: 1,
  headerHeight: {
    calc: "max(iconSize, dataFontSize) + spacing * 4 * headerVerticalPaddingScale"
  },
  headerVerticalPaddingScale: 1,
  paginationPanelHeight: {
    ref: "rowHeight",
    calc: "max(rowHeight, 22px)"
  },
  dragHandleColor: foregroundMix(0.7),
  headerColumnResizeHandleHeight: "30%",
  headerColumnResizeHandleWidth: 2,
  headerColumnResizeHandleColor: {
    ref: "borderColor"
  },
  widgetContainerHorizontalPadding: {
    calc: "spacing * 1.5"
  },
  widgetContainerVerticalPadding: {
    calc: "spacing * 1.5"
  },
  widgetHorizontalSpacing: {
    calc: "spacing * 1.5"
  },
  widgetVerticalSpacing: {
    ref: "spacing"
  },
  iconButtonColor: { ref: "iconColor" },
  iconButtonBackgroundColor: "transparent",
  iconButtonBackgroundSpread: 4,
  iconButtonBorderRadius: 1,
  iconButtonHoverColor: { ref: "iconButtonColor" },
  iconButtonHoverBackgroundColor: foregroundMix(0.1),
  iconButtonActiveColor: accentColor,
  iconButtonActiveBackgroundColor: accentMix(0.28),
  iconButtonActiveIndicatorColor: accentColor,
  menuBorder: {
    color: foregroundMix(0.2)
  },
  menuBackgroundColor: foregroundBackgroundMix(0.03),
  menuTextColor: foregroundBackgroundMix(0.95),
  menuShadow: {
    ref: "popupShadow"
  },
  menuSeparatorColor: {
    ref: "borderColor"
  },
  setFilterIndentSize: {
    ref: "iconSize"
  },
  chartMenuPanelWidth: 260,
  chartMenuLabelColor: foregroundMix(0.8),
  dialogShadow: {
    ref: "popupShadow"
  },
  cellEditingBorder: {
    color: accentColor
  },
  cellEditingShadow: { ref: "cardShadow" },
  fullRowEditInvalidBackgroundColor: {
    ref: "invalidColor",
    onto: "backgroundColor",
    mix: 0.25
  },
  dialogBorder: {
    color: foregroundMix(0.2)
  },
  panelBackgroundColor: backgroundColor,
  panelTitleBarHeight: { ref: "headerHeight" },
  panelTitleBarBackgroundColor: {
    ref: "headerBackgroundColor"
  },
  panelTitleBarIconColor: {
    ref: "headerTextColor"
  },
  panelTitleBarTextColor: {
    ref: "headerTextColor"
  },
  panelTitleBarFontWeight: {
    ref: "headerFontWeight"
  },
  panelTitleBarBorder: true,
  columnSelectIndentSize: {
    ref: "iconSize"
  },
  toolPanelSeparatorBorder: true,
  columnDropCellBackgroundColor: foregroundMix(0.07),
  columnDropCellTextColor: {
    ref: "textColor"
  },
  columnDropCellDragHandleColor: {
    ref: "textColor"
  },
  columnDropCellBorder: {
    color: foregroundMix(0.13)
  },
  selectCellBackgroundColor: foregroundMix(0.07),
  selectCellBorder: {
    color: foregroundMix(0.13)
  },
  advancedFilterBuilderButtonBarBorder: true,
  advancedFilterBuilderIndentSize: {
    calc: "spacing * 2 + iconSize"
  },
  advancedFilterBuilderJoinPillColor: "#f08e8d",
  advancedFilterBuilderColumnPillColor: "#a6e194",
  advancedFilterBuilderOptionPillColor: "#f3c08b",
  advancedFilterBuilderValuePillColor: "#85c0e4",
  filterPanelApplyButtonColor: backgroundColor,
  filterPanelApplyButtonBackgroundColor: accentColor,
  filterPanelCardSubtleColor: {
    ref: "textColor",
    mix: 0.7
  },
  filterPanelCardSubtleHoverColor: { ref: "textColor" },
  findMatchColor: foregroundColor,
  findMatchBackgroundColor: "#ffff00",
  findActiveMatchColor: foregroundColor,
  findActiveMatchBackgroundColor: "#ffa500",
  filterToolPanelGroupIndent: {
    ref: "spacing"
  },
  rowLoadingSkeletonEffectColor: foregroundMix(0.15),
  statusBarLabelColor: foregroundColor,
  statusBarLabelFontWeight: 500,
  statusBarValueColor: foregroundColor,
  statusBarValueFontWeight: 500,
  pinnedSourceRowTextColor: {
    ref: "textColor"
  },
  pinnedSourceRowBackgroundColor: {
    ref: "dataBackgroundColor"
  },
  pinnedSourceRowFontWeight: 600,
  pinnedRowFontWeight: 600,
  pinnedRowBackgroundColor: {
    ref: "dataBackgroundColor"
  },
  pinnedRowTextColor: {
    ref: "textColor"
  }
};
var batchEditStyleDefaultCSS = (
  /*css*/
  `.ag-cell-batch-edit{background-color:var(--ag-cell-batch-edit-background-color);color:var(--ag-cell-batch-edit-text-color);display:inherit}.ag-row-batch-edit{background-color:var(--ag-row-batch-edit-background-color);color:var(--ag-row-batch-edit-text-color)}`
);
var baseParams = {
  cellBatchEditBackgroundColor: "rgba(220 181 139 / 16%)",
  cellBatchEditTextColor: "#422f00",
  rowBatchEditBackgroundColor: {
    ref: "cellBatchEditBackgroundColor"
  },
  rowBatchEditTextColor: {
    ref: "cellBatchEditTextColor"
  }
};
var baseDarkBatchEditParams = {
  ...baseParams,
  cellBatchEditTextColor: "#f3d0b3"
};
var makeBatchEditStyleBaseTreeShakeable = () => createPart({
  feature: "batchEditStyle",
  params: baseParams,
  css: batchEditStyleDefaultCSS
});
var batchEditStyleBase = /* @__PURE__ */ makeBatchEditStyleBaseTreeShakeable();
var buttonStyleBaseCSS = (
  /*css*/
  `:where(.ag-button){background:none;border:none;color:inherit;cursor:pointer;font-family:inherit;font-size:inherit;font-weight:inherit;letter-spacing:inherit;line-height:inherit;margin:0;padding:0;text-indent:inherit;text-shadow:inherit;text-transform:inherit;word-spacing:inherit;&:disabled{cursor:default}&:focus-visible{box-shadow:var(--ag-focus-shadow);outline:none}}.ag-standard-button{-webkit-appearance:none;-moz-appearance:none;appearance:none;background-color:var(--ag-button-background-color);border:var(--ag-button-border);border-radius:var(--ag-button-border-radius);color:var(--ag-button-text-color);cursor:pointer;font-weight:var(--ag-button-font-weight);padding:var(--ag-button-vertical-padding) var(--ag-button-horizontal-padding);&:hover{background-color:var(--ag-button-hover-background-color);border:var(--ag-button-hover-border);color:var(--ag-button-hover-text-color)}&:active{background-color:var(--ag-button-active-background-color);border:var(--ag-button-active-border);color:var(--ag-button-active-text-color)}&:disabled{background-color:var(--ag-button-disabled-background-color);border:var(--ag-button-disabled-border);color:var(--ag-button-disabled-text-color)}}`
);
var baseParams2 = {
  buttonTextColor: "inherit",
  buttonFontWeight: "normal",
  buttonBackgroundColor: "transparent",
  buttonBorder: false,
  buttonBorderRadius: { ref: "borderRadius" },
  buttonHorizontalPadding: { calc: "spacing * 2" },
  buttonVerticalPadding: { ref: "spacing" },
  buttonHoverTextColor: { ref: "buttonTextColor" },
  buttonHoverBackgroundColor: { ref: "buttonBackgroundColor" },
  buttonHoverBorder: { ref: "buttonBorder" },
  buttonActiveTextColor: { ref: "buttonHoverTextColor" },
  buttonActiveBackgroundColor: { ref: "buttonHoverBackgroundColor" },
  buttonActiveBorder: { ref: "buttonHoverBorder" },
  buttonDisabledTextColor: { ref: "inputDisabledTextColor" },
  buttonDisabledBackgroundColor: { ref: "inputDisabledBackgroundColor" },
  buttonDisabledBorder: { ref: "inputDisabledBorder" }
};
var makeButtonStyleQuartzTreeShakeable = () => createPart({
  feature: "buttonStyle",
  params: {
    ...baseParams2,
    buttonBackgroundColor: backgroundColor,
    buttonBorder: true,
    buttonHoverBackgroundColor: { ref: "rowHoverColor" },
    buttonActiveBorder: { color: accentColor }
  },
  css: buttonStyleBaseCSS
});
var buttonStyleQuartz = /* @__PURE__ */ makeButtonStyleQuartzTreeShakeable();
var makeButtonStyleBalhamTreeShakeable = () => createPart({
  feature: "buttonStyle",
  params: {
    ...baseParams2,
    buttonBorder: { color: foregroundColor, width: 2, style: "outset" },
    buttonActiveBorder: { color: foregroundColor, width: 2, style: "inset" },
    buttonBackgroundColor: foregroundBackgroundMix(0.07),
    buttonHoverBackgroundColor: backgroundColor,
    buttonVerticalPadding: { calc: "spacing * 0.5" }
  },
  css: buttonStyleBaseCSS
});
var buttonStyleBalham = /* @__PURE__ */ makeButtonStyleBalhamTreeShakeable();
var columnDropStyleBorderedCSS = (
  /*css*/
  `.ag-column-drop-vertical-empty-message{align-items:center;border:dashed var(--ag-border-width);border-color:var(--ag-border-color);display:flex;inset:0;justify-content:center;margin:calc(var(--ag-spacing)*1.5) calc(var(--ag-spacing)*2);overflow:hidden;padding:calc(var(--ag-spacing)*2);position:absolute}`
);
var columnDropStylePlainCSS = (
  /*css*/
  `.ag-column-drop-vertical-empty-message{color:var(--ag-subtle-text-color);font-size:calc(var(--ag-font-size) - 1px);font-weight:600;padding-top:var(--ag-spacing)}:where(.ag-ltr) .ag-column-drop-vertical-empty-message{padding-left:calc(var(--ag-icon-size) + var(--ag-spacing) + var(--ag-widget-horizontal-spacing));padding-right:var(--ag-spacing)}:where(.ag-rtl) .ag-column-drop-vertical-empty-message{padding-left:var(--ag-spacing);padding-right:calc(var(--ag-icon-size) + var(--ag-spacing) + var(--ag-widget-horizontal-spacing))}`
);
var makeColumnDropStyleBorderedTreeShakeable = () => {
  return createPart({
    feature: "columnDropStyle",
    css: columnDropStyleBorderedCSS
  });
};
var columnDropStyleBordered = /* @__PURE__ */ makeColumnDropStyleBorderedTreeShakeable();
var makeColumnDropStylePlainTreeShakeable = () => {
  return createPart({
    feature: "columnDropStyle",
    css: columnDropStylePlainCSS
  });
};
var columnDropStylePlain = /* @__PURE__ */ makeColumnDropStylePlainTreeShakeable();
var gridThemeLogger = {
  warn: (...args2) => {
    _warn(args2[0], args2[1]);
  },
  error: (...args2) => {
    _error(args2[0], args2[1]);
  },
  preInitErr: (...args2) => {
    _logPreInitErr(args2[0], args2[2], args2[1]);
  }
};
var createTheme = () => createSharedTheme(gridThemeLogger).withParams(coreDefaults).withPart(buttonStyleQuartz).withPart(columnDropStyleBordered).withPart(batchEditStyleBase);
var checkboxStyleDefaultCSS = (
  /*css*/
  `.ag-checkbox-input-wrapper,.ag-radio-button-input-wrapper{background-color:var(--ag-checkbox-unchecked-background-color);border:solid var(--ag-checkbox-border-width) var(--ag-checkbox-unchecked-border-color);flex:none;height:var(--ag-icon-size);position:relative;width:var(--ag-icon-size);:where(input){-webkit-appearance:none;-moz-appearance:none;appearance:none;cursor:pointer;display:block;height:var(--ag-icon-size);margin:0;opacity:0;width:var(--ag-icon-size)}&:after{content:"";display:block;inset:0;-webkit-mask-position:center;mask-position:center;-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;pointer-events:none;position:absolute}&:where(.ag-checked){background-color:var(--ag-checkbox-checked-background-color);border-color:var(--ag-checkbox-checked-border-color);&:after{background-color:var(--ag-checkbox-checked-shape-color)}}&:where(:focus-within,:active){box-shadow:var(--ag-focus-shadow)}&:where(.ag-disabled){filter:grayscale();opacity:.5}}.ag-checkbox-input-wrapper{border-radius:var(--ag-checkbox-border-radius);&:where(.ag-checked):after{-webkit-mask-image:var(--ag-checkbox-checked-shape-image);mask-image:var(--ag-checkbox-checked-shape-image)}&:where(.ag-indeterminate){background-color:var(--ag-checkbox-indeterminate-background-color);border-color:var(--ag-checkbox-indeterminate-border-color);&:after{background-color:var(--ag-checkbox-indeterminate-shape-color);-webkit-mask-image:var(--ag-checkbox-indeterminate-shape-image);mask-image:var(--ag-checkbox-indeterminate-shape-image)}}}.ag-cell-editing-error .ag-checkbox-input-wrapper:focus-within{box-shadow:var(--ag-focus-error-shadow)}.ag-radio-button-input-wrapper{border-radius:100%;&:where(.ag-checked):after{-webkit-mask-image:var(--ag-radio-checked-shape-image);mask-image:var(--ag-radio-checked-shape-image)}}`
);
var makeCheckboxStyleDefaultTreeShakeable = () => createPart({
  feature: "checkboxStyle",
  params: {
    checkboxBorderWidth: 1,
    checkboxBorderRadius: {
      ref: "borderRadius"
    },
    checkboxUncheckedBackgroundColor: backgroundColor,
    checkboxUncheckedBorderColor: foregroundBackgroundMix(0.3),
    checkboxCheckedBackgroundColor: accentColor,
    checkboxCheckedBorderColor: { ref: "checkboxCheckedBackgroundColor" },
    checkboxCheckedShapeImage: {
      svg: '<svg xmlns="http://www.w3.org/2000/svg" width="10" height="7" fill="none"><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75" d="M1 3.5 3.5 6l5-5"/></svg>'
    },
    checkboxCheckedShapeColor: backgroundColor,
    checkboxIndeterminateBackgroundColor: foregroundBackgroundMix(0.3),
    checkboxIndeterminateBorderColor: { ref: "checkboxIndeterminateBackgroundColor" },
    checkboxIndeterminateShapeImage: {
      svg: '<svg xmlns="http://www.w3.org/2000/svg" width="10" height="2" fill="none"><rect width="10" height="2" fill="#000" rx="1"/></svg>'
    },
    checkboxIndeterminateShapeColor: backgroundColor,
    radioCheckedShapeImage: {
      svg: '<svg xmlns="http://www.w3.org/2000/svg" width="6" height="6" fill="none"><circle cx="3" cy="3" r="3" fill="#000"/></svg>'
    }
  },
  css: checkboxStyleDefaultCSS
});
var checkboxStyleDefault = /* @__PURE__ */ makeCheckboxStyleDefaultTreeShakeable();
var darkParams = () => ({
  ...defaultLightColorSchemeParams,
  ...baseDarkBatchEditParams,
  backgroundColor: "hsl(217, 0%, 17%)",
  foregroundColor: "#FFF",
  chromeBackgroundColor: foregroundBackgroundMix(0.05),
  rowHoverColor: accentMix(0.15),
  selectedRowBackgroundColor: accentMix(0.2),
  menuBackgroundColor: foregroundBackgroundMix(0.1),
  browserColorScheme: "dark",
  popupShadow: "0 0px 20px #000A",
  cardShadow: "0 1px 4px 1px #000A",
  advancedFilterBuilderJoinPillColor: "#7a3a37",
  advancedFilterBuilderColumnPillColor: "#355f2d",
  advancedFilterBuilderOptionPillColor: "#5a3168",
  advancedFilterBuilderValuePillColor: "#374c86",
  filterPanelApplyButtonColor: foregroundColor,
  findMatchColor: backgroundColor,
  findActiveMatchColor: backgroundColor,
  checkboxUncheckedBorderColor: foregroundBackgroundMix(0.4),
  toggleButtonOffBackgroundColor: foregroundBackgroundMix(0.4),
  rowBatchEditBackgroundColor: foregroundBackgroundMix(0.1)
});
var darkBlueParams = () => ({
  ...darkParams(),
  backgroundColor: "#1f2836"
});
var makeColorSchemeVariableTreeShakeable = () => createPart({
  feature: "colorScheme",
  params: defaultLightColorSchemeParams,
  modeParams: {
    light: defaultLightColorSchemeParams,
    dark: darkParams(),
    "dark-blue": darkBlueParams()
  }
});
var colorSchemeVariable = /* @__PURE__ */ makeColorSchemeVariableTreeShakeable();
var iconSetBalhamCSS = (
  /*css*/
  `.ag-icon-aggregation:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Eaggregation%3C/title%3E%3Cpath d='M25.128 2.002c2.56.096 4.772 2.292 4.87 4.87a712 712 0 0 1 0 18.256c-.096 2.56-2.292 4.772-4.87 4.87a712 712 0 0 1-18.256 0c-2.558-.096-4.772-2.29-4.87-4.87a712 712 0 0 1 0-18.256c.096-2.56 2.292-4.772 4.87-4.87a712 712 0 0 1 18.256 0M7.006 4c-1.57.02-2.946 1.348-3.004 2.922-.078 6.078-.23 12.16.002 18.234.094 1.484 1.354 2.746 2.84 2.84 6.1.232 12.212.232 18.312 0 1.48-.094 2.746-1.35 2.84-2.84.232-6.1.232-12.212 0-18.312-.094-1.48-1.35-2.746-2.84-2.84C19.11 3.774 13.056 4 7.006 4M22 12h-2v-2h-8v.092c.056 1.352 3.426 2.598 4.472 4.404.682 1.174.438 2.754-.572 3.72C14.29 19.618 12 20.924 12 22h8v-2h2v4H10c0-1.586-.098-3.304 1.016-4.314 1.904-1.632 4.89-3.108 3.54-4.42-1.918-1.68-4.464-2.936-4.554-5.12L10 8h12z'/%3E%3C/svg%3E")}.ag-icon-arrows:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Earrows%3C/title%3E%3Cpath d='m6.414 17 2.294 2.292-1.416 1.416L2.586 16l4.706-4.708 1.416 1.416L6.414 15H15V6.414l-2.292 2.294-1.416-1.416L16 2.586l4.708 4.706-1.416 1.416L17 6.414V15h8.586l-2.294-2.292 1.416-1.416L29.414 16l-4.706 4.708-1.416-1.416L25.586 17H17v8.586l2.292-2.294 1.416 1.416L16 29.414l-4.708-4.706 1.416-1.416L15 25.586V17z'/%3E%3C/svg%3E")}.ag-icon-asc:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Easc%3C/title%3E%3Cpath d='m15 10.621-4.292 4.294-1.416-1.416L16 6.793l6.708 6.706-1.416 1.416L17 10.621v14.586h-2z'/%3E%3C/svg%3E")}.ag-icon-cancel:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Ecancel%3C/title%3E%3Cpath d='M16 4C9.378 4 4 9.378 4 16s5.378 12 12 12 12-5.378 12-12S22.622 4 16 4m0 2c5.52 0 10 4.48 10 10s-4.48 10-10 10S6 21.52 6 16 10.48 6 16 6m0 8.586 5.292-5.294 1.416 1.416L17.414 16l5.294 5.292-1.416 1.416L16 17.414l-5.292 5.294-1.416-1.416L14.586 16l-5.294-5.292 1.416-1.416z'/%3E%3C/svg%3E")}.ag-icon-chart:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Echart%3C/title%3E%3Cpath d='M6.667 12.267h4v13.067h-4zm7.466-5.6h3.733v18.667h-3.733zM21.6 17.333h3.733v8H21.6z'/%3E%3C/svg%3E")}.ag-icon-color-picker:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Ecolor-picker%3C/title%3E%3Cpath d='M23.907 17.587 10.574 4.254l-1.88 1.88 3.173 3.173-8.28 8.28 10.16 10.16zm-16.547 0 6.387-6.387 6.387 6.387H7.361zm18.387 2s-2.667 2.893-2.667 4.667c0 1.467 1.2 2.667 2.667 2.667s2.667-1.2 2.667-2.667c0-1.773-2.667-4.667-2.667-4.667'/%3E%3C/svg%3E")}.ag-icon-columns:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Ecolumns%3C/title%3E%3Cpath d='M14 25h-2V7h2zm6 0h-2V7h2zm6 0h-2V7h2zM8 25H6V7h2z'/%3E%3C/svg%3E")}.ag-icon-contracted:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Econtracted%3C/title%3E%3Cpath d='m21.061 16-8.706 8.708-1.416-1.416L18.233 16l-7.294-7.292 1.416-1.416z'/%3E%3C/svg%3E")}.ag-icon-copy:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Ecopy%3C/title%3E%3Cpath d='M21.929 27.999h-7.828a5.09 5.09 0 0 1-5.086-5.086v-9.812a5.087 5.087 0 0 1 5.086-5.086h7.828a5.09 5.09 0 0 1 5.086 5.086v9.812a5.087 5.087 0 0 1-5.086 5.086m.16-17.984h-8.088a2.94 2.94 0 0 0-2.938 2.938v10.132a2.94 2.94 0 0 0 2.938 2.938h8.088a2.94 2.94 0 0 0 2.936-2.938V12.953a2.94 2.94 0 0 0-2.936-2.938M7.041 26.013h-2.05a4 4 0 0 1-.006-.228V9.065a5.07 5.07 0 0 1 5.064-5.064h12.812q.069 0 .134.002v2.012H9.915a2.876 2.876 0 0 0-2.874 2.874z'/%3E%3C/svg%3E")}.ag-icon-cross:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='4 4 24 24'%3E%3Ctitle%3Ecross%3C/title%3E%3Cpath d='m16 14.586 5.292-5.294 1.416 1.416L17.414 16l5.294 5.292-1.416 1.416L16 17.414l-5.292 5.294-1.416-1.416L14.586 16l-5.294-5.292 1.416-1.416z'/%3E%3C/svg%3E")}.ag-icon-csv:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' xml:space='preserve' style='fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2' viewBox='0 0 32 32'%3E%3Cpath d='M384 131.9c-7.753-8.433-110.425-128.473-114.9-133L48-.1C21.5 0 0 21.5 0 48v416c0 26.5 21.5 48 48 48h288c26.5 0 48-21.5 48-48zm-35.9 2.1H257V27.9zM30 479V27h200l1 105c0 13.3-1.3 29 12 29h111l1 318z' style='fill-rule:nonzero' transform='translate(3.934 -.054)scale(.06285)'/%3E%3Cpath d='M.688-.226a.2.2 0 0 1-.017.074.28.28 0 0 1-.145.14.412.412 0 0 1-.234.013.28.28 0 0 1-.202-.168.468.468 0 0 1-.04-.19q0-.086.025-.155a.319.319 0 0 1 .182-.191.4.4 0 0 1 .134-.025q.087 0 .155.035a.3.3 0 0 1 .104.085.17.17 0 0 1 .036.097.06.06 0 0 1-.018.044.06.06 0 0 1-.042.019.06.06 0 0 1-.042-.013.2.2 0 0 1-.031-.046.2.2 0 0 0-.066-.079.16.16 0 0 0-.095-.027.17.17 0 0 0-.142.068.3.3 0 0 0-.053.193.4.4 0 0 0 .023.139.2.2 0 0 0 .067.083.2.2 0 0 0 .1.027q.063 0 .106-.031a.2.2 0 0 0 .065-.091.2.2 0 0 1 .023-.046q.014-.018.044-.018a.06.06 0 0 1 .044.018.06.06 0 0 1 .019.045' style='fill-rule:nonzero' transform='matrix(8.39799 0 0 12.455 7.122 25.977)'/%3E%3Cpath d='M.622-.215a.2.2 0 0 1-.033.117.23.23 0 0 1-.098.081.4.4 0 0 1-.153.029.34.34 0 0 1-.175-.04.23.23 0 0 1-.079-.077.17.17 0 0 1-.031-.093q0-.027.019-.045a.06.06 0 0 1 .046-.019.06.06 0 0 1 .039.014.1.1 0 0 1 .027.044.3.3 0 0 0 .03.057q.015.023.044.038.03.015.076.015.065 0 .105-.03a.09.09 0 0 0 .04-.075.08.08 0 0 0-.022-.058.14.14 0 0 0-.056-.034 1 1 0 0 0-.092-.025.7.7 0 0 1-.129-.042.2.2 0 0 1-.083-.066.17.17 0 0 1-.03-.104q0-.058.032-.105a.2.2 0 0 1 .093-.07.4.4 0 0 1 .144-.025q.066 0 .114.016a.3.3 0 0 1 .08.044.2.2 0 0 1 .046.057q.015.03.015.058a.07.07 0 0 1-.018.046.06.06 0 0 1-.046.021q-.025 0-.038-.012a.2.2 0 0 1-.028-.041.2.2 0 0 0-.047-.063Q.387-.625.326-.625a.15.15 0 0 0-.09.025q-.035.024-.035.059 0 .021.012.037a.1.1 0 0 0 .032.027.4.4 0 0 0 .111.036q.06.015.11.031.048.018.083.042a.2.2 0 0 1 .054.062.2.2 0 0 1 .019.091' style='fill-rule:nonzero' transform='matrix(8.39799 0 0 12.455 13.339 25.977)'/%3E%3Cpath d='m.184-.633.162.48.163-.483q.013-.038.019-.053a.062.062 0 0 1 .061-.039q.018 0 .034.009a.1.1 0 0 1 .025.025q.009.015.009.031L.654-.64l-.007.025-.009.024-.173.468-.019.051a.2.2 0 0 1-.021.042.1.1 0 0 1-.033.03.1.1 0 0 1-.049.012.1.1 0 0 1-.05-.011A.1.1 0 0 1 .26-.03a.2.2 0 0 1-.021-.042L.22-.123.05-.587.041-.612.033-.638.03-.662q0-.025.02-.046a.07.07 0 0 1 .05-.02q.037 0 .053.023.015.023.031.072' style='fill-rule:nonzero' transform='matrix(8.39799 0 0 12.455 18.94 25.977)'/%3E%3C/svg%3E")}.ag-icon-cut:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' xml:space='preserve' style='fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2' viewBox='0 0 32 32'%3E%3Cpath d='M14.703 15.096 6.215 4.719a1 1 0 1 1 1.548-1.267l13.058 15.965A5.001 5.001 0 0 1 28 23.916a5 5 0 0 1-4.999 4.999 5 5 0 0 1-4.999-4.999 4.98 4.98 0 0 1 1.23-3.283l-3.238-3.958-3.272 4.001a4.98 4.98 0 0 1 1.265 3.323 5 5 0 0 1-4.999 4.999 5 5 0 0 1-4.999-4.999 5 5 0 0 1 7.13-4.522zM8.991 20.8a3.1 3.1 0 0 0-3.1 3.1c0 1.711 1.389 3.1 3.1 3.1s3.1-1.389 3.1-3.1-1.389-3.1-3.1-3.1M23 20.8a3.1 3.1 0 0 0-3.1 3.1c0 1.711 1.389 3.1 3.1 3.1s3.1-1.389 3.1-3.1-1.389-3.1-3.1-3.1m-5.723-8.852 1.292 1.579 7.205-8.808a1 1 0 0 0-1.548-1.267z' style='fill-rule:nonzero'/%3E%3C/svg%3E")}.ag-icon-desc:before,.ag-icon-down:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Edesc%3C/title%3E%3Cpath d='m17 21.379 4.292-4.294 1.416 1.416L16 25.207l-6.708-6.706 1.416-1.416L15 21.379V6.793h2z'/%3E%3C/svg%3E")}.ag-icon-excel:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' xml:space='preserve' style='fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2' viewBox='0 0 32 32'%3E%3Cpath d='M384 131.9c-7.753-8.433-110.425-128.473-114.9-133L48-.1C21.5 0 0 21.5 0 48v416c0 26.5 21.5 48 48 48h288c26.5 0 48-21.5 48-48zm-35.9 2.1H257V27.9zM30 479V27h200l1 105c0 13.3-1.3 29 12 29h111l1 318z' style='fill-rule:nonzero' transform='translate(3.934 -.054)scale(.06285)'/%3E%3Cpath d='m.052-.139.16-.234-.135-.208a.4.4 0 0 1-.028-.052.1.1 0 0 1-.01-.042.05.05 0 0 1 .018-.037.07.07 0 0 1 .045-.016q.03 0 .047.018a1 1 0 0 1 .047.066l.107.174.115-.174.024-.038.019-.026.021-.015a.1.1 0 0 1 .027-.005.06.06 0 0 1 .044.016.05.05 0 0 1 .018.039q0 .033-.038.089l-.141.211.152.234a.3.3 0 0 1 .03.051.1.1 0 0 1 .009.038.1.1 0 0 1-.008.031.1.1 0 0 1-.024.023.1.1 0 0 1-.034.008.1.1 0 0 1-.035-.008.1.1 0 0 1-.023-.022L.427-.067.301-.265l-.134.204-.022.034-.016.019a.1.1 0 0 1-.022.015.1.1 0 0 1-.03.005.06.06 0 0 1-.044-.016.06.06 0 0 1-.017-.047q0-.036.036-.088' style='fill-rule:nonzero' transform='matrix(17.82892 0 0 16.50777 10.371 25.928)'/%3E%3C/svg%3E")}.ag-icon-expanded:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Eexpanded%3C/title%3E%3Cpath d='M21.061 8.708 13.767 16l7.294 7.292-1.416 1.416L10.939 16l8.706-8.708z'/%3E%3C/svg%3E")}.ag-icon-eye-slash:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Eeye-slash%3C/title%3E%3Cpath d='M9.304 7.89a15.2 15.2 0 0 1 6.404-1.638c.294-.002.292-.002.584 0 5.956.174 11.328 4.088 13.62 9.748 0 0-1.318 3.178-3.224 5.174a13.6 13.6 0 0 1-2.226 1.874L26.414 25 25 26.414l-2.336-2.336C17.866 26.396 11.776 26.15 7.36 22.96a14.9 14.9 0 0 1-4.168-4.612c-.41-.71-.694-1.336-1.104-2.348 0 0 .898-2.218 2.002-3.718a14.6 14.6 0 0 1 3.442-3.334L5.586 7 7 5.586zm-.3 2.528c-2.038 1.344-3.708 3.246-4.724 5.508L4.248 16c2.46 5.762 9.622 9.064 15.63 7.15q.688-.219 1.342-.516l-.912-.912a6.96 6.96 0 0 1-4.19 1.394c-3.862 0-7-3.136-7-7 0-1.57.52-3.022 1.394-4.19zm14.032 11.204a13.25 13.25 0 0 0 4.684-5.548l.032-.074c-1.984-4.646-6.834-7.798-12.006-7.748-1.712.05-3.386.458-4.922 1.158l1.102 1.102a6.97 6.97 0 0 1 4.192-1.396 7.003 7.003 0 0 1 5.606 11.192zm-11.09-8.262a5.003 5.003 0 0 0 6.928 6.928zm8.342 5.514a5.002 5.002 0 0 0-6.928-6.928z'/%3E%3C/svg%3E")}.ag-icon-eye:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Eeye%3C/title%3E%3Cpath d='M16.292 6.32c5.956.174 11.328 4.086 13.62 9.746 0 0-1.318 3.18-3.224 5.176-4.862 5.088-13.534 5.97-19.328 1.784a14.9 14.9 0 0 1-4.168-4.612c-.41-.71-.694-1.336-1.104-2.348 0 0 .898-2.216 2.002-3.716 2.678-3.64 7.03-5.896 11.618-6.03.294-.004.292-.004.584 0m-.546 2c-4.896.142-9.458 3.202-11.466 7.672l-.032.074c2.46 5.762 9.622 9.066 15.63 7.152 3.458-1.102 6.342-3.738 7.842-7.076l.032-.076C25.768 11.42 20.918 8.27 15.746 8.32m.254.946c3.754 0 6.8 3.048 6.8 6.8 0 3.754-3.046 6.8-6.8 6.8s-6.8-3.046-6.8-6.8c0-3.752 3.046-6.8 6.8-6.8m5 6.768V16c0-2.76-2.24-5-5-5s-5 2.24-5 5v.066c0 2.76 2.24 5 5 5s5-2.24 5-5z'/%3E%3C/svg%3E")}.ag-icon-filter:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Efilter%3C/title%3E%3Cpath d='M26 8.184c-.066 2.658-4.058 5.154-6.742 7.974a1.05 1.05 0 0 0-.258.682v3.66L13 25c0-2.74.066-5.482-.002-8.222a1.05 1.05 0 0 0-.256-.62C10.026 13.304 6.06 10.61 6 8.184V6h20zM8 8c0 .304.06.612.258.842 2.716 2.854 6.682 5.548 6.742 7.974V21l2-1.5v-2.684c.066-2.658 4.058-5.154 6.742-7.974.198-.23.258-.538.258-.842z'/%3E%3C/svg%3E")}.ag-icon-first:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Efirst%3C/title%3E%3Cpath d='M24.354 8.708 17.06 16l7.294 7.292-1.416 1.416L14.232 16l8.706-8.708zM9.646 8v16h-2V8z'/%3E%3C/svg%3E")}.ag-icon-group:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Egroup%3C/title%3E%3Cpath d='M25.128 2.002c2.56.096 4.772 2.292 4.87 4.87a712 712 0 0 1 0 18.256c-.096 2.56-2.292 4.772-4.87 4.87a712 712 0 0 1-18.256 0c-2.558-.096-4.772-2.29-4.87-4.87a712 712 0 0 1 0-18.256c.096-2.56 2.292-4.772 4.87-4.87a712 712 0 0 1 18.256 0M7.006 4c-1.57.02-2.946 1.348-3.004 2.922-.078 6.078-.23 12.16.002 18.234.094 1.484 1.354 2.746 2.84 2.84 6.1.232 12.212.232 18.312 0 1.48-.094 2.746-1.35 2.84-2.84.232-6.1.232-12.212 0-18.312-.094-1.48-1.35-2.746-2.84-2.84C19.11 3.774 13.056 4 7.006 4M14 21h-4v-2h4zm12 0H16v-2h10zm-12-4h-4v-2h4zm12 0H16v-2h10zm-16-4H6v-2h4zm16 0H12v-2h14z'/%3E%3C/svg%3E")}.ag-icon-last:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Elast%3C/title%3E%3Cpath d='m17.768 16-8.706 8.708-1.416-1.416L14.94 16 7.646 8.708l1.416-1.416zm6.586 8h-2V8h2z'/%3E%3C/svg%3E")}.ag-icon-left:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Eleft%3C/title%3E%3Cpath d='m17.621 11-2 2h12.586v6H15.621l2 2-4.414 4.414L3.793 16l9.414-9.414zm-11 5 6.586 6.586L14.793 21l-4-4h15.414v-2H10.793l4-4-1.586-1.586z'/%3E%3C/svg%3E")}.ag-icon-linked:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Elinked%3C/title%3E%3Cpath d='M17.138 13.418a1.03 1.03 0 0 0-.298.658s.125.096.226.178c1.372 1.114 2.033 3.039 1.582 4.796a4.7 4.7 0 0 1-1.205 2.123c-1.145 1.151-2.296 2.294-3.445 3.441-1.241 1.232-3.185 1.691-4.864 1.105-1.546-.54-2.756-1.938-3.048-3.572-.267-1.496.246-3.108 1.319-4.186l.578-.578-.03-.092a10.5 10.5 0 0 1-.452-2.3v-.005c-.776.775-1.621 1.489-2.275 2.396-1.817 2.522-1.643 6.323.706 8.669 1.813 1.811 4.708 2.462 7.171 1.517a6.75 6.75 0 0 0 2.336-1.518l3.427-3.424c1.939-1.954 2.533-5.126 1.294-7.674a6.8 6.8 0 0 0-2.071-2.481l-.003-.002zM21.265 4a6.8 6.8 0 0 0-4.734 1.964l-3.427 3.424c-1.961 1.977-2.52 5.092-1.32 7.619a6.8 6.8 0 0 0 2.098 2.537l.003.002c.32-.32.643-.637.96-.96.167-.172.27-.401.286-.64l-.204-.167c-1.603-1.287-2.215-3.68-1.316-5.616a4.7 4.7 0 0 1 .918-1.32c1.145-1.151 2.296-2.294 3.445-3.441 1.239-1.23 3.178-1.694 4.864-1.105 1.83.639 3.16 2.498 3.12 4.493a4.8 4.8 0 0 1-1.391 3.265l-.578.578.03.092c.235.743.387 1.519.452 2.3v.005c.732-.731 1.521-1.406 2.162-2.244 1.192-1.559 1.643-3.651 1.204-5.575a6.8 6.8 0 0 0-3.98-4.703 6.8 6.8 0 0 0-2.529-.506h-.061z'/%3E%3C/svg%3E")}.ag-icon-loading:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Eloading%3C/title%3E%3Cpath d='M17 29h-2v-8h2zm-3.586-9L7 26.414 5.586 25 12 18.586zm13 5L25 26.414 18.586 20 20 18.586zM29 17h-8v-2h8zm-18 0H3v-2h8zm2.414-5L12 13.414 5.586 7 7 5.586zm13-5L20 13.414 18.586 12 25 5.586zM17 11h-2V3h2z'/%3E%3C/svg%3E")}.ag-icon-maximize:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='3 3 26 26'%3E%3Ctitle%3Emaximize%3C/title%3E%3Cpath d='m7.54 17.4.1 6.98 6.96.1-2.24-2.24L16 18.6 13.4 16l-3.64 3.64zm16.92-2.8-.1-6.98-6.96-.1 2.24 2.24L16 13.4l2.6 2.6 3.64-3.64z'/%3E%3C/svg%3E")}.ag-icon-menu:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Emenu%3C/title%3E%3Cpath d='M26 23H6v-2h20zm0-6H6v-2h20zm0-6H6V9h20z'/%3E%3C/svg%3E")}.ag-icon-menu-alt:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='32' height='32' fill='none'%3E%3Cpath fill='%23000' d='M16 18a2 2 0 1 0 0-4 2 2 0 0 0 0 4m0-7a2 2 0 1 0 0-4 2 2 0 0 0 0 4m0 14a2 2 0 1 0 0-4 2 2 0 0 0 0 4'/%3E%3C/svg%3E")}.ag-icon-minimize:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='3 3 26 26'%3E%3Ctitle%3Eminimize%3C/title%3E%3Cpath d='m14.8 24.26-.1-6.96-6.96-.1 2.24 2.24-3.64 3.64 2.6 2.6 3.64-3.64zm2.4-16.52.1 6.96 6.96.1-2.24-2.24 3.64-3.64-2.6-2.6-3.64 3.64z'/%3E%3C/svg%3E")}.ag-icon-minus:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' xml:space='preserve' style='fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2' viewBox='0 0 32 32'%3E%3Cpath d='M7.515 7.515c-4.683 4.682-4.683 12.288 0 16.97 4.682 4.683 12.288 4.683 16.97 0 4.683-4.682 4.683-12.288 0-16.97-4.682-4.683-12.288-4.683-16.97 0m1.414 1.414c3.903-3.903 10.239-3.903 14.142 0s3.903 10.239 0 14.142-10.239 3.903-14.142 0-3.903-10.239 0-14.142m-1.414 6.07h16.97v2.002H7.515z' style='fill-rule:nonzero'/%3E%3C/svg%3E")}.ag-icon-next:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Enext%3C/title%3E%3Cpath d='m21.061 16-8.706 8.708-1.416-1.416L18.233 16l-7.294-7.292 1.416-1.416z'/%3E%3C/svg%3E")}.ag-icon-none:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Enone%3C/title%3E%3Cpath d='m10.044 21.258 4.478-4.198L16 18.444 9 25l-7-6.556 1.478-1.384 4.478 4.198V7h2.088zm14 3.742h-2.088V10.742l-4.478 4.198L16 13.556 23 7q3.5 3.28 7 6.556l-1.478 1.384-4.478-4.198z'/%3E%3C/svg%3E")}.ag-icon-not-allowed:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Enot-allowed%3C/title%3E%3Cpath d='M16.186 3.646c8.188.154 14.898 9.796 11.17 17.78-3.298 7.066-13.932 9.374-19.848 3.87-3.9-3.632-5.076-9.896-2.684-14.708 2.082-4.19 6.588-6.974 11.362-6.942m-.298 1.998c-6.922.132-12.578 8.308-9.33 15.052 3.342 6.934 15.246 7.646 18.932 0 3.076-6.386-1.988-15.1-9.602-15.052m7.596 6.422c2.864 5.33-1.744 13.186-8.306 12.536a8.6 8.6 0 0 1-3.232-.998l-1.266-.706L22.778 10.8q.351.633.706 1.266m-9.422 10.276c3.296 1.028 7.246-1.006 8.216-4.418a6.6 6.6 0 0 0-.056-3.742zm2.104-14.696a8.8 8.8 0 0 1 3.936 1.038l1.266.706L9.27 21.488c-3.018-5.41-.99-13.37 6.318-13.834q.289-.01.578-.008m-.31 2c-4.06.154-7.23 4.614-6.03 8.46l8.16-8.16a6.8 6.8 0 0 0-2.13-.3'/%3E%3C/svg%3E")}.ag-icon-paste:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Epaste%3C/title%3E%3Cpath d='M20 6.5c0-1-1-3-4-3s-4 2-4 3H8c-2.21 0-4 1.79-4 4v14c0 2.21 1.79 4 4 4h16c2.21 0 4-1.79 4-4v-14c0-2.21-1.79-4-4-4zm-4 .546c.734 0 1.334.572 1.334 1.272S16.734 9.59 16 9.59s-1.334-.572-1.334-1.272.6-1.272 1.334-1.272M24 26.5H8a2 2 0 0 1-2-2v-14a2 2 0 0 1 2-2h2v4h12v-4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2'/%3E%3C/svg%3E")}.ag-icon-pin:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Epin%3C/title%3E%3Cpath d='m10.78 19.777-4.668-4.666s.032-1 .67-1.87c1.366-1.86 4.052-1.96 6.056-1.572l3.158-3.108c-.7-2.342 3.352-5.046 3.352-5.046l9.166 9.168q-.334.447-.67.894c-1.074 1.426-2.538 2.63-4.272 2.338l-3.32 3.218c.046.344.042.03.118 1.152.144 2.13-.64 4.324-2.632 5.34l-.746.364-4.798-4.798-7.292 7.294-1.416-1.416zm8.24-13.672c-.688.568-1.416 1.45-1.024 2.072l.49.722-4.986 4.988c-1.988-.506-4.346-.636-5.156.614l9.02 9.032q.14-.099.272-.21c1.226-1.08.764-3.04.498-4.9l4.79-4.79s1.47.938 2.936-.776l-6.79-6.79q-.026.019-.05.038'/%3E%3C/svg%3E")}.ag-icon-pivot:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Epivot%3C/title%3E%3Cpath d='M25.128 2.002c2.56.096 4.772 2.292 4.87 4.87a712 712 0 0 1 0 18.256c-.096 2.56-2.292 4.772-4.87 4.87a712 712 0 0 1-18.256 0c-2.558-.096-4.772-2.29-4.87-4.87a712 712 0 0 1 0-18.256c.096-2.56 2.292-4.772 4.87-4.87a712 712 0 0 1 18.256 0m2.966 7.954H9.892v18.136c5.086.13 10.18.098 15.264-.096 1.48-.094 2.746-1.35 2.84-2.84.192-5.064.226-10.134.098-15.2M3.968 24.1q.015.528.036 1.056c.094 1.484 1.354 2.746 2.84 2.84l1.012.036V24.1zM22 15.414l-.292.294-1.416-1.416L23 11.586l2.708 2.706-1.416 1.416-.292-.294v3.592c-.032 2.604-2.246 4.892-4.872 4.992L15.414 24l.294.292-1.416 1.416L11.586 23l2.706-2.708 1.416 1.416-.322.32c3.372.03 6.578-.164 6.614-3.034zM3.88 18.038c.002 1.346.012 2.694.038 4.04h3.938v-4.04zm.05-6.062a681 681 0 0 0-.044 4.042h3.97v-4.042zm5.962-7.99Q8.449 3.999 7.006 4c-1.57.02-2.946 1.348-3.004 2.922q-.02 1.517-.042 3.034h3.896v-2.02h2.036zm14.244-.016v3.966h3.898q-.017-.546-.038-1.092c-.094-1.48-1.35-2.746-2.84-2.84q-.51-.019-1.02-.034m-8.14-.054q-2.035.022-4.07.048v3.972h4.07zm6.106.008c-1.358-.022-2.714-.026-4.07-.022v4.034h4.07z'/%3E%3C/svg%3E")}.ag-icon-plus:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' xml:space='preserve' style='fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2' viewBox='0 0 32 32'%3E%3Cpath d='M7.515 7.515c-4.683 4.682-4.683 12.288 0 16.97 4.682 4.683 12.288 4.683 16.97 0 4.683-4.682 4.683-12.288 0-16.97-4.682-4.683-12.288-4.683-16.97 0m1.414 1.414c3.903-3.903 10.239-3.903 14.142 0s3.903 10.239 0 14.142-10.239 3.903-14.142 0-3.903-10.239 0-14.142M15 15l-.001-7.485h2.002L17 15l7.485-.001v2.002L17 17l.001 7.485h-2.002L15 17l-7.485.001v-2.002z' style='fill-rule:nonzero'/%3E%3C/svg%3E")}.ag-icon-previous:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Eprevious%3C/title%3E%3Cpath d='M21.061 8.708 13.767 16l7.294 7.292-1.416 1.416L10.939 16l8.706-8.708z'/%3E%3C/svg%3E")}.ag-icon-right:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Eright%3C/title%3E%3Cpath d='m28.207 16-9.414 9.414L14.379 21l2-2H3.793v-6h12.586l-2-2 4.414-4.414zm-11-5 4 4H5.793v2h15.414l-4 4 1.586 1.586L25.379 16l-6.586-6.586z'/%3E%3C/svg%3E")}.ag-icon-save:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Esave%3C/title%3E%3Cpath d='M25.333 16v9.333H6.666V16H3.999v9.333C3.999 26.8 5.199 28 6.666 28h18.667C26.8 28 28 26.8 28 25.333V16zm-8 .893 3.453-3.44 1.88 1.88L15.999 22l-6.667-6.667 1.88-1.88 3.453 3.44V4h2.667v12.893z'/%3E%3C/svg%3E")}.ag-icon-small-down:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Esmall-down%3C/title%3E%3Cpath d='M24.708 12.355 16 21.061l-8.708-8.706 1.416-1.416L16 18.233l7.292-7.294z'/%3E%3C/svg%3E")}.ag-icon-small-left:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Esmall-left%3C/title%3E%3Cpath d='M21.061 8.708 13.767 16l7.294 7.292-1.416 1.416L10.939 16l8.706-8.708z'/%3E%3C/svg%3E")}.ag-icon-small-right:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Esmall-right%3C/title%3E%3Cpath d='m21.061 16-8.706 8.708-1.416-1.416L18.233 16l-7.294-7.292 1.416-1.416z'/%3E%3C/svg%3E")}.ag-icon-small-up:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Esmall-up%3C/title%3E%3Cpath d='m24.708 19.645-1.416 1.416L16 13.767l-7.292 7.294-1.416-1.416L16 10.939z'/%3E%3C/svg%3E")}.ag-icon-tick:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Etick%3C/title%3E%3Cpath d='M24.708 10.855 13 22.561l-5.708-5.706 1.416-1.416L13 19.733 23.292 9.439z'/%3E%3C/svg%3E")}.ag-icon-tree-closed:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Etree-closed%3C/title%3E%3Cpath d='m21.061 16-8.706 8.708-1.416-1.416L18.233 16l-7.294-7.292 1.416-1.416z'/%3E%3C/svg%3E")}.ag-icon-tree-indeterminate:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Etree-indeterminate%3C/title%3E%3Cpath d='M6 15h20v2H6z'/%3E%3C/svg%3E")}.ag-icon-tree-open:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Etree-open%3C/title%3E%3Cpath d='M24.708 12.355 16 21.061l-8.708-8.706 1.416-1.416L16 18.233l7.292-7.294z'/%3E%3C/svg%3E")}.ag-icon-unlinked:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Eunlinked%3C/title%3E%3Cpath d='M5.35 3.999a.2.2 0 0 0-.14.058c-.388.38-.768.768-1.152 1.152a.21.21 0 0 0-.002.288c7.459 7.506 14.965 14.965 22.447 22.447a.21.21 0 0 0 .288.002q.576-.574 1.151-1.151a.21.21 0 0 0 .002-.288C20.484 19.002 12.979 11.542 5.497 4.06a.2.2 0 0 0-.146-.061zm.611 12.548c-1.933 1.939-2.538 5.119-1.289 7.688a6.79 6.79 0 0 0 4.891 3.672 6.82 6.82 0 0 0 5.893-1.866l1.984-1.984-1.438-1.438-1.986 1.986c-1.486 1.476-3.993 1.81-5.834.629a4.73 4.73 0 0 1-2.024-2.853 4.76 4.76 0 0 1 1.241-4.393l1.986-1.986-1.438-1.438-1.984 1.984zM21.273 3.999a6.78 6.78 0 0 0-4.727 1.963l-1.984 1.984L16 9.384l1.985-1.985a4.74 4.74 0 0 1 2.776-1.338c1.974-.224 4.045.926 4.845 2.834.712 1.699.329 3.778-1.004 5.12L22.616 16l1.439 1.438q1-1 2-2c2.012-2.031 2.557-5.368 1.112-7.982-1.144-2.07-3.432-3.441-5.834-3.459h-.061z'/%3E%3C/svg%3E")}.ag-icon-up:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Easc%3C/title%3E%3Cpath d='m15 10.621-4.292 4.294-1.416-1.416L16 6.793l6.708 6.706-1.416 1.416L17 10.621v14.586h-2z'/%3E%3C/svg%3E")}.ag-icon-grip:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ctitle%3Egrip%3C/title%3E%3Cpath d='M8 24H6v-4h2zm6 0h-2v-4h2zm6 0h-2v-4h2zm6 0h-2v-4h2zM8 18H6v-4h2zm6 0h-2v-4h2zm6 0h-2v-4h2zm6 0h-2v-4h2zM8 12H6V8h2zm6 0h-2V8h2zm6 0h-2V8h2zm6 0h-2V8h2z'/%3E%3C/svg%3E")}.ag-icon-settings:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='32' height='32' fill='none' viewBox='0 0 32 32'%3E%3Cpath fill='%23000' d='M30 8h-4.1c-.5-2.3-2.5-4-4.9-4s-4.4 1.7-4.9 4H2v2h14.1c.5 2.3 2.5 4 4.9 4s4.4-1.7 4.9-4H30zm-9 4c-1.7 0-3-1.3-3-3s1.3-3 3-3 3 1.3 3 3-1.3 3-3 3M2 24h4.1c.5 2.3 2.5 4 4.9 4s4.4-1.7 4.9-4H30v-2H15.9c-.5-2.3-2.5-4-4.9-4s-4.4 1.7-4.9 4H2zm9-4c1.7 0 3 1.3 3 3s-1.3 3-3 3-3-1.3-3-3 1.3-3 3-3'/%3E%3C/svg%3E")}.ag-icon-column-arrow:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 32 32'%3E%3Cpath fill='currentColor' fill-rule='evenodd' d='M11 4a1 1 0 0 1 1 1v22a1 1 0 1 1-2 0V5a1 1 0 0 1 1-1' clip-rule='evenodd'/%3E%3Cpath fill='currentColor' fill-rule='evenodd' d='M2 13a1 1 0 0 1 1-1h23.5a1 1 0 1 1 0 2H3a1 1 0 0 1-1-1' clip-rule='evenodd'/%3E%3Cpath fill='currentColor' fill-rule='evenodd' d='M2 4h18v24H2zm2 2v20h14V6zM26.793 13 23 9.207l1.414-1.414L29.621 13l-5.207 5.207L23 16.793z' clip-rule='evenodd'/%3E%3C/svg%3E")}.ag-icon-un-pin:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='32' height='32' fill='none' viewBox='0 0 32 32'%3E%3Cpath fill='currentColor' fill-rule='evenodd' d='m6.112 15.111 3.272 3.271 1.436-1.402-2.476-2.479c.81-1.25 3.168-1.12 5.156-.614l4.986-4.988-.49-.722c-.392-.622.336-1.504 1.024-2.072l.008-.007.01-.006.032-.025 1.447 1.447 1.432-1.397-2.601-2.602s-4.052 2.704-3.352 5.046l-3.158 3.108c-2.004-.388-4.69-.288-6.056 1.572-.638.87-.67 1.87-.67 1.87m.581 11.582.014.014 5.502-5.501 4.783 4.783.746-.364c1.992-1.016 2.776-3.21 2.632-5.34-.055-.805-.068-.87-.088-.97-.008-.04-.017-.085-.03-.182l3.32-3.218c1.734.292 3.198-.912 4.272-2.338q.337-.447.67-.894l-.001-.001-.007-.007-.007-.007-.007-.007-3.87-3.87 1.585-1.584-1.414-1.414-14.381 14.38-1.237 1.209-5.69 5.687 1.417 1.416zM23.21 10.206l2.65 2.651c-1.465 1.714-2.935.776-2.935.776l-4.79 4.79q.041.291.087.583c.257 1.676.513 3.35-.585 4.317a4 4 0 0 1-.272.21l-3.739-3.744z' clip-rule='evenodd'/%3E%3C/svg%3E")}.ag-icon-pinned-top:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='32' height='32' fill='none' viewBox='0 0 32 32'%3E%3Cpath fill='currentColor' d='m16.708 10.878 8.708 8.706L24 21l-6.292-6.294V27h-2V14.706L9.416 21 8 19.584q4.348-4.344 8.691-8.69zM25 6H8v2h17z'/%3E%3C/svg%3E")}.ag-icon-pinned-bottom:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='32' height='32' fill='none' viewBox='0 0 32 32'%3E%3Cpath fill='currentColor' d='M16.708 22.122 8 13.416 9.416 12l6.292 6.294V6h2v12.294L24 12l1.416 1.416-8.691 8.69zM7.416 28h17v-2h-17z'/%3E%3C/svg%3E")}.ag-icon-chevron-up:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='none' viewBox='0 0 16 16'%3E%3Cpath fill='currentColor' fill-rule='evenodd' d='M3.479 10.521a.75.75 0 0 1 0-1.06l4-4a.75.75 0 0 1 1.06 0l4 4a.75.75 0 0 1-1.06 1.06l-3.47-3.47-3.47 3.47a.75.75 0 0 1-1.06 0' clip-rule='evenodd'/%3E%3C/svg%3E")}.ag-icon-chevron-down:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='none' viewBox='0 0 16 16'%3E%3Cpath fill='currentColor' fill-rule='evenodd' d='M12.521 5.461a.75.75 0 0 1 0 1.06l-4 4a.75.75 0 0 1-1.06 0l-4-4a.75.75 0 0 1 1.06-1.06l3.47 3.47 3.47-3.47a.75.75 0 0 1 1.06 0' clip-rule='evenodd'/%3E%3C/svg%3E")}.ag-icon-chevron-left:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='none' viewBox='0 0 16 16'%3E%3Cpath fill='currentColor' fill-rule='evenodd' d='M10.53 12.512a.75.75 0 0 1-1.06 0l-4-4a.75.75 0 0 1 0-1.06l4-4a.75.75 0 0 1 1.06 1.06l-3.47 3.47 3.47 3.47a.75.75 0 0 1 0 1.06' clip-rule='evenodd'/%3E%3C/svg%3E")}.ag-icon-chevron-right:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='none' viewBox='0 0 16 16'%3E%3Cpath fill='currentColor' fill-rule='evenodd' d='M5.47 3.47a.75.75 0 0 1 1.06 0l4 4a.75.75 0 0 1 0 1.06l-4 4a.75.75 0 0 1-1.06-1.06L8.94 8 5.47 4.53a.75.75 0 0 1 0-1.06' clip-rule='evenodd'/%3E%3C/svg%3E")}.ag-icon-filter-add:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='32' height='32' fill='none' viewBox='0 0 32 32'%3E%3Cpath fill='currentColor' d='M19.834 8H8c0 .304.06.612.258.842 2.716 2.854 6.682 5.548 6.742 7.974V21l2-1.5v-2.684c.056-2.267 2.968-4.417 5.49-6.75v3.087c-1.081.974-2.245 1.968-3.232 3.005a1.05 1.05 0 0 0-.258.682v3.66L13 25c0-2.74.066-5.482-.002-8.222a1.05 1.05 0 0 0-.256-.62C10.026 13.304 6.06 10.61 6 8.184V6h13.834z'/%3E%3Cpath fill='currentColor' d='M26 6h2.946v2.002H26v3.313h-2.002V8.002h-2.946V6h2.946V3.04H26z'/%3E%3C/svg%3E")}.ag-icon-edit:before{mask-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='32' height='32' fill='none' viewBox='0 0 32 32'%3E%3Cpath fill='currentColor' d='M23.182 5a3.82 3.82 0 0 1 2.83 6.383l-.131.137-2.09 2.088a1 1 0 0 1-.084.099 1 1 0 0 1-.098.084L12.533 24.869a3 3 0 0 1-1.245.746l-4.353 1.32-.003.002a1.5 1.5 0 0 1-1.87-1.867l.003-.004 1.32-4.352v-.003l.06-.174c.13-.344.321-.661.565-.936l.126-.135L18.209 8.39a1 1 0 0 1 .18-.181l2.092-2.09.137-.132A3.82 3.82 0 0 1 23.182 5M8.548 20.883a1 1 0 0 0-.25.415l-1.049 3.451 3.457-1.048.114-.042q.17-.076.301-.206l10.458-10.46-2.572-2.572zM23.182 7c-.482 0-.946.19-1.287.531v.001l-1.474 1.475 2.572 2.572 1.474-1.474.121-.133A1.82 1.82 0 0 0 23.182 7'/%3E%3C/svg%3E")}`
);
var iconSetBalham = /* @__PURE__ */ createPart({
  feature: "iconSet",
  css: iconSetBalhamCSS
});
var iconNameToSvgFragment = {
  aggregation: '<path d="M18 7V4H6l6 8-6 8h12v-3"/>',
  arrows: '<polyline points="5 9 2 12 5 15"/><polyline points="9 5 12 2 15 5"/><polyline points="15 19 12 22 9 19"/><polyline points="19 9 22 12 19 15"/><line x1="2" x2="22" y1="12" y2="12"/><line x1="12" x2="12" y1="2" y2="22"/>',
  asc: '<path d="m5 12 7-7 7 7"/><path d="M12 19V5"/>',
  cancel: '<path d="m18 6-12 12"/><path d="m6 6 12 12"/>',
  chart: '<line x1="18" x2="18" y1="20" y2="10"/><line x1="12" x2="12" y1="20" y2="4"/><line x1="6" x2="6" y1="20" y2="14"/>',
  "color-picker": '<path d="m19 11-8-8-8.6 8.6a2 2 0 0 0 0 2.8l5.2 5.2c.8.8 2 .8 2.8 0L19 11Z"/><path d="m5 2 5 5"/><path d="M2 13h15"/><path d="M22 20a2 2 0 1 1-4 0c0-1.6 1.7-2.4 2-4 .3 1.6 2 2.4 2 4Z"/>',
  columns: '<path d="M9 3H5a2 2 0 0 0-2 2v4m6-6h10a2 2 0 0 1 2 2v4M9 3v18m0 0h10a2 2 0 0 0 2-2V9M9 21H5a2 2 0 0 1-2-2V9m0 0h18"/>',
  contracted: '<path d="m9 18 6-6-6-6"/>',
  copy: '<rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>',
  cross: '<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',
  csv: '<path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/><path d="M8 13h2"/><path d="M8 17h2"/><path d="M14 13h2"/><path d="M14 17h2"/>',
  cut: '<circle cx="6" cy="6" r="3"/><path d="M8.12 8.12 12 12"/><path d="M20 4 8.12 15.88"/><circle cx="6" cy="18" r="3"/><path d="M14.8 14.8 20 20"/>',
  desc: '<path d="M12 5v14"/><path d="m19 12-7 7-7-7"/>',
  down: '<path d="M12 5v14"/><path d="m19 12-7 7-7-7"/>',
  excel: '<path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/><path d="M8 13h2"/><path d="M8 17h2"/><path d="M14 13h2"/><path d="M14 17h2"/>',
  expanded: '<path d="m15 18-6-6 6-6"/>',
  "eye-slash": '<path d="M9.88 9.88a3 3 0 1 0 4.24 4.24"/><path d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"/><path d="M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"/><line x1="2" x2="22" y1="2" y2="22"/>',
  eye: '<path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/>',
  filter: '<path d="M3 6h18"/><path d="M7 12h10"/><path d="M10 18h4"/>',
  first: '<path d="m17 18-6-6 6-6"/><path d="M7 6v12"/>',
  group: '<path d="M16 12H3"/><path d="M16 18H3"/><path d="M10 6H3"/><path d="M21 18V8a2 2 0 0 0-2-2h-5"/><path d="m16 8-2-2 2-2"/>',
  last: '<path d="m7 18 6-6-6-6"/><path d="M17 6v12"/>',
  left: '<path d="m12 19-7-7 7-7"/><path d="M19 12H5"/>',
  linked: '<path d="M9 17H7A5 5 0 0 1 7 7h2"/><path d="M15 7h2a5 5 0 1 1 0 10h-2"/><line x1="8" x2="16" y1="12" y2="12"/>',
  loading: '<line x1="12" x2="12" y1="2" y2="6"/><line x1="12" x2="12" y1="18" y2="22"/><line x1="4.93" x2="7.76" y1="4.93" y2="7.76"/><line x1="16.24" x2="19.07" y1="16.24" y2="19.07"/><line x1="2" x2="6" y1="12" y2="12"/><line x1="18" x2="22" y1="12" y2="12"/><line x1="4.93" x2="7.76" y1="19.07" y2="16.24"/><line x1="16.24" x2="19.07" y1="7.76" y2="4.93"/>',
  maximize: '<polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" x2="14" y1="3" y2="10"/><line x1="3" x2="10" y1="21" y2="14"/>',
  menu: '<line x1="4" x2="20" y1="12" y2="12"/><line x1="4" x2="20" y1="6" y2="6"/><line x1="4" x2="20" y1="18" y2="18"/>',
  "menu-alt": '<circle cx="12" cy="5" r="0.75" fill="#D9D9D9"/><circle cx="12" cy="12" r="0.75" fill="#D9D9D9"/><circle cx="12" cy="19" r="0.75" fill="#D9D9D9"/>',
  minimize: '<polyline points="4 14 10 14 10 20"/><polyline points="20 10 14 10 14 4"/><line x1="14" x2="21" y1="10" y2="3"/><line x1="3" x2="10" y1="21" y2="14"/>',
  minus: '<circle cx="12" cy="12" r="10"/><path d="M8 12h8"/>',
  next: '<path d="m9 18 6-6-6-6"/>',
  none: '<path d="m7 15 5 5 5-5"/><path d="m7 9 5-5 5 5"/>',
  "not-allowed": '<circle cx="12" cy="12" r="10"/><path d="m4.9 4.9 14.2 14.2"/>',
  paste: '<path d="M15 2H9a1 1 0 0 0-1 1v2c0 .6.4 1 1 1h6c.6 0 1-.4 1-1V3c0-.6-.4-1-1-1Z"/><path d="M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2M16 4h2a2 2 0 0 1 2 2v2M11 14h10"/><path d="m17 10 4 4-4 4"/>',
  pin: '<line x1="12" x2="12" y1="17" y2="22"/><path d="M5 17h14v-1.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V6h1a2 2 0 0 0 0-4H8a2 2 0 0 0 0 4h1v4.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24Z"/>',
  pivot: '<path d="M15 3v18"/><rect width="18" height="18" x="3" y="3" rx="2"/><path d="M21 9H3"/><path d="M21 15H3"/>',
  plus: '<circle cx="12" cy="12" r="10"/><path d="M8 12h8"/><path d="M12 8v8"/>',
  previous: '<path d="m15 18-6-6 6-6"/>',
  right: '<path d="M5 12h14"/><path d="m12 5 7 7-7 7"/>',
  save: '<path d="M12 17V3"/><path d="m6 11 6 6 6-6"/><path d="M19 21H5"/>',
  "small-left": '<path d="m15 18-6-6 6-6"/>',
  "small-right": '<path d="m9 18 6-6-6-6"/>',
  tick: '<path d="M20 6 9 17l-5-5"/>',
  "tree-closed": '<path d="m9 18 6-6-6-6"/>',
  "tree-indeterminate": '<path d="M5 12h14"/>',
  "tree-open": '<path d="m6 9 6 6 6-6"/>',
  unlinked: '<path d="M9 17H7A5 5 0 0 1 7 7"/><path d="M15 7h2a5 5 0 0 1 4 8"/><line x1="8" x2="12" y1="12" y2="12"/><line x1="2" x2="22" y1="2" y2="22"/>',
  up: '<path d="m5 12 7-7 7 7"/><path d="M12 19V5"/>',
  grip: '<circle cx="5" cy="8" r="0.5"/><circle cx="12" cy="8" r="0.5"/><circle cx="19" cy="8" r="0.5"/><circle cx="5" cy="16" r="0.5"/><circle cx="12" cy="16" r="0.5"/><circle cx="19" cy="16" r="0.5"/><g stroke="none" fill="currentColor"><circle cx="5" cy="8" r="1"/><circle cx="12" cy="8" r="1"/><circle cx="19" cy="8" r="1"/><circle cx="5" cy="16" r="1"/><circle cx="12" cy="16" r="1"/><circle cx="19" cy="16" r="1"/></g>',
  settings: '<path d="M20 7h-9"/><path d="M14 17H5"/><circle cx="17" cy="17" r="3"/><circle cx="7" cy="7" r="3"/>'
};
var iconNameToFullSvg = {
  "column-arrow": '<svg xmlns="http://www.w3.org/2000/svg" class="ag-icon" fill="none" viewBox="0 0 32 32"><path fill-rule="evenodd" clip-rule="evenodd" d="M0 26C0 28.2092 1.79086 30 4 30H14C16.2091 30 18 28.2092 18 26V15H25.8786L24.4394 16.4393C23.8536 17.0251 23.8536 17.9749 24.4394 18.5607C25.0252 19.1464 25.9748 19.1464 26.5606 18.5607L30.5606 14.5607C31.1464 13.9749 31.1464 13.0251 30.5606 12.4393L26.5606 8.43934C25.9748 7.85356 25.0252 7.85356 24.4394 8.43934C23.8536 9.02512 23.8536 9.97488 24.4394 10.5607L25.8786 12H18V6C18 3.79086 16.2091 2 14 2H4C1.79086 2 0 3.79086 0 6V26ZM14 5H10.5V12H15V6C15 5.44772 14.5523 5 14 5ZM4 5H7.5V12H3V6C3 5.44772 3.44772 5 4 5ZM10.5 15H15V26C15 26.5522 14.5523 27 14 27H10.5V15ZM4 27H7.5V15H3V26C3 26.5522 3.44772 27 4 27Z" fill="currentColor"/></svg>',
  "small-down": '<svg xmlns="http://www.w3.org/2000/svg" class="ag-icon" fill="black" stroke="none" viewBox="0 0 32 32"><path d="M7.334 10.667 16 21.334l8.667-10.667H7.334Z"/></svg>',
  "small-up": '<svg xmlns="http://www.w3.org/2000/svg" class="ag-icon" fill="black" stroke="none" viewBox="0 0 32 32"><path d="M7.334 21.333 16 10.666l8.667 10.667H7.334Z"/></svg>',
  "pinned-top": '<svg xmlns="http://www.w3.org/2000/svg" class="ag-icon" fill="none" viewBox="0 0 16 16"><path fill="currentColor" d="M12.53 3.72A.75.75 0 0 1 12 5H4a.75.75 0 0 1 0-1.5h8a.75.75 0 0 1 .53.22ZM3.269 10.744a.75.75 0 0 1 .2-.524l4-4a.75.75 0 0 1 1.06 0l4 4a.75.75 0 1 1-1.06 1.06L8.75 8.56V14a.75.75 0 0 1-1.5 0V8.56l-2.72 2.72a.75.75 0 0 1-1.26-.536Z"/></svg>',
  "pinned-bottom": '<svg xmlns="http://www.w3.org/2000/svg" fill="none" class="ag-icon" viewBox="0 0 16 16"><path fill="currentColor" d="M3.47 12.28A.75.75 0 0 1 4 11h8a.75.75 0 0 1 0 1.5H4a.75.75 0 0 1-.53-.22ZM12.731 5.256a.75.75 0 0 1-.2.524l-4 4a.75.75 0 0 1-1.06 0l-4-4a.75.75 0 1 1 1.06-1.06l2.72 2.72V2a.75.75 0 0 1 1.5 0v5.44l2.72-2.72a.75.75 0 0 1 1.26.536Z"/></svg>',
  "un-pin": '<svg xmlns="http://www.w3.org/2000/svg" fill="none" class="ag-icon" viewBox="0 0 16 16"><path fill="currentColor" d="M8 11a.75.75 0 0 0-.75.75v3.333a.75.75 0 1 0 1.5 0V11.75A.75.75 0 0 0 8 11Z"/><path fill="currentColor" d="M13.11 1.436a.75.75 0 0 0-1.22-.872l-10 14a.75.75 0 1 0 1.22.872L5.207 12.5h7.376a.75.75 0 0 0 .75-.75v-1.174a2.08 2.08 0 0 0-1.153-1.863l-1.185-.599-.005-.002a.58.58 0 0 1-.323-.522V5.165a2.083 2.083 0 0 0 1.854-2.904l.589-.825Zm-3.943 5.52v.634a2.08 2.08 0 0 0 1.153 1.863l1.185.6.005.002a.58.58 0 0 1 .323.522V11H6.28l2.887-4.044ZM9.277 1H5.25a2.084 2.084 0 0 0-.083 4.165v1.676l1.5-2.132v-.292a.75.75 0 0 0-.75-.75H5.25a.584.584 0 0 1 0-1.167h2.972L9.277 1Z"/></svg>',
  "chevron-down": '<svg width="16" height="16" viewBox="0 0 16 16" class="ag-icon" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 6L8 10L4 6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
  "chevron-up": '<svg width="16" height="16" viewBox="0 0 16 16" class="ag-icon" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4 10L8 6L12 10" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
  "chevron-left": '<svg width="16" height="16" viewBox="0 0 16 16" class="ag-icon" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M10 12L6 8L10 4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
  "chevron-right": '<svg width="16" height="16" viewBox="0 0 16 16" class="ag-icon" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M6 12L10 8L6 4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
  "filter-add": '<svg width="16" height="16" viewBox="0 0 16 16" class="ag-icon" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M5.12126 7.75L10.8517 7.75" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/><path d="M6.65934 11.748L9.32778 11.748" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/><path d="M12.2943 1.04872V6.19184M14.9886 3.74341H9.68478" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/><path d="M8.25488 3C8.04799 3.18323 7.91706 3.45099 7.91699 3.74902C7.91713 4.04868 8.04988 4.31681 8.25879 4.5H2C1.58579 4.5 1.25 4.16421 1.25 3.75C1.25 3.33579 1.58579 3 2 3H8.25488Z" fill="currentColor"/></svg>',
  edit: '<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M3.5 10.6262V12.5012H5.375L10.905 6.97122L9.03 5.09622L3.5 10.6262ZM12.355 5.52122C12.4014 5.47497 12.4381 5.42002 12.4632 5.35953C12.4883 5.29905 12.5012 5.23421 12.5012 5.16872C12.5012 5.10324 12.4883 5.0384 12.4632 4.97791C12.4381 4.91742 12.4014 4.86248 12.355 4.81622L11.185 3.64622C11.1387 3.59987 11.0838 3.5631 11.0233 3.53801C10.9628 3.51291 10.898 3.5 10.8325 3.5C10.767 3.5 10.7022 3.51291 10.6417 3.53801C10.5812 3.5631 10.5263 3.59987 10.48 3.64622L9.565 4.56122L11.44 6.43622L12.355 5.52122Z" fill="currentColor"/></svg>'
};
var getQuartzIconsCss = (args2 = {}) => {
  let result2 = "";
  for (const iconName of [...Object.keys(iconNameToSvgFragment), ...Object.keys(iconNameToFullSvg)]) {
    const iconSvg = quartzIconSvg(iconName, args2.strokeWidth);
    result2 += `.ag-icon-${iconName}::before { mask-image: url('data:image/svg+xml,${encodeURIComponent(iconSvg)}'); }
`;
  }
  return result2;
};
var quartzIconSvg = (name2, strokeWidth = 1.5) => {
  const fullSVG = iconNameToFullSvg[name2];
  if (fullSVG) {
    return fullSVG;
  }
  const svgFragment = iconNameToSvgFragment[name2];
  if (!svgFragment) {
    throw new Error(`Missing icon data for ${name2}`);
  }
  return `<svg xmlns="http://www.w3.org/2000/svg" class="ag-icon" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke="black" stroke-width="${strokeWidth}" viewBox="0 0 24 24"><style>* { vector-effect: non-scaling-stroke; }</style>` + svgFragment + "</svg>";
};
var iconSetQuartz = (args2 = {}) => {
  return createPart({
    feature: "iconSet",
    css: () => getQuartzIconsCss(args2)
  });
};
var iconSetQuartzRegular = /* @__PURE__ */ iconSetQuartz();
var inputStyleBaseCSS = (
  /*css*/
  `:where(.ag-input-field-input[type=number]:not(.ag-number-field-input-stepper)){-webkit-appearance:textfield;-moz-appearance:textfield;appearance:textfield;&::-webkit-inner-spin-button,&::-webkit-outer-spin-button{-webkit-appearance:none;appearance:none;margin:0}}.ag-input-field-input:where(input:not([type]),input[type=text],input[type=number],input[type=tel],input[type=date],input[type=datetime-local],textarea){background-color:var(--ag-input-background-color);border:var(--ag-input-border);border-radius:var(--ag-input-border-radius);color:var(--ag-input-text-color);font-family:inherit;font-size:inherit;line-height:inherit;margin:0;min-height:var(--ag-input-height);padding:0;&:where(:disabled){background-color:var(--ag-input-disabled-background-color);border:var(--ag-input-disabled-border);color:var(--ag-input-disabled-text-color)}&:where(:focus){background-color:var(--ag-input-focus-background-color);border:var(--ag-input-focus-border);box-shadow:var(--ag-input-focus-shadow);color:var(--ag-input-focus-text-color);outline:none}&:where(:invalid){background-color:var(--ag-input-invalid-background-color);border:var(--ag-input-invalid-border);color:var(--ag-input-invalid-text-color)}&:where(.invalid){background-color:var(--ag-input-invalid-background-color);border:var(--ag-input-invalid-border);color:var(--ag-input-invalid-text-color)}&::-moz-placeholder{color:var(--ag-input-placeholder-text-color)}&::placeholder{color:var(--ag-input-placeholder-text-color)}}:where(.ag-ltr) .ag-input-field-input:where(input:not([type]),input[type=text],input[type=number],input[type=tel],input[type=date],input[type=datetime-local],textarea){padding-left:var(--ag-input-padding-start)}:where(.ag-rtl) .ag-input-field-input:where(input:not([type]),input[type=text],input[type=number],input[type=tel],input[type=date],input[type=datetime-local],textarea){padding-right:var(--ag-input-padding-start)}:where(.ag-column-select-header-filter-wrapper,.ag-filter-toolpanel-search,.ag-mini-filter,.ag-filter-filter,.ag-filter-add-select){.ag-input-wrapper:before{background-color:currentcolor;color:var(--ag-input-icon-color);content:"";display:block;height:12px;-webkit-mask-image:url("data:image/svg+xml;charset=utf-8;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMiIgaGVpZ2h0PSIxMiIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjMDAwIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiIHN0cm9rZS13aWR0aD0iMS41Ij48cGF0aCBkPSJNNS4zIDlhMy43IDMuNyAwIDEgMCAwLTcuNSAzLjcgMy43IDAgMCAwIDAgNy41Wk0xMC41IDEwLjUgOC4zIDguMiIvPjwvc3ZnPg==");mask-image:url("data:image/svg+xml;charset=utf-8;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMiIgaGVpZ2h0PSIxMiIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjMDAwIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiIHN0cm9rZS13aWR0aD0iMS41Ij48cGF0aCBkPSJNNS4zIDlhMy43IDMuNyAwIDEgMCAwLTcuNSAzLjcgMy43IDAgMCAwIDAgNy41Wk0xMC41IDEwLjUgOC4zIDguMiIvPjwvc3ZnPg==");-webkit-mask-position:center;mask-position:center;-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;opacity:.5;position:absolute;width:12px}}:where(.ag-ltr) :where(.ag-column-select-header-filter-wrapper,.ag-filter-toolpanel-search,.ag-mini-filter,.ag-filter-filter,.ag-filter-add-select){.ag-input-wrapper:before{margin-left:var(--ag-spacing)}.ag-number-field-input,.ag-text-field-input{padding-left:calc(var(--ag-spacing)*1.5 + 12px)}}:where(.ag-rtl) :where(.ag-column-select-header-filter-wrapper,.ag-filter-toolpanel-search,.ag-mini-filter,.ag-filter-filter,.ag-filter-add-select){.ag-input-wrapper:before{margin-right:var(--ag-spacing)}.ag-number-field-input,.ag-text-field-input{padding-right:calc(var(--ag-spacing)*1.5 + 12px)}}`
);
var inputStyleBorderedCSS = (
  /*css*/
  `.ag-input-field-input:where(input:not([type]),input[type=text],input[type=number],input[type=tel],input[type=date],input[type=datetime-local],textarea){&:focus{box-shadow:var(--ag-focus-shadow);&:where(.invalid),&:where(:invalid){box-shadow:var(--ag-focus-error-shadow)}}}`
);
var baseParams3 = {
  inputBackgroundColor: "transparent",
  inputBorder: false,
  inputBorderRadius: 0,
  inputTextColor: {
    ref: "textColor"
  },
  inputPlaceholderTextColor: {
    ref: "inputTextColor",
    mix: 0.5
  },
  inputPaddingStart: 0,
  inputHeight: {
    calc: "max(iconSize, fontSize) + spacing * 2"
  },
  inputFocusBackgroundColor: {
    ref: "inputBackgroundColor"
  },
  inputFocusBorder: {
    ref: "inputBorder"
  },
  inputFocusShadow: "none",
  inputFocusTextColor: {
    ref: "inputTextColor"
  },
  inputDisabledBackgroundColor: {
    ref: "inputBackgroundColor"
  },
  inputDisabledBorder: {
    ref: "inputBorder"
  },
  inputDisabledTextColor: {
    ref: "inputTextColor"
  },
  inputInvalidBackgroundColor: {
    ref: "inputBackgroundColor"
  },
  inputInvalidBorder: {
    ref: "inputBorder"
  },
  inputInvalidTextColor: {
    ref: "inputTextColor"
  },
  inputIconColor: {
    ref: "inputTextColor"
  },
  pickerButtonBorder: false,
  pickerButtonFocusBorder: { ref: "inputFocusBorder" },
  pickerButtonBackgroundColor: { ref: "backgroundColor" },
  pickerButtonFocusBackgroundColor: { ref: "backgroundColor" },
  pickerListBorder: false,
  pickerListBackgroundColor: { ref: "backgroundColor" },
  colorPickerThumbSize: 18,
  colorPickerTrackSize: 12,
  colorPickerThumbBorderWidth: 3,
  colorPickerTrackBorderRadius: 12,
  colorPickerColorBorderRadius: 4
};
var makeInputStyleBorderedTreeShakeable = () => createPart({
  feature: "inputStyle",
  params: {
    ...baseParams3,
    inputBackgroundColor: backgroundColor,
    inputBorder: true,
    inputBorderRadius: {
      ref: "borderRadius"
    },
    inputPaddingStart: {
      ref: "spacing"
    },
    inputFocusBorder: {
      color: accentColor
    },
    inputFocusShadow: {
      ref: "focusShadow"
    },
    inputDisabledBackgroundColor: foregroundBackgroundMix(0.06),
    inputDisabledTextColor: {
      ref: "textColor",
      mix: 0.5
    },
    inputInvalidBorder: {
      color: { ref: "invalidColor" }
    },
    pickerButtonBorder: true,
    pickerListBorder: true
  },
  css: () => inputStyleBaseCSS + inputStyleBorderedCSS
});
var inputStyleBordered = /* @__PURE__ */ makeInputStyleBorderedTreeShakeable();
var tabStyleBaseCSS = (
  /*css*/
  `.ag-tabs-header{background-color:var(--ag-tab-bar-background-color);border-bottom:var(--ag-tab-bar-border);display:flex;flex:1;gap:var(--ag-tab-spacing);padding:var(--ag-tab-bar-top-padding) var(--ag-tab-bar-horizontal-padding) 0}.ag-tabs-header-wrapper{display:flex}.ag-tabs-close-button-wrapper{align-items:center;border:0;display:flex;padding:var(--ag-spacing)}:where(.ag-ltr) .ag-tabs-close-button-wrapper{border-right:solid var(--ag-border-width) var(--ag-border-color)}:where(.ag-rtl) .ag-tabs-close-button-wrapper{border-left:solid var(--ag-border-width) var(--ag-border-color)}.ag-tabs-close-button{background-color:unset;border:0;cursor:pointer;padding:0}.ag-tab{align-items:center;background-color:var(--ag-tab-background-color);border-left:var(--ag-tab-selected-border-width) solid transparent;border-right:var(--ag-tab-selected-border-width) solid transparent;color:var(--ag-tab-text-color);cursor:pointer;display:flex;flex:1;justify-content:center;padding:var(--ag-tab-top-padding) var(--ag-tab-horizontal-padding) var(--ag-tab-bottom-padding);position:relative;&:hover{background-color:var(--ag-tab-hover-background-color);color:var(--ag-tab-hover-text-color)}&.ag-tab-selected{background-color:var(--ag-tab-selected-background-color);color:var(--ag-tab-selected-text-color)}&:after{background-color:var(--ag-tab-selected-underline-color);bottom:0;content:"";display:block;height:var(--ag-tab-selected-underline-width);left:0;opacity:0;position:absolute;right:0;transition:opacity var(--ag-tab-selected-underline-transition-duration)}&.ag-tab-selected:after{opacity:1}}:where(.ag-ltr) .ag-tab{&.ag-tab-selected{&:where(:not(:first-of-type)){border-left-color:var(--ag-tab-selected-border-color)}&:where(:not(:last-of-type)){border-right-color:var(--ag-tab-selected-border-color)}}}:where(.ag-rtl) .ag-tab{&.ag-tab-selected{&:where(:not(:first-of-type)){border-right-color:var(--ag-tab-selected-border-color)}&:where(:not(:last-of-type)){border-left-color:var(--ag-tab-selected-border-color)}}}`
);
var tabStyleRolodexCSS = (
  /*css*/
  `.ag-tab{border-left:var(--ag-tab-selected-border-width) solid transparent;border-right:var(--ag-tab-selected-border-width) solid transparent;border-top:var(--ag-tab-selected-border-width) solid transparent;flex:none;&.ag-tab-selected{border-left-color:var(--ag-tab-selected-border-color);border-right-color:var(--ag-tab-selected-border-color);border-top-color:var(--ag-tab-selected-border-color);margin-bottom:-1px;padding-bottom:calc(var(--ag-tab-bottom-padding) + 1px)}}`
);
var baseParams4 = {
  tabBarBackgroundColor: "transparent",
  tabBarHorizontalPadding: 0,
  tabBarTopPadding: 0,
  tabBackgroundColor: "transparent",
  tabTextColor: {
    ref: "textColor"
  },
  tabHorizontalPadding: {
    ref: "spacing"
  },
  tabTopPadding: {
    ref: "spacing"
  },
  tabBottomPadding: {
    ref: "spacing"
  },
  tabSpacing: "0",
  tabHoverBackgroundColor: {
    ref: "tabBackgroundColor"
  },
  tabHoverTextColor: {
    ref: "tabTextColor"
  },
  tabSelectedBackgroundColor: {
    ref: "tabBackgroundColor"
  },
  tabSelectedTextColor: {
    ref: "tabTextColor"
  },
  tabSelectedBorderWidth: { ref: "borderWidth" },
  tabSelectedBorderColor: "transparent",
  tabSelectedUnderlineColor: "transparent",
  tabSelectedUnderlineWidth: 0,
  tabSelectedUnderlineTransitionDuration: 0,
  tabBarBorder: false
};
var makeTabStyleQuartzTreeShakeable = () => createPart({
  feature: "tabStyle",
  params: {
    ...baseParams4,
    tabBarBorder: true,
    tabBarBackgroundColor: foregroundMix(0.05),
    tabTextColor: {
      ref: "textColor",
      mix: 0.7
    },
    tabSelectedTextColor: {
      ref: "textColor"
    },
    tabHoverTextColor: {
      ref: "textColor"
    },
    tabSelectedBorderColor: {
      ref: "borderColor"
    },
    tabSelectedBackgroundColor: backgroundColor
  },
  css: tabStyleBaseCSS
});
var tabStyleQuartz = /* @__PURE__ */ makeTabStyleQuartzTreeShakeable();
var makeTabStyleRolodexTreeShakeable = () => createPart({
  feature: "tabStyle",
  params: {
    ...baseParams4,
    tabBarBackgroundColor: {
      ref: "chromeBackgroundColor"
    },
    tabBarHorizontalPadding: {
      ref: "spacing"
    },
    tabBarTopPadding: {
      ref: "spacing"
    },
    tabBarBorder: true,
    tabHorizontalPadding: { calc: "spacing * 2" },
    tabTopPadding: {
      ref: "spacing"
    },
    tabBottomPadding: {
      ref: "spacing"
    },
    tabSpacing: {
      ref: "spacing"
    },
    tabSelectedBorderColor: {
      ref: "borderColor"
    },
    tabSelectedBackgroundColor: backgroundColor
  },
  css: () => tabStyleBaseCSS + tabStyleRolodexCSS
});
var tabStyleRolodex = /* @__PURE__ */ makeTabStyleRolodexTreeShakeable();
var makeThemeQuartzTreeShakeable = () => createTheme().withPart(checkboxStyleDefault).withPart(colorSchemeVariable).withPart(iconSetQuartzRegular).withPart(tabStyleQuartz).withPart(inputStyleBordered).withPart(columnDropStyleBordered).withParams({
  fontFamily: [
    { googleFont: "IBM Plex Sans" },
    "-apple-system",
    "BlinkMacSystemFont",
    "Segoe UI",
    "Roboto",
    "Oxygen-Sans",
    "Ubuntu"
  ]
});
var themeQuartz = /* @__PURE__ */ makeThemeQuartzTreeShakeable();
var makeThemeBalhamTreeShakeable = () => createTheme().withPart(buttonStyleBalham).withPart(checkboxStyleDefault).withPart(colorSchemeVariable).withPart(iconSetBalham).withPart(tabStyleRolodex).withPart(inputStyleBordered).withPart(columnDropStylePlain).withParams({
  accentColor: "#0091ea",
  borderColor: foregroundMix(0.2),
  spacing: 4,
  widgetVerticalSpacing: { calc: "max(8px, spacing)" },
  borderRadius: 2,
  wrapperBorderRadius: 2,
  headerColumnResizeHandleColor: "transparent",
  headerColumnBorder: true,
  headerColumnBorderHeight: "50%",
  oddRowBackgroundColor: {
    ref: "chromeBackgroundColor",
    mix: 0.5
  },
  checkboxBorderRadius: 2,
  checkboxBorderWidth: 1,
  checkboxUncheckedBackgroundColor: backgroundColor,
  checkboxUncheckedBorderColor: foregroundBackgroundMix(0.5),
  checkboxCheckedBackgroundColor: backgroundColor,
  checkboxCheckedBorderColor: accentColor,
  checkboxCheckedShapeColor: accentColor,
  checkboxIndeterminateBackgroundColor: backgroundColor,
  checkboxIndeterminateBorderColor: foregroundBackgroundMix(0.5),
  checkboxIndeterminateShapeColor: foregroundBackgroundMix(0.5),
  focusShadow: { radius: 2, spread: 1, color: accentColor },
  headerTextColor: foregroundMix(0.6),
  iconButtonHoverBackgroundColor: "transparent",
  iconButtonActiveBackgroundColor: "transparent",
  fontSize: 12,
  tabSelectedBackgroundColor: backgroundColor,
  headerFontWeight: "bold",
  toggleButtonWidth: 32,
  toggleButtonHeight: 16,
  toggleButtonSwitchInset: 1,
  toggleButtonOffBackgroundColor: foregroundBackgroundMix(0.5),
  sideButtonBorder: true,
  sideButtonBarTopPadding: { calc: "spacing * 4" },
  popupShadow: "5px 5px 10px rgba(0, 0, 0, 0.3)",
  statusBarLabelColor: foregroundMix(0.54),
  statusBarLabelFontWeight: 600,
  statusBarValueFontWeight: 600,
  panelTitleBarIconColor: foregroundColor,
  colorPickerThumbSize: 13,
  colorPickerTrackSize: 11,
  colorPickerThumbBorderWidth: 2,
  colorPickerTrackBorderRadius: 2,
  colorPickerColorBorderRadius: 2
});
var themeBalham = /* @__PURE__ */ makeThemeBalhamTreeShakeable();
var CELL_HORIZONTAL_PADDING = {
  cssName: "--ag-cell-horizontal-padding",
  changeKey: "cellHorizontalPaddingChanged",
  defaultValue: 16
};
var INDENTATION_LEVEL = {
  cssName: "--ag-indentation-level",
  changeKey: "indentationLevelChanged",
  defaultValue: 0,
  noWarn: true,
  cacheDefault: true
};
var ROW_GROUP_INDENT_SIZE = {
  cssName: "--ag-row-group-indent-size",
  changeKey: "rowGroupIndentSizeChanged",
  defaultValue: 0
};
var ROW_HEIGHT = {
  cssName: "--ag-row-height",
  changeKey: "rowHeightChanged",
  defaultValue: 42
};
var HEADER_HEIGHT = {
  cssName: "--ag-header-height",
  changeKey: "headerHeightChanged",
  defaultValue: 48
};
var LIST_ITEM_HEIGHT = {
  cssName: "--ag-list-item-height",
  changeKey: "listItemHeightChanged",
  defaultValue: 24
};
var ROW_BORDER_WIDTH = {
  cssName: "--ag-row-border",
  changeKey: "rowBorderWidthChanged",
  defaultValue: 1,
  border: true
};
var PINNED_BORDER_WIDTH = {
  cssName: "--ag-pinned-row-border",
  changeKey: "pinnedRowBorderWidthChanged",
  defaultValue: 1,
  border: true
};
function _addAdditionalCss(cssMap, modules) {
  for (const module of modules.sort((a2, b) => a2.moduleName.localeCompare(b.moduleName))) {
    const moduleCss = module.css;
    if (moduleCss) {
      cssMap.set(`module-${module.moduleName}`, moduleCss);
    }
  }
}
var Environment = class extends BaseEnvironment {
  constructor() {
    super(...arguments);
    this.sizeEls = /* @__PURE__ */ new Map();
    this.lastKnownValues = /* @__PURE__ */ new Map();
    this.sizesMeasured = false;
  }
  initVariables() {
    this.addManagedPropertyListener("rowHeight", () => this.refreshRowHeightVariable());
    this.getSizeEl(ROW_HEIGHT);
    this.getSizeEl(HEADER_HEIGHT);
    this.getSizeEl(LIST_ITEM_HEIGHT);
    this.getSizeEl(ROW_BORDER_WIDTH);
    this.getSizeEl(PINNED_BORDER_WIDTH);
    this.refreshRowBorderWidthVariable();
  }
  getPinnedRowBorderWidth() {
    return this.getCSSVariablePixelValue(PINNED_BORDER_WIDTH);
  }
  getRowBorderWidth() {
    return this.getCSSVariablePixelValue(ROW_BORDER_WIDTH);
  }
  getDefaultRowHeight() {
    return this.getCSSVariablePixelValue(ROW_HEIGHT);
  }
  getDefaultHeaderHeight() {
    return this.getCSSVariablePixelValue(HEADER_HEIGHT);
  }
  getDefaultCellHorizontalPadding() {
    return this.getCSSVariablePixelValue(CELL_HORIZONTAL_PADDING);
  }
  getCellPaddingLeft() {
    const cellHorizontalPadding = this.getDefaultCellHorizontalPadding();
    const indentationLevel = this.getCSSVariablePixelValue(INDENTATION_LEVEL);
    const rowGroupIndentSize = this.getCSSVariablePixelValue(ROW_GROUP_INDENT_SIZE);
    return cellHorizontalPadding - 1 + rowGroupIndentSize * indentationLevel;
  }
  getCellPadding() {
    const cellPaddingRight = this.getDefaultCellHorizontalPadding() - 1;
    return this.getCellPaddingLeft() + cellPaddingRight;
  }
  getDefaultColumnMinWidth() {
    return Math.min(36, this.getDefaultRowHeight());
  }
  getDefaultListItemHeight() {
    return this.getCSSVariablePixelValue(LIST_ITEM_HEIGHT);
  }
  refreshRowHeightVariable() {
    const { eRootDiv } = this;
    const oldRowHeight = eRootDiv.style.getPropertyValue("--ag-line-height").trim();
    const height = this.gos.get("rowHeight");
    if (height == null || isNaN(height) || !isFinite(height)) {
      if (oldRowHeight !== null) {
        eRootDiv.style.setProperty("--ag-line-height", null);
      }
      return -1;
    }
    const newRowHeight = `${height}px`;
    if (oldRowHeight != newRowHeight) {
      eRootDiv.style.setProperty("--ag-line-height", newRowHeight);
      return height;
    }
    return oldRowHeight != "" ? Number.parseFloat(oldRowHeight) : -1;
  }
  getCSSVariablePixelValue(variable) {
    const cached = this.lastKnownValues.get(variable);
    if (cached != null) {
      return cached;
    }
    const measurement = this.measureSizeEl(variable);
    if (measurement === "detached" || measurement === "no-styles") {
      if (variable.cacheDefault) {
        this.lastKnownValues.set(variable, variable.defaultValue);
      }
      return variable.defaultValue;
    }
    this.lastKnownValues.set(variable, measurement);
    return measurement;
  }
  measureSizeEl(variable) {
    const sizeEl = this.getSizeEl(variable);
    if (sizeEl.offsetParent == null) {
      return "detached";
    }
    const newSize = sizeEl.offsetWidth;
    if (newSize === NO_VALUE_SENTINEL) {
      return "no-styles";
    }
    this.sizesMeasured = true;
    return newSize;
  }
  getMeasurementContainer() {
    let container2 = this.eMeasurementContainer;
    if (!container2) {
      container2 = this.eMeasurementContainer = _createElement({ tag: "div", cls: "ag-measurement-container" });
      this.eRootDiv.appendChild(container2);
    }
    return container2;
  }
  getSizeEl(variable) {
    let sizeEl = this.sizeEls.get(variable);
    if (sizeEl) {
      return sizeEl;
    }
    const container2 = this.getMeasurementContainer();
    sizeEl = _createElement({ tag: "div" });
    const { border, noWarn } = variable;
    if (border) {
      sizeEl.className = "ag-measurement-element-border";
      sizeEl.style.setProperty(
        "--ag-internal-measurement-border",
        `var(${variable.cssName}, solid ${NO_VALUE_SENTINEL}px)`
      );
    } else {
      sizeEl.style.width = `var(${variable.cssName}, ${NO_VALUE_SENTINEL}px)`;
    }
    container2.appendChild(sizeEl);
    this.sizeEls.set(variable, sizeEl);
    let lastMeasurement = this.measureSizeEl(variable);
    if (lastMeasurement === "no-styles" && !noWarn) {
      _warn(9, { variable });
    }
    const unsubscribe = _observeResize(this.beans, sizeEl, () => {
      const newMeasurement = this.measureSizeEl(variable);
      if (newMeasurement === "detached" || newMeasurement === "no-styles") {
        return;
      }
      this.lastKnownValues.set(variable, newMeasurement);
      if (newMeasurement !== lastMeasurement) {
        lastMeasurement = newMeasurement;
        this.fireStylesChangedEvent(variable.changeKey);
      }
    });
    this.addDestroyFunc(() => unsubscribe());
    return sizeEl;
  }
  fireStylesChangedEvent(change) {
    if (change === "rowBorderWidthChanged") {
      this.refreshRowBorderWidthVariable();
    }
    this.eventSvc.dispatchEvent({
      type: "gridStylesChanged",
      [change]: true
    });
  }
  refreshRowBorderWidthVariable() {
    const width = this.getCSSVariablePixelValue(ROW_BORDER_WIDTH);
    this.eRootDiv.style.setProperty("--ag-internal-row-border-width", `${width}px`);
  }
  postProcessThemeChange(newGridTheme, themeGridOption) {
    if (newGridTheme && getComputedStyle(this.getMeasurementContainer()).getPropertyValue("--ag-legacy-styles-loaded")) {
      if (themeGridOption) {
        _error(106);
      } else {
        _error(239);
      }
    }
  }
  getAdditionalCss() {
    const additionalCss = /* @__PURE__ */ new Map();
    additionalCss.set("core", [coreCSS]);
    _addAdditionalCss(additionalCss, Array.from(_getAllRegisteredModules()));
    return additionalCss;
  }
  getDefaultTheme() {
    return themeQuartz;
  }
  themeError(theme) {
    _error(240, { theme });
  }
};
var NO_VALUE_SENTINEL = 15538;
var EventService = class extends BaseEventService {
  postConstruct() {
    const { globalListener, globalSyncListener } = this.beans;
    if (globalListener) {
      this.addGlobalListener(globalListener, true);
    }
    if (globalSyncListener) {
      this.addGlobalListener(globalSyncListener, false);
    }
  }
};
function getHeaderIndexToFocus(beans, column2, level) {
  const columnRowIndex = beans.visibleCols.headerGroupRowCount;
  if (level >= columnRowIndex) {
    return {
      column: column2,
      headerRowIndex: level
    };
  }
  let parent = column2.getParent();
  while (parent && parent.getProvidedColumnGroup().getLevel() > level) {
    parent = parent.getParent();
  }
  const isColSpanning = column2.isSpanHeaderHeight();
  if (!parent || isColSpanning && parent.isPadding()) {
    return {
      column: column2,
      headerRowIndex: columnRowIndex
    };
  }
  return {
    column: parent,
    headerRowIndex: parent.getProvidedColumnGroup().getLevel()
  };
}
var HeaderNavigationService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "headerNavigation";
    this.currentHeaderRowWithoutSpan = -1;
  }
  postConstruct() {
    const beans = this.beans;
    beans.ctrlsSvc.whenReady(this, (p) => {
      this.gridBodyCon = p.gridBodyCtrl;
    });
    const eDocument = _getDocument(beans);
    this.addManagedElementListeners(eDocument, {
      mousedown: () => {
        this.currentHeaderRowWithoutSpan = -1;
      }
    });
  }
  getHeaderPositionForColumn(colKey, floatingFilter) {
    let column2;
    const { colModel, colGroupSvc, ctrlsSvc } = this.beans;
    if (typeof colKey === "string") {
      column2 = colModel.getCol(colKey);
      if (!column2) {
        column2 = colGroupSvc?.getColumnGroup(colKey) ?? null;
      }
    } else {
      column2 = colKey;
    }
    if (!column2) {
      return null;
    }
    const centerHeaderContainer = ctrlsSvc.getHeaderRowContainerCtrl();
    const allCtrls = centerHeaderContainer?.getAllCtrls();
    const isFloatingFilterVisible = _last(allCtrls || []).type === "filter";
    const headerRowCount = getFocusHeaderRowCount(this.beans) - 1;
    let row2 = -1;
    let col = column2;
    while (col) {
      row2++;
      col = col.getParent();
    }
    let headerRowIndex = row2;
    if (floatingFilter && isFloatingFilterVisible && headerRowIndex === headerRowCount - 1) {
      headerRowIndex++;
    }
    return headerRowIndex === -1 ? null : {
      headerRowIndex,
      column: column2
    };
  }
  /*
   * This method navigates grid header vertically
   * @return {boolean} true to preventDefault on the event that caused this navigation.
   */
  navigateVertically(direction, event) {
    const { focusSvc, visibleCols } = this.beans;
    const { focusedHeader } = focusSvc;
    if (!focusedHeader) {
      return false;
    }
    const { headerRowIndex } = focusedHeader;
    const column2 = focusedHeader.column;
    const rowLen = getFocusHeaderRowCount(this.beans);
    const currentRowType = this.getHeaderRowType(headerRowIndex);
    const columnHeaderRowIndex = visibleCols.headerGroupRowCount;
    let {
      headerRowIndex: nextRow,
      column: nextFocusColumn,
      headerRowIndexWithoutSpan
    } = direction === "UP" ? getColumnVisibleParent(currentRowType, column2, headerRowIndex) : getColumnVisibleChild(column2, headerRowIndex, columnHeaderRowIndex);
    let skipColumn = false;
    if (nextRow < 0) {
      nextRow = 0;
      nextFocusColumn = column2;
      skipColumn = true;
    }
    if (nextRow >= rowLen) {
      nextRow = -1;
      this.currentHeaderRowWithoutSpan = -1;
    } else if (headerRowIndexWithoutSpan !== void 0) {
      this.currentHeaderRowWithoutSpan = headerRowIndexWithoutSpan;
    }
    if (!skipColumn && !nextFocusColumn) {
      return false;
    }
    return focusSvc.focusHeaderPosition({
      headerPosition: { headerRowIndex: nextRow, column: nextFocusColumn },
      allowUserOverride: true,
      event
    });
  }
  /*
   * This method navigates grid header horizontally
   * @returns {boolean} true to preventDefault on the event that caused this navigation.
   */
  navigateHorizontally(direction, fromTab = false, event) {
    const { focusSvc, gos } = this.beans;
    const focusedHeader = { ...focusSvc.focusedHeader };
    let nextHeader;
    let normalisedDirection;
    if (this.currentHeaderRowWithoutSpan !== -1) {
      focusedHeader.headerRowIndex = this.currentHeaderRowWithoutSpan;
    } else {
      this.currentHeaderRowWithoutSpan = focusedHeader.headerRowIndex;
    }
    if (direction === "LEFT" !== gos.get("enableRtl")) {
      normalisedDirection = "Before";
      nextHeader = this.findHeader(focusedHeader, normalisedDirection);
    } else {
      normalisedDirection = "After";
      nextHeader = this.findHeader(focusedHeader, normalisedDirection);
    }
    const userFunc = gos.getCallback("tabToNextHeader");
    if (fromTab && userFunc) {
      const wasFocusedFromUserFunc = focusSvc.focusHeaderPositionFromUserFunc({
        userFunc,
        headerPosition: nextHeader,
        direction: normalisedDirection
      });
      if (wasFocusedFromUserFunc) {
        const { headerRowIndex } = focusSvc.focusedHeader || {};
        if (headerRowIndex != null && headerRowIndex != focusedHeader.headerRowIndex) {
          this.currentHeaderRowWithoutSpan = headerRowIndex;
        }
      }
      return wasFocusedFromUserFunc;
    }
    if (nextHeader || !fromTab) {
      return focusSvc.focusHeaderPosition({
        headerPosition: nextHeader,
        direction: normalisedDirection,
        fromTab,
        allowUserOverride: true,
        event
      });
    }
    return this.focusNextHeaderRow(focusedHeader, normalisedDirection, event);
  }
  focusNextHeaderRow(focusedHeader, direction, event) {
    const beans = this.beans;
    const currentIndex = focusedHeader.headerRowIndex;
    let nextFocusedCol = null;
    let nextRowIndex;
    const headerRowCount = getFocusHeaderRowCount(beans);
    const allVisibleCols = this.beans.visibleCols.allCols;
    if (direction === "Before") {
      if (currentIndex <= 0) {
        return false;
      }
      nextFocusedCol = _last(allVisibleCols);
      nextRowIndex = currentIndex - 1;
      this.currentHeaderRowWithoutSpan -= 1;
    } else {
      nextFocusedCol = allVisibleCols[0];
      nextRowIndex = currentIndex + 1;
      if (this.currentHeaderRowWithoutSpan < headerRowCount) {
        this.currentHeaderRowWithoutSpan += 1;
      } else {
        this.currentHeaderRowWithoutSpan = -1;
      }
    }
    let { column: column2, headerRowIndex } = getHeaderIndexToFocus(this.beans, nextFocusedCol, nextRowIndex);
    if (headerRowIndex >= headerRowCount) {
      headerRowIndex = -1;
    }
    return beans.focusSvc.focusHeaderPosition({
      headerPosition: { column: column2, headerRowIndex },
      direction,
      fromTab: true,
      allowUserOverride: true,
      event
    });
  }
  scrollToColumn(column2, direction = "After") {
    if (column2.getPinned()) {
      return;
    }
    let columnToScrollTo;
    if (isColumnGroup(column2)) {
      const columns2 = column2.getDisplayedLeafColumns();
      columnToScrollTo = direction === "Before" ? _last(columns2) : columns2[0];
    } else {
      columnToScrollTo = column2;
    }
    this.gridBodyCon.scrollFeature.ensureColumnVisible(columnToScrollTo);
  }
  findHeader(focusedHeader, direction) {
    const { colGroupSvc, visibleCols } = this.beans;
    let currentFocusedColumn = focusedHeader.column;
    if (currentFocusedColumn instanceof AgColumnGroup) {
      const leafChildren = currentFocusedColumn.getDisplayedLeafColumns();
      currentFocusedColumn = direction === "Before" ? leafChildren[0] : leafChildren[leafChildren.length - 1];
    }
    const nextFocusedCol = direction === "Before" ? visibleCols.getColBefore(currentFocusedColumn) : visibleCols.getColAfter(currentFocusedColumn);
    if (!nextFocusedCol) {
      return void 0;
    }
    const headerGroupRowIndex = visibleCols.headerGroupRowCount;
    if (focusedHeader.headerRowIndex >= headerGroupRowIndex) {
      return {
        headerRowIndex: focusedHeader.headerRowIndex,
        column: nextFocusedCol
      };
    }
    const groupAtLevel = colGroupSvc?.getColGroupAtLevel(nextFocusedCol, focusedHeader.headerRowIndex);
    if (!groupAtLevel) {
      const isSpanningCol = nextFocusedCol instanceof AgColumn && nextFocusedCol.isSpanHeaderHeight();
      return {
        headerRowIndex: isSpanningCol ? visibleCols.headerGroupRowCount : focusedHeader.headerRowIndex,
        column: nextFocusedCol
      };
    }
    if (groupAtLevel.isPadding() && nextFocusedCol.isSpanHeaderHeight()) {
      return {
        headerRowIndex: visibleCols.headerGroupRowCount,
        column: nextFocusedCol
      };
    }
    return {
      headerRowIndex: focusedHeader.headerRowIndex,
      column: groupAtLevel ?? nextFocusedCol
    };
  }
  getHeaderRowType(rowIndex) {
    const centerHeaderContainer = this.beans.ctrlsSvc.getHeaderRowContainerCtrl();
    if (centerHeaderContainer) {
      return centerHeaderContainer.getRowType(rowIndex);
    }
  }
};
function getColumnVisibleParent(currentRowType, currentColumn, currentIndex) {
  const optimisticNextIndex = currentIndex - 1;
  if (currentRowType !== "filter") {
    const isSpanningCol = currentColumn instanceof AgColumn && currentColumn.isSpanHeaderHeight();
    let nextVisibleParent = currentColumn.getParent();
    while (nextVisibleParent && // skip if row isn't visible or col is padding and spanned
    (nextVisibleParent.getProvidedColumnGroup().getLevel() > optimisticNextIndex || isSpanningCol && nextVisibleParent.isPadding())) {
      nextVisibleParent = nextVisibleParent.getParent();
    }
    if (nextVisibleParent) {
      if (isSpanningCol) {
        return {
          column: nextVisibleParent,
          headerRowIndex: nextVisibleParent.getProvidedColumnGroup().getLevel(),
          headerRowIndexWithoutSpan: optimisticNextIndex
        };
      } else {
        return {
          column: nextVisibleParent,
          headerRowIndex: optimisticNextIndex,
          headerRowIndexWithoutSpan: optimisticNextIndex
        };
      }
    }
  }
  return {
    column: currentColumn,
    headerRowIndex: optimisticNextIndex,
    headerRowIndexWithoutSpan: optimisticNextIndex
  };
}
function getColumnVisibleChild(column2, currentIndex, columnHeaderRowIndex) {
  const optimisticNextIndex = currentIndex + 1;
  const result2 = {
    column: column2,
    headerRowIndex: optimisticNextIndex,
    headerRowIndexWithoutSpan: optimisticNextIndex
  };
  if (column2 instanceof AgColumnGroup) {
    if (optimisticNextIndex >= columnHeaderRowIndex) {
      return {
        column: column2.getDisplayedLeafColumns()[0],
        headerRowIndex: columnHeaderRowIndex,
        headerRowIndexWithoutSpan: optimisticNextIndex
      };
    }
    const children2 = column2.getDisplayedChildren();
    let firstChild = children2[0];
    if (firstChild instanceof AgColumnGroup && firstChild.isPadding()) {
      const firstCol = firstChild.getDisplayedLeafColumns()[0];
      if (firstCol.isSpanHeaderHeight()) {
        firstChild = firstCol;
      }
    }
    result2.column = firstChild;
    const isSpanningCol = firstChild instanceof AgColumn && firstChild.isSpanHeaderHeight();
    if (isSpanningCol) {
      result2.headerRowIndex = columnHeaderRowIndex;
      result2.headerRowIndexWithoutSpan = optimisticNextIndex;
    }
  }
  return result2;
}
var FocusService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "focusSvc";
    this.focusFallbackTimeout = null;
    this.needsFocusRestored = false;
  }
  wireBeans(beans) {
    this.colModel = beans.colModel;
    this.visibleCols = beans.visibleCols;
    this.rowRenderer = beans.rowRenderer;
    this.navigation = beans.navigation;
    this.filterManager = beans.filterManager;
    this.overlays = beans.overlays;
  }
  postConstruct() {
    const clearFocusedCellListener = this.clearFocusedCell.bind(this);
    this.addManagedEventListeners({
      columnPivotModeChanged: clearFocusedCellListener,
      newColumnsLoaded: this.onColumnEverythingChanged.bind(this),
      columnGroupOpened: clearFocusedCellListener,
      columnRowGroupChanged: clearFocusedCellListener
    });
    this.addDestroyFunc(_registerKeyboardFocusEvents(this.beans));
  }
  attemptToRecoverFocus() {
    this.needsFocusRestored = true;
    if (this.focusFallbackTimeout != null) {
      clearTimeout(this.focusFallbackTimeout);
    }
    this.focusFallbackTimeout = window.setTimeout(this.setFocusRecovered.bind(this), 100);
  }
  setFocusRecovered() {
    this.needsFocusRestored = false;
    if (this.focusFallbackTimeout != null) {
      clearTimeout(this.focusFallbackTimeout);
      this.focusFallbackTimeout = null;
    }
  }
  /**
   * Specifies whether to take focus, as grid either already has focus, or lost it due
   * to a destroyed cell
   * @returns true if the grid should re-take focus, otherwise false
   */
  shouldTakeFocus() {
    if (this.gos.get("suppressFocusAfterRefresh")) {
      this.setFocusRecovered();
      return false;
    }
    if (this.needsFocusRestored) {
      this.setFocusRecovered();
      return true;
    }
    return this.doesRowOrCellHaveBrowserFocus();
  }
  onColumnEverythingChanged() {
    if (!this.focusedCell) {
      return;
    }
    const col = this.focusedCell.column;
    const colFromColumnModel = this.colModel.getCol(col.getId());
    if (col !== colFromColumnModel) {
      this.clearFocusedCell();
    }
  }
  // we check if the browser is focusing something, and if it is, and
  // it's the cell we think is focused, then return the cell. so this
  // methods returns the cell if a) we think it has focus and b) the
  // browser thinks it has focus. this then returns nothing if we
  // first focus a cell, then second click outside the grid, as then the
  // grid cell will still be focused as far as the grid is concerned,
  // however the browser focus will have moved somewhere else.
  getFocusCellToUseAfterRefresh() {
    const { gos, focusedCell } = this;
    if (gos.get("suppressFocusAfterRefresh") || gos.get("suppressCellFocus") || !focusedCell) {
      return null;
    }
    if (!this.doesRowOrCellHaveBrowserFocus()) {
      return null;
    }
    return focusedCell;
  }
  getFocusHeaderToUseAfterRefresh() {
    if (this.gos.get("suppressFocusAfterRefresh") || !this.focusedHeader) {
      return null;
    }
    if (!this.isDomDataPresentInHierarchy(_getActiveDomElement(this.beans), DOM_DATA_KEY_HEADER_CTRL)) {
      return null;
    }
    return this.focusedHeader;
  }
  /**
   * Check for both cells and rows, as a row might be destroyed and the dom data removed before the cell if the
   * row is animating out.
   */
  doesRowOrCellHaveBrowserFocus() {
    const activeElement = _getActiveDomElement(this.beans);
    if (this.isDomDataPresentInHierarchy(activeElement, DOM_DATA_KEY_CELL_CTRL)) {
      return true;
    }
    return this.isDomDataPresentInHierarchy(activeElement, DOM_DATA_KEY_ROW_CTRL);
  }
  isDomDataPresentInHierarchy(eBrowserCell, key2) {
    let ePointer = eBrowserCell;
    while (ePointer) {
      const data2 = _getDomData(this.gos, ePointer, key2);
      if (data2) {
        return true;
      }
      ePointer = ePointer.parentNode;
    }
    return false;
  }
  getFocusedCell() {
    return this.focusedCell;
  }
  getFocusEventParams(focusedCellPosition) {
    const { rowIndex, rowPinned, column: column2 } = focusedCellPosition;
    const params = {
      rowIndex,
      rowPinned,
      column: column2,
      isFullWidthCell: false
    };
    const rowCtrl = this.rowRenderer.getRowByPosition({ rowIndex, rowPinned });
    if (rowCtrl) {
      params.isFullWidthCell = rowCtrl.isFullWidth();
    }
    return params;
  }
  clearFocusedCell() {
    if (this.focusedCell == null) {
      return;
    }
    const focusEventParams = this.getFocusEventParams(this.focusedCell);
    this.focusedCell = null;
    this.eventSvc.dispatchEvent({
      type: "cellFocusCleared",
      ...focusEventParams
    });
  }
  setFocusedCell(params) {
    this.setFocusRecovered();
    const {
      column: column2,
      rowIndex,
      rowPinned,
      forceBrowserFocus = false,
      preventScrollOnBrowserFocus = false,
      sourceEvent
    } = params;
    const gridColumn = this.colModel.getCol(column2);
    if (!gridColumn) {
      this.focusedCell = null;
      return;
    }
    this.focusedCell = {
      rowIndex,
      rowPinned: _makeNull(rowPinned),
      column: gridColumn
    };
    const focusEventParams = this.getFocusEventParams(this.focusedCell);
    this.eventSvc.dispatchEvent({
      type: "cellFocused",
      ...focusEventParams,
      ...this.previousCellFocusParams && { previousParams: this.previousCellFocusParams },
      forceBrowserFocus,
      preventScrollOnBrowserFocus,
      sourceEvent
    });
    this.previousCellFocusParams = focusEventParams;
  }
  isCellFocused(cellPosition) {
    if (this.focusedCell == null) {
      return false;
    }
    return _areCellsEqual(cellPosition, this.focusedCell);
  }
  isHeaderWrapperFocused(headerCtrl) {
    if (this.focusedHeader == null) {
      return false;
    }
    const {
      column: column2,
      rowCtrl: { rowIndex: headerRowIndex, pinned }
    } = headerCtrl;
    const { column: focusedColumn, headerRowIndex: focusedHeaderRowIndex } = this.focusedHeader;
    return column2 === focusedColumn && headerRowIndex === focusedHeaderRowIndex && pinned == focusedColumn.getPinned();
  }
  focusHeaderPosition(params) {
    this.setFocusRecovered();
    if (_isHeaderFocusSuppressed(this.beans)) {
      return false;
    }
    const { direction, fromTab, allowUserOverride, event, fromCell, rowWithoutSpanValue, scroll = true } = params;
    let { headerPosition } = params;
    if (fromCell && this.filterManager?.isAdvFilterHeaderActive()) {
      return this.focusAdvancedFilter(headerPosition);
    }
    if (allowUserOverride) {
      const currentPosition = this.focusedHeader;
      const headerRowCount = getFocusHeaderRowCount(this.beans);
      if (fromTab) {
        const userFunc = this.gos.getCallback("tabToNextHeader");
        if (userFunc) {
          headerPosition = this.getHeaderPositionFromUserFunc({
            userFunc,
            direction,
            currentPosition,
            headerPosition,
            headerRowCount
          });
        }
      } else {
        const userFunc = this.gos.getCallback("navigateToNextHeader");
        if (userFunc && event) {
          const params2 = {
            key: event.key,
            previousHeaderPosition: currentPosition,
            nextHeaderPosition: headerPosition,
            headerRowCount,
            event
          };
          headerPosition = userFunc(params2);
        }
      }
    }
    if (!headerPosition) {
      return false;
    }
    return this.focusProvidedHeaderPosition({
      headerPosition,
      direction,
      event,
      fromCell,
      rowWithoutSpanValue,
      scroll
    });
  }
  focusHeaderPositionFromUserFunc(params) {
    if (_isHeaderFocusSuppressed(this.beans)) {
      return false;
    }
    const { userFunc, headerPosition, direction, event } = params;
    const currentPosition = this.focusedHeader;
    const headerRowCount = getFocusHeaderRowCount(this.beans);
    const newHeaderPosition = this.getHeaderPositionFromUserFunc({
      userFunc,
      direction,
      currentPosition,
      headerPosition,
      headerRowCount
    });
    return !!newHeaderPosition && this.focusProvidedHeaderPosition({
      headerPosition: newHeaderPosition,
      direction,
      event
    });
  }
  getHeaderPositionFromUserFunc(params) {
    const { userFunc, direction, currentPosition, headerPosition, headerRowCount } = params;
    const userFuncParams = {
      backwards: direction === "Before",
      previousHeaderPosition: currentPosition,
      nextHeaderPosition: headerPosition,
      headerRowCount
    };
    const userResult = userFunc(userFuncParams);
    if (userResult === true) {
      return currentPosition;
    }
    if (userResult === false) {
      return null;
    }
    return userResult;
  }
  focusProvidedHeaderPosition(params) {
    const { headerPosition, direction, fromCell, rowWithoutSpanValue, event, scroll = true } = params;
    const { column: column2, headerRowIndex } = headerPosition;
    const { filterManager, ctrlsSvc, headerNavigation } = this.beans;
    if (this.focusedHeader && isHeaderPositionEqual(params.headerPosition, this.focusedHeader)) {
      return false;
    }
    if (headerRowIndex === -1) {
      if (filterManager?.isAdvFilterHeaderActive()) {
        return this.focusAdvancedFilter(headerPosition);
      }
      return this.focusGridView({ column: column2, event });
    }
    if (scroll) {
      headerNavigation?.scrollToColumn(column2, direction);
    }
    const headerRowContainerCtrl = ctrlsSvc.getHeaderRowContainerCtrl(column2.getPinned());
    const focusSuccess = headerRowContainerCtrl?.focusHeader(headerPosition.headerRowIndex, column2, event) || false;
    if (headerNavigation && focusSuccess && (rowWithoutSpanValue != null || fromCell)) {
      headerNavigation.currentHeaderRowWithoutSpan = rowWithoutSpanValue ?? -1;
    }
    return focusSuccess;
  }
  focusFirstHeader() {
    if (this.overlays?.isExclusive() && this.focusOverlay()) {
      return true;
    }
    const firstColumn = this.visibleCols.allCols[0];
    if (!firstColumn) {
      return false;
    }
    const headerPosition = getHeaderIndexToFocus(this.beans, firstColumn, 0);
    return this.focusHeaderPosition({
      headerPosition,
      rowWithoutSpanValue: 0
    });
  }
  focusLastHeader(event) {
    if (this.overlays?.isExclusive() && this.focusOverlay(true)) {
      return true;
    }
    const headerRowIndex = getFocusHeaderRowCount(this.beans) - 1;
    const column2 = _last(this.visibleCols.allCols);
    return this.focusHeaderPosition({
      headerPosition: { headerRowIndex, column: column2 },
      rowWithoutSpanValue: -1,
      event
    });
  }
  focusPreviousFromFirstCell(event) {
    if (this.filterManager?.isAdvFilterHeaderActive()) {
      return this.focusAdvancedFilter(null);
    }
    return this.focusLastHeader(event);
  }
  isAnyCellFocused() {
    return !!this.focusedCell;
  }
  isRowFocused(rowIndex, rowPinnedType) {
    if (this.focusedCell == null) {
      return false;
    }
    return this.focusedCell.rowIndex === rowIndex && this.focusedCell.rowPinned === _makeNull(rowPinnedType);
  }
  focusOverlay(backwards) {
    const overlayGui = this.overlays?.isVisible() && this.overlays.eWrapper?.getGui();
    return !!overlayGui && _focusInto(overlayGui, backwards);
  }
  focusGridView(params) {
    const { backwards = false, canFocusOverlay = true, event } = params;
    if (this.overlays?.isExclusive()) {
      return canFocusOverlay && this.focusOverlay(backwards);
    }
    if (_isCellFocusSuppressed(this.beans)) {
      if (backwards) {
        if (!_isHeaderFocusSuppressed(this.beans)) {
          return this.focusLastHeader();
        }
      }
      if (canFocusOverlay && this.focusOverlay(backwards)) {
        return true;
      }
      if (backwards) {
        return false;
      }
      return _focusNextGridCoreContainer(this.beans, backwards);
    }
    const nextRow = backwards ? _getLastRow(this.beans) : _getFirstRow(this.beans);
    if (nextRow) {
      const column2 = params.column ?? this.focusedHeader?.column;
      const { rowIndex, rowPinned } = nextRow;
      const rowNode = _getRowNode(this.beans, nextRow);
      if (!column2 || !rowNode || rowIndex == null) {
        return false;
      }
      if (column2.isSuppressNavigable(rowNode)) {
        const isRtl = this.gos.get("enableRtl");
        let key2;
        if (!event || event.key === KeyCode.TAB) {
          key2 = isRtl ? KeyCode.LEFT : KeyCode.RIGHT;
        } else {
          key2 = event.key;
        }
        this.beans.navigation?.navigateToNextCell(
          null,
          key2,
          { rowIndex, column: column2, rowPinned: rowPinned || null },
          true
        );
        return true;
      }
      this.navigation?.ensureCellVisible({ rowIndex, column: column2, rowPinned });
      if (backwards) {
        const rowCtrl = this.rowRenderer.getRowByPosition(nextRow);
        if (rowCtrl?.isFullWidth() && this.navigation?.tryToFocusFullWidthRow(nextRow, backwards)) {
          return true;
        }
      }
      this.setFocusedCell({
        rowIndex,
        column: column2,
        rowPinned: _makeNull(rowPinned),
        forceBrowserFocus: true
      });
      this.beans.rangeSvc?.setRangeToCell({ rowIndex, rowPinned, column: column2 });
      return true;
    }
    if (canFocusOverlay && this.focusOverlay(backwards)) {
      return true;
    }
    if (backwards && this.focusLastHeader()) {
      return true;
    }
    return false;
  }
  focusAdvancedFilter(position) {
    this.advFilterFocusColumn = position?.column;
    return this.beans.advancedFilter?.getCtrl().focusHeaderComp() ?? false;
  }
  focusNextFromAdvancedFilter(backwards, forceFirstColumn) {
    const column2 = (forceFirstColumn ? void 0 : this.advFilterFocusColumn) ?? this.visibleCols.allCols?.[0];
    if (backwards) {
      return this.focusHeaderPosition({
        headerPosition: {
          column: column2,
          headerRowIndex: getFocusHeaderRowCount(this.beans) - 1
        }
      });
    } else {
      return this.focusGridView({ column: column2 });
    }
  }
  clearAdvancedFilterColumn() {
    this.advFilterFocusColumn = void 0;
  }
};
var ScrollVisibleService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "scrollVisibleSvc";
  }
  wireBeans(beans) {
    this.ctrlsSvc = beans.ctrlsSvc;
    this.colAnimation = beans.colAnimation;
  }
  postConstruct() {
    this.horizontalScrollShowing = this.gos.get("alwaysShowHorizontalScroll") === true;
    this.verticalScrollShowing = this.gos.get("alwaysShowVerticalScroll") === true;
    this.getScrollbarWidth();
    this.addManagedEventListeners({
      displayedColumnsChanged: this.updateScrollVisible.bind(this),
      displayedColumnsWidthChanged: this.updateScrollVisible.bind(this)
    });
  }
  updateScrollVisible() {
    const { colAnimation } = this;
    if (colAnimation?.isActive()) {
      colAnimation.executeLaterVMTurn(() => {
        colAnimation.executeLaterVMTurn(() => this.updateScrollVisibleImpl());
      });
    } else {
      this.updateScrollVisibleImpl();
    }
  }
  updateScrollVisibleImpl() {
    const centerRowCtrl = this.ctrlsSvc.get("center");
    if (!centerRowCtrl || this.colAnimation?.isActive()) {
      return;
    }
    const params = {
      horizontalScrollShowing: centerRowCtrl.isHorizontalScrollShowing(),
      verticalScrollShowing: this.verticalScrollShowing
    };
    this.setScrollsVisible(params);
    this.updateScrollGap();
  }
  updateScrollGap() {
    const centerRowCtrl = this.ctrlsSvc.get("center");
    const horizontalGap = centerRowCtrl.hasHorizontalScrollGap();
    const verticalGap = centerRowCtrl.hasVerticalScrollGap();
    const atLeastOneDifferent = this.horizontalScrollGap !== horizontalGap || this.verticalScrollGap !== verticalGap;
    if (atLeastOneDifferent) {
      this.horizontalScrollGap = horizontalGap;
      this.verticalScrollGap = verticalGap;
      this.eventSvc.dispatchEvent({
        type: "scrollGapChanged"
      });
    }
  }
  setScrollsVisible(params) {
    const atLeastOneDifferent = this.horizontalScrollShowing !== params.horizontalScrollShowing || this.verticalScrollShowing !== params.verticalScrollShowing;
    if (atLeastOneDifferent) {
      this.horizontalScrollShowing = params.horizontalScrollShowing;
      this.verticalScrollShowing = params.verticalScrollShowing;
      this.eventSvc.dispatchEvent({
        type: "scrollVisibilityChanged"
      });
    }
  }
  // the user might be using some non-standard scrollbar, eg a scrollbar that has zero
  // width and overlays (like the Safari scrollbar, but presented in Chrome). so we
  // allow the user to provide the scroll width before we work it out.
  getScrollbarWidth() {
    if (this.scrollbarWidth == null) {
      const gridOptionsScrollbarWidth = this.gos.get("scrollbarWidth");
      const useGridOptions = typeof gridOptionsScrollbarWidth === "number" && gridOptionsScrollbarWidth >= 0;
      const scrollbarWidth = useGridOptions ? gridOptionsScrollbarWidth : _getScrollbarWidth();
      if (scrollbarWidth != null) {
        this.scrollbarWidth = scrollbarWidth;
        this.eventSvc.dispatchEvent({
          type: "scrollbarWidthChanged"
        });
      }
    }
    return this.scrollbarWidth;
  }
};
var GridDestroyService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "gridDestroySvc";
    this.destroyCalled = false;
  }
  destroy() {
    if (this.destroyCalled) {
      return;
    }
    const { stateSvc, ctrlsSvc, context } = this.beans;
    this.eventSvc.dispatchEvent({
      type: "gridPreDestroyed",
      state: stateSvc?.getState() ?? {}
    });
    this.destroyCalled = true;
    ctrlsSvc.get("gridCtrl")?.destroyGridUi();
    context.destroy();
    super.destroy();
  }
};
var ALWAYS_SYNC_GLOBAL_EVENTS = /* @__PURE__ */ new Set(["gridPreDestroyed", "fillStart", "pasteStart"]);
var _PUBLIC_EVENTS = [
  "columnEverythingChanged",
  "newColumnsLoaded",
  "columnPivotModeChanged",
  "pivotMaxColumnsExceeded",
  "columnRowGroupChanged",
  "expandOrCollapseAll",
  "columnPivotChanged",
  "gridColumnsChanged",
  "columnValueChanged",
  "columnMoved",
  "columnVisible",
  "columnPinned",
  "columnGroupOpened",
  "columnResized",
  "displayedColumnsChanged",
  "virtualColumnsChanged",
  "columnHeaderMouseOver",
  "columnHeaderMouseLeave",
  "columnHeaderClicked",
  "columnHeaderContextMenu",
  "asyncTransactionsFlushed",
  "rowGroupOpened",
  "rowDataUpdated",
  "pinnedRowDataChanged",
  "pinnedRowsChanged",
  "rangeSelectionChanged",
  "cellSelectionChanged",
  "chartCreated",
  "chartRangeSelectionChanged",
  "chartOptionsChanged",
  "chartDestroyed",
  "toolPanelVisibleChanged",
  "toolPanelSizeChanged",
  "modelUpdated",
  "cutStart",
  "cutEnd",
  "pasteStart",
  "pasteEnd",
  "fillStart",
  "fillEnd",
  "cellSelectionDeleteStart",
  "cellSelectionDeleteEnd",
  "rangeDeleteStart",
  "rangeDeleteEnd",
  "undoStarted",
  "undoEnded",
  "redoStarted",
  "redoEnded",
  "cellClicked",
  "cellDoubleClicked",
  "cellMouseDown",
  "cellContextMenu",
  "cellValueChanged",
  "cellEditRequest",
  "rowValueChanged",
  "headerFocused",
  "cellFocused",
  "rowSelected",
  "selectionChanged",
  "tooltipShow",
  "tooltipHide",
  "cellKeyDown",
  "cellMouseOver",
  "cellMouseOut",
  "filterChanged",
  "filterModified",
  "filterUiChanged",
  "filterOpened",
  "floatingFilterUiChanged",
  "advancedFilterBuilderVisibleChanged",
  "sortChanged",
  "virtualRowRemoved",
  "rowClicked",
  "rowDoubleClicked",
  "gridReady",
  "gridPreDestroyed",
  "gridSizeChanged",
  "viewportChanged",
  "firstDataRendered",
  "dragStarted",
  "dragStopped",
  "dragCancelled",
  "rowEditingStarted",
  "rowEditingStopped",
  "cellEditingStarted",
  "cellEditingStopped",
  "bodyScroll",
  "bodyScrollEnd",
  "paginationChanged",
  "componentStateChanged",
  "storeRefreshed",
  "stateUpdated",
  "columnMenuVisibleChanged",
  "contextMenuVisibleChanged",
  "rowDragEnter",
  "rowDragMove",
  "rowDragLeave",
  "rowDragEnd",
  "rowDragCancel",
  "findChanged",
  "rowResizeStarted",
  "rowResizeEnded",
  "columnsReset",
  "bulkEditingStarted",
  "bulkEditingStopped",
  "batchEditingStarted",
  "batchEditingStopped"
];
var _PUBLIC_EVENT_HANDLERS_MAP = _PUBLIC_EVENTS.reduce(
  (mem, ev) => {
    mem[ev] = _getCallbackForEvent(ev);
    return mem;
  },
  {}
);
var makeIconParams = (dataRefSuffix, classSuffix) => ({
  tag: "span",
  ref: `eSort${dataRefSuffix}`,
  cls: `ag-sort-indicator-icon ag-sort-${classSuffix} ag-hidden`,
  attrs: { "aria-hidden": "true" }
});
var SortIndicatorElement = {
  tag: "span",
  cls: "ag-sort-indicator-container",
  children: [
    makeIconParams("Order", "order"),
    makeIconParams("Asc", "ascending-icon"),
    makeIconParams("Desc", "descending-icon"),
    makeIconParams("Mixed", "mixed-icon"),
    makeIconParams("None", "none-icon")
  ]
};
var SortIndicatorComp = class extends Component {
  constructor(skipTemplate) {
    super();
    this.eSortOrder = RefPlaceholder;
    this.eSortAsc = RefPlaceholder;
    this.eSortDesc = RefPlaceholder;
    this.eSortMixed = RefPlaceholder;
    this.eSortNone = RefPlaceholder;
    if (!skipTemplate) {
      this.setTemplate(SortIndicatorElement);
    }
  }
  attachCustomElements(eSortOrder, eSortAsc, eSortDesc, eSortMixed, eSortNone) {
    this.eSortOrder = eSortOrder;
    this.eSortAsc = eSortAsc;
    this.eSortDesc = eSortDesc;
    this.eSortMixed = eSortMixed;
    this.eSortNone = eSortNone;
  }
  setupSort(column2, suppressOrder = false) {
    this.column = column2;
    this.suppressOrder = suppressOrder;
    this.setupMultiSortIndicator();
    if (!column2.isSortable() && !column2.getColDef().showRowGroup) {
      return;
    }
    this.addInIcon("sortAscending", this.eSortAsc, column2);
    this.addInIcon("sortDescending", this.eSortDesc, column2);
    this.addInIcon("sortUnSort", this.eSortNone, column2);
    const updateIcons = this.updateIcons.bind(this);
    const sortUpdated = this.onSortChanged.bind(this);
    this.addManagedPropertyListener("unSortIcon", updateIcons);
    this.addManagedEventListeners({
      newColumnsLoaded: updateIcons,
      // Watch global events, as row group columns can effect their display column.
      sortChanged: sortUpdated,
      // when grouping changes so can sort indexes and icons
      columnRowGroupChanged: sortUpdated
    });
    this.onSortChanged();
  }
  addInIcon(iconName, eParent, column2) {
    if (eParent == null) {
      return;
    }
    const eIcon = _createIconNoSpan(iconName, this.beans, column2);
    if (eIcon) {
      eParent.appendChild(eIcon);
    }
  }
  onSortChanged() {
    this.updateIcons();
    if (!this.suppressOrder) {
      this.updateSortOrder();
    }
  }
  updateIcons() {
    const { eSortAsc, eSortDesc, eSortNone, column: column2, gos, beans } = this;
    const sortDirection = beans.sortSvc.getDisplaySortForColumn(column2);
    if (eSortAsc) {
      const isAscending = sortDirection === "asc";
      _setDisplayed(eSortAsc, isAscending, { skipAriaHidden: true });
    }
    if (eSortDesc) {
      const isDescending = sortDirection === "desc";
      _setDisplayed(eSortDesc, isDescending, { skipAriaHidden: true });
    }
    if (eSortNone) {
      const alwaysHideNoSort = !column2.getColDef().unSortIcon && !gos.get("unSortIcon");
      const isNone = sortDirection === null || sortDirection === void 0;
      _setDisplayed(eSortNone, !alwaysHideNoSort && isNone, { skipAriaHidden: true });
    }
  }
  setupMultiSortIndicator() {
    const { eSortMixed, column: column2, gos } = this;
    this.addInIcon("sortUnSort", eSortMixed, column2);
    const isColumnShowingRowGroup = column2.getColDef().showRowGroup;
    const areGroupsCoupled = _isColumnsSortingCoupledToGroup(gos);
    if (areGroupsCoupled && isColumnShowingRowGroup) {
      this.addManagedEventListeners({
        // Watch global events, as row group columns can effect their display column.
        sortChanged: this.updateMultiSortIndicator.bind(this),
        // when grouping changes so can sort indexes and icons
        columnRowGroupChanged: this.updateMultiSortIndicator.bind(this)
      });
      this.updateMultiSortIndicator();
    }
  }
  updateMultiSortIndicator() {
    const { eSortMixed, beans, column: column2 } = this;
    if (eSortMixed) {
      const isMixedSort = beans.sortSvc.getDisplaySortForColumn(column2) === "mixed";
      _setDisplayed(eSortMixed, isMixedSort, { skipAriaHidden: true });
    }
  }
  // we listen here for global sort events, NOT column sort events, as we want to do this
  // when sorting has been set on all column (if we listened just for our col (where we
  // set the asc / desc icons) then it's possible other cols are yet to get their sorting state.
  updateSortOrder() {
    const {
      eSortOrder,
      column: column2,
      beans: { sortSvc }
    } = this;
    if (!eSortOrder) {
      return;
    }
    const allColumnsWithSorting = sortSvc.getColumnsWithSortingOrdered();
    const indexThisCol = sortSvc.getDisplaySortIndexForColumn(column2) ?? -1;
    const moreThanOneColSorting = allColumnsWithSorting.some(
      (col) => sortSvc.getDisplaySortIndexForColumn(col) ?? -1 >= 1
    );
    const showIndex = indexThisCol >= 0 && moreThanOneColSorting;
    _setDisplayed(eSortOrder, showIndex, { skipAriaHidden: true });
    if (indexThisCol >= 0) {
      eSortOrder.textContent = (indexThisCol + 1).toString();
    } else {
      _clearElement(eSortOrder);
    }
  }
};
var SortIndicatorSelector = {
  selector: "AG-SORT-INDICATOR",
  component: SortIndicatorComp
};
var DEFAULT_SORTING_ORDER = ["asc", "desc", null];
var SortService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "sortSvc";
  }
  progressSort(column2, multiSort, source2) {
    const nextDirection = this.getNextSortDirection(column2);
    this.setSortForColumn(column2, nextDirection, multiSort, source2);
  }
  progressSortFromEvent(column2, event) {
    const sortUsingCtrl = this.gos.get("multiSortKey") === "ctrl";
    const multiSort = sortUsingCtrl ? event.ctrlKey || event.metaKey : event.shiftKey;
    this.progressSort(column2, multiSort, "uiColumnSorted");
  }
  setSortForColumn(column2, sort, multiSort, source2) {
    if (sort !== "asc" && sort !== "desc") {
      sort = null;
    }
    const { gos, showRowGroupCols } = this.beans;
    const isColumnsSortingCoupledToGroup = _isColumnsSortingCoupledToGroup(gos);
    let columnsToUpdate = [column2];
    if (isColumnsSortingCoupledToGroup) {
      if (column2.getColDef().showRowGroup) {
        const rowGroupColumns = showRowGroupCols?.getSourceColumnsForGroupColumn?.(column2);
        const sortableRowGroupColumns = rowGroupColumns?.filter((col) => col.isSortable());
        if (sortableRowGroupColumns) {
          columnsToUpdate = [column2, ...sortableRowGroupColumns];
        }
      }
    }
    for (const col of columnsToUpdate) {
      this.setColSort(col, sort, source2);
    }
    const doingMultiSort = (multiSort || gos.get("alwaysMultiSort")) && !gos.get("suppressMultiSort");
    const updatedColumns = [];
    if (!doingMultiSort) {
      const clearedColumns = this.clearSortBarTheseColumns(columnsToUpdate, source2);
      updatedColumns.push(...clearedColumns);
    }
    this.updateSortIndex(column2);
    updatedColumns.push(...columnsToUpdate);
    this.dispatchSortChangedEvents(source2, updatedColumns);
  }
  updateSortIndex(lastColToChange) {
    const { gos, colModel, showRowGroupCols } = this.beans;
    const isCoupled = _isColumnsSortingCoupledToGroup(gos);
    const groupParent = showRowGroupCols?.getShowRowGroupCol(lastColToChange.getId());
    const lastSortIndexCol = isCoupled ? groupParent || lastColToChange : lastColToChange;
    const allSortedCols = this.getColumnsWithSortingOrdered();
    colModel.forAllCols((col) => this.setColSortIndex(col, null));
    const allSortedColsWithoutChangesOrGroups = allSortedCols.filter((col) => {
      if (isCoupled && col.getColDef().showRowGroup) {
        return false;
      }
      return col !== lastSortIndexCol;
    });
    const sortedColsWithIndices = lastSortIndexCol.getSort() ? [...allSortedColsWithoutChangesOrGroups, lastSortIndexCol] : allSortedColsWithoutChangesOrGroups;
    sortedColsWithIndices.forEach((col, idx) => this.setColSortIndex(col, idx));
  }
  // gets called by API, so if data changes, use can call this, which will end up
  // working out the sort order again of the rows.
  onSortChanged(source2, columns2) {
    this.dispatchSortChangedEvents(source2, columns2);
  }
  isSortActive() {
    let isSorting = false;
    this.beans.colModel.forAllCols((col) => {
      if (col.getSort()) {
        isSorting = true;
      }
    });
    return isSorting;
  }
  dispatchSortChangedEvents(source2, columns2) {
    const event = {
      type: "sortChanged",
      source: source2
    };
    if (columns2) {
      event.columns = columns2;
    }
    this.eventSvc.dispatchEvent(event);
  }
  clearSortBarTheseColumns(columnsToSkip, source2) {
    const clearedColumns = [];
    this.beans.colModel.forAllCols((columnToClear) => {
      if (!columnsToSkip.includes(columnToClear)) {
        if (columnToClear.getSort()) {
          clearedColumns.push(columnToClear);
        }
        this.setColSort(columnToClear, void 0, source2);
      }
    });
    return clearedColumns;
  }
  getNextSortDirection(column2) {
    const sortingOrder = column2.getColDef().sortingOrder ?? this.gos.get("sortingOrder") ?? DEFAULT_SORTING_ORDER;
    const currentIndex = sortingOrder.indexOf(column2.getSort());
    const notInArray = currentIndex < 0;
    const lastItemInArray = currentIndex == sortingOrder.length - 1;
    return notInArray || lastItemInArray ? sortingOrder[0] : sortingOrder[currentIndex + 1];
  }
  /**
   * @returns a map of sort indexes for every sorted column, if groups sort primaries then they will have equivalent indices
   */
  getIndexedSortMap() {
    const { gos, colModel, showRowGroupCols, rowGroupColsSvc } = this.beans;
    let allSortedCols = [];
    colModel.forAllCols((col) => {
      if (col.getSort()) {
        allSortedCols.push(col);
      }
    });
    if (colModel.isPivotMode()) {
      const isSortingLinked = _isColumnsSortingCoupledToGroup(gos);
      allSortedCols = allSortedCols.filter((col) => {
        const isAggregated = !!col.getAggFunc();
        const isSecondary = !col.isPrimary();
        const isGroup = isSortingLinked ? showRowGroupCols?.getShowRowGroupCol(col.getId()) : col.getColDef().showRowGroup;
        return isAggregated || isSecondary || isGroup;
      });
    }
    const sortedRowGroupCols = rowGroupColsSvc?.columns.filter((col) => !!col.getSort()) ?? [];
    const allColsIndexes = {};
    allSortedCols.forEach((col, index) => allColsIndexes[col.getId()] = index);
    allSortedCols.sort((a2, b) => {
      const iA = a2.getSortIndex();
      const iB = b.getSortIndex();
      if (iA != null && iB != null) {
        return iA - iB;
      } else if (iA == null && iB == null) {
        const posA = allColsIndexes[a2.getId()];
        const posB = allColsIndexes[b.getId()];
        return posA > posB ? 1 : -1;
      } else if (iB == null) {
        return -1;
      } else {
        return 1;
      }
    });
    const isSortLinked = _isColumnsSortingCoupledToGroup(gos) && !!sortedRowGroupCols.length;
    if (isSortLinked) {
      allSortedCols = [
        ...new Set(
          // if linked sorting, replace all columns with the display group column for index purposes, and ensure uniqueness
          allSortedCols.map((col) => showRowGroupCols?.getShowRowGroupCol(col.getId()) ?? col)
        )
      ];
    }
    const indexMap = /* @__PURE__ */ new Map();
    allSortedCols.forEach((col, idx) => indexMap.set(col, idx));
    if (isSortLinked) {
      for (const col of sortedRowGroupCols) {
        const groupDisplayCol = showRowGroupCols.getShowRowGroupCol(col.getId());
        indexMap.set(col, indexMap.get(groupDisplayCol));
      }
    }
    return indexMap;
  }
  getColumnsWithSortingOrdered() {
    return [...this.getIndexedSortMap().entries()].sort(([, idx1], [, idx2]) => idx1 - idx2).map(([col]) => col);
  }
  // used by server side row models, to sent sort to server
  getSortModel() {
    return this.getColumnsWithSortingOrdered().filter((column2) => column2.getSort()).map((column2) => ({
      sort: column2.getSort(),
      colId: column2.getId()
    }));
  }
  getSortOptions() {
    return this.getColumnsWithSortingOrdered().filter((column2) => column2.getSort()).map((column2) => ({
      sort: column2.getSort(),
      column: column2
    }));
  }
  canColumnDisplayMixedSort(column2) {
    const isColumnSortCouplingActive = _isColumnsSortingCoupledToGroup(this.gos);
    const isGroupDisplayColumn = !!column2.getColDef().showRowGroup;
    return isColumnSortCouplingActive && isGroupDisplayColumn;
  }
  getDisplaySortForColumn(column2) {
    const linkedColumns = this.beans.showRowGroupCols?.getSourceColumnsForGroupColumn(column2);
    if (!this.canColumnDisplayMixedSort(column2) || !linkedColumns?.length) {
      return column2.getSort();
    }
    const columnHasUniqueData = column2.getColDef().field != null || !!column2.getColDef().valueGetter;
    const sortableColumns = columnHasUniqueData ? [column2, ...linkedColumns] : linkedColumns;
    const firstSort = sortableColumns[0].getSort();
    const allMatch = sortableColumns.every((col) => col.getSort() == firstSort);
    if (!allMatch) {
      return "mixed";
    }
    return firstSort;
  }
  getDisplaySortIndexForColumn(column2) {
    return this.getIndexedSortMap().get(column2);
  }
  setupHeader(comp, column2, clickElement) {
    let lastMovingChanged = 0;
    comp.addManagedListeners(column2, {
      movingChanged: () => {
        lastMovingChanged = Date.now();
      }
    });
    if (clickElement) {
      comp.addManagedElementListeners(clickElement, {
        click: (event) => {
          const moving = column2.isMoving();
          const nowTime = Date.now();
          const movedRecently = nowTime - lastMovingChanged < 50;
          const columnMoving = moving || movedRecently;
          if (!columnMoving) {
            this.progressSortFromEvent(column2, event);
          }
        }
      });
    }
    const onSortingChanged = () => {
      const sort = column2.getSort();
      comp.toggleCss("ag-header-cell-sorted-asc", sort === "asc");
      comp.toggleCss("ag-header-cell-sorted-desc", sort === "desc");
      comp.toggleCss("ag-header-cell-sorted-none", !sort);
      if (column2.getColDef().showRowGroup) {
        const sourceColumns = this.beans.showRowGroupCols?.getSourceColumnsForGroupColumn(column2);
        const sortDirectionsMatch = sourceColumns?.every(
          (sourceCol) => column2.getSort() == sourceCol.getSort()
        );
        const isMultiSorting = !sortDirectionsMatch;
        comp.toggleCss("ag-header-cell-sorted-mixed", isMultiSorting);
      }
    };
    comp.addManagedEventListeners({
      sortChanged: onSortingChanged,
      columnRowGroupChanged: onSortingChanged
    });
  }
  initCol(column2) {
    const { sort, initialSort, sortIndex, initialSortIndex } = column2.colDef;
    if (sort !== void 0) {
      if (sort === "asc" || sort === "desc") {
        column2.sort = sort;
      }
    } else if (initialSort === "asc" || initialSort === "desc") {
      column2.sort = initialSort;
    }
    if (sortIndex !== void 0) {
      if (sortIndex !== null) {
        column2.sortIndex = sortIndex;
      }
    } else if (initialSortIndex !== null) {
      column2.sortIndex = initialSortIndex;
    }
  }
  updateColSort(column2, sort, source2) {
    if (sort !== void 0) {
      if (sort === "desc" || sort === "asc") {
        this.setColSort(column2, sort, source2);
      } else {
        this.setColSort(column2, void 0, source2);
      }
    }
  }
  setColSort(column2, sort, source2) {
    if (column2.sort !== sort) {
      column2.sort = sort;
      column2.dispatchColEvent("sortChanged", source2);
    }
    column2.dispatchStateUpdatedEvent("sort");
  }
  setColSortIndex(column2, sortOrder) {
    column2.sortIndex = sortOrder;
    column2.dispatchStateUpdatedEvent("sortIndex");
  }
  createSortIndicator(skipTemplate) {
    return new SortIndicatorComp(skipTemplate);
  }
  getSortIndicatorSelector() {
    return SortIndicatorSelector;
  }
};
var USER_COMP_MODULES = {
  agSetColumnFilter: "SetFilter",
  agSetColumnFloatingFilter: "SetFilter",
  agMultiColumnFilter: "MultiFilter",
  agMultiColumnFloatingFilter: "MultiFilter",
  agGroupColumnFilter: "GroupFilter",
  agGroupColumnFloatingFilter: "GroupFilter",
  agGroupCellRenderer: "GroupCellRenderer",
  agGroupRowRenderer: "GroupCellRenderer",
  agRichSelect: "RichSelect",
  agRichSelectCellEditor: "RichSelect",
  agDetailCellRenderer: "SharedMasterDetail",
  agSparklineCellRenderer: "Sparklines",
  agDragAndDropImage: "SharedDragAndDrop",
  agColumnHeader: "ColumnHeaderComp",
  agColumnGroupHeader: "ColumnGroupHeaderComp",
  agSortIndicator: "Sort",
  agAnimateShowChangeCellRenderer: "HighlightChanges",
  agAnimateSlideCellRenderer: "HighlightChanges",
  agLoadingCellRenderer: "LoadingCellRenderer",
  agSkeletonCellRenderer: "SkeletonCellRenderer",
  agCheckboxCellRenderer: "CheckboxCellRenderer",
  agLoadingOverlay: "Overlay",
  agNoRowsOverlay: "Overlay",
  agTooltipComponent: "Tooltip",
  agReadOnlyFloatingFilter: "CustomFilter",
  agTextColumnFilter: "TextFilter",
  agNumberColumnFilter: "NumberFilter",
  agDateColumnFilter: "DateFilter",
  agDateInput: "DateFilter",
  agTextColumnFloatingFilter: "TextFilter",
  agNumberColumnFloatingFilter: "NumberFilter",
  agDateColumnFloatingFilter: "DateFilter",
  agCellEditor: "TextEditor",
  agSelectCellEditor: "SelectEditor",
  agTextCellEditor: "TextEditor",
  agNumberCellEditor: "NumberEditor",
  agDateCellEditor: "DateEditor",
  agDateStringCellEditor: "DateEditor",
  agCheckboxCellEditor: "CheckboxEditor",
  agLargeTextCellEditor: "LargeTextEditor",
  agMenuItem: "MenuItem",
  agColumnsToolPanel: "ColumnsToolPanel",
  agFiltersToolPanel: "FiltersToolPanel",
  agNewFiltersToolPanel: "NewFiltersToolPanel",
  agAggregationComponent: "StatusBar",
  agSelectedRowCountComponent: "StatusBar",
  agTotalRowCountComponent: "StatusBar",
  agFilteredRowCountComponent: "StatusBar",
  agTotalAndFilteredRowCountComponent: "StatusBar",
  agFindCellRenderer: "Find"
};
function quote(s) {
  return `"${s}"`;
}
var COLUMN_DEFINITION_DEPRECATIONS = () => ({
  checkboxSelection: { version: "32.2", message: "Use `rowSelection.checkboxes` in `GridOptions` instead." },
  headerCheckboxSelection: {
    version: "32.2",
    message: "Use `rowSelection.headerCheckbox = true` in `GridOptions` instead."
  },
  headerCheckboxSelectionFilteredOnly: {
    version: "32.2",
    message: 'Use `rowSelection.selectAll = "filtered"` in `GridOptions` instead.'
  },
  headerCheckboxSelectionCurrentPageOnly: {
    version: "32.2",
    message: 'Use `rowSelection.selectAll = "currentPage"` in `GridOptions` instead.'
  },
  showDisabledCheckboxes: {
    version: "32.2",
    message: "Use `rowSelection.hideDisabledCheckboxes = true` in `GridOptions` instead."
  },
  rowGroupingHierarchy: {
    version: "34.3",
    message: "Use `colDef.groupHierarchy` instead."
  }
});
var COLUMN_DEFINITION_MOD_VALIDATIONS = {
  aggFunc: "SharedAggregation",
  autoHeight: "RowAutoHeight",
  cellClass: "CellStyle",
  cellClassRules: "CellStyle",
  cellEditor: ({ cellEditor, editable }) => {
    if (!editable) {
      return null;
    }
    if (typeof cellEditor === "string") {
      return USER_COMP_MODULES[cellEditor] ?? "CustomEditor";
    }
    return "CustomEditor";
  },
  cellRenderer: ({ cellRenderer }) => {
    if (typeof cellRenderer !== "string") {
      return null;
    }
    return USER_COMP_MODULES[cellRenderer];
  },
  cellStyle: "CellStyle",
  columnChooserParams: "ColumnMenu",
  contextMenuItems: "ContextMenu",
  dndSource: "DragAndDrop",
  dndSourceOnRowDrag: "DragAndDrop",
  editable: ({ editable, cellEditor }) => {
    if (editable && !cellEditor) {
      return "TextEditor";
    }
    return null;
  },
  enableCellChangeFlash: "HighlightChanges",
  enablePivot: "SharedPivot",
  enableRowGroup: "SharedRowGrouping",
  enableValue: "SharedAggregation",
  filter: ({ filter: filter2 }) => {
    if (filter2 && typeof filter2 !== "string" && typeof filter2 !== "boolean") {
      return "CustomFilter";
    }
    if (typeof filter2 === "string") {
      return USER_COMP_MODULES[filter2] ?? "ColumnFilter";
    }
    return "ColumnFilter";
  },
  floatingFilter: "ColumnFilter",
  getQuickFilterText: "QuickFilter",
  headerTooltip: "Tooltip",
  headerTooltipValueGetter: "Tooltip",
  mainMenuItems: "ColumnMenu",
  menuTabs: (options) => {
    const enterpriseMenuTabs = ["columnsMenuTab", "generalMenuTab"];
    if (options.menuTabs?.some((tab2) => enterpriseMenuTabs.includes(tab2))) {
      return "ColumnMenu";
    }
    return null;
  },
  pivot: "SharedPivot",
  pivotIndex: "SharedPivot",
  rowDrag: "RowDrag",
  rowGroup: "SharedRowGrouping",
  rowGroupIndex: "SharedRowGrouping",
  tooltipField: "Tooltip",
  tooltipValueGetter: "Tooltip",
  tooltipComponentSelector: "Tooltip",
  spanRows: "CellSpan",
  groupHierarchy: "SharedRowGrouping"
};
var COLUMN_DEFINITION_VALIDATIONS = () => {
  const validations = {
    autoHeight: {
      supportedRowModels: ["clientSide", "serverSide"],
      validate: (_colDef, { paginationAutoPageSize }) => {
        if (paginationAutoPageSize) {
          return "colDef.autoHeight is not supported with paginationAutoPageSize.";
        }
        return null;
      }
    },
    cellRendererParams: {
      validate: (colDef) => {
        const groupColumn = colDef.rowGroup != null || colDef.rowGroupIndex != null || colDef.cellRenderer === "agGroupCellRenderer";
        if (groupColumn && "checkbox" in colDef.cellRendererParams) {
          return 'Since v33.0, `cellRendererParams.checkbox` has been deprecated. Use `rowSelection.checkboxLocation = "autoGroupColumn"` instead.';
        }
        return null;
      }
    },
    flex: {
      validate: (_options, gridOptions) => {
        if (gridOptions.autoSizeStrategy) {
          return "colDef.flex is not supported with gridOptions.autoSizeStrategy";
        }
        return null;
      }
    },
    headerCheckboxSelection: {
      supportedRowModels: ["clientSide", "serverSide"],
      validate: (_options, { rowSelection }) => rowSelection === "multiple" ? null : "headerCheckboxSelection is only supported with rowSelection=multiple"
    },
    headerCheckboxSelectionCurrentPageOnly: {
      supportedRowModels: ["clientSide"],
      validate: (_options, { rowSelection }) => rowSelection === "multiple" ? null : "headerCheckboxSelectionCurrentPageOnly is only supported with rowSelection=multiple"
    },
    headerCheckboxSelectionFilteredOnly: {
      supportedRowModels: ["clientSide"],
      validate: (_options, { rowSelection }) => rowSelection === "multiple" ? null : "headerCheckboxSelectionFilteredOnly is only supported with rowSelection=multiple"
    },
    headerValueGetter: {
      validate: (_options) => {
        const headerValueGetter = _options.headerValueGetter;
        if (typeof headerValueGetter === "function" || typeof headerValueGetter === "string") {
          return null;
        }
        return "headerValueGetter must be a function or a valid string expression";
      }
    },
    icons: {
      validate: ({ icons }) => {
        if (icons) {
          if (icons["smallDown"]) {
            return _errMsg(262);
          }
          if (icons["smallLeft"]) {
            return _errMsg(263);
          }
          if (icons["smallRight"]) {
            return _errMsg(264);
          }
        }
        return null;
      }
    },
    sortingOrder: {
      validate: (_options) => {
        const sortingOrder = _options.sortingOrder;
        if (Array.isArray(sortingOrder) && sortingOrder.length > 0) {
          const invalidItems = sortingOrder.filter((a2) => !DEFAULT_SORTING_ORDER.includes(a2));
          if (invalidItems.length > 0) {
            return `sortingOrder must be an array with elements from [${DEFAULT_SORTING_ORDER.map(toStringWithNullUndefined).join()}], currently it includes [${invalidItems.map(toStringWithNullUndefined).join()}]`;
          }
        } else if (!Array.isArray(sortingOrder) || sortingOrder.length <= 0) {
          return `sortingOrder must be an array with at least one element, currently it's ${sortingOrder}`;
        }
        return null;
      }
    },
    type: {
      validate: (_options) => {
        const type = _options.type;
        if (type instanceof Array) {
          const invalidArray = type.some((a2) => typeof a2 !== "string");
          if (invalidArray) {
            return "if colDef.type is supplied an array it should be of type 'string[]'";
          }
          return null;
        }
        if (typeof type === "string") {
          return null;
        }
        return "colDef.type should be of type 'string' | 'string[]'";
      }
    },
    rowSpan: {
      validate: (_options, { suppressRowTransform }) => {
        if (!suppressRowTransform) {
          return "colDef.rowSpan requires suppressRowTransform to be enabled.";
        }
        return null;
      }
    },
    spanRows: {
      dependencies: {
        editable: { required: [false, void 0] },
        rowDrag: { required: [false, void 0] },
        colSpan: { required: [void 0] },
        rowSpan: { required: [void 0] }
      },
      validate: (_options, {
        rowSelection,
        cellSelection,
        suppressRowTransform,
        enableCellSpan,
        rowDragEntireRow,
        enableCellTextSelection
      }) => {
        if (typeof rowSelection === "object") {
          if (rowSelection?.mode === "singleRow" && rowSelection?.enableClickSelection) {
            return "colDef.spanRows is not supported with rowSelection.clickSelection";
          }
        }
        if (cellSelection) {
          return "colDef.spanRows is not supported with cellSelection.";
        }
        if (suppressRowTransform) {
          return "colDef.spanRows is not supported with suppressRowTransform.";
        }
        if (!enableCellSpan) {
          return "colDef.spanRows requires enableCellSpan to be enabled.";
        }
        if (rowDragEntireRow) {
          return "colDef.spanRows is not supported with rowDragEntireRow.";
        }
        if (enableCellTextSelection) {
          return "colDef.spanRows is not supported with enableCellTextSelection.";
        }
        return null;
      }
    },
    groupHierarchy: {
      validate(options, { groupHierarchyConfig = {} }, beans) {
        const GROUP_HIERARCHY_PARTS = /* @__PURE__ */ new Set([
          "year",
          "quarter",
          "month",
          "formattedMonth",
          "day",
          "hour",
          "minute",
          "second"
        ]);
        const unrecognisedParts = [];
        for (const part of options.groupHierarchy ?? []) {
          if (typeof part === "object") {
            beans.validation?.validateColDef(part);
            continue;
          }
          if (!GROUP_HIERARCHY_PARTS.has(part) && !(part in groupHierarchyConfig)) {
            unrecognisedParts.push(quote(part));
          }
        }
        if (unrecognisedParts.length > 0) {
          const warning2 = `The following parts of colDef.groupHierarchy are not recognised: ${unrecognisedParts.join(", ")}.`;
          const suggestions = `Choose one of ${[...GROUP_HIERARCHY_PARTS].map(quote).join(", ")}, or define your own parts in gridOptions.groupHierarchyConfig.`;
          return `${warning2}
${suggestions}`;
        }
        return null;
      }
    }
  };
  return validations;
};
var colDefPropertyMap = {
  headerName: void 0,
  columnGroupShow: void 0,
  headerStyle: void 0,
  headerClass: void 0,
  toolPanelClass: void 0,
  headerValueGetter: void 0,
  pivotKeys: void 0,
  groupId: void 0,
  colId: void 0,
  sort: void 0,
  initialSort: void 0,
  field: void 0,
  type: void 0,
  cellDataType: void 0,
  tooltipComponent: void 0,
  tooltipField: void 0,
  headerTooltip: void 0,
  headerTooltipValueGetter: void 0,
  cellClass: void 0,
  showRowGroup: void 0,
  filter: void 0,
  initialAggFunc: void 0,
  defaultAggFunc: void 0,
  aggFunc: void 0,
  pinned: void 0,
  initialPinned: void 0,
  chartDataType: void 0,
  cellAriaRole: void 0,
  cellEditorPopupPosition: void 0,
  headerGroupComponent: void 0,
  headerGroupComponentParams: void 0,
  cellStyle: void 0,
  cellRenderer: void 0,
  cellRendererParams: void 0,
  cellEditor: void 0,
  cellEditorParams: void 0,
  filterParams: void 0,
  pivotValueColumn: void 0,
  headerComponent: void 0,
  headerComponentParams: void 0,
  floatingFilterComponent: void 0,
  floatingFilterComponentParams: void 0,
  tooltipComponentParams: void 0,
  refData: void 0,
  columnChooserParams: void 0,
  children: void 0,
  sortingOrder: void 0,
  allowedAggFuncs: void 0,
  menuTabs: void 0,
  pivotTotalColumnIds: void 0,
  cellClassRules: void 0,
  icons: void 0,
  sortIndex: void 0,
  initialSortIndex: void 0,
  flex: void 0,
  initialFlex: void 0,
  width: void 0,
  initialWidth: void 0,
  minWidth: void 0,
  maxWidth: void 0,
  rowGroupIndex: void 0,
  initialRowGroupIndex: void 0,
  pivotIndex: void 0,
  initialPivotIndex: void 0,
  suppressColumnsToolPanel: void 0,
  suppressFiltersToolPanel: void 0,
  openByDefault: void 0,
  marryChildren: void 0,
  suppressStickyLabel: void 0,
  hide: void 0,
  initialHide: void 0,
  rowGroup: void 0,
  initialRowGroup: void 0,
  pivot: void 0,
  initialPivot: void 0,
  checkboxSelection: void 0,
  showDisabledCheckboxes: void 0,
  headerCheckboxSelection: void 0,
  headerCheckboxSelectionFilteredOnly: void 0,
  headerCheckboxSelectionCurrentPageOnly: void 0,
  suppressHeaderMenuButton: void 0,
  suppressMovable: void 0,
  lockPosition: void 0,
  lockVisible: void 0,
  lockPinned: void 0,
  unSortIcon: void 0,
  suppressSizeToFit: void 0,
  suppressAutoSize: void 0,
  enableRowGroup: void 0,
  enablePivot: void 0,
  enableValue: void 0,
  editable: void 0,
  suppressPaste: void 0,
  suppressNavigable: void 0,
  enableCellChangeFlash: void 0,
  rowDrag: void 0,
  dndSource: void 0,
  autoHeight: void 0,
  wrapText: void 0,
  sortable: void 0,
  resizable: void 0,
  singleClickEdit: void 0,
  floatingFilter: void 0,
  cellEditorPopup: void 0,
  suppressFillHandle: void 0,
  wrapHeaderText: void 0,
  autoHeaderHeight: void 0,
  dndSourceOnRowDrag: void 0,
  valueGetter: void 0,
  valueSetter: void 0,
  filterValueGetter: void 0,
  keyCreator: void 0,
  valueFormatter: void 0,
  valueParser: void 0,
  comparator: void 0,
  equals: void 0,
  pivotComparator: void 0,
  suppressKeyboardEvent: void 0,
  suppressHeaderKeyboardEvent: void 0,
  colSpan: void 0,
  rowSpan: void 0,
  spanRows: void 0,
  getQuickFilterText: void 0,
  onCellValueChanged: void 0,
  onCellClicked: void 0,
  onCellDoubleClicked: void 0,
  onCellContextMenu: void 0,
  rowDragText: void 0,
  tooltipValueGetter: void 0,
  tooltipComponentSelector: void 0,
  cellRendererSelector: void 0,
  cellEditorSelector: void 0,
  suppressSpanHeaderHeight: void 0,
  useValueFormatterForExport: void 0,
  useValueParserForImport: void 0,
  mainMenuItems: void 0,
  contextMenuItems: void 0,
  suppressFloatingFilterButton: void 0,
  suppressHeaderFilterButton: void 0,
  suppressHeaderContextMenu: void 0,
  loadingCellRenderer: void 0,
  loadingCellRendererParams: void 0,
  loadingCellRendererSelector: void 0,
  context: void 0,
  dateComponent: void 0,
  dateComponentParams: void 0,
  getFindText: void 0,
  rowGroupingHierarchy: void 0,
  groupHierarchy: void 0
};
var ALL_PROPERTIES = () => Object.keys(colDefPropertyMap);
var COL_DEF_VALIDATORS = () => ({
  objectName: "colDef",
  allProperties: ALL_PROPERTIES(),
  docsUrl: "column-properties/",
  deprecations: COLUMN_DEFINITION_DEPRECATIONS(),
  validations: COLUMN_DEFINITION_VALIDATIONS()
});
var STRING_GRID_OPTIONS = [
  "overlayLoadingTemplate",
  "overlayNoRowsTemplate",
  "gridId",
  "quickFilterText",
  "rowModelType",
  "editType",
  "domLayout",
  "clipboardDelimiter",
  "rowGroupPanelShow",
  "multiSortKey",
  "pivotColumnGroupTotals",
  "pivotRowTotals",
  "pivotPanelShow",
  "fillHandleDirection",
  "groupDisplayType",
  "treeDataDisplayType",
  "treeDataChildrenField",
  "treeDataParentIdField",
  "colResizeDefault",
  "tooltipTrigger",
  "serverSidePivotResultFieldSeparator",
  "columnMenu",
  "tooltipShowMode",
  "invalidEditValueMode",
  "grandTotalRow",
  "themeCssLayer",
  "findSearchValue",
  "styleNonce",
  "renderingMode"
];
var OBJECT_GRID_OPTIONS = [
  "components",
  "rowStyle",
  "context",
  "autoGroupColumnDef",
  "localeText",
  "icons",
  "datasource",
  "dragAndDropImageComponentParams",
  "serverSideDatasource",
  "viewportDatasource",
  "groupRowRendererParams",
  "aggFuncs",
  "fullWidthCellRendererParams",
  "defaultColGroupDef",
  "defaultColDef",
  "defaultCsvExportParams",
  "defaultExcelExportParams",
  "columnTypes",
  "rowClassRules",
  "detailCellRendererParams",
  "loadingCellRendererParams",
  "loadingOverlayComponentParams",
  "noRowsOverlayComponentParams",
  "popupParent",
  "themeStyleContainer",
  "statusBar",
  "chartThemeOverrides",
  "customChartThemes",
  "chartToolPanelsDef",
  "dataTypeDefinitions",
  "advancedFilterParent",
  "advancedFilterBuilderParams",
  "advancedFilterParams",
  "initialState",
  "autoSizeStrategy",
  "selectionColumnDef",
  "findOptions",
  "filterHandlers",
  "groupHierarchyConfig"
];
var ARRAY_GRID_OPTIONS = [
  "sortingOrder",
  "alignedGrids",
  "rowData",
  "columnDefs",
  "excelStyles",
  "pinnedTopRowData",
  "pinnedBottomRowData",
  "chartThemes",
  "rowClass",
  "paginationPageSizeSelector"
];
var _NUMBER_GRID_OPTIONS = [
  "rowHeight",
  "detailRowHeight",
  "rowBuffer",
  "headerHeight",
  "groupHeaderHeight",
  "groupLockGroupColumns",
  "floatingFiltersHeight",
  "pivotHeaderHeight",
  "pivotGroupHeaderHeight",
  "groupDefaultExpanded",
  "pivotDefaultExpanded",
  "viewportRowModelPageSize",
  "viewportRowModelBufferSize",
  "autoSizePadding",
  "maxBlocksInCache",
  "maxConcurrentDatasourceRequests",
  "tooltipShowDelay",
  "tooltipHideDelay",
  "cacheOverflowSize",
  "paginationPageSize",
  "cacheBlockSize",
  "infiniteInitialRowCount",
  "serverSideInitialRowCount",
  "scrollbarWidth",
  "asyncTransactionWaitMillis",
  "blockLoadDebounceMillis",
  "keepDetailRowsCount",
  "undoRedoCellEditingLimit",
  "cellFlashDuration",
  "cellFadeDuration",
  "tabIndex",
  "pivotMaxGeneratedColumns",
  "rowDragInsertDelay"
];
var OTHER_GRID_OPTIONS = ["theme", "rowSelection"];
var _BOOLEAN_MIXED_GRID_OPTIONS = [
  "cellSelection",
  "sideBar",
  "rowNumbers",
  "suppressGroupChangesColumnVisibility",
  "groupAggFiltering",
  "suppressStickyTotalRow",
  "groupHideParentOfSingleChild",
  "enableRowPinning"
];
var _BOOLEAN_GRID_OPTIONS = [
  "loadThemeGoogleFonts",
  "suppressMakeColumnVisibleAfterUnGroup",
  "suppressRowClickSelection",
  "suppressCellFocus",
  "suppressHeaderFocus",
  "suppressHorizontalScroll",
  "groupSelectsChildren",
  "alwaysShowHorizontalScroll",
  "alwaysShowVerticalScroll",
  "debug",
  "enableBrowserTooltips",
  "enableCellExpressions",
  "groupSuppressBlankHeader",
  "suppressMenuHide",
  "suppressRowDeselection",
  "unSortIcon",
  "suppressMultiSort",
  "alwaysMultiSort",
  "singleClickEdit",
  "suppressLoadingOverlay",
  "suppressNoRowsOverlay",
  "suppressAutoSize",
  "skipHeaderOnAutoSize",
  "suppressColumnMoveAnimation",
  "suppressMoveWhenColumnDragging",
  "suppressMovableColumns",
  "suppressFieldDotNotation",
  "enableRangeSelection",
  "enableRangeHandle",
  "enableFillHandle",
  "suppressClearOnFillReduction",
  "deltaSort",
  "suppressTouch",
  "allowContextMenuWithControlKey",
  "suppressContextMenu",
  "suppressDragLeaveHidesColumns",
  "suppressRowGroupHidesColumns",
  "suppressMiddleClickScrolls",
  "suppressPreventDefaultOnMouseWheel",
  "suppressCopyRowsToClipboard",
  "copyHeadersToClipboard",
  "copyGroupHeadersToClipboard",
  "pivotMode",
  "suppressAggFuncInHeader",
  "suppressColumnVirtualisation",
  "alwaysAggregateAtRootLevel",
  "suppressFocusAfterRefresh",
  "functionsReadOnly",
  "animateRows",
  "groupSelectsFiltered",
  "groupRemoveSingleChildren",
  "groupRemoveLowestSingleChildren",
  "enableRtl",
  "enableCellSpan",
  "suppressClickEdit",
  "rowDragEntireRow",
  "rowDragManaged",
  "suppressRowDrag",
  "suppressMoveWhenRowDragging",
  "rowDragMultiRow",
  "enableGroupEdit",
  "embedFullWidthRows",
  "suppressPaginationPanel",
  "groupHideOpenParents",
  "groupAllowUnbalanced",
  "pagination",
  "paginationAutoPageSize",
  "suppressScrollOnNewData",
  "suppressScrollWhenPopupsAreOpen",
  "purgeClosedRowNodes",
  "cacheQuickFilter",
  "includeHiddenColumnsInQuickFilter",
  "ensureDomOrder",
  "accentedSort",
  "suppressChangeDetection",
  "valueCache",
  "valueCacheNeverExpires",
  "aggregateOnlyChangedColumns",
  "suppressAnimationFrame",
  "suppressExcelExport",
  "suppressCsvExport",
  "includeHiddenColumnsInAdvancedFilter",
  "suppressMultiRangeSelection",
  "enterNavigatesVerticallyAfterEdit",
  "enterNavigatesVertically",
  "suppressPropertyNamesCheck",
  "rowMultiSelectWithClick",
  "suppressRowHoverHighlight",
  "suppressRowTransform",
  "suppressClipboardPaste",
  "suppressLastEmptyLineOnPaste",
  "enableCharts",
  "suppressMaintainUnsortedOrder",
  "enableCellTextSelection",
  "suppressBrowserResizeObserver",
  "suppressMaxRenderedRowRestriction",
  "excludeChildrenWhenTreeDataFiltering",
  "tooltipMouseTrack",
  "tooltipInteraction",
  "keepDetailRows",
  "paginateChildRows",
  "preventDefaultOnContextMenu",
  "undoRedoCellEditing",
  "allowDragFromColumnsToolPanel",
  "pivotSuppressAutoColumn",
  "suppressExpandablePivotGroups",
  "debounceVerticalScrollbar",
  "detailRowAutoHeight",
  "serverSideSortAllLevels",
  "serverSideEnableClientSideSort",
  "serverSideOnlyRefreshFilteredGroups",
  "suppressAggFilteredOnly",
  "showOpenedGroup",
  "suppressClipboardApi",
  "suppressModelUpdateAfterUpdateTransaction",
  "stopEditingWhenCellsLoseFocus",
  "groupMaintainOrder",
  "columnHoverHighlight",
  "readOnlyEdit",
  "suppressRowVirtualisation",
  "enableCellEditingOnBackspace",
  "resetRowDataOnUpdate",
  "removePivotHeaderRowWhenSingleValueColumn",
  "suppressCopySingleCellRanges",
  "suppressGroupRowsSticky",
  "suppressCutToClipboard",
  "rowGroupPanelSuppressSort",
  "allowShowChangeAfterFilter",
  "enableAdvancedFilter",
  "masterDetail",
  "treeData",
  "reactiveCustomComponents",
  "applyQuickFilterBeforePivotOrAgg",
  "suppressServerSideFullWidthLoadingRow",
  "suppressAdvancedFilterEval",
  "loading",
  "maintainColumnOrder",
  "enableStrictPivotColumnOrder",
  "suppressSetFilterByDefault",
  "enableFilterHandlers",
  "suppressStartEditOnTab",
  "hidePaddedHeaderRows",
  "ssrmExpandAllAffectsAllRows"
];
var _FUNCTION_GRID_OPTIONS = [
  "doesExternalFilterPass",
  "processPivotResultColDef",
  "processPivotResultColGroupDef",
  "getBusinessKeyForNode",
  "isRowSelectable",
  "rowDragText",
  "groupRowRenderer",
  "dragAndDropImageComponent",
  "fullWidthCellRenderer",
  "loadingCellRenderer",
  "loadingOverlayComponent",
  "noRowsOverlayComponent",
  "detailCellRenderer",
  "quickFilterParser",
  "quickFilterMatcher",
  "getLocaleText",
  "isExternalFilterPresent",
  "getRowHeight",
  "getRowClass",
  "getRowStyle",
  "getFullRowEditValidationErrors",
  "getContextMenuItems",
  "getMainMenuItems",
  "processRowPostCreate",
  "processCellForClipboard",
  "getGroupRowAgg",
  "isFullWidthRow",
  "sendToClipboard",
  "focusGridInnerElement",
  "navigateToNextHeader",
  "tabToNextHeader",
  "navigateToNextCell",
  "tabToNextCell",
  "processCellFromClipboard",
  "getDocument",
  "postProcessPopup",
  "getChildCount",
  "getDataPath",
  "isRowMaster",
  "postSortRows",
  "processHeaderForClipboard",
  "processUnpinnedColumns",
  "processGroupHeaderForClipboard",
  "paginationNumberFormatter",
  "processDataFromClipboard",
  "getServerSideGroupKey",
  "isServerSideGroup",
  "createChartContainer",
  "getChartToolbarItems",
  "fillOperation",
  "isApplyServerSideTransaction",
  "getServerSideGroupLevelParams",
  "isServerSideGroupOpenByDefault",
  "isGroupOpenByDefault",
  "initialGroupOrderComparator",
  "loadingCellRendererSelector",
  "getRowId",
  "chartMenuItems",
  "groupTotalRow",
  "alwaysPassFilter",
  "isRowPinnable",
  "isRowPinned",
  "isRowValidDropPosition"
];
var _GET_ALL_GRID_OPTIONS = () => [
  ...ARRAY_GRID_OPTIONS,
  ...OBJECT_GRID_OPTIONS,
  ...STRING_GRID_OPTIONS,
  ..._NUMBER_GRID_OPTIONS,
  ..._FUNCTION_GRID_OPTIONS,
  ..._BOOLEAN_GRID_OPTIONS,
  ..._BOOLEAN_MIXED_GRID_OPTIONS,
  ...OTHER_GRID_OPTIONS
];
var GRID_OPTION_DEPRECATIONS = () => ({
  suppressLoadingOverlay: { version: "32", message: "Use `loading`=false instead." },
  enableFillHandle: { version: "32.2", message: "Use `cellSelection.handle` instead." },
  enableRangeHandle: { version: "32.2", message: "Use `cellSelection.handle` instead." },
  enableRangeSelection: { version: "32.2", message: "Use `cellSelection = true` instead." },
  suppressMultiRangeSelection: {
    version: "32.2",
    message: "Use `cellSelection.suppressMultiRanges` instead."
  },
  suppressClearOnFillReduction: {
    version: "32.2",
    message: "Use `cellSelection.handle.suppressClearOnFillReduction` instead."
  },
  fillHandleDirection: { version: "32.2", message: "Use `cellSelection.handle.direction` instead." },
  fillOperation: { version: "32.2", message: "Use `cellSelection.handle.setFillValue` instead." },
  suppressRowClickSelection: {
    version: "32.2",
    message: "Use `rowSelection.enableClickSelection` instead."
  },
  suppressRowDeselection: { version: "32.2", message: "Use `rowSelection.enableClickSelection` instead." },
  rowMultiSelectWithClick: {
    version: "32.2",
    message: "Use `rowSelection.enableSelectionWithoutKeys` instead."
  },
  groupSelectsChildren: {
    version: "32.2",
    message: 'Use `rowSelection.groupSelects = "descendants"` instead.'
  },
  groupSelectsFiltered: {
    version: "32.2",
    message: 'Use `rowSelection.groupSelects = "filteredDescendants"` instead.'
  },
  isRowSelectable: { version: "32.2", message: "Use `selectionOptions.isRowSelectable` instead." },
  suppressCopySingleCellRanges: { version: "32.2", message: "Use `rowSelection.copySelectedRows` instead." },
  suppressCopyRowsToClipboard: { version: "32.2", message: "Use `rowSelection.copySelectedRows` instead." },
  onRangeSelectionChanged: { version: "32.2", message: "Use `onCellSelectionChanged` instead." },
  onRangeDeleteStart: { version: "32.2", message: "Use `onCellSelectionDeleteStart` instead." },
  onRangeDeleteEnd: { version: "32.2", message: "Use `onCellSelectionDeleteEnd` instead." },
  suppressBrowserResizeObserver: {
    version: "32.2",
    message: "The grid always uses the browser's ResizeObserver, this grid option has no effect."
  },
  onColumnEverythingChanged: {
    version: "32.2",
    message: "Either use `onDisplayedColumnsChanged` which is fired at the same time, or use one of the more specific column events."
  },
  groupRemoveSingleChildren: {
    version: "33",
    message: "Use `groupHideParentOfSingleChild` instead."
  },
  groupRemoveLowestSingleChildren: {
    version: "33",
    message: 'Use `groupHideParentOfSingleChild: "leafGroupsOnly"` instead.'
  },
  suppressRowGroupHidesColumns: {
    version: "33",
    message: 'Use `suppressGroupChangesColumnVisibility: "suppressHideOnGroup"` instead.'
  },
  suppressMakeColumnVisibleAfterUnGroup: {
    version: "33",
    message: 'Use `suppressGroupChangesColumnVisibility: "suppressShowOnUngroup"` instead.'
  },
  unSortIcon: { version: "33", message: "Use `defaultColDef.unSortIcon` instead." },
  sortingOrder: { version: "33", message: "Use `defaultColDef.sortingOrder` instead." },
  suppressPropertyNamesCheck: {
    version: "33",
    message: "`gridOptions` and `columnDefs` both have a `context` property that should be used for arbitrary user data. This means that column definitions and gridOptions should only contain valid properties making this property redundant."
  },
  suppressAdvancedFilterEval: {
    version: "34",
    message: "Advanced filter no longer uses function evaluation, so this option has no effect."
  }
});
function toConstrainedNum(key2, value2, min2) {
  if (typeof value2 === "number" || value2 == null) {
    if (value2 == null) {
      return null;
    }
    return value2 >= min2 ? null : `${key2}: value should be greater than or equal to ${min2}`;
  }
  return `${key2}: value should be a number`;
}
var GRID_OPTIONS_MODULES = {
  alignedGrids: "AlignedGrids",
  allowContextMenuWithControlKey: "ContextMenu",
  autoSizeStrategy: "ColumnAutoSize",
  cellSelection: "CellSelection",
  columnHoverHighlight: "ColumnHover",
  datasource: "InfiniteRowModel",
  doesExternalFilterPass: "ExternalFilter",
  editType: "EditCore",
  invalidEditValueMode: "EditCore",
  enableAdvancedFilter: "AdvancedFilter",
  enableCellSpan: "CellSpan",
  enableCharts: "IntegratedCharts",
  enableRangeSelection: "CellSelection",
  enableRowPinning: "PinnedRow",
  findSearchValue: "Find",
  getFullRowEditValidationErrors: "EditCore",
  getContextMenuItems: "ContextMenu",
  getLocaleText: "Locale",
  getMainMenuItems: "ColumnMenu",
  getRowClass: "RowStyle",
  getRowStyle: "RowStyle",
  groupTotalRow: "SharedRowGrouping",
  grandTotalRow: "ClientSideRowModelHierarchy",
  initialState: "GridState",
  isExternalFilterPresent: "ExternalFilter",
  isRowPinnable: "PinnedRow",
  isRowPinned: "PinnedRow",
  localeText: "Locale",
  masterDetail: "SharedMasterDetail",
  pagination: "Pagination",
  pinnedBottomRowData: "PinnedRow",
  pinnedTopRowData: "PinnedRow",
  pivotMode: "SharedPivot",
  pivotPanelShow: "RowGroupingPanel",
  quickFilterText: "QuickFilter",
  rowClass: "RowStyle",
  rowClassRules: "RowStyle",
  rowData: "ClientSideRowModel",
  rowDragManaged: "RowDrag",
  rowGroupPanelShow: "RowGroupingPanel",
  rowNumbers: "RowNumbers",
  rowSelection: "SharedRowSelection",
  rowStyle: "RowStyle",
  serverSideDatasource: "ServerSideRowModel",
  sideBar: "SideBar",
  statusBar: "StatusBar",
  treeData: "SharedTreeData",
  undoRedoCellEditing: "UndoRedoEdit",
  valueCache: "ValueCache",
  viewportDatasource: "ViewportRowModel"
};
var GRID_OPTION_VALIDATIONS = () => {
  const definedValidations = {
    autoSizePadding: {
      validate({ autoSizePadding }) {
        return toConstrainedNum("autoSizePadding", autoSizePadding, 0);
      }
    },
    cacheBlockSize: {
      supportedRowModels: ["serverSide", "infinite"],
      validate({ cacheBlockSize }) {
        return toConstrainedNum("cacheBlockSize", cacheBlockSize, 1);
      }
    },
    cacheOverflowSize: {
      validate({ cacheOverflowSize }) {
        return toConstrainedNum("cacheOverflowSize", cacheOverflowSize, 1);
      }
    },
    datasource: {
      supportedRowModels: ["infinite"]
    },
    domLayout: {
      validate: (options) => {
        const domLayout = options.domLayout;
        const validLayouts = ["autoHeight", "normal", "print"];
        if (domLayout && !validLayouts.includes(domLayout)) {
          return `domLayout must be one of [${validLayouts.join()}], currently it's ${domLayout}`;
        }
        return null;
      }
    },
    enableFillHandle: {
      dependencies: {
        enableRangeSelection: { required: [true] }
      }
    },
    enableRangeHandle: {
      dependencies: {
        enableRangeSelection: { required: [true] }
      }
    },
    enableRangeSelection: {
      dependencies: {
        rowDragEntireRow: { required: [false, void 0] }
      }
    },
    enableRowPinning: {
      supportedRowModels: ["clientSide"],
      validate({ enableRowPinning, pinnedTopRowData, pinnedBottomRowData }) {
        if (enableRowPinning && (pinnedTopRowData || pinnedBottomRowData)) {
          return "Manual row pinning cannot be used together with pinned row data. Either set `enableRowPinning` to `false`, or remove `pinnedTopRowData` and `pinnedBottomRowData`.";
        }
        return null;
      }
    },
    isRowPinnable: {
      supportedRowModels: ["clientSide"],
      validate({ enableRowPinning, isRowPinnable, pinnedTopRowData, pinnedBottomRowData }) {
        if (isRowPinnable && (pinnedTopRowData || pinnedBottomRowData)) {
          return "Manual row pinning cannot be used together with pinned row data. Either remove `isRowPinnable`, or remove `pinnedTopRowData` and `pinnedBottomRowData`.";
        }
        if (!enableRowPinning && isRowPinnable) {
          return "`isRowPinnable` requires `enableRowPinning` to be set.";
        }
        return null;
      }
    },
    isRowPinned: {
      supportedRowModels: ["clientSide"],
      validate({ enableRowPinning, isRowPinned, pinnedTopRowData, pinnedBottomRowData }) {
        if (isRowPinned && (pinnedTopRowData || pinnedBottomRowData)) {
          return "Manual row pinning cannot be used together with pinned row data. Either remove `isRowPinned`, or remove `pinnedTopRowData` and `pinnedBottomRowData`.";
        }
        if (!enableRowPinning && isRowPinned) {
          return "`isRowPinned` requires `enableRowPinning` to be set.";
        }
        return null;
      }
    },
    groupDefaultExpanded: {
      supportedRowModels: ["clientSide"]
    },
    groupHideOpenParents: {
      supportedRowModels: ["clientSide", "serverSide"],
      dependencies: {
        groupTotalRow: { required: [void 0, "bottom"] },
        treeData: {
          required: [void 0, false],
          reason: "Tree Data has values at the group level so it doesn't make sense to hide them."
        }
      }
    },
    groupHideParentOfSingleChild: {
      dependencies: {
        groupHideOpenParents: { required: [void 0, false] }
      }
    },
    groupRemoveLowestSingleChildren: {
      dependencies: {
        groupHideOpenParents: { required: [void 0, false] },
        groupRemoveSingleChildren: { required: [void 0, false] }
      }
    },
    groupRemoveSingleChildren: {
      dependencies: {
        groupHideOpenParents: { required: [void 0, false] },
        groupRemoveLowestSingleChildren: { required: [void 0, false] }
      }
    },
    groupSelectsChildren: {
      dependencies: {
        rowSelection: { required: ["multiple"] }
      }
    },
    groupHierarchyConfig: {
      validate({ groupHierarchyConfig = {} }, gridOptions, beans) {
        for (const k of Object.keys(groupHierarchyConfig)) {
          beans.validation?.validateColDef(groupHierarchyConfig[k]);
        }
        return null;
      }
    },
    icons: {
      validate: ({ icons }) => {
        if (icons) {
          if (icons["smallDown"]) {
            return _errMsg(262);
          }
          if (icons["smallLeft"]) {
            return _errMsg(263);
          }
          if (icons["smallRight"]) {
            return _errMsg(264);
          }
        }
        return null;
      }
    },
    infiniteInitialRowCount: {
      validate({ infiniteInitialRowCount }) {
        return toConstrainedNum("infiniteInitialRowCount", infiniteInitialRowCount, 1);
      }
    },
    initialGroupOrderComparator: {
      supportedRowModels: ["clientSide"]
    },
    ssrmExpandAllAffectsAllRows: {
      validate: (options) => {
        if (typeof options.ssrmExpandAllAffectsAllRows === "boolean") {
          if (options.rowModelType !== "serverSide") {
            return "'ssrmExpandAllAffectsAllRows' is only supported with the Server Side Row Model.";
          }
          if (options.ssrmExpandAllAffectsAllRows && typeof options.getRowId !== "function") {
            return `'getRowId' callback must be provided for Server Side Row Model grouping to work correctly.`;
          }
        }
        return null;
      }
    },
    keepDetailRowsCount: {
      validate({ keepDetailRowsCount }) {
        return toConstrainedNum("keepDetailRowsCount", keepDetailRowsCount, 1);
      }
    },
    paginationPageSize: {
      validate({ paginationPageSize }) {
        return toConstrainedNum("paginationPageSize", paginationPageSize, 1);
      }
    },
    paginationPageSizeSelector: {
      validate: (options) => {
        const values2 = options.paginationPageSizeSelector;
        if (typeof values2 === "boolean" || values2 == null) {
          return null;
        }
        if (!values2.length) {
          return `'paginationPageSizeSelector' cannot be an empty array.
                    If you want to hide the page size selector, set paginationPageSizeSelector to false.`;
        }
        return null;
      }
    },
    pivotMode: {
      dependencies: {
        treeData: {
          required: [false, void 0],
          reason: "Pivot Mode is not supported with Tree Data."
        }
      }
    },
    quickFilterText: {
      supportedRowModels: ["clientSide"]
    },
    rowBuffer: {
      validate({ rowBuffer }) {
        return toConstrainedNum("rowBuffer", rowBuffer, 0);
      }
    },
    rowClass: {
      validate: (options) => {
        const rowClass = options.rowClass;
        if (typeof rowClass === "function") {
          return "rowClass should not be a function, please use getRowClass instead";
        }
        return null;
      }
    },
    rowData: {
      supportedRowModels: ["clientSide"]
    },
    rowDragManaged: {
      supportedRowModels: ["clientSide"],
      dependencies: {
        pagination: {
          required: [false, void 0]
        }
      }
    },
    rowSelection: {
      validate({ rowSelection }) {
        if (rowSelection && typeof rowSelection === "string") {
          return 'As of version 32.2.1, using `rowSelection` with the values "single" or "multiple" has been deprecated. Use the object value instead.';
        }
        if (rowSelection && typeof rowSelection !== "object") {
          return "Expected `RowSelectionOptions` object for the `rowSelection` property.";
        }
        if (rowSelection && rowSelection.mode !== "multiRow" && rowSelection.mode !== "singleRow") {
          return `Selection mode "${rowSelection.mode}" is invalid. Use one of 'singleRow' or 'multiRow'.`;
        }
        return null;
      }
    },
    rowStyle: {
      validate: (options) => {
        const rowStyle = options.rowStyle;
        if (rowStyle && typeof rowStyle === "function") {
          return "rowStyle should be an object of key/value styles, not be a function, use getRowStyle() instead";
        }
        return null;
      }
    },
    serverSideDatasource: {
      supportedRowModels: ["serverSide"]
    },
    serverSideInitialRowCount: {
      supportedRowModels: ["serverSide"],
      validate({ serverSideInitialRowCount }) {
        return toConstrainedNum("serverSideInitialRowCount", serverSideInitialRowCount, 1);
      }
    },
    serverSideOnlyRefreshFilteredGroups: {
      supportedRowModels: ["serverSide"]
    },
    serverSideSortAllLevels: {
      supportedRowModels: ["serverSide"]
    },
    sortingOrder: {
      validate: (_options) => {
        const sortingOrder = _options.sortingOrder;
        if (Array.isArray(sortingOrder) && sortingOrder.length > 0) {
          const invalidItems = sortingOrder.filter((a2) => !DEFAULT_SORTING_ORDER.includes(a2));
          if (invalidItems.length > 0) {
            return `sortingOrder must be an array with elements from [${DEFAULT_SORTING_ORDER.map(toStringWithNullUndefined).join()}], currently it includes [${invalidItems.map(toStringWithNullUndefined).join()}]`;
          }
        } else if (!Array.isArray(sortingOrder) || sortingOrder.length <= 0) {
          return `sortingOrder must be an array with at least one element, currently it's ${sortingOrder}`;
        }
        return null;
      }
    },
    tooltipHideDelay: {
      validate: (options) => {
        if (options.tooltipHideDelay && options.tooltipHideDelay < 0) {
          return "tooltipHideDelay should not be lower than 0";
        }
        return null;
      }
    },
    tooltipShowDelay: {
      validate: (options) => {
        if (options.tooltipShowDelay && options.tooltipShowDelay < 0) {
          return "tooltipShowDelay should not be lower than 0";
        }
        return null;
      }
    },
    treeData: {
      supportedRowModels: ["clientSide", "serverSide"],
      validate: (options) => {
        const rowModel = options.rowModelType ?? "clientSide";
        switch (rowModel) {
          case "clientSide": {
            const { treeDataChildrenField, treeDataParentIdField, getDataPath, getRowId } = options;
            if (!treeDataChildrenField && !treeDataParentIdField && !getDataPath) {
              return "treeData requires either 'treeDataChildrenField' or 'treeDataParentIdField' or 'getDataPath' in the clientSide row model.";
            }
            if (treeDataChildrenField) {
              if (getDataPath) {
                return "Cannot use both 'treeDataChildrenField' and 'getDataPath' at the same time.";
              }
              if (treeDataParentIdField) {
                return "Cannot use both 'treeDataChildrenField' and 'treeDataParentIdField' at the same time.";
              }
            }
            if (treeDataParentIdField) {
              if (!getRowId) {
                return "getRowId callback not provided, tree data with parent id cannot be built.";
              }
              if (getDataPath) {
                return "Cannot use both 'treeDataParentIdField' and 'getDataPath' at the same time.";
              }
            }
            return null;
          }
          case "serverSide": {
            const ssrmWarning = `treeData requires 'isServerSideGroup' and 'getServerSideGroupKey' in the ${rowModel} row model.`;
            return options.isServerSideGroup && options.getServerSideGroupKey ? null : ssrmWarning;
          }
        }
        return null;
      }
    },
    viewportDatasource: {
      supportedRowModels: ["viewport"]
    },
    viewportRowModelBufferSize: {
      validate({ viewportRowModelBufferSize }) {
        return toConstrainedNum("viewportRowModelBufferSize", viewportRowModelBufferSize, 0);
      }
    },
    viewportRowModelPageSize: {
      validate({ viewportRowModelPageSize }) {
        return toConstrainedNum("viewportRowModelPageSize", viewportRowModelPageSize, 1);
      }
    },
    rowDragEntireRow: {
      dependencies: {
        cellSelection: { required: [void 0] }
      }
    },
    autoGroupColumnDef: {
      validate({ autoGroupColumnDef, showOpenedGroup }) {
        if (autoGroupColumnDef?.field && showOpenedGroup) {
          return "autoGroupColumnDef.field and showOpenedGroup are not supported when used together.";
        }
        if (autoGroupColumnDef?.valueGetter && showOpenedGroup) {
          return "autoGroupColumnDef.valueGetter and showOpenedGroup are not supported when used together.";
        }
        return null;
      }
    },
    renderingMode: {
      validate: (options) => {
        const renderingMode = options.renderingMode;
        const validModes = ["default", "legacy"];
        if (renderingMode && !validModes.includes(renderingMode)) {
          return `renderingMode must be one of [${validModes.join()}], currently it's ${renderingMode}`;
        }
        return null;
      }
    },
    autoSizeStrategy: {
      validate: ({ autoSizeStrategy }) => {
        if (!autoSizeStrategy) {
          return null;
        }
        const validModes = [
          "fitCellContents",
          "fitGridWidth",
          "fitProvidedWidth"
        ];
        const type = autoSizeStrategy.type;
        if (type !== "fitCellContents" && type !== "fitGridWidth" && type !== "fitProvidedWidth") {
          return `Invalid Auto-size strategy. \`autoSizeStrategy\` must be one of ${validModes.map((m) => '"' + m + '"').join(", ")}, currently it's ${type}`;
        }
        if (type === "fitProvidedWidth" && typeof autoSizeStrategy.width != "number") {
          return `When using the 'fitProvidedWidth' auto-size strategy, must provide a numeric \`width\`. You provided ${autoSizeStrategy.width}`;
        }
        return null;
      }
    }
  };
  const validations = {};
  for (const key2 of _BOOLEAN_GRID_OPTIONS) {
    validations[key2] = { expectedType: "boolean" };
  }
  for (const key2 of _NUMBER_GRID_OPTIONS) {
    validations[key2] = { expectedType: "number" };
  }
  _mergeDeep(validations, definedValidations);
  return validations;
};
var GRID_OPTIONS_VALIDATORS = () => ({
  objectName: "gridOptions",
  allProperties: [..._GET_ALL_GRID_OPTIONS(), ...Object.values(_PUBLIC_EVENT_HANDLERS_MAP)],
  propertyExceptions: ["api"],
  docsUrl: "grid-options/",
  deprecations: GRID_OPTION_DEPRECATIONS(),
  validations: GRID_OPTION_VALIDATIONS()
});
var changeSetId = 0;
var gridInstanceSequence = 0;
var GRID_DOM_KEY = "__ag_grid_instance";
var GridOptionsService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "gos";
    this.domDataKey = "__AG_" + Math.random().toString();
    this.instanceId = gridInstanceSequence++;
    this.gridReadyFired = false;
    this.queueEvents = [];
    this.propEventSvc = new LocalEventService();
    this.globalEventHandlerFactory = (restrictToSyncOnly) => {
      return (eventName, event) => {
        if (!this.isAlive()) {
          return;
        }
        const alwaysSync = ALWAYS_SYNC_GLOBAL_EVENTS.has(eventName);
        if (alwaysSync && !restrictToSyncOnly || !alwaysSync && restrictToSyncOnly) {
          return;
        }
        if (!isPublicEventHandler(eventName)) {
          return;
        }
        const fireEvent = (name2, e) => {
          const eventHandlerName = _PUBLIC_EVENT_HANDLERS_MAP[name2];
          const eventHandler2 = this.gridOptions[eventHandlerName];
          if (typeof eventHandler2 === "function") {
            this.beans.frameworkOverrides.wrapOutgoing(() => eventHandler2(e));
          }
        };
        if (this.gridReadyFired) {
          fireEvent(eventName, event);
        } else if (eventName === "gridReady") {
          fireEvent(eventName, event);
          this.gridReadyFired = true;
          for (const q of this.queueEvents) {
            fireEvent(q.eventName, q.event);
          }
          this.queueEvents = [];
        } else {
          this.queueEvents.push({ eventName, event });
        }
      };
    };
  }
  wireBeans(beans) {
    this.gridOptions = beans.gridOptions;
    this.validation = beans.validation;
    this.api = beans.gridApi;
    this.gridId = beans.context.getId();
  }
  // This is quicker then having code call gridOptionsService.get('context')
  get gridOptionsContext() {
    return this.gridOptions["context"];
  }
  postConstruct() {
    this.validateGridOptions(this.gridOptions);
    this.eventSvc.addGlobalListener(this.globalEventHandlerFactory().bind(this), true);
    this.eventSvc.addGlobalListener(this.globalEventHandlerFactory(true).bind(this), false);
    this.propEventSvc.setFrameworkOverrides(this.beans.frameworkOverrides);
    this.addManagedEventListeners({
      gridOptionsChanged: ({ options }) => {
        this.updateGridOptions({ options, force: true, source: "optionsUpdated" });
      }
    });
  }
  destroy() {
    super.destroy();
    this.queueEvents = [];
  }
  /**
   * Get the raw value of the GridOptions property provided.
   * @param property
   */
  get(property) {
    return this.gridOptions[property] ?? GRID_OPTION_DEFAULTS[property];
  }
  /**
   * Get the GridOption callback but wrapped so that the common params of api and context are automatically applied to the params.
   * @param property GridOption callback properties based on the fact that this property has a callback with params extending AgGridCommon
   */
  getCallback(property) {
    return this.mergeGridCommonParams(this.gridOptions[property]);
  }
  /**
   * Returns `true` if a value has been specified for this GridOption.
   * @param property GridOption property
   */
  exists(property) {
    return _exists(this.gridOptions[property]);
  }
  /**
   * Wrap the user callback and attach the api and context to the params object on the way through.
   * @param callback User provided callback
   * @returns Wrapped callback where the params object not require api and context
   */
  mergeGridCommonParams(callback) {
    if (callback) {
      const wrapped = (callbackParams) => {
        return callback(this.addCommon(callbackParams));
      };
      return wrapped;
    }
    return callback;
  }
  updateGridOptions({
    options,
    force,
    source: source2 = "api"
  }) {
    const changeSet = { id: changeSetId++, properties: [] };
    const events = [];
    const { gridOptions, validation: validation2 } = this;
    for (const key2 of Object.keys(options)) {
      const value2 = GlobalGridOptions.applyGlobalGridOption(key2, options[key2]);
      validation2?.warnOnInitialPropertyUpdate(source2, key2);
      const shouldForce = force || typeof value2 === "object" && source2 === "api";
      const previousValue = gridOptions[key2];
      if (shouldForce || previousValue !== value2) {
        gridOptions[key2] = value2;
        const event = {
          type: key2,
          currentValue: value2,
          previousValue,
          changeSet,
          source: source2
        };
        events.push(event);
      }
    }
    this.validateGridOptions(this.gridOptions);
    changeSet.properties = events.map((event) => event.type);
    for (const event of events) {
      _logIfDebug(this, `Updated property ${event.type} from`, event.previousValue, ` to `, event.currentValue);
      this.propEventSvc.dispatchEvent(event);
    }
  }
  addPropertyEventListener(key2, listener) {
    this.propEventSvc.addEventListener(key2, listener);
  }
  removePropertyEventListener(key2, listener) {
    this.propEventSvc.removeEventListener(key2, listener);
  }
  getDomDataKey() {
    return this.domDataKey;
  }
  /** Prefer _addGridCommonParams from gridOptionsUtils for bundle size savings */
  addCommon(params) {
    params.api = this.api;
    params.context = this.gridOptionsContext;
    return params;
  }
  validateOptions(options, modValidations) {
    for (const key2 of Object.keys(options)) {
      const value2 = options[key2];
      if (value2 == null || value2 === false) {
        continue;
      }
      let moduleToCheck = modValidations[key2];
      if (typeof moduleToCheck === "function") {
        moduleToCheck = moduleToCheck(options, this.gridOptions, this.beans);
      }
      if (moduleToCheck) {
        this.assertModuleRegistered(moduleToCheck, key2);
      }
    }
  }
  validateGridOptions(gridOptions) {
    this.validateOptions(gridOptions, GRID_OPTIONS_MODULES);
    this.validation?.processGridOptions(gridOptions);
  }
  validateColDef(colDef, colId, skipInferenceCheck) {
    if (skipInferenceCheck || !this.beans.dataTypeSvc?.isColPendingInference(colId)) {
      this.validateOptions(colDef, COLUMN_DEFINITION_MOD_VALIDATIONS);
      this.validation?.validateColDef(colDef);
    }
  }
  assertModuleRegistered(moduleName, reasonOrId) {
    const registered = Array.isArray(moduleName) ? moduleName.some((modName) => this.isModuleRegistered(modName)) : this.isModuleRegistered(moduleName);
    if (!registered) {
      _error(200, {
        ...this.getModuleErrorParams(),
        moduleName,
        reasonOrId
      });
    }
    return registered;
  }
  getModuleErrorParams() {
    return {
      gridId: this.gridId,
      gridScoped: _areModulesGridScoped(),
      rowModelType: this.get("rowModelType"),
      isUmd: _isUmd()
    };
  }
  isModuleRegistered(moduleName) {
    return _isModuleRegistered(moduleName, this.gridId, this.get("rowModelType"));
  }
  setInstanceDomData(element) {
    element[GRID_DOM_KEY] = this.instanceId;
  }
  isElementInThisInstance(element) {
    let pointer = element;
    while (pointer) {
      const instanceId = pointer[GRID_DOM_KEY];
      if (_exists(instanceId)) {
        const eventFromThisGrid = instanceId === this.instanceId;
        return eventFromThisGrid;
      }
      pointer = pointer.parentElement;
    }
    return false;
  }
};
function isPublicEventHandler(eventName) {
  return !!_PUBLIC_EVENT_HANDLERS_MAP[eventName];
}
function getHeaderCompElementParams(includeSortIndicator) {
  const hiddenAttrs = { "aria-hidden": "true" };
  return {
    tag: "div",
    cls: "ag-cell-label-container",
    role: "presentation",
    children: [
      {
        tag: "span",
        ref: "eMenu",
        cls: "ag-header-icon ag-header-cell-menu-button",
        attrs: hiddenAttrs
      },
      {
        tag: "span",
        ref: "eFilterButton",
        cls: "ag-header-icon ag-header-cell-filter-button",
        attrs: hiddenAttrs
      },
      {
        tag: "div",
        ref: "eLabel",
        cls: "ag-header-cell-label",
        role: "presentation",
        children: [
          { tag: "span", ref: "eText", cls: "ag-header-cell-text" },
          {
            tag: "span",
            ref: "eFilter",
            cls: "ag-header-icon ag-header-label-icon ag-filter-icon",
            attrs: hiddenAttrs
          },
          includeSortIndicator ? { tag: "ag-sort-indicator", ref: "eSortIndicator" } : null
        ]
      }
    ]
  };
}
var HeaderCompElement = getHeaderCompElementParams(true);
var HeaderCompElementNoSort = getHeaderCompElementParams(false);
var HeaderComp = class extends Component {
  constructor() {
    super(...arguments);
    this.eFilter = RefPlaceholder;
    this.eFilterButton = RefPlaceholder;
    this.eSortIndicator = RefPlaceholder;
    this.eMenu = RefPlaceholder;
    this.eLabel = RefPlaceholder;
    this.eText = RefPlaceholder;
    this.eSortOrder = RefPlaceholder;
    this.eSortAsc = RefPlaceholder;
    this.eSortDesc = RefPlaceholder;
    this.eSortMixed = RefPlaceholder;
    this.eSortNone = RefPlaceholder;
    this.isLoadingInnerComponent = false;
  }
  refresh(params) {
    const oldParams = this.params;
    this.params = params;
    if (this.workOutTemplate(params, !!this.beans?.sortSvc) != this.currentTemplate || this.workOutShowMenu() != this.currentShowMenu || params.enableSorting != this.currentSort || this.currentSuppressMenuHide != null && this.shouldSuppressMenuHide() != this.currentSuppressMenuHide || oldParams.enableFilterButton != params.enableFilterButton || oldParams.enableFilterIcon != params.enableFilterIcon) {
      return false;
    }
    if (this.innerHeaderComponent) {
      const mergedParams = { ...params };
      _mergeDeep(mergedParams, params.innerHeaderComponentParams);
      this.innerHeaderComponent.refresh?.(mergedParams);
    } else {
      this.setDisplayName(params);
    }
    return true;
  }
  workOutTemplate(params, isSorting) {
    const paramsTemplate = params.template;
    if (paramsTemplate) {
      return paramsTemplate?.trim ? paramsTemplate.trim() : paramsTemplate;
    } else {
      return isSorting ? HeaderCompElement : HeaderCompElementNoSort;
    }
  }
  init(params) {
    this.params = params;
    const { sortSvc, touchSvc, rowNumbersSvc, userCompFactory } = this.beans;
    const sortComp = sortSvc?.getSortIndicatorSelector();
    this.currentTemplate = this.workOutTemplate(params, !!sortComp);
    this.setTemplate(this.currentTemplate, sortComp ? [sortComp] : void 0);
    touchSvc?.setupForHeader(this);
    this.setMenu();
    this.setupSort();
    rowNumbersSvc?.setupForHeader(this);
    this.setupFilterIcon();
    this.setupFilterButton();
    this.workOutInnerHeaderComponent(userCompFactory, params);
    this.setDisplayName(params);
  }
  workOutInnerHeaderComponent(userCompFactory, params) {
    const userCompDetails = _getInnerHeaderCompDetails(userCompFactory, params, params);
    if (!userCompDetails) {
      return;
    }
    this.isLoadingInnerComponent = true;
    userCompDetails.newAgStackInstance().then((comp) => {
      this.isLoadingInnerComponent = false;
      if (!comp) {
        return;
      }
      if (this.isAlive()) {
        this.innerHeaderComponent = comp;
        if (this.eText) {
          this.eText.appendChild(comp.getGui());
        }
      } else {
        this.destroyBean(comp);
      }
    });
  }
  setDisplayName(params) {
    const { displayName } = params;
    const oldDisplayName = this.currentDisplayName;
    this.currentDisplayName = displayName;
    if (!this.eText || oldDisplayName === displayName || this.innerHeaderComponent || this.isLoadingInnerComponent) {
      return;
    }
    this.eText.textContent = _toString(displayName);
  }
  addInIcon(iconName, eParent, column2) {
    const eIcon = _createIconNoSpan(iconName, this.beans, column2);
    if (eIcon) {
      eParent.appendChild(eIcon);
    }
  }
  workOutShowMenu() {
    return this.params.enableMenu && !!this.beans.menuSvc?.isHeaderMenuButtonEnabled();
  }
  shouldSuppressMenuHide() {
    return !!this.beans.menuSvc?.isHeaderMenuButtonAlwaysShowEnabled();
  }
  setMenu() {
    if (!this.eMenu) {
      return;
    }
    this.currentShowMenu = this.workOutShowMenu();
    if (!this.currentShowMenu) {
      _removeFromParent(this.eMenu);
      this.eMenu = void 0;
      return;
    }
    const { gos, eMenu, params } = this;
    const isLegacyMenu = _isLegacyMenuEnabled(gos);
    this.addInIcon(isLegacyMenu ? "menu" : "menuAlt", eMenu, params.column);
    eMenu.classList.toggle("ag-header-menu-icon", !isLegacyMenu);
    const currentSuppressMenuHide = this.shouldSuppressMenuHide();
    this.currentSuppressMenuHide = currentSuppressMenuHide;
    this.addManagedElementListeners(eMenu, { click: () => this.showColumnMenu(this.eMenu) });
    this.toggleMenuAlwaysShow(currentSuppressMenuHide);
  }
  toggleMenuAlwaysShow(alwaysShow) {
    this.eMenu?.classList.toggle("ag-header-menu-always-show", alwaysShow);
  }
  showColumnMenu(element) {
    const { currentSuppressMenuHide, params } = this;
    if (!currentSuppressMenuHide) {
      this.toggleMenuAlwaysShow(true);
    }
    params.showColumnMenu(element, () => {
      if (!currentSuppressMenuHide) {
        this.toggleMenuAlwaysShow(false);
      }
    });
  }
  onMenuKeyboardShortcut(isFilterShortcut) {
    const { params, gos, beans, eMenu, eFilterButton } = this;
    const column2 = params.column;
    const isLegacyMenuEnabled = _isLegacyMenuEnabled(gos);
    if (isFilterShortcut && !isLegacyMenuEnabled) {
      if (beans.menuSvc?.isFilterMenuInHeaderEnabled(column2)) {
        params.showFilter(eFilterButton ?? eMenu ?? this.getGui());
        return true;
      }
    } else if (params.enableMenu) {
      this.showColumnMenu(eMenu ?? eFilterButton ?? this.getGui());
      return true;
    }
    return false;
  }
  setupSort() {
    const { sortSvc } = this.beans;
    if (!sortSvc) {
      return;
    }
    const { enableSorting, column: column2 } = this.params;
    this.currentSort = enableSorting;
    if (!this.eSortIndicator) {
      this.eSortIndicator = this.createBean(sortSvc.createSortIndicator(true));
      const { eSortIndicator, eSortOrder, eSortAsc, eSortDesc, eSortMixed, eSortNone } = this;
      eSortIndicator.attachCustomElements(eSortOrder, eSortAsc, eSortDesc, eSortMixed, eSortNone);
    }
    this.eSortIndicator.setupSort(column2);
    if (!this.currentSort) {
      return;
    }
    sortSvc.setupHeader(this, column2, this.eLabel);
  }
  setupFilterIcon() {
    const { eFilter, params } = this;
    if (!eFilter) {
      return;
    }
    const onFilterChangedIcon = () => {
      const filterPresent = params.column.isFilterActive();
      _setDisplayed(eFilter, filterPresent, { skipAriaHidden: true });
    };
    this.configureFilter(params.enableFilterIcon, eFilter, onFilterChangedIcon, "filterActive");
  }
  setupFilterButton() {
    const { eFilterButton, params } = this;
    if (!eFilterButton) {
      return;
    }
    const configured = this.configureFilter(
      params.enableFilterButton,
      eFilterButton,
      this.onFilterChangedButton.bind(this),
      "filter"
    );
    if (configured) {
      this.addManagedElementListeners(eFilterButton, {
        click: () => params.showFilter(eFilterButton)
      });
    } else {
      this.eFilterButton = void 0;
    }
  }
  configureFilter(enabled, element, filterChangedCallback, icon2) {
    if (!enabled) {
      _removeFromParent(element);
      return false;
    }
    const column2 = this.params.column;
    this.addInIcon(icon2, element, column2);
    this.addManagedListeners(column2, { filterChanged: filterChangedCallback });
    filterChangedCallback();
    return true;
  }
  onFilterChangedButton() {
    const filterPresent = this.params.column.isFilterActive();
    this.eFilterButton.classList.toggle("ag-filter-active", filterPresent);
  }
  getAnchorElementForMenu(isFilter) {
    const { eFilterButton, eMenu } = this;
    if (isFilter) {
      return eFilterButton ?? eMenu ?? this.getGui();
    }
    return eMenu ?? eFilterButton ?? this.getGui();
  }
  destroy() {
    super.destroy();
    if (this.innerHeaderComponent) {
      this.destroyBean(this.innerHeaderComponent);
      this.innerHeaderComponent = void 0;
    }
  }
};
var HeaderGroupCompElement = {
  tag: "div",
  cls: "ag-header-group-cell-label",
  role: "presentation",
  children: [
    { tag: "span", ref: "agLabel", cls: "ag-header-group-text", role: "presentation" },
    { tag: "span", ref: "agOpened", cls: `ag-header-icon ag-header-expand-icon ag-header-expand-icon-expanded` },
    { tag: "span", ref: "agClosed", cls: `ag-header-icon ag-header-expand-icon ag-header-expand-icon-collapsed` }
  ]
};
var HeaderGroupComp = class extends Component {
  constructor() {
    super(HeaderGroupCompElement);
    this.agOpened = RefPlaceholder;
    this.agClosed = RefPlaceholder;
    this.agLabel = RefPlaceholder;
    this.isLoadingInnerComponent = false;
  }
  init(params) {
    const { userCompFactory, touchSvc } = this.beans;
    this.params = params;
    this.checkWarnings();
    this.workOutInnerHeaderGroupComponent(userCompFactory, params);
    this.setupLabel(params);
    this.addGroupExpandIcon(params);
    this.setupExpandIcons();
    touchSvc?.setupForHeaderGroup(this);
  }
  checkWarnings() {
    const paramsAny = this.params;
    if (paramsAny.template) {
      _warn(89);
    }
  }
  workOutInnerHeaderGroupComponent(userCompFactory, params) {
    const userCompDetails = _getInnerHeaderGroupCompDetails(userCompFactory, params, params);
    if (!userCompDetails) {
      return;
    }
    this.isLoadingInnerComponent = true;
    userCompDetails.newAgStackInstance().then((comp) => {
      this.isLoadingInnerComponent = false;
      if (!comp) {
        return;
      }
      if (this.isAlive()) {
        this.innerHeaderGroupComponent = comp;
        this.agLabel.appendChild(comp.getGui());
      } else {
        this.destroyBean(comp);
      }
    });
  }
  setupExpandIcons() {
    const {
      agOpened,
      agClosed,
      params: { columnGroup },
      beans
    } = this;
    this.addInIcon("columnGroupOpened", agOpened);
    this.addInIcon("columnGroupClosed", agClosed);
    const expandAction = (event) => {
      if (_isStopPropagationForAgGrid(event)) {
        return;
      }
      const newExpandedValue = !columnGroup.isExpanded();
      beans.colGroupSvc.setColumnGroupOpened(
        columnGroup.getProvidedColumnGroup(),
        newExpandedValue,
        "uiColumnExpanded"
      );
    };
    this.addTouchAndClickListeners(beans, agClosed, expandAction);
    this.addTouchAndClickListeners(beans, agOpened, expandAction);
    const stopPropagationAction = (event) => {
      _stopPropagationForAgGrid(event);
    };
    this.addManagedElementListeners(agClosed, { dblclick: stopPropagationAction });
    this.addManagedElementListeners(agOpened, { dblclick: stopPropagationAction });
    this.addManagedElementListeners(this.getGui(), { dblclick: expandAction });
    this.updateIconVisibility();
    const providedColumnGroup = columnGroup.getProvidedColumnGroup();
    const updateIcon = this.updateIconVisibility.bind(this);
    this.addManagedListeners(providedColumnGroup, {
      expandedChanged: updateIcon,
      expandableChanged: updateIcon
    });
  }
  addTouchAndClickListeners(beans, eElement, action) {
    beans.touchSvc?.setupForHeaderGroupElement(this, eElement, action);
    this.addManagedElementListeners(eElement, { click: action });
  }
  updateIconVisibility() {
    const {
      agOpened,
      agClosed,
      params: { columnGroup }
    } = this;
    if (columnGroup.isExpandable()) {
      const expanded = columnGroup.isExpanded();
      _setDisplayed(agOpened, expanded);
      _setDisplayed(agClosed, !expanded);
    } else {
      _setDisplayed(agOpened, false);
      _setDisplayed(agClosed, false);
    }
  }
  addInIcon(iconName, element) {
    const eIcon = _createIconNoSpan(iconName, this.beans, null);
    if (eIcon) {
      element.appendChild(eIcon);
    }
  }
  addGroupExpandIcon(params) {
    if (!params.columnGroup.isExpandable()) {
      const { agOpened, agClosed } = this;
      _setDisplayed(agOpened, false);
      _setDisplayed(agClosed, false);
    }
  }
  setupLabel(params) {
    const { displayName, columnGroup } = params;
    const hasInnerComponent = this.innerHeaderGroupComponent || this.isLoadingInnerComponent;
    if (_exists(displayName) && !hasInnerComponent) {
      this.agLabel.textContent = _toString(displayName);
    }
    this.toggleCss("ag-sticky-label", !columnGroup.getColGroupDef()?.suppressStickyLabel);
  }
  destroy() {
    super.destroy();
    if (this.innerHeaderGroupComponent) {
      this.destroyBean(this.innerHeaderGroupComponent);
      this.innerHeaderGroupComponent = void 0;
    }
  }
};
var ColumnHeaderCompModule = {
  moduleName: "ColumnHeaderComp",
  version: VERSION,
  userComponents: {
    agColumnHeader: HeaderComp
  },
  icons: {
    // button to launch legacy column menu
    menu: "menu",
    // button to launch new enterprise column menu
    menuAlt: "menu-alt"
  }
};
var ColumnGroupHeaderCompModule = {
  moduleName: "ColumnGroupHeaderComp",
  version: VERSION,
  userComponents: {
    agColumnGroupHeader: HeaderGroupComp
  },
  icons: {
    // header column group shown when expanded (click to contract)
    columnGroupOpened: "expanded",
    // header column group shown when contracted (click to expand)
    columnGroupClosed: "contracted"
  }
};
var AnimationFrameService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "animationFrameSvc";
    this.p1 = { list: [], sorted: false };
    this.p2 = { list: [], sorted: false };
    this.f1 = { list: [], sorted: false };
    this.destroyTasks = [];
    this.ticking = false;
    this.scrollGoingDown = true;
    this.lastScrollTop = 0;
    this.taskCount = 0;
  }
  setScrollTop(scrollTop) {
    this.scrollGoingDown = scrollTop >= this.lastScrollTop;
    if (scrollTop === 0) {
      this.scrollGoingDown = true;
    }
    this.lastScrollTop = scrollTop;
  }
  postConstruct() {
    this.active = !this.gos.get("suppressAnimationFrame");
    this.batchFrameworkComps = this.beans.frameworkOverrides.batchFrameworkComps;
  }
  // this method is for our AG Grid sanity only - if animation frames are turned off,
  // then no place in the code should be looking to add any work to be done in animation
  // frames. this stops bugs - where some code is asking for a frame to be executed
  // when it should not.
  verify() {
    if (this.active === false) {
      _warn(92);
    }
  }
  createTask(task, index, list2, isFramework, isDeferred = false) {
    this.verify();
    let taskList = list2;
    if (isFramework && this.batchFrameworkComps) {
      taskList = "f1";
    }
    const taskItem = { task, index, createOrder: ++this.taskCount, deferred: isDeferred };
    this.addTaskToList(this[taskList], taskItem);
    this.schedule();
  }
  addTaskToList(taskList, task) {
    taskList.list.push(task);
    taskList.sorted = false;
  }
  sortTaskList(taskList) {
    if (taskList.sorted) {
      return;
    }
    const sortDirection = this.scrollGoingDown ? 1 : -1;
    taskList.list.sort((a2, b) => {
      if (a2.deferred !== b.deferred) {
        return a2.deferred ? -1 : 1;
      }
      if (a2.index !== b.index) {
        return sortDirection * (b.index - a2.index);
      }
      return b.createOrder - a2.createOrder;
    });
    taskList.sorted = true;
  }
  addDestroyTask(task) {
    this.verify();
    this.destroyTasks.push(task);
    this.schedule();
  }
  executeFrame(millis) {
    const { p1, p2, f1, destroyTasks, beans } = this;
    const { ctrlsSvc, frameworkOverrides } = beans;
    const p1Tasks = p1.list;
    const p2Tasks = p2.list;
    const f1Tasks = f1.list;
    const frameStart = Date.now();
    let duration2 = 0;
    const noMaxMillis = millis <= 0;
    const scrollFeature = ctrlsSvc.getScrollFeature();
    while (noMaxMillis || duration2 < millis) {
      const gridBodyDidSomething = scrollFeature.scrollGridIfNeeded();
      if (!gridBodyDidSomething) {
        let task;
        if (p1Tasks.length) {
          this.sortTaskList(p1);
          task = p1Tasks.pop().task;
        } else if (p2Tasks.length) {
          this.sortTaskList(p2);
          task = p2Tasks.pop().task;
        } else if (f1Tasks.length) {
          frameworkOverrides.wrapOutgoing(() => {
            while (noMaxMillis || duration2 < millis) {
              const gridBodyDidSomething2 = scrollFeature.scrollGridIfNeeded();
              if (!gridBodyDidSomething2) {
                if (f1Tasks.length) {
                  this.sortTaskList(f1);
                  task = f1Tasks.pop().task;
                  task();
                } else {
                  break;
                }
              } else {
                break;
              }
              duration2 = Date.now() - frameStart;
            }
          });
          task = () => {
          };
        } else if (destroyTasks.length) {
          task = destroyTasks.pop();
        } else {
          break;
        }
        task();
      }
      duration2 = Date.now() - frameStart;
    }
    if (p1Tasks.length || p2Tasks.length || f1Tasks.length || destroyTasks.length) {
      this.requestFrame();
    } else {
      this.ticking = false;
    }
  }
  flushAllFrames() {
    if (!this.active) {
      return;
    }
    this.executeFrame(-1);
  }
  schedule() {
    if (!this.active) {
      return;
    }
    if (!this.ticking) {
      this.ticking = true;
      this.requestFrame();
    }
  }
  requestFrame() {
    const callback = this.executeFrame.bind(this, 60);
    _requestAnimationFrame(this.beans, callback);
  }
  isQueueEmpty() {
    return !this.ticking;
  }
};
var AnimationFrameModule = {
  moduleName: "AnimationFrame",
  version: VERSION,
  beans: [AnimationFrameService]
};
var IconService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "iconSvc";
  }
  createIconNoSpan(iconName, params) {
    return _createIconNoSpan(iconName, this.beans, params?.column);
  }
};
var TouchService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "touchSvc";
  }
  mockBodyContextMenu(ctrl, listener) {
    this.mockContextMenu(ctrl, ctrl.eBodyViewport, listener);
  }
  mockHeaderContextMenu(ctrl, listener) {
    this.mockContextMenu(ctrl, ctrl.eGui, listener);
  }
  mockRowContextMenu(ctrl) {
    if (!_isIOSUserAgent()) {
      return;
    }
    const listener = (mouseListener, touch, touchEvent) => {
      const { rowCtrl, cellCtrl } = ctrl.getControlsForEventTarget(touchEvent?.target ?? null);
      if (cellCtrl?.column) {
        cellCtrl.dispatchCellContextMenuEvent(touchEvent ?? null);
      }
      this.beans.contextMenuSvc?.handleContextMenuMouseEvent(void 0, touchEvent, rowCtrl, cellCtrl);
    };
    this.mockContextMenu(ctrl, ctrl.element, listener);
  }
  handleCellDoubleClick(ctrl, mouseEvent) {
    const isDoubleClickOnIPad = () => {
      if (!_isIOSUserAgent() || _isEventSupported("dblclick")) {
        return false;
      }
      const nowMillis = Date.now();
      const res = nowMillis - ctrl.lastIPadMouseClickEvent < 200;
      ctrl.lastIPadMouseClickEvent = nowMillis;
      return res;
    };
    if (isDoubleClickOnIPad()) {
      ctrl.onCellDoubleClicked(mouseEvent);
      mouseEvent.preventDefault();
      return true;
    }
    return false;
  }
  setupForHeader(comp) {
    const { gos, sortSvc, menuSvc } = this.beans;
    if (gos.get("suppressTouch")) {
      return;
    }
    const { params, eMenu, eFilterButton } = comp;
    const touchListener = new TouchListener(comp.getGui(), true);
    comp.addDestroyFunc(() => touchListener.destroy());
    const suppressMenuHide = comp.shouldSuppressMenuHide();
    const tapMenuButton = suppressMenuHide && _exists(eMenu) && params.enableMenu;
    let menuTouchListener = touchListener;
    if (tapMenuButton) {
      menuTouchListener = new TouchListener(eMenu, true);
      comp.addDestroyFunc(() => menuTouchListener.destroy());
    }
    if (params.enableMenu || menuSvc?.isHeaderContextMenuEnabled(params.column)) {
      const eventType = tapMenuButton ? "tap" : "longTap";
      const showMenuFn = (event) => params.showColumnMenuAfterMouseClick(event.touchStart);
      comp.addManagedListeners(menuTouchListener, { [eventType]: showMenuFn });
      comp.addManagedListeners(touchListener, { longTap: showMenuFn });
    }
    if (params.enableSorting) {
      const tapListener = (event) => {
        const target = event.touchStart.target;
        if (suppressMenuHide && (eMenu?.contains(target) || eFilterButton?.contains(target))) {
          return;
        }
        sortSvc?.progressSort(params.column, false, "uiColumnSorted");
      };
      comp.addManagedListeners(touchListener, { tap: tapListener });
    }
    if (params.enableFilterButton && eFilterButton) {
      const filterButtonTouchListener = new TouchListener(eFilterButton, true);
      comp.addManagedListeners(filterButtonTouchListener, {
        tap: () => params.showFilter(eFilterButton)
      });
      comp.addDestroyFunc(() => filterButtonTouchListener.destroy());
    }
  }
  setupForHeaderGroup(comp) {
    const params = comp.params;
    if (this.beans.menuSvc?.isHeaderContextMenuEnabled(
      params.columnGroup.getProvidedColumnGroup()
    )) {
      const touchListener = new TouchListener(params.eGridHeader, true);
      const showMenuFn = (event) => params.showColumnMenuAfterMouseClick(event.touchStart);
      comp.addManagedListeners(touchListener, { longTap: showMenuFn });
      comp.addDestroyFunc(() => touchListener.destroy());
    }
  }
  setupForHeaderGroupElement(comp, eElement, action) {
    const touchListener = new TouchListener(eElement, true);
    comp.addManagedListeners(touchListener, { tap: action });
    comp.addDestroyFunc(() => touchListener.destroy());
  }
  mockContextMenu(ctrl, element, listener) {
    if (!_isIOSUserAgent()) {
      return;
    }
    const touchListener = new TouchListener(element);
    const longTapListener = (event) => {
      if (!_isEventFromThisInstance(this.beans, event.touchEvent)) {
        return;
      }
      listener(void 0, event.touchStart, event.touchEvent);
    };
    ctrl.addManagedListeners(touchListener, { longTap: longTapListener });
    ctrl.addDestroyFunc(() => touchListener.destroy());
  }
};
var TouchModule = {
  moduleName: "Touch",
  version: VERSION,
  beans: [TouchService]
};
var CellNavigationService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "cellNavigation";
  }
  wireBeans(beans) {
    this.rowSpanSvc = beans.rowSpanSvc;
  }
  // returns null if no cell to focus on, ie at the end of the grid
  getNextCellToFocus(key2, focusedCell, ctrlPressed = false) {
    if (ctrlPressed) {
      return this.getNextCellToFocusWithCtrlPressed(key2, focusedCell);
    }
    return this.getNextCellToFocusWithoutCtrlPressed(key2, focusedCell);
  }
  getNextCellToFocusWithCtrlPressed(key2, focusedCell) {
    const upKey = key2 === KeyCode.UP;
    const downKey = key2 === KeyCode.DOWN;
    const leftKey = key2 === KeyCode.LEFT;
    let column2;
    let rowIndex;
    const { pageBounds, gos, visibleCols, pinnedRowModel } = this.beans;
    const { rowPinned } = focusedCell;
    if (upKey || downKey) {
      if (rowPinned && pinnedRowModel) {
        if (upKey) {
          rowIndex = 0;
        } else {
          rowIndex = rowPinned === "top" ? pinnedRowModel.getPinnedTopRowCount() - 1 : pinnedRowModel.getPinnedBottomRowCount() - 1;
        }
      } else {
        rowIndex = upKey ? pageBounds.getFirstRow() : pageBounds.getLastRow();
      }
      column2 = focusedCell.column;
    } else {
      const isRtl = gos.get("enableRtl");
      rowIndex = focusedCell.rowIndex;
      const allColumns = leftKey !== isRtl ? visibleCols.allCols : [...visibleCols.allCols].reverse();
      column2 = allColumns.find(
        (col) => this.isCellGoodToFocusOn({
          rowIndex,
          rowPinned: null,
          column: col
        })
      );
    }
    return column2 ? {
      rowIndex,
      rowPinned,
      column: column2
    } : null;
  }
  getNextCellToFocusWithoutCtrlPressed(key2, focusedCell) {
    let pointer = focusedCell;
    let finished = false;
    while (!finished) {
      switch (key2) {
        case KeyCode.UP:
          pointer = this.getCellAbove(pointer);
          break;
        case KeyCode.DOWN:
          pointer = this.getCellBelow(pointer);
          break;
        case KeyCode.RIGHT:
          pointer = this.gos.get("enableRtl") ? this.getCellToLeft(pointer) : this.getCellToRight(pointer);
          break;
        case KeyCode.LEFT:
          pointer = this.gos.get("enableRtl") ? this.getCellToRight(pointer) : this.getCellToLeft(pointer);
          break;
        default:
          pointer = null;
          _warn(8, { key: key2 });
          break;
      }
      if (pointer) {
        finished = this.isCellGoodToFocusOn(pointer);
      } else {
        finished = true;
      }
    }
    return pointer;
  }
  isCellGoodToFocusOn(gridCell) {
    const column2 = gridCell.column;
    let rowNode;
    const { pinnedRowModel, rowModel } = this.beans;
    switch (gridCell.rowPinned) {
      case "top":
        rowNode = pinnedRowModel?.getPinnedTopRow(gridCell.rowIndex);
        break;
      case "bottom":
        rowNode = pinnedRowModel?.getPinnedBottomRow(gridCell.rowIndex);
        break;
      default:
        rowNode = rowModel.getRow(gridCell.rowIndex);
        break;
    }
    if (!rowNode) {
      return false;
    }
    const suppressNavigable = this.isSuppressNavigable(column2, rowNode);
    return !suppressNavigable;
  }
  getCellToLeft(lastCell) {
    if (!lastCell) {
      return null;
    }
    const colToLeft = this.beans.visibleCols.getColBefore(lastCell.column);
    if (!colToLeft) {
      return null;
    }
    return {
      rowIndex: lastCell.rowIndex,
      column: colToLeft,
      rowPinned: lastCell.rowPinned
    };
  }
  getCellToRight(lastCell) {
    if (!lastCell) {
      return null;
    }
    const colToRight = this.beans.visibleCols.getColAfter(lastCell.column);
    if (!colToRight) {
      return null;
    }
    return {
      rowIndex: lastCell.rowIndex,
      column: colToRight,
      rowPinned: lastCell.rowPinned
    };
  }
  getCellBelow(lastCell) {
    if (!lastCell) {
      return null;
    }
    const adjustedLastCell = this.rowSpanSvc?.getCellEnd(lastCell) ?? lastCell;
    const rowBelow = _getRowBelow(this.beans, adjustedLastCell, true);
    if (rowBelow) {
      return {
        rowIndex: rowBelow.rowIndex,
        column: lastCell.column,
        rowPinned: rowBelow.rowPinned
      };
    }
    return null;
  }
  getCellAbove(lastCell) {
    if (!lastCell) {
      return null;
    }
    const adjustedLastCell = this.rowSpanSvc?.getCellStart(lastCell) ?? lastCell;
    const rowAbove = _getRowAbove(
      this.beans,
      {
        rowIndex: adjustedLastCell.rowIndex,
        rowPinned: adjustedLastCell.rowPinned
      },
      true
    );
    if (rowAbove) {
      return {
        rowIndex: rowAbove.rowIndex,
        column: lastCell.column,
        rowPinned: rowAbove.rowPinned
      };
    }
    return null;
  }
  getNextTabbedCell(gridCell, backwards) {
    if (backwards) {
      return this.getNextTabbedCellBackwards(gridCell);
    }
    return this.getNextTabbedCellForwards(gridCell);
  }
  getNextTabbedCellForwards(gridCell) {
    const { visibleCols, pagination } = this.beans;
    const displayedColumns = visibleCols.allCols;
    let newRowIndex = gridCell.rowIndex;
    let newFloating = gridCell.rowPinned;
    let newColumn = visibleCols.getColAfter(gridCell.column);
    if (!newColumn) {
      newColumn = displayedColumns[0];
      const rowBelow = _getRowBelow(this.beans, gridCell, true);
      if (_missing(rowBelow)) {
        return null;
      }
      if (!rowBelow.rowPinned && !(pagination?.isRowInPage(rowBelow.rowIndex) ?? true)) {
        return null;
      }
      newRowIndex = rowBelow ? rowBelow.rowIndex : null;
      newFloating = rowBelow ? rowBelow.rowPinned : null;
    }
    return { rowIndex: newRowIndex, column: newColumn, rowPinned: newFloating };
  }
  getNextTabbedCellBackwards(gridCell) {
    const { beans } = this;
    const { visibleCols, pagination } = beans;
    const displayedColumns = visibleCols.allCols;
    let newRowIndex = gridCell.rowIndex;
    let newFloating = gridCell.rowPinned;
    let newColumn = visibleCols.getColBefore(gridCell.column);
    if (!newColumn) {
      newColumn = _last(displayedColumns);
      const rowAbove = _getRowAbove(beans, { rowIndex: gridCell.rowIndex, rowPinned: gridCell.rowPinned }, true);
      if (_missing(rowAbove)) {
        return null;
      }
      if (!rowAbove.rowPinned && !(pagination?.isRowInPage(rowAbove.rowIndex) ?? true)) {
        return null;
      }
      newRowIndex = rowAbove ? rowAbove.rowIndex : null;
      newFloating = rowAbove ? rowAbove.rowPinned : null;
    }
    return { rowIndex: newRowIndex, column: newColumn, rowPinned: newFloating };
  }
  isSuppressNavigable(column2, rowNode) {
    const { suppressNavigable } = column2.colDef;
    if (typeof suppressNavigable === "boolean") {
      return suppressNavigable;
    }
    if (typeof suppressNavigable === "function") {
      const params = column2.createColumnFunctionCallbackParams(rowNode);
      const userFunc = suppressNavigable;
      return userFunc(params);
    }
    return false;
  }
};
function getFocusedCell(beans) {
  return beans.focusSvc.getFocusedCell();
}
function clearFocusedCell(beans) {
  return beans.focusSvc.clearFocusedCell();
}
function setFocusedCell(beans, rowIndex, colKey, rowPinned) {
  beans.focusSvc.setFocusedCell({ rowIndex, column: colKey, rowPinned, forceBrowserFocus: true });
}
function tabToNextCell(beans, event) {
  return beans.navigation?.tabToNextCell(false, event) ?? false;
}
function tabToPreviousCell(beans, event) {
  return beans.navigation?.tabToNextCell(true, event) ?? false;
}
function setFocusedHeader(beans, colKey, floatingFilter = false) {
  const headerPosition = beans.headerNavigation?.getHeaderPositionForColumn(colKey, floatingFilter);
  if (!headerPosition) {
    return;
  }
  beans.focusSvc.focusHeaderPosition({ headerPosition });
}
var EditModelService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "editModelSvc";
    this.edits = /* @__PURE__ */ new Map();
    this.cellValidations = new EditCellValidationModel();
    this.rowValidations = new EditRowValidationModel();
    this.suspendEdits = false;
  }
  suspend(suspend) {
    this.suspendEdits = suspend;
  }
  removeEdits({ rowNode, column: column2 }) {
    if (!this.hasEdits({ rowNode }) || !rowNode) {
      return;
    }
    const editRow = this.getEditRow(rowNode);
    if (column2) {
      editRow.delete(column2);
    } else {
      editRow.clear();
    }
    if (editRow.size === 0) {
      this.edits.delete(rowNode);
    }
  }
  getEditRow(rowNode, params = {}) {
    if (this.suspendEdits) {
      return void 0;
    }
    if (this.edits.size === 0) {
      return void 0;
    }
    const edits = rowNode && this.edits.get(rowNode);
    if (edits) {
      return edits;
    }
    if (params.checkSiblings) {
      const pinnedSibling = rowNode.pinnedSibling;
      if (pinnedSibling) {
        return this.getEditRow(pinnedSibling);
      }
    }
    return void 0;
  }
  getEditRowDataValue(rowNode, { checkSiblings } = {}) {
    if (!rowNode || this.edits.size === 0) {
      return void 0;
    }
    const editRow = this.getEditRow(rowNode);
    const pinnedSibling = rowNode.pinnedSibling;
    const siblingRow = checkSiblings && pinnedSibling && this.getEditRow(pinnedSibling);
    if (!editRow && !siblingRow) {
      return void 0;
    }
    const data2 = Object.assign({}, rowNode.data);
    const applyEdits = (edits, data22) => edits.forEach(({ pendingValue }, column2) => {
      if (pendingValue !== UNEDITED) {
        data22[column2.getColId()] = pendingValue;
      }
    });
    if (editRow) {
      applyEdits(editRow, data2);
    }
    if (siblingRow) {
      applyEdits(siblingRow, data2);
    }
    return data2;
  }
  getEdit(position, copy) {
    const edit = this._getEdit(position);
    return copy && edit ? { ...edit } : edit;
  }
  _getEdit(position) {
    if (this.suspendEdits) {
      return void 0;
    }
    if (this.edits.size === 0) {
      return void 0;
    }
    return position.rowNode && position.column && this.getEditRow(position.rowNode)?.get(position.column);
  }
  getEditMap(copy = true) {
    if (this.suspendEdits || this.edits.size === 0) {
      return /* @__PURE__ */ new Map();
    }
    if (!copy) {
      return this.edits;
    }
    const map2 = /* @__PURE__ */ new Map();
    this.edits.forEach((editRow, rowNode) => {
      const newEditRow = /* @__PURE__ */ new Map();
      editRow.forEach(
        ({ editorState: _, ...cellData }, column2) => (
          // Ensure we copy the cell data to avoid reference issues
          newEditRow.set(column2, { ...cellData })
        )
      );
      map2.set(rowNode, newEditRow);
    });
    return map2;
  }
  setEditMap(newEdits) {
    this.edits.clear();
    newEdits.forEach((editRow, rowNode) => {
      const newRow = /* @__PURE__ */ new Map();
      editRow.forEach(
        (cellData, column2) => (
          // Ensure we copy the cell data to avoid reference issues
          newRow.set(column2, { ...cellData })
        )
      );
      this.edits.set(rowNode, newRow);
    });
  }
  setEdit(position, edit) {
    (this.edits.size === 0 || !this.edits.has(position.rowNode)) && this.edits.set(position.rowNode, /* @__PURE__ */ new Map());
    const currentEdit = this._getEdit(position);
    const updatedEdit = Object.assign({
      editorState: {
        isCancelAfterEnd: void 0,
        isCancelBeforeStart: void 0
      },
      ...currentEdit,
      ...edit
    });
    this.getEditRow(position.rowNode).set(position.column, updatedEdit);
    return updatedEdit;
  }
  clearEditValue(position) {
    const { rowNode, column: column2 } = position;
    if (rowNode) {
      if (column2) {
        const edit = this._getEdit(position);
        if (edit) {
          edit.editorValue = void 0;
          edit.pendingValue = edit.sourceValue;
          edit.state = "changed";
        }
      } else {
        this.getEditRow(rowNode)?.forEach((cellData) => {
          cellData.editorValue = void 0;
          cellData.pendingValue = cellData.sourceValue;
          cellData.state = "changed";
        });
      }
    }
  }
  getState(position) {
    if (this.suspendEdits) {
      return void 0;
    }
    return this.getEdit(position)?.state;
  }
  getEditPositions(editMap) {
    if (this.suspendEdits || (editMap ?? this.edits).size === 0) {
      return [];
    }
    const positions = [];
    (editMap ?? this.edits).forEach((editRow, rowNode) => {
      for (const column2 of editRow.keys()) {
        const { editorState: _, ...rest } = editRow.get(column2);
        positions.push({
          rowNode,
          column: column2,
          ...rest
        });
      }
    });
    return positions;
  }
  hasRowEdits(rowNode, params) {
    if (this.suspendEdits) {
      return false;
    }
    if (this.edits.size === 0) {
      return false;
    }
    const rowEdits = this.getEditRow(rowNode, params);
    return !!rowEdits;
  }
  hasEdits(position = {}, params = {}) {
    if (this.suspendEdits) {
      return false;
    }
    if (this.edits.size === 0) {
      return false;
    }
    const { rowNode, column: column2 } = position;
    const { withOpenEditor } = params;
    if (rowNode) {
      const rowEdits = this.getEditRow(rowNode, params);
      if (!rowEdits) {
        return false;
      }
      if (column2) {
        if (withOpenEditor) {
          return this.getEdit(position)?.state === "editing";
        }
        return rowEdits.has(column2) ?? false;
      }
      if (rowEdits.size !== 0) {
        if (withOpenEditor) {
          return Array.from(rowEdits.values()).some(({ state }) => state === "editing");
        }
        return true;
      }
      return false;
    }
    if (withOpenEditor) {
      return this.getEditPositions().some(({ state }) => state === "editing");
    }
    return this.edits.size > 0;
  }
  start(position) {
    const map2 = this.getEditRow(position.rowNode) ?? /* @__PURE__ */ new Map();
    const { rowNode, column: column2 } = position;
    if (column2 && !map2.has(column2)) {
      map2.set(column2, {
        editorValue: void 0,
        pendingValue: UNEDITED,
        sourceValue: this.beans.valueSvc.getValue(column2, rowNode, false, "api"),
        state: "editing",
        editorState: {
          isCancelAfterEnd: void 0,
          isCancelBeforeStart: void 0
        }
      });
    }
    this.edits.set(rowNode, map2);
  }
  stop(position) {
    if (!this.hasEdits(position)) {
      return;
    }
    if (position) {
      this.removeEdits(position);
    } else {
      this.clear();
    }
  }
  clear() {
    for (const pendingRowEdits of this.edits.values()) {
      pendingRowEdits.clear();
    }
    this.edits.clear();
  }
  getCellValidationModel() {
    return this.cellValidations;
  }
  getRowValidationModel() {
    return this.rowValidations;
  }
  setCellValidationModel(model2) {
    this.cellValidations = model2;
  }
  setRowValidationModel(model2) {
    this.rowValidations = model2;
  }
  destroy() {
    super.destroy();
    this.clear();
  }
};
var EditCellValidationModel = class {
  constructor() {
    this.cellValidations = /* @__PURE__ */ new Map();
  }
  getCellValidation(position) {
    const { rowNode, column: column2 } = position || {};
    return this.cellValidations?.get(rowNode)?.get(column2);
  }
  hasCellValidation(position) {
    if (!position?.rowNode || !position.column) {
      return this.cellValidations.size > 0;
    }
    return !!this.getCellValidation(position);
  }
  setCellValidation(position, validation2) {
    const { rowNode, column: column2 } = position;
    if (!this.cellValidations.has(rowNode)) {
      this.cellValidations.set(rowNode, /* @__PURE__ */ new Map());
    }
    this.cellValidations.get(rowNode).set(column2, validation2);
  }
  clearCellValidation(position) {
    const { rowNode, column: column2 } = position;
    this.cellValidations.get(rowNode)?.delete(column2);
  }
  setCellValidationMap(validationMap) {
    this.cellValidations = validationMap;
  }
  getCellValidationMap() {
    return this.cellValidations;
  }
  clearCellValidationMap() {
    this.cellValidations.clear();
  }
};
var EditRowValidationModel = class {
  constructor() {
    this.rowValidations = /* @__PURE__ */ new Map();
  }
  getRowValidation(position) {
    const { rowNode } = position || {};
    return this.rowValidations.get(rowNode);
  }
  hasRowValidation(position) {
    if (!position?.rowNode) {
      return this.rowValidations.size > 0;
    }
    return !!this.getRowValidation(position);
  }
  setRowValidation({ rowNode }, rowValidation) {
    this.rowValidations.set(rowNode, rowValidation);
  }
  clearRowValidation({ rowNode }) {
    this.rowValidations.delete(rowNode);
  }
  setRowValidationMap(validationMap) {
    this.rowValidations = validationMap;
  }
  getRowValidationMap() {
    return this.rowValidations;
  }
  clearRowValidationMap() {
    this.rowValidations.clear();
  }
};
function _getRowCtrl(beans, inputs = {}) {
  const { rowIndex, rowId, rowCtrl, rowPinned } = inputs;
  if (rowCtrl) {
    return rowCtrl;
  }
  const { rowModel, rowRenderer } = beans;
  let { rowNode } = inputs;
  if (!rowNode) {
    if (rowId) {
      rowNode = _getRowById(beans, rowId, rowPinned);
    } else if (rowIndex != null) {
      rowNode = rowModel.getRow(rowIndex);
    }
  }
  return rowRenderer.getRowCtrls(rowNode ? [rowNode] : [])?.[0];
}
function _getCellCtrl(beans, inputs = {}) {
  const { cellCtrl, colId, columnId, column: column2 } = inputs;
  if (cellCtrl) {
    return cellCtrl;
  }
  const actualColumn = beans.colModel.getCol(colId ?? columnId ?? _getColId(column2));
  const rowCtrl = inputs.rowCtrl ?? _getRowCtrl(beans, inputs);
  const result2 = rowCtrl?.getCellCtrl(actualColumn) ?? void 0;
  if (result2) {
    return result2;
  }
  const rowNode = inputs.rowNode ?? rowCtrl?.rowNode;
  if (rowNode) {
    return beans.rowRenderer.getCellCtrls([rowNode], [actualColumn])?.[0];
  }
  return void 0;
}
function _stopEditing(beans) {
  const { editSvc } = beans;
  if (editSvc?.isBatchEditing()) {
    _destroyEditors(beans);
  } else {
    editSvc?.stopEditing(void 0, { source: "api" });
  }
}
function _addStopEditingWhenGridLosesFocus(bean, beans, viewports) {
  const { gos, popupSvc } = beans;
  if (!gos.get("stopEditingWhenCellsLoseFocus")) {
    return;
  }
  const focusOutListener = (event) => {
    const elementWithFocus = event.relatedTarget;
    if (_getTabIndex(elementWithFocus) === null) {
      _stopEditing(beans);
      return;
    }
    let clickInsideGrid = (
      // see if click came from inside the viewports
      viewports.some((viewport2) => viewport2.contains(elementWithFocus)) && // and also that it's not from a detail grid
      gos.isElementInThisInstance(elementWithFocus)
    );
    if (!clickInsideGrid) {
      clickInsideGrid = !!popupSvc && (popupSvc.getActivePopups().some((popup) => popup.contains(elementWithFocus)) || popupSvc.isElementWithinCustomPopup(elementWithFocus));
    }
    if (!clickInsideGrid) {
      _stopEditing(beans);
    }
  };
  for (const viewport2 of viewports) {
    bean.addManagedElementListeners(viewport2, { focusout: focusOutListener });
  }
}
function _getColId(column2) {
  if (!column2) {
    return void 0;
  }
  if (typeof column2 === "string") {
    return column2;
  }
  return column2.getColId();
}
var UNEDITED = Symbol("unedited");
function getCellEditorInstanceMap(beans, params = {}) {
  const res = [];
  const ctrls = beans.rowRenderer.getCellCtrls(params.rowNodes, params.columns);
  for (const ctrl of ctrls) {
    const cellEditor = ctrl.comp?.getCellEditor();
    if (cellEditor) {
      res.push({
        ctrl,
        editor: _unwrapUserComp(cellEditor)
      });
    }
  }
  return res;
}
var getCellEditorInstances = (beans, params = {}) => getCellEditorInstanceMap(beans, params).map((res) => res.editor);
function _setupEditors(beans, editingCells, position, key2, event, cellStartedEdit) {
  if (editingCells.length === 0 && position?.rowNode && position?.column) {
    _setupEditor(beans, position, { key: key2, event, cellStartedEdit });
  }
  const { valueSvc, editSvc, editModelSvc } = beans;
  const { rowNode, column: column2 } = position ?? {};
  for (const cellPosition of editingCells) {
    const { rowNode: cellRowNode, column: cellColumn } = cellPosition;
    const curCellCtrl = _getCellCtrl(beans, cellPosition);
    if (!curCellCtrl) {
      if (cellRowNode && cellColumn) {
        const oldValue = valueSvc.getValue(cellColumn, cellRowNode, void 0, "api");
        const isNewValueCell = position?.rowNode === cellRowNode && position?.column === cellColumn;
        const cellStartValue = isNewValueCell && key2 || void 0;
        const newValue = cellStartValue ?? editSvc?.getCellDataValue(cellPosition, false) ?? valueSvc.getValueForDisplay(cellColumn, cellRowNode)?.value ?? oldValue ?? UNEDITED;
        editModelSvc?.setEdit(cellPosition, {
          pendingValue: newValue,
          sourceValue: oldValue,
          state: "editing"
        });
      }
      continue;
    }
    const shouldStartEditing2 = cellStartedEdit && rowNode === curCellCtrl.rowNode && curCellCtrl.column === column2;
    _setupEditor(
      beans,
      { rowNode, column: curCellCtrl.column },
      {
        key: shouldStartEditing2 ? key2 : null,
        event: shouldStartEditing2 ? event : null,
        cellStartedEdit: shouldStartEditing2 && cellStartedEdit
      }
    );
  }
}
function _sourceAndPendingDiffer({
  pendingValue,
  sourceValue
}) {
  if (pendingValue === UNEDITED) {
    pendingValue = sourceValue;
  }
  return pendingValue !== sourceValue;
}
function _setupEditor(beans, position, params) {
  const enableGroupEditing = beans.gos.get("enableGroupEdit");
  const { key: key2, event, cellStartedEdit, silent } = params ?? {};
  const cellCtrl = _getCellCtrl(beans, position);
  const editorComp = cellCtrl?.comp?.getCellEditor();
  const editorParams = _createEditorParams(beans, position, key2, cellStartedEdit && !silent);
  const previousEdit = beans.editModelSvc?.getEdit(position);
  let newValue = editorParams.value;
  if (newValue === void 0) {
    newValue = previousEdit?.sourceValue;
  }
  beans.editModelSvc?.setEdit(position, {
    editorValue: newValue,
    state: "editing"
  });
  if (editorComp) {
    editorComp.refresh?.(editorParams);
    return;
  }
  const colDef = position.column.getColDef();
  const compDetails = _getCellEditorDetails(beans.userCompFactory, colDef, editorParams);
  const popup = compDetails?.popupFromSelector != null ? compDetails.popupFromSelector : !!colDef.cellEditorPopup;
  const popupLocation = compDetails?.popupPositionFromSelector != null ? compDetails.popupPositionFromSelector : colDef.cellEditorPopupPosition;
  checkAndPreventDefault(compDetails.params, event);
  if (cellCtrl) {
    cellCtrl.editCompDetails = compDetails;
    cellCtrl.onEditorAttachedFuncs.push(() => cellCtrl.rangeFeature?.unsetComp());
    cellCtrl.comp?.setEditDetails(compDetails, popup, popupLocation, beans.gos.get("reactiveCustomComponents"));
    cellCtrl?.rowCtrl?.refreshRow({ suppressFlash: true });
    const edit = beans.editModelSvc?.getEdit(position, true);
    if (!silent && !edit?.editorState?.cellStartedEditing) {
      beans.editSvc?.dispatchCellEvent(
        position,
        event,
        "cellEditingStarted",
        enableGroupEditing ? { value: newValue } : {}
      );
      beans.editModelSvc?.setEdit(position, { editorState: { cellStartedEditing: true } });
    }
  }
}
function _valueFromEditor(beans, cellEditor, params) {
  const noValueResult = { editorValueExists: false };
  if (_hasValidationRules(beans)) {
    const validationErrors = cellEditor.getValidationErrors?.();
    if ((validationErrors?.length ?? 0) > 0) {
      return noValueResult;
    }
  }
  if (params?.isCancelling) {
    return noValueResult;
  }
  if (params?.isStopping) {
    const isCancelAfterEnd = cellEditor?.isCancelAfterEnd?.();
    if (isCancelAfterEnd) {
      return { ...noValueResult, isCancelAfterEnd };
    }
  }
  const editorValue = cellEditor.getValue();
  return {
    editorValue,
    editorValueExists: true
  };
}
function _createEditorParams(beans, position, key2, cellStartedEdit) {
  const { valueSvc, gos, editSvc } = beans;
  const enableGroupEditing = beans.gos.get("enableGroupEdit");
  const cellCtrl = _getCellCtrl(beans, position);
  const rowIndex = position.rowNode?.rowIndex ?? void 0;
  const batchEdit = editSvc?.isBatchEditing();
  const agColumn = beans.colModel.getCol(position.column.getId());
  const { rowNode, column: column2 } = position;
  const editor = cellCtrl.comp?.getCellEditor();
  const cellDataValue = editSvc?.getCellDataValue(position, false);
  const initialNewValue = cellDataValue === void 0 ? editor ? _valueFromEditor(beans, editor)?.editorValue : void 0 : cellDataValue;
  const value2 = initialNewValue === UNEDITED ? valueSvc.getValueForDisplay(agColumn, rowNode)?.value : initialNewValue;
  return _addGridCommonParams(gos, {
    value: enableGroupEditing ? initialNewValue : value2,
    eventKey: key2 ?? null,
    column: column2,
    colDef: column2.getColDef(),
    rowIndex,
    node: rowNode,
    data: rowNode.data,
    cellStartedEdit: cellStartedEdit ?? false,
    onKeyDown: cellCtrl?.onKeyDown.bind(cellCtrl),
    stopEditing: (suppressNavigateAfterEdit) => {
      editSvc.stopEditing(position, { source: batchEdit ? "ui" : "api", suppressNavigateAfterEdit });
      _destroyEditor(beans, position);
    },
    eGridCell: cellCtrl?.eGui,
    parseValue: (newValue) => valueSvc.parseValue(agColumn, rowNode, newValue, cellCtrl?.value),
    formatValue: cellCtrl?.formatValue.bind(cellCtrl),
    validate: () => {
      editSvc?.validateEdit();
    }
  });
}
function _purgeUnchangedEdits(beans, includeEditing) {
  const { editModelSvc } = beans;
  editModelSvc?.getEditMap().forEach((editRow, rowNode) => {
    editRow.forEach((edit, column2) => {
      if (!includeEditing && (edit.state === "editing" || edit.pendingValue === UNEDITED)) {
        return;
      }
      if (!_sourceAndPendingDiffer(edit) && (edit.state !== "editing" || includeEditing)) {
        editModelSvc?.removeEdits({ rowNode, column: column2 });
      }
    });
  });
}
function _refreshEditorOnColDefChanged(beans, cellCtrl) {
  const editor = cellCtrl.comp?.getCellEditor();
  if (!editor?.refresh) {
    return;
  }
  const { eventKey, cellStartedEdit } = cellCtrl.editCompDetails.params;
  const { column: column2 } = cellCtrl;
  const editorParams = _createEditorParams(beans, cellCtrl, eventKey, cellStartedEdit);
  const colDef = column2.getColDef();
  const compDetails = _getCellEditorDetails(beans.userCompFactory, colDef, editorParams);
  editor.refresh(checkAndPreventDefault(compDetails.params, eventKey));
}
function checkAndPreventDefault(params, event) {
  if (event instanceof KeyboardEvent && params.column.getColDef().cellEditor === "agNumberCellEditor") {
    params.suppressPreventDefault = ["-", "+", ".", "e"].includes(event?.key ?? "") || params.suppressPreventDefault;
  } else {
    event?.preventDefault?.();
  }
  return params;
}
function _syncFromEditors(beans, params) {
  for (const cellId of beans.editModelSvc?.getEditPositions() ?? []) {
    const cellCtrl = _getCellCtrl(beans, cellId);
    if (!cellCtrl) {
      continue;
    }
    const editor = cellCtrl.comp?.getCellEditor();
    if (!editor) {
      continue;
    }
    const { editorValue, editorValueExists, isCancelAfterEnd } = _valueFromEditor(beans, editor, params);
    if (isCancelAfterEnd) {
      beans.editModelSvc?.setEdit(cellId, { editorState: { isCancelAfterEnd } });
    }
    _syncFromEditor(beans, cellId, editorValue, void 0, !editorValueExists, params);
  }
}
function _syncFromEditor(beans, position, editorValue, _source, valueSameAsSource, params) {
  const { editModelSvc, valueSvc } = beans;
  if (!editModelSvc) {
    return;
  }
  const { rowNode, column: column2 } = position;
  if (!(rowNode && column2)) {
    return;
  }
  let edit = editModelSvc.getEdit(position, true);
  if (!edit?.sourceValue) {
    edit = editModelSvc.setEdit(position, {
      sourceValue: valueSvc.getValue(column2, rowNode, void 0, "api"),
      pendingValue: edit ? edit.editorValue : UNEDITED
    });
  }
  editModelSvc.setEdit(position, {
    editorValue: valueSameAsSource ? edit.sourceValue : editorValue
  });
  if (params?.persist) {
    _persistEditorValue(beans, position);
  }
}
function _persistEditorValue(beans, position) {
  const { editModelSvc } = beans;
  const edit = editModelSvc?.getEdit(position, true);
  editModelSvc?.setEdit(position, {
    pendingValue: edit?.editorValue
  });
}
function _destroyEditors(beans, edits, params) {
  if (!edits) {
    edits = beans.editModelSvc?.getEditPositions();
  }
  for (const cellPosition of edits ?? []) {
    _destroyEditor(beans, cellPosition, params);
  }
}
function _destroyEditor(beans, position, params) {
  const enableGroupEditing = beans.gos.get("enableGroupEdit");
  const { editModelSvc } = beans;
  const cellCtrl = _getCellCtrl(beans, position);
  const edit = editModelSvc?.getEdit(position, true);
  if (!cellCtrl) {
    if (edit) {
      editModelSvc?.setEdit(position, { state: "changed" });
    }
    return;
  }
  const { comp } = cellCtrl;
  if (comp && !comp.getCellEditor()) {
    cellCtrl?.refreshCell();
    if (edit) {
      editModelSvc?.setEdit(position, { state: "changed" });
      const args2 = enableGroupEditing ? groupEditOverrides(params, edit) : {
        valueChanged: false,
        newValue: void 0,
        oldValue: edit.sourceValue
      };
      dispatchEditingStopped(beans, position, args2, params);
    }
    return;
  }
  if (_hasValidationRules(beans)) {
    const errorMessages = comp?.getCellEditor()?.getValidationErrors?.();
    const cellValidationModel = editModelSvc?.getCellValidationModel();
    if (errorMessages?.length) {
      cellValidationModel?.setCellValidation(position, { errorMessages });
    } else {
      cellValidationModel?.clearCellValidation(position);
    }
  }
  editModelSvc?.setEdit(position, { state: "changed" });
  comp?.setEditDetails();
  comp?.refreshEditStyles(false, false);
  cellCtrl?.refreshCell({ force: true, suppressFlash: true });
  const latest2 = editModelSvc?.getEdit(position);
  if (latest2 && latest2.state === "changed") {
    const args2 = enableGroupEditing ? groupEditOverrides(params, latest2) : {
      valueChanged: _sourceAndPendingDiffer(latest2) && !params?.cancel,
      newValue: params?.cancel || latest2.editorState.isCancelAfterEnd ? void 0 : latest2?.editorValue ?? edit?.pendingValue,
      oldValue: latest2?.sourceValue
    };
    dispatchEditingStopped(beans, position, args2, params);
  }
}
function groupEditOverrides(params, latest2) {
  return params?.cancel ? {
    valueChanged: false,
    oldValue: latest2.sourceValue,
    newValue: void 0,
    value: latest2.sourceValue
  } : {
    valueChanged: false,
    oldValue: latest2.sourceValue,
    newValue: latest2.pendingValue,
    value: latest2.sourceValue
  };
}
function dispatchEditingStopped(beans, position, args2, { silent, event } = {}) {
  const { editSvc, editModelSvc } = beans;
  const latest2 = editModelSvc?.getEdit(position);
  const { editorState } = latest2 || {};
  const { isCancelBeforeStart } = editorState || {};
  if (!silent && !isCancelBeforeStart) {
    editSvc?.dispatchCellEvent(position, event, "cellEditingStopped", args2);
    editModelSvc?.setEdit(position, { editorState: { cellStoppedEditing: true } });
  }
}
function _hasValidationRules(beans) {
  const { gos, colModel } = beans;
  const getFullRowEditValidationErrors = !!gos.get("getFullRowEditValidationErrors");
  const columnsHaveRules = colModel.getColumnDefs()?.filter((c2) => c2.editable).some(({ cellEditorParams }) => {
    const { minLength, maxLength, getValidationErrors, min: min2, max: max2 } = cellEditorParams || {};
    return minLength !== void 0 || maxLength !== void 0 || getValidationErrors !== void 0 || min2 !== void 0 || max2 !== void 0;
  });
  const editorsHaveRules = beans.gridApi.getCellEditorInstances().some((editor) => editor.getValidationElement || editor.getValidationErrors);
  return columnsHaveRules || getFullRowEditValidationErrors || editorsHaveRules;
}
function _populateModelValidationErrors(beans, force) {
  if (!(force || _hasValidationRules(beans))) {
    return;
  }
  const mappedEditors = getCellEditorInstanceMap(beans);
  const cellValidationModel = new EditCellValidationModel();
  const { ariaAnnounce, localeSvc, editModelSvc, gos } = beans;
  const includeRows = gos.get("editType") === "fullRow";
  const translate = _getLocaleTextFunc(localeSvc);
  const ariaValidationErrorPrefix = translate("ariaValidationErrorPrefix", "Cell Editor Validation");
  for (const mappedEditor of mappedEditors) {
    const { ctrl, editor } = mappedEditor;
    const { rowNode, column: column2 } = ctrl;
    const errorMessages = editor.getValidationErrors?.() ?? [];
    const el = editor.getValidationElement?.(false) || !editor.isPopup?.() && ctrl.eGui;
    if (el) {
      const isInvalid = errorMessages != null && errorMessages.length > 0;
      const invalidMessage = isInvalid ? errorMessages.join(". ") : "";
      _setAriaInvalid(el, isInvalid);
      if (isInvalid) {
        ariaAnnounce.announceValue(`${ariaValidationErrorPrefix} ${errorMessages}`, "editorValidation");
      }
      if (el instanceof HTMLInputElement) {
        el.setCustomValidity(invalidMessage);
      } else {
        el.classList.toggle("invalid", isInvalid);
      }
    }
    if (errorMessages?.length > 0) {
      cellValidationModel.setCellValidation(
        {
          rowNode,
          column: column2
        },
        {
          errorMessages
        }
      );
    }
  }
  _syncFromEditors(beans, { persist: false });
  editModelSvc?.setCellValidationModel(cellValidationModel);
  const rowCtrlSet = /* @__PURE__ */ new Set();
  for (const { ctrl } of mappedEditors) {
    rowCtrlSet.add(ctrl.rowCtrl);
  }
  if (includeRows) {
    const rowValidations = _generateRowValidationErrors(beans);
    editModelSvc?.setRowValidationModel(rowValidations);
  }
  for (const rowCtrl of rowCtrlSet.values()) {
    rowCtrl.rowEditStyleFeature?.applyRowStyles();
    for (const cellCtrl of rowCtrl.getAllCellCtrls()) {
      cellCtrl.tooltipFeature?.refreshTooltip(true);
      cellCtrl.editorTooltipFeature?.refreshTooltip(true);
      cellCtrl.editStyleFeature?.applyCellStyles?.();
    }
  }
}
var _generateRowValidationErrors = (beans) => {
  const rowValidationModel = new EditRowValidationModel();
  const getFullRowEditValidationErrors = beans.gos.get("getFullRowEditValidationErrors");
  const editMap = beans.editModelSvc?.getEditMap();
  if (!editMap) {
    return rowValidationModel;
  }
  for (const rowNode of editMap.keys()) {
    const rowEditMap = editMap.get(rowNode);
    if (!rowEditMap) {
      continue;
    }
    const editorsState = [];
    const { rowIndex, rowPinned } = rowNode;
    for (const column2 of rowEditMap.keys()) {
      const editValue = rowEditMap.get(column2);
      if (!editValue) {
        continue;
      }
      const { editorValue, pendingValue, sourceValue } = editValue;
      const newValue = editorValue ?? (pendingValue === UNEDITED ? void 0 : pendingValue) ?? sourceValue;
      editorsState.push({
        column: column2,
        colId: column2.getColId(),
        rowIndex,
        rowPinned,
        oldValue: sourceValue,
        newValue
      });
    }
    const errorMessages = getFullRowEditValidationErrors?.({ editorsState }) ?? [];
    if (errorMessages.length > 0) {
      rowValidationModel.setRowValidation(
        {
          rowNode
        },
        { errorMessages }
      );
    }
  }
  return rowValidationModel;
};
function _validateEdit(beans) {
  _populateModelValidationErrors(beans, true);
  const map2 = beans.editModelSvc?.getCellValidationModel().getCellValidationMap();
  if (!map2) {
    return null;
  }
  const validations = [];
  map2.forEach((rowValidations, rowNode) => {
    rowValidations.forEach(({ errorMessages }, column2) => {
      validations.push({
        column: column2,
        rowIndex: rowNode.rowIndex,
        rowPinned: rowNode.rowPinned,
        messages: errorMessages ?? null
      });
    });
  });
  return validations;
}
function _createCellEvent(beans, domEvent, eventType, { rowNode, column: column2 }, value2) {
  const event = _addGridCommonParams(beans.gos, {
    type: eventType,
    node: rowNode,
    data: rowNode.data,
    value: value2,
    column: column2,
    colDef: column2.getColDef(),
    rowPinned: rowNode.rowPinned,
    event: domEvent,
    rowIndex: rowNode.rowIndex
  });
  return event;
}
function _isDeleteKey(key2, alwaysReturnFalseOnBackspace = false) {
  if (key2 === KeyCode.DELETE) {
    return true;
  }
  if (!alwaysReturnFalseOnBackspace && key2 === KeyCode.BACKSPACE) {
    return _isMacOsUserAgent();
  }
  return false;
}
var CellKeyboardListenerFeature = class extends BeanStub {
  constructor(cellCtrl, beans, rowNode, rowCtrl) {
    super();
    this.cellCtrl = cellCtrl;
    this.rowNode = rowNode;
    this.rowCtrl = rowCtrl;
    this.beans = beans;
  }
  init() {
    this.eGui = this.cellCtrl.eGui;
  }
  onKeyDown(event) {
    const key2 = event.key;
    switch (key2) {
      case KeyCode.ENTER:
        this.onEnterKeyDown(event);
        break;
      case KeyCode.F2:
        this.onF2KeyDown(event);
        break;
      case KeyCode.ESCAPE:
        this.onEscapeKeyDown(event);
        break;
      case KeyCode.TAB:
        this.onTabKeyDown(event);
        break;
      case KeyCode.BACKSPACE:
      case KeyCode.DELETE:
        this.onBackspaceOrDeleteKeyDown(key2, event);
        break;
      case KeyCode.DOWN:
      case KeyCode.UP:
      case KeyCode.RIGHT:
      case KeyCode.LEFT:
        this.onNavigationKeyDown(event, key2);
        break;
    }
  }
  onNavigationKeyDown(event, key2) {
    const { cellCtrl, beans } = this;
    if (beans.editSvc?.isEditing(cellCtrl, { withOpenEditor: true })) {
      return;
    }
    if (event.shiftKey && cellCtrl.isRangeSelectionEnabled()) {
      this.onShiftRangeSelect(event);
    } else {
      const currentCellPosition = cellCtrl.getFocusedCellPosition();
      beans.navigation?.navigateToNextCell(event, key2, currentCellPosition, true);
    }
    event.preventDefault();
  }
  onShiftRangeSelect(event) {
    const { rangeSvc, navigation: navigation2 } = this.beans;
    if (!rangeSvc) {
      return;
    }
    const endCell = rangeSvc.extendLatestRangeInDirection(event);
    if (!endCell) {
      return;
    }
    if (event.key === KeyCode.LEFT || event.key === KeyCode.RIGHT) {
      navigation2?.ensureColumnVisible(endCell.column);
    } else {
      navigation2?.ensureRowVisible(endCell.rowIndex);
    }
  }
  onTabKeyDown(event) {
    this.beans.navigation?.onTabKeyDown(this.cellCtrl, event);
  }
  onBackspaceOrDeleteKeyDown(key2, event) {
    const { cellCtrl, beans, rowNode } = this;
    const { gos, rangeSvc, eventSvc, editSvc } = beans;
    eventSvc.dispatchEvent({ type: "keyShortcutChangedCellStart" });
    if (_isDeleteKey(key2, gos.get("enableCellEditingOnBackspace")) && !editSvc?.isEditing(cellCtrl, { withOpenEditor: true })) {
      if (rangeSvc && _isCellSelectionEnabled(gos)) {
        rangeSvc.clearCellRangeCellValues({ dispatchWrapperEvents: true, wrapperEventSource: "deleteKey" });
      } else if (cellCtrl.isCellEditable()) {
        const { column: column2 } = cellCtrl;
        const emptyValue = this.beans.valueSvc.getDeleteValue(column2, rowNode);
        rowNode.setDataValue(column2, emptyValue, "cellClear");
      }
    } else if (!editSvc?.isEditing(cellCtrl, { withOpenEditor: true })) {
      beans.editSvc?.startEditing(cellCtrl, { startedEdit: true, event });
    }
    eventSvc.dispatchEvent({ type: "keyShortcutChangedCellEnd" });
  }
  onEnterKeyDown(event) {
    const { cellCtrl, beans } = this;
    const { editSvc, navigation: navigation2 } = beans;
    const cellEditing = editSvc?.isEditing(cellCtrl, { withOpenEditor: true });
    const rowNode = cellCtrl.rowNode;
    const rowEditing = editSvc?.isRowEditing(rowNode, { withOpenEditor: true });
    const startEditingAction = (cellCtrl2) => {
      const started = editSvc?.startEditing(cellCtrl2, {
        startedEdit: true,
        event,
        source: "edit"
      });
      if (started) {
        event.preventDefault();
      }
    };
    if (cellEditing || rowEditing) {
      if (this.isCtrlEnter(event)) {
        editSvc?.applyBulkEdit(cellCtrl, beans?.rangeSvc?.getCellRanges() || []);
        return;
      }
      _populateModelValidationErrors(beans);
      if (editSvc?.checkNavWithValidation(void 0, event) === "block-stop") {
        return;
      }
      if (editSvc?.isEditing(cellCtrl, { withOpenEditor: true })) {
        editSvc?.stopEditing(cellCtrl, {
          event,
          source: "edit"
        });
      } else if (rowEditing && !cellCtrl.isCellEditable()) {
        editSvc?.stopEditing({ rowNode }, { event, source: "edit" });
      } else {
        startEditingAction(cellCtrl);
      }
    } else if (beans.gos.get("enterNavigatesVertically")) {
      const key2 = event.shiftKey ? KeyCode.UP : KeyCode.DOWN;
      navigation2?.navigateToNextCell(null, key2, cellCtrl.cellPosition, false);
    } else {
      if (editSvc?.hasValidationErrors()) {
        return;
      }
      if (editSvc?.hasValidationErrors(cellCtrl)) {
        editSvc.revertSingleCellEdit(cellCtrl, true);
      }
      startEditingAction(cellCtrl);
    }
  }
  isCtrlEnter(e) {
    return (e.ctrlKey || e.metaKey) && e.key === KeyCode.ENTER;
  }
  onF2KeyDown(event) {
    const {
      cellCtrl,
      beans: { editSvc }
    } = this;
    const editing = editSvc?.isEditing();
    if (editing) {
      _populateModelValidationErrors(this.beans);
      if (editSvc?.checkNavWithValidation(void 0, event) === "block-stop") {
        return;
      }
    }
    editSvc?.startEditing(cellCtrl, { startedEdit: true, event });
  }
  onEscapeKeyDown(event) {
    const {
      cellCtrl,
      beans: { editSvc }
    } = this;
    if (editSvc?.checkNavWithValidation(cellCtrl, event) === "block-stop") {
      editSvc.revertSingleCellEdit(cellCtrl);
    }
    editSvc?.stopEditing(cellCtrl, {
      event,
      cancel: true
    });
  }
  processCharacter(event) {
    const eventTarget = event.target;
    const eventOnChildComponent = eventTarget !== this.eGui;
    const {
      beans: { editSvc },
      cellCtrl
    } = this;
    if (eventOnChildComponent) {
      return;
    }
    if (editSvc?.isEditing(cellCtrl, { withOpenEditor: true })) {
      return;
    }
    const key2 = event.key;
    if (key2 === KeyCode.SPACE) {
      this.onSpaceKeyDown(event);
    } else if (editSvc?.isCellEditable(cellCtrl, "ui")) {
      if (editSvc?.hasValidationErrors() && !editSvc?.hasValidationErrors(cellCtrl)) {
        return;
      }
      editSvc?.startEditing(cellCtrl, { startedEdit: true, event, source: "api" });
      const compDetails = cellCtrl.editCompDetails;
      const shouldPreventDefault = !compDetails?.params?.suppressPreventDefault;
      if (shouldPreventDefault) {
        event.preventDefault();
      }
    }
  }
  onSpaceKeyDown(event) {
    const { gos, editSvc } = this.beans;
    const { rowNode } = this.cellCtrl;
    if (!editSvc?.isEditing(this.cellCtrl, { withOpenEditor: true }) && _isRowSelection(gos)) {
      this.beans.selectionSvc?.handleSelectionEvent(event, rowNode, "spaceKey");
    }
    event.preventDefault();
  }
};
var CellMouseListenerFeature = class extends BeanStub {
  constructor(cellCtrl, beans, column2) {
    super();
    this.cellCtrl = cellCtrl;
    this.column = column2;
    this.beans = beans;
  }
  onMouseEvent(eventName, mouseEvent) {
    if (_isStopPropagationForAgGrid(mouseEvent)) {
      return;
    }
    switch (eventName) {
      case "click":
        this.onCellClicked(mouseEvent);
        break;
      case "mousedown":
      case "touchstart":
        this.onMouseDown(mouseEvent);
        break;
      case "dblclick":
        this.onCellDoubleClicked(mouseEvent);
        break;
      case "mouseout":
        this.onMouseOut(mouseEvent);
        break;
      case "mouseover":
        this.onMouseOver(mouseEvent);
        break;
    }
  }
  onCellClicked(event) {
    if (this.beans.touchSvc?.handleCellDoubleClick(this, event)) {
      return;
    }
    const { eventSvc, rangeSvc, editSvc, editModelSvc, frameworkOverrides, gos } = this.beans;
    const isMultiKey = event.ctrlKey || event.metaKey;
    const { cellCtrl } = this;
    const { column: column2, cellPosition, rowNode } = cellCtrl;
    const suppressMouseEvent2 = _suppressCellMouseEvent(gos, column2, rowNode, event);
    if (rangeSvc && isMultiKey && !suppressMouseEvent2) {
      if (rangeSvc.getCellRangeCount(cellPosition) > 1) {
        rangeSvc.intersectLastRange(true);
      }
    }
    const cellClickedEvent = cellCtrl.createEvent(event, "cellClicked");
    cellClickedEvent.isEventHandlingSuppressed = suppressMouseEvent2;
    eventSvc.dispatchEvent(cellClickedEvent);
    const colDef = column2.getColDef();
    if (colDef.onCellClicked) {
      window.setTimeout(() => {
        frameworkOverrides.wrapOutgoing(() => {
          colDef.onCellClicked(cellClickedEvent);
        });
      }, 0);
    }
    if (suppressMouseEvent2) {
      return;
    }
    if (editModelSvc?.getState(cellCtrl) !== "editing") {
      const editing = editSvc?.isEditing();
      const cellValidations = editModelSvc?.getCellValidationModel().getCellValidationMap().size ?? 0;
      const rowValidations = editModelSvc?.getRowValidationModel().getRowValidationMap().size ?? 0;
      if (editing && (cellValidations > 0 || rowValidations > 0)) {
        return;
      }
      if (editSvc?.shouldStartEditing(cellCtrl, event)) {
        editSvc?.startEditing(cellCtrl, { event });
      } else if (editSvc?.shouldStopEditing(cellCtrl, event)) {
        if (this.beans.gos.get("editType") === "fullRow") {
          editSvc?.stopEditing(cellCtrl, {
            event,
            source: "edit"
          });
        } else {
          editSvc?.stopEditing(void 0, {
            event,
            source: "edit"
          });
        }
      }
    }
  }
  onCellDoubleClicked(event) {
    const { column: column2, beans, cellCtrl } = this;
    const { eventSvc, frameworkOverrides, editSvc, editModelSvc, gos } = beans;
    const suppressMouseEvent2 = _suppressCellMouseEvent(gos, cellCtrl.column, cellCtrl.rowNode, event);
    const colDef = column2.getColDef();
    const cellDoubleClickedEvent = cellCtrl.createEvent(
      event,
      "cellDoubleClicked"
    );
    cellDoubleClickedEvent.isEventHandlingSuppressed = suppressMouseEvent2;
    eventSvc.dispatchEvent(cellDoubleClickedEvent);
    if (typeof colDef.onCellDoubleClicked === "function") {
      window.setTimeout(() => {
        frameworkOverrides.wrapOutgoing(() => {
          colDef.onCellDoubleClicked(cellDoubleClickedEvent);
        });
      }, 0);
    }
    if (suppressMouseEvent2) {
      return;
    }
    if (editSvc?.shouldStartEditing(cellCtrl, event) && editModelSvc?.getState(cellCtrl) !== "editing") {
      const editing = editSvc?.isEditing();
      const cellValidations = editModelSvc?.getCellValidationModel().getCellValidationMap().size ?? 0;
      const rowValidations = editModelSvc?.getRowValidationModel().getRowValidationMap().size ?? 0;
      if (editing && (cellValidations > 0 || rowValidations > 0)) {
        return;
      }
      editSvc?.startEditing(cellCtrl, { event });
    }
  }
  onMouseDown(mouseEvent) {
    const { ctrlKey, metaKey, shiftKey } = mouseEvent;
    const target = mouseEvent.target;
    const { cellCtrl, beans } = this;
    const { eventSvc, rangeSvc, rowNumbersSvc, focusSvc, gos, editSvc } = beans;
    const { column: column2, rowNode, cellPosition } = cellCtrl;
    const suppressMouseEvent2 = _suppressCellMouseEvent(gos, column2, rowNode, mouseEvent);
    const fireMouseDownEvent = () => {
      const cellMouseDownEvent = cellCtrl.createEvent(mouseEvent, "cellMouseDown");
      cellMouseDownEvent.isEventHandlingSuppressed = suppressMouseEvent2;
      eventSvc.dispatchEvent(cellMouseDownEvent);
    };
    if (suppressMouseEvent2) {
      fireMouseDownEvent();
      return;
    }
    if (this.isRightClickInExistingRange(mouseEvent)) {
      return;
    }
    const hasRanges = rangeSvc && !rangeSvc.isEmpty();
    const containsWidget = this.containsWidget(target);
    const isRowNumberColumn = isRowNumberCol(column2);
    if (rowNumbersSvc && isRowNumberColumn && !rowNumbersSvc.handleMouseDownOnCell(cellPosition, mouseEvent)) {
      if (rangeSvc) {
        mouseEvent.preventDefault();
      }
      mouseEvent.stopImmediatePropagation();
      return;
    }
    if (!shiftKey || !hasRanges) {
      const editing = editSvc?.isEditing(cellCtrl);
      const isEnableCellTextSelection = gos.get("enableCellTextSelection");
      const shouldFocus = isEnableCellTextSelection && mouseEvent.defaultPrevented;
      const forceBrowserFocus = (_isBrowserSafari() || shouldFocus) && !editing && !_isFocusableFormField(target) && !containsWidget;
      cellCtrl.focusCell(forceBrowserFocus, mouseEvent);
    }
    if (shiftKey && hasRanges && !focusSvc.isCellFocused(cellPosition)) {
      mouseEvent.preventDefault();
      const focusedCell = focusSvc.getFocusedCell();
      if (focusedCell) {
        const { column: column22, rowIndex, rowPinned } = focusedCell;
        if (editSvc?.isEditing(focusedCell)) {
          editSvc?.stopEditing(focusedCell);
        }
        focusSvc.setFocusedCell({
          column: column22,
          rowIndex,
          rowPinned,
          forceBrowserFocus: true,
          preventScrollOnBrowserFocus: true,
          sourceEvent: mouseEvent
        });
      }
    }
    if (containsWidget) {
      return;
    }
    if (rangeSvc) {
      if (isRowNumberColumn) {
        mouseEvent.preventDefault();
      }
      const hasRightClickedOnRowNumber = _interpretAsRightClick(beans, mouseEvent) && isRowNumberColumn;
      if (shiftKey) {
        rangeSvc.extendLatestRangeToCell(cellPosition);
      } else if (!hasRightClickedOnRowNumber) {
        const isMultiKey = ctrlKey || metaKey;
        rangeSvc.setRangeToCell(cellPosition, isMultiKey);
      }
    }
    fireMouseDownEvent();
  }
  isRightClickInExistingRange(mouseEvent) {
    const { rangeSvc } = this.beans;
    if (rangeSvc) {
      const cellInRange = rangeSvc.isCellInAnyRange(this.cellCtrl.cellPosition);
      const isRightClick = _interpretAsRightClick(this.beans, mouseEvent);
      if (cellInRange && isRightClick) {
        return true;
      }
    }
    return false;
  }
  containsWidget(target) {
    return _isElementChildOfClass(target, "ag-selection-checkbox", 3) || _isElementChildOfClass(target, "ag-drag-handle", 3);
  }
  onMouseOut(mouseEvent) {
    if (this.mouseStayingInsideCell(mouseEvent)) {
      return;
    }
    const { eventSvc, colHover } = this.beans;
    eventSvc.dispatchEvent(this.cellCtrl.createEvent(mouseEvent, "cellMouseOut"));
    colHover?.clearMouseOver();
  }
  onMouseOver(mouseEvent) {
    if (this.mouseStayingInsideCell(mouseEvent)) {
      return;
    }
    const { eventSvc, colHover } = this.beans;
    eventSvc.dispatchEvent(this.cellCtrl.createEvent(mouseEvent, "cellMouseOver"));
    colHover?.setMouseOver([this.column]);
  }
  mouseStayingInsideCell(e) {
    if (!e.target || !e.relatedTarget) {
      return false;
    }
    const eCell = this.cellCtrl.eGui;
    const cellContainsTarget = eCell.contains(e.target);
    const cellContainsRelatedTarget = eCell.contains(e.relatedTarget);
    return cellContainsTarget && cellContainsRelatedTarget;
  }
};
var CellPositionFeature = class extends BeanStub {
  constructor(cellCtrl, beans) {
    super();
    this.cellCtrl = cellCtrl;
    this.beans = beans;
    this.column = cellCtrl.column;
    this.rowNode = cellCtrl.rowNode;
  }
  setupRowSpan() {
    this.rowSpan = this.column.getRowSpan(this.rowNode);
    this.addManagedListeners(this.beans.eventSvc, { newColumnsLoaded: () => this.onNewColumnsLoaded() });
  }
  init() {
    this.eSetLeft = this.cellCtrl.getRootElement();
    this.eContent = this.cellCtrl.eGui;
    const cellSpan = this.cellCtrl.getCellSpan();
    if (!cellSpan) {
      this.setupColSpan();
      this.setupRowSpan();
    }
    this.onLeftChanged();
    this.onWidthChanged();
    if (!cellSpan) {
      this._legacyApplyRowSpan();
    }
    if (cellSpan) {
      const refreshSpanHeight = this.refreshSpanHeight.bind(this, cellSpan);
      refreshSpanHeight();
      this.addManagedListeners(this.beans.eventSvc, {
        paginationChanged: refreshSpanHeight,
        recalculateRowBounds: refreshSpanHeight,
        pinnedHeightChanged: refreshSpanHeight
      });
    }
  }
  refreshSpanHeight(cellSpan) {
    const spanHeight = cellSpan.getCellHeight();
    if (spanHeight != null) {
      this.eContent.style.height = `${spanHeight}px`;
    }
  }
  onNewColumnsLoaded() {
    const rowSpan = this.column.getRowSpan(this.rowNode);
    if (this.rowSpan === rowSpan) {
      return;
    }
    this.rowSpan = rowSpan;
    this._legacyApplyRowSpan(true);
  }
  onDisplayColumnsChanged() {
    const colsSpanning = this.getColSpanningList();
    if (!_areEqual(this.colsSpanning, colsSpanning)) {
      this.colsSpanning = colsSpanning;
      this.onWidthChanged();
      this.onLeftChanged();
    }
  }
  setupColSpan() {
    if (this.column.getColDef().colSpan == null) {
      return;
    }
    this.colsSpanning = this.getColSpanningList();
    this.addManagedListeners(this.beans.eventSvc, {
      // because we are col spanning, a reorder of the cols can change what cols we are spanning over
      displayedColumnsChanged: this.onDisplayColumnsChanged.bind(this),
      // because we are spanning over multiple cols, we check for width any time any cols width changes.
      // this is expensive - really we should be explicitly checking only the cols we are spanning over
      // instead of every col, however it would be tricky code to track the cols we are spanning over, so
      // because hardly anyone will be using colSpan, am favouring this easier way for more maintainable code.
      displayedColumnsWidthChanged: this.onWidthChanged.bind(this)
    });
  }
  onWidthChanged() {
    if (!this.eContent) {
      return;
    }
    const width = this.getCellWidth();
    this.eContent.style.width = `${width}px`;
  }
  getCellWidth() {
    if (!this.colsSpanning) {
      return this.column.getActualWidth();
    }
    return this.colsSpanning.reduce((width, col) => width + col.getActualWidth(), 0);
  }
  getColSpanningList() {
    const { column: column2, rowNode } = this;
    const colSpan = column2.getColSpan(rowNode);
    const colsSpanning = [];
    if (colSpan === 1) {
      colsSpanning.push(column2);
    } else {
      let pointer = column2;
      const pinned = column2.getPinned();
      for (let i2 = 0; pointer && i2 < colSpan; i2++) {
        colsSpanning.push(pointer);
        pointer = this.beans.visibleCols.getColAfter(pointer);
        if (!pointer || _missing(pointer)) {
          break;
        }
        if (pinned !== pointer.getPinned()) {
          break;
        }
      }
    }
    return colsSpanning;
  }
  onLeftChanged() {
    if (!this.eSetLeft) {
      return;
    }
    const left2 = this.modifyLeftForPrintLayout(this.getCellLeft());
    this.eSetLeft.style.left = left2 + "px";
  }
  getCellLeft() {
    let mostLeftCol;
    if (this.beans.gos.get("enableRtl") && this.colsSpanning) {
      mostLeftCol = _last(this.colsSpanning);
    } else {
      mostLeftCol = this.column;
    }
    return mostLeftCol.getLeft();
  }
  modifyLeftForPrintLayout(leftPosition) {
    if (!this.cellCtrl.printLayout || this.column.getPinned() === "left") {
      return leftPosition;
    }
    const { visibleCols } = this.beans;
    const leftWidth = visibleCols.getColsLeftWidth();
    if (this.column.getPinned() === "right") {
      const bodyWidth = visibleCols.bodyWidth;
      return leftWidth + bodyWidth + (leftPosition || 0);
    }
    return leftWidth + (leftPosition || 0);
  }
  _legacyApplyRowSpan(force) {
    if (this.rowSpan === 1 && !force) {
      return;
    }
    const singleRowHeight = _getRowHeightAsNumber(this.beans);
    const totalRowHeight = singleRowHeight * this.rowSpan;
    this.eContent.style.height = `${totalRowHeight}px`;
    this.eContent.style.zIndex = "1";
  }
  // overriding to make public, as we don't dispose this bean via context
  destroy() {
    super.destroy();
  }
};
var CSS_CELL = "ag-cell";
var CSS_AUTO_HEIGHT = "ag-cell-auto-height";
var CSS_NORMAL_HEIGHT = "ag-cell-normal-height";
var CSS_CELL_FOCUS = "ag-cell-focus";
var CSS_CELL_FIRST_RIGHT_PINNED = "ag-cell-first-right-pinned";
var CSS_CELL_LAST_LEFT_PINNED = "ag-cell-last-left-pinned";
var CSS_CELL_NOT_INLINE_EDITING = "ag-cell-not-inline-editing";
var CSS_CELL_WRAP_TEXT = "ag-cell-wrap-text";
var instanceIdSequence4 = 0;
var CellCtrl = class extends BeanStub {
  constructor(column2, rowNode, beans, rowCtrl) {
    super();
    this.column = column2;
    this.rowNode = rowNode;
    this.rowCtrl = rowCtrl;
    this.rangeFeature = void 0;
    this.rowResizeFeature = void 0;
    this.positionFeature = void 0;
    this.customStyleFeature = void 0;
    this.editStyleFeature = void 0;
    this.mouseListener = void 0;
    this.keyboardListener = void 0;
    this.suppressRefreshCell = false;
    this.onCompAttachedFuncs = [];
    this.onEditorAttachedFuncs = [];
    this.focusEventWhileNotReady = null;
    this.hasBeenFocused = false;
    this.hasEdit = false;
    this.tooltipFeature = void 0;
    this.editorTooltipFeature = void 0;
    this.beans = beans;
    this.gos = beans.gos;
    this.editSvc = beans.editSvc;
    this.hasEdit = !!beans.editSvc;
    const { colId } = column2;
    this.instanceId = colId + "-" + instanceIdSequence4++;
    this.createCellPosition();
    this.updateAndFormatValue(false);
  }
  addFeatures() {
    const { beans } = this;
    this.positionFeature = new CellPositionFeature(this, beans);
    this.customStyleFeature = beans.cellStyles?.createCellCustomStyleFeature(this, beans);
    this.editStyleFeature = beans.editSvc?.createCellStyleFeature(this, beans);
    this.mouseListener = new CellMouseListenerFeature(this, beans, this.column);
    this.keyboardListener = new CellKeyboardListenerFeature(this, beans, this.rowNode, this.rowCtrl);
    this.enableTooltipFeature();
    const { rangeSvc } = beans;
    const cellSelectionEnabled = rangeSvc && _isCellSelectionEnabled(beans.gos);
    if (cellSelectionEnabled) {
      this.rangeFeature = rangeSvc.createCellRangeFeature(beans, this);
    }
    if (isRowNumberCol(this.column)) {
      this.rowResizeFeature = this.beans.rowNumbersSvc.createRowNumbersRowResizerFeature(beans, this);
    }
  }
  isCellSpanning() {
    return false;
  }
  getCellSpan() {
    return void 0;
  }
  removeFeatures() {
    const context = this.beans.context;
    this.positionFeature = context.destroyBean(this.positionFeature);
    this.editorTooltipFeature = context.destroyBean(this.editorTooltipFeature);
    this.customStyleFeature = context.destroyBean(this.customStyleFeature);
    this.editStyleFeature = context.destroyBean(this.editStyleFeature);
    this.mouseListener = context.destroyBean(this.mouseListener);
    this.keyboardListener = context.destroyBean(this.keyboardListener);
    this.rangeFeature = context.destroyBean(this.rangeFeature);
    this.rowResizeFeature = context.destroyBean(this.rowResizeFeature);
    this.disableTooltipFeature();
  }
  enableTooltipFeature(value2, shouldDisplayTooltip) {
    this.tooltipFeature = this.beans.tooltipSvc?.enableCellTooltipFeature(this, value2, shouldDisplayTooltip);
  }
  disableTooltipFeature() {
    this.tooltipFeature = this.beans.context.destroyBean(this.tooltipFeature);
  }
  enableEditorTooltipFeature(editor) {
    if (this.editorTooltipFeature) {
      this.disableEditorTooltipFeature();
    }
    this.editorTooltipFeature = this.beans.tooltipSvc?.setupCellEditorTooltip(this, editor);
    _populateModelValidationErrors(this.beans);
  }
  disableEditorTooltipFeature() {
    this.editorTooltipFeature = this.beans.context.destroyBean(this.editorTooltipFeature);
  }
  setComp(comp, eCell, _eWrapper, eCellWrapper, printLayout, startEditing, compBean) {
    this.comp = comp;
    this.eGui = eCell;
    this.printLayout = printLayout;
    compBean ?? (compBean = this);
    this.addDomData(compBean);
    this.addFeatures();
    compBean.addDestroyFunc(() => this.removeFeatures());
    this.onSuppressCellFocusChanged(this.beans.gos.get("suppressCellFocus"));
    this.setupFocus();
    this.applyStaticCssClasses();
    this.setWrapText();
    this.onFirstRightPinnedChanged();
    this.onLastLeftPinnedChanged();
    this.onColumnHover();
    this.setupControlComps();
    this.setupAutoHeight(eCellWrapper, compBean);
    this.refreshFirstAndLastStyles();
    this.refreshAriaColIndex();
    this.positionFeature?.init();
    this.customStyleFeature?.setComp(comp);
    this.editStyleFeature?.setComp(comp);
    this.tooltipFeature?.refreshTooltip();
    this.keyboardListener?.init();
    this.rangeFeature?.setComp(comp);
    this.rowResizeFeature?.refreshRowResizer();
    if (startEditing && this.isCellEditable() || this.hasEdit && this.editSvc?.isEditing(this, { withOpenEditor: true })) {
      this.editSvc?.startEditing(this, {
        startedEdit: false,
        source: "api",
        silent: true,
        continueEditing: true
      });
    } else {
      this.showValue(false, true);
    }
    if (this.onCompAttachedFuncs.length) {
      for (const func2 of this.onCompAttachedFuncs) {
        func2();
      }
      this.onCompAttachedFuncs = [];
    }
  }
  setupAutoHeight(eCellWrapper, compBean) {
    this.isAutoHeight = this.beans.rowAutoHeight?.setupCellAutoHeight(this, eCellWrapper, compBean) ?? false;
  }
  getCellAriaRole() {
    return this.column.getColDef().cellAriaRole ?? "gridcell";
  }
  isCellRenderer() {
    const colDef = this.column.getColDef();
    return colDef.cellRenderer != null || colDef.cellRendererSelector != null;
  }
  getValueToDisplay() {
    return this.valueFormatted ?? this.value;
  }
  getDeferLoadingCellRenderer() {
    const { beans, column: column2 } = this;
    const { userCompFactory, ctrlsSvc, eventSvc } = beans;
    const colDef = column2.getColDef();
    const params = this.createCellRendererParams();
    params.deferRender = true;
    const loadingDetails = _getLoadingCellRendererDetails(userCompFactory, colDef, params);
    if (ctrlsSvc.getGridBodyCtrl()?.scrollFeature?.isScrolling()) {
      let resolver;
      const onReady = new AgPromise((resolve2) => {
        resolver = resolve2;
      });
      const [removeBodyScrollEnd] = this.addManagedListeners(eventSvc, {
        bodyScrollEnd: () => {
          resolver();
          removeBodyScrollEnd();
        }
      });
      return { loadingComp: loadingDetails, onReady };
    }
    return { loadingComp: loadingDetails, onReady: AgPromise.resolve() };
  }
  showValue(forceNewCellRendererInstance, skipRangeHandleRefresh) {
    const { beans, column: column2, rowNode, rangeFeature } = this;
    const { userCompFactory } = beans;
    let valueToDisplay = this.getValueToDisplay();
    let compDetails;
    const isSsrmLoading = rowNode.stub && rowNode.groupData?.[column2.getId()] == null;
    const colDef = column2.getColDef();
    if (isSsrmLoading || this.isCellRenderer()) {
      const params = this.createCellRendererParams();
      if (!isSsrmLoading || isRowNumberCol(column2)) {
        compDetails = _getCellRendererDetails(userCompFactory, colDef, params);
      } else {
        compDetails = _getLoadingCellRendererDetails(userCompFactory, colDef, params);
      }
    }
    if (!compDetails && !isSsrmLoading && beans.findSvc?.isMatch(rowNode, column2)) {
      const params = this.createCellRendererParams();
      compDetails = _getCellRendererDetails(
        userCompFactory,
        { ...column2.getColDef(), cellRenderer: "agFindCellRenderer" },
        params
      );
    }
    if (this.hasEdit && this.editSvc.isBatchEditing() && this.editSvc.isRowEditing(rowNode, { checkSiblings: true })) {
      const result2 = this.editSvc.prepDetailsDuringBatch(this, { compDetails, valueToDisplay });
      if (result2) {
        if (result2.compDetails) {
          compDetails = result2.compDetails;
        } else if (result2.valueToDisplay) {
          valueToDisplay = result2.valueToDisplay;
        }
      }
    }
    this.comp.setRenderDetails(compDetails, valueToDisplay, forceNewCellRendererInstance);
    this.customRowDragComp?.refreshVisibility();
    if (!skipRangeHandleRefresh && rangeFeature) {
      _requestAnimationFrame(beans, () => rangeFeature?.refreshHandle());
    }
    this.rowResizeFeature?.refreshRowResizer();
  }
  setupControlComps() {
    const colDef = this.column.getColDef();
    this.includeSelection = this.isIncludeControl(this.isCheckboxSelection(colDef), true);
    this.includeRowDrag = this.isIncludeControl(colDef.rowDrag);
    this.includeDndSource = this.isIncludeControl(colDef.dndSource);
    this.comp.setIncludeSelection(this.includeSelection);
    this.comp.setIncludeDndSource(this.includeDndSource);
    this.comp.setIncludeRowDrag(this.includeRowDrag);
  }
  isForceWrapper() {
    return this.beans.gos.get("enableCellTextSelection") || this.column.isAutoHeight();
  }
  getCellValueClass() {
    const prefix = "ag-cell-value";
    const isCheckboxRenderer = this.column.getColDef().cellRenderer === "agCheckboxCellRenderer";
    let suffix = "";
    if (isCheckboxRenderer) {
      suffix = " ag-allow-overflow";
    }
    return `${prefix}${suffix}`;
  }
  /**
   * Wrapper providing general conditions under which control elements (e.g. checkboxes and drag handles)
   * are rendered for a particular cell.
   * @param value Whether to render the control in the specific context of the caller
   * @param allowManuallyPinned Whether manually pinned rows are permitted this form of control element
   */
  // eslint-disable-next-line @typescript-eslint/ban-types
  isIncludeControl(value2, allowManuallyPinned = false) {
    const rowUnpinned = this.rowNode.rowPinned == null;
    return (rowUnpinned || allowManuallyPinned && _isManualPinnedRow(this.rowNode)) && !!value2;
  }
  isCheckboxSelection(colDef) {
    const { rowSelection, groupDisplayType } = this.beans.gridOptions;
    const checkboxLocation = _getCheckboxLocation(rowSelection);
    const isSelectionColumn = isColumnSelectionCol(this.column);
    if (groupDisplayType === "custom" && checkboxLocation !== "selectionColumn" && isSelectionColumn) {
      return false;
    }
    return colDef.checkboxSelection || isSelectionColumn && typeof rowSelection === "object" && _getCheckboxes(rowSelection);
  }
  refreshShouldDestroy() {
    const colDef = this.column.getColDef();
    const selectionChanged = this.includeSelection != this.isIncludeControl(this.isCheckboxSelection(colDef), true);
    const rowDragChanged = this.includeRowDrag != this.isIncludeControl(colDef.rowDrag);
    const dndSourceChanged = this.includeDndSource != this.isIncludeControl(colDef.dndSource);
    const autoHeightChanged = this.isAutoHeight != this.column.isAutoHeight();
    return selectionChanged || rowDragChanged || dndSourceChanged || autoHeightChanged;
  }
  onPopupEditorClosed() {
    const { editSvc } = this.beans;
    if (!editSvc?.isEditing(this, { withOpenEditor: true })) {
      return;
    }
    editSvc?.stopEditing(this, { source: editSvc?.isBatchEditing() ? "ui" : "api" });
  }
  /**
   * Ends the Cell Editing
   * @param cancel `True` if the edit process is being canceled.
   * @returns `True` if the value of the `GridCell` has been updated, otherwise `False`.
   */
  stopEditing(cancel = false) {
    const { editSvc } = this.beans;
    return editSvc?.stopEditing(this, { cancel, source: editSvc?.isBatchEditing() ? "ui" : "api" }) ?? false;
  }
  createCellRendererParams() {
    const {
      value: value2,
      valueFormatted,
      column: column2,
      rowNode,
      comp,
      eGui,
      beans: { valueSvc, gos, editSvc }
    } = this;
    const res = _addGridCommonParams(gos, {
      value: value2,
      valueFormatted,
      getValue: () => valueSvc.getValueForDisplay(column2, rowNode).value,
      setValue: (value22) => editSvc?.setDataValue({ rowNode, column: column2 }, value22) || rowNode.setDataValue(column2, value22),
      formatValue: this.formatValue.bind(this),
      data: rowNode.data,
      node: rowNode,
      pinned: column2.getPinned(),
      colDef: column2.getColDef(),
      column: column2,
      refreshCell: this.refreshCell.bind(this),
      eGridCell: eGui,
      eParentOfValue: comp.getParentOfValue(),
      registerRowDragger: (rowDraggerElement, dragStartPixels, value22, suppressVisibilityChange) => this.registerRowDragger(rowDraggerElement, dragStartPixels, suppressVisibilityChange),
      setTooltip: (value22, shouldDisplayTooltip) => {
        gos.assertModuleRegistered("Tooltip", 3);
        if (this.tooltipFeature) {
          this.disableTooltipFeature();
        }
        this.enableTooltipFeature(value22, shouldDisplayTooltip);
        this.tooltipFeature?.refreshTooltip();
      }
    });
    return res;
  }
  onCellChanged(event) {
    const eventImpactsThisCell = event.column === this.column;
    if (eventImpactsThisCell) {
      this.refreshCell({});
    }
  }
  refreshOrDestroyCell(params) {
    if (this.refreshShouldDestroy()) {
      this.rowCtrl?.recreateCell(this);
    } else {
      this.refreshCell(params);
    }
    if (this.hasEdit && this.editCompDetails) {
      const { editSvc, comp } = this;
      if (!comp?.getCellEditor() && editSvc.isEditing(this, { withOpenEditor: true })) {
        editSvc.startEditing(this, { startedEdit: false, source: "api", silent: true });
      }
    }
  }
  // + stop editing {force: true, suppressFlash: true}
  // + event cellChanged {}
  // + cellRenderer.params.refresh() {} -> method passes 'as is' to the cellRenderer, so params could be anything
  // + rowCtrl: event dataChanged {suppressFlash: !update, newData: !update}
  // + rowCtrl: api refreshCells() {animate: true/false}
  // + rowRenderer: api softRefreshView() {}
  refreshCell({ force, suppressFlash, newData } = {}) {
    const {
      editStyleFeature,
      customStyleFeature,
      rowCtrl: { rowEditStyleFeature },
      beans: { cellFlashSvc, filterManager },
      column: column2,
      comp,
      suppressRefreshCell,
      tooltipFeature
    } = this;
    if (suppressRefreshCell) {
      return;
    }
    const { field: field2, valueGetter, showRowGroup, enableCellChangeFlash } = column2.getColDef();
    const noValueProvided = field2 == null && valueGetter == null && showRowGroup == null;
    const forceRefresh = force || noValueProvided || newData;
    const isCellCompReady = !!comp;
    const valuesDifferent = this.updateAndFormatValue(isCellCompReady);
    const dataNeedsUpdating = forceRefresh || valuesDifferent;
    if (!isCellCompReady) {
      return;
    }
    if (dataNeedsUpdating) {
      this.showValue(!!newData, false);
      const processingFilterChange = filterManager?.isSuppressFlashingCellsBecauseFiltering();
      const flashCell = !suppressFlash && !processingFilterChange && enableCellChangeFlash;
      if (flashCell) {
        cellFlashSvc?.flashCell(this);
      }
      editStyleFeature?.applyCellStyles?.();
      customStyleFeature?.applyUserStyles();
      customStyleFeature?.applyClassesFromColDef();
      rowEditStyleFeature?.applyRowStyles();
    }
    tooltipFeature?.refreshTooltip();
    customStyleFeature?.applyCellClassRules();
  }
  isCellEditable() {
    return this.column.isCellEditable(this.rowNode);
  }
  formatValue(value2) {
    return this.callValueFormatter(value2) ?? value2;
  }
  callValueFormatter(value2) {
    return this.beans.valueSvc.formatValue(this.column, this.rowNode, value2);
  }
  updateAndFormatValue(compareValues) {
    const oldValue = this.value;
    const oldValueFormatted = this.valueFormatted;
    const { value: value2, valueFormatted } = this.beans.valueSvc.getValueForDisplay(this.column, this.rowNode, true);
    this.value = value2;
    this.valueFormatted = valueFormatted;
    if (compareValues) {
      return !this.valuesAreEqual(oldValue, this.value) || this.valueFormatted != oldValueFormatted;
    }
    return true;
  }
  valuesAreEqual(val1, val2) {
    const colDef = this.column.getColDef();
    return colDef.equals ? colDef.equals(val1, val2) : val1 === val2;
  }
  addDomData(compBean) {
    const element = this.eGui;
    _setDomData(this.beans.gos, element, DOM_DATA_KEY_CELL_CTRL, this);
    compBean.addDestroyFunc(() => _setDomData(this.beans.gos, element, DOM_DATA_KEY_CELL_CTRL, null));
  }
  createEvent(domEvent, eventType) {
    const { rowNode, column: column2, value: value2, beans } = this;
    return _createCellEvent(beans, domEvent, eventType, { rowNode, column: column2 }, value2);
  }
  processCharacter(event) {
    this.keyboardListener?.processCharacter(event);
  }
  onKeyDown(event) {
    this.keyboardListener?.onKeyDown(event);
  }
  onMouseEvent(eventName, mouseEvent) {
    this.mouseListener?.onMouseEvent(eventName, mouseEvent);
  }
  getColSpanningList() {
    return this.positionFeature?.getColSpanningList() ?? [];
  }
  onLeftChanged() {
    if (!this.comp) {
      return;
    }
    this.positionFeature?.onLeftChanged();
  }
  onDisplayedColumnsChanged() {
    if (!this.eGui) {
      return;
    }
    this.refreshAriaColIndex();
    this.refreshFirstAndLastStyles();
  }
  refreshFirstAndLastStyles() {
    const { comp, column: column2, beans } = this;
    refreshFirstAndLastStyles(comp, column2, beans.visibleCols);
  }
  refreshAriaColIndex() {
    const colIdx = this.beans.visibleCols.getAriaColIndex(this.column);
    _setAriaColIndex(this.eGui, colIdx);
  }
  onWidthChanged() {
    return this.positionFeature?.onWidthChanged();
  }
  getRowPosition() {
    const { rowIndex, rowPinned } = this.cellPosition;
    return {
      rowIndex,
      rowPinned
    };
  }
  updateRangeBordersIfRangeCount() {
    if (!this.comp) {
      return;
    }
    this.rangeFeature?.updateRangeBordersIfRangeCount();
  }
  onCellSelectionChanged() {
    if (!this.comp) {
      return;
    }
    this.rangeFeature?.onCellSelectionChanged();
  }
  isRangeSelectionEnabled() {
    return this.rangeFeature != null;
  }
  focusCell(forceBrowserFocus = false, sourceEvent) {
    const allowedTarget = this.editSvc?.allowedFocusTargetOnValidation(this);
    if (allowedTarget && allowedTarget !== this) {
      return;
    }
    this.beans.focusSvc.setFocusedCell({
      ...this.getFocusedCellPosition(),
      forceBrowserFocus,
      sourceEvent
    });
  }
  /**
   * Restores focus to the cell, if it should have it
   * @param waitForRender if the cell has just setComp, it may not be rendered yet, so we wait for the next render
   */
  restoreFocus(waitForRender = false) {
    const {
      beans: { editSvc, focusSvc },
      comp
    } = this;
    if (!comp || editSvc?.isEditing(this) || !this.isCellFocused() || !focusSvc.shouldTakeFocus()) {
      return;
    }
    const focus = () => {
      if (!this.isAlive()) {
        return;
      }
      const focusableElement = comp.getFocusableElement();
      if (this.isCellFocused()) {
        focusableElement.focus({ preventScroll: true });
      }
    };
    if (waitForRender) {
      setTimeout(focus, 0);
      return;
    }
    focus();
  }
  onRowIndexChanged() {
    this.createCellPosition();
    this.onCellFocused();
    this.restoreFocus();
    this.rangeFeature?.onCellSelectionChanged();
    this.rowResizeFeature?.refreshRowResizer();
  }
  onSuppressCellFocusChanged(suppressCellFocus) {
    const element = this.eGui;
    if (!element) {
      return;
    }
    if (isRowNumberCol(this.column)) {
      suppressCellFocus = true;
    }
    _addOrRemoveAttribute(element, "tabindex", suppressCellFocus ? void 0 : -1);
  }
  onFirstRightPinnedChanged() {
    if (!this.comp) {
      return;
    }
    const firstRightPinned = this.column.isFirstRightPinned();
    this.comp.toggleCss(CSS_CELL_FIRST_RIGHT_PINNED, firstRightPinned);
  }
  onLastLeftPinnedChanged() {
    if (!this.comp) {
      return;
    }
    const lastLeftPinned = this.column.isLastLeftPinned();
    this.comp.toggleCss(CSS_CELL_LAST_LEFT_PINNED, lastLeftPinned);
  }
  /**
   * Returns whether cell is focused by the focusSvc, overridden by spannedCellCtrl
   */
  checkCellFocused() {
    return this.beans.focusSvc.isCellFocused(this.cellPosition);
  }
  isCellFocused() {
    const isFocused = this.checkCellFocused();
    this.hasBeenFocused || (this.hasBeenFocused = isFocused);
    return isFocused;
  }
  setupFocus() {
    this.restoreFocus(true);
    this.onCellFocused(this.focusEventWhileNotReady ?? void 0);
  }
  onCellFocused(event) {
    const { beans } = this;
    if (_isCellFocusSuppressed(beans)) {
      return;
    }
    if (!this.comp) {
      if (event) {
        this.focusEventWhileNotReady = event;
      }
      return;
    }
    const cellFocused = this.isCellFocused();
    const editing = beans.editSvc?.isEditing(this) ?? false;
    this.comp.toggleCss(CSS_CELL_FOCUS, cellFocused);
    if (cellFocused && event?.forceBrowserFocus) {
      let focusEl = this.comp.getFocusableElement();
      if (editing) {
        const focusableEls = _findFocusableElements(focusEl, null, true);
        if (focusableEls.length) {
          focusEl = focusableEls[0];
        }
      }
      focusEl.focus({ preventScroll: !!event.preventScrollOnBrowserFocus });
    }
    if (cellFocused && event) {
      this.rowCtrl.announceDescription();
    }
  }
  createCellPosition() {
    const { rowIndex, rowPinned } = this.rowNode;
    this.cellPosition = {
      rowIndex,
      rowPinned: _makeNull(rowPinned),
      column: this.column
    };
  }
  // CSS Classes that only get applied once, they never change
  applyStaticCssClasses() {
    const { comp } = this;
    comp.toggleCss(CSS_CELL, true);
    comp.toggleCss(CSS_CELL_NOT_INLINE_EDITING, true);
    const autoHeight = this.column.isAutoHeight() == true;
    comp.toggleCss(CSS_AUTO_HEIGHT, autoHeight);
    comp.toggleCss(CSS_NORMAL_HEIGHT, !autoHeight);
  }
  onColumnHover() {
    this.beans.colHover?.onCellColumnHover(this.column, this.comp);
  }
  onColDefChanged() {
    if (!this.comp) {
      return;
    }
    if (this.column.isTooltipEnabled()) {
      this.disableTooltipFeature();
      this.enableTooltipFeature();
    } else {
      this.disableTooltipFeature();
    }
    this.setWrapText();
    if (this.editSvc?.isEditing(this)) {
      this.editSvc?.handleColDefChanged(this);
    } else {
      this.refreshOrDestroyCell({ force: true, suppressFlash: true });
    }
  }
  setWrapText() {
    const value2 = this.column.getColDef().wrapText == true;
    this.comp.toggleCss(CSS_CELL_WRAP_TEXT, value2);
  }
  dispatchCellContextMenuEvent(event) {
    const colDef = this.column.getColDef();
    const cellContextMenuEvent = this.createEvent(event, "cellContextMenu");
    const { beans } = this;
    beans.eventSvc.dispatchEvent(cellContextMenuEvent);
    if (colDef.onCellContextMenu) {
      window.setTimeout(() => {
        beans.frameworkOverrides.wrapOutgoing(() => {
          colDef.onCellContextMenu(cellContextMenuEvent);
        });
      }, 0);
    }
  }
  getCellRenderer() {
    return this.comp?.getCellRenderer() ?? null;
  }
  destroy() {
    this.onCompAttachedFuncs = [];
    this.onEditorAttachedFuncs = [];
    if (this.isCellFocused() && this.hasBrowserFocus()) {
      this.beans.focusSvc.attemptToRecoverFocus();
    }
    super.destroy();
  }
  hasBrowserFocus() {
    return this.eGui?.contains(_getActiveDomElement(this.beans)) ?? false;
  }
  createSelectionCheckbox() {
    const cbSelectionComponent = this.beans.selectionSvc?.createCheckboxSelectionComponent();
    if (!cbSelectionComponent) {
      return void 0;
    }
    this.beans.context.createBean(cbSelectionComponent);
    cbSelectionComponent.init({ rowNode: this.rowNode, column: this.column });
    return cbSelectionComponent;
  }
  createDndSource() {
    const dndSourceComp = this.beans.registry.createDynamicBean(
      "dndSourceComp",
      false,
      this.rowNode,
      this.column,
      this.eGui
    );
    if (dndSourceComp) {
      this.beans.context.createBean(dndSourceComp);
    }
    return dndSourceComp;
  }
  registerRowDragger(customElement, dragStartPixels, alwaysVisible) {
    if (this.customRowDragComp) {
      this.customRowDragComp.setDragElement(customElement, dragStartPixels);
      return;
    }
    const newComp = this.createRowDragComp(customElement, dragStartPixels, alwaysVisible);
    if (newComp) {
      this.customRowDragComp = newComp;
      this.addDestroyFunc(() => {
        this.beans.context.destroyBean(newComp);
        this.customRowDragComp = null;
      });
      newComp.refreshVisibility();
    }
  }
  createRowDragComp(customElement, dragStartPixels, alwaysVisible) {
    const rowDragComp = this.beans.rowDragSvc?.createRowDragCompForCell(
      this.rowNode,
      this.column,
      () => this.value,
      customElement,
      dragStartPixels,
      alwaysVisible
    );
    if (!rowDragComp) {
      return void 0;
    }
    this.beans.context.createBean(rowDragComp);
    return rowDragComp;
  }
  cellEditorAttached() {
    for (const func2 of this.onEditorAttachedFuncs) {
      func2();
    }
    this.onEditorAttachedFuncs = [];
  }
  setFocusedCellPosition(_cellPosition) {
  }
  getFocusedCellPosition() {
    return this.cellPosition;
  }
  // used by spannedCellCtrl
  refreshAriaRowIndex() {
  }
  /**
   * Returns the root element of the cell, could be a span container rather than the cell element.
   * @returns The root element of the cell.
   */
  getRootElement() {
    return this.eGui;
  }
};
function processClassRules(expressionSvc, previousClassRules, classRules, params, onApplicableClass, onNotApplicableClass) {
  if (classRules == null && previousClassRules == null) {
    return;
  }
  const classesToApply = {};
  const classesToRemove = {};
  const forEachSingleClass = (className2, callback) => {
    for (const singleClass of className2.split(" ")) {
      if (singleClass.trim() == "") {
        continue;
      }
      callback(singleClass);
    }
  };
  if (classRules) {
    const classNames = Object.keys(classRules);
    for (let i2 = 0; i2 < classNames.length; i2++) {
      const className2 = classNames[i2];
      const rule = classRules[className2];
      let resultOfRule;
      if (typeof rule === "string") {
        resultOfRule = expressionSvc ? expressionSvc.evaluate(rule, params) : true;
      } else if (typeof rule === "function") {
        resultOfRule = rule(params);
      }
      forEachSingleClass(className2, (singleClass) => {
        resultOfRule ? classesToApply[singleClass] = true : classesToRemove[singleClass] = true;
      });
    }
  }
  if (previousClassRules && onNotApplicableClass) {
    for (const className2 of Object.keys(previousClassRules)) {
      forEachSingleClass(className2, (singleClass) => {
        if (!classesToApply[singleClass]) {
          classesToRemove[singleClass] = true;
        }
      });
    }
  }
  if (onNotApplicableClass) {
    Object.keys(classesToRemove).forEach(onNotApplicableClass);
  }
  Object.keys(classesToApply).forEach(onApplicableClass);
}
function calculateRowLevel(rowNode) {
  if (rowNode.group) {
    return rowNode.level;
  }
  const parent = rowNode.parent;
  return parent ? parent.level + 1 : 0;
}
var RowStyleService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "rowStyleSvc";
  }
  processClassesFromGridOptions(classes, rowNode) {
    const gos = this.gos;
    const process2 = (rowCls) => {
      if (typeof rowCls === "string") {
        classes.push(rowCls);
      } else if (Array.isArray(rowCls)) {
        for (const e of rowCls) {
          classes.push(e);
        }
      }
    };
    const rowClass = gos.get("rowClass");
    if (rowClass) {
      process2(rowClass);
    }
    const rowClassFunc = gos.getCallback("getRowClass");
    if (rowClassFunc) {
      const params = {
        data: rowNode.data,
        node: rowNode,
        rowIndex: rowNode.rowIndex
      };
      const rowClassFuncResult = rowClassFunc(params);
      process2(rowClassFuncResult);
    }
  }
  preProcessRowClassRules(classes, rowNode) {
    this.processRowClassRules(
      rowNode,
      (className2) => {
        classes.push(className2);
      },
      () => {
      }
    );
  }
  processRowClassRules(rowNode, onApplicableClass, onNotApplicableClass) {
    const { gos, expressionSvc } = this.beans;
    const rowClassParams = _addGridCommonParams(gos, {
      data: rowNode.data,
      node: rowNode,
      rowIndex: rowNode.rowIndex
    });
    processClassRules(
      expressionSvc,
      void 0,
      gos.get("rowClassRules"),
      rowClassParams,
      onApplicableClass,
      onNotApplicableClass
    );
  }
  processStylesFromGridOptions(rowNode) {
    const gos = this.gos;
    const rowStyle = gos.get("rowStyle");
    const rowStyleFunc = gos.getCallback("getRowStyle");
    let rowStyleFuncResult;
    if (rowStyleFunc) {
      const params = {
        data: rowNode.data,
        node: rowNode,
        rowIndex: rowNode.rowIndex
      };
      rowStyleFuncResult = rowStyleFunc(params);
    }
    if (rowStyleFuncResult || rowStyle) {
      return Object.assign({}, rowStyle, rowStyleFuncResult);
    }
    return void 0;
  }
};
var instanceIdSequence5 = 0;
var RowCtrl = class extends BeanStub {
  constructor(rowNode, beans, animateIn, useAnimationFrameForCreate, printLayout) {
    super();
    this.rowNode = rowNode;
    this.useAnimationFrameForCreate = useAnimationFrameForCreate;
    this.printLayout = printLayout;
    this.allRowGuis = [];
    this.active = true;
    this.centerCellCtrls = { list: [], map: {} };
    this.leftCellCtrls = { list: [], map: {} };
    this.rightCellCtrls = { list: [], map: {} };
    this.slideInAnimation = {
      left: false,
      center: false,
      right: false,
      fullWidth: false
    };
    this.fadeInAnimation = {
      left: false,
      center: false,
      right: false,
      fullWidth: false
    };
    this.rowDragComps = [];
    this.lastMouseDownOnDragger = false;
    this.emptyStyle = {};
    this.updateColumnListsPending = false;
    this.rowId = null;
    this.businessKey = null;
    this.beans = beans;
    this.gos = beans.gos;
    this.paginationPage = beans.pagination?.getCurrentPage() ?? 0;
    this.suppressRowTransform = this.gos.get("suppressRowTransform");
    this.instanceId = rowNode.id + "-" + instanceIdSequence5++;
    this.rowId = _escapeString(rowNode.id);
    this.initRowBusinessKey();
    this.rowFocused = beans.focusSvc.isRowFocused(this.rowNode.rowIndex, this.rowNode.rowPinned);
    this.rowLevel = calculateRowLevel(this.rowNode);
    this.setRowType();
    this.setAnimateFlags(animateIn);
    this.rowStyles = this.processStylesFromGridOptions();
    this.rowEditStyleFeature = beans.editSvc?.createRowStyleFeature(this, beans);
    this.addListeners();
  }
  initRowBusinessKey() {
    this.businessKeyForNodeFunc = this.gos.get("getBusinessKeyForNode");
    this.updateRowBusinessKey();
  }
  updateRowBusinessKey() {
    if (typeof this.businessKeyForNodeFunc !== "function") {
      return;
    }
    const businessKey = this.businessKeyForNodeFunc(this.rowNode);
    this.businessKey = _escapeString(businessKey);
  }
  updateGui(containerType, gui) {
    if (containerType === "left") {
      this.leftGui = gui;
    } else if (containerType === "right") {
      this.rightGui = gui;
    } else if (containerType === "fullWidth") {
      this.fullWidthGui = gui;
    } else {
      this.centerGui = gui;
    }
  }
  setComp(rowComp, element, containerType, compBean) {
    const { context, focusSvc } = this.beans;
    compBean = setupCompBean(this, context, compBean);
    const gui = { rowComp, element, containerType, compBean };
    this.allRowGuis.push(gui);
    this.updateGui(containerType, gui);
    this.initialiseRowComp(gui);
    const rowNode = this.rowNode;
    const isSsrmLoadingRow = this.rowType === "FullWidthLoading" || rowNode.stub;
    const isIrmLoadingRow = !rowNode.data && this.beans.rowModel.getType() === "infinite";
    if (!isSsrmLoadingRow && !isIrmLoadingRow && !rowNode.rowPinned) {
      this.beans.rowRenderer.dispatchFirstDataRenderedEvent();
    }
    const focusableElement = this.fullWidthGui?.element;
    if (focusableElement) {
      const editing = this.beans.editSvc?.isEditing(this);
      if (!editing && focusSvc.isRowFocused(rowNode.rowIndex, rowNode.rowPinned) && focusSvc.shouldTakeFocus()) {
        setTimeout(() => focusableElement.focus({ preventScroll: true }), 0);
      }
    }
  }
  unsetComp(containerType) {
    this.allRowGuis = this.allRowGuis.filter((rowGui) => rowGui.containerType !== containerType);
    this.updateGui(containerType, void 0);
  }
  isCacheable() {
    return this.rowType === "FullWidthDetail" && this.gos.get("keepDetailRows");
  }
  setCached(cached) {
    const displayValue = cached ? "none" : "";
    for (const rg of this.allRowGuis) {
      rg.element.style.display = displayValue;
    }
  }
  initialiseRowComp(gui) {
    const gos = this.gos;
    this.onSuppressCellFocusChanged(this.beans.gos.get("suppressCellFocus"));
    this.listenOnDomOrder(gui);
    this.onRowHeightChanged(gui);
    this.updateRowIndexes(gui);
    this.setFocusedClasses(gui);
    this.setStylesFromGridOptions(false, gui);
    if (_isRowSelection(gos) && this.rowNode.selectable) {
      this.onRowSelected(gui);
    }
    this.updateColumnLists(!this.useAnimationFrameForCreate);
    const comp = gui.rowComp;
    const initialRowClasses = this.getInitialRowClasses(gui.containerType);
    for (const name2 of initialRowClasses) {
      comp.toggleCss(name2, true);
    }
    this.executeSlideAndFadeAnimations(gui);
    if (this.rowNode.group) {
      _setAriaExpanded(gui.element, this.rowNode.expanded == true);
    }
    this.setRowCompRowId(comp);
    this.setRowCompRowBusinessKey(comp);
    _setDomData(gos, gui.element, DOM_DATA_KEY_ROW_CTRL, this);
    gui.compBean.addDestroyFunc(() => _setDomData(gos, gui.element, DOM_DATA_KEY_ROW_CTRL, null));
    if (this.useAnimationFrameForCreate) {
      this.beans.animationFrameSvc.createTask(
        this.addHoverFunctionality.bind(this, gui),
        this.rowNode.rowIndex,
        "p2",
        false
      );
    } else {
      this.addHoverFunctionality(gui);
    }
    if (this.isFullWidth()) {
      this.setupFullWidth(gui);
    }
    if (gos.get("rowDragEntireRow")) {
      this.addRowDraggerToRow(gui);
    }
    if (this.useAnimationFrameForCreate) {
      this.beans.animationFrameSvc.addDestroyTask(() => {
        if (!this.isAlive()) {
          return;
        }
        gui.rowComp.toggleCss("ag-after-created", true);
      });
    }
    this.executeProcessRowPostCreateFunc();
  }
  setRowCompRowBusinessKey(comp) {
    if (this.businessKey == null) {
      return;
    }
    comp.setRowBusinessKey(this.businessKey);
  }
  setRowCompRowId(comp) {
    const rowId = _escapeString(this.rowNode.id);
    this.rowId = rowId;
    if (rowId == null) {
      return;
    }
    comp.setRowId(rowId);
  }
  executeSlideAndFadeAnimations(gui) {
    const { containerType } = gui;
    const shouldSlide = this.slideInAnimation[containerType];
    if (shouldSlide) {
      _batchCall(() => {
        this.onTopChanged();
      });
      this.slideInAnimation[containerType] = false;
    }
    const shouldFade = this.fadeInAnimation[containerType];
    if (shouldFade) {
      _batchCall(() => {
        gui.rowComp.toggleCss("ag-opacity-zero", false);
      });
      this.fadeInAnimation[containerType] = false;
    }
  }
  addRowDraggerToRow(gui) {
    const rowDragComp = this.beans.rowDragSvc?.createRowDragCompForRow(this.rowNode, gui.element);
    if (!rowDragComp) {
      return;
    }
    const rowDragBean = this.createBean(rowDragComp, this.beans.context);
    this.rowDragComps.push(rowDragBean);
    gui.compBean.addDestroyFunc(() => {
      this.rowDragComps = this.rowDragComps.filter((r2) => r2 !== rowDragBean);
      this.rowEditStyleFeature = this.destroyBean(this.rowEditStyleFeature, this.beans.context);
      this.destroyBean(rowDragBean, this.beans.context);
    });
  }
  setupFullWidth(gui) {
    const pinned = this.getPinnedForContainer(gui.containerType);
    const compDetails = this.createFullWidthCompDetails(gui.element, pinned);
    gui.rowComp.showFullWidth(compDetails);
  }
  getFullWidthCellRenderers() {
    if (this.gos.get("embedFullWidthRows")) {
      return this.allRowGuis.map((gui) => gui?.rowComp?.getFullWidthCellRenderer());
    }
    return [this.fullWidthGui?.rowComp?.getFullWidthCellRenderer()];
  }
  executeProcessRowPostCreateFunc() {
    const func2 = this.gos.getCallback("processRowPostCreate");
    if (!func2 || !this.areAllContainersReady()) {
      return;
    }
    const params = {
      // areAllContainersReady asserts that centerGui is not null
      eRow: this.centerGui.element,
      ePinnedLeftRow: this.leftGui ? this.leftGui.element : void 0,
      ePinnedRightRow: this.rightGui ? this.rightGui.element : void 0,
      node: this.rowNode,
      rowIndex: this.rowNode.rowIndex,
      addRenderedRowListener: this.addEventListener.bind(this)
    };
    func2(params);
  }
  areAllContainersReady() {
    const {
      leftGui,
      centerGui,
      rightGui,
      beans: { visibleCols }
    } = this;
    const isLeftReady = !!leftGui || !visibleCols.isPinningLeft();
    const isCenterReady = !!centerGui;
    const isRightReady = !!rightGui || !visibleCols.isPinningRight();
    return isLeftReady && isCenterReady && isRightReady;
  }
  isNodeFullWidthCell() {
    if (this.rowNode.detail) {
      return true;
    }
    const isFullWidthCellFunc = this.beans.gos.getCallback("isFullWidthRow");
    return isFullWidthCellFunc ? isFullWidthCellFunc({ rowNode: this.rowNode }) : false;
  }
  setRowType() {
    const isStub = this.rowNode.stub && !this.gos.get("suppressServerSideFullWidthLoadingRow") && !this.gos.get("groupHideOpenParents");
    const isFullWidthCell = this.isNodeFullWidthCell();
    const isDetailCell = this.gos.get("masterDetail") && this.rowNode.detail;
    const pivotMode = this.beans.colModel.isPivotMode();
    const isFullWidthGroup = _isFullWidthGroupRow(this.gos, this.rowNode, pivotMode);
    if (isStub) {
      this.rowType = "FullWidthLoading";
    } else if (isDetailCell) {
      this.rowType = "FullWidthDetail";
    } else if (isFullWidthCell) {
      this.rowType = "FullWidth";
    } else if (isFullWidthGroup) {
      this.rowType = "FullWidthGroup";
    } else {
      this.rowType = "Normal";
    }
  }
  updateColumnLists(suppressAnimationFrame = false, useFlushSync = false) {
    if (this.isFullWidth()) {
      return;
    }
    const { animationFrameSvc } = this.beans;
    const noAnimation = !animationFrameSvc?.active || suppressAnimationFrame || this.printLayout;
    if (noAnimation) {
      this.updateColumnListsImpl(useFlushSync);
      return;
    }
    if (this.updateColumnListsPending) {
      return;
    }
    animationFrameSvc.createTask(
      () => {
        if (!this.active) {
          return;
        }
        this.updateColumnListsImpl(true);
      },
      this.rowNode.rowIndex,
      "p1",
      false
    );
    this.updateColumnListsPending = true;
  }
  /**
   * Overridden by SpannedRowCtrl
   */
  getNewCellCtrl(col) {
    const isCellSpan = this.beans.rowSpanSvc?.isCellSpanning(col, this.rowNode);
    if (isCellSpan) {
      return void 0;
    }
    return new CellCtrl(col, this.rowNode, this.beans, this);
  }
  /**
   * Overridden by SpannedRowCtrl, if span context changes cell needs rebuilt
   */
  isCorrectCtrlForSpan(cell2) {
    return !this.beans.rowSpanSvc?.isCellSpanning(cell2.column, this.rowNode);
  }
  createCellCtrls(prev, cols, pinned = null) {
    const res = {
      list: [],
      map: {}
    };
    const addCell = (colInstanceId, cellCtrl, index) => {
      if (index != null) {
        res.list.splice(index, 0, cellCtrl);
      } else {
        res.list.push(cellCtrl);
      }
      res.map[colInstanceId] = cellCtrl;
    };
    const colsFromPrev = [];
    for (const col of cols) {
      const colInstanceId = col.getInstanceId();
      let cellCtrl = prev.map[colInstanceId];
      if (cellCtrl && !this.isCorrectCtrlForSpan(cellCtrl)) {
        cellCtrl.destroy();
        cellCtrl = void 0;
      }
      if (!cellCtrl) {
        cellCtrl = this.getNewCellCtrl(col);
      }
      if (!cellCtrl) {
        continue;
      }
      addCell(colInstanceId, cellCtrl);
    }
    for (const prevCellCtrl of prev.list) {
      const colInstanceId = prevCellCtrl.column.getInstanceId();
      const cellInResult = res.map[colInstanceId] != null;
      if (cellInResult) {
        continue;
      }
      const keepCell = !this.isCellEligibleToBeRemoved(prevCellCtrl, pinned);
      if (keepCell) {
        colsFromPrev.push([colInstanceId, prevCellCtrl]);
      } else {
        prevCellCtrl.destroy();
      }
    }
    if (colsFromPrev.length) {
      for (const [colInstanceId, cellCtrl] of colsFromPrev) {
        const index = res.list.findIndex((ctrl) => ctrl.column.getLeft() > cellCtrl.column.getLeft());
        const normalisedIndex = index === -1 ? void 0 : Math.max(index - 1, 0);
        addCell(colInstanceId, cellCtrl, normalisedIndex);
      }
    }
    const { focusSvc, visibleCols } = this.beans;
    const focusedCell = focusSvc.getFocusedCell();
    if (focusedCell && focusedCell.column.getPinned() == pinned) {
      const focusedColInstanceId = focusedCell.column.getInstanceId();
      const focusedCellCtrl = res.map[focusedColInstanceId];
      if (!focusedCellCtrl && visibleCols.allCols.includes(focusedCell.column)) {
        const cellCtrl = this.createFocusedCellCtrl();
        if (cellCtrl) {
          const index = res.list.findIndex((ctrl) => ctrl.column.getLeft() > cellCtrl.column.getLeft());
          const normalisedIndex = index === -1 ? void 0 : Math.max(index - 1, 0);
          addCell(focusedColInstanceId, cellCtrl, normalisedIndex);
        }
      }
    }
    return res;
  }
  /**
   * Creates a new cell ctrl for the focused cell, if this is the correct row ctrl.
   * @returns a CellCtrl for the focused cell, if required.
   */
  createFocusedCellCtrl() {
    const { focusSvc, rowSpanSvc } = this.beans;
    const focusedCell = focusSvc.getFocusedCell();
    if (!focusedCell) {
      return void 0;
    }
    const focusedSpan = rowSpanSvc?.getCellSpan(focusedCell.column, this.rowNode);
    if (focusedSpan) {
      if (focusedSpan.firstNode !== this.rowNode || !focusedSpan.doesSpanContain(focusedCell)) {
        return void 0;
      }
    } else if (!focusSvc.isRowFocused(this.rowNode.rowIndex, this.rowNode.rowPinned)) {
      return void 0;
    }
    return this.getNewCellCtrl(focusedCell.column);
  }
  updateColumnListsImpl(useFlushSync) {
    this.updateColumnListsPending = false;
    this.createAllCellCtrls();
    this.setCellCtrls(useFlushSync);
  }
  setCellCtrls(useFlushSync) {
    for (const item2 of this.allRowGuis) {
      const cellControls = this.getCellCtrlsForContainer(item2.containerType);
      item2.rowComp.setCellCtrls(cellControls, useFlushSync);
    }
  }
  getCellCtrlsForContainer(containerType) {
    switch (containerType) {
      case "left":
        return this.leftCellCtrls.list;
      case "right":
        return this.rightCellCtrls.list;
      case "fullWidth":
        return [];
      case "center":
        return this.centerCellCtrls.list;
    }
  }
  createAllCellCtrls() {
    const colViewport = this.beans.colViewport;
    const presentedColsService = this.beans.visibleCols;
    if (this.printLayout) {
      this.centerCellCtrls = this.createCellCtrls(this.centerCellCtrls, presentedColsService.allCols);
      this.leftCellCtrls = { list: [], map: {} };
      this.rightCellCtrls = { list: [], map: {} };
    } else {
      const centerCols = colViewport.getColsWithinViewport(this.rowNode);
      this.centerCellCtrls = this.createCellCtrls(this.centerCellCtrls, centerCols);
      const leftCols = presentedColsService.getLeftColsForRow(this.rowNode);
      this.leftCellCtrls = this.createCellCtrls(this.leftCellCtrls, leftCols, "left");
      const rightCols = presentedColsService.getRightColsForRow(this.rowNode);
      this.rightCellCtrls = this.createCellCtrls(this.rightCellCtrls, rightCols, "right");
    }
  }
  isCellEligibleToBeRemoved(cellCtrl, nextContainerPinned) {
    const REMOVE_CELL = true;
    const KEEP_CELL = false;
    const { column: column2 } = cellCtrl;
    if (column2.getPinned() != nextContainerPinned) {
      return REMOVE_CELL;
    }
    if (!this.isCorrectCtrlForSpan(cellCtrl)) {
      return REMOVE_CELL;
    }
    const { visibleCols, editSvc } = this.beans;
    const editing = editSvc?.isEditing(cellCtrl);
    const focused = cellCtrl.isCellFocused();
    const mightWantToKeepCell = editing || focused;
    if (mightWantToKeepCell) {
      const displayedColumns = visibleCols.allCols;
      const cellStillDisplayed = displayedColumns.indexOf(column2) >= 0;
      return cellStillDisplayed ? KEEP_CELL : REMOVE_CELL;
    }
    return REMOVE_CELL;
  }
  getDomOrder() {
    const isEnsureDomOrder = this.gos.get("ensureDomOrder");
    return isEnsureDomOrder || _isDomLayout(this.gos, "print");
  }
  listenOnDomOrder(gui) {
    const listener = () => {
      gui.rowComp.setDomOrder(this.getDomOrder());
    };
    gui.compBean.addManagedPropertyListeners(["domLayout", "ensureDomOrder"], listener);
  }
  setAnimateFlags(animateIn) {
    if (this.rowNode.sticky || !animateIn) {
      return;
    }
    const oldRowTopExists = _exists(this.rowNode.oldRowTop);
    const { visibleCols } = this.beans;
    const pinningLeft = visibleCols.isPinningLeft();
    const pinningRight = visibleCols.isPinningRight();
    if (oldRowTopExists) {
      const { slideInAnimation } = this;
      if (this.isFullWidth() && !this.gos.get("embedFullWidthRows")) {
        slideInAnimation.fullWidth = true;
        return;
      }
      slideInAnimation.center = true;
      slideInAnimation.left = pinningLeft;
      slideInAnimation.right = pinningRight;
    } else {
      const { fadeInAnimation } = this;
      if (this.isFullWidth() && !this.gos.get("embedFullWidthRows")) {
        fadeInAnimation.fullWidth = true;
        return;
      }
      fadeInAnimation.center = true;
      fadeInAnimation.left = pinningLeft;
      fadeInAnimation.right = pinningRight;
    }
  }
  isFullWidth() {
    return this.rowType !== "Normal";
  }
  refreshFullWidth() {
    const tryRefresh = (gui, pinned) => {
      if (!gui) {
        return true;
      }
      return gui.rowComp.refreshFullWidth(() => {
        const compDetails = this.createFullWidthCompDetails(gui.element, pinned);
        return compDetails.params;
      });
    };
    const fullWidthSuccess = tryRefresh(this.fullWidthGui, null);
    const centerSuccess = tryRefresh(this.centerGui, null);
    const leftSuccess = tryRefresh(this.leftGui, "left");
    const rightSuccess = tryRefresh(this.rightGui, "right");
    const allFullWidthRowsRefreshed = fullWidthSuccess && centerSuccess && leftSuccess && rightSuccess;
    return allFullWidthRowsRefreshed;
  }
  addListeners() {
    const { beans, gos, rowNode } = this;
    const { expansionSvc, eventSvc, context, rowSpanSvc } = beans;
    this.addManagedListeners(this.rowNode, {
      heightChanged: () => this.onRowHeightChanged(),
      rowSelected: () => this.onRowSelected(),
      rowIndexChanged: this.onRowIndexChanged.bind(this),
      topChanged: this.onTopChanged.bind(this),
      ...expansionSvc?.getRowExpandedListeners(this) ?? {}
    });
    if (rowNode.detail) {
      this.addManagedListeners(rowNode.parent, { dataChanged: this.onRowNodeDataChanged.bind(this) });
    }
    this.addManagedListeners(rowNode, {
      dataChanged: this.onRowNodeDataChanged.bind(this),
      cellChanged: this.postProcessCss.bind(this),
      rowHighlightChanged: this.onRowNodeHighlightChanged.bind(this),
      draggingChanged: this.postProcessRowDragging.bind(this),
      uiLevelChanged: this.onUiLevelChanged.bind(this),
      rowPinned: this.onRowPinned.bind(this)
    });
    this.addManagedListeners(eventSvc, {
      paginationPixelOffsetChanged: this.onPaginationPixelOffsetChanged.bind(this),
      heightScaleChanged: this.onTopChanged.bind(this),
      displayedColumnsChanged: this.onDisplayedColumnsChanged.bind(this),
      virtualColumnsChanged: this.onVirtualColumnsChanged.bind(this),
      cellFocused: this.onCellFocusChanged.bind(this),
      cellFocusCleared: this.onCellFocusChanged.bind(this),
      paginationChanged: this.onPaginationChanged.bind(this),
      modelUpdated: this.refreshFirstAndLastRowStyles.bind(this),
      columnMoved: () => this.updateColumnLists()
    });
    if (rowSpanSvc) {
      this.addManagedListeners(rowSpanSvc, {
        spannedCellsUpdated: ({ pinned }) => {
          if (pinned && !rowNode.rowPinned) {
            return;
          }
          this.updateColumnLists();
        }
      });
    }
    this.addDestroyFunc(() => {
      this.rowDragComps = this.destroyBeans(this.rowDragComps, context);
      this.tooltipFeature = this.destroyBean(this.tooltipFeature, context);
      this.rowEditStyleFeature = this.destroyBean(this.rowEditStyleFeature, context);
    });
    this.addManagedPropertyListeners(
      ["rowStyle", "getRowStyle", "rowClass", "getRowClass", "rowClassRules"],
      this.postProcessCss.bind(this)
    );
    this.addManagedPropertyListener("rowDragEntireRow", () => {
      const useRowDragEntireRow = gos.get("rowDragEntireRow");
      if (useRowDragEntireRow) {
        for (const gui of this.allRowGuis) {
          this.addRowDraggerToRow(gui);
        }
        return;
      }
      this.rowDragComps = this.destroyBeans(this.rowDragComps, context);
    });
    this.addListenersForCellComps();
  }
  addListenersForCellComps() {
    this.addManagedListeners(this.rowNode, {
      rowIndexChanged: () => {
        for (const cellCtrl of this.getAllCellCtrls()) {
          cellCtrl.onRowIndexChanged();
        }
      },
      cellChanged: (event) => {
        for (const cellCtrl of this.getAllCellCtrls()) {
          cellCtrl.onCellChanged(event);
        }
      }
    });
  }
  /** Should only ever be triggered on source rows (i.e. not on pinned siblings) */
  onRowPinned() {
    for (const gui of this.allRowGuis) {
      gui.rowComp.toggleCss("ag-row-pinned-source", !!this.rowNode.pinnedSibling);
    }
  }
  onRowNodeDataChanged(event) {
    this.refreshRow({
      suppressFlash: !event.update,
      newData: !event.update
    });
  }
  refreshRow(params) {
    const fullWidthChanged = this.isFullWidth() !== !!this.isNodeFullWidthCell();
    if (fullWidthChanged) {
      this.beans.rowRenderer.redrawRow(this.rowNode);
      return;
    }
    if (this.isFullWidth()) {
      const refresh = this.refreshFullWidth();
      if (!refresh) {
        this.beans.rowRenderer.redrawRow(this.rowNode);
      }
      return;
    }
    for (const cellCtrl of this.getAllCellCtrls()) {
      cellCtrl.refreshCell(params);
    }
    for (const gui of this.allRowGuis) {
      this.setRowCompRowId(gui.rowComp);
      this.updateRowBusinessKey();
      this.setRowCompRowBusinessKey(gui.rowComp);
    }
    this.onRowSelected();
    this.postProcessCss();
  }
  postProcessCss() {
    this.setStylesFromGridOptions(true);
    this.postProcessClassesFromGridOptions();
    this.postProcessRowClassRules();
    this.rowEditStyleFeature?.applyRowStyles();
    this.postProcessRowDragging();
  }
  onRowNodeHighlightChanged() {
    const rowDropHighlightSvc = this.beans.rowDropHighlightSvc;
    const highlighted = rowDropHighlightSvc?.row === this.rowNode ? rowDropHighlightSvc.position : "none";
    const aboveOn = highlighted === "above";
    const insideOn = highlighted === "inside";
    const belowOn = highlighted === "below";
    const treeData = this.gos.get("treeData");
    const indented2 = treeData && (belowOn || aboveOn);
    const uiLevel = this.rowNode.uiLevel.toString();
    for (const gui of this.allRowGuis) {
      const rowComp = gui.rowComp;
      rowComp.toggleCss("ag-row-highlight-above", aboveOn);
      rowComp.toggleCss("ag-row-highlight-inside", insideOn);
      rowComp.toggleCss("ag-row-highlight-below", belowOn);
      rowComp.toggleCss("ag-row-highlight-indent", indented2);
      if (indented2) {
        gui.element.style.setProperty("--ag-row-highlight-level", uiLevel);
      } else {
        gui.element.style.removeProperty("--ag-row-highlight-level");
      }
    }
  }
  postProcessRowDragging() {
    const dragging = this.rowNode.dragging;
    for (const gui of this.allRowGuis) {
      gui.rowComp.toggleCss("ag-row-dragging", dragging);
    }
  }
  onDisplayedColumnsChanged() {
    this.updateColumnLists(true);
    this.beans.rowAutoHeight?.requestCheckAutoHeight();
  }
  onVirtualColumnsChanged() {
    this.updateColumnLists(false, true);
  }
  getRowPosition() {
    return {
      rowPinned: _makeNull(this.rowNode.rowPinned),
      rowIndex: this.rowNode.rowIndex
    };
  }
  onKeyboardNavigate(keyboardEvent) {
    const groupInfo = this.findFullWidthInfoForEvent(keyboardEvent);
    if (!groupInfo) {
      return;
    }
    const { rowGui, column: column2 } = groupInfo;
    const currentFullWidthContainer = rowGui.element;
    const isFullWidthContainerFocused = currentFullWidthContainer === keyboardEvent.target;
    if (!isFullWidthContainerFocused) {
      return;
    }
    const node2 = this.rowNode;
    const { focusSvc, navigation: navigation2 } = this.beans;
    const lastFocusedCell = focusSvc.getFocusedCell();
    const cellPosition = {
      rowIndex: node2.rowIndex,
      rowPinned: node2.rowPinned,
      column: lastFocusedCell?.column ?? column2
    };
    navigation2?.navigateToNextCell(keyboardEvent, keyboardEvent.key, cellPosition, true);
    keyboardEvent.preventDefault();
  }
  onTabKeyDown(keyboardEvent) {
    if (keyboardEvent.defaultPrevented || _isStopPropagationForAgGrid(keyboardEvent)) {
      return;
    }
    const currentFullWidthComp = this.allRowGuis.find(
      (c2) => c2.element.contains(keyboardEvent.target)
    );
    const currentFullWidthContainer = currentFullWidthComp ? currentFullWidthComp.element : null;
    const isFullWidthContainerFocused = currentFullWidthContainer === keyboardEvent.target;
    const activeEl = _getActiveDomElement(this.beans);
    let isDetailGridCellFocused = false;
    if (currentFullWidthContainer && activeEl) {
      isDetailGridCellFocused = currentFullWidthContainer.contains(activeEl) && activeEl.classList.contains("ag-cell");
    }
    let nextEl = null;
    if (!isFullWidthContainerFocused && !isDetailGridCellFocused) {
      nextEl = _findNextFocusableElement(this.beans, currentFullWidthContainer, false, keyboardEvent.shiftKey);
    }
    if (this.isFullWidth() && isFullWidthContainerFocused || !nextEl) {
      this.beans.navigation?.onTabKeyDown(this, keyboardEvent);
    }
  }
  getFullWidthElement() {
    if (this.fullWidthGui) {
      return this.fullWidthGui.element;
    }
    return null;
  }
  getRowYPosition() {
    const displayedEl = this.allRowGuis.find((el) => _isVisible(el.element))?.element;
    if (displayedEl) {
      return displayedEl.getBoundingClientRect().top;
    }
    return 0;
  }
  onSuppressCellFocusChanged(suppressCellFocus) {
    const tabIndex = this.isFullWidth() && suppressCellFocus ? void 0 : this.gos.get("tabIndex");
    for (const gui of this.allRowGuis) {
      _addOrRemoveAttribute(gui.element, "tabindex", tabIndex);
    }
  }
  onFullWidthRowFocused(event) {
    const node2 = this.rowNode;
    const isFocused = !event ? false : this.isFullWidth() && event.rowIndex === node2.rowIndex && event.rowPinned == node2.rowPinned;
    let element;
    if (this.fullWidthGui) {
      element = this.fullWidthGui.element;
    } else {
      const column2 = this.beans.colModel.getCol(event?.column);
      const pinned = column2?.pinned;
      if (pinned) {
        element = pinned === "right" ? this.rightGui?.element : this.leftGui?.element;
      } else {
        element = this.centerGui?.element;
      }
    }
    if (!element) {
      return;
    }
    element.classList.toggle("ag-full-width-focus", isFocused);
    if (isFocused && event?.forceBrowserFocus) {
      element.focus({ preventScroll: true });
    }
  }
  recreateCell(cellCtrl) {
    this.centerCellCtrls = this.removeCellCtrl(this.centerCellCtrls, cellCtrl);
    this.leftCellCtrls = this.removeCellCtrl(this.leftCellCtrls, cellCtrl);
    this.rightCellCtrls = this.removeCellCtrl(this.rightCellCtrls, cellCtrl);
    cellCtrl.destroy();
    this.updateColumnLists();
  }
  removeCellCtrl(prev, cellCtrlToRemove) {
    const res = {
      list: [],
      map: {}
    };
    for (const cellCtrl of prev.list) {
      if (cellCtrl === cellCtrlToRemove) {
        continue;
      }
      res.list.push(cellCtrl);
      res.map[cellCtrl.column.getInstanceId()] = cellCtrl;
    }
    return res;
  }
  onMouseEvent(eventName, mouseEvent) {
    switch (eventName) {
      case "dblclick":
        this.onRowDblClick(mouseEvent);
        break;
      case "click":
        this.onRowClick(mouseEvent);
        break;
      case "touchstart":
      case "mousedown":
        this.onRowMouseDown(mouseEvent);
        break;
    }
  }
  createRowEvent(type, domEvent) {
    const { rowNode } = this;
    return _addGridCommonParams(this.gos, {
      type,
      node: rowNode,
      data: rowNode.data,
      rowIndex: rowNode.rowIndex,
      rowPinned: rowNode.rowPinned,
      event: domEvent
    });
  }
  createRowEventWithSource(type, domEvent) {
    const event = this.createRowEvent(type, domEvent);
    event.source = this;
    return event;
  }
  onRowDblClick(mouseEvent) {
    if (_isStopPropagationForAgGrid(mouseEvent)) {
      return;
    }
    const rowEvent = this.createRowEventWithSource("rowDoubleClicked", mouseEvent);
    rowEvent.isEventHandlingSuppressed = this.isSuppressMouseEvent(mouseEvent);
    this.beans.eventSvc.dispatchEvent(rowEvent);
  }
  findFullWidthInfoForEvent(event) {
    if (!event) {
      return;
    }
    const rowGui = this.findFullWidthRowGui(event.target);
    const column2 = this.getColumnForFullWidth(rowGui);
    if (!rowGui || !column2) {
      return;
    }
    return { rowGui, column: column2 };
  }
  findFullWidthRowGui(target) {
    return this.allRowGuis.find((c2) => c2.element.contains(target));
  }
  getColumnForFullWidth(fullWidthRowGui) {
    const { visibleCols } = this.beans;
    switch (fullWidthRowGui?.containerType) {
      case "center":
        return visibleCols.centerCols[0];
      case "left":
        return visibleCols.leftCols[0];
      case "right":
        return visibleCols.rightCols[0];
      default:
        return visibleCols.allCols[0];
    }
  }
  onRowMouseDown(mouseEvent) {
    this.lastMouseDownOnDragger = _isElementChildOfClass(mouseEvent.target, "ag-row-drag", 3);
    if (!this.isFullWidth() || this.isSuppressMouseEvent(mouseEvent)) {
      return;
    }
    const { rangeSvc, focusSvc } = this.beans;
    rangeSvc?.removeAllCellRanges();
    const groupInfo = this.findFullWidthInfoForEvent(mouseEvent);
    if (!groupInfo) {
      return;
    }
    const { rowGui, column: column2 } = groupInfo;
    const element = rowGui.element;
    const target = mouseEvent.target;
    const node2 = this.rowNode;
    let forceBrowserFocus = mouseEvent.defaultPrevented || _isBrowserSafari();
    if (element && element.contains(target) && _isFocusableFormField(target)) {
      forceBrowserFocus = false;
    }
    focusSvc.setFocusedCell({
      rowIndex: node2.rowIndex,
      column: column2,
      rowPinned: node2.rowPinned,
      forceBrowserFocus
    });
  }
  isSuppressMouseEvent(mouseEvent) {
    const { gos, rowNode } = this;
    if (this.isFullWidth()) {
      const fullWidthRowGui = this.findFullWidthRowGui(mouseEvent.target);
      return _suppressFullWidthMouseEvent(
        gos,
        fullWidthRowGui?.rowComp.getFullWidthCellRendererParams(),
        rowNode,
        mouseEvent
      );
    }
    const cellCtrl = _getCellCtrlForEventTarget(gos, mouseEvent.target);
    return cellCtrl != null && _suppressCellMouseEvent(gos, cellCtrl.column, rowNode, mouseEvent);
  }
  onRowClick(mouseEvent) {
    const stop = _isStopPropagationForAgGrid(mouseEvent) || this.lastMouseDownOnDragger;
    if (stop) {
      return;
    }
    const isSuppressMouseEvent = this.isSuppressMouseEvent(mouseEvent);
    const { eventSvc, selectionSvc } = this.beans;
    const rowEvent = this.createRowEventWithSource("rowClicked", mouseEvent);
    rowEvent.isEventHandlingSuppressed = isSuppressMouseEvent;
    eventSvc.dispatchEvent(rowEvent);
    if (isSuppressMouseEvent) {
      return;
    }
    selectionSvc?.handleSelectionEvent(mouseEvent, this.rowNode, "rowClicked");
  }
  setupDetailRowAutoHeight(eDetailGui) {
    if (this.rowType !== "FullWidthDetail") {
      return;
    }
    this.beans.masterDetailSvc?.setupDetailRowAutoHeight(this, eDetailGui);
  }
  createFullWidthCompDetails(eRow, pinned) {
    const { gos, rowNode } = this;
    const params = _addGridCommonParams(gos, {
      fullWidth: true,
      data: rowNode.data,
      node: rowNode,
      value: rowNode.key,
      valueFormatted: rowNode.key,
      // these need to be taken out, as part of 'afterAttached' now
      eGridCell: eRow,
      eParentOfValue: eRow,
      pinned,
      addRenderedRowListener: this.addEventListener.bind(this),
      // This is not on the type of ICellRendererParams
      registerRowDragger: (rowDraggerElement, dragStartPixels, value2, rowDragEntireRow) => this.addFullWidthRowDragging(rowDraggerElement, dragStartPixels, value2, rowDragEntireRow),
      setTooltip: (value2, shouldDisplayTooltip) => {
        gos.assertModuleRegistered("Tooltip", 3);
        this.setupFullWidthRowTooltip(value2, shouldDisplayTooltip);
      }
    });
    const compFactory = this.beans.userCompFactory;
    switch (this.rowType) {
      case "FullWidthDetail":
        return _getFullWidthDetailCellRendererDetails(compFactory, params);
      case "FullWidthGroup": {
        const { value: value2, valueFormatted } = this.beans.valueSvc.getValueForDisplay(void 0, this.rowNode, true);
        params.value = value2;
        params.valueFormatted = valueFormatted;
        return _getFullWidthGroupCellRendererDetails(compFactory, params);
      }
      case "FullWidthLoading":
        return _getFullWidthLoadingCellRendererDetails(compFactory, params);
      default:
        return _getFullWidthCellRendererDetails(compFactory, params);
    }
  }
  setupFullWidthRowTooltip(value2, shouldDisplayTooltip) {
    if (!this.fullWidthGui) {
      return;
    }
    this.tooltipFeature = this.beans.tooltipSvc?.setupFullWidthRowTooltip(
      this.tooltipFeature,
      this,
      value2,
      shouldDisplayTooltip
    );
  }
  addFullWidthRowDragging(rowDraggerElement, dragStartPixels, value2 = "", alwaysVisible) {
    const { rowDragSvc, context } = this.beans;
    if (!rowDragSvc || !this.isFullWidth()) {
      return;
    }
    const rowDragComp = rowDragSvc.createRowDragComp(
      () => value2,
      this.rowNode,
      void 0,
      rowDraggerElement,
      dragStartPixels,
      alwaysVisible
    );
    this.createBean(rowDragComp, context);
    this.addDestroyFunc(() => {
      this.destroyBean(rowDragComp, context);
    });
  }
  onUiLevelChanged() {
    const newLevel = calculateRowLevel(this.rowNode);
    if (this.rowLevel != newLevel) {
      const classToAdd = "ag-row-level-" + newLevel;
      const classToRemove = "ag-row-level-" + this.rowLevel;
      for (const gui of this.allRowGuis) {
        gui.rowComp.toggleCss(classToAdd, true);
        gui.rowComp.toggleCss(classToRemove, false);
      }
    }
    this.rowLevel = newLevel;
  }
  isFirstRowOnPage() {
    return this.rowNode.rowIndex === this.beans.pageBounds.getFirstRow();
  }
  isLastRowOnPage() {
    return this.rowNode.rowIndex === this.beans.pageBounds.getLastRow();
  }
  refreshFirstAndLastRowStyles() {
    const newFirst = this.isFirstRowOnPage();
    const newLast = this.isLastRowOnPage();
    if (this.firstRowOnPage !== newFirst) {
      this.firstRowOnPage = newFirst;
      for (const gui of this.allRowGuis) {
        gui.rowComp.toggleCss("ag-row-first", newFirst);
      }
    }
    if (this.lastRowOnPage !== newLast) {
      this.lastRowOnPage = newLast;
      for (const gui of this.allRowGuis) {
        gui.rowComp.toggleCss("ag-row-last", newLast);
      }
    }
  }
  getAllCellCtrls() {
    if (this.leftCellCtrls.list.length === 0 && this.rightCellCtrls.list.length === 0) {
      return this.centerCellCtrls.list;
    }
    const res = [...this.centerCellCtrls.list, ...this.leftCellCtrls.list, ...this.rightCellCtrls.list];
    return res;
  }
  postProcessClassesFromGridOptions() {
    const cssClasses = [];
    this.beans.rowStyleSvc?.processClassesFromGridOptions(cssClasses, this.rowNode);
    if (!cssClasses.length) {
      return;
    }
    for (const classStr of cssClasses) {
      for (const c2 of this.allRowGuis) {
        c2.rowComp.toggleCss(classStr, true);
      }
    }
  }
  postProcessRowClassRules() {
    this.beans.rowStyleSvc?.processRowClassRules(
      this.rowNode,
      (className2) => {
        for (const gui of this.allRowGuis) {
          gui.rowComp.toggleCss(className2, true);
        }
      },
      (className2) => {
        for (const gui of this.allRowGuis) {
          gui.rowComp.toggleCss(className2, false);
        }
      }
    );
  }
  setStylesFromGridOptions(updateStyles, gui) {
    if (updateStyles) {
      this.rowStyles = this.processStylesFromGridOptions();
    }
    this.forEachGui(gui, (gui2) => gui2.rowComp.setUserStyles(this.rowStyles));
  }
  getPinnedForContainer(rowContainerType) {
    if (rowContainerType === "left" || rowContainerType === "right") {
      return rowContainerType;
    }
    return null;
  }
  getInitialRowClasses(rowContainerType) {
    const pinned = this.getPinnedForContainer(rowContainerType);
    const fullWidthRow = this.isFullWidth();
    const { rowNode, beans } = this;
    const classes = [];
    classes.push("ag-row");
    classes.push(this.rowFocused ? "ag-row-focus" : "ag-row-no-focus");
    if (this.fadeInAnimation[rowContainerType]) {
      classes.push("ag-opacity-zero");
    }
    classes.push(rowNode.rowIndex % 2 === 0 ? "ag-row-even" : "ag-row-odd");
    if (rowNode.isRowPinned()) {
      classes.push("ag-row-pinned");
      if (beans.pinnedRowModel?.isManual()) {
        classes.push("ag-row-pinned-manual");
      }
    }
    if (!rowNode.isRowPinned() && rowNode.pinnedSibling) {
      classes.push("ag-row-pinned-source");
    }
    if (rowNode.isSelected()) {
      classes.push("ag-row-selected");
    }
    if (rowNode.footer) {
      classes.push("ag-row-footer");
    }
    classes.push("ag-row-level-" + this.rowLevel);
    if (rowNode.stub) {
      classes.push("ag-row-loading");
    }
    if (fullWidthRow) {
      classes.push("ag-full-width-row");
    }
    beans.expansionSvc?.addExpandedCss(classes, rowNode);
    if (rowNode.dragging) {
      classes.push("ag-row-dragging");
    }
    const { rowStyleSvc } = beans;
    if (rowStyleSvc) {
      rowStyleSvc.processClassesFromGridOptions(classes, rowNode);
      rowStyleSvc.preProcessRowClassRules(classes, rowNode);
    }
    classes.push(this.printLayout ? "ag-row-position-relative" : "ag-row-position-absolute");
    if (this.isFirstRowOnPage()) {
      classes.push("ag-row-first");
    }
    if (this.isLastRowOnPage()) {
      classes.push("ag-row-last");
    }
    if (fullWidthRow) {
      if (pinned === "left") {
        classes.push("ag-cell-last-left-pinned");
      }
      if (pinned === "right") {
        classes.push("ag-cell-first-right-pinned");
      }
    }
    return classes;
  }
  processStylesFromGridOptions() {
    return this.beans.rowStyleSvc?.processStylesFromGridOptions(this.rowNode) ?? this.emptyStyle;
  }
  onRowSelected(gui) {
    this.beans.selectionSvc?.onRowCtrlSelected(
      this,
      (gui2) => {
        if (gui2 === this.centerGui || gui2 === this.fullWidthGui) {
          this.announceDescription();
        }
      },
      gui
    );
  }
  announceDescription() {
    this.beans.selectionSvc?.announceAriaRowSelection(this.rowNode);
  }
  addHoverFunctionality(eGui) {
    if (!this.active) {
      return;
    }
    const { element, compBean } = eGui;
    const { rowNode, beans, gos } = this;
    compBean.addManagedListeners(element, {
      // We use pointer events here instead of mouse events, as pointer events
      // are more reliable for hover detection, especially with touch devices
      // or hybrid touch + mouse devices.
      pointerenter: (e) => {
        if (e.pointerType === "mouse") {
          rowNode.dispatchRowEvent("mouseEnter");
        }
      },
      pointerleave: (e) => {
        if (e.pointerType === "mouse") {
          rowNode.dispatchRowEvent("mouseLeave");
        }
      }
    });
    compBean.addManagedListeners(rowNode, {
      mouseEnter: () => {
        if (!beans.dragSvc?.dragging && !gos.get("suppressRowHoverHighlight")) {
          element.classList.add("ag-row-hover");
          rowNode.setHovered(true);
        }
      },
      mouseLeave: () => {
        this.resetHoveredStatus(element);
      }
    });
  }
  resetHoveredStatus(el) {
    const elements = el ? [el] : this.allRowGuis.map((gui) => gui.element);
    for (const element of elements) {
      element.classList.remove("ag-row-hover");
    }
    this.rowNode.setHovered(false);
  }
  // for animation, we don't want to animate entry or exit to a very far away pixel,
  // otherwise the row would move so fast, it would appear to disappear. so this method
  // moves the row closer to the viewport if it is far away, so the row slide in / out
  // at a speed the user can see.
  roundRowTopToBounds(rowTop) {
    const range = this.beans.ctrlsSvc.getScrollFeature().getApproximateVScollPosition();
    const minPixel = this.applyPaginationOffset(range.top, true) - 100;
    const maxPixel = this.applyPaginationOffset(range.bottom, true) + 100;
    return Math.min(Math.max(minPixel, rowTop), maxPixel);
  }
  forEachGui(gui, callback) {
    if (gui) {
      callback(gui);
    } else {
      for (const gui2 of this.allRowGuis) {
        callback(gui2);
      }
    }
  }
  isRowRendered() {
    return this.allRowGuis.length > 0;
  }
  onRowHeightChanged(gui) {
    if (this.rowNode.rowHeight == null) {
      return;
    }
    const rowHeight = this.rowNode.rowHeight;
    const defaultRowHeight = this.beans.environment.getDefaultRowHeight();
    const isHeightFromFunc = _isGetRowHeightFunction(this.gos);
    const heightFromFunc = isHeightFromFunc ? _getRowHeightForNode(this.beans, this.rowNode).height : void 0;
    const lineHeight = heightFromFunc ? `${Math.min(defaultRowHeight, heightFromFunc) - 2}px` : void 0;
    this.forEachGui(gui, (gui2) => {
      gui2.element.style.height = `${rowHeight}px`;
      if (lineHeight) {
        gui2.element.style.setProperty("--ag-line-height", lineHeight);
      }
    });
  }
  // note - this is NOT called by context, as we don't wire / unwire the CellComp for performance reasons.
  destroyFirstPass(suppressAnimation = false) {
    this.active = false;
    const { rowNode } = this;
    if (!suppressAnimation && _isAnimateRows(this.gos) && !rowNode.sticky) {
      const rowStillVisibleJustNotInViewport = rowNode.rowTop != null;
      if (rowStillVisibleJustNotInViewport) {
        const rowTop = this.roundRowTopToBounds(rowNode.rowTop);
        this.setRowTop(rowTop);
      } else {
        for (const gui of this.allRowGuis) {
          gui.rowComp.toggleCss("ag-opacity-zero", true);
        }
      }
    }
    if (this.fullWidthGui?.element.contains(_getActiveDomElement(this.beans))) {
      this.beans.focusSvc.attemptToRecoverFocus();
    }
    rowNode.setHovered(false);
    const event = this.createRowEvent("virtualRowRemoved");
    this.dispatchLocalEvent(event);
    this.beans.eventSvc.dispatchEvent(event);
    super.destroy();
  }
  destroySecondPass() {
    this.allRowGuis.length = 0;
    const destroyCellCtrls = (ctrls) => {
      for (const c2 of ctrls.list) {
        c2.destroy();
      }
      return { list: [], map: {} };
    };
    this.centerCellCtrls = destroyCellCtrls(this.centerCellCtrls);
    this.leftCellCtrls = destroyCellCtrls(this.leftCellCtrls);
    this.rightCellCtrls = destroyCellCtrls(this.rightCellCtrls);
  }
  setFocusedClasses(gui) {
    this.forEachGui(gui, (gui2) => {
      gui2.rowComp.toggleCss("ag-row-focus", this.rowFocused);
      gui2.rowComp.toggleCss("ag-row-no-focus", !this.rowFocused);
    });
  }
  onCellFocusChanged() {
    const { focusSvc } = this.beans;
    const rowFocused = focusSvc.isRowFocused(this.rowNode.rowIndex, this.rowNode.rowPinned);
    if (rowFocused !== this.rowFocused) {
      this.rowFocused = rowFocused;
      this.setFocusedClasses();
    }
  }
  onPaginationChanged() {
    const currentPage = this.beans.pagination?.getCurrentPage() ?? 0;
    if (this.paginationPage !== currentPage) {
      this.paginationPage = currentPage;
      this.onTopChanged();
    }
    this.refreshFirstAndLastRowStyles();
  }
  onTopChanged() {
    this.setRowTop(this.rowNode.rowTop);
  }
  onPaginationPixelOffsetChanged() {
    this.onTopChanged();
  }
  // applies pagination offset, eg if on second page, and page height is 500px, then removes
  // 500px from the top position, so a row with rowTop 600px is displayed at location 100px.
  // reverse will take the offset away rather than add.
  applyPaginationOffset(topPx, reverse2 = false) {
    if (this.rowNode.isRowPinned() || this.rowNode.sticky) {
      return topPx;
    }
    const pixelOffset = this.beans.pageBounds.getPixelOffset();
    const multiplier = reverse2 ? 1 : -1;
    return topPx + pixelOffset * multiplier;
  }
  setRowTop(pixels) {
    if (this.printLayout) {
      return;
    }
    if (_exists(pixels)) {
      const afterPaginationPixels = this.applyPaginationOffset(pixels);
      const skipScaling = this.rowNode.isRowPinned() || this.rowNode.sticky;
      const afterScalingPixels = skipScaling ? afterPaginationPixels : this.beans.rowContainerHeight.getRealPixelPosition(afterPaginationPixels);
      const topPx = `${afterScalingPixels}px`;
      this.setRowTopStyle(topPx);
    }
  }
  // the top needs to be set into the DOM element when the element is created, not updated afterwards.
  // otherwise the transition would not work, as it would be transitioning from zero (the unset value).
  // for example, suppose a row that is outside the viewport, then user does a filter to remove other rows
  // and this row now appears in the viewport, and the row moves up (ie it was under the viewport and not rendered,
  // but now is in the viewport) then a new RowComp is created, however it should have it's position initialised
  // to below the viewport, so the row will appear to animate up. if we didn't set the initial position at creation
  // time, the row would animate down (ie from position zero).
  getInitialRowTop(rowContainerType) {
    return this.suppressRowTransform ? this.getInitialRowTopShared(rowContainerType) : void 0;
  }
  getInitialTransform(rowContainerType) {
    return this.suppressRowTransform ? void 0 : `translateY(${this.getInitialRowTopShared(rowContainerType)})`;
  }
  getInitialRowTopShared(rowContainerType) {
    if (this.printLayout) {
      return "";
    }
    const rowNode = this.rowNode;
    let rowTop;
    if (rowNode.sticky) {
      rowTop = rowNode.stickyRowTop;
    } else {
      const pixels = this.slideInAnimation[rowContainerType] ? this.roundRowTopToBounds(rowNode.oldRowTop) : rowNode.rowTop;
      const afterPaginationPixels = this.applyPaginationOffset(pixels);
      rowTop = rowNode.isRowPinned() ? afterPaginationPixels : this.beans.rowContainerHeight.getRealPixelPosition(afterPaginationPixels);
    }
    return rowTop + "px";
  }
  setRowTopStyle(topPx) {
    for (const gui of this.allRowGuis) {
      this.suppressRowTransform ? gui.rowComp.setTop(topPx) : gui.rowComp.setTransform(`translateY(${topPx})`);
    }
  }
  getCellCtrl(column2, skipColSpanSearch = false) {
    let res = null;
    for (const cellCtrl of this.getAllCellCtrls()) {
      if (cellCtrl.column == column2) {
        res = cellCtrl;
      }
    }
    if (res != null || skipColSpanSearch) {
      return res;
    }
    for (const cellCtrl of this.getAllCellCtrls()) {
      if (cellCtrl?.getColSpanningList().indexOf(column2) >= 0) {
        res = cellCtrl;
      }
    }
    return res;
  }
  onRowIndexChanged() {
    if (this.rowNode.rowIndex != null) {
      this.onCellFocusChanged();
      this.updateRowIndexes();
      this.postProcessCss();
    }
  }
  updateRowIndexes(gui) {
    const rowIndexStr = this.rowNode.getRowIndexString();
    if (rowIndexStr === null) {
      return;
    }
    const headerRowCount = (this.beans.ctrlsSvc.getHeaderRowContainerCtrl()?.getRowCount() ?? 0) + (this.beans.filterManager?.getHeaderRowCount() ?? 0);
    const rowIsEven = this.rowNode.rowIndex % 2 === 0;
    const ariaRowIndex = headerRowCount + this.rowNode.rowIndex + 1;
    this.forEachGui(gui, (c2) => {
      c2.rowComp.setRowIndex(rowIndexStr);
      c2.rowComp.toggleCss("ag-row-even", rowIsEven);
      c2.rowComp.toggleCss("ag-row-odd", !rowIsEven);
      _setAriaRowIndex(c2.element, ariaRowIndex);
    });
  }
};
var NavigationService = class extends BeanStub {
  constructor() {
    super();
    this.beanName = "navigation";
    this.onPageDown = _throttle(this.onPageDown, 100);
    this.onPageUp = _throttle(this.onPageUp, 100);
  }
  postConstruct() {
    this.beans.ctrlsSvc.whenReady(this, (p) => {
      this.gridBodyCon = p.gridBodyCtrl;
    });
  }
  handlePageScrollingKey(event, fromFullWidth = false) {
    const key2 = event.key;
    const alt = event.altKey;
    const ctrl = event.ctrlKey || event.metaKey;
    const rangeServiceShouldHandleShift = !!this.beans.rangeSvc && event.shiftKey;
    const currentCell = _getCellPositionForEvent(this.gos, event);
    let processed = false;
    switch (key2) {
      case KeyCode.PAGE_HOME:
      case KeyCode.PAGE_END:
        if (!ctrl && !alt) {
          this.onHomeOrEndKey(key2);
          processed = true;
        }
        break;
      case KeyCode.LEFT:
      case KeyCode.RIGHT:
      case KeyCode.UP:
      case KeyCode.DOWN:
        if (!currentCell) {
          return false;
        }
        if (ctrl && !alt && !rangeServiceShouldHandleShift) {
          this.onCtrlUpDownLeftRight(key2, currentCell);
          processed = true;
        }
        break;
      case KeyCode.PAGE_DOWN:
      case KeyCode.PAGE_UP:
        if (!ctrl && !alt) {
          processed = this.handlePageUpDown(key2, currentCell, fromFullWidth);
        }
        break;
    }
    if (processed) {
      event.preventDefault();
    }
    return processed;
  }
  handlePageUpDown(key2, currentCell, fromFullWidth) {
    if (fromFullWidth) {
      currentCell = this.beans.focusSvc.getFocusedCell();
    }
    if (!currentCell) {
      return false;
    }
    if (key2 === KeyCode.PAGE_UP) {
      this.onPageUp(currentCell);
    } else {
      this.onPageDown(currentCell);
    }
    return true;
  }
  navigateTo({
    scrollIndex,
    scrollType,
    scrollColumn,
    focusIndex,
    focusColumn,
    isAsync,
    rowPinned
  }) {
    const { scrollFeature } = this.gridBodyCon;
    if (_exists(scrollColumn) && !scrollColumn.isPinned()) {
      scrollFeature.ensureColumnVisible(scrollColumn);
    }
    if (_exists(scrollIndex)) {
      scrollFeature.ensureIndexVisible(scrollIndex, scrollType);
    }
    if (!isAsync) {
      scrollFeature.ensureIndexVisible(focusIndex);
    }
    const { focusSvc, rangeSvc } = this.beans;
    focusSvc.setFocusedCell({
      rowIndex: focusIndex,
      column: focusColumn,
      rowPinned,
      forceBrowserFocus: true
    });
    rangeSvc?.setRangeToCell({ rowIndex: focusIndex, rowPinned, column: focusColumn });
  }
  // this method is throttled, see the `constructor`
  onPageDown(gridCell) {
    const beans = this.beans;
    const scrollPosition = getVScroll(beans);
    const pixelsInOnePage = this.getViewportHeight();
    const { pageBounds, rowModel, rowAutoHeight } = beans;
    const pagingPixelOffset = pageBounds.getPixelOffset();
    const currentPageBottomPixel = scrollPosition.top + pixelsInOnePage;
    const currentPageBottomRow = rowModel.getRowIndexAtPixel(currentPageBottomPixel + pagingPixelOffset);
    if (rowAutoHeight?.active) {
      this.navigateToNextPageWithAutoHeight(gridCell, currentPageBottomRow);
    } else {
      this.navigateToNextPage(gridCell, currentPageBottomRow);
    }
  }
  // this method is throttled, see the `constructor`
  onPageUp(gridCell) {
    const beans = this.beans;
    const scrollPosition = getVScroll(beans);
    const { pageBounds, rowModel, rowAutoHeight } = beans;
    const pagingPixelOffset = pageBounds.getPixelOffset();
    const currentPageTopPixel = scrollPosition.top;
    const currentPageTopRow = rowModel.getRowIndexAtPixel(currentPageTopPixel + pagingPixelOffset);
    if (rowAutoHeight?.active) {
      this.navigateToNextPageWithAutoHeight(gridCell, currentPageTopRow, true);
    } else {
      this.navigateToNextPage(gridCell, currentPageTopRow, true);
    }
  }
  navigateToNextPage(gridCell, scrollIndex, up = false) {
    const { pageBounds, rowModel } = this.beans;
    const pixelsInOnePage = this.getViewportHeight();
    const firstRow = pageBounds.getFirstRow();
    const lastRow = pageBounds.getLastRow();
    const pagingPixelOffset = pageBounds.getPixelOffset();
    const currentRowNode = rowModel.getRow(gridCell.rowIndex);
    const rowPixelDiff = up ? (
      // eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain
      currentRowNode?.rowHeight - pixelsInOnePage - pagingPixelOffset
    ) : pixelsInOnePage - pagingPixelOffset;
    const nextCellPixel = currentRowNode?.rowTop + rowPixelDiff;
    let focusIndex = rowModel.getRowIndexAtPixel(nextCellPixel + pagingPixelOffset);
    if (focusIndex === gridCell.rowIndex) {
      const diff2 = up ? -1 : 1;
      scrollIndex = focusIndex = gridCell.rowIndex + diff2;
    }
    let scrollType;
    if (up) {
      scrollType = "bottom";
      if (focusIndex < firstRow) {
        focusIndex = firstRow;
      }
      if (scrollIndex < firstRow) {
        scrollIndex = firstRow;
      }
    } else {
      scrollType = "top";
      if (focusIndex > lastRow) {
        focusIndex = lastRow;
      }
      if (scrollIndex > lastRow) {
        scrollIndex = lastRow;
      }
    }
    if (this.isRowTallerThanView(rowModel.getRow(focusIndex))) {
      scrollIndex = focusIndex;
      scrollType = "top";
    }
    this.navigateTo({
      scrollIndex,
      scrollType,
      scrollColumn: null,
      focusIndex,
      focusColumn: gridCell.column
    });
  }
  navigateToNextPageWithAutoHeight(gridCell, scrollIndex, up = false) {
    this.navigateTo({
      scrollIndex,
      scrollType: up ? "bottom" : "top",
      scrollColumn: null,
      focusIndex: scrollIndex,
      focusColumn: gridCell.column
    });
    setTimeout(() => {
      const focusIndex = this.getNextFocusIndexForAutoHeight(gridCell, up);
      this.navigateTo({
        scrollIndex,
        scrollType: up ? "bottom" : "top",
        scrollColumn: null,
        focusIndex,
        focusColumn: gridCell.column,
        isAsync: true
      });
    }, 50);
  }
  getNextFocusIndexForAutoHeight(gridCell, up = false) {
    const step = up ? -1 : 1;
    const pixelsInOnePage = this.getViewportHeight();
    const { pageBounds, rowModel } = this.beans;
    const lastRowIndex = pageBounds.getLastRow();
    let pixelSum = 0;
    let currentIndex = gridCell.rowIndex;
    while (currentIndex >= 0 && currentIndex <= lastRowIndex) {
      const currentCell = rowModel.getRow(currentIndex);
      if (currentCell) {
        const currentCellHeight = currentCell.rowHeight ?? 0;
        if (pixelSum + currentCellHeight > pixelsInOnePage) {
          break;
        }
        pixelSum += currentCellHeight;
      }
      currentIndex += step;
    }
    return Math.max(0, Math.min(currentIndex, lastRowIndex));
  }
  getViewportHeight() {
    const beans = this.beans;
    const scrollPosition = getVScroll(beans);
    const scrollbarWidth = this.beans.scrollVisibleSvc.getScrollbarWidth();
    let pixelsInOnePage = scrollPosition.bottom - scrollPosition.top;
    if (beans.ctrlsSvc.get("center").isHorizontalScrollShowing()) {
      pixelsInOnePage -= scrollbarWidth;
    }
    return pixelsInOnePage;
  }
  isRowTallerThanView(rowNode) {
    if (!rowNode) {
      return false;
    }
    const rowHeight = rowNode.rowHeight;
    if (typeof rowHeight !== "number") {
      return false;
    }
    return rowHeight > this.getViewportHeight();
  }
  onCtrlUpDownLeftRight(key2, gridCell) {
    const cellToFocus = this.beans.cellNavigation.getNextCellToFocus(key2, gridCell, true);
    const normalisedPosition = this.getNormalisedPosition(cellToFocus);
    const { rowIndex, rowPinned, column: column2 } = normalisedPosition ?? cellToFocus;
    const col = column2;
    this.navigateTo({
      scrollIndex: rowIndex,
      scrollType: null,
      scrollColumn: col,
      focusIndex: rowIndex,
      focusColumn: col,
      rowPinned
    });
  }
  // home brings focus to top left cell, end brings focus to bottom right, grid scrolled to bring
  // same cell into view (which means either scroll all the way up, or all the way down).
  onHomeOrEndKey(key2) {
    const homeKey = key2 === KeyCode.PAGE_HOME;
    const { visibleCols, pageBounds, rowModel } = this.beans;
    const allColumns = visibleCols.allCols;
    const scrollIndex = homeKey ? pageBounds.getFirstRow() : pageBounds.getLastRow();
    const rowNode = rowModel.getRow(scrollIndex);
    if (!rowNode) {
      return;
    }
    const columnToSelect = (homeKey ? allColumns : [...allColumns].reverse()).find(
      (col) => !col.isSuppressNavigable(rowNode)
    );
    if (!columnToSelect) {
      return;
    }
    this.navigateTo({
      scrollIndex,
      scrollType: null,
      scrollColumn: columnToSelect,
      focusIndex: scrollIndex,
      focusColumn: columnToSelect
    });
  }
  // result of keyboard event
  onTabKeyDown(previous, keyboardEvent) {
    const backwards = keyboardEvent.shiftKey;
    const movedToNextCell = this.tabToNextCellCommon(previous, backwards, keyboardEvent);
    const beans = this.beans;
    const { ctrlsSvc, pageBounds, focusSvc, gos } = beans;
    if (movedToNextCell !== false) {
      if (movedToNextCell) {
        keyboardEvent.preventDefault();
      } else if (movedToNextCell === null) {
        ctrlsSvc.get("gridCtrl").allowFocusForNextCoreContainer(backwards);
      }
      return;
    }
    if (backwards) {
      const { rowIndex, rowPinned } = previous.getRowPosition();
      const firstRow = rowPinned ? rowIndex === 0 : rowIndex === pageBounds.getFirstRow();
      if (firstRow) {
        if (gos.get("headerHeight") === 0 || _isHeaderFocusSuppressed(beans)) {
          _focusNextGridCoreContainer(beans, true, true);
        } else {
          keyboardEvent.preventDefault();
          focusSvc.focusPreviousFromFirstCell(keyboardEvent);
        }
      }
    } else {
      if (previous instanceof CellCtrl) {
        previous.focusCell(true);
      }
      if (focusSvc.focusOverlay(false) || _focusNextGridCoreContainer(beans, backwards)) {
        keyboardEvent.preventDefault();
      }
    }
  }
  // comes from API
  tabToNextCell(backwards, event) {
    const beans = this.beans;
    const { focusSvc, rowRenderer } = beans;
    const focusedCell = focusSvc.getFocusedCell();
    if (!focusedCell) {
      return false;
    }
    let cellOrRow = _getCellByPosition(beans, focusedCell);
    if (!cellOrRow) {
      cellOrRow = rowRenderer.getRowByPosition(focusedCell);
      if (!cellOrRow?.isFullWidth()) {
        return false;
      }
    }
    return !!this.tabToNextCellCommon(cellOrRow, backwards, event, "api");
  }
  tabToNextCellCommon(previous, backwards, event, source2 = "ui") {
    const { editSvc, focusSvc } = this.beans;
    let res = void 0;
    const cellCtrl = previous instanceof CellCtrl ? previous : previous.getAllCellCtrls()?.[0];
    if (editSvc?.isEditing()) {
      res = editSvc?.moveToNextCell(cellCtrl, backwards, event, source2);
    } else {
      res = this.moveToNextCellNotEditing(previous, backwards, event);
    }
    if (res === null) {
      return res;
    }
    return res || !!focusSvc.focusedHeader;
  }
  // returns null if no navigation should be performed
  moveToNextCellNotEditing(previousCell, backwards, event) {
    const displayedColumns = this.beans.visibleCols.allCols;
    let cellPos;
    if (previousCell instanceof RowCtrl) {
      cellPos = {
        ...previousCell.getRowPosition(),
        column: backwards ? displayedColumns[0] : _last(displayedColumns)
      };
      if (this.gos.get("embedFullWidthRows") && event) {
        const focusedContainer = previousCell.findFullWidthInfoForEvent(event);
        if (focusedContainer) {
          cellPos.column = focusedContainer.column;
        }
      }
    } else {
      cellPos = previousCell.getFocusedCellPosition();
    }
    const nextCell = this.findNextCellToFocusOn(cellPos, { backwards, startEditing: false });
    if (nextCell === false) {
      return null;
    }
    if (nextCell instanceof CellCtrl) {
      nextCell.focusCell(true);
    } else if (nextCell) {
      return this.tryToFocusFullWidthRow(nextCell, backwards);
    }
    return _exists(nextCell);
  }
  /**
   * called by the cell, when tab is pressed while editing.
   * @returns RenderedCell when navigation successful, false if navigation should not be performed, otherwise null
   */
  findNextCellToFocusOn(previousPosition, { backwards, startEditing, skipToNextEditableCell }) {
    let nextPosition = previousPosition;
    const beans = this.beans;
    const { cellNavigation, gos, focusSvc, rowRenderer, rangeSvc } = beans;
    while (true) {
      if (previousPosition !== nextPosition) {
        previousPosition = nextPosition;
      }
      if (!backwards) {
        nextPosition = this.getLastCellOfColSpan(nextPosition);
      }
      nextPosition = cellNavigation.getNextTabbedCell(nextPosition, backwards);
      const userFunc = gos.getCallback("tabToNextCell");
      if (_exists(userFunc)) {
        const params = {
          backwards,
          editing: startEditing,
          previousCellPosition: previousPosition,
          nextCellPosition: nextPosition ? nextPosition : null
        };
        const userResult = userFunc(params);
        if (userResult === true) {
          nextPosition = previousPosition;
        } else if (userResult === false) {
          return false;
        } else {
          nextPosition = {
            rowIndex: userResult.rowIndex,
            column: userResult.column,
            rowPinned: userResult.rowPinned
          };
        }
      }
      if (!nextPosition) {
        return null;
      }
      if (nextPosition.rowIndex < 0) {
        const headerLen = getFocusHeaderRowCount(beans);
        focusSvc.focusHeaderPosition({
          headerPosition: {
            headerRowIndex: headerLen + nextPosition.rowIndex,
            column: nextPosition.column
          },
          fromCell: true
        });
        return null;
      }
      const fullRowEdit = gos.get("editType") === "fullRow";
      if (startEditing && (!fullRowEdit || skipToNextEditableCell)) {
        const cellIsEditable = this.isCellEditable(nextPosition);
        if (!cellIsEditable) {
          continue;
        }
      }
      this.ensureCellVisible(nextPosition);
      const nextCell = _getCellByPosition(beans, nextPosition);
      if (!nextCell) {
        const row2 = rowRenderer.getRowByPosition(nextPosition);
        if (!row2 || !row2.isFullWidth() || startEditing) {
          continue;
        }
        return { ...row2.getRowPosition(), column: nextPosition?.column };
      }
      if (cellNavigation.isSuppressNavigable(nextCell.column, nextCell.rowNode)) {
        continue;
      }
      nextCell.setFocusedCellPosition(nextPosition);
      rangeSvc?.setRangeToCell(nextPosition);
      return nextCell;
    }
  }
  isCellEditable(cell2) {
    const rowNode = this.lookupRowNodeForCell(cell2);
    if (rowNode) {
      return cell2.column.isCellEditable(rowNode);
    }
    return false;
  }
  lookupRowNodeForCell({ rowIndex, rowPinned }) {
    const { pinnedRowModel, rowModel } = this.beans;
    if (rowPinned === "top") {
      return pinnedRowModel?.getPinnedTopRow(rowIndex);
    }
    if (rowPinned === "bottom") {
      return pinnedRowModel?.getPinnedBottomRow(rowIndex);
    }
    return rowModel.getRow(rowIndex);
  }
  // we use index for rows, but column object for columns, as the next column (by index) might not
  // be visible (header grouping) so it's not reliable, so using the column object instead.
  navigateToNextCell(event, key2, currentCell, allowUserOverride) {
    let nextCell = currentCell;
    let hitEdgeOfGrid = false;
    const beans = this.beans;
    const { cellNavigation, focusSvc, gos } = beans;
    while (nextCell && (nextCell === currentCell || !this.isValidNavigateCell(nextCell))) {
      if (gos.get("enableRtl")) {
        if (key2 === KeyCode.LEFT) {
          nextCell = this.getLastCellOfColSpan(nextCell);
        }
      } else if (key2 === KeyCode.RIGHT) {
        nextCell = this.getLastCellOfColSpan(nextCell);
      }
      nextCell = cellNavigation.getNextCellToFocus(key2, nextCell);
      hitEdgeOfGrid = _missing(nextCell);
    }
    if (hitEdgeOfGrid && event && event.key === KeyCode.UP) {
      nextCell = {
        rowIndex: -1,
        rowPinned: null,
        column: currentCell.column
      };
    }
    if (allowUserOverride) {
      const userFunc = gos.getCallback("navigateToNextCell");
      if (_exists(userFunc)) {
        const params = {
          key: key2,
          previousCellPosition: currentCell,
          nextCellPosition: nextCell ? nextCell : null,
          event
        };
        const userCell = userFunc(params);
        if (_exists(userCell)) {
          nextCell = {
            rowPinned: userCell.rowPinned,
            rowIndex: userCell.rowIndex,
            column: userCell.column
          };
        } else {
          nextCell = null;
        }
      }
    }
    if (!nextCell) {
      return;
    }
    if (nextCell.rowIndex < 0) {
      const headerLen = getFocusHeaderRowCount(beans);
      focusSvc.focusHeaderPosition({
        headerPosition: { headerRowIndex: headerLen + nextCell.rowIndex, column: currentCell.column },
        event: event || void 0,
        fromCell: true
      });
      return;
    }
    const normalisedPosition = this.getNormalisedPosition(nextCell);
    if (normalisedPosition) {
      this.focusPosition(normalisedPosition);
    } else {
      this.tryToFocusFullWidthRow(nextCell);
    }
  }
  getNormalisedPosition(cellPosition) {
    const isSpannedCell = !!this.beans.spannedRowRenderer?.getCellByPosition(cellPosition);
    if (isSpannedCell) {
      return cellPosition;
    }
    this.ensureCellVisible(cellPosition);
    const cellCtrl = _getCellByPosition(this.beans, cellPosition);
    if (!cellCtrl) {
      return null;
    }
    cellPosition = cellCtrl.getFocusedCellPosition();
    this.ensureCellVisible(cellPosition);
    return cellPosition;
  }
  tryToFocusFullWidthRow(position, backwards) {
    const { visibleCols, rowRenderer, focusSvc, eventSvc } = this.beans;
    const displayedColumns = visibleCols.allCols;
    const rowComp = rowRenderer.getRowByPosition(position);
    if (!rowComp?.isFullWidth()) {
      return false;
    }
    const currentCellFocused = focusSvc.getFocusedCell();
    const cellPosition = {
      rowIndex: position.rowIndex,
      rowPinned: position.rowPinned,
      column: position.column || (backwards ? _last(displayedColumns) : displayedColumns[0])
    };
    this.focusPosition(cellPosition);
    const fromBelow = backwards == null ? currentCellFocused != null && _isRowBefore(cellPosition, currentCellFocused) : backwards;
    eventSvc.dispatchEvent({
      type: "fullWidthRowFocused",
      rowIndex: cellPosition.rowIndex,
      rowPinned: cellPosition.rowPinned,
      column: cellPosition.column,
      isFullWidthCell: true,
      fromBelow
    });
    return true;
  }
  focusPosition(cellPosition) {
    const { focusSvc, rangeSvc } = this.beans;
    focusSvc.setFocusedCell({
      rowIndex: cellPosition.rowIndex,
      column: cellPosition.column,
      rowPinned: cellPosition.rowPinned,
      forceBrowserFocus: true
    });
    rangeSvc?.setRangeToCell(cellPosition);
  }
  isValidNavigateCell(cell2) {
    const rowNode = _getRowNode(this.beans, cell2);
    return !!rowNode;
  }
  getLastCellOfColSpan(cell2) {
    const cellCtrl = _getCellByPosition(this.beans, cell2);
    if (!cellCtrl) {
      return cell2;
    }
    const colSpanningList = cellCtrl.getColSpanningList();
    if (colSpanningList.length === 1) {
      return cell2;
    }
    return {
      rowIndex: cell2.rowIndex,
      column: _last(colSpanningList),
      rowPinned: cell2.rowPinned
    };
  }
  ensureCellVisible(gridCell) {
    const isGroupStickyEnabled = _isGroupRowsSticky(this.gos);
    const rowNode = this.beans.rowModel.getRow(gridCell.rowIndex);
    const skipScrollToRow = isGroupStickyEnabled && rowNode?.sticky;
    const { scrollFeature } = this.gridBodyCon;
    if (!skipScrollToRow && _missing(gridCell.rowPinned)) {
      scrollFeature.ensureIndexVisible(gridCell.rowIndex);
    }
    if (!gridCell.column.isPinned()) {
      scrollFeature.ensureColumnVisible(gridCell.column);
    }
  }
  ensureColumnVisible(column2) {
    const scrollFeature = this.gridBodyCon.scrollFeature;
    if (!column2.isPinned()) {
      scrollFeature.ensureColumnVisible(column2);
    }
  }
  ensureRowVisible(rowIndex) {
    const scrollFeature = this.gridBodyCon.scrollFeature;
    scrollFeature.ensureIndexVisible(rowIndex);
  }
};
function getVScroll(beans) {
  return beans.ctrlsSvc.getScrollFeature().getVScrollPosition();
}
var KeyboardNavigationModule = {
  moduleName: "KeyboardNavigation",
  version: VERSION,
  beans: [NavigationService, CellNavigationService, HeaderNavigationService],
  apiFunctions: {
    getFocusedCell,
    clearFocusedCell,
    setFocusedCell,
    setFocusedHeader,
    tabToNextCell,
    tabToPreviousCell
  }
};
var PageBoundsListener = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "pageBoundsListener";
  }
  postConstruct() {
    this.addManagedEventListeners({
      modelUpdated: this.onModelUpdated.bind(this),
      recalculateRowBounds: this.calculatePages.bind(this)
    });
    this.onModelUpdated();
  }
  onModelUpdated(modelUpdatedEvent) {
    this.calculatePages();
    this.eventSvc.dispatchEvent({
      type: "paginationChanged",
      animate: modelUpdatedEvent?.animate ?? false,
      newData: modelUpdatedEvent?.newData ?? false,
      newPage: modelUpdatedEvent?.newPage ?? false,
      newPageSize: modelUpdatedEvent?.newPageSize ?? false,
      keepRenderedRows: modelUpdatedEvent?.keepRenderedRows ?? false
    });
  }
  calculatePages() {
    const { pageBounds, pagination, rowModel } = this.beans;
    if (pagination) {
      pagination.calculatePages();
    } else {
      pageBounds.calculateBounds(0, rowModel.getRowCount() - 1);
    }
  }
};
var PageBoundsService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "pageBounds";
    this.pixelOffset = 0;
  }
  getFirstRow() {
    return this.topRowBounds?.rowIndex ?? -1;
  }
  getLastRow() {
    return this.bottomRowBounds?.rowIndex ?? -1;
  }
  getCurrentPageHeight() {
    const { topRowBounds, bottomRowBounds } = this;
    if (!topRowBounds || !bottomRowBounds) {
      return 0;
    }
    return Math.max(bottomRowBounds.rowTop + bottomRowBounds.rowHeight - topRowBounds.rowTop, 0);
  }
  getCurrentPagePixelRange() {
    const { topRowBounds, bottomRowBounds } = this;
    const pageFirstPixel = topRowBounds?.rowTop ?? 0;
    const pageLastPixel = bottomRowBounds ? bottomRowBounds.rowTop + bottomRowBounds.rowHeight : 0;
    return { pageFirstPixel, pageLastPixel };
  }
  calculateBounds(topDisplayedRowIndex, bottomDisplayedRowIndex) {
    const { rowModel } = this.beans;
    const topRowBounds = rowModel.getRowBounds(topDisplayedRowIndex);
    if (topRowBounds) {
      topRowBounds.rowIndex = topDisplayedRowIndex;
    }
    this.topRowBounds = topRowBounds;
    const bottomRowBounds = rowModel.getRowBounds(bottomDisplayedRowIndex);
    if (bottomRowBounds) {
      bottomRowBounds.rowIndex = bottomDisplayedRowIndex;
    }
    this.bottomRowBounds = bottomRowBounds;
    this.calculatePixelOffset();
  }
  getPixelOffset() {
    return this.pixelOffset;
  }
  calculatePixelOffset() {
    const value2 = this.topRowBounds?.rowTop ?? 0;
    if (this.pixelOffset === value2) {
      return;
    }
    this.pixelOffset = value2;
    this.eventSvc.dispatchEvent({ type: "paginationPixelOffsetChanged" });
  }
};
var pinnedColumnModuleCSS = (
  /*css*/
  `.ag-pinned-left-floating-bottom,.ag-pinned-left-floating-top,.ag-pinned-right-floating-bottom,.ag-pinned-right-floating-top{min-width:0;overflow:hidden;position:relative}.ag-pinned-left-sticky-top,.ag-pinned-right-sticky-top{height:100%;overflow:hidden;position:relative}.ag-sticky-bottom-full-width-container,.ag-sticky-top-full-width-container{height:100%;overflow:hidden;width:100%}.ag-pinned-left-header,.ag-pinned-right-header{display:inline-block;height:100%;overflow:hidden;position:relative}.ag-body-horizontal-scroll:not(.ag-scrollbar-invisible){.ag-horizontal-left-spacer:not(.ag-scroller-corner){border-right:var(--ag-pinned-column-border)}.ag-horizontal-right-spacer:not(.ag-scroller-corner){border-left:var(--ag-pinned-column-border)}}.ag-pinned-right-header{border-left:var(--ag-pinned-column-border)}.ag-pinned-left-header{border-right:var(--ag-pinned-column-border)}.ag-cell.ag-cell-first-right-pinned:not(.ag-cell-range-left,.ag-cell-range-single-cell,.ag-cell-focus:not(.ag-cell-range-selected):focus-within){border-left:var(--ag-pinned-column-border)}.ag-cell.ag-cell-last-left-pinned:not(.ag-cell-range-right,.ag-cell-range-single-cell,.ag-cell-focus:not(.ag-cell-range-selected):focus-within){border-right:var(--ag-pinned-column-border)}.ag-pinned-left-header .ag-header-cell-resize:after{left:calc(50% - var(--ag-header-column-resize-handle-width))}.ag-pinned-right-header .ag-header-cell-resize:after{left:50%}.ag-pinned-left-header .ag-header-cell-resize{right:-3px}.ag-pinned-right-header .ag-header-cell-resize{left:-3px}`
);
var SetPinnedWidthFeature = class extends BeanStub {
  constructor(isLeft, elements) {
    super();
    this.isLeft = isLeft;
    this.elements = elements;
    this.getWidth = isLeft ? () => this.beans.pinnedCols.leftWidth : () => this.beans.pinnedCols.rightWidth;
  }
  postConstruct() {
    this.addManagedEventListeners({
      [`${this.isLeft ? "left" : "right"}PinnedWidthChanged`]: this.onPinnedWidthChanged.bind(this)
    });
  }
  onPinnedWidthChanged() {
    const width = this.getWidth();
    const displayed = width > 0;
    for (const element of this.elements) {
      if (element) {
        _setDisplayed(element, displayed);
        _setFixedWidth(element, width);
      }
    }
  }
};
var PinnedColumnService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "pinnedCols";
  }
  postConstruct() {
    this.beans.ctrlsSvc.whenReady(this, (p) => {
      this.gridBodyCtrl = p.gridBodyCtrl;
    });
    const listener = this.checkContainerWidths.bind(this);
    this.addManagedEventListeners({
      displayedColumnsChanged: listener,
      displayedColumnsWidthChanged: listener
    });
    this.addManagedPropertyListener("domLayout", listener);
  }
  checkContainerWidths() {
    const { gos, visibleCols, eventSvc } = this.beans;
    const printLayout = _isDomLayout(gos, "print");
    const newLeftWidth = printLayout ? 0 : visibleCols.getColsLeftWidth();
    const newRightWidth = printLayout ? 0 : visibleCols.getDisplayedColumnsRightWidth();
    if (newLeftWidth != this.leftWidth) {
      this.leftWidth = newLeftWidth;
      eventSvc.dispatchEvent({ type: "leftPinnedWidthChanged" });
    }
    if (newRightWidth != this.rightWidth) {
      this.rightWidth = newRightWidth;
      eventSvc.dispatchEvent({ type: "rightPinnedWidthChanged" });
    }
  }
  keepPinnedColumnsNarrowerThanViewport() {
    const eBodyViewport = this.gridBodyCtrl.eBodyViewport;
    const bodyWidth = _getInnerWidth(eBodyViewport);
    if (bodyWidth <= 50) {
      return;
    }
    const processedColumnsToRemove = this.getPinnedColumnsOverflowingViewport(bodyWidth - 50);
    const processUnpinnedColumns = this.gos.getCallback("processUnpinnedColumns");
    const { columns: columns2, hasLockedPinned } = processedColumnsToRemove;
    let columnsToRemove = columns2;
    if (!columnsToRemove.length && !hasLockedPinned) {
      return;
    }
    if (processUnpinnedColumns) {
      const params = {
        columns: columnsToRemove,
        viewportWidth: bodyWidth
      };
      columnsToRemove = processUnpinnedColumns(params);
    }
    if (!columnsToRemove?.length) {
      return;
    }
    columnsToRemove = columnsToRemove.filter((col) => !isRowNumberCol(col));
    this.setColsPinned(columnsToRemove, null, "viewportSizeFeature");
  }
  createPinnedWidthFeature(isLeft, ...elements) {
    return new SetPinnedWidthFeature(isLeft, elements);
  }
  setColsPinned(keys2, pinned, source2) {
    const { colModel, colAnimation, visibleCols, gos } = this.beans;
    if (!colModel.cols) {
      return;
    }
    if (!keys2?.length) {
      return;
    }
    if (_isDomLayout(gos, "print")) {
      _warn(37);
      return;
    }
    colAnimation?.start();
    let actualPinned;
    if (pinned === true || pinned === "left") {
      actualPinned = "left";
    } else if (pinned === "right") {
      actualPinned = "right";
    } else {
      actualPinned = null;
    }
    const updatedCols = [];
    for (const key2 of keys2) {
      if (!key2) {
        continue;
      }
      const column2 = colModel.getCol(key2);
      if (!column2) {
        continue;
      }
      if (column2.getPinned() !== actualPinned) {
        this.setColPinned(column2, actualPinned);
        updatedCols.push(column2);
      }
    }
    if (updatedCols.length) {
      visibleCols.refresh(source2);
      dispatchColumnPinnedEvent(this.eventSvc, updatedCols, source2);
    }
    colAnimation?.finish();
  }
  initCol(column2) {
    const { pinned, initialPinned } = column2.colDef;
    if (pinned !== void 0) {
      this.setColPinned(column2, pinned);
    } else {
      this.setColPinned(column2, initialPinned);
    }
  }
  setColPinned(column2, pinned) {
    if (pinned === true || pinned === "left") {
      column2.pinned = "left";
    } else if (pinned === "right") {
      column2.pinned = "right";
    } else {
      column2.pinned = null;
    }
    column2.dispatchStateUpdatedEvent("pinned");
  }
  setupHeaderPinnedWidth(ctrl) {
    const { scrollVisibleSvc } = this.beans;
    if (ctrl.pinned == null) {
      return;
    }
    const pinningLeft = ctrl.pinned === "left";
    const pinningRight = ctrl.pinned === "right";
    ctrl.hidden = true;
    const listener = () => {
      const width = pinningLeft ? this.leftWidth : this.rightWidth;
      if (width == null) {
        return;
      }
      const hidden2 = width == 0;
      const hiddenChanged = ctrl.hidden !== hidden2;
      const isRtl = this.gos.get("enableRtl");
      const scrollbarWidth = scrollVisibleSvc.getScrollbarWidth();
      const addPaddingForScrollbar = scrollVisibleSvc.verticalScrollShowing && (isRtl && pinningLeft || !isRtl && pinningRight);
      const widthWithPadding = addPaddingForScrollbar ? width + scrollbarWidth : width;
      ctrl.comp.setPinnedContainerWidth(`${widthWithPadding}px`);
      ctrl.comp.setDisplayed(!hidden2);
      if (hiddenChanged) {
        ctrl.hidden = hidden2;
        ctrl.refresh();
      }
    };
    ctrl.addManagedEventListeners({
      leftPinnedWidthChanged: listener,
      rightPinnedWidthChanged: listener,
      scrollVisibilityChanged: listener,
      scrollbarWidthChanged: listener
    });
  }
  getHeaderResizeDiff(diff2, column2) {
    const pinned = column2.getPinned();
    if (pinned) {
      const { leftWidth, rightWidth } = this;
      const bodyWidth = _getInnerWidth(this.beans.ctrlsSvc.getGridBodyCtrl().eBodyViewport) - 50;
      if (leftWidth + rightWidth + diff2 > bodyWidth) {
        if (bodyWidth > leftWidth + rightWidth) {
          diff2 = bodyWidth - leftWidth - rightWidth;
        } else {
          return 0;
        }
      }
    }
    return diff2;
  }
  getPinnedColumnsOverflowingViewport(viewportWidth) {
    const pinnedRightWidth = this.rightWidth ?? 0;
    const pinnedLeftWidth = this.leftWidth ?? 0;
    const totalPinnedWidth = pinnedRightWidth + pinnedLeftWidth;
    let hasLockedPinned = false;
    if (totalPinnedWidth < viewportWidth) {
      return { columns: [], hasLockedPinned };
    }
    const { visibleCols } = this.beans;
    const pinnedLeftColumns = [...visibleCols.leftCols];
    const pinnedRightColumns = [...visibleCols.rightCols];
    let indexRight = 0;
    let indexLeft = 0;
    const totalWidthRemoved = 0;
    const columnsToRemove = [];
    let spaceNecessary = totalPinnedWidth - totalWidthRemoved - viewportWidth;
    while ((indexLeft < pinnedLeftColumns.length || indexRight < pinnedRightColumns.length) && spaceNecessary > 0) {
      if (indexRight < pinnedRightColumns.length) {
        const currentColumn = pinnedRightColumns[indexRight++];
        if (currentColumn.colDef.lockPinned) {
          hasLockedPinned = true;
          continue;
        }
        spaceNecessary -= currentColumn.getActualWidth();
        columnsToRemove.push(currentColumn);
      }
      if (indexLeft < pinnedLeftColumns.length && spaceNecessary > 0) {
        const currentColumn = pinnedLeftColumns[indexLeft++];
        if (currentColumn.colDef.lockPinned) {
          hasLockedPinned = true;
          continue;
        }
        spaceNecessary -= currentColumn.getActualWidth();
        columnsToRemove.push(currentColumn);
      }
    }
    return { columns: columnsToRemove, hasLockedPinned };
  }
};
var PinnedColumnModule = {
  moduleName: "PinnedColumn",
  version: VERSION,
  beans: [PinnedColumnService],
  css: [pinnedColumnModuleCSS]
};
var AriaAnnouncementService = class extends BeanStub {
  constructor() {
    super();
    this.beanName = "ariaAnnounce";
    this.descriptionContainer = null;
    this.pendingAnnouncements = /* @__PURE__ */ new Map();
    this.lastAnnouncement = "";
    this.updateAnnouncement = _debounce(this, this.updateAnnouncement.bind(this), 200);
  }
  postConstruct() {
    const beans = this.beans;
    const eDocument = _getDocument(beans);
    const div = this.descriptionContainer = eDocument.createElement("div");
    div.classList.add("ag-aria-description-container");
    _setAriaLive(div, "polite");
    _setAriaRelevant(div, "additions text");
    _setAriaAtomic(div, true);
    beans.eGridDiv.appendChild(div);
  }
  /**
   * @param key used for debouncing calls
   */
  announceValue(value2, key2) {
    this.pendingAnnouncements.set(key2, value2);
    this.updateAnnouncement();
  }
  updateAnnouncement() {
    if (!this.descriptionContainer) {
      return;
    }
    const value2 = Array.from(this.pendingAnnouncements.values()).join(". ");
    this.pendingAnnouncements.clear();
    this.descriptionContainer.textContent = "";
    setTimeout(() => {
      this.handleAnnouncementUpdate(value2);
    }, 50);
  }
  handleAnnouncementUpdate(value2) {
    if (!this.isAlive() || !this.descriptionContainer) {
      return;
    }
    let valueToAnnounce = value2;
    if (valueToAnnounce == null || valueToAnnounce.replace(/[ .]/g, "") == "") {
      this.lastAnnouncement = "";
      return;
    }
    if (this.lastAnnouncement === valueToAnnounce) {
      valueToAnnounce = `${valueToAnnounce}​`;
    }
    this.lastAnnouncement = valueToAnnounce;
    this.descriptionContainer.textContent = valueToAnnounce;
  }
  destroy() {
    super.destroy();
    const { descriptionContainer } = this;
    if (descriptionContainer) {
      _clearElement(descriptionContainer);
      descriptionContainer.remove();
    }
    this.descriptionContainer = null;
    this.pendingAnnouncements.clear();
  }
};
var AriaModule = {
  moduleName: "Aria",
  version: VERSION,
  beans: [AriaAnnouncementService]
};
var columnDelayRenderCSS = (
  /*css*/
  `:where(.ag-delay-render){.ag-cell,.ag-header-cell,.ag-header-group-cell,.ag-row,.ag-spanned-cell-wrapper{visibility:hidden}}`
);
var HideClass = "ag-delay-render";
var ColumnDelayRenderService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "colDelayRenderSvc";
    this.hideRequested = false;
    this.alreadyRevealed = false;
    this.timesRetried = 0;
    this.requesters = /* @__PURE__ */ new Set();
  }
  hideColumns(key2) {
    if (this.alreadyRevealed || this.requesters.has(key2)) {
      return;
    }
    this.requesters.add(key2);
    if (!this.hideRequested) {
      this.beans.ctrlsSvc.whenReady(this, (p) => {
        p.gridBodyCtrl.eGridBody.classList.add(HideClass);
      });
      this.hideRequested = true;
    }
  }
  revealColumns(key2) {
    if (this.alreadyRevealed || !this.isAlive()) {
      return;
    }
    this.requesters.delete(key2);
    if (this.requesters.size > 0) {
      return;
    }
    const { renderStatus, ctrlsSvc } = this.beans;
    if (renderStatus) {
      if (!renderStatus.areHeaderCellsRendered() && this.timesRetried < 5) {
        this.timesRetried++;
        setTimeout(() => this.revealColumns(key2));
        return;
      }
      this.timesRetried = 0;
    }
    ctrlsSvc.getGridBodyCtrl().eGridBody.classList.remove(HideClass);
    this.alreadyRevealed = true;
  }
};
var ColumnDelayRenderModule = {
  moduleName: "ColumnDelayRender",
  version: VERSION,
  beans: [ColumnDelayRenderService],
  css: [columnDelayRenderCSS]
};
function showLoadingOverlay(beans) {
  beans.overlays?.showLoadingOverlay();
}
function showNoRowsOverlay(beans) {
  beans.overlays?.showNoRowsOverlay();
}
function hideOverlay(beans) {
  beans.overlays?.hideOverlay();
}
var overlayWrapperComponentCSS = (
  /*css*/
  `.ag-overlay{inset:0;pointer-events:none;position:absolute;z-index:2}.ag-overlay-panel,.ag-overlay-wrapper{display:flex;height:100%;width:100%}.ag-overlay-wrapper{align-items:center;flex:none;justify-content:center;text-align:center}.ag-overlay-loading-wrapper{pointer-events:all}.ag-overlay-loading-center{background:var(--ag-background-color);border:solid var(--ag-border-width) var(--ag-border-color);border-radius:var(--ag-border-radius);box-shadow:var(--ag-popup-shadow);padding:var(--ag-spacing)}`
);
var OverlayWrapperElement = {
  tag: "div",
  cls: "ag-overlay",
  role: "presentation",
  children: [
    {
      tag: "div",
      cls: "ag-overlay-panel",
      role: "presentation",
      children: [{ tag: "div", ref: "eOverlayWrapper", cls: "ag-overlay-wrapper", role: "presentation" }]
    }
  ]
};
var OverlayWrapperComponent = class extends Component {
  constructor() {
    super(OverlayWrapperElement);
    this.eOverlayWrapper = RefPlaceholder;
    this.activePromise = null;
    this.activeOverlay = null;
    this.updateListenerDestroyFunc = null;
    this.activeCssClass = null;
    this.elToFocusAfter = null;
    this.registerCSS(overlayWrapperComponentCSS);
  }
  handleKeyDown(e) {
    if (e.key !== KeyCode.TAB || e.defaultPrevented || _isStopPropagationForAgGrid(e)) {
      return;
    }
    const beans = this.beans;
    const nextEl = _findNextFocusableElement(beans, this.eOverlayWrapper, false, e.shiftKey);
    if (nextEl) {
      return;
    }
    let isFocused = false;
    if (e.shiftKey) {
      isFocused = beans.focusSvc.focusGridView({
        column: _last(beans.visibleCols.allCols),
        backwards: true,
        canFocusOverlay: false
      });
    } else {
      isFocused = _focusNextGridCoreContainer(beans, false);
    }
    if (isFocused) {
      e.preventDefault();
    }
  }
  updateLayoutClasses(cssClass, params) {
    const overlayWrapperClassList = this.eOverlayWrapper.classList;
    const { AUTO_HEIGHT, NORMAL, PRINT } = LayoutCssClasses;
    overlayWrapperClassList.toggle(AUTO_HEIGHT, params.autoHeight);
    overlayWrapperClassList.toggle(NORMAL, params.normal);
    overlayWrapperClassList.toggle(PRINT, params.print);
  }
  postConstruct() {
    this.createManagedBean(new LayoutFeature(this));
    this.setDisplayed(false, { skipAriaHidden: true });
    this.beans.overlays.setOverlayWrapperComp(this);
    this.addManagedElementListeners(this.getFocusableElement(), { keydown: this.handleKeyDown.bind(this) });
  }
  setWrapperTypeClass(overlayWrapperCssClass) {
    const overlayWrapperClassList = this.eOverlayWrapper.classList;
    if (this.activeCssClass) {
      overlayWrapperClassList.toggle(this.activeCssClass, false);
    }
    this.activeCssClass = overlayWrapperCssClass;
    overlayWrapperClassList.toggle(overlayWrapperCssClass, true);
  }
  showOverlay(overlayComponentPromise, overlayWrapperCssClass, exclusive, gridOption) {
    this.setWrapperTypeClass(overlayWrapperCssClass);
    this.destroyActiveOverlay();
    this.elToFocusAfter = null;
    this.activePromise = overlayComponentPromise;
    if (!overlayComponentPromise) {
      return;
    }
    this.setDisplayed(true, { skipAriaHidden: true });
    if (exclusive && this.isGridFocused()) {
      const activeElement = _getActiveDomElement(this.beans);
      if (activeElement && !_isNothingFocused(this.beans)) {
        this.elToFocusAfter = activeElement;
      }
    }
    overlayComponentPromise.then((comp) => {
      if (this.activePromise !== overlayComponentPromise) {
        if (this.activeOverlay !== comp) {
          this.destroyBean(comp);
          comp = null;
        }
        return;
      }
      this.activePromise = null;
      if (!comp) {
        return;
      }
      if (this.activeOverlay !== comp) {
        this.eOverlayWrapper.appendChild(comp.getGui());
        this.activeOverlay = comp;
        if (gridOption) {
          const component = comp;
          this.updateListenerDestroyFunc = this.addManagedPropertyListener(gridOption, ({ currentValue }) => {
            component.refresh?.(_addGridCommonParams(this.gos, { ...currentValue ?? {} }));
          });
        }
      }
      if (exclusive && this.isGridFocused()) {
        _focusInto(this.eOverlayWrapper);
      }
    });
  }
  updateOverlayWrapperPaddingTop(padding) {
    this.eOverlayWrapper.style.setProperty("padding-top", `${padding}px`);
  }
  destroyActiveOverlay() {
    this.activePromise = null;
    const activeOverlay = this.activeOverlay;
    if (!activeOverlay) {
      return;
    }
    let elementToFocus = this.elToFocusAfter;
    this.activeOverlay = null;
    this.elToFocusAfter = null;
    if (elementToFocus && !this.isGridFocused()) {
      elementToFocus = null;
    }
    const updateListenerDestroyFunc = this.updateListenerDestroyFunc;
    if (updateListenerDestroyFunc) {
      updateListenerDestroyFunc();
      this.updateListenerDestroyFunc = null;
    }
    this.destroyBean(activeOverlay);
    _clearElement(this.eOverlayWrapper);
    elementToFocus?.focus?.({ preventScroll: true });
  }
  hideOverlay() {
    this.destroyActiveOverlay();
    this.setDisplayed(false, { skipAriaHidden: true });
  }
  isGridFocused() {
    const activeEl = _getActiveDomElement(this.beans);
    return !!activeEl && this.beans.eGridDiv.contains(activeEl);
  }
  destroy() {
    this.elToFocusAfter = null;
    this.destroyActiveOverlay();
    this.beans.overlays.setOverlayWrapperComp(void 0);
    super.destroy();
  }
};
var OverlayWrapperSelector = {
  selector: "AG-OVERLAY-WRAPPER",
  component: OverlayWrapperComponent
};
var OverlayService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "overlays";
    this.state = 0;
    this.showInitialOverlay = true;
    this.wrapperPadding = 0;
  }
  postConstruct() {
    this.isClientSide = _isClientSideRowModel(this.gos);
    this.isServerSide = !this.isClientSide && _isServerSideRowModel(this.gos);
    const updateOverlayVisibility = () => this.updateOverlayVisibility();
    this.addManagedEventListeners({
      newColumnsLoaded: updateOverlayVisibility,
      rowDataUpdated: updateOverlayVisibility,
      gridSizeChanged: this.refreshWrapperPadding.bind(this),
      rowCountReady: () => {
        this.showInitialOverlay = false;
        this.updateOverlayVisibility();
      }
    });
    this.addManagedPropertyListener("loading", updateOverlayVisibility);
  }
  setOverlayWrapperComp(overlayWrapperComp) {
    this.eWrapper = overlayWrapperComp;
    this.updateOverlayVisibility();
  }
  /** Returns true if the overlay is visible. */
  isVisible() {
    return this.state !== 0 && !!this.eWrapper;
  }
  /** Returns true if the overlay is visible and is exclusive (popup over the grid) */
  isExclusive() {
    return this.state === 1 && !!this.eWrapper;
  }
  showLoadingOverlay() {
    this.showInitialOverlay = false;
    const gos = this.gos;
    const loading = gos.get("loading");
    if (!loading && (loading !== void 0 || gos.get("suppressLoadingOverlay"))) {
      return;
    }
    this.doShowLoadingOverlay();
  }
  showNoRowsOverlay() {
    this.showInitialOverlay = false;
    const gos = this.gos;
    if (gos.get("loading") || gos.get("suppressNoRowsOverlay")) {
      return;
    }
    this.doShowNoRowsOverlay();
  }
  hideOverlay() {
    this.showInitialOverlay = false;
    if (this.gos.get("loading")) {
      _warn(99);
      return;
    }
    this.doHideOverlay();
  }
  getOverlayWrapperSelector() {
    return OverlayWrapperSelector;
  }
  getOverlayWrapperCompClass() {
    return OverlayWrapperComponent;
  }
  updateOverlayVisibility() {
    if (!this.eWrapper) {
      this.state = 0;
      return;
    }
    const {
      state,
      isClientSide,
      isServerSide,
      beans: { gos, colModel, rowModel }
    } = this;
    let loading = this.gos.get("loading");
    if (loading !== void 0) {
      this.showInitialOverlay = false;
    }
    if (this.showInitialOverlay && loading === void 0 && !gos.get("suppressLoadingOverlay")) {
      loading = !gos.get("columnDefs") || !colModel.ready || !gos.get("rowData") && isClientSide;
    }
    if (loading) {
      if (state !== 1) {
        this.doShowLoadingOverlay();
      }
    } else {
      this.showInitialOverlay = false;
      if (isClientSide && rowModel.isEmpty() && !gos.get("suppressNoRowsOverlay")) {
        if (state !== 2) {
          this.doShowNoRowsOverlay();
        }
      } else if (state === 1 || !isServerSide && state !== 0) {
        this.doHideOverlay();
      }
    }
  }
  doShowLoadingOverlay() {
    if (!this.eWrapper) {
      return;
    }
    this.state = 1;
    this.showOverlay(
      _getLoadingOverlayCompDetails(this.beans.userCompFactory, _addGridCommonParams(this.gos, {})),
      "ag-overlay-loading-wrapper",
      "loadingOverlayComponentParams"
    );
    this.updateExclusive();
  }
  doShowNoRowsOverlay() {
    if (!this.eWrapper) {
      return;
    }
    this.state = 2;
    this.showOverlay(
      _getNoRowsOverlayCompDetails(this.beans.userCompFactory, _addGridCommonParams(this.gos, {})),
      "ag-overlay-no-rows-wrapper",
      "noRowsOverlayComponentParams"
    );
    this.updateExclusive();
  }
  doHideOverlay() {
    if (!this.eWrapper) {
      return;
    }
    this.state = 0;
    this.eWrapper.hideOverlay();
    this.updateExclusive();
  }
  showOverlay(compDetails, wrapperCssClass, gridOption) {
    const promise = compDetails?.newAgStackInstance() ?? null;
    this.eWrapper?.showOverlay(promise, wrapperCssClass, this.isExclusive(), gridOption);
    this.refreshWrapperPadding();
  }
  updateExclusive() {
    const wasExclusive = this.exclusive;
    this.exclusive = this.isExclusive();
    if (this.exclusive !== wasExclusive) {
      this.eventSvc.dispatchEvent({
        type: "overlayExclusiveChanged"
      });
    }
  }
  refreshWrapperPadding() {
    const eWrapper = this.eWrapper;
    if (!eWrapper) {
      return;
    }
    let newPadding = 0;
    if (this.state === 2) {
      const headerCtrl = this.beans.ctrlsSvc.get("gridHeaderCtrl");
      const headerHeight = headerCtrl?.headerHeight || 0;
      newPadding = headerHeight;
    }
    if (this.wrapperPadding === newPadding) {
      return;
    }
    this.wrapperPadding = newPadding;
    eWrapper.updateOverlayWrapperPaddingTop(newPadding);
  }
};
var OverlayModule = {
  moduleName: "Overlay",
  version: VERSION,
  userComponents: {
    agLoadingOverlay: LoadingOverlayComponent2,
    agNoRowsOverlay: NoRowsOverlayComponent2
  },
  apiFunctions: {
    showLoadingOverlay,
    showNoRowsOverlay,
    hideOverlay
  },
  beans: [OverlayService]
};
var RowContainerHeightService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "rowContainerHeight";
    this.scrollY = 0;
    this.uiBodyHeight = 0;
  }
  postConstruct() {
    this.addManagedEventListeners({ bodyHeightChanged: this.updateOffset.bind(this) });
    this.maxDivHeight = _getMaxDivHeight();
    _logIfDebug(this.gos, "RowContainerHeightService - maxDivHeight = " + this.maxDivHeight);
  }
  updateOffset() {
    if (!this.stretching) {
      return;
    }
    const newScrollY = this.beans.ctrlsSvc.getScrollFeature().getVScrollPosition().top;
    const newBodyHeight = this.getUiBodyHeight();
    const atLeastOneChanged = newScrollY !== this.scrollY || newBodyHeight !== this.uiBodyHeight;
    if (atLeastOneChanged) {
      this.scrollY = newScrollY;
      this.uiBodyHeight = newBodyHeight;
      this.calculateOffset();
    }
  }
  calculateOffset() {
    this.setUiContainerHeight(this.maxDivHeight);
    this.pixelsToShave = this.modelHeight - this.uiContainerHeight;
    this.maxScrollY = this.uiContainerHeight - this.uiBodyHeight;
    const scrollPercent = this.scrollY / this.maxScrollY;
    const divStretchOffset = scrollPercent * this.pixelsToShave;
    _logIfDebug(
      this.gos,
      `RowContainerHeightService - Div Stretch Offset = ${divStretchOffset} (${this.pixelsToShave} * ${scrollPercent})`
    );
    this.setDivStretchOffset(divStretchOffset);
  }
  setUiContainerHeight(height) {
    if (height !== this.uiContainerHeight) {
      this.uiContainerHeight = height;
      this.eventSvc.dispatchEvent({ type: "rowContainerHeightChanged" });
    }
  }
  clearOffset() {
    this.setUiContainerHeight(this.modelHeight);
    this.pixelsToShave = 0;
    this.setDivStretchOffset(0);
  }
  setDivStretchOffset(newOffset) {
    const newOffsetFloor = typeof newOffset === "number" ? Math.floor(newOffset) : null;
    if (this.divStretchOffset === newOffsetFloor) {
      return;
    }
    this.divStretchOffset = newOffsetFloor;
    this.eventSvc.dispatchEvent({ type: "heightScaleChanged" });
  }
  setModelHeight(modelHeight) {
    this.modelHeight = modelHeight;
    this.stretching = modelHeight != null && // null happens when in print layout
    this.maxDivHeight > 0 && modelHeight > this.maxDivHeight;
    if (this.stretching) {
      this.calculateOffset();
    } else {
      this.clearOffset();
    }
  }
  getRealPixelPosition(modelPixel) {
    return modelPixel - this.divStretchOffset;
  }
  getUiBodyHeight() {
    const pos2 = this.beans.ctrlsSvc.getScrollFeature().getVScrollPosition();
    return pos2.bottom - pos2.top;
  }
  getScrollPositionForPixel(rowTop) {
    if (this.pixelsToShave <= 0) {
      return rowTop;
    }
    const modelMaxScroll = this.modelHeight - this.getUiBodyHeight();
    const scrollPercent = rowTop / modelMaxScroll;
    const scrollPixel = this.maxScrollY * scrollPercent;
    return scrollPixel;
  }
};
var ROW_ANIMATION_TIMEOUT = 400;
var RowRenderer = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "rowRenderer";
    this.destroyFuncsForColumnListeners = [];
    this.rowCtrlsByRowIndex = {};
    this.zombieRowCtrls = {};
    this.allRowCtrls = [];
    this.topRowCtrls = [];
    this.bottomRowCtrls = [];
    this.refreshInProgress = false;
    this.dataFirstRenderedFired = false;
    this.setupRangeSelectionListeners = () => {
      const onCellSelectionChanged = () => {
        for (const cellCtrl of this.getAllCellCtrls()) {
          cellCtrl.onCellSelectionChanged();
        }
      };
      const onColumnMovedPinnedVisible = () => {
        for (const cellCtrl of this.getAllCellCtrls()) {
          cellCtrl.updateRangeBordersIfRangeCount();
        }
      };
      const addCellSelectionListeners = () => {
        this.eventSvc.addListener("cellSelectionChanged", onCellSelectionChanged);
        this.eventSvc.addListener("columnMoved", onColumnMovedPinnedVisible);
        this.eventSvc.addListener("columnPinned", onColumnMovedPinnedVisible);
        this.eventSvc.addListener("columnVisible", onColumnMovedPinnedVisible);
      };
      const removeCellSelectionListeners = () => {
        this.eventSvc.removeListener("cellSelectionChanged", onCellSelectionChanged);
        this.eventSvc.removeListener("columnMoved", onColumnMovedPinnedVisible);
        this.eventSvc.removeListener("columnPinned", onColumnMovedPinnedVisible);
        this.eventSvc.removeListener("columnVisible", onColumnMovedPinnedVisible);
      };
      this.addDestroyFunc(() => removeCellSelectionListeners());
      this.addManagedPropertyListeners(["enableRangeSelection", "cellSelection"], () => {
        const isEnabled = _isCellSelectionEnabled(this.gos);
        if (isEnabled) {
          addCellSelectionListeners();
        } else {
          removeCellSelectionListeners();
        }
      });
      const cellSelectionEnabled = _isCellSelectionEnabled(this.gos);
      if (cellSelectionEnabled) {
        addCellSelectionListeners();
      }
    };
  }
  wireBeans(beans) {
    this.pageBounds = beans.pageBounds;
    this.colModel = beans.colModel;
    this.pinnedRowModel = beans.pinnedRowModel;
    this.rowModel = beans.rowModel;
    this.focusSvc = beans.focusSvc;
    this.rowContainerHeight = beans.rowContainerHeight;
    this.ctrlsSvc = beans.ctrlsSvc;
    this.editSvc = beans.editSvc;
  }
  postConstruct() {
    this.ctrlsSvc.whenReady(this, (p) => {
      this.gridBodyCtrl = p.gridBodyCtrl;
      this.initialise();
    });
  }
  initialise() {
    this.addManagedEventListeners({
      paginationChanged: this.onPageLoaded.bind(this),
      pinnedRowDataChanged: this.onPinnedRowDataChanged.bind(this),
      pinnedRowsChanged: this.onPinnedRowsChanged.bind(this),
      displayedColumnsChanged: this.onDisplayedColumnsChanged.bind(this),
      bodyScroll: this.onBodyScroll.bind(this),
      bodyHeightChanged: this.redraw.bind(this, {})
    });
    this.addManagedPropertyListeners(["domLayout", "embedFullWidthRows"], () => this.onDomLayoutChanged());
    this.addManagedPropertyListeners(["suppressMaxRenderedRowRestriction", "rowBuffer"], () => this.redraw());
    this.addManagedPropertyListener("suppressCellFocus", (e) => this.onSuppressCellFocusChanged(e.currentValue));
    this.addManagedPropertyListeners(
      [
        "groupSuppressBlankHeader",
        "getBusinessKeyForNode",
        "fullWidthCellRenderer",
        "fullWidthCellRendererParams",
        "suppressStickyTotalRow",
        "groupRowRenderer",
        "groupRowRendererParams",
        // maybe only needs to refresh FW rows...
        "loadingCellRenderer",
        "loadingCellRendererParams",
        "detailCellRenderer",
        "detailCellRendererParams",
        "enableRangeSelection",
        "enableCellTextSelection"
      ],
      () => this.redrawRows()
    );
    this.addManagedPropertyListener("cellSelection", ({ currentValue, previousValue }) => {
      if (!previousValue && currentValue || previousValue && !currentValue) {
        this.redrawRows();
      }
    });
    const { stickyRowSvc, gos, showRowGroupCols } = this.beans;
    if (showRowGroupCols) {
      this.addManagedPropertyListener("showOpenedGroup", () => {
        const columns2 = showRowGroupCols.getShowRowGroupCols();
        if (columns2.length) {
          this.refreshCells({ columns: columns2, force: true });
        }
      });
    }
    if (stickyRowSvc) {
      this.stickyRowFeature = stickyRowSvc.createStickyRowFeature(
        this,
        this.createRowCon.bind(this),
        this.destroyRowCtrls.bind(this)
      );
    } else {
      const gridBodyCtrl = this.gridBodyCtrl;
      gridBodyCtrl.setStickyTopHeight(0);
      gridBodyCtrl.setStickyBottomHeight(0);
    }
    this.registerCellEventListeners();
    this.initialiseCache();
    this.printLayout = _isDomLayout(gos, "print");
    this.embedFullWidthRows = this.printLayout || gos.get("embedFullWidthRows");
    this.redrawAfterModelUpdate();
  }
  initialiseCache() {
    if (this.gos.get("keepDetailRows")) {
      const countProp = this.getKeepDetailRowsCount();
      const count2 = countProp != null ? countProp : 3;
      this.cachedRowCtrls = new RowCtrlCache(count2);
    }
  }
  getKeepDetailRowsCount() {
    return this.gos.get("keepDetailRowsCount");
  }
  getStickyTopRowCtrls() {
    return this.stickyRowFeature?.stickyTopRowCtrls ?? [];
  }
  getStickyBottomRowCtrls() {
    return this.stickyRowFeature?.stickyBottomRowCtrls ?? [];
  }
  updateAllRowCtrls() {
    const liveList = Object.values(this.rowCtrlsByRowIndex);
    const zombieList = Object.values(this.zombieRowCtrls);
    const cachedList = this.cachedRowCtrls?.getEntries() ?? [];
    if (zombieList.length > 0 || cachedList.length > 0) {
      this.allRowCtrls = [...liveList, ...zombieList, ...cachedList];
    } else {
      this.allRowCtrls = liveList;
    }
  }
  /**
   * Checks if the cell is rendered or not. Also returns true if row ctrl is present but has not rendered
   * cells yet.
   * @returns true if cellCtrl is present, or if the row is present but has not rendered rows yet
   */
  isCellBeingRendered(rowIndex, column2) {
    const rowCtrl = this.rowCtrlsByRowIndex[rowIndex];
    if (!column2 || !rowCtrl) {
      return !!rowCtrl;
    }
    if (rowCtrl.isFullWidth()) {
      return true;
    }
    const spannedCell = this.beans.spannedRowRenderer?.getCellByPosition({ rowIndex, column: column2, rowPinned: null });
    return !!spannedCell || !!rowCtrl.getCellCtrl(column2) || !rowCtrl.isRowRendered();
  }
  /**
   * Notifies all row and cell controls of any change in focused cell.
   * @param event cell focused event
   */
  updateCellFocus(event) {
    for (const cellCtrl of this.getAllCellCtrls()) {
      cellCtrl.onCellFocused(event);
    }
    for (const rowCtrl of this.getFullWidthRowCtrls()) {
      rowCtrl.onFullWidthRowFocused(event);
    }
  }
  /**
   * Called when a new cell is focused in the grid
   * - if the focused cell isn't rendered; re-draw rows to dry to render it
   * - subsequently updates all cell and row controls with the new focused cell
   * @param event cell focused event
   */
  onCellFocusChanged(event) {
    if (event?.rowIndex != null && !event.rowPinned) {
      const col = this.beans.colModel.getCol(event.column) ?? void 0;
      if (!this.isCellBeingRendered(event.rowIndex, col)) {
        this.redraw();
      }
    }
    this.updateCellFocus(event);
  }
  onSuppressCellFocusChanged(suppressCellFocus) {
    for (const cellCtrl of this.getAllCellCtrls()) {
      cellCtrl.onSuppressCellFocusChanged(suppressCellFocus);
    }
    for (const rowCtrl of this.getFullWidthRowCtrls()) {
      rowCtrl.onSuppressCellFocusChanged(suppressCellFocus);
    }
  }
  // in a clean design, each cell would register for each of these events. however when scrolling, all the cells
  // registering and de-registering for events is a performance bottleneck. so we register here once and inform
  // all active cells.
  registerCellEventListeners() {
    this.addManagedEventListeners({
      cellFocused: (event) => this.onCellFocusChanged(event),
      cellFocusCleared: () => this.updateCellFocus(),
      flashCells: (event) => {
        const { cellFlashSvc } = this.beans;
        if (cellFlashSvc) {
          for (const cellCtrl of this.getAllCellCtrls()) {
            cellFlashSvc.onFlashCells(cellCtrl, event);
          }
        }
      },
      columnHoverChanged: () => {
        for (const cellCtrl of this.getAllCellCtrls()) {
          cellCtrl.onColumnHover();
        }
      },
      displayedColumnsChanged: () => {
        for (const cellCtrl of this.getAllCellCtrls()) {
          cellCtrl.onDisplayedColumnsChanged();
        }
      },
      displayedColumnsWidthChanged: () => {
        if (this.printLayout) {
          for (const cellCtrl of this.getAllCellCtrls()) {
            cellCtrl.onLeftChanged();
          }
        }
      }
    });
    this.setupRangeSelectionListeners();
    this.refreshListenersToColumnsForCellComps();
    this.addManagedEventListeners({
      gridColumnsChanged: this.refreshListenersToColumnsForCellComps.bind(this)
    });
    this.addDestroyFunc(this.removeGridColumnListeners.bind(this));
  }
  // executes all functions in destroyFuncsForColumnListeners and then clears the list
  removeGridColumnListeners() {
    for (const func2 of this.destroyFuncsForColumnListeners) {
      func2();
    }
    this.destroyFuncsForColumnListeners.length = 0;
  }
  // this function adds listeners onto all the grid columns, which are the column that we could have cellComps for.
  // when the grid columns change, we add listeners again. in an ideal design, each CellComp would just register to
  // the column it belongs to on creation, however this was a bottleneck with the number of cells, so do it here
  // once instead.
  refreshListenersToColumnsForCellComps() {
    this.removeGridColumnListeners();
    const cols = this.colModel.getCols();
    for (const col of cols) {
      const forEachCellWithThisCol = (callback) => {
        for (const cellCtrl of this.getAllCellCtrls()) {
          if (cellCtrl.column === col) {
            callback(cellCtrl);
          }
        }
      };
      const leftChangedListener = () => {
        forEachCellWithThisCol((cellCtrl) => cellCtrl.onLeftChanged());
      };
      const widthChangedListener = () => {
        forEachCellWithThisCol((cellCtrl) => cellCtrl.onWidthChanged());
      };
      const firstRightPinnedChangedListener = () => {
        forEachCellWithThisCol((cellCtrl) => cellCtrl.onFirstRightPinnedChanged());
      };
      const lastLeftPinnedChangedListener = () => {
        forEachCellWithThisCol((cellCtrl) => cellCtrl.onLastLeftPinnedChanged());
      };
      const colDefChangedListener = () => {
        forEachCellWithThisCol((cellCtrl) => cellCtrl.onColDefChanged());
      };
      col.__addEventListener("leftChanged", leftChangedListener);
      col.__addEventListener("widthChanged", widthChangedListener);
      col.__addEventListener("firstRightPinnedChanged", firstRightPinnedChangedListener);
      col.__addEventListener("lastLeftPinnedChanged", lastLeftPinnedChangedListener);
      col.__addEventListener("colDefChanged", colDefChangedListener);
      this.destroyFuncsForColumnListeners.push(() => {
        col.__removeEventListener("leftChanged", leftChangedListener);
        col.__removeEventListener("widthChanged", widthChangedListener);
        col.__removeEventListener("firstRightPinnedChanged", firstRightPinnedChangedListener);
        col.__removeEventListener("lastLeftPinnedChanged", lastLeftPinnedChangedListener);
        col.__removeEventListener("colDefChanged", colDefChangedListener);
      });
    }
  }
  onDomLayoutChanged() {
    const printLayout = _isDomLayout(this.gos, "print");
    const embedFullWidthRows = printLayout || this.gos.get("embedFullWidthRows");
    const destroyRows = embedFullWidthRows !== this.embedFullWidthRows || this.printLayout !== printLayout;
    this.printLayout = printLayout;
    this.embedFullWidthRows = embedFullWidthRows;
    if (destroyRows) {
      this.redrawAfterModelUpdate({ domLayoutChanged: true });
    }
  }
  // for row models that have datasources, when we update the datasource, we need to force the rowRenderer
  // to redraw all rows. otherwise the old rows from the old datasource will stay displayed.
  datasourceChanged() {
    this.firstRenderedRow = 0;
    this.lastRenderedRow = -1;
    const rowIndexesToRemove = Object.keys(this.rowCtrlsByRowIndex);
    this.removeRowCtrls(rowIndexesToRemove);
  }
  onPageLoaded(event) {
    const params = {
      recycleRows: event.keepRenderedRows,
      animate: event.animate,
      newData: event.newData,
      newPage: event.newPage,
      // because this is a model updated event (not pinned rows), we
      // can skip updating the pinned rows. this is needed so that if user
      // is doing transaction updates, the pinned rows are not getting constantly
      // trashed - or editing cells in pinned rows are not refreshed and put into read mode
      onlyBody: true
    };
    this.redrawAfterModelUpdate(params);
  }
  /**
   * @param column AgColumn
   * @returns An array with HTMLElement for every cell of the column passed as param.
   * If the cell is spanning across multiple columns, it only returns the html element
   * if the column passed is the first column of the span (used for auto width calculation).
   */
  getAllCellsNotSpanningForColumn(column2) {
    const res = [];
    for (const rowCtrl of this.getAllRowCtrls()) {
      const eCell = rowCtrl.getCellCtrl(column2, true)?.eGui;
      if (eCell) {
        res.push(eCell);
      }
    }
    return res;
  }
  refreshFloatingRowComps(recycleRows = true) {
    this.refreshFloatingRows(this.topRowCtrls, "top", recycleRows);
    this.refreshFloatingRows(this.bottomRowCtrls, "bottom", recycleRows);
  }
  /**
   * Determines which row controllers need to be destroyed and re-created vs which ones can
   * be re-used.
   *
   * This is operation is to pinned/floating rows as `this.recycleRows` is to normal/body rows.
   *
   * All `RowCtrl` instances in `rowCtrls` that don't correspond to `RowNode` instances in `rowNodes` are destroyed.
   * All `RowNode` instances in `rowNodes` that don't correspond to `RowCtrl` instances in `rowCtrls` are created.
   * All instances in `rowCtrls` must be in the same order as their corresponding nodes in `rowNodes`.
   *
   * @param rowCtrls The list of existing row controllers
   * @param rowNodes The canonical list of row nodes that should have associated controllers
   */
  refreshFloatingRows(rowCtrls, floating, recycleRows) {
    const { pinnedRowModel, beans, printLayout } = this;
    const rowCtrlMap = Object.fromEntries(rowCtrls.map((ctrl) => [ctrl.rowNode.id, ctrl]));
    pinnedRowModel?.forEachPinnedRow(floating, (node2, i2) => {
      const rowCtrl = rowCtrls[i2];
      const rowCtrlDoesNotExist = rowCtrl && pinnedRowModel.getPinnedRowById(rowCtrl.rowNode.id, floating) === void 0;
      if (rowCtrlDoesNotExist) {
        rowCtrl.destroyFirstPass();
        rowCtrl.destroySecondPass();
      }
      if (node2.id in rowCtrlMap && recycleRows) {
        rowCtrls[i2] = rowCtrlMap[node2.id];
        delete rowCtrlMap[node2.id];
      } else {
        rowCtrls[i2] = new RowCtrl(node2, beans, false, false, printLayout);
      }
    });
    const rowNodeCount = (floating === "top" ? pinnedRowModel?.getPinnedTopRowCount() : pinnedRowModel?.getPinnedBottomRowCount()) ?? 0;
    rowCtrls.length = rowNodeCount;
  }
  onPinnedRowDataChanged() {
    const params = {
      recycleRows: true
    };
    this.redrawAfterModelUpdate(params);
  }
  onPinnedRowsChanged() {
    this.redrawAfterModelUpdate({ recycleRows: true });
  }
  redrawRow(rowNode, suppressEvent = false) {
    if (rowNode.sticky) {
      this.stickyRowFeature?.refreshStickyNode(rowNode);
    } else if (this.cachedRowCtrls?.has(rowNode)) {
      this.cachedRowCtrls.removeRow(rowNode);
      return;
    } else {
      const destroyAndRecreateCtrl = (dataStruct) => {
        const ctrl = dataStruct[rowNode.rowIndex];
        if (!ctrl) {
          return;
        }
        if (ctrl.rowNode !== rowNode) {
          return;
        }
        ctrl.destroyFirstPass();
        ctrl.destroySecondPass();
        dataStruct[rowNode.rowIndex] = this.createRowCon(rowNode, false, false);
      };
      switch (rowNode.rowPinned) {
        case "top":
          destroyAndRecreateCtrl(this.topRowCtrls);
          break;
        case "bottom":
          destroyAndRecreateCtrl(this.bottomRowCtrls);
          break;
        default:
          destroyAndRecreateCtrl(this.rowCtrlsByRowIndex);
          this.updateAllRowCtrls();
      }
    }
    if (!suppressEvent) {
      this.dispatchDisplayedRowsChanged(false);
    }
  }
  redrawRows(rowNodes) {
    const { editSvc } = this.beans;
    if (editSvc?.isEditing()) {
      if (editSvc.isBatchEditing()) {
        editSvc.cleanupEditors();
      } else {
        editSvc.stopEditing(void 0, { source: "api" });
      }
    }
    const partialRefresh = rowNodes != null;
    if (partialRefresh) {
      for (const node2 of rowNodes ?? []) {
        this.redrawRow(node2, true);
      }
      this.dispatchDisplayedRowsChanged(false);
      return;
    }
    this.redrawAfterModelUpdate();
  }
  // gets called from:
  // +) initialisation (in registerGridComp) params = null
  // +) onDomLayoutChanged, params = null
  // +) onPageLoaded, recycleRows, animate, newData, newPage from event, onlyBody=true
  // +) onPinnedRowDataChanged, recycleRows = true
  // +) redrawRows (from Grid API), recycleRows = true/false
  redrawAfterModelUpdate(params = {}) {
    this.getLockOnRefresh();
    const focusedCell = this.beans.focusSvc?.getFocusCellToUseAfterRefresh();
    this.updateContainerHeights();
    this.scrollToTopIfNewData(params);
    const recycleRows = !params.domLayoutChanged && !!params.recycleRows;
    const animate2 = params.animate && _isAnimateRows(this.gos);
    const rowsToRecycle = recycleRows ? this.getRowsToRecycle() : null;
    if (!recycleRows) {
      this.removeAllRowComps();
    }
    this.workOutFirstAndLastRowsToRender();
    const { stickyRowFeature, gos } = this;
    if (stickyRowFeature) {
      stickyRowFeature.checkStickyRows();
      const extraHeight = stickyRowFeature.extraTopHeight + stickyRowFeature.extraBottomHeight;
      if (extraHeight) {
        this.updateContainerHeights(extraHeight);
      }
    }
    this.recycleRows(rowsToRecycle, animate2);
    this.gridBodyCtrl.updateRowCount();
    if (!params.onlyBody) {
      this.refreshFloatingRowComps(gos.get("enableRowPinning") ? recycleRows : void 0);
    }
    this.dispatchDisplayedRowsChanged();
    if (focusedCell != null) {
      this.restoreFocusedCell(focusedCell);
    }
    this.releaseLockOnRefresh();
  }
  scrollToTopIfNewData(params) {
    const scrollToTop = params.newData || params.newPage;
    const suppressScrollToTop = this.gos.get("suppressScrollOnNewData");
    if (scrollToTop && !suppressScrollToTop) {
      this.gridBodyCtrl.scrollFeature.scrollToTop();
      this.stickyRowFeature?.resetOffsets();
    }
  }
  updateContainerHeights(additionalHeight = 0) {
    const { rowContainerHeight } = this;
    if (this.printLayout) {
      rowContainerHeight.setModelHeight(null);
      return;
    }
    let containerHeight = this.pageBounds.getCurrentPageHeight();
    if (containerHeight === 0) {
      containerHeight = 1;
    }
    rowContainerHeight.setModelHeight(containerHeight + additionalHeight);
  }
  getLockOnRefresh() {
    if (this.refreshInProgress) {
      throw new Error(_errMsg(252));
    }
    this.refreshInProgress = true;
    this.beans.frameworkOverrides.getLockOnRefresh?.();
  }
  releaseLockOnRefresh() {
    this.refreshInProgress = false;
    this.beans.frameworkOverrides.releaseLockOnRefresh?.();
  }
  isRefreshInProgress() {
    return this.refreshInProgress;
  }
  // sets the focus to the provided cell, if the cell is provided. this way, the user can call refresh without
  // worry about the focus been lost. this is important when the user is using keyboard navigation to do edits
  // and the cellEditor is calling 'refresh' to get other cells to update (as other cells might depend on the
  // edited cell).
  restoreFocusedCell(cellPosition) {
    if (!cellPosition) {
      return;
    }
    const focusSvc = this.beans.focusSvc;
    const cellToFocus = this.findPositionToFocus(cellPosition);
    if (!cellToFocus) {
      focusSvc.focusHeaderPosition({
        headerPosition: {
          headerRowIndex: getFocusHeaderRowCount(this.beans) - 1,
          column: cellPosition.column
        }
      });
      return;
    }
    if (cellPosition.rowIndex !== cellToFocus.rowIndex || cellPosition.rowPinned != cellToFocus.rowPinned) {
      focusSvc.setFocusedCell({
        ...cellToFocus,
        preventScrollOnBrowserFocus: true,
        forceBrowserFocus: true
      });
      return;
    }
    if (!focusSvc.doesRowOrCellHaveBrowserFocus()) {
      this.updateCellFocus(
        _addGridCommonParams(this.gos, {
          ...cellToFocus,
          forceBrowserFocus: true,
          preventScrollOnBrowserFocus: true,
          type: "cellFocused"
        })
      );
    }
  }
  findPositionToFocus(cellPosition) {
    const { pagination, pageBounds } = this.beans;
    let rowPosition = cellPosition;
    if (rowPosition.rowPinned == null && pagination && pageBounds && !pagination.isRowInPage(rowPosition.rowIndex)) {
      rowPosition = { rowPinned: null, rowIndex: pageBounds.getFirstRow() };
    }
    while (rowPosition) {
      if (rowPosition.rowPinned == null && pageBounds) {
        if (rowPosition.rowIndex < pageBounds.getFirstRow()) {
          rowPosition = _getRowAbove(this.beans, { rowPinned: null, rowIndex: 0 });
          if (!rowPosition) {
            return null;
          }
        } else if (rowPosition.rowIndex > pageBounds.getLastRow()) {
          rowPosition = { rowPinned: null, rowIndex: pageBounds.getLastRow() };
        }
      }
      const row2 = this.getRowByPosition(rowPosition);
      if (row2?.isAlive()) {
        return { ...row2.getRowPosition(), column: cellPosition.column };
      }
      rowPosition = _getRowAbove(this.beans, rowPosition);
    }
    return null;
  }
  getAllCellCtrls() {
    const res = [];
    const rowCtrls = this.getAllRowCtrls();
    const rowCtrlsLength = rowCtrls.length;
    for (let i2 = 0; i2 < rowCtrlsLength; i2++) {
      const cellCtrls = rowCtrls[i2].getAllCellCtrls();
      const cellCtrlsLength = cellCtrls.length;
      for (let j2 = 0; j2 < cellCtrlsLength; j2++) {
        res.push(cellCtrls[j2]);
      }
    }
    return res;
  }
  getAllRowCtrls() {
    const { spannedRowRenderer } = this.beans;
    const stickyTopRowCtrls = this.getStickyTopRowCtrls();
    const stickyBottomRowCtrls = this.getStickyBottomRowCtrls();
    const res = [
      ...this.topRowCtrls,
      ...this.bottomRowCtrls,
      ...stickyTopRowCtrls,
      ...stickyBottomRowCtrls,
      ...spannedRowRenderer?.getCtrls("top") ?? [],
      ...spannedRowRenderer?.getCtrls("bottom") ?? [],
      ...spannedRowRenderer?.getCtrls("center") ?? [],
      ...Object.values(this.rowCtrlsByRowIndex)
    ];
    return res;
  }
  addRenderedRowListener(eventName, rowIndex, callback) {
    const rowComp = this.rowCtrlsByRowIndex[rowIndex];
    if (rowComp) {
      rowComp.addEventListener(eventName, callback);
    }
  }
  refreshCells({ rowNodes, columns: columns2, force, suppressFlash } = {}) {
    const refreshCellParams = {
      force,
      newData: false,
      suppressFlash
    };
    for (const cellCtrl of this.getCellCtrls(rowNodes, columns2)) {
      cellCtrl.refreshOrDestroyCell(refreshCellParams);
    }
    this.refreshFullWidth(rowNodes);
  }
  refreshRows(params = {}) {
    for (const rowCtrl of this.getRowCtrls(params.rowNodes)) {
      rowCtrl.refreshRow(params);
    }
    this.refreshFullWidth(params.rowNodes);
  }
  refreshFullWidth(rowNodes) {
    if (!rowNodes) {
      return;
    }
    let rowRedrawn = false;
    for (const rowCtrl of this.getRowCtrls(rowNodes)) {
      if (!rowCtrl.isFullWidth()) {
        continue;
      }
      const refreshed = rowCtrl.refreshFullWidth();
      if (!refreshed) {
        rowRedrawn = true;
        this.redrawRow(rowCtrl.rowNode, true);
      }
    }
    if (rowRedrawn) {
      this.dispatchDisplayedRowsChanged(false);
    }
  }
  /**
   * @param rowNodes if provided, returns the RowCtrls for the provided rowNodes. otherwise returns all RowCtrls.
   */
  getRowCtrls(rowNodes) {
    const rowIdsMap = mapRowNodes(rowNodes);
    const allRowCtrls = this.getAllRowCtrls();
    if (!rowNodes || !rowIdsMap) {
      return allRowCtrls;
    }
    return allRowCtrls.filter((rowCtrl) => {
      const rowNode = rowCtrl.rowNode;
      return isRowInMap(rowNode, rowIdsMap);
    });
  }
  // returns CellCtrl's that match the provided rowNodes and columns. eg if one row node
  // and two columns provided, that identifies 4 cells, so 4 CellCtrl's returned.
  getCellCtrls(rowNodes, columns2) {
    let colIdsMap;
    if (_exists(columns2)) {
      colIdsMap = {};
      columns2.forEach((colKey) => {
        const column2 = this.colModel.getCol(colKey);
        if (_exists(column2)) {
          colIdsMap[column2.getId()] = true;
        }
      });
    }
    const res = [];
    for (const rowCtrl of this.getRowCtrls(rowNodes)) {
      for (const cellCtrl of rowCtrl.getAllCellCtrls()) {
        const colId = cellCtrl.column.getId();
        const excludeColFromRefresh = colIdsMap && !colIdsMap[colId];
        if (excludeColFromRefresh) {
          continue;
        }
        res.push(cellCtrl);
      }
    }
    return res;
  }
  destroy() {
    this.removeAllRowComps(true);
    super.destroy();
  }
  removeAllRowComps(suppressAnimation = false) {
    const rowIndexesToRemove = Object.keys(this.rowCtrlsByRowIndex);
    this.removeRowCtrls(rowIndexesToRemove, suppressAnimation);
    this.stickyRowFeature?.destroyStickyCtrls();
  }
  getRowsToRecycle() {
    const stubNodeIndexes = [];
    for (const index of Object.keys(this.rowCtrlsByRowIndex)) {
      const rowCtrl = this.rowCtrlsByRowIndex[index];
      const stubNode = rowCtrl.rowNode.id == null;
      if (stubNode) {
        stubNodeIndexes.push(index);
      }
    }
    this.removeRowCtrls(stubNodeIndexes);
    const ctrlsByIdMap = {};
    for (const rowCtrl of Object.values(this.rowCtrlsByRowIndex)) {
      const rowNode = rowCtrl.rowNode;
      ctrlsByIdMap[rowNode.id] = rowCtrl;
    }
    this.rowCtrlsByRowIndex = {};
    return ctrlsByIdMap;
  }
  // takes array of row indexes
  removeRowCtrls(rowsToRemove, suppressAnimation = false) {
    for (const indexToRemove of rowsToRemove) {
      const rowCtrl = this.rowCtrlsByRowIndex[indexToRemove];
      if (rowCtrl) {
        rowCtrl.destroyFirstPass(suppressAnimation);
        rowCtrl.destroySecondPass();
      }
      delete this.rowCtrlsByRowIndex[indexToRemove];
    }
  }
  onBodyScroll(e) {
    if (e.direction !== "vertical") {
      return;
    }
    this.redraw({ afterScroll: true });
  }
  // gets called when rows don't change, but viewport does, so after:
  // 1) height of grid body changes, ie number of displayed rows has changed
  // 2) grid scrolled to new position
  // 3) ensure index visible (which is a scroll)
  redraw(params = {}) {
    const { focusSvc, animationFrameSvc } = this.beans;
    const { afterScroll } = params;
    let cellFocused;
    const stickyRowFeature = this.stickyRowFeature;
    if (stickyRowFeature) {
      cellFocused = focusSvc?.getFocusCellToUseAfterRefresh() || void 0;
    }
    const oldFirstRow = this.firstRenderedRow;
    const oldLastRow = this.lastRenderedRow;
    this.workOutFirstAndLastRowsToRender();
    let hasStickyRowChanges = false;
    if (stickyRowFeature) {
      hasStickyRowChanges = stickyRowFeature.checkStickyRows();
      const extraHeight = stickyRowFeature.extraTopHeight + stickyRowFeature.extraBottomHeight;
      if (extraHeight) {
        this.updateContainerHeights(extraHeight);
      }
    }
    const rangeChanged = this.firstRenderedRow !== oldFirstRow || this.lastRenderedRow !== oldLastRow;
    if (afterScroll && !hasStickyRowChanges && !rangeChanged) {
      return;
    }
    this.getLockOnRefresh();
    this.recycleRows(null, false, afterScroll);
    this.releaseLockOnRefresh();
    this.dispatchDisplayedRowsChanged(afterScroll && !hasStickyRowChanges);
    if (cellFocused != null) {
      const newFocusedCell = focusSvc?.getFocusCellToUseAfterRefresh();
      if (cellFocused != null && newFocusedCell == null) {
        animationFrameSvc?.flushAllFrames();
        this.restoreFocusedCell(cellFocused);
      }
    }
  }
  removeRowCompsNotToDraw(indexesToDraw, suppressAnimation) {
    const indexesToDrawMap = {};
    for (const index of indexesToDraw) {
      indexesToDrawMap[index] = true;
    }
    const existingIndexes = Object.keys(this.rowCtrlsByRowIndex);
    const indexesNotToDraw = existingIndexes.filter((index) => !indexesToDrawMap[index]);
    this.removeRowCtrls(indexesNotToDraw, suppressAnimation);
  }
  calculateIndexesToDraw(rowsToRecycle) {
    const indexesToDraw = [];
    for (let i2 = this.firstRenderedRow; i2 <= this.lastRenderedRow; i2++) {
      indexesToDraw.push(i2);
    }
    const pagination = this.beans.pagination;
    const focusedRowIndex = this.beans.focusSvc?.getFocusedCell()?.rowIndex;
    if (focusedRowIndex != null && (focusedRowIndex < this.firstRenderedRow || focusedRowIndex > this.lastRenderedRow) && (!pagination || pagination.isRowInPage(focusedRowIndex)) && focusedRowIndex < this.rowModel.getRowCount()) {
      indexesToDraw.push(focusedRowIndex);
    }
    const checkRowToDraw = (rowComp) => {
      const index = rowComp.rowNode.rowIndex;
      if (index == null || index === focusedRowIndex) {
        return;
      }
      if (index < this.firstRenderedRow || index > this.lastRenderedRow) {
        if (this.doNotUnVirtualiseRow(rowComp)) {
          indexesToDraw.push(index);
        }
      }
    };
    for (const rowCtrl of Object.values(this.rowCtrlsByRowIndex)) {
      checkRowToDraw(rowCtrl);
    }
    if (rowsToRecycle) {
      for (const rowCtrl of Object.values(rowsToRecycle)) {
        checkRowToDraw(rowCtrl);
      }
    }
    indexesToDraw.sort((a2, b) => a2 - b);
    const ret = [];
    for (let i2 = 0; i2 < indexesToDraw.length; i2++) {
      const currRow = indexesToDraw[i2];
      const rowNode = this.rowModel.getRow(currRow);
      if (rowNode && !rowNode.sticky) {
        ret.push(currRow);
      }
    }
    return ret;
  }
  recycleRows(rowsToRecycle, animate2 = false, afterScroll = false) {
    const indexesToDraw = this.calculateIndexesToDraw(rowsToRecycle);
    if (this.printLayout || afterScroll) {
      animate2 = false;
    }
    this.removeRowCompsNotToDraw(indexesToDraw, !animate2);
    for (const rowIndex of indexesToDraw) {
      this.createOrUpdateRowCtrl(rowIndex, rowsToRecycle, animate2, afterScroll);
    }
    if (rowsToRecycle) {
      const { animationFrameSvc } = this.beans;
      const useAnimationFrame = animationFrameSvc?.active && afterScroll && !this.printLayout;
      if (useAnimationFrame) {
        animationFrameSvc.addDestroyTask(() => {
          this.destroyRowCtrls(rowsToRecycle, animate2);
          this.updateAllRowCtrls();
          this.dispatchDisplayedRowsChanged();
        });
      } else {
        this.destroyRowCtrls(rowsToRecycle, animate2);
      }
    }
    this.updateAllRowCtrls();
  }
  dispatchDisplayedRowsChanged(afterScroll = false) {
    this.eventSvc.dispatchEvent({
      type: "displayedRowsChanged",
      afterScroll
    });
  }
  onDisplayedColumnsChanged() {
    const { visibleCols } = this.beans;
    const pinningLeft = visibleCols.isPinningLeft();
    const pinningRight = visibleCols.isPinningRight();
    const atLeastOneChanged = this.pinningLeft !== pinningLeft || pinningRight !== this.pinningRight;
    if (atLeastOneChanged) {
      this.pinningLeft = pinningLeft;
      this.pinningRight = pinningRight;
      if (this.embedFullWidthRows) {
        this.redrawFullWidthEmbeddedRows();
      }
    }
  }
  // when embedding, what gets showed in each section depends on what is pinned. eg if embedding group expand / collapse,
  // then it should go into the pinned left area if pinning left, or the center area if not pinning.
  redrawFullWidthEmbeddedRows() {
    const rowsToRemove = [];
    for (const fullWidthCtrl of this.getFullWidthRowCtrls()) {
      const rowIndex = fullWidthCtrl.rowNode.rowIndex;
      rowsToRemove.push(rowIndex.toString());
    }
    this.refreshFloatingRowComps();
    this.removeRowCtrls(rowsToRemove);
    this.redraw({ afterScroll: true });
  }
  getFullWidthRowCtrls(rowNodes) {
    const rowNodesMap = mapRowNodes(rowNodes);
    return this.getAllRowCtrls().filter((rowCtrl) => {
      if (!rowCtrl.isFullWidth()) {
        return false;
      }
      const rowNode = rowCtrl.rowNode;
      if (rowNodesMap != null && !isRowInMap(rowNode, rowNodesMap)) {
        return false;
      }
      return true;
    });
  }
  createOrUpdateRowCtrl(rowIndex, rowsToRecycle, animate2, afterScroll) {
    let rowNode;
    let rowCtrl = this.rowCtrlsByRowIndex[rowIndex];
    if (!rowCtrl) {
      rowNode = this.rowModel.getRow(rowIndex);
      if (_exists(rowNode) && _exists(rowsToRecycle) && rowsToRecycle[rowNode.id] && rowNode.alreadyRendered) {
        rowCtrl = rowsToRecycle[rowNode.id];
        rowsToRecycle[rowNode.id] = null;
      }
    }
    const creatingNewRowCtrl = !rowCtrl;
    if (creatingNewRowCtrl) {
      if (!rowNode) {
        rowNode = this.rowModel.getRow(rowIndex);
      }
      if (_exists(rowNode)) {
        rowCtrl = this.createRowCon(rowNode, animate2, afterScroll);
      } else {
        return;
      }
    }
    if (rowNode) {
      rowNode.alreadyRendered = true;
    }
    this.rowCtrlsByRowIndex[rowIndex] = rowCtrl;
  }
  destroyRowCtrls(rowCtrlsMap, animate2) {
    const executeInAWhileFuncs = [];
    if (rowCtrlsMap) {
      for (const rowCtrl of Object.values(rowCtrlsMap)) {
        if (!rowCtrl) {
          continue;
        }
        if (this.cachedRowCtrls && rowCtrl.isCacheable()) {
          this.cachedRowCtrls.addRow(rowCtrl);
          continue;
        }
        rowCtrl.destroyFirstPass(!animate2);
        if (animate2) {
          const instanceId = rowCtrl.instanceId;
          this.zombieRowCtrls[instanceId] = rowCtrl;
          executeInAWhileFuncs.push(() => {
            rowCtrl.destroySecondPass();
            delete this.zombieRowCtrls[instanceId];
          });
        } else {
          rowCtrl.destroySecondPass();
        }
      }
    }
    if (animate2) {
      executeInAWhileFuncs.push(() => {
        if (this.isAlive()) {
          this.updateAllRowCtrls();
          this.dispatchDisplayedRowsChanged();
        }
      });
      window.setTimeout(() => {
        for (const func2 of executeInAWhileFuncs) {
          func2();
        }
      }, ROW_ANIMATION_TIMEOUT);
    }
  }
  getRowBuffer() {
    return this.gos.get("rowBuffer");
  }
  getRowBufferInPixels() {
    const rowsToBuffer = this.getRowBuffer();
    const defaultRowHeight = _getRowHeightAsNumber(this.beans);
    return rowsToBuffer * defaultRowHeight;
  }
  workOutFirstAndLastRowsToRender() {
    const { rowContainerHeight, pageBounds, rowModel } = this;
    rowContainerHeight.updateOffset();
    let newFirst;
    let newLast;
    if (!rowModel.isRowsToRender()) {
      newFirst = 0;
      newLast = -1;
    } else if (this.printLayout) {
      this.beans.environment.refreshRowHeightVariable();
      newFirst = pageBounds.getFirstRow();
      newLast = pageBounds.getLastRow();
    } else {
      const bufferPixels = this.getRowBufferInPixels();
      const scrollFeature = this.ctrlsSvc.getScrollFeature();
      const suppressRowVirtualisation = this.gos.get("suppressRowVirtualisation");
      let rowHeightsChanged = false;
      let firstPixel;
      let lastPixel;
      do {
        const paginationOffset = pageBounds.getPixelOffset();
        const { pageFirstPixel, pageLastPixel } = pageBounds.getCurrentPagePixelRange();
        const divStretchOffset = rowContainerHeight.divStretchOffset;
        const bodyVRange = scrollFeature.getVScrollPosition();
        const bodyTopPixel = bodyVRange.top;
        const bodyBottomPixel = bodyVRange.bottom;
        if (suppressRowVirtualisation) {
          firstPixel = pageFirstPixel + divStretchOffset;
          lastPixel = pageLastPixel + divStretchOffset;
        } else {
          firstPixel = Math.max(bodyTopPixel + paginationOffset - bufferPixels, pageFirstPixel) + divStretchOffset;
          lastPixel = Math.min(bodyBottomPixel + paginationOffset + bufferPixels, pageLastPixel) + divStretchOffset;
        }
        this.firstVisibleVPixel = Math.max(bodyTopPixel + paginationOffset, pageFirstPixel) + divStretchOffset;
        this.lastVisibleVPixel = Math.min(bodyBottomPixel + paginationOffset, pageLastPixel) + divStretchOffset;
        rowHeightsChanged = this.ensureAllRowsInRangeHaveHeightsCalculated(firstPixel, lastPixel);
      } while (rowHeightsChanged);
      let firstRowIndex = rowModel.getRowIndexAtPixel(firstPixel);
      let lastRowIndex = rowModel.getRowIndexAtPixel(lastPixel);
      const pageFirstRow = pageBounds.getFirstRow();
      const pageLastRow = pageBounds.getLastRow();
      if (firstRowIndex < pageFirstRow) {
        firstRowIndex = pageFirstRow;
      }
      if (lastRowIndex > pageLastRow) {
        lastRowIndex = pageLastRow;
      }
      newFirst = firstRowIndex;
      newLast = lastRowIndex;
    }
    const rowLayoutNormal = _isDomLayout(this.gos, "normal");
    const suppressRowCountRestriction = this.gos.get("suppressMaxRenderedRowRestriction");
    const rowBufferMaxSize = Math.max(this.getRowBuffer(), 500);
    if (rowLayoutNormal && !suppressRowCountRestriction) {
      if (newLast - newFirst > rowBufferMaxSize) {
        newLast = newFirst + rowBufferMaxSize;
      }
    }
    const firstDiffers = newFirst !== this.firstRenderedRow;
    const lastDiffers = newLast !== this.lastRenderedRow;
    if (firstDiffers || lastDiffers) {
      this.firstRenderedRow = newFirst;
      this.lastRenderedRow = newLast;
      this.eventSvc.dispatchEvent({
        type: "viewportChanged",
        firstRow: newFirst,
        lastRow: newLast
      });
    }
  }
  /**
   * This event will only be fired once, and is queued until after the browser next renders.
   * This allows us to fire an event during the start of the render cycle, when we first see data being rendered
   * but not execute the event until all of the data has finished being rendered to the dom.
   */
  dispatchFirstDataRenderedEvent() {
    if (this.dataFirstRenderedFired) {
      return;
    }
    this.dataFirstRenderedFired = true;
    _requestAnimationFrame(this.beans, () => {
      this.beans.eventSvc.dispatchEvent({
        type: "firstDataRendered",
        firstRow: this.firstRenderedRow,
        lastRow: this.lastRenderedRow
      });
    });
  }
  ensureAllRowsInRangeHaveHeightsCalculated(topPixel, bottomPixel) {
    const pinnedRowHeightsChanged = this.pinnedRowModel?.ensureRowHeightsValid();
    const stickyHeightsChanged = this.stickyRowFeature?.ensureRowHeightsValid();
    const { pageBounds, rowModel } = this;
    const rowModelHeightsChanged = rowModel.ensureRowHeightsValid(
      topPixel,
      bottomPixel,
      pageBounds.getFirstRow(),
      pageBounds.getLastRow()
    );
    if (rowModelHeightsChanged || stickyHeightsChanged) {
      this.eventSvc.dispatchEvent({
        type: "recalculateRowBounds"
      });
    }
    if (stickyHeightsChanged || rowModelHeightsChanged || pinnedRowHeightsChanged) {
      this.updateContainerHeights();
      return true;
    }
    return false;
  }
  // check that none of the rows to remove are editing or focused as:
  // a) if editing, we want to keep them, otherwise the user will loose the context of the edit,
  //    eg user starts editing, enters some text, then scrolls down and then up, next time row rendered
  //    the edit is reset - so we want to keep it rendered.
  // b) if focused, we want ot keep keyboard focus, so if user ctrl+c, it goes to clipboard,
  //    otherwise the user can range select and drag (with focus cell going out of the viewport)
  //    and then ctrl+c, nothing will happen if cell is removed from dom.
  // c) if detail record of master detail, as users complained that the context of detail rows
  //    was getting lost when detail row out of view. eg user expands to show detail row,
  //    then manipulates the detail panel (eg sorts the detail grid), then context is lost
  //    after detail panel is scrolled out of / into view.
  doNotUnVirtualiseRow(rowCtrl) {
    const REMOVE_ROW = false;
    const KEEP_ROW = true;
    const rowNode = rowCtrl.rowNode;
    const rowHasFocus = this.focusSvc.isRowFocused(rowNode.rowIndex, rowNode.rowPinned);
    const rowIsEditing = this.editSvc?.isEditing(rowCtrl);
    const rowIsDetail = rowNode.detail;
    const mightWantToKeepRow = rowHasFocus || rowIsEditing || rowIsDetail;
    if (!mightWantToKeepRow) {
      return REMOVE_ROW;
    }
    const rowNodePresent = this.isRowPresent(rowNode);
    return rowNodePresent ? KEEP_ROW : REMOVE_ROW;
  }
  isRowPresent(rowNode) {
    if (!this.rowModel.isRowPresent(rowNode)) {
      return false;
    }
    return this.beans.pagination?.isRowInPage(rowNode.rowIndex) ?? true;
  }
  createRowCon(rowNode, animate2, afterScroll) {
    const rowCtrlFromCache = this.cachedRowCtrls?.getRow(rowNode) ?? null;
    if (rowCtrlFromCache) {
      return rowCtrlFromCache;
    }
    const useAnimationFrameForCreate = afterScroll && !this.printLayout && !!this.beans.animationFrameSvc?.active;
    const res = new RowCtrl(rowNode, this.beans, animate2, useAnimationFrameForCreate, this.printLayout);
    return res;
  }
  getRenderedNodes() {
    const viewportRows = Object.values(this.rowCtrlsByRowIndex).map((rowCtrl) => rowCtrl.rowNode);
    const stickyTopRows = this.getStickyTopRowCtrls().map((rowCtrl) => rowCtrl.rowNode);
    const stickyBottomRows = this.getStickyBottomRowCtrls().map((rowCtrl) => rowCtrl.rowNode);
    return [...stickyTopRows, ...viewportRows, ...stickyBottomRows];
  }
  getRowByPosition(rowPosition) {
    let rowCtrl;
    const { rowIndex } = rowPosition;
    switch (rowPosition.rowPinned) {
      case "top":
        rowCtrl = this.topRowCtrls[rowIndex];
        break;
      case "bottom":
        rowCtrl = this.bottomRowCtrls[rowIndex];
        break;
      default:
        rowCtrl = this.rowCtrlsByRowIndex[rowIndex];
        if (!rowCtrl) {
          rowCtrl = this.getStickyTopRowCtrls().find((ctrl) => ctrl.rowNode.rowIndex === rowIndex) || null;
          if (!rowCtrl) {
            rowCtrl = this.getStickyBottomRowCtrls().find((ctrl) => ctrl.rowNode.rowIndex === rowIndex) || null;
          }
        }
        break;
    }
    return rowCtrl;
  }
  // returns true if any row between startIndex and endIndex is rendered. used by
  // SSRM or IRM, as they don't want to purge visible blocks from cache.
  isRangeInRenderedViewport(startIndex, endIndex) {
    const parentClosed = startIndex == null || endIndex == null;
    if (parentClosed) {
      return false;
    }
    const blockAfterViewport = startIndex > this.lastRenderedRow;
    const blockBeforeViewport = endIndex < this.firstRenderedRow;
    const blockInsideViewport = !blockBeforeViewport && !blockAfterViewport;
    return blockInsideViewport;
  }
};
var RowCtrlCache = class {
  constructor(maxCount) {
    this.entriesMap = {};
    this.entriesList = [];
    this.maxCount = maxCount;
  }
  addRow(rowCtrl) {
    this.entriesMap[rowCtrl.rowNode.id] = rowCtrl;
    this.entriesList.push(rowCtrl);
    rowCtrl.setCached(true);
    if (this.entriesList.length > this.maxCount) {
      const rowCtrlToDestroy = this.entriesList[0];
      rowCtrlToDestroy.destroyFirstPass();
      rowCtrlToDestroy.destroySecondPass();
      this.removeFromCache(rowCtrlToDestroy);
    }
  }
  getRow(rowNode) {
    if (rowNode?.id == null) {
      return null;
    }
    const res = this.entriesMap[rowNode.id];
    if (!res) {
      return null;
    }
    this.removeFromCache(res);
    res.setCached(false);
    const rowNodeMismatch = res.rowNode != rowNode;
    return rowNodeMismatch ? null : res;
  }
  has(rowNode) {
    return this.entriesMap[rowNode.id] != null;
  }
  removeRow(rowNode) {
    const rowNodeId = rowNode.id;
    const ctrl = this.entriesMap[rowNodeId];
    delete this.entriesMap[rowNodeId];
    _removeFromArray(this.entriesList, ctrl);
  }
  removeFromCache(rowCtrl) {
    const rowNodeId = rowCtrl.rowNode.id;
    delete this.entriesMap[rowNodeId];
    _removeFromArray(this.entriesList, rowCtrl);
  }
  getEntries() {
    return this.entriesList;
  }
};
function mapRowNodes(rowNodes) {
  if (!rowNodes) {
    return;
  }
  const res = {
    top: {},
    bottom: {},
    normal: {}
  };
  for (const rowNode of rowNodes) {
    const id2 = rowNode.id;
    switch (rowNode.rowPinned) {
      case "top":
        res.top[id2] = rowNode;
        break;
      case "bottom":
        res.bottom[id2] = rowNode;
        break;
      default:
        res.normal[id2] = rowNode;
        break;
    }
  }
  return res;
}
function isRowInMap(rowNode, rowIdsMap) {
  const id2 = rowNode.id;
  const floating = rowNode.rowPinned;
  switch (floating) {
    case "top":
      return rowIdsMap.top[id2] != null;
    case "bottom":
      return rowIdsMap.bottom[id2] != null;
    default:
      return rowIdsMap.normal[id2] != null;
  }
}
var RowNodeSorter = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "rowNodeSorter";
  }
  postConstruct() {
    const { gos } = this;
    this.isAccentedSort = gos.get("accentedSort");
    this.primaryColumnsSortGroups = _isColumnsSortingCoupledToGroup(gos);
    this.addManagedPropertyListener(
      "accentedSort",
      (propChange) => this.isAccentedSort = propChange.currentValue
    );
    this.addManagedPropertyListener(
      "autoGroupColumnDef",
      () => this.primaryColumnsSortGroups = _isColumnsSortingCoupledToGroup(gos)
    );
  }
  doFullSort(rowNodes, sortOptions) {
    const sortedRowNodes = rowNodes.map((rowNode, currentPos) => ({
      currentPos,
      rowNode
    }));
    sortedRowNodes.sort(this.compareRowNodes.bind(this, sortOptions));
    return sortedRowNodes.map((item2) => item2.rowNode);
  }
  compareRowNodes(sortOptions, sortedNodeA, sortedNodeB) {
    const nodeA = sortedNodeA.rowNode;
    const nodeB = sortedNodeB.rowNode;
    for (let i2 = 0, len = sortOptions.length; i2 < len; i2++) {
      const sortOption = sortOptions[i2];
      const isDescending = sortOption.sort === "desc";
      const valueA = this.getValue(nodeA, sortOption.column);
      const valueB = this.getValue(nodeB, sortOption.column);
      let comparatorResult;
      const providedComparator = this.getComparator(sortOption, nodeA);
      if (providedComparator) {
        comparatorResult = providedComparator(valueA, valueB, nodeA, nodeB, isDescending);
      } else {
        comparatorResult = _defaultComparator(valueA, valueB, this.isAccentedSort);
      }
      const validResult = !isNaN(comparatorResult);
      if (validResult && comparatorResult !== 0) {
        return sortOption.sort === "asc" ? comparatorResult : comparatorResult * -1;
      }
    }
    return sortedNodeA.currentPos - sortedNodeB.currentPos;
  }
  getComparator(sortOption, rowNode) {
    const column2 = sortOption.column;
    const comparatorOnCol = column2.getColDef().comparator;
    if (comparatorOnCol != null) {
      return comparatorOnCol;
    }
    if (!column2.getColDef().showRowGroup) {
      return;
    }
    const groupLeafField = !rowNode.group && column2.getColDef().field;
    if (!groupLeafField) {
      return;
    }
    const primaryColumn = this.beans.colModel.getColDefCol(groupLeafField);
    if (!primaryColumn) {
      return;
    }
    return primaryColumn.getColDef().comparator;
  }
  getValue(node2, column2) {
    const { valueSvc, colModel, showRowGroupCols, gos } = this.beans;
    if (!this.primaryColumnsSortGroups) {
      return valueSvc.getValue(column2, node2, false);
    }
    const isNodeGroupedAtLevel = node2.rowGroupColumn === column2;
    if (isNodeGroupedAtLevel) {
      const isGroupRows = _isGroupUseEntireRow(gos, colModel.isPivotActive());
      if (isGroupRows) {
        const leafChild = node2.data ? node2 : _firstLeaf(node2.childrenAfterGroup);
        return leafChild && valueSvc.getValue(column2, leafChild, false);
      }
      const displayCol = showRowGroupCols?.getShowRowGroupCol(column2.getId());
      if (!displayCol) {
        return void 0;
      }
      return node2.groupData?.[displayCol.getId()];
    }
    if (node2.group && column2.getColDef().showRowGroup) {
      return void 0;
    }
    return valueSvc.getValue(column2, node2, false);
  }
};
function onSortChanged(beans) {
  beans.sortSvc?.onSortChanged("api");
}
var SortModule = {
  moduleName: "Sort",
  version: VERSION,
  beans: [SortService, RowNodeSorter],
  apiFunctions: {
    onSortChanged
  },
  userComponents: {
    agSortIndicator: SortIndicatorComp
  },
  icons: {
    // show on column header when column is sorted ascending
    sortAscending: "asc",
    // show on column header when column is sorted descending
    sortDescending: "desc",
    // show on column header when column has no sort, only when enabled with gridOptions.unSortIcon=true
    sortUnSort: "none"
  }
};
var SyncService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "syncSvc";
    this.waitingForColumns = false;
  }
  postConstruct() {
    this.addManagedPropertyListener("columnDefs", (event) => this.setColumnDefs(event));
  }
  start() {
    this.beans.ctrlsSvc.whenReady(this, () => {
      const columnDefs = this.gos.get("columnDefs");
      if (columnDefs) {
        this.setColumnsAndData(columnDefs);
      } else {
        this.waitingForColumns = true;
      }
      this.gridReady();
    });
  }
  setColumnsAndData(columnDefs) {
    const { colModel, rowModel } = this.beans;
    colModel.setColumnDefs(columnDefs ?? [], "gridInitializing");
    rowModel.start();
  }
  gridReady() {
    const { eventSvc, gos } = this;
    eventSvc.dispatchEvent({
      type: "gridReady"
    });
    _logIfDebug(gos, `initialised successfully, enterprise = ${gos.isModuleRegistered("EnterpriseCore")}`);
  }
  setColumnDefs(event) {
    const columnDefs = this.gos.get("columnDefs");
    if (!columnDefs) {
      return;
    }
    if (this.waitingForColumns) {
      this.waitingForColumns = false;
      this.setColumnsAndData(columnDefs);
      return;
    }
    this.beans.colModel.setColumnDefs(columnDefs, _convertColumnEventSourceType(event.source));
  }
};
function expireValueCache(beans) {
  beans.valueCache?.expire();
}
function getCellValue(beans, params) {
  const { colKey, rowNode, useFormatter } = params;
  const column2 = beans.colModel.getColDefCol(colKey) ?? beans.colModel.getCol(colKey);
  if (_missing(column2)) {
    return null;
  }
  const result2 = beans.valueSvc.getValueForDisplay(column2, rowNode, useFormatter);
  if (useFormatter) {
    return result2.valueFormatted ?? _toString(result2.value);
  }
  return result2.value;
}
var SOURCE_PASTE = "paste";
var ChangeDetectionService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "changeDetectionSvc";
    this.clientSideRowModel = null;
  }
  postConstruct() {
    const { gos, rowModel } = this.beans;
    if (_isClientSideRowModel(gos)) {
      this.clientSideRowModel = rowModel;
    }
    this.addManagedEventListeners({ cellValueChanged: this.onCellValueChanged.bind(this) });
  }
  onCellValueChanged(event) {
    const { gos, rowRenderer } = this.beans;
    if (event.source === SOURCE_PASTE || gos.get("suppressChangeDetection")) {
      return;
    }
    const rowNode = event.node;
    const nodesToRefresh = [rowNode];
    const clientSideRowModel = this.clientSideRowModel;
    const rootNode = clientSideRowModel?.rootNode;
    if (rootNode && !rowNode.isRowPinned()) {
      const onlyChangedColumns = gos.get("aggregateOnlyChangedColumns");
      const changedPath = new ChangedPath(onlyChangedColumns, rootNode);
      changedPath.addParentNode(rowNode.parent, [event.column]);
      clientSideRowModel.doAggregate(changedPath);
      changedPath.forEachChangedNodeDepthFirst((rowNode2) => {
        nodesToRefresh.push(rowNode2);
        if (rowNode2.sibling) {
          nodesToRefresh.push(rowNode2.sibling);
        }
      });
    }
    rowRenderer.refreshCells({ rowNodes: nodesToRefresh });
  }
};
var ExpressionService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "expressionSvc";
    this.cache = {};
  }
  evaluate(expression, params) {
    if (typeof expression === "string") {
      return this.evaluateExpression(expression, params);
    } else {
      _error(15, { expression });
    }
  }
  evaluateExpression(expression, params) {
    try {
      const javaScriptFunction = this.createExpressionFunction(expression);
      const result2 = javaScriptFunction(
        params.value,
        params.context,
        params.oldValue,
        params.newValue,
        params.value,
        params.node,
        params.data,
        params.colDef,
        params.rowIndex,
        params.api,
        params.getValue,
        params.column,
        params.columnGroup
      );
      return result2;
    } catch (e) {
      _error(16, { expression, params, e });
      return null;
    }
  }
  createExpressionFunction(expression) {
    const expressionToFunctionCache = this.cache;
    if (expressionToFunctionCache[expression]) {
      return expressionToFunctionCache[expression];
    }
    const functionBody = this.createFunctionBody(expression);
    const theFunction = new Function(
      "x, ctx, oldValue, newValue, value, node, data, colDef, rowIndex, api, getValue, column, columnGroup",
      functionBody
    );
    expressionToFunctionCache[expression] = theFunction;
    return theFunction;
  }
  createFunctionBody(expression) {
    if (expression.includes("return")) {
      return expression;
    } else {
      return "return " + expression + ";";
    }
  }
};
var ValueCache = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "valueCache";
    this.cacheVersion = 0;
  }
  postConstruct() {
    const gos = this.gos;
    this.active = gos.get("valueCache");
    this.neverExpires = gos.get("valueCacheNeverExpires");
  }
  onDataChanged() {
    if (this.neverExpires) {
      return;
    }
    this.expire();
  }
  expire() {
    this.cacheVersion++;
  }
  setValue(rowNode, colId, value2) {
    if (this.active) {
      const cacheVersion = this.cacheVersion;
      if (rowNode.__cacheVersion !== cacheVersion) {
        rowNode.__cacheVersion = cacheVersion;
        rowNode.__cacheData = {};
      }
      rowNode.__cacheData[colId] = value2;
    }
  }
  getValue(rowNode, colId) {
    if (!this.active || rowNode.__cacheVersion !== this.cacheVersion) {
      return void 0;
    }
    return rowNode.__cacheData[colId];
  }
};
var ValueCacheModule = {
  moduleName: "ValueCache",
  version: VERSION,
  beans: [ValueCache],
  apiFunctions: {
    expireValueCache
  }
};
var ExpressionModule = {
  moduleName: "Expression",
  version: VERSION,
  beans: [ExpressionService]
};
var ChangeDetectionModule = {
  moduleName: "ChangeDetection",
  version: VERSION,
  beans: [ChangeDetectionService]
};
var CellApiModule = {
  moduleName: "CellApi",
  version: VERSION,
  apiFunctions: {
    getCellValue
  }
};
var ValueService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "valueSvc";
    this.hasEditSvc = false;
    this.initialised = false;
    this.isSsrm = false;
  }
  wireBeans(beans) {
    this.expressionSvc = beans.expressionSvc;
    this.colModel = beans.colModel;
    this.valueCache = beans.valueCache;
    this.dataTypeSvc = beans.dataTypeSvc;
    this.editSvc = beans.editSvc;
    this.hasEditSvc = !!beans.editSvc;
  }
  postConstruct() {
    if (!this.initialised) {
      this.init();
    }
  }
  init() {
    this.executeValueGetter = this.valueCache ? this.executeValueGetterWithValueCache.bind(this) : this.executeValueGetterWithoutValueCache.bind(this);
    this.isSsrm = _isServerSideRowModel(this.gos);
    this.cellExpressions = this.gos.get("enableCellExpressions");
    this.isTreeData = this.gos.get("treeData");
    this.initialised = true;
    const listener = (event) => this.callColumnCellValueChangedHandler(event);
    this.eventSvc.addListener("cellValueChanged", listener, true);
    this.addDestroyFunc(() => this.eventSvc.removeListener("cellValueChanged", listener, true));
    this.addManagedPropertyListener("treeData", (propChange) => this.isTreeData = propChange.currentValue);
  }
  /**
   * Use this function to get a displayable cell value.
   * The values from this function are not used for sorting, filtering, or aggregation purposes.
   * Handles: groupHideOpenParents, showOpenedGroup and groupSuppressBlankHeader behaviours
   */
  getValueForDisplay(column2, node2, includeValueFormatted = false, exporting = false, source2 = "ui") {
    const { showRowGroupColValueSvc } = this.beans;
    const isFullWidthGroup = !column2 && node2.group;
    const isGroupCol = column2?.colDef.showRowGroup;
    const processTreeDataAsGroup = !this.isTreeData || node2.footer;
    if (showRowGroupColValueSvc && processTreeDataAsGroup && (isFullWidthGroup || isGroupCol)) {
      const groupValue = showRowGroupColValueSvc.getGroupValue(node2, column2);
      if (groupValue == null) {
        return {
          value: null,
          valueFormatted: null
        };
      }
      if (!includeValueFormatted) {
        return {
          value: groupValue.value,
          valueFormatted: null
        };
      }
      const valueFormatted = showRowGroupColValueSvc.formatAndPrefixGroupColValue(groupValue, column2, exporting);
      return {
        value: groupValue.value,
        valueFormatted
      };
    }
    if (!column2) {
      return {
        value: node2.key,
        valueFormatted: null
      };
    }
    const isPivotLeaf = node2.leafGroup && this.colModel.isPivotMode();
    const isOpenedGroup = node2.group && node2.expanded && !node2.footer && !isPivotLeaf;
    const groupShowsAggData = this.gos.get("groupSuppressBlankHeader") || !node2.sibling;
    const ignoreAggData = isOpenedGroup && !groupShowsAggData;
    const value2 = this.getValue(column2, node2, ignoreAggData, source2);
    const format2 = includeValueFormatted && !(exporting && column2.colDef.useValueFormatterForExport === false);
    return {
      value: value2,
      valueFormatted: format2 ? this.formatValue(column2, node2, value2) : null
    };
  }
  getValue(column2, rowNode, ignoreAggData = false, source2 = "ui") {
    if (!this.initialised) {
      this.init();
    }
    if (!rowNode) {
      return;
    }
    const colDef = column2.getColDef();
    const field2 = colDef.field;
    const colId = column2.getColId();
    const data2 = rowNode.data;
    if (this.hasEditSvc && source2 === "ui") {
      const editSvc = this.editSvc;
      if (editSvc.isEditing()) {
        const newValue = editSvc.getCellDataValue({ rowNode, column: column2 }, true);
        if (newValue !== void 0) {
          return newValue;
        }
      }
    }
    let result2;
    const rowGroupColId = colDef.showRowGroup;
    if (typeof rowGroupColId === "string") {
      const colRowGroupIndex = this.beans.rowGroupColsSvc?.getColumnIndex(rowGroupColId) ?? -1;
      if (colRowGroupIndex > rowNode.level) {
        return null;
      }
    }
    const allowUserValuesForCell = typeof rowGroupColId !== "string" || !rowNode.group;
    const groupDataExists = rowNode.groupData && colId in rowNode.groupData;
    const aggDataExists = !ignoreAggData && rowNode.aggData && rowNode.aggData[colId] !== void 0;
    const ignoreSsrmAggData = this.isSsrm && ignoreAggData && !!colDef.aggFunc;
    const ssrmFooterGroupCol = this.isSsrm && rowNode.footer && rowNode.field && (colDef.showRowGroup === true || colDef.showRowGroup === rowNode.field);
    if (this.isTreeData && aggDataExists) {
      result2 = rowNode.aggData[colId];
    } else if (this.isTreeData && colDef.valueGetter) {
      result2 = this.executeValueGetter(colDef.valueGetter, data2, column2, rowNode);
    } else if (this.isTreeData && field2 && data2) {
      result2 = _getValueUsingField(data2, field2, column2.isFieldContainsDots());
    } else if (groupDataExists) {
      result2 = rowNode.groupData[colId];
    } else if (aggDataExists) {
      result2 = rowNode.aggData[colId];
    } else if (colDef.valueGetter && !ignoreSsrmAggData) {
      if (!allowUserValuesForCell) {
        return result2;
      }
      result2 = this.executeValueGetter(colDef.valueGetter, data2, column2, rowNode);
    } else if (ssrmFooterGroupCol) {
      result2 = _getValueUsingField(data2, rowNode.field, column2.isFieldContainsDots());
    } else if (field2 && data2 && !ignoreSsrmAggData) {
      if (!allowUserValuesForCell) {
        return result2;
      }
      result2 = _getValueUsingField(data2, field2, column2.isFieldContainsDots());
    }
    if (this.cellExpressions && typeof result2 === "string" && result2.indexOf("=") === 0) {
      const cellValueGetter = result2.substring(1);
      result2 = this.executeValueGetter(cellValueGetter, data2, column2, rowNode);
    }
    return result2;
  }
  parseValue(column2, rowNode, newValue, oldValue) {
    const colDef = column2.getColDef();
    const valueParser = colDef.valueParser;
    if (_exists(valueParser)) {
      const params = _addGridCommonParams(this.gos, {
        node: rowNode,
        data: rowNode?.data,
        oldValue,
        newValue,
        colDef,
        column: column2
      });
      if (typeof valueParser === "function") {
        return valueParser(params);
      }
      return this.expressionSvc?.evaluate(valueParser, params);
    }
    return newValue;
  }
  getDeleteValue(column2, rowNode) {
    if (_exists(column2.getColDef().valueParser)) {
      return this.parseValue(column2, rowNode, "", this.getValueForDisplay(column2, rowNode).value) ?? null;
    }
    return null;
  }
  formatValue(column2, node2, value2, suppliedFormatter, useFormatterFromColumn = true) {
    const { expressionSvc } = this.beans;
    let result2 = null;
    let formatter;
    const colDef = column2.getColDef();
    if (suppliedFormatter) {
      formatter = suppliedFormatter;
    } else if (useFormatterFromColumn) {
      formatter = colDef.valueFormatter;
    }
    if (formatter) {
      const data2 = node2 ? node2.data : null;
      const params = _addGridCommonParams(this.gos, {
        value: value2,
        node: node2,
        data: data2,
        colDef,
        column: column2
      });
      if (typeof formatter === "function") {
        result2 = formatter(params);
      } else {
        result2 = expressionSvc ? expressionSvc.evaluate(formatter, params) : null;
      }
    } else if (colDef.refData) {
      return colDef.refData[value2] || "";
    }
    if (result2 == null && Array.isArray(value2)) {
      result2 = value2.join(", ");
    }
    return result2;
  }
  /**
   * Sets the value of a GridCell
   * @param rowNode The `RowNode` to be updated
   * @param colKey The `Column` to be updated
   * @param newValue The new value to be set
   * @param eventSource The event source
   * @returns `True` if the value has been updated, otherwise`False`.
   */
  setValue(rowNode, colKey, newValue, eventSource) {
    const column2 = this.colModel.getColDefCol(colKey);
    if (!rowNode || !column2) {
      return false;
    }
    if (_missing(rowNode.data)) {
      rowNode.data = {};
    }
    const { field: field2, valueSetter } = column2.getColDef();
    if (_missing(field2) && _missing(valueSetter)) {
      _warn(17);
      return false;
    }
    if (this.dataTypeSvc && !this.dataTypeSvc.checkType(column2, newValue)) {
      _warn(135);
      return false;
    }
    const params = _addGridCommonParams(this.gos, {
      node: rowNode,
      data: rowNode.data,
      oldValue: this.getValue(column2, rowNode, void 0, eventSource),
      newValue,
      colDef: column2.getColDef(),
      column: column2
    });
    params.newValue = newValue;
    let valueWasDifferent;
    if (_exists(valueSetter)) {
      if (typeof valueSetter === "function") {
        valueWasDifferent = valueSetter(params);
      } else {
        valueWasDifferent = this.expressionSvc?.evaluate(valueSetter, params);
      }
    } else {
      valueWasDifferent = this.setValueUsingField(rowNode.data, field2, newValue, column2.isFieldContainsDots());
    }
    if (valueWasDifferent === void 0) {
      valueWasDifferent = true;
    }
    if (!valueWasDifferent) {
      return false;
    }
    rowNode.resetQuickFilterAggregateText();
    this.valueCache?.onDataChanged();
    const savedValue = this.getValue(column2, rowNode);
    this.dispatchCellValueChangedEvent(rowNode, params, savedValue, eventSource);
    if (rowNode.pinnedSibling) {
      this.dispatchCellValueChangedEvent(rowNode.pinnedSibling, params, savedValue, eventSource);
    }
    return true;
  }
  dispatchCellValueChangedEvent(rowNode, params, value2, source2) {
    this.eventSvc.dispatchEvent({
      type: "cellValueChanged",
      event: null,
      rowIndex: rowNode.rowIndex,
      rowPinned: rowNode.rowPinned,
      column: params.column,
      colDef: params.colDef,
      data: rowNode.data,
      node: rowNode,
      oldValue: params.oldValue,
      newValue: value2,
      value: value2,
      source: source2
    });
  }
  callColumnCellValueChangedHandler(event) {
    const onCellValueChanged = event.colDef.onCellValueChanged;
    if (typeof onCellValueChanged === "function") {
      this.beans.frameworkOverrides.wrapOutgoing(() => {
        onCellValueChanged({
          node: event.node,
          data: event.data,
          oldValue: event.oldValue,
          newValue: event.newValue,
          colDef: event.colDef,
          column: event.column,
          api: event.api,
          context: event.context
        });
      });
    }
  }
  setValueUsingField(data2, field2, newValue, isFieldContainsDots) {
    if (!field2) {
      return false;
    }
    let valuesAreSame = false;
    if (!isFieldContainsDots) {
      valuesAreSame = data2[field2] === newValue;
      if (!valuesAreSame) {
        data2[field2] = newValue;
      }
    } else {
      const fieldPieces = field2.split(".");
      let currentObject = data2;
      while (fieldPieces.length > 0 && currentObject) {
        const fieldPiece = fieldPieces.shift();
        if (fieldPieces.length === 0) {
          valuesAreSame = currentObject[fieldPiece] === newValue;
          if (!valuesAreSame) {
            currentObject[fieldPiece] = newValue;
          }
        } else {
          currentObject = currentObject[fieldPiece];
        }
      }
    }
    return !valuesAreSame;
  }
  executeValueGetterWithValueCache(valueGetter, data2, column2, rowNode) {
    const colId = column2.getColId();
    const valueFromCache = this.valueCache.getValue(rowNode, colId);
    if (valueFromCache !== void 0) {
      return valueFromCache;
    }
    const result2 = this.executeValueGetterWithoutValueCache(valueGetter, data2, column2, rowNode);
    this.valueCache.setValue(rowNode, colId, result2);
    return result2;
  }
  executeValueGetterWithoutValueCache(valueGetter, data2, column2, rowNode) {
    const params = _addGridCommonParams(this.gos, {
      data: data2,
      node: rowNode,
      column: column2,
      colDef: column2.getColDef(),
      getValue: this.getValueCallback.bind(this, rowNode)
    });
    let result2;
    if (typeof valueGetter === "function") {
      result2 = valueGetter(params);
    } else {
      result2 = this.expressionSvc?.evaluate(valueGetter, params);
    }
    return result2;
  }
  getValueCallback(node2, field2) {
    const otherColumn = this.colModel.getColDefCol(field2);
    if (otherColumn) {
      return this.getValue(otherColumn, node2);
    }
    return null;
  }
  // used by row grouping and pivot, to get key for a row. col can be a pivot col or a row grouping col
  getKeyForNode(col, rowNode) {
    const value2 = this.getValue(col, rowNode);
    const keyCreator = col.getColDef().keyCreator;
    let result2 = value2;
    if (keyCreator) {
      const keyParams = _addGridCommonParams(this.gos, {
        value: value2,
        colDef: col.getColDef(),
        column: col,
        node: rowNode,
        data: rowNode.data
      });
      result2 = keyCreator(keyParams);
    }
    if (typeof result2 === "string" || result2 == null) {
      return result2;
    }
    result2 = String(result2);
    if (result2 === "[object Object]") {
      _warn(121);
    }
    return result2;
  }
};
var CommunityCoreModule = {
  moduleName: "CommunityCore",
  version: VERSION,
  beans: [
    GridDestroyService,
    ApiFunctionService,
    Registry,
    UserComponentFactory,
    RowContainerHeightService,
    VisibleColsService,
    EventService,
    GridOptionsService,
    ColumnModel,
    PageBoundsService,
    PageBoundsListener,
    RowRenderer,
    ValueService,
    FocusService,
    Environment,
    ScrollVisibleService,
    CtrlsService,
    SyncService,
    ColumnNameService,
    ColumnViewportService,
    IconService
  ],
  icons: {
    // icon on select dropdowns (select cell editor, charts tool panels)
    selectOpen: "small-down",
    /** @deprecated v33 */
    smallDown: "small-down",
    /** @deprecated v33 */
    colorPicker: "color-picker",
    /** @deprecated v33 */
    smallUp: "small-up",
    /** @deprecated v33 */
    checkboxChecked: "small-up",
    /** @deprecated v33 */
    checkboxIndeterminate: "checkbox-indeterminate",
    /** @deprecated v33 */
    checkboxUnchecked: "checkbox-unchecked",
    /** @deprecated v33 */
    radioButtonOn: "radio-button-on",
    /** @deprecated v33 */
    radioButtonOff: "radio-button-off",
    /** @deprecated v33 */
    smallLeft: "small-left",
    /** @deprecated v33 */
    smallRight: "small-right"
  },
  apiFunctions: {
    getGridId,
    destroy,
    isDestroyed,
    getGridOption,
    setGridOption,
    updateGridOptions,
    isModuleRegistered
  },
  dependsOn: [
    DataTypeModule,
    ColumnMoveModule,
    ColumnResizeModule,
    SortModule,
    ColumnHeaderCompModule,
    ColumnGroupModule,
    ColumnGroupHeaderCompModule,
    OverlayModule,
    ChangeDetectionModule,
    AnimationFrameModule,
    KeyboardNavigationModule,
    PinnedColumnModule,
    AriaModule,
    TouchModule,
    CellRendererFunctionModule,
    ColumnFlexModule,
    ExpressionModule,
    SkeletonCellRendererModule,
    ColumnDelayRenderModule
  ]
};
var ENTERPRISE_MODULE_NAMES = {
  AdvancedFilter: 1,
  AiToolkit: 1,
  AllEnterprise: 1,
  BatchEdit: 1,
  CellSelection: 1,
  Clipboard: 1,
  ColumnMenu: 1,
  ColumnsToolPanel: 1,
  ContextMenu: 1,
  ExcelExport: 1,
  FiltersToolPanel: 1,
  Find: 1,
  GridCharts: 1,
  IntegratedCharts: 1,
  GroupFilter: 1,
  MasterDetail: 1,
  Menu: 1,
  MultiFilter: 1,
  NewFiltersToolPanel: 1,
  Pivot: 1,
  RangeSelection: 1,
  RichSelect: 1,
  RowNumbers: 1,
  RowGrouping: 1,
  RowGroupingPanel: 1,
  ServerSideRowModelApi: 1,
  ServerSideRowModel: 1,
  SetFilter: 1,
  SideBar: 1,
  Sparklines: 1,
  StatusBar: 1,
  TreeData: 1,
  ViewportRowModel: 1
};
var ALL_COLUMN_FILTERS = [
  "TextFilter",
  "NumberFilter",
  "DateFilter",
  "SetFilter",
  "MultiFilter",
  "GroupFilter",
  "CustomFilter"
];
var RESOLVABLE_MODULE_NAMES = {
  EditCore: [
    "TextEditor",
    "NumberEditor",
    "DateEditor",
    "CheckboxEditor",
    "LargeTextEditor",
    "SelectEditor",
    "RichSelect",
    "CustomEditor"
  ],
  CheckboxCellRenderer: ["AllCommunity"],
  ClientSideRowModelHierarchy: ["RowGrouping", "Pivot", "TreeData"],
  ColumnFilter: ALL_COLUMN_FILTERS,
  ColumnGroupHeaderComp: ["AllCommunity"],
  ColumnGroup: ["AllCommunity"],
  ColumnHeaderComp: ["AllCommunity"],
  ColumnMove: ["AllCommunity"],
  ColumnResize: ["AllCommunity"],
  CommunityCore: ["AllCommunity"],
  CsrmSsrmSharedApi: ["ClientSideRowModelApi", "ServerSideRowModelApi"],
  RowModelSharedApi: ["ClientSideRowModelApi", "ServerSideRowModelApi"],
  EnterpriseCore: ["AllEnterprise"],
  FilterCore: [...ALL_COLUMN_FILTERS, "QuickFilter", "ExternalFilter", "AdvancedFilter"],
  GroupCellRenderer: ["RowGrouping", "Pivot", "TreeData", "MasterDetail", "ServerSideRowModel"],
  KeyboardNavigation: ["AllCommunity"],
  LoadingCellRenderer: ["ServerSideRowModel"],
  MenuCore: ["ColumnMenu", "ContextMenu"],
  MenuItem: ["ColumnMenu", "ContextMenu", "MultiFilter", "IntegratedCharts", "ColumnsToolPanel"],
  Overlay: ["AllCommunity"],
  PinnedColumn: ["AllCommunity"],
  SharedAggregation: ["RowGrouping", "Pivot", "TreeData", "ServerSideRowModel"],
  SharedDragAndDrop: ["AllCommunity"],
  SharedMasterDetail: ["MasterDetail", "ServerSideRowModel"],
  SharedMenu: [...ALL_COLUMN_FILTERS, "ColumnMenu", "ContextMenu"],
  SharedPivot: ["Pivot", "ServerSideRowModel"],
  SharedRowGrouping: ["RowGrouping", "ServerSideRowModel"],
  SharedRowSelection: ["RowSelection", "ServerSideRowModel"],
  SkeletonCellRenderer: ["ServerSideRowModel"],
  Sort: ["AllCommunity"],
  SsrmInfiniteSharedApi: ["InfiniteRowModel", "ServerSideRowModelApi"],
  SharedTreeData: ["TreeData", "ServerSideRowModel"]
};
var MODULES_FOR_ROW_MODELS = {
  InfiniteRowModel: "infinite",
  ClientSideRowModelApi: "clientSide",
  ClientSideRowModel: "clientSide",
  ServerSideRowModelApi: "serverSide",
  ServerSideRowModel: "serverSide",
  ViewportRowModel: "viewport"
};
function resolveModuleNames(moduleName, rowModelType) {
  const resolvedModuleNames = [];
  for (const modName of Array.isArray(moduleName) ? moduleName : [moduleName]) {
    const resolved = RESOLVABLE_MODULE_NAMES[modName];
    if (resolved) {
      for (const resolvedModName of resolved) {
        const rowModelForModule = MODULES_FOR_ROW_MODELS[resolvedModName];
        if (!rowModelForModule || rowModelForModule === rowModelType) {
          resolvedModuleNames.push(resolvedModName);
        }
      }
    } else {
      resolvedModuleNames.push(modName);
    }
  }
  return resolvedModuleNames;
}
var NoModulesRegisteredError = () => `No AG Grid modules are registered! It is recommended to start with all Community features via the AllCommunityModule:
                    
    import { ModuleRegistry, AllCommunityModule } from 'ag-grid-community';
    
    ModuleRegistry.registerModules([ AllCommunityModule ]);
    `;
var moduleImportMsg = (moduleNames) => {
  const imports = moduleNames.map(
    (moduleName) => `import { ${convertToUserModuleName(moduleName)} } from '${ENTERPRISE_MODULE_NAMES[moduleName] ? "ag-grid-enterprise" : "ag-grid-community"}';`
  );
  const includeCharts = moduleNames.some((m) => m === "IntegratedCharts" || m === "Sparklines");
  if (includeCharts) {
    const chartImport = `import { AgChartsEnterpriseModule } from 'ag-charts-enterprise';`;
    imports.push(chartImport);
  }
  return `import { ModuleRegistry } from 'ag-grid-community'; 
${imports.join(" \n")} 

ModuleRegistry.registerModules([ ${moduleNames.map((m) => convertToUserModuleName(m, true)).join(", ")} ]); 

For more info see: ${baseDocLink}/modules/`;
};
function convertToUserModuleName(moduleName, inModuleRegistration = false) {
  if (inModuleRegistration && (moduleName === "IntegratedCharts" || moduleName === "Sparklines")) {
    return `${moduleName}Module.with(AgChartsEnterpriseModule)`;
  }
  return `${moduleName}Module`;
}
function umdMissingModule(reasonOrId, moduleNames) {
  const chartModules = moduleNames.filter((m) => m === "IntegratedCharts" || m === "Sparklines");
  let message2 = "";
  const agChartsDynamic = globalThis?.agCharts;
  if (!agChartsDynamic && chartModules.length > 0) {
    message2 = `Unable to use ${reasonOrId} as either the ag-charts-community or ag-charts-enterprise script needs to be included alongside ag-grid-enterprise.
`;
  } else if (moduleNames.some((m) => ENTERPRISE_MODULE_NAMES[m])) {
    message2 = message2 + `Unable to use ${reasonOrId} as that requires the ag-grid-enterprise script to be included.
`;
  }
  return message2;
}
function missingRowModelTypeError({
  moduleName,
  rowModelType
}) {
  return `To use the ${moduleName}Module you must set the gridOption "rowModelType='${rowModelType}'"`;
}
var missingModule = ({
  reasonOrId,
  moduleName,
  gridScoped,
  gridId,
  rowModelType,
  additionalText,
  isUmd: isUmd2
}) => {
  const resolvedModuleNames = resolveModuleNames(moduleName, rowModelType);
  const reason = typeof reasonOrId === "string" ? reasonOrId : MISSING_MODULE_REASONS[reasonOrId];
  if (isUmd2) {
    return umdMissingModule(reason, resolvedModuleNames);
  }
  const chartModules = resolvedModuleNames.filter((m) => m === "IntegratedCharts" || m === "Sparklines");
  const chartImportRequired = chartModules.length > 0 ? `${chartModules.map((m) => convertToUserModuleName(m)).join()} must be initialised with an AG Charts module. One of 'AgChartsCommunityModule' / 'AgChartsEnterpriseModule'.` : "";
  const explanation2 = `Unable to use ${reason} as ${resolvedModuleNames.length > 1 ? "one of " + resolvedModuleNames.map((m) => convertToUserModuleName(m)).join(", ") : convertToUserModuleName(resolvedModuleNames[0])} is not registered${gridScoped ? " for gridId: " + gridId : ""}. ${chartImportRequired} Check if you have registered the module:
`;
  return `${explanation2}
${moduleImportMsg(resolvedModuleNames)}` + (additionalText ? ` 

${additionalText}` : "");
};
var missingChartsWithModule = (gridModule) => {
  return `${gridModule} must be initialised with an AG Charts module. One of 'AgChartsCommunityModule' / 'AgChartsEnterpriseModule'.

import { AgChartsEnterpriseModule } from 'ag-charts-enterprise';
import { ModuleRegistry } from 'ag-grid-community';
import { ${gridModule} } from 'ag-grid-enterprise';
    
ModuleRegistry.registerModules([${gridModule}.with(AgChartsEnterpriseModule)]);
    `;
};
var clipboardApiError = (method) => `AG Grid: Unable to use the Clipboard API (navigator.clipboard.${method}()). The reason why it could not be used has been logged in the previous line. For this reason the grid has defaulted to using a workaround which doesn't perform as well. Either fix why Clipboard API is blocked, OR stop this message from appearing by setting grid property suppressClipboardApi=true (which will default the grid to using the workaround rather than the API.`;
var AG_GRID_ERRORS = {
  1: () => "`rowData` must be an array",
  2: ({ nodeId }) => `Duplicate node id '${nodeId}' detected from getRowId callback, this could cause issues in your grid.`,
  3: () => "Calling gridApi.resetRowHeights() makes no sense when using Auto Row Height.",
  4: ({ id: id2 }) => `Could not find row id=${id2}, data item was not found for this id`,
  5: ({ data: data2 }) => [
    `Could not find data item as object was not found.`,
    data2,
    " Consider using getRowId to help the Grid find matching row data"
  ],
  6: () => `'groupHideOpenParents' only works when specifying specific columns for 'colDef.showRowGroup'`,
  7: () => "Pivoting is not supported with aligned grids as it may produce different columns in each grid.",
  8: ({ key: key2 }) => `Unknown key for navigation ${key2}`,
  9: ({ variable }) => `No value for ${variable?.cssName}. This usually means that the grid has been initialised before styles have been loaded. The default value of ${variable?.defaultValue} will be used and updated when styles load.`,
  10: ({ eventType }) => `As of v33, the '${eventType}' event is deprecated. Use the global 'modelUpdated' event to determine when row children have changed.`,
  11: () => "No gridOptions provided to createGrid",
  12: ({ colKey }) => ["column ", colKey, " not found"],
  13: () => "Could not find rowIndex, this means tasks are being executed on a rowNode that has been removed from the grid.",
  14: ({ groupPrefix }) => `Row IDs cannot start with ${groupPrefix}, this is a reserved prefix for AG Grid's row grouping feature.`,
  15: ({ expression }) => ["value should be either a string or a function", expression],
  16: ({ expression, params, e }) => [
    "Processing of the expression failed",
    "Expression = ",
    expression,
    "Params = ",
    params,
    "Exception = ",
    e
  ],
  17: () => "you need either field or valueSetter set on colDef for editing to work",
  18: () => `alignedGrids contains an undefined option.`,
  19: () => `alignedGrids - No api found on the linked grid.`,
  20: () => `You may want to configure via a callback to avoid setup race conditions:
                     "alignedGrids: () => [linkedGrid]"`,
  21: () => "pivoting is not supported with aligned grids. You can only use one of these features at a time in a grid.",
  22: ({ key: key2 }) => `${key2} is an initial property and cannot be updated.`,
  23: () => "The return of `getRowHeight` cannot be zero. If the intention is to hide rows, use a filter instead.",
  24: () => "row height must be a number if not using standard row model",
  25: ({ id: id2 }) => [`The getRowId callback must return a string. The ID `, id2, ` is being cast to a string.`],
  26: ({ fnName, preDestroyLink }) => {
    return `Grid API function ${fnName}() cannot be called as the grid has been destroyed.
 Either clear local references to the grid api, when it is destroyed, or check gridApi.isDestroyed() to avoid calling methods against a destroyed grid.
 To run logic when the grid is about to be destroyed use the gridPreDestroy event. See: ${preDestroyLink}`;
  },
  27: ({ fnName, module }) => `API function '${fnName}' not registered to module '${module}'`,
  28: () => "setRowCount cannot be used while using row grouping.",
  29: () => "tried to call sizeColumnsToFit() but the grid is coming back with zero width, maybe the grid is not visible yet on the screen?",
  30: ({ toIndex }) => [
    "tried to insert columns in invalid location, toIndex = ",
    toIndex,
    "remember that you should not count the moving columns when calculating the new index"
  ],
  31: () => "infinite loop in resizeColumnSets",
  32: () => "applyColumnState() - the state attribute should be an array, however an array was not found. Please provide an array of items (one for each col you want to change) for state.",
  33: () => "stateItem.aggFunc must be a string. if using your own aggregation functions, register the functions first before using them in get/set state. This is because it is intended for the column state to be stored and retrieved as simple JSON.",
  34: ({ key: key2 }) => `the column type '${key2}' is a default column type and cannot be overridden.`,
  35: () => `Column type definitions 'columnTypes' with a 'type' attribute are not supported because a column type cannot refer to another column type. Only column definitions 'columnDefs' can use the 'type' attribute to refer to a column type.`,
  36: ({ t: t2 }) => "colDef.type '" + t2 + "' does not correspond to defined gridOptions.columnTypes",
  37: () => `Changing the column pinning status is not allowed with domLayout='print'`,
  38: ({ iconName }) => `provided icon '${iconName}' needs to be a string or a function`,
  39: () => "Applying column order broke a group where columns should be married together. Applying new order has been discarded.",
  40: ({ e, method }) => `${e}
${clipboardApiError(method)}`,
  41: () => "Browser did not allow document.execCommand('copy'). Ensure 'api.copySelectedRowsToClipboard() is invoked via a user event, i.e. button click, otherwise the browser will prevent it for security reasons.",
  42: () => "Browser does not support document.execCommand('copy') for clipboard operations",
  43: ({ iconName }) => `As of v33, icon '${iconName}' is deprecated. Use the icon CSS name instead.`,
  44: () => 'Data type definition hierarchies (via the "extendsDataType" property) cannot contain circular references.',
  45: ({ parentCellDataType }) => `The data type definition ${parentCellDataType} does not exist.`,
  46: () => 'The "baseDataType" property of a data type definition must match that of its parent.',
  47: ({ cellDataType }) => `Missing data type definition - "${cellDataType}"`,
  48: ({ property }) => `Cell data type is "object" but no Value ${property} has been provided. Please either provide an object data type definition with a Value ${property}, or set "colDef.value${property}"`,
  49: ({ methodName }) => `Framework component is missing the method ${methodName}()`,
  50: ({ compName }) => `Could not find component ${compName}, did you forget to configure this component?`,
  51: () => `Export cancelled. Export is not allowed as per your configuration.`,
  52: () => "There is no `window` associated with the current `document`",
  53: () => `unknown value type during csv conversion`,
  54: () => "Could not find document body, it is needed for drag and drop and context menu.",
  55: () => "addRowDropZone - A container target needs to be provided",
  56: () => "addRowDropZone - target already exists in the list of DropZones. Use `removeRowDropZone` before adding it again.",
  57: () => "unable to show popup filter, filter instantiation failed",
  58: () => "no values found for select cellEditor",
  59: () => "cannot select pinned rows",
  60: () => "cannot select node until it has finished loading",
  61: () => "since version v32.2.0, rowNode.isFullWidthCell() has been deprecated. Instead check `rowNode.detail` followed by the user provided `isFullWidthRow` grid option.",
  62: ({ colId }) => `setFilterModel() - no column found for colId: ${colId}`,
  63: ({ colId }) => `setFilterModel() - unable to fully apply model, filtering disabled for colId: ${colId}`,
  64: ({ colId }) => `setFilterModel() - unable to fully apply model, unable to create filter for colId: ${colId}`,
  65: () => "filter missing setModel method, which is needed for setFilterModel",
  66: () => "filter API missing getModel method, which is needed for getFilterModel",
  67: () => "Filter is missing isFilterActive() method",
  68: () => "Column Filter API methods have been disabled as Advanced Filters are enabled.",
  69: ({ guiFromFilter }) => `getGui method from filter returned ${guiFromFilter}; it should be a DOM element.`,
  70: ({ newFilter }) => `Grid option quickFilterText only supports string inputs, received: ${typeof newFilter}`,
  71: () => "debounceMs is ignored when apply button is present",
  72: ({ keys: keys2 }) => [`ignoring FilterOptionDef as it doesn't contain one of `, keys2],
  73: () => `invalid FilterOptionDef supplied as it doesn't contain a 'displayKey'`,
  74: () => "no filter options for filter",
  75: () => "Unknown button type specified",
  76: ({ filterModelType }) => [
    'Unexpected type of filter "',
    filterModelType,
    '", it looks like the filter was configured with incorrect Filter Options'
  ],
  77: () => `Filter model is missing 'conditions'`,
  78: () => 'Filter Model contains more conditions than "filterParams.maxNumConditions". Additional conditions have been ignored.',
  79: () => '"filterParams.maxNumConditions" must be greater than or equal to zero.',
  80: () => '"filterParams.numAlwaysVisibleConditions" must be greater than or equal to zero.',
  81: () => '"filterParams.numAlwaysVisibleConditions" cannot be greater than "filterParams.maxNumConditions".',
  82: ({ param }) => `DateFilter ${param} is not a number`,
  83: () => `DateFilter minValidYear should be <= maxValidYear`,
  84: () => `DateFilter minValidDate should be <= maxValidDate`,
  85: () => "DateFilter should not have both minValidDate and minValidYear parameters set at the same time! minValidYear will be ignored.",
  86: () => "DateFilter should not have both maxValidDate and maxValidYear parameters set at the same time! maxValidYear will be ignored.",
  87: () => "DateFilter parameter minValidDate should always be lower than or equal to parameter maxValidDate.",
  88: ({ index }) => `Invalid row index for ensureIndexVisible: ${index}`,
  89: () => `A template was provided for Header Group Comp - templates are only supported for Header Comps (not groups)`,
  90: () => `datasource is missing getRows method`,
  91: () => "Filter is missing method doesFilterPass",
  92: () => `AnimationFrameService called but animation frames are off`,
  93: () => "cannot add multiple ranges when `cellSelection.suppressMultiRanges = true`",
  94: ({
    paginationPageSizeOption,
    pageSizeSet,
    pageSizesSet,
    pageSizeOptions
  }) => `'paginationPageSize=${paginationPageSizeOption}'${pageSizeSet ? "" : " (default value)"}, but ${paginationPageSizeOption} is not included in${pageSizesSet ? "" : " the default"} paginationPageSizeSelector=[${pageSizeOptions?.join(", ")}].`,
  95: ({
    paginationPageSizeOption,
    paginationPageSizeSelector: paginationPageSizeSelector2
  }) => `Either set '${paginationPageSizeSelector2}' to an array that includes ${paginationPageSizeOption} or to 'false' to disable the page size selector.`,
  96: ({ id: id2, data: data2 }) => [
    "Duplicate ID",
    id2,
    "found for pinned row with data",
    data2,
    "When `getRowId` is defined, it must return unique IDs for all pinned rows. Use the `rowPinned` parameter."
  ],
  97: ({ colId }) => `cellEditor for column ${colId} is missing getGui() method`,
  98: () => "popup cellEditor does not work with fullRowEdit - you cannot use them both - either turn off fullRowEdit, or stop using popup editors.",
  99: () => "Since v32, `api.hideOverlay()` does not hide the loading overlay when `loading=true`. Set `loading=false` instead.",
  // 100: ({ rowModelType }: { rowModelType: RowModelType }) =>
  //     `selectAll only available when rowModelType='clientSide', ie not ${rowModelType}` as const,
  101: ({
    propertyName,
    componentName,
    agGridDefaults,
    jsComps
  }) => {
    const textOutput2 = [];
    const validComponents = [
      // Don't include the old names / internals in potential suggestions
      ...Object.keys(agGridDefaults ?? []).filter(
        (k) => !["agCellEditor", "agGroupRowRenderer", "agSortIndicator"].includes(k)
      ),
      ...Object.keys(jsComps ?? []).filter((k) => !!jsComps[k])
    ];
    const suggestions = _fuzzySuggestions({
      inputValue: componentName,
      allSuggestions: validComponents,
      hideIrrelevant: true,
      filterByPercentageOfBestMatch: 0.8
    }).values;
    textOutput2.push(
      `Could not find '${componentName}' component. It was configured as "${propertyName}: '${componentName}'" but it wasn't found in the list of registered components.
`
    );
    if (suggestions.length > 0) {
      textOutput2.push(`         Did you mean: [${suggestions.slice(0, 3)}]?
`);
    }
    textOutput2.push(`If using a custom component check it has been registered correctly.`);
    return textOutput2;
  },
  102: () => "selectAll: 'filtered' only works when gridOptions.rowModelType='clientSide'",
  103: () => "Invalid selection state. When using client-side row model, the state must conform to `string[]`.",
  104: ({ value: value2, param }) => `Numeric value ${value2} passed to ${param} param will be interpreted as ${value2} seconds. If this is intentional use "${value2}s" to silence this warning.`,
  105: ({ e }) => [`chart rendering failed`, e],
  106: () => `Theming API and Legacy Themes are both used in the same page. A Theming API theme has been provided to the 'theme' grid option, but the file (ag-grid.css) is also included and will cause styling issues. Remove ag-grid.css from the page. See the migration guide: ${baseDocLink}/theming-migration/`,
  107: ({ key: key2, value: value2 }) => `Invalid value for theme param ${key2} - ${value2}`,
  108: ({ e }) => ["chart update failed", e],
  109: ({ inputValue, allSuggestions }) => {
    const suggestions = _fuzzySuggestions({
      inputValue,
      allSuggestions,
      hideIrrelevant: true,
      filterByPercentageOfBestMatch: 0.8
    }).values;
    return [
      `Could not find '${inputValue}' aggregate function. It was configured as "aggFunc: '${inputValue}'" but it wasn't found in the list of registered aggregations.`,
      suggestions.length > 0 ? `         Did you mean: [${suggestions.slice(0, 3)}]?` : "",
      `If using a custom aggregation function check it has been registered correctly.`
    ].join("\n");
  },
  110: () => "groupHideOpenParents only works when specifying specific columns for colDef.showRowGroup",
  111: () => "Invalid selection state. When `groupSelects` is enabled, the state must conform to `IServerSideGroupSelectionState`.",
  113: () => "Set Filter cannot initialise because you are using a row model that does not contain all rows in the browser. Either use a different filter type, or configure Set Filter such that you provide it with values",
  114: ({ component }) => `Could not find component with name of ${component}. Is it in Vue.components?`,
  // 115: () => 'The provided selection state should be an object.' as const,
  116: () => "Invalid selection state. The state must conform to `IServerSideSelectionState`.",
  117: () => "selectAll must be of boolean type.",
  118: () => "Infinite scrolling must be enabled in order to set the row count.",
  119: () => "Unable to instantiate filter",
  120: () => "MultiFloatingFilterComp expects MultiFilter as its parent",
  121: () => "a column you are grouping or pivoting by has objects as values. If you want to group by complex objects then either a) use a colDef.keyCreator (see AG Grid docs) or b) to toString() on the object to return a key",
  122: () => "could not find the document, document is empty",
  123: () => "Advanced Filter is only supported with the Client-Side Row Model or Server-Side Row Model.",
  124: () => "No active charts to update.",
  125: ({ chartId }) => `Unable to update chart. No active chart found with ID: ${chartId}.`,
  126: () => "unable to restore chart as no chart model is provided",
  127: ({ allRange }) => `unable to create chart as ${allRange ? "there are no columns in the grid" : "no range is selected"}.`,
  128: ({ feature }) => `${feature} is only available if using 'multiRow' selection mode.`,
  129: ({ feature, rowModel }) => `${feature} is only available if using 'clientSide' or 'serverSide' rowModelType, you are using ${rowModel}.`,
  130: () => 'cannot multi select unless selection mode is "multiRow"',
  // 131: () => 'cannot range select while selecting multiple rows' as const,
  132: () => "Row selection features are not available unless `rowSelection` is enabled.",
  133: ({ iconName }) => `icon '${iconName}' function should return back a string or a dom object`,
  134: ({ iconName }) => `Did not find icon '${iconName}'`,
  135: () => `Data type of the new value does not match the cell data type of the column`,
  136: () => `Unable to update chart as the 'type' is missing. It must be either 'rangeChartUpdate', 'pivotChartUpdate', or 'crossFilterChartUpdate'.`,
  137: ({ type, currentChartType }) => `Unable to update chart as a '${type}' update type is not permitted on a ${currentChartType}.`,
  138: ({ chartType }) => `invalid chart type supplied: ${chartType}`,
  139: ({ customThemeName }) => `a custom chart theme with the name ${customThemeName} has been supplied but not added to the 'chartThemes' list`,
  140: ({ name: name2 }) => `no stock theme exists with the name '${name2}' and no custom chart theme with that name was supplied to 'customChartThemes'`,
  141: () => "cross filtering with row grouping is not supported.",
  142: () => "cross filtering is only supported in the client side row model.",
  143: ({ panel: panel2 }) => `'${panel2}' is not a valid Chart Tool Panel name`,
  144: ({ type }) => `Invalid charts data panel group name supplied: '${type}'`,
  145: ({ group }) => `As of v32, only one charts customize panel group can be expanded at a time. '${group}' will not be expanded.`,
  146: ({ comp }) => `Unable to instantiate component '${comp}' as its module hasn't been loaded. Add 'ValidationModule' to see which module is required.`,
  147: ({ group }) => `Invalid charts customize panel group name supplied: '${group}'`,
  148: ({ group }) => `invalid chartGroupsDef config '${group}'`,
  149: ({ group, chartType }) => `invalid chartGroupsDef config '${group}.${chartType}'`,
  150: () => `'seriesChartTypes' are required when the 'customCombo' chart type is specified.`,
  151: ({ chartType }) => `invalid chartType '${chartType}' supplied in 'seriesChartTypes', converting to 'line' instead.`,
  152: ({ colId }) => `no 'seriesChartType' found for colId = '${colId}', defaulting to 'line'.`,
  153: ({ chartDataType }) => `unexpected chartDataType value '${chartDataType}' supplied, instead use 'category', 'series' or 'excluded'`,
  154: ({ colId }) => `cross filtering requires a 'agSetColumnFilter' or 'agMultiColumnFilter' to be defined on the column with id: ${colId}`,
  155: ({ option }) => `'${option}' is not a valid Chart Toolbar Option`,
  156: ({ panel: panel2 }) => `Invalid panel in chartToolPanelsDef.panels: '${panel2}'`,
  157: ({ unrecognisedGroupIds }) => ["unable to find group(s) for supplied groupIds:", unrecognisedGroupIds],
  158: () => "can not expand a column item that does not represent a column group header",
  159: () => "Invalid params supplied to createExcelFileForExcel() - `ExcelExportParams.data` is empty.",
  160: () => `Export cancelled. Export is not allowed as per your configuration.`,
  161: () => "The Excel Exporter is currently on Multi Sheet mode. End that operation by calling 'api.getMultipleSheetAsExcel()' or 'api.exportMultipleSheetsAsExcel()'",
  162: ({ id: id2, dataType }) => `Unrecognized data type for excel export [${id2}.dataType=${dataType}]`,
  163: ({ featureName }) => `Excel table export does not work with ${featureName}. The exported Excel file will not contain any Excel tables.
 Please turn off ${featureName} to enable Excel table exports.`,
  164: () => "Unable to add data table to Excel sheet: A table already exists.",
  165: () => "Unable to add data table to Excel sheet: Missing required parameters.",
  166: ({ unrecognisedGroupIds }) => ["unable to find groups for these supplied groupIds:", unrecognisedGroupIds],
  167: ({ unrecognisedColIds }) => ["unable to find columns for these supplied colIds:", unrecognisedColIds],
  168: () => "detailCellRendererParams.template should be function or string",
  169: () => 'Reference to eDetailGrid was missing from the details template. Please add data-ref="eDetailGrid" to the template.',
  170: ({ providedStrategy }) => `invalid cellRendererParams.refreshStrategy = ${providedStrategy} supplied, defaulting to refreshStrategy = 'rows'.`,
  171: () => "could not find detail grid options for master detail, please set gridOptions.detailCellRendererParams.detailGridOptions",
  172: () => "could not find getDetailRowData for master / detail, please set gridOptions.detailCellRendererParams.getDetailRowData",
  173: ({ group }) => `invalid chartGroupsDef config '${group}'`,
  174: ({ group, chartType }) => `invalid chartGroupsDef config '${group}.${chartType}'`,
  175: ({ menuTabName, itemsToConsider }) => [
    `Trying to render an invalid menu item '${menuTabName}'. Check that your 'menuTabs' contains one of `,
    itemsToConsider
  ],
  176: ({ key: key2 }) => `unknown menu item type ${key2}`,
  177: () => `valid values for cellSelection.handle.direction are 'x', 'y' and 'xy'. Default to 'xy'.`,
  178: ({ colId }) => `column ${colId} is not visible`,
  179: () => "totalValueGetter should be either a function or a string (expression)",
  180: () => "agRichSelectCellEditor requires cellEditorParams.values to be set",
  181: () => "agRichSelectCellEditor cannot have `multiSelect` and `allowTyping` set to `true`. AllowTyping has been turned off.",
  182: () => 'you cannot mix groupDisplayType = "multipleColumns" with treeData, only one column can be used to display groups when doing tree data',
  183: () => "Group Column Filter only works on group columns. Please use a different filter.",
  184: ({ parentGroupData, childNodeData }) => [`duplicate group keys for row data, keys should be unique`, [parentGroupData, childNodeData]],
  185: ({ data: data2 }) => [`getDataPath() should not return an empty path`, [data2]],
  186: ({
    rowId,
    rowData,
    duplicateRowsData
  }) => [
    `duplicate group keys for row data, keys should be unique`,
    rowId,
    rowData,
    ...duplicateRowsData ?? []
  ],
  187: ({ rowId, firstData, secondData }) => [
    `Duplicate node id ${rowId}. Row IDs are provided via the getRowId() callback. Please modify the getRowId() callback code to provide unique row id values.`,
    "first instance",
    firstData,
    "second instance",
    secondData
  ],
  188: (props) => `getRowId callback must be provided for Server Side Row Model ${props?.feature || "selection"} to work correctly.`,
  189: ({ startRow }) => `invalid value ${startRow} for startRow, the value should be >= 0`,
  190: ({ rowGroupId, data: data2 }) => [
    `null and undefined values are not allowed for server side row model keys`,
    rowGroupId ? `column = ${rowGroupId}` : ``,
    `data is `,
    data2
  ],
  // 191: () => `cannot multi select unless selection mode is 'multiRow'` as const,
  // 192: () => `cannot use range selection when multi selecting rows` as const,
  // 193: () => "cannot multi select unless selection mode is 'multiRow'" as const,
  194: ({ method }) => `calling gridApi.${method}() is only possible when using rowModelType=\`clientSide\`.`,
  195: ({ justCurrentPage }) => `selecting just ${justCurrentPage ? "current page" : "filtered"} only works when gridOptions.rowModelType='clientSide'`,
  196: ({ key: key2 }) => `Provided ids must be of string type. Invalid id provided: ${key2}`,
  197: () => "`toggledNodes` must be an array of string ids.",
  // 198: () => `cannot multi select unless selection mode is 'multiRow'` as const,
  199: () => `getSelectedNodes and getSelectedRows functions cannot be used with select all functionality with the server-side row model. Use \`api.getServerSideSelectionState()\` instead.`,
  200: missingModule,
  201: ({ rowModelType }) => `Could not find row model for rowModelType = ${rowModelType}`,
  202: () => `\`getSelectedNodes\` and \`getSelectedRows\` functions cannot be used with \`groupSelectsChildren\` and the server-side row model. Use \`api.getServerSideSelectionState()\` instead.`,
  203: () => "Server Side Row Model does not support Dynamic Row Height and Cache Purging. Either a) remove getRowHeight() callback or b) remove maxBlocksInCache property. Purging has been disabled.",
  204: () => "Server Side Row Model does not support Auto Row Height and Cache Purging. Either a) remove colDef.autoHeight or b) remove maxBlocksInCache property. Purging has been disabled.",
  205: ({ duplicateIdText }) => `Unable to display rows as duplicate row ids (${duplicateIdText}) were returned by the getRowId callback. Please modify the getRowId callback to provide unique ids.`,
  206: () => "getRowId callback must be implemented for transactions to work. Transaction was ignored.",
  207: () => 'The Set Filter Parameter "defaultToNothingSelected" value was ignored because it does not work when "excelMode" is used.',
  208: () => `Set Filter Value Formatter must return string values. Please ensure the Set Filter Value Formatter returns string values for complex objects.`,
  209: () => `Set Filter Key Creator is returning null for provided values and provided values are primitives. Please provide complex objects. See ${baseDocLink}/filter-set-filter-list/#filter-value-types`,
  210: () => "Set Filter has a Key Creator, but provided values are primitives. Did you mean to provide complex objects?",
  211: () => "property treeList=true for Set Filter params, but you did not provide a treeListPathGetter or values of type Date.",
  212: () => `please review all your toolPanel components, it seems like at least one of them doesn't have an id`,
  213: () => "Advanced Filter does not work with Filters Tool Panel. Filters Tool Panel has been disabled.",
  214: ({ key: key2 }) => `unable to lookup Tool Panel as invalid key supplied: ${key2}`,
  215: ({ key: key2, defaultByKey }) => `the key ${key2} is not a valid key for specifying a tool panel, valid keys are: ${Object.keys(defaultByKey ?? {}).join(",")}`,
  216: ({ name: name2 }) => `Missing component for '${name2}'`,
  217: ({ invalidColIds }) => ["unable to find grid columns for the supplied colDef(s):", invalidColIds],
  218: ({ property, defaultOffset }) => `${property} must be a number, the value you provided is not a valid number. Using the default of ${defaultOffset}px.`,
  219: ({ property }) => `Property ${property} does not exist on the target object.`,
  220: ({ lineDash }) => `'${lineDash}' is not a valid 'lineDash' option.`,
  221: () => `agAggregationComponent should only be used with the client and server side row model.`,
  222: () => `agFilteredRowCountComponent should only be used with the client side row model.`,
  223: () => `agSelectedRowCountComponent should only be used with the client and server side row model.`,
  224: () => `agTotalAndFilteredRowCountComponent should only be used with the client side row model.`,
  225: () => "agTotalRowCountComponent should only be used with the client side row model.",
  226: () => "viewport is missing init method.",
  227: () => "menu item icon must be DOM node or string",
  228: ({ menuItemOrString }) => `unrecognised menu item ${menuItemOrString}`,
  229: ({ index }) => ["invalid row index for ensureIndexVisible: ", index],
  230: () => "detailCellRendererParams.template is not supported by AG Grid React. To change the template, provide a Custom Detail Cell Renderer. See https://www.ag-grid.com/react-data-grid/master-detail-custom-detail/",
  // @deprecated v32 mark for removal as part of v32 deprecated features
  231: () => "As of v32, using custom components with `reactiveCustomComponents = false` is deprecated.",
  232: () => "Using both rowData and v-model. rowData will be ignored.",
  233: ({ methodName }) => `Framework component is missing the method ${methodName}()`,
  234: () => 'Group Column Filter does not work with the colDef property "field". This property will be ignored.',
  235: () => 'Group Column Filter does not work with the colDef property "filterValueGetter". This property will be ignored.',
  236: () => 'Group Column Filter does not work with the colDef property "filterParams". This property will be ignored.',
  237: () => "Group Column Filter does not work with Tree Data enabled. Please disable Tree Data, or use a different filter.",
  238: () => "setRowCount can only accept a positive row count.",
  239: () => 'Theming API and CSS File Themes are both used in the same page. In v33 we released the Theming API as the new default method of styling the grid. See the migration docs https://www.ag-grid.com/react-data-grid/theming-migration/. Because no value was provided to the `theme` grid option it defaulted to themeQuartz. But the file (ag-grid.css) is also included and will cause styling issues. Either pass the string "legacy" to the theme grid option to use v32 style themes, or remove ag-grid.css from the page to use Theming API.',
  240: ({ theme }) => `theme grid option must be a Theming API theme object or the string "legacy", received: ${theme}`,
  // 241: () => `cannot select multiple rows when rowSelection.mode is set to 'singleRow'` as const,
  // 242: () => 'cannot select multiple rows when using rangeSelect' as const,
  243: () => "Failed to deserialize state - each provided state object must be an object.",
  244: () => "Failed to deserialize state - `selectAllChildren` must be a boolean value or undefined.",
  245: () => "Failed to deserialize state - `toggledNodes` must be an array.",
  246: () => "Failed to deserialize state - Every `toggledNode` requires an associated string id.",
  247: () => `Row selection state could not be parsed due to invalid data. Ensure all child state has toggledNodes or does not conform with the parent rule. 
Please rebuild the selection state and reapply it.`,
  248: () => "SetFloatingFilter expects SetFilter as its parent",
  249: () => "Must supply a Value Formatter in Set Filter params when using a Key Creator",
  250: () => "Must supply a Key Creator in Set Filter params when `treeList = true` on a group column, and Tree Data or Row Grouping is enabled.",
  251: ({ chartType }) => `AG Grid: Unable to create chart as an invalid chartType = '${chartType}' was supplied.`,
  252: () => "cannot get grid to draw rows when it is in the middle of drawing rows. \nYour code probably called a grid API method while the grid was in the render stage. \nTo overcome this, put the API call into a timeout, e.g. instead of api.redrawRows(), call setTimeout(function() { api.redrawRows(); }, 0). \nTo see what part of your code that caused the refresh check this stacktrace.",
  253: ({ version: version2 }) => ["Illegal version string: ", version2],
  254: () => "Cannot create chart: no chart themes available.",
  255: ({ point }) => `Lone surrogate U+${point?.toString(16).toUpperCase()} is not a scalar value`,
  256: () => "Unable to initialise. See validation error, or load ValidationModule if missing.",
  257: () => missingChartsWithModule("IntegratedChartsModule"),
  258: () => missingChartsWithModule("SparklinesModule"),
  259: ({ part }) => `the argument to theme.withPart must be a Theming API part object, received: ${part}`,
  260: ({
    propName,
    compName,
    gridScoped,
    gridId,
    rowModelType
  }) => missingModule({
    reasonOrId: `AG Grid '${propName}' component: ${compName}`,
    moduleName: USER_COMP_MODULES[compName],
    gridId,
    gridScoped,
    rowModelType
  }),
  261: () => "As of v33, `column.isHovered()` is deprecated. Use `api.isColumnHovered(column)` instead.",
  262: () => 'As of v33, icon key "smallDown" is deprecated. Use "advancedFilterBuilderSelect" for Advanced Filter Builder dropdown, "selectOpen" for Select cell editor and dropdowns (e.g. Integrated Charts menu), "richSelectOpen" for Rich Select cell editor.',
  263: () => 'As of v33, icon key "smallLeft" is deprecated. Use "panelDelimiterRtl" for Row Group Panel / Pivot Panel, "subMenuOpenRtl" for sub-menus.',
  264: () => 'As of v33, icon key "smallRight" is deprecated. Use "panelDelimiter" for Row Group Panel / Pivot Panel, "subMenuOpen" for sub-menus.',
  265: ({ colId }) => `Unable to infer chart data type for column '${colId}' if first data entry is null. Please specify "chartDataType", or a "cellDataType" in the column definition. For more information, see ${baseDocLink}/integrated-charts-range-chart#coldefchartdatatype .`,
  266: () => 'As of v33.1, using "keyCreator" with the Rich Select Editor has been deprecated. It now requires the "formatValue" callback to convert complex data to strings.',
  267: () => "Detail grids can not use a different theme to the master grid, the `theme` detail grid option will be ignored.",
  268: () => "Transactions aren't supported with tree data when using treeDataChildrenField",
  269: () => "When `masterSelects: 'detail'`, detail grids must be configured with multi-row selection",
  270: ({ id: id2, parentId }) => `Cycle detected for row with id='${id2}' and parent id='${parentId}'. Resetting the parent for row with id='${id2}' and showing it as a root-level node.`,
  271: ({ id: id2, parentId }) => `Parent row not found for row with id='${id2}' and parent id='${parentId}'. Showing row with id='${id2}' as a root-level node.`,
  272: () => NoModulesRegisteredError(),
  273: ({ providedId, usedId }) => `Provided column id '${providedId}' was already in use, ensure all column and group ids are unique. Using '${usedId}' instead.`,
  274: ({ prop }) => {
    let msg = `Since v33, ${prop} has been deprecated.`;
    switch (prop) {
      case "maxComponentCreationTimeMs":
        msg += " This property is no longer required and so will be removed in a future version.";
        break;
      case "setGridApi":
        msg += ` This method is not called by AG Grid. To access the GridApi see: https://ag-grid.com/react-data-grid/grid-interface/#grid-api `;
        break;
      case "children":
        msg += ` For multiple versions AgGridReact does not support children.`;
        break;
    }
    return msg;
  },
  275: missingRowModelTypeError,
  276: () => "Row Numbers Row Resizer cannot be used when Grid Columns have `autoHeight` enabled.",
  277: ({ colId }) => `'enableFilterHandlers' is set to true, but column '${colId}' does not have 'filter.doesFilterPass' or 'filter.handler' set.`,
  278: ({ colId }) => `Unable to create filter handler for column '${colId}'`,
  279: (_) => {
  },
  // `Unable to create dynamic bean '${name}' during module init lifecycle, dynamic beans must be initialised on first use.` as const,
  280: ({ colId }) => `'name' must be provided for custom filter components for column '${colId}`,
  281: ({ colId }) => `Filter for column '${colId}' does not have 'filterParams.buttons', but the new Filters Tool Panel has buttons configured. Either configure buttons for the filter, or disable buttons on the Filters Tool Panel.`,
  282: () => "New filter tool panel requires `enableFilterHandlers: true`.",
  283: () => "As of v34, use the same method on the filter handler (`api.getColumnFilterHandler(colKey)`) instead.",
  284: () => "As of v34, filters are active when they have a model. Use `api.getColumnFilterModel()` instead.",
  285: () => "As of v34, use (`api.getColumnFilterModel()`) instead.",
  286: () => "As of v34, use (`api.setColumnFilterModel()`) instead.",
  287: () => "`api.doFilterAction()` requires `enableFilterHandlers = true",
  288: () => "`api.getColumnFilterModel(key, true)` requires `enableFilterHandlers = true",
  289: ({ rowModelType }) => `Row Model '${rowModelType}' is not supported with Batch Editing`,
  290: ({ rowIndex, rowPinned }) => `Row with index '${rowIndex}' and pinned state '${rowPinned}' not found`,
  291: () => "License Key being set multiple times with different values. This can result in an incorrect license key being used,",
  292: ({ colId }) => `The Multi Filter for column '${colId}' has buttons configured against the child filters. When 'enableFilterHandlers=true', buttons must instead be provided against the parent Multi Filter params. The child filter buttons will be ignored.`
};
function getError(errorId, args2) {
  const msgOrFunc = AG_GRID_ERRORS[errorId];
  if (!msgOrFunc) {
    return [`Missing error text for error id ${errorId}!`];
  }
  const errorBody = msgOrFunc(args2);
  const errorLink = getErrorLink(errorId, args2);
  const errorSuffix = `
See ${errorLink}`;
  return Array.isArray(errorBody) ? errorBody.concat(errorSuffix) : [errorBody, errorSuffix];
}
var MISSING_MODULE_REASONS = {
  1: "Charting Aggregation",
  2: "pivotResultFields",
  3: "setTooltip"
};
var _gridApiCache = /* @__PURE__ */ new WeakMap();
var _gridElementCache = /* @__PURE__ */ new WeakMap();
var nextGridId = 1;
var GridCoreCreator = class {
  create(eGridDiv, providedOptions, createUi, acceptChanges, params, _destroyCallback) {
    const gridOptions = GlobalGridOptions.applyGlobalGridOptions(providedOptions);
    const gridId = gridOptions.gridId ?? String(nextGridId++);
    const registeredModules = this.getRegisteredModules(params, gridId, gridOptions.rowModelType);
    const beanClasses = this.createBeansList(gridOptions.rowModelType, registeredModules, gridId);
    const providedBeanInstances = this.createProvidedBeans(eGridDiv, gridOptions, params);
    if (!beanClasses) {
      return void 0;
    }
    const destroyCallback = () => {
      _gridElementCache.delete(api2);
      _gridApiCache.delete(eGridDiv);
      _unRegisterGridModules(gridId);
      _destroyCallback?.();
    };
    const contextParams = {
      providedBeanInstances,
      beanClasses,
      id: gridId,
      beanInitComparator: gridBeanInitComparator,
      beanDestroyComparator: gridBeanDestroyComparator,
      derivedBeans: [createGridApi],
      destroyCallback
    };
    const context = new AgContext(contextParams);
    this.registerModuleFeatures(context, registeredModules);
    createUi(context);
    context.getBean("syncSvc").start();
    acceptChanges?.(context);
    const api2 = context.getBean("gridApi");
    _gridApiCache.set(eGridDiv, api2);
    _gridElementCache.set(api2, eGridDiv);
    return api2;
  }
  getRegisteredModules(params, gridId, rowModelType) {
    _registerModule(CommunityCoreModule, void 0, true);
    params?.modules?.forEach((m) => _registerModule(m, gridId));
    return _getRegisteredModules(gridId, getDefaultRowModelType(rowModelType));
  }
  registerModuleFeatures(context, registeredModules) {
    const registry = context.getBean("registry");
    const apiFunctionSvc = context.getBean("apiFunctionSvc");
    for (const module of registeredModules) {
      registry.registerModule(module);
      const apiFunctions = module.apiFunctions;
      if (apiFunctions) {
        const names = Object.keys(apiFunctions);
        for (const name2 of names) {
          apiFunctionSvc?.addFunction(name2, apiFunctions[name2]);
        }
      }
    }
  }
  createProvidedBeans(eGridDiv, gridOptions, params) {
    let frameworkOverrides = params ? params.frameworkOverrides : null;
    if (_missing(frameworkOverrides)) {
      frameworkOverrides = new VanillaFrameworkOverrides();
    }
    const seed = {
      gridOptions,
      eGridDiv,
      eRootDiv: eGridDiv,
      globalListener: params ? params.globalListener : null,
      globalSyncListener: params ? params.globalSyncListener : null,
      frameworkOverrides
    };
    if (params?.providedBeanInstances) {
      Object.assign(seed, params.providedBeanInstances);
    }
    return seed;
  }
  createBeansList(userProvidedRowModelType, registeredModules, gridId) {
    const rowModelModuleNames = {
      clientSide: "ClientSideRowModel",
      infinite: "InfiniteRowModel",
      serverSide: "ServerSideRowModel",
      viewport: "ViewportRowModel"
    };
    const rowModelType = getDefaultRowModelType(userProvidedRowModelType);
    const rowModuleModelName = rowModelModuleNames[rowModelType];
    if (!rowModuleModelName) {
      _logPreInitErr(201, { rowModelType }, `Unknown rowModelType ${rowModelType}.`);
      return;
    }
    if (!_hasUserRegistered()) {
      _logPreInitErr(272, void 0, NoModulesRegisteredError());
      return;
    }
    if (!userProvidedRowModelType) {
      const registeredRowModelModules = Object.entries(rowModelModuleNames).filter(
        ([rowModelType2, module]) => _isModuleRegistered(module, gridId, rowModelType2)
      );
      if (registeredRowModelModules.length == 1) {
        const [userRowModelType, moduleName] = registeredRowModelModules[0];
        if (userRowModelType !== rowModelType) {
          const params = {
            moduleName,
            rowModelType: userRowModelType
          };
          _logPreInitErr(275, params, missingRowModelTypeError(params));
          return;
        }
      }
    }
    if (!_isModuleRegistered(rowModuleModelName, gridId, rowModelType)) {
      _logPreInitErr(
        200,
        {
          reasonOrId: `rowModelType = '${rowModelType}'`,
          moduleName: rowModuleModelName,
          gridScoped: _areModulesGridScoped(),
          gridId,
          rowModelType
        },
        `Missing module ${rowModuleModelName}Module for rowModelType ${rowModelType}.`
      );
      return;
    }
    const beans = /* @__PURE__ */ new Set();
    for (const module of registeredModules) {
      for (const bean of module.beans ?? []) {
        beans.add(bean);
      }
    }
    return Array.from(beans);
  }
};
function getDefaultRowModelType(passedRowModelType) {
  return passedRowModelType ?? "clientSide";
}
function _getClientSideRowModel(beans) {
  const rowModel = beans.rowModel;
  return rowModel.getType() === "clientSide" ? rowModel : void 0;
}
function _getInfiniteRowModel(beans) {
  const rowModel = beans.rowModel;
  return rowModel.getType() === "infinite" ? rowModel : void 0;
}
function _getServerSideRowModel(beans) {
  const rowModel = beans.rowModel;
  return rowModel.getType() === "serverSide" ? rowModel : void 0;
}
var LocaleService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "localeSvc";
  }
  getLocaleTextFunc() {
    const gos = this.gos;
    const getLocaleText = gos.getCallback("getLocaleText");
    if (getLocaleText) {
      return _getLocaleTextFromFunc(getLocaleText);
    }
    return _getLocaleTextFromMap(gos.get("localeText"));
  }
};
function convertColumnState(columnState, enablePivotMode = false) {
  const sortColumns2 = [];
  const groupColIds = [];
  const aggregationColumns = [];
  const pivotColIds = [];
  const leftColIds = [];
  const rightColIds = [];
  const hiddenColIds = [];
  const columnSizes = [];
  const columns2 = [];
  let defaultSortIndex = 0;
  for (let i2 = 0; i2 < columnState.length; i2++) {
    const {
      colId,
      sort,
      sortIndex,
      rowGroup,
      rowGroupIndex,
      aggFunc,
      pivot: pivot2,
      pivotIndex,
      pinned,
      hide: hide2,
      width,
      flex: flex2
    } = columnState[i2];
    columns2.push(colId);
    if (sort) {
      sortColumns2[sortIndex ?? defaultSortIndex++] = { colId, sort };
    }
    if (rowGroup) {
      groupColIds[rowGroupIndex ?? 0] = colId;
    }
    if (typeof aggFunc === "string") {
      aggregationColumns.push({ colId, aggFunc });
    }
    if (pivot2) {
      pivotColIds[pivotIndex ?? 0] = colId;
    }
    if (pinned) {
      (pinned === "right" ? rightColIds : leftColIds).push(colId);
    }
    if (hide2) {
      hiddenColIds.push(colId);
    }
    if (flex2 != null || width) {
      columnSizes.push({ colId, flex: flex2 ?? void 0, width });
    }
  }
  return {
    sort: sortColumns2.length ? { sortModel: _removeEmptyValues(sortColumns2) } : void 0,
    rowGroup: groupColIds.length ? { groupColIds: _removeEmptyValues(groupColIds) } : void 0,
    aggregation: aggregationColumns.length ? { aggregationModel: aggregationColumns } : void 0,
    pivot: pivotColIds.length || enablePivotMode ? { pivotMode: enablePivotMode, pivotColIds: _removeEmptyValues(pivotColIds) } : void 0,
    columnPinning: leftColIds.length || rightColIds.length ? { leftColIds, rightColIds } : void 0,
    columnVisibility: hiddenColIds.length ? { hiddenColIds } : void 0,
    columnSizing: columnSizes.length ? { columnSizingModel: columnSizes } : void 0,
    columnOrder: columns2.length ? { orderedColIds: columns2 } : void 0
  };
}
function _removeEmptyValues(array2) {
  return array2.filter((a2) => a2 != void 0);
}
function _convertColumnGroupState(columnGroupState) {
  const openColumnGroups = [];
  for (const { groupId, open } of columnGroupState) {
    if (open) {
      openColumnGroups.push(groupId);
    }
  }
  return openColumnGroups.length ? { openColumnGroupIds: openColumnGroups } : void 0;
}
var BaseComponentWrapper = class {
  wrap(OriginalConstructor, mandatoryMethods, optionalMethods, componentType) {
    const wrapper2 = this.createWrapper(OriginalConstructor, componentType);
    for (const methodName of mandatoryMethods ?? []) {
      this.createMethod(wrapper2, methodName, true);
    }
    for (const methodName of optionalMethods ?? []) {
      this.createMethod(wrapper2, methodName, false);
    }
    return wrapper2;
  }
  createMethod(wrapper2, methodName, mandatory) {
    wrapper2.addMethod(methodName, this.createMethodProxy(wrapper2, methodName, mandatory));
  }
  createMethodProxy(wrapper2, methodName, mandatory) {
    return function() {
      if (wrapper2.hasMethod(methodName)) {
        return wrapper2.callMethod(methodName, arguments);
      }
      if (mandatory) {
        _warn(49, { methodName });
      }
      return null;
    };
  }
};
function _isShowTooltipWhenTruncated(gos) {
  return gos.get("tooltipShowMode") === "whenTruncated";
}
function _formatNumberCommas(value2, getLocaleTextFunc) {
  if (typeof value2 !== "number") {
    return "";
  }
  const localeTextFunc = getLocaleTextFunc();
  const thousandSeparator = localeTextFunc("thousandSeparator", ",");
  const decimalSeparator = localeTextFunc("decimalSeparator", ".");
  return value2.toString().replace(".", decimalSeparator).replace(/(\d)(?=(\d{3})+(?!\d))/g, `$1${thousandSeparator}`);
}
var BaseCreator = class extends BeanStub {
  getFileName(fileName) {
    const extension = this.getDefaultFileExtension();
    if (!fileName?.length) {
      fileName = this.getDefaultFileName();
    }
    return fileName.includes(".") ? fileName : `${fileName}.${extension}`;
  }
  getData(params) {
    const serializingSession = this.createSerializingSession(params);
    return this.beans.gridSerializer.serialize(serializingSession, params);
  }
  getDefaultFileName() {
    return `export.${this.getDefaultFileExtension()}`;
  }
};
var BaseGridSerializingSession = class {
  constructor(config2) {
    const {
      colModel,
      rowGroupColsSvc,
      colNames,
      valueSvc,
      gos,
      processCellCallback,
      processHeaderCallback,
      processGroupHeaderCallback,
      processRowGroupCallback
    } = config2;
    this.colModel = colModel;
    this.rowGroupColsSvc = rowGroupColsSvc;
    this.colNames = colNames;
    this.valueSvc = valueSvc;
    this.gos = gos;
    this.processCellCallback = processCellCallback;
    this.processHeaderCallback = processHeaderCallback;
    this.processGroupHeaderCallback = processGroupHeaderCallback;
    this.processRowGroupCallback = processRowGroupCallback;
  }
  prepare(_columnsToExport) {
  }
  extractHeaderValue(column2) {
    const value2 = this.getHeaderName(this.processHeaderCallback, column2);
    return value2 ?? "";
  }
  extractRowCellValue(column2, currentColumnIndex, accumulatedRowIndex, type, node2) {
    const isFullWidthGroup = currentColumnIndex === 0 && _isFullWidthGroupRow(this.gos, node2, this.colModel.isPivotMode());
    if (this.processRowGroupCallback && (this.gos.get("treeData") || node2.group) && (column2.isRowGroupDisplayed(node2.rowGroupColumn?.getColId() ?? "") || isFullWidthGroup)) {
      return { value: this.processRowGroupCallback(_addGridCommonParams(this.gos, { column: column2, node: node2 })) ?? "" };
    }
    if (this.processCellCallback) {
      return {
        value: this.processCellCallback(
          _addGridCommonParams(this.gos, {
            accumulatedRowIndex,
            column: column2,
            node: node2,
            value: this.valueSvc.getValueForDisplay(column2, node2, void 0, void 0).value,
            type,
            parseValue: (valueToParse) => this.valueSvc.parseValue(
              column2,
              node2,
              valueToParse,
              this.valueSvc.getValue(column2, node2, void 0)
            ),
            formatValue: (valueToFormat) => this.valueSvc.formatValue(column2, node2, valueToFormat) ?? valueToFormat
          })
        ) ?? ""
      };
    }
    const isTreeData = this.gos.get("treeData");
    const valueService = this.valueSvc;
    const isGrandTotalRow = node2.level === -1 && node2.footer;
    const isMultiAutoCol = column2.colDef.showRowGroup === true && (node2.group || isTreeData);
    if (!isGrandTotalRow && (isFullWidthGroup || isMultiAutoCol)) {
      let concatenatedGroupValue = "";
      let pointer = node2;
      while (pointer && pointer.level !== -1) {
        const { value: value22, valueFormatted: valueFormatted2 } = valueService.getValueForDisplay(
          isFullWidthGroup ? void 0 : column2,
          // full width group doesn't have a column
          pointer,
          true,
          true
        );
        concatenatedGroupValue = ` -> ${valueFormatted2 ?? value22 ?? ""}${concatenatedGroupValue}`;
        pointer = pointer.parent;
      }
      return {
        value: concatenatedGroupValue,
        // don't return the unformatted value; as if the grid detects number it'll not use the concatenated string
        valueFormatted: concatenatedGroupValue
      };
    }
    const { value: value2, valueFormatted } = valueService.getValueForDisplay(column2, node2, true, true);
    return {
      value: value2 ?? "",
      valueFormatted
    };
  }
  getHeaderName(callback, column2) {
    if (callback) {
      return callback(_addGridCommonParams(this.gos, { column: column2 }));
    }
    return this.colNames.getDisplayNameForColumn(column2, "csv", true);
  }
};
function _downloadFile(fileName, content2) {
  const win = document.defaultView || window;
  if (!win) {
    _warn(52);
    return;
  }
  const element = document.createElement("a");
  const url = win.URL.createObjectURL(content2);
  element.setAttribute("href", url);
  element.setAttribute("download", fileName);
  element.style.display = "none";
  document.body.appendChild(element);
  element.dispatchEvent(
    new MouseEvent("click", {
      bubbles: false,
      cancelable: true,
      view: win
    })
  );
  element.remove();
  win.setTimeout(() => {
    win.URL.revokeObjectURL(url);
  }, 0);
}
var INITIAL_GRID_OPTION_KEYS = {
  enableBrowserTooltips: true,
  tooltipTrigger: true,
  tooltipMouseTrack: true,
  tooltipShowMode: true,
  tooltipInteraction: true,
  defaultColGroupDef: true,
  suppressAutoSize: true,
  skipHeaderOnAutoSize: true,
  autoSizeStrategy: true,
  components: true,
  stopEditingWhenCellsLoseFocus: true,
  undoRedoCellEditing: true,
  undoRedoCellEditingLimit: true,
  excelStyles: true,
  cacheQuickFilter: true,
  customChartThemes: true,
  chartThemeOverrides: true,
  chartToolPanelsDef: true,
  loadingCellRendererSelector: true,
  localeText: true,
  keepDetailRows: true,
  keepDetailRowsCount: true,
  detailRowHeight: true,
  detailRowAutoHeight: true,
  tabIndex: true,
  valueCache: true,
  valueCacheNeverExpires: true,
  enableCellExpressions: true,
  suppressTouch: true,
  suppressBrowserResizeObserver: true,
  suppressPropertyNamesCheck: true,
  debug: true,
  dragAndDropImageComponent: true,
  loadingOverlayComponent: true,
  suppressLoadingOverlay: true,
  noRowsOverlayComponent: true,
  paginationPageSizeSelector: true,
  paginateChildRows: true,
  pivotPanelShow: true,
  pivotSuppressAutoColumn: true,
  suppressExpandablePivotGroups: true,
  aggFuncs: true,
  allowShowChangeAfterFilter: true,
  ensureDomOrder: true,
  enableRtl: true,
  suppressColumnVirtualisation: true,
  suppressMaxRenderedRowRestriction: true,
  suppressRowVirtualisation: true,
  rowDragText: true,
  groupLockGroupColumns: true,
  suppressGroupRowsSticky: true,
  rowModelType: true,
  cacheOverflowSize: true,
  infiniteInitialRowCount: true,
  serverSideInitialRowCount: true,
  maxBlocksInCache: true,
  maxConcurrentDatasourceRequests: true,
  blockLoadDebounceMillis: true,
  serverSideOnlyRefreshFilteredGroups: true,
  serverSidePivotResultFieldSeparator: true,
  viewportRowModelPageSize: true,
  viewportRowModelBufferSize: true,
  debounceVerticalScrollbar: true,
  suppressAnimationFrame: true,
  suppressPreventDefaultOnMouseWheel: true,
  scrollbarWidth: true,
  icons: true,
  suppressRowTransform: true,
  gridId: true,
  enableGroupEdit: true,
  initialState: true,
  processUnpinnedColumns: true,
  createChartContainer: true,
  getLocaleText: true,
  getRowId: true,
  reactiveCustomComponents: true,
  renderingMode: true,
  columnMenu: true,
  suppressSetFilterByDefault: true,
  getDataPath: true,
  enableCellSpan: true,
  enableFilterHandlers: true,
  filterHandlers: true
};
var clientSide = "clientSide";
var serverSide = "serverSide";
var infinite = "infinite";
var functionRowModels = {
  onGroupExpandedOrCollapsed: [clientSide],
  refreshClientSideRowModel: [clientSide],
  isRowDataEmpty: [clientSide],
  forEachLeafNode: [clientSide],
  forEachNodeAfterFilter: [clientSide],
  forEachNodeAfterFilterAndSort: [clientSide],
  resetRowHeights: [clientSide, serverSide],
  applyTransaction: [clientSide],
  applyTransactionAsync: [clientSide],
  flushAsyncTransactions: [clientSide],
  getBestCostNodeSelection: [clientSide],
  getServerSideSelectionState: [serverSide],
  setServerSideSelectionState: [serverSide],
  applyServerSideTransaction: [serverSide],
  applyServerSideTransactionAsync: [serverSide],
  applyServerSideRowData: [serverSide],
  retryServerSideLoads: [serverSide],
  flushServerSideAsyncTransactions: [serverSide],
  refreshServerSide: [serverSide],
  getServerSideGroupLevelState: [serverSide],
  refreshInfiniteCache: [infinite],
  purgeInfiniteCache: [infinite],
  getInfiniteRowCount: [infinite],
  isLastRowIndexKnown: [infinite, serverSide],
  expandAll: [clientSide, serverSide],
  collapseAll: [clientSide, serverSide],
  onRowHeightChanged: [clientSide, serverSide],
  setRowCount: [infinite, serverSide],
  getCacheBlockState: [infinite, serverSide]
};
var deprecatedFunctions = {
  showLoadingOverlay: {
    version: "v32",
    message: '`showLoadingOverlay` is deprecated. Use the grid option "loading"=true instead or setGridOption("loading", true).'
  },
  clearRangeSelection: {
    version: "v32.2",
    message: "Use `clearCellSelection` instead."
  },
  getInfiniteRowCount: {
    version: "v32.2",
    old: "getInfiniteRowCount()",
    new: "getDisplayedRowCount()"
  },
  selectAllFiltered: {
    version: "v33",
    old: "selectAllFiltered()",
    new: 'selectAll("filtered")'
  },
  deselectAllFiltered: {
    version: "v33",
    old: "deselectAllFiltered()",
    new: 'deselectAll("filtered")'
  },
  selectAllOnCurrentPage: {
    version: "v33",
    old: "selectAllOnCurrentPage()",
    new: 'selectAll("currentPage")'
  },
  deselectAllOnCurrentPage: {
    version: "v33",
    old: "deselectAllOnCurrentPage()",
    new: 'deselectAll("currentPage")'
  }
};
function validateApiFunction(functionName2, apiFunction, beans) {
  const deprecation = deprecatedFunctions[functionName2];
  if (deprecation) {
    const { version: version2, new: replacement, old, message: message2 } = deprecation;
    const apiMethod = old ?? functionName2;
    return (...args2) => {
      const replacementMessage = replacement ? `Please use ${replacement} instead. ` : "";
      _warnOnce(`Since ${version2} api.${apiMethod} is deprecated. ${replacementMessage}${message2 ?? ""}`);
      return apiFunction.apply(apiFunction, args2);
    };
  }
  const rowModels = functionRowModels[functionName2];
  if (rowModels) {
    return (...args2) => {
      const rowModel = beans.rowModel.getType();
      if (!rowModels.includes(rowModel)) {
        _errorOnce(
          `api.${functionName2} can only be called when gridOptions.rowModelType is ${rowModels.join(" or ")}`
        );
        return void 0;
      }
      return apiFunction.apply(apiFunction, args2);
    };
  }
  return apiFunction;
}
var DYNAMIC_BEAN_MODULES = {
  detailCellRendererCtrl: "SharedMasterDetail",
  dndSourceComp: "DragAndDrop",
  fillHandle: "CellSelection",
  groupCellRendererCtrl: "GroupCellRenderer",
  headerFilterCellCtrl: "ColumnFilter",
  headerGroupCellCtrl: "ColumnGroup",
  rangeHandle: "CellSelection",
  tooltipFeature: "Tooltip",
  highlightTooltipFeature: "Tooltip",
  tooltipStateManager: "Tooltip",
  groupStrategy: "RowGrouping",
  treeGroupStrategy: "TreeData",
  rowNumberRowResizer: "RowNumbers",
  singleCell: "EditCore",
  fullRow: "EditCore",
  agSetColumnFilterHandler: "SetFilter",
  agMultiColumnFilterHandler: "MultiFilter",
  agGroupColumnFilterHandler: "GroupFilter",
  agNumberColumnFilterHandler: "NumberFilter",
  agDateColumnFilterHandler: "DateFilter",
  agTextColumnFilterHandler: "TextFilter"
};
var ICON_VALUES = {
  expanded: 1,
  contracted: 1,
  "tree-closed": 1,
  "tree-open": 1,
  "tree-indeterminate": 1,
  pin: 1,
  "eye-slash": 1,
  arrows: 1,
  left: 1,
  right: 1,
  group: 1,
  aggregation: 1,
  pivot: 1,
  "not-allowed": 1,
  chart: 1,
  cross: 1,
  cancel: 1,
  tick: 1,
  first: 1,
  previous: 1,
  next: 1,
  last: 1,
  linked: 1,
  unlinked: 1,
  "color-picker": 1,
  loading: 1,
  menu: 1,
  "menu-alt": 1,
  filter: 1,
  "filter-add": 1,
  columns: 1,
  maximize: 1,
  minimize: 1,
  copy: 1,
  cut: 1,
  paste: 1,
  grip: 1,
  save: 1,
  csv: 1,
  excel: 1,
  "small-down": 1,
  "small-left": 1,
  "small-right": 1,
  "small-up": 1,
  asc: 1,
  desc: 1,
  none: 1,
  up: 1,
  down: 1,
  plus: 1,
  minus: 1,
  settings: 1,
  "checkbox-checked": 1,
  "checkbox-indeterminate": 1,
  "checkbox-unchecked": 1,
  "radio-button-on": 1,
  "radio-button-off": 1,
  eye: 1,
  "column-arrow": 1,
  "un-pin": 1,
  "pinned-top": 1,
  "pinned-bottom": 1,
  "chevron-up": 1,
  "chevron-down": 1,
  "chevron-left": 1,
  "chevron-right": 1,
  edit: 1
};
var ICON_MODULES = {
  chart: "MenuCore",
  cancel: "EnterpriseCore",
  first: "Pagination",
  previous: "Pagination",
  next: "Pagination",
  last: "Pagination",
  linked: "IntegratedCharts",
  loadingMenuItems: "MenuCore",
  unlinked: "IntegratedCharts",
  menu: "ColumnHeaderComp",
  legacyMenu: "ColumnMenu",
  filter: "ColumnFilter",
  filterActive: "ColumnFilter",
  filterAdd: "NewFiltersToolPanel",
  filterCardCollapse: "NewFiltersToolPanel",
  filterCardExpand: "NewFiltersToolPanel",
  filterCardEditing: "NewFiltersToolPanel",
  filterTab: "ColumnMenu",
  filtersToolPanel: "FiltersToolPanel",
  columns: ["MenuCore"],
  columnsToolPanel: ["ColumnsToolPanel"],
  maximize: "EnterpriseCore",
  minimize: "EnterpriseCore",
  save: "MenuCore",
  columnGroupOpened: "ColumnGroupHeaderComp",
  columnGroupClosed: "ColumnGroupHeaderComp",
  accordionOpen: "EnterpriseCore",
  accordionClosed: "EnterpriseCore",
  accordionIndeterminate: "EnterpriseCore",
  columnSelectClosed: ["ColumnsToolPanel", "ColumnMenu"],
  columnSelectOpen: ["ColumnsToolPanel", "ColumnMenu"],
  columnSelectIndeterminate: ["ColumnsToolPanel", "ColumnMenu"],
  columnMovePin: "SharedDragAndDrop",
  columnMoveHide: "SharedDragAndDrop",
  columnMoveMove: "SharedDragAndDrop",
  columnMoveLeft: "SharedDragAndDrop",
  columnMoveRight: "SharedDragAndDrop",
  columnMoveGroup: "SharedDragAndDrop",
  columnMoveValue: "SharedDragAndDrop",
  columnMovePivot: "SharedDragAndDrop",
  dropNotAllowed: "SharedDragAndDrop",
  ensureColumnVisible: ["ColumnsToolPanel", "ColumnMenu"],
  groupContracted: "GroupCellRenderer",
  groupExpanded: "GroupCellRenderer",
  setFilterGroupClosed: "SetFilter",
  setFilterGroupOpen: "SetFilter",
  setFilterGroupIndeterminate: "SetFilter",
  setFilterLoading: "SetFilter",
  close: "EnterpriseCore",
  check: "MenuItem",
  colorPicker: "CommunityCore",
  groupLoading: "LoadingCellRenderer",
  menuAlt: "ColumnHeaderComp",
  menuPin: "MenuCore",
  menuValue: "MenuCore",
  menuAddRowGroup: ["MenuCore", "ColumnsToolPanel"],
  menuRemoveRowGroup: ["MenuCore", "ColumnsToolPanel"],
  clipboardCopy: "MenuCore",
  clipboardCut: "MenuCore",
  clipboardPaste: "MenuCore",
  pivotPanel: ["ColumnsToolPanel", "RowGroupingPanel"],
  rowGroupPanel: ["ColumnsToolPanel", "RowGroupingPanel"],
  valuePanel: "ColumnsToolPanel",
  columnDrag: "EnterpriseCore",
  rowDrag: ["RowDrag", "DragAndDrop"],
  csvExport: "MenuCore",
  excelExport: "MenuCore",
  smallDown: "CommunityCore",
  selectOpen: "CommunityCore",
  richSelectOpen: "RichSelect",
  richSelectRemove: "RichSelect",
  smallLeft: "CommunityCore",
  smallRight: "CommunityCore",
  subMenuOpen: "MenuItem",
  subMenuOpenRtl: "MenuItem",
  panelDelimiter: "RowGroupingPanel",
  panelDelimiterRtl: "RowGroupingPanel",
  smallUp: "CommunityCore",
  sortAscending: ["MenuCore", "Sort"],
  sortDescending: ["MenuCore", "Sort"],
  sortUnSort: ["MenuCore", "Sort"],
  advancedFilterBuilder: "AdvancedFilter",
  advancedFilterBuilderDrag: "AdvancedFilter",
  advancedFilterBuilderInvalid: "AdvancedFilter",
  advancedFilterBuilderMoveUp: "AdvancedFilter",
  advancedFilterBuilderMoveDown: "AdvancedFilter",
  advancedFilterBuilderAdd: "AdvancedFilter",
  advancedFilterBuilderRemove: "AdvancedFilter",
  advancedFilterBuilderSelectOpen: "AdvancedFilter",
  chartsMenu: "IntegratedCharts",
  chartsMenuEdit: "IntegratedCharts",
  chartsMenuAdvancedSettings: "IntegratedCharts",
  chartsMenuAdd: "IntegratedCharts",
  chartsColorPicker: "IntegratedCharts",
  chartsThemePrevious: "IntegratedCharts",
  chartsThemeNext: "IntegratedCharts",
  chartsDownload: "IntegratedCharts",
  checkboxChecked: "CommunityCore",
  checkboxIndeterminate: "CommunityCore",
  checkboxUnchecked: "CommunityCore",
  radioButtonOn: "CommunityCore",
  radioButtonOff: "CommunityCore",
  rowPin: "PinnedRow",
  rowUnpin: "PinnedRow",
  rowPinBottom: "PinnedRow",
  rowPinTop: "PinnedRow"
};
var DEPRECATED_ICONS_V33 = /* @__PURE__ */ new Set([
  "colorPicker",
  "smallUp",
  "checkboxChecked",
  "checkboxIndeterminate",
  "checkboxUnchecked",
  "radioButtonOn",
  "radioButtonOff",
  "smallDown",
  "smallLeft",
  "smallRight"
]);
var ValidationService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "validation";
  }
  wireBeans(beans) {
    this.gridOptions = beans.gridOptions;
    provideValidationServiceLogger(getError);
  }
  warnOnInitialPropertyUpdate(source2, key2) {
    if (source2 === "api" && INITIAL_GRID_OPTION_KEYS[key2]) {
      _warn(22, { key: key2 });
    }
  }
  processGridOptions(options) {
    this.processOptions(options, GRID_OPTIONS_VALIDATORS());
  }
  validateApiFunction(functionName2, apiFunction) {
    return validateApiFunction(functionName2, apiFunction, this.beans);
  }
  missingUserComponent(propertyName, componentName, agGridDefaults, jsComps) {
    const moduleForComponent = USER_COMP_MODULES[componentName];
    if (moduleForComponent) {
      this.gos.assertModuleRegistered(
        moduleForComponent,
        `AG Grid '${propertyName}' component: ${componentName}`
      );
    } else {
      _warn(101, {
        propertyName,
        componentName,
        agGridDefaults,
        jsComps
      });
    }
  }
  missingDynamicBean(beanName) {
    const moduleName = DYNAMIC_BEAN_MODULES[beanName];
    return moduleName ? _errMsg(200, {
      ...this.gos.getModuleErrorParams(),
      moduleName,
      reasonOrId: beanName
    }) : void 0;
  }
  checkRowEvents(eventType) {
    if (DEPRECATED_ROW_NODE_EVENTS.has(eventType)) {
      _warn(10, { eventType });
    }
  }
  validateIcon(iconName) {
    if (DEPRECATED_ICONS_V33.has(iconName)) {
      _warn(43, { iconName });
    }
    if (ICON_VALUES[iconName]) {
      return;
    }
    const moduleName = ICON_MODULES[iconName];
    if (moduleName) {
      _error(200, {
        reasonOrId: `icon '${iconName}'`,
        moduleName,
        gridScoped: _areModulesGridScoped(),
        gridId: this.beans.context.getId(),
        rowModelType: this.gos.get("rowModelType"),
        additionalText: "Alternatively, use the CSS icon name directly."
      });
      return;
    }
    _warn(134, { iconName });
  }
  isProvidedUserComp(compName) {
    return !!USER_COMP_MODULES[compName];
  }
  /** Should only be called via the GridOptionsService */
  validateColDef(colDef) {
    this.processOptions(colDef, COL_DEF_VALIDATORS());
  }
  processOptions(options, validator) {
    const { validations, deprecations, allProperties, propertyExceptions, objectName, docsUrl } = validator;
    if (allProperties && this.gridOptions.suppressPropertyNamesCheck !== true) {
      this.checkProperties(
        options,
        [...propertyExceptions ?? [], ...Object.keys(deprecations)],
        allProperties,
        objectName,
        docsUrl
      );
    }
    const warnings = /* @__PURE__ */ new Set();
    const optionKeys = Object.keys(options);
    optionKeys.forEach((key2) => {
      const deprecation = deprecations[key2];
      if (deprecation) {
        const { message: message2, version: version2 } = deprecation;
        warnings.add(`As of v${version2}, ${String(key2)} is deprecated. ${message2 ?? ""}`);
      }
      const value2 = options[key2];
      if (value2 == null || value2 === false) {
        return;
      }
      const rules = validations[key2];
      if (!rules) {
        return;
      }
      const { dependencies, validate, supportedRowModels, expectedType } = rules;
      if (expectedType) {
        const actualType = typeof value2;
        if (actualType !== expectedType) {
          warnings.add(
            `${String(key2)} should be of type '${expectedType}' but received '${actualType}' (${value2}).`
          );
          return;
        }
      }
      if (supportedRowModels) {
        const rowModel = this.gridOptions.rowModelType ?? "clientSide";
        if (!supportedRowModels.includes(rowModel)) {
          warnings.add(
            `${String(key2)} is not supported with the '${rowModel}' row model. It is only valid with: ${supportedRowModels.join(", ")}.`
          );
          return;
        }
      }
      if (dependencies) {
        const warning2 = this.checkForRequiredDependencies(key2, dependencies, options);
        if (warning2) {
          warnings.add(warning2);
          return;
        }
      }
      if (validate) {
        const warning2 = validate(options, this.gridOptions, this.beans);
        if (warning2) {
          warnings.add(warning2);
          return;
        }
      }
    });
    if (warnings.size > 0) {
      for (const warning2 of warnings) {
        _warnOnce(warning2);
      }
    }
  }
  checkForRequiredDependencies(key2, validator, options) {
    const optionEntries = Object.entries(validator);
    const failedOptions = optionEntries.filter(([key22, value2]) => {
      const gridOptionValue = options[key22];
      return !value2.required.includes(gridOptionValue);
    });
    if (failedOptions.length === 0) {
      return null;
    }
    return failedOptions.map(
      ([failedKey, possibleOptions]) => `'${String(key2)}' requires '${failedKey}' to be one of [${possibleOptions.required.map((o) => {
        if (o === null) {
          return "null";
        } else if (o === void 0) {
          return "undefined";
        }
        return o;
      }).join(", ")}]. ${possibleOptions.reason ?? ""}`
    ).join("\n           ");
  }
  checkProperties(object2, exceptions, validProperties, containerName, docsUrl) {
    const VUE_FRAMEWORK_PROPS = ["__ob__", "__v_skip", "__metadata__"];
    const invalidProperties = _fuzzyCheckStrings(
      Object.getOwnPropertyNames(object2),
      [...VUE_FRAMEWORK_PROPS, ...exceptions, ...validProperties],
      validProperties
    );
    const invalidPropertiesKeys = Object.keys(invalidProperties);
    for (const key2 of invalidPropertiesKeys) {
      const value2 = invalidProperties[key2];
      let message2 = `invalid ${containerName} property '${key2}' did you mean any of these: ${value2.slice(0, 8).join(", ")}.`;
      if (validProperties.includes("context")) {
        message2 += `
If you are trying to annotate ${containerName} with application data, use the '${containerName}.context' property instead.`;
      }
      _warnOnce(message2);
    }
    if (invalidPropertiesKeys.length > 0 && docsUrl) {
      const url = this.beans.frameworkOverrides.getDocLink(docsUrl);
      _warnOnce(`to see all the valid ${containerName} properties please check: ${url}`);
    }
  }
};
function _fuzzyCheckStrings(inputValues, validValues, allSuggestions) {
  const fuzzyMatches = {};
  const invalidInputs = inputValues.filter(
    (inputValue) => !validValues.some((validValue) => validValue === inputValue)
  );
  if (invalidInputs.length > 0) {
    for (const invalidInput of invalidInputs) {
      fuzzyMatches[invalidInput] = _fuzzySuggestions({ inputValue: invalidInput, allSuggestions }).values;
    }
  }
  return fuzzyMatches;
}
var DEPRECATED_ROW_NODE_EVENTS = /* @__PURE__ */ new Set([
  "firstChildChanged",
  "lastChildChanged",
  "childIndexChanged"
]);
var ValidationModule = {
  moduleName: "Validation",
  version: VERSION,
  beans: [ValidationService]
};
function updateRowNodeAfterFilter(rowNode) {
  const sibling2 = rowNode.sibling;
  if (sibling2) {
    sibling2.childrenAfterFilter = rowNode.childrenAfterFilter;
  }
}
var FilterStage = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "filterStage";
    this.step = "filter";
    this.refreshProps = ["excludeChildrenWhenTreeDataFiltering"];
  }
  wireBeans(beans) {
    this.filterManager = beans.filterManager;
  }
  execute(params) {
    const { changedPath } = params;
    this.filter(changedPath);
  }
  filter(changedPath) {
    const filterActive = !!this.filterManager?.isChildFilterPresent();
    this.filterNodes(filterActive, changedPath);
  }
  filterNodes(filterActive, changedPath) {
    const filterCallback = (rowNode, includeChildNodes) => {
      if (rowNode.hasChildren()) {
        if (filterActive && !includeChildNodes) {
          rowNode.childrenAfterFilter = rowNode.childrenAfterGroup.filter((childNode) => {
            const passBecauseChildren = childNode.childrenAfterFilter && childNode.childrenAfterFilter.length > 0;
            const passBecauseDataPasses = childNode.data && this.filterManager.doesRowPassFilter({ rowNode: childNode });
            return passBecauseChildren || passBecauseDataPasses;
          });
        } else {
          rowNode.childrenAfterFilter = rowNode.childrenAfterGroup;
        }
      } else {
        rowNode.childrenAfterFilter = rowNode.childrenAfterGroup;
      }
      updateRowNodeAfterFilter(rowNode);
    };
    if (this.doingTreeDataFiltering()) {
      const treeDataDepthFirstFilter = (rowNode, alreadyFoundInParent) => {
        if (rowNode.childrenAfterGroup) {
          for (let i2 = 0; i2 < rowNode.childrenAfterGroup.length; i2++) {
            const childNode = rowNode.childrenAfterGroup[i2];
            const foundInParent = alreadyFoundInParent || this.filterManager.doesRowPassFilter({ rowNode: childNode });
            if (childNode.childrenAfterGroup) {
              treeDataDepthFirstFilter(rowNode.childrenAfterGroup[i2], foundInParent);
            } else {
              filterCallback(childNode, foundInParent);
            }
          }
        }
        filterCallback(rowNode, alreadyFoundInParent);
      };
      const treeDataFilterCallback = (rowNode) => treeDataDepthFirstFilter(rowNode, false);
      changedPath.executeFromRootNode(treeDataFilterCallback);
    } else {
      const defaultFilterCallback = (rowNode) => filterCallback(rowNode, false);
      changedPath.forEachChangedNodeDepthFirst(defaultFilterCallback, true);
    }
  }
  doingTreeDataFiltering() {
    return this.gos.get("treeData") && !this.gos.get("excludeChildrenWhenTreeDataFiltering");
  }
};
var HeaderFilterCellCtrl = class extends AbstractHeaderCellCtrl {
  constructor() {
    super(...arguments);
    this.iconCreated = false;
  }
  wireComp(comp, eGui, eButtonShowMainFilter, eFloatingFilterBody, compBeanInput) {
    this.comp = comp;
    const compBean = setupCompBean(this, this.beans.context, compBeanInput);
    this.eButtonShowMainFilter = eButtonShowMainFilter;
    this.eFloatingFilterBody = eFloatingFilterBody;
    this.setGui(eGui, compBean);
    this.setupActive();
    this.refreshHeaderStyles();
    this.setupWidth(compBean);
    this.setupLeft(compBean);
    this.setupHover(compBean);
    this.setupFocus(compBean);
    this.setupAria();
    this.setupFilterButton();
    this.setupUserComp();
    this.setupSyncWithFilter(compBean);
    this.setupUi();
    compBean.addManagedElementListeners(this.eButtonShowMainFilter, { click: this.showParentFilter.bind(this) });
    this.setupFilterChangedListener(compBean);
    const colDefChanged = () => this.onColDefChanged(compBean);
    compBean.addManagedListeners(this.column, { colDefChanged });
    compBean.addManagedEventListeners({
      filterSwitched: ({ column: column2 }) => {
        if (column2 === this.column) {
          colDefChanged();
        }
      }
    });
    compBean.addDestroyFunc(() => {
      this.eButtonShowMainFilter = null;
      this.eFloatingFilterBody = null;
      this.userCompDetails = null;
      this.clearComponent();
    });
  }
  // empty abstract method
  resizeHeader() {
  }
  moveHeader() {
  }
  getHeaderClassParams() {
    const { column: column2, beans } = this;
    const colDef = column2.colDef;
    return _addGridCommonParams(beans.gos, {
      colDef,
      column: column2,
      floatingFilter: true
    });
  }
  setupActive() {
    const colDef = this.column.getColDef();
    const filterExists = !!colDef.filter;
    const floatingFilterExists = !!colDef.floatingFilter;
    this.active = filterExists && floatingFilterExists;
  }
  setupUi() {
    this.comp.setButtonWrapperDisplayed(!this.suppressFilterButton && this.active);
    this.comp.addOrRemoveBodyCssClass("ag-floating-filter-full-body", this.suppressFilterButton);
    this.comp.addOrRemoveBodyCssClass("ag-floating-filter-body", !this.suppressFilterButton);
    if (!this.active || this.iconCreated) {
      return;
    }
    const eMenuIcon = _createIconNoSpan("filter", this.beans, this.column);
    if (eMenuIcon) {
      this.iconCreated = true;
      this.eButtonShowMainFilter.appendChild(eMenuIcon);
    }
  }
  setupFocus(compBean) {
    compBean.createManagedBean(
      new ManagedFocusFeature(this.eGui, {
        shouldStopEventPropagation: this.shouldStopEventPropagation.bind(this),
        onTabKeyDown: this.onTabKeyDown.bind(this),
        handleKeyDown: this.handleKeyDown.bind(this),
        onFocusIn: this.onFocusIn.bind(this)
      })
    );
  }
  setupAria() {
    const localeTextFunc = this.getLocaleTextFunc();
    _setAriaLabel(this.eButtonShowMainFilter, localeTextFunc("ariaFilterMenuOpen", "Open Filter Menu"));
  }
  onTabKeyDown(e) {
    const { beans } = this;
    const activeEl = _getActiveDomElement(beans);
    const wrapperHasFocus = activeEl === this.eGui;
    if (wrapperHasFocus) {
      return;
    }
    const nextFocusableEl = _findNextFocusableElement(beans, this.eGui, null, e.shiftKey);
    if (nextFocusableEl) {
      beans.headerNavigation?.scrollToColumn(this.column);
      e.preventDefault();
      nextFocusableEl.focus();
      return;
    }
    const nextFocusableColumn = this.findNextColumnWithFloatingFilter(e.shiftKey);
    if (!nextFocusableColumn) {
      return;
    }
    if (beans.focusSvc.focusHeaderPosition({
      headerPosition: {
        headerRowIndex: this.rowCtrl.rowIndex,
        column: nextFocusableColumn
      },
      event: e
    })) {
      e.preventDefault();
    }
  }
  findNextColumnWithFloatingFilter(backwards) {
    const presentedColsService = this.beans.visibleCols;
    let nextCol = this.column;
    do {
      nextCol = backwards ? presentedColsService.getColBefore(nextCol) : presentedColsService.getColAfter(nextCol);
      if (!nextCol) {
        break;
      }
    } while (!nextCol.getColDef().filter || !nextCol.getColDef().floatingFilter);
    return nextCol;
  }
  handleKeyDown(e) {
    super.handleKeyDown(e);
    const wrapperHasFocus = this.getWrapperHasFocus();
    switch (e.key) {
      case KeyCode.UP:
      case KeyCode.DOWN:
      case KeyCode.LEFT:
      case KeyCode.RIGHT:
        if (wrapperHasFocus) {
          return;
        }
        _stopPropagationForAgGrid(e);
      case KeyCode.ENTER:
        if (wrapperHasFocus) {
          if (_focusInto(this.eGui)) {
            e.preventDefault();
          }
        }
        break;
      case KeyCode.ESCAPE:
        if (!wrapperHasFocus) {
          this.eGui.focus();
        }
    }
  }
  onFocusIn(e) {
    const isRelatedWithin = this.eGui.contains(e.relatedTarget);
    if (isRelatedWithin) {
      return;
    }
    const notFromHeaderWrapper = !!e.relatedTarget && !e.relatedTarget.classList.contains("ag-floating-filter");
    const fromWithinHeader = !!e.relatedTarget && _isElementChildOfClass(e.relatedTarget, "ag-floating-filter");
    if (notFromHeaderWrapper && fromWithinHeader && e.target === this.eGui) {
      const lastFocusEvent = this.lastFocusEvent;
      const fromTab = !!(lastFocusEvent && lastFocusEvent.key === KeyCode.TAB);
      if (lastFocusEvent && fromTab) {
        const shouldFocusLast = lastFocusEvent.shiftKey;
        _focusInto(this.eGui, shouldFocusLast);
      }
    }
    this.focusThis();
  }
  setupHover(compBean) {
    this.beans.colHover?.addHeaderFilterColumnHoverListener(compBean, this.comp, this.column, this.eGui);
  }
  setupLeft(compBean) {
    const setLeftFeature = new SetLeftFeature(this.column, this.eGui, this.beans);
    compBean.createManagedBean(setLeftFeature);
  }
  setupFilterButton() {
    this.suppressFilterButton = !this.beans.menuSvc?.isFloatingFilterButtonEnabled(this.column);
    this.highlightFilterButtonWhenActive = !_isLegacyMenuEnabled(this.gos);
  }
  setupUserComp() {
    if (!this.active) {
      return;
    }
    const compDetails = this.beans.colFilter?.getFloatingFilterCompDetails(
      this.column,
      () => this.showParentFilter()
    );
    if (compDetails) {
      this.setCompDetails(compDetails);
    }
  }
  setCompDetails(compDetails) {
    this.userCompDetails = compDetails;
    this.comp.setCompDetails(compDetails);
  }
  showParentFilter() {
    const eventSource = this.suppressFilterButton ? this.eFloatingFilterBody : this.eButtonShowMainFilter;
    this.beans.menuSvc?.showFilterMenu({
      column: this.column,
      buttonElement: eventSource,
      containerType: "floatingFilter",
      positionBy: "button"
    });
  }
  setupSyncWithFilter(compBean) {
    if (!this.active) {
      return;
    }
    const {
      beans: { colFilter },
      column: column2,
      gos
    } = this;
    const syncWithFilter = (event) => {
      if (event?.source === "filterDestroyed" && (!this.isAlive() || !colFilter?.isAlive())) {
        return;
      }
      const compPromise = this.comp.getFloatingFilterComp();
      if (!compPromise) {
        return;
      }
      compPromise.then((comp) => {
        if (comp) {
          if (gos.get("enableFilterHandlers")) {
            const eventWithParams = event;
            let source2 = "filter";
            if (eventWithParams?.afterFloatingFilter) {
              source2 = "ui";
            } else if (eventWithParams?.afterDataChange) {
              source2 = "dataChanged";
            } else if (event?.source === "api") {
              source2 = "api";
            }
            this.updateFloatingFilterParams(this.userCompDetails, source2);
            return;
          }
          const parentModel = colFilter?.getCurrentFloatingFilterParentModel(column2);
          const filterChangedEvent = event ? {
            // event can have additional params like `afterDataChange` which need to be passed through
            ...event,
            columns: event.columns ?? [],
            source: event.source === "api" ? "api" : "columnFilter"
          } : null;
          comp.onParentModelChanged(parentModel, filterChangedEvent);
        }
      });
    };
    [this.destroySyncListener] = compBean.addManagedListeners(column2, { filterChanged: syncWithFilter });
    if (colFilter?.isFilterActive(column2)) {
      syncWithFilter(null);
    }
  }
  setupWidth(compBean) {
    const listener = () => {
      const width = `${this.column.getActualWidth()}px`;
      this.comp.setWidth(width);
    };
    compBean.addManagedListeners(this.column, { widthChanged: listener });
    listener();
  }
  setupFilterChangedListener(compBean) {
    if (this.active) {
      [this.destroyFilterChangedListener] = compBean.addManagedListeners(this.column, {
        filterChanged: this.updateFilterButton.bind(this)
      });
      this.updateFilterButton();
    }
  }
  updateFilterButton() {
    if (!this.suppressFilterButton && this.comp) {
      const isFilterAllowed = !!this.beans.filterManager?.isFilterAllowed(this.column);
      this.comp.setButtonWrapperDisplayed(isFilterAllowed);
      if (this.highlightFilterButtonWhenActive && isFilterAllowed) {
        this.eButtonShowMainFilter.classList.toggle("ag-filter-active", this.column.isFilterActive());
      }
    }
  }
  onColDefChanged(compBean) {
    const wasActive = this.active;
    this.setupActive();
    const becomeActive = !wasActive && this.active;
    if (wasActive && !this.active) {
      this.destroySyncListener();
      this.destroyFilterChangedListener();
    }
    const colFilter = this.beans.colFilter;
    const newCompDetails = this.active ? colFilter?.getFloatingFilterCompDetails(this.column, () => this.showParentFilter()) : null;
    const compPromise = this.comp.getFloatingFilterComp();
    if (!compPromise || !newCompDetails) {
      this.updateCompDetails(compBean, newCompDetails, becomeActive);
    } else {
      compPromise.then((compInstance) => {
        if (!compInstance || colFilter?.areFilterCompsDifferent(this.userCompDetails ?? null, newCompDetails)) {
          this.updateCompDetails(compBean, newCompDetails, becomeActive);
        } else {
          this.updateFloatingFilterParams(newCompDetails, "colDef");
        }
      });
    }
  }
  updateCompDetails(compBean, compDetails, becomeActive) {
    if (!this.isAlive()) {
      return;
    }
    this.setCompDetails(compDetails);
    this.setupFilterButton();
    this.setupUi();
    if (becomeActive) {
      this.setupSyncWithFilter(compBean);
      this.setupFilterChangedListener(compBean);
    }
  }
  updateFloatingFilterParams(userCompDetails, source2) {
    if (!userCompDetails) {
      return;
    }
    let params = userCompDetails.params;
    this.comp.getFloatingFilterComp()?.then((floatingFilter) => {
      if (typeof floatingFilter?.refresh === "function") {
        if (this.gos.get("enableFilterHandlers")) {
          params = {
            ...params,
            model: _getFilterModel(this.beans.colFilter?.model ?? {}, this.column.getColId()),
            source: source2
          };
        }
        floatingFilter.refresh(params);
      }
    });
  }
  addResizeAndMoveKeyboardListeners() {
  }
  destroy() {
    super.destroy();
    this.destroySyncListener = null;
    this.destroyFilterChangedListener = null;
  }
};
function showColumnMenu(beans, colKey) {
  const column2 = beans.colModel.getCol(colKey);
  if (!column2) {
    _error(12, { colKey });
    return;
  }
  beans.menuSvc?.showColumnMenu({
    column: column2,
    positionBy: "auto"
  });
}
function hidePopupMenu(beans) {
  beans.menuSvc?.hidePopupMenu();
}
var SharedMenuModule = {
  moduleName: "SharedMenu",
  version: VERSION,
  beans: [MenuService],
  apiFunctions: {
    showColumnMenu,
    hidePopupMenu
  }
};
var PopupService = class extends BasePopupService {
  postConstruct() {
    this.beans.ctrlsSvc.whenReady(this, (p) => {
      this.gridCtrl = p.gridCtrl;
    });
    this.addManagedEventListeners({ gridStylesChanged: this.handleThemeChange.bind(this) });
  }
  getDefaultPopupParent() {
    return this.gridCtrl.getGui();
  }
  positionPopupForMenu(params) {
    const { eventSource, ePopup, event } = params;
    const sourceRect = eventSource.getBoundingClientRect();
    const parentRect = this.getParentRect();
    this.setAlignedTo(eventSource, ePopup);
    let minWidthSet = false;
    const updatePosition = () => {
      const y = this.keepXYWithinBounds(
        ePopup,
        sourceRect.top - parentRect.top,
        0
        /* Vertical */
      );
      const minWidth = ePopup.clientWidth > 0 ? ePopup.clientWidth : 200;
      if (!minWidthSet) {
        ePopup.style.minWidth = `${minWidth}px`;
        minWidthSet = true;
      }
      const widthOfParent = parentRect.right - parentRect.left;
      const maxX = widthOfParent - minWidth;
      let x;
      if (this.gos.get("enableRtl")) {
        x = xLeftPosition();
        if (x < 0) {
          x = xRightPosition();
          this.setAlignedStyles(ePopup, "left");
        }
        if (x > maxX) {
          x = 0;
          this.setAlignedStyles(ePopup, "right");
        }
      } else {
        x = xRightPosition();
        if (x > maxX) {
          x = xLeftPosition();
          this.setAlignedStyles(ePopup, "right");
        }
        if (x < 0) {
          x = 0;
          this.setAlignedStyles(ePopup, "left");
        }
      }
      return { x, y };
      function xRightPosition() {
        return sourceRect.right - parentRect.left - 2;
      }
      function xLeftPosition() {
        return sourceRect.left - parentRect.left - minWidth;
      }
    };
    this.positionPopup({
      ePopup,
      keepWithinBounds: true,
      updatePosition,
      postProcessCallback: () => this.callPostProcessPopup(
        params,
        "subMenu",
        ePopup,
        eventSource,
        event instanceof MouseEvent ? event : void 0
      )
    });
  }
  callPostProcessPopup(params, type, ePopup, eventSource, mouseEvent) {
    const callback = this.gos.getCallback("postProcessPopup");
    if (callback) {
      const { column: column2, rowNode } = params;
      const postProcessParams = {
        column: column2,
        rowNode,
        ePopup,
        type,
        eventSource,
        mouseEvent
      };
      callback(postProcessParams);
    }
  }
  getActivePopups() {
    return this.popupList.map((popup) => popup.element);
  }
  handleThemeChange(e) {
    if (e.themeChanged) {
      const environment = this.beans.environment;
      for (const popup of this.popupList) {
        environment.applyThemeClasses(popup.wrapper);
      }
    }
  }
  hasAnchoredPopup() {
    return this.popupList.some((popup) => popup.isAnchored);
  }
  isStopPropagation(event) {
    return _isStopPropagationForAgGrid(event);
  }
};
var PopupModule = {
  moduleName: "Popup",
  version: VERSION,
  beans: [PopupService]
};
var columnFiltersCSS = (
  /*css*/
  `.ag-set-filter{--ag-indentation-level:0}.ag-set-filter-item{align-items:center;display:flex;height:100%}:where(.ag-ltr) .ag-set-filter-item{padding-left:calc(var(--ag-widget-container-horizontal-padding) + var(--ag-indentation-level)*var(--ag-set-filter-indent-size))}:where(.ag-rtl) .ag-set-filter-item{padding-right:calc(var(--ag-widget-container-horizontal-padding) + var(--ag-indentation-level)*var(--ag-set-filter-indent-size))}.ag-set-filter-item-checkbox{display:flex;height:100%;width:100%}.ag-set-filter-group-icons{display:block;>*{cursor:pointer}}:where(.ag-ltr) .ag-set-filter-group-icons{margin-right:var(--ag-widget-container-horizontal-padding)}:where(.ag-rtl) .ag-set-filter-group-icons{margin-left:var(--ag-widget-container-horizontal-padding)}.ag-filter-body-wrapper{display:flex;flex-direction:column}:where(.ag-menu:not(.ag-tabs) .ag-filter) .ag-filter-body-wrapper,:where(.ag-menu:not(.ag-tabs) .ag-filter)>:not(.ag-filter-wrapper){min-width:180px}.ag-filter-filter{flex:1 1 0px}.ag-filter-condition{display:flex;justify-content:center}.ag-floating-filter-body{display:flex;flex:1 1 auto;height:100%;position:relative}.ag-floating-filter-full-body{align-items:center;display:flex;flex:1 1 auto;height:100%;overflow:hidden;width:100%}:where(.ag-floating-filter-full-body)>div{flex:1 1 auto}.ag-floating-filter-input{align-items:center;display:flex;width:100%;>*{flex:1 1 auto}:where(.ag-input-field-input[type=date]),:where(.ag-input-field-input[type=datetime-local]){width:1px}}.ag-floating-filter-button{display:flex;flex:none}.ag-date-floating-filter-wrapper{display:flex}.ag-set-floating-filter-input :where(input)[disabled]{pointer-events:none}.ag-floating-filter-button-button{-webkit-appearance:none;-moz-appearance:none;appearance:none;border:none;height:var(--ag-icon-size);width:var(--ag-icon-size)}.ag-filter-loading{align-items:unset;background-color:var(--ag-chrome-background-color);height:100%;padding:var(--ag-widget-container-vertical-padding) var(--ag-widget-container-horizontal-padding);position:absolute;width:100%;z-index:1;:where(.ag-menu) &{background-color:var(--ag-menu-background-color)}}.ag-filter-separator{border-top:solid var(--ag-border-width) var(--menu-separator-color)}:where(.ag-filter-select) .ag-picker-field-wrapper{width:0}.ag-filter-condition-operator{height:17px}:where(.ag-ltr) .ag-filter-condition-operator-or{margin-left:calc(var(--ag-spacing)*2)}:where(.ag-rtl) .ag-filter-condition-operator-or{margin-right:calc(var(--ag-spacing)*2)}.ag-set-filter-select-all{padding-top:var(--ag-widget-container-vertical-padding)}.ag-filter-no-matches,.ag-set-filter-list{height:calc(var(--ag-list-item-height)*6)}.ag-filter-no-matches{padding:var(--ag-widget-container-vertical-padding) var(--ag-widget-container-horizontal-padding)}.ag-set-filter-tree-list{height:calc(var(--ag-list-item-height)*10)}.ag-set-filter-filter{margin-left:var(--ag-widget-container-horizontal-padding);margin-right:var(--ag-widget-container-horizontal-padding);margin-top:var(--ag-widget-container-vertical-padding)}.ag-filter-to{margin-top:var(--ag-widget-vertical-spacing)}.ag-mini-filter{margin:var(--ag-widget-container-vertical-padding) var(--ag-widget-container-horizontal-padding)}:where(.ag-ltr) .ag-set-filter-add-group-indent{margin-left:calc(var(--ag-icon-size) + var(--ag-widget-container-horizontal-padding))}:where(.ag-rtl) .ag-set-filter-add-group-indent{margin-right:calc(var(--ag-icon-size) + var(--ag-widget-container-horizontal-padding))}:where(.ag-filter-menu) .ag-set-filter-list{min-width:200px}.ag-filter-virtual-list-item:focus-visible{box-shadow:inset var(--ag-focus-shadow)}.ag-filter-apply-panel{display:flex;justify-content:flex-end;overflow:hidden;padding:var(--ag-widget-vertical-spacing) var(--ag-widget-container-horizontal-padding) var(--ag-widget-container-vertical-padding)}.ag-filter-apply-panel-button{line-height:1.5}:where(.ag-ltr) .ag-filter-apply-panel-button{margin-left:calc(var(--ag-spacing)*2)}:where(.ag-rtl) .ag-filter-apply-panel-button{margin-right:calc(var(--ag-spacing)*2)}.ag-simple-filter-body-wrapper{display:flex;flex-direction:column;min-height:calc(var(--ag-list-item-height) + var(--ag-widget-container-vertical-padding) + var(--ag-widget-vertical-spacing));overflow-y:auto;padding:var(--ag-widget-container-vertical-padding) var(--ag-widget-container-horizontal-padding);padding-bottom:calc(var(--ag-widget-container-vertical-padding) - var(--ag-widget-vertical-spacing));&>*{margin-bottom:var(--ag-widget-vertical-spacing)}:where(.ag-resizer-wrapper){margin:0}}.ag-multi-filter-menu-item{margin:var(--ag-spacing) 0}.ag-multi-filter-group-title-bar{background-color:transparent;color:var(--ag-header-text-color);font-weight:500;padding:calc(var(--ag-spacing)*1.5) var(--ag-spacing)}.ag-group-filter-field-select-wrapper{display:flex;flex-direction:column;gap:var(--ag-widget-vertical-spacing);padding:var(--ag-widget-container-vertical-padding) var(--ag-widget-container-horizontal-padding)}`
);
function isColumnFilterPresent(beans) {
  const filterManager = beans.filterManager;
  return !!filterManager?.isColumnFilterPresent() || !!filterManager?.isAggregateFilterPresent();
}
function getColumnFilterInstance(beans, key2) {
  return beans.filterManager?.getColumnFilterInstance(key2) ?? Promise.resolve(void 0);
}
function destroyFilter(beans, key2) {
  const column2 = beans.colModel.getColDefCol(key2);
  if (column2) {
    return beans.colFilter?.destroyFilter(column2, "api");
  }
}
function setFilterModel(beans, model2) {
  beans.frameworkOverrides.wrapIncoming(() => beans.filterManager?.setFilterModel(model2));
}
function getFilterModel(beans) {
  return beans.filterManager?.getFilterModel() ?? {};
}
function getColumnFilterModel(beans, key2, useUnapplied) {
  const { gos, colModel, colFilter } = beans;
  if (useUnapplied && !gos.get("enableFilterHandlers")) {
    _warn(288);
    useUnapplied = false;
  }
  const column2 = colModel.getColDefCol(key2);
  return column2 ? colFilter?.getModelForColumn(column2, useUnapplied) ?? null : null;
}
function setColumnFilterModel(beans, column2, model2) {
  return beans.filterManager?.setColumnFilterModel(column2, model2) ?? Promise.resolve();
}
function showColumnFilter(beans, colKey) {
  const column2 = beans.colModel.getCol(colKey);
  if (!column2) {
    _error(12, { colKey });
    return;
  }
  beans.menuSvc?.showFilterMenu({
    column: column2,
    containerType: "columnFilter",
    positionBy: "auto"
  });
}
function hideColumnFilter(beans) {
  beans.menuSvc?.hideFilterMenu();
}
function getColumnFilterHandler(beans, colKey) {
  const column2 = beans.colModel.getCol(colKey);
  if (!column2) {
    _error(12, { colKey });
    return void 0;
  }
  return beans.colFilter?.getHandler(column2, true);
}
function doFilterAction(beans, params) {
  const { colModel, colFilter, gos } = beans;
  if (!gos.get("enableFilterHandlers")) {
    _warn(287);
    return;
  }
  const { colId, action } = params;
  if (colId) {
    const column2 = colModel.getColById(colId);
    if (column2) {
      colFilter?.updateModel(column2, action);
    }
  } else {
    colFilter?.updateAllModels(action);
  }
}
var DUMMY_HANDLER = {
  filterHandler: () => ({
    doesFilterPass: () => true
  })
};
var ColumnFilterService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "colFilter";
    this.allColumnFilters = /* @__PURE__ */ new Map();
    this.allColumnListeners = /* @__PURE__ */ new Map();
    this.activeAggregateFilters = [];
    this.activeColumnFilters = [];
    this.processingFilterChange = false;
    this.modelUpdates = [];
    this.columnModelUpdates = [];
    this.state = /* @__PURE__ */ new Map();
    this.handlerMap = {
      ...FILTER_HANDLER_MAP
    };
    this.isGlobalButtons = false;
    this.activeFilterComps = /* @__PURE__ */ new Set();
  }
  postConstruct() {
    this.addManagedEventListeners({
      gridColumnsChanged: this.onColumnsChanged.bind(this),
      dataTypesInferred: this.processFilterModelUpdateQueue.bind(this)
    });
    const gos = this.gos;
    const initialFilterModel = {
      ...gos.get("initialState")?.filter?.filterModel ?? {}
    };
    this.initialModel = initialFilterModel;
    this.model = {
      ...initialFilterModel
    };
    if (!gos.get("enableFilterHandlers")) {
      delete this.handlerMap["agMultiColumnFilter"];
    }
  }
  refreshModel() {
    this.onNewRowsLoaded("rowDataUpdated");
  }
  setModel(model2, source2 = "api", forceUpdateActive) {
    const { colModel, dataTypeSvc, filterManager } = this.beans;
    if (dataTypeSvc?.isPendingInference) {
      this.modelUpdates.push({ model: model2, source: source2 });
      return;
    }
    const allPromises = [];
    const previousModel = this.getModel(true);
    if (model2) {
      const modelKeys = new Set(Object.keys(model2));
      this.allColumnFilters.forEach((filterWrapper, colId) => {
        const newModel = model2[colId];
        allPromises.push(this.setModelOnFilterWrapper(filterWrapper, newModel));
        modelKeys.delete(colId);
      });
      modelKeys.forEach((colId) => {
        const column2 = colModel.getColDefCol(colId) || colModel.getCol(colId);
        if (!column2) {
          _warn(62, { colId });
          return;
        }
        if (!column2.isFilterAllowed()) {
          _warn(63, { colId });
          return;
        }
        const filterWrapper = this.getOrCreateFilterWrapper(column2, true);
        if (!filterWrapper) {
          _warn(64, { colId });
          return;
        }
        allPromises.push(this.setModelOnFilterWrapper(filterWrapper, model2[colId], true));
      });
    } else {
      this.model = {};
      this.allColumnFilters.forEach((filterWrapper) => {
        allPromises.push(this.setModelOnFilterWrapper(filterWrapper, null));
      });
    }
    AgPromise.all(allPromises).then(() => {
      const currentModel = this.getModel(true);
      const columns2 = [];
      this.allColumnFilters.forEach((filterWrapper, colId) => {
        const before = previousModel ? previousModel[colId] : null;
        const after = currentModel ? currentModel[colId] : null;
        if (!_jsonEquals(before, after)) {
          columns2.push(filterWrapper.column);
        }
      });
      if (columns2.length > 0) {
        filterManager?.onFilterChanged({ columns: columns2, source: source2 });
      } else if (forceUpdateActive) {
        this.updateActive("filterChanged");
      }
    });
  }
  getModel(excludeInitialState) {
    const result2 = {};
    const {
      allColumnFilters,
      initialModel,
      beans: { colModel }
    } = this;
    allColumnFilters.forEach((filterWrapper, key2) => {
      const model2 = this.getModelFromFilterWrapper(filterWrapper);
      if (_exists(model2)) {
        result2[key2] = model2;
      }
    });
    if (!excludeInitialState) {
      for (const colId of Object.keys(initialModel)) {
        const model2 = initialModel[colId];
        if (_exists(model2) && !allColumnFilters.has(colId) && colModel.getCol(colId)?.isFilterAllowed()) {
          result2[colId] = model2;
        }
      }
    }
    return result2;
  }
  setState(model2, state, source2 = "api") {
    this.state.clear();
    if (state) {
      for (const colId of Object.keys(state)) {
        const newState = state[colId];
        this.state.set(colId, {
          model: _getFilterModel(this.model, colId),
          state: newState
        });
      }
    }
    this.setModel(model2, source2, true);
  }
  getState() {
    const state = this.state;
    if (!state.size) {
      return void 0;
    }
    const newState = {};
    let hasNewState = false;
    state.forEach((colState, colId) => {
      const actualState = colState.state;
      if (actualState != null) {
        hasNewState = true;
        newState[colId] = actualState;
      }
    });
    return hasNewState ? newState : void 0;
  }
  getModelFromFilterWrapper(filterWrapper) {
    const column2 = filterWrapper.column;
    const colId = column2.getColId();
    if (filterWrapper.isHandler) {
      return _getFilterModel(this.model, colId);
    }
    const filter2 = filterWrapper.filter;
    if (filter2) {
      if (typeof filter2.getModel !== "function") {
        _warn(66);
        return null;
      }
      return filter2.getModel();
    }
    return _getFilterModel(this.initialModel, colId);
  }
  isFilterPresent() {
    return this.activeColumnFilters.length > 0;
  }
  isAggFilterPresent() {
    return !!this.activeAggregateFilters.length;
  }
  disableFilters() {
    this.initialModel = {};
    const { allColumnFilters } = this;
    if (allColumnFilters.size) {
      allColumnFilters.forEach(
        (filterWrapper) => this.disposeFilterWrapper(filterWrapper, "advancedFilterEnabled")
      );
      return true;
    }
    return false;
  }
  updateActiveFilters() {
    const isFilterActive = (filter2) => {
      if (!filter2) {
        return false;
      }
      if (!filter2.isFilterActive) {
        _warn(67);
        return false;
      }
      return filter2.isFilterActive();
    };
    const { colModel, gos } = this.beans;
    const groupFilterEnabled = !!_getGroupAggFiltering(gos);
    const isAggFilter = (column2) => {
      const isSecondary = !column2.isPrimary();
      if (isSecondary) {
        return true;
      }
      const isShowingPrimaryColumns = !colModel.isPivotActive();
      const isValueActive = column2.isValueActive();
      if (!isValueActive || !isShowingPrimaryColumns) {
        return false;
      }
      if (colModel.isPivotMode()) {
        return true;
      }
      return groupFilterEnabled;
    };
    const activeAggregateFilters = [];
    const activeColumnFilters = [];
    const addFilter = (column2, filterActive, doesFilterPassWrapper) => {
      if (filterActive) {
        if (isAggFilter(column2)) {
          activeAggregateFilters.push(doesFilterPassWrapper);
        } else {
          activeColumnFilters.push(doesFilterPassWrapper);
        }
      }
    };
    const promises = [];
    this.allColumnFilters.forEach((filterWrapper) => {
      const column2 = filterWrapper.column;
      const colId = column2.getColId();
      if (filterWrapper.isHandler) {
        promises.push(
          AgPromise.resolve().then(() => {
            addFilter(column2, this.isHandlerActive(column2), {
              colId,
              isHandler: true,
              handler: filterWrapper.handler,
              handlerParams: filterWrapper.handlerParams
            });
          })
        );
      } else {
        const promise = getFilterUiFromWrapper(filterWrapper);
        if (promise) {
          promises.push(
            promise.then((filter2) => {
              addFilter(column2, isFilterActive(filter2), {
                colId,
                isHandler: false,
                comp: filter2
              });
            })
          );
        }
      }
    });
    return AgPromise.all(promises).then(() => {
      this.activeAggregateFilters = activeAggregateFilters;
      this.activeColumnFilters = activeColumnFilters;
    });
  }
  updateFilterFlagInColumns(source2, additionalEventAttributes) {
    const promises = [];
    this.allColumnFilters.forEach((filterWrapper) => {
      const column2 = filterWrapper.column;
      if (filterWrapper.isHandler) {
        promises.push(
          AgPromise.resolve().then(() => {
            this.setColFilterActive(
              column2,
              this.isHandlerActive(column2),
              source2,
              additionalEventAttributes
            );
          })
        );
      } else {
        const promise = getFilterUiFromWrapper(filterWrapper);
        if (promise) {
          promises.push(
            promise.then((filter2) => {
              this.setColFilterActive(
                column2,
                filter2.isFilterActive(),
                source2,
                additionalEventAttributes
              );
            })
          );
        }
      }
    });
    this.beans.groupFilter?.updateFilterFlags(source2, additionalEventAttributes);
    return AgPromise.all(promises);
  }
  doFiltersPass(node2, colIdToSkip, targetAggregates) {
    const { data: data2, aggData } = node2;
    const targetedFilters = targetAggregates ? this.activeAggregateFilters : this.activeColumnFilters;
    const targetedData = targetAggregates ? aggData : data2;
    const model2 = this.model;
    for (let i2 = 0; i2 < targetedFilters.length; i2++) {
      const filter2 = targetedFilters[i2];
      const { colId, isHandler } = filter2;
      if (colId === colIdToSkip) {
        continue;
      }
      if (isHandler) {
        const { handler, handlerParams } = filter2;
        if (!handler.doesFilterPass({
          node: node2,
          data: targetedData,
          model: _getFilterModel(model2, colId),
          handlerParams
        })) {
          return false;
        }
      } else {
        const comp = filter2.comp;
        if (typeof comp.doesFilterPass !== "function") {
          _error(91);
          continue;
        }
        if (!comp.doesFilterPass({ node: node2, data: targetedData })) {
          return false;
        }
      }
    }
    return true;
  }
  getHandlerParams(column2) {
    const wrapper2 = this.allColumnFilters.get(column2.getColId());
    return wrapper2?.isHandler ? wrapper2.handlerParams : void 0;
  }
  // sometimes (especially in React) the filter can call onFilterChanged when we are in the middle
  // of a render cycle. this would be bad, so we wait for render cycle to complete when this happens.
  // this happens in react when we change React State in the grid (eg setting RowCtrl's in RowContainer)
  // which results in React State getting applied in the main application, triggering a useEffect() to
  // be kicked off adn then the application calling the grid's API. in AG-6554, the custom filter was
  // getting it's useEffect() triggered in this way.
  callOnFilterChangedOutsideRenderCycle(params) {
    const { rowRenderer, filterManager } = this.beans;
    const action = () => {
      if (this.isAlive()) {
        filterManager?.onFilterChanged(params);
      }
    };
    if (rowRenderer.isRefreshInProgress()) {
      setTimeout(action, 0);
    } else {
      action();
    }
  }
  updateBeforeFilterChanged(params = {}) {
    const { column: column2, additionalEventAttributes } = params;
    const colId = column2?.getColId();
    return this.updateActiveFilters().then(
      () => this.updateFilterFlagInColumns("filterChanged", additionalEventAttributes).then(() => {
        this.allColumnFilters.forEach((filterWrapper) => {
          const { column: filterColumn, isHandler } = filterWrapper;
          if (colId === filterColumn.getColId()) {
            return;
          }
          if (isHandler) {
            filterWrapper.handler.onAnyFilterChanged?.();
          }
          getFilterUiFromWrapper(filterWrapper, isHandler)?.then((filter2) => {
            if (typeof filter2?.onAnyFilterChanged === "function") {
              filter2.onAnyFilterChanged();
            }
          });
        });
        this.processingFilterChange = true;
      })
    );
  }
  updateAfterFilterChanged() {
    this.processingFilterChange = false;
  }
  isSuppressFlashingCellsBecauseFiltering() {
    const allowShowChangeAfterFilter = this.gos.get("allowShowChangeAfterFilter") ?? false;
    return !allowShowChangeAfterFilter && this.processingFilterChange;
  }
  onNewRowsLoaded(source2) {
    const promises = [];
    this.allColumnFilters.forEach((filterWrapper) => {
      const isHandler = filterWrapper.isHandler;
      if (isHandler) {
        filterWrapper.handler.onNewRowsLoaded?.();
      }
      const promise = getFilterUiFromWrapper(filterWrapper, isHandler);
      if (promise) {
        promises.push(
          promise.then((filter2) => {
            filter2.onNewRowsLoaded?.();
          })
        );
      }
    });
    AgPromise.all(promises).then(() => this.updateActive(source2, { afterDataChange: true }));
  }
  updateActive(source2, additionalEventAttributes) {
    this.updateFilterFlagInColumns(source2, additionalEventAttributes).then(() => this.updateActiveFilters());
  }
  createGetValue(filterColumn, filterValueGetterOverride) {
    const { filterValueSvc, colModel } = this.beans;
    return (rowNode, column2) => {
      const columnToUse = column2 ? colModel.getCol(column2) : filterColumn;
      return columnToUse ? filterValueSvc.getValue(columnToUse, rowNode, filterValueGetterOverride) : void 0;
    };
  }
  isFilterActive(column2) {
    const filterWrapper = this.cachedFilter(column2);
    if (filterWrapper?.isHandler) {
      return this.isHandlerActive(column2);
    }
    const filter2 = filterWrapper?.filter;
    if (filter2) {
      return filter2.isFilterActive();
    }
    return _getFilterModel(this.initialModel, column2.getColId()) != null;
  }
  isHandlerActive(column2) {
    const active = _exists(_getFilterModel(this.model, column2.getColId()));
    if (active) {
      return active;
    }
    const groupFilter = this.beans.groupFilter;
    return groupFilter?.isGroupFilter(column2) ? groupFilter.isFilterActive(column2) : false;
  }
  getOrCreateFilterUi(column2) {
    const filterWrapper = this.getOrCreateFilterWrapper(column2, true);
    return filterWrapper ? getFilterUiFromWrapper(filterWrapper) : null;
  }
  getFilterUiForDisplay(column2) {
    const filterWrapper = this.getOrCreateFilterWrapper(column2, true);
    if (!filterWrapper) {
      return null;
    }
    const compPromise = getFilterUiFromWrapper(filterWrapper);
    if (!compPromise) {
      return null;
    }
    return compPromise.then((comp) => ({
      comp,
      params: filterWrapper.filterUi.filterParams,
      isHandler: filterWrapper.isHandler
    }));
  }
  getHandler(column2, createIfMissing) {
    const filterWrapper = this.getOrCreateFilterWrapper(column2, createIfMissing);
    return filterWrapper?.isHandler ? filterWrapper.handler : void 0;
  }
  getOrCreateFilterWrapper(column2, createIfMissing) {
    if (!column2.isFilterAllowed()) {
      return void 0;
    }
    let filterWrapper = this.cachedFilter(column2);
    if (!filterWrapper && createIfMissing) {
      filterWrapper = this.createFilterWrapper(column2);
      this.setColumnFilterWrapper(column2, filterWrapper);
    }
    return filterWrapper;
  }
  cachedFilter(column2) {
    return this.allColumnFilters.get(column2.getColId());
  }
  getDefaultFilter(column2, isFloating = false) {
    return this.getDefaultFilterFromDataType(() => this.beans.dataTypeSvc?.getBaseDataType(column2), isFloating);
  }
  getDefaultFilterFromDataType(getCellDataType, isFloating = false) {
    if (_isSetFilterByDefault(this.gos)) {
      return isFloating ? "agSetColumnFloatingFilter" : "agSetColumnFilter";
    }
    return _getDefaultSimpleFilter(getCellDataType(), isFloating);
  }
  getDefaultFloatingFilter(column2) {
    return this.getDefaultFilter(column2, true);
  }
  createFilterComp(column2, filterDef, defaultFilter, getFilterParams, isHandler, source2) {
    const createFilterCompDetails = () => {
      const params = this.createFilterCompParams(column2, isHandler, source2);
      const updatedParams = getFilterParams(params, isHandler);
      return _getFilterDetails(this.beans.userCompFactory, filterDef, updatedParams, defaultFilter);
    };
    const compDetails = createFilterCompDetails();
    if (!compDetails) {
      return null;
    }
    const createFilterUi = (update2) => {
      return (update2 ? createFilterCompDetails() : compDetails).newAgStackInstance();
    };
    return {
      compDetails,
      createFilterUi
    };
  }
  createFilterInstance(column2, filterDef, defaultFilter, getFilterParams) {
    const selectableFilter = this.beans.selectableFilter;
    if (selectableFilter?.isSelectable(filterDef)) {
      filterDef = selectableFilter.getFilterDef(column2, filterDef);
    }
    const { handler, handlerParams, handlerGenerator } = this.createHandler(column2, filterDef, defaultFilter) ?? {};
    const filterCompDetails = this.createFilterComp(
      column2,
      filterDef,
      defaultFilter,
      getFilterParams,
      !!handler,
      "init"
    );
    if (!filterCompDetails) {
      return {
        compDetails: null,
        createFilterUi: null,
        handler,
        handlerGenerator,
        handlerParams
      };
    }
    const { compDetails, createFilterUi } = filterCompDetails;
    if (this.isGlobalButtons) {
      const hasLocalButtons = !!compDetails.params?.buttons?.length;
      if (!hasLocalButtons) {
        _warn(281, { colId: column2.getColId() });
      }
    }
    return {
      compDetails,
      handler,
      handlerGenerator,
      handlerParams,
      createFilterUi
    };
  }
  createBaseFilterParams(column2, forFloatingFilter) {
    const { filterManager, rowModel } = this.beans;
    return _addGridCommonParams(this.gos, {
      column: column2,
      colDef: column2.getColDef(),
      getValue: this.createGetValue(column2),
      doesRowPassOtherFilter: forFloatingFilter ? () => true : (node2) => filterManager?.doesRowPassOtherFilters(column2.getColId(), node2) ?? true,
      // to avoid breaking changes to `filterParams` defined as functions
      // we need to provide the below options even though they are not valid for handlers
      rowModel
    });
  }
  createFilterCompParams(column2, useHandler, source2, forFloatingFilter) {
    const filterChangedCallback = this.filterChangedCallbackFactory(column2);
    const params = this.createBaseFilterParams(column2, forFloatingFilter);
    params.filterChangedCallback = filterChangedCallback;
    params.filterModifiedCallback = forFloatingFilter ? () => {
    } : (additionalEventAttributes) => this.filterModified(column2, additionalEventAttributes);
    if (useHandler) {
      const displayParams = params;
      const colId = column2.getColId();
      const model2 = _getFilterModel(this.model, colId);
      displayParams.model = model2;
      displayParams.state = this.state.get(colId) ?? {
        model: model2
      };
      displayParams.onModelChange = (model22, additionalEventAttributes) => {
        this.updateStoredModel(colId, model22);
        this.refreshHandlerAndUi(column2, model22, "ui", false, additionalEventAttributes).then(() => {
          filterChangedCallback({ ...additionalEventAttributes, source: "columnFilter" });
        });
      };
      displayParams.onStateChange = (state) => {
        this.updateState(column2, state);
        this.updateOrRefreshFilterUi(column2);
      };
      displayParams.onAction = (action, additionalEventAttributes, event) => {
        this.updateModel(column2, action, additionalEventAttributes);
        this.dispatchLocalEvent({
          type: "filterAction",
          column: column2,
          action,
          event
        });
      };
      displayParams.getHandler = () => this.getHandler(column2, true);
      displayParams.onUiChange = (additionalEventAttributes) => this.filterUiChanged(column2, additionalEventAttributes);
      displayParams.source = source2;
    }
    return params;
  }
  createFilterUiForHandler(compDetails, createFilterUi) {
    return createFilterUi ? {
      created: false,
      create: createFilterUi,
      filterParams: compDetails.params,
      compDetails
    } : null;
  }
  createFilterUiLegacy(compDetails, createFilterUi, updateInstanceCallback) {
    const promise = createFilterUi();
    const filterUi = {
      created: true,
      create: createFilterUi,
      filterParams: compDetails.params,
      compDetails,
      promise
    };
    promise.then(updateInstanceCallback);
    return filterUi;
  }
  createFilterWrapper(column2) {
    const { compDetails, handler, handlerGenerator, handlerParams, createFilterUi } = this.createFilterInstance(
      column2,
      column2.getColDef(),
      this.getDefaultFilter(column2),
      (params) => params
    );
    const colId = column2.getColId();
    if (handler) {
      delete this.initialModel[colId];
      handler.init?.({
        ...handlerParams,
        source: "init",
        model: _getFilterModel(this.model, colId)
      });
      return {
        column: column2,
        isHandler: true,
        handler,
        handlerGenerator,
        handlerParams,
        filterUi: this.createFilterUiForHandler(compDetails, createFilterUi)
      };
    }
    if (createFilterUi) {
      const filterWrapper = {
        column: column2,
        filterUi: null,
        isHandler: false
      };
      filterWrapper.filterUi = this.createFilterUiLegacy(compDetails, createFilterUi, (filterComp) => {
        filterWrapper.filter = filterComp ?? void 0;
      });
      return filterWrapper;
    }
    return {
      column: column2,
      filterUi: null,
      isHandler: false
    };
  }
  createHandlerFunc(column2, filterDef, defaultFilter) {
    const { gos, frameworkOverrides, registry } = this.beans;
    let doesFilterPass;
    const getFilterHandlerFromDef = (filterDef2) => {
      const filter2 = filterDef2.filter;
      if (isColumnFilterComp(filter2)) {
        const handler = filter2.handler;
        if (handler) {
          return handler;
        }
        doesFilterPass = filter2.doesFilterPass;
        if (doesFilterPass) {
          return () => ({
            doesFilterPass
          });
        }
        return void 0;
      }
      return typeof filter2 === "string" ? filter2 : void 0;
    };
    const enableFilterHandlers = gos.get("enableFilterHandlers");
    const providedFilterHandler = enableFilterHandlers ? getFilterHandlerFromDef(filterDef) : void 0;
    const resolveProvidedFilterHandler = (handlerName2) => () => this.createBean(registry.createDynamicBean(handlerName2, true));
    let filterHandler;
    let handlerName;
    if (typeof providedFilterHandler === "string") {
      const userFilterHandler = gos.get("filterHandlers")?.[providedFilterHandler];
      if (userFilterHandler != null) {
        filterHandler = userFilterHandler;
      } else if (FILTER_HANDLERS.has(providedFilterHandler)) {
        filterHandler = resolveProvidedFilterHandler(providedFilterHandler);
        handlerName = providedFilterHandler;
      }
    } else {
      filterHandler = providedFilterHandler;
    }
    if (!filterHandler) {
      let filterName;
      const { compName, jsComp, fwComp } = _getFilterCompKeys(frameworkOverrides, filterDef);
      if (compName) {
        filterName = compName;
      } else {
        const usingDefaultFilter = jsComp == null && fwComp == null && filterDef.filter === true;
        if (usingDefaultFilter) {
          filterName = defaultFilter;
        }
      }
      handlerName = this.handlerMap[filterName];
      if (handlerName) {
        filterHandler = resolveProvidedFilterHandler(handlerName);
      }
    }
    if (!filterHandler) {
      if (!enableFilterHandlers) {
        return void 0;
      }
      if (_isClientSideRowModel(gos)) {
        _warn(277, { colId: column2.getColId() });
      }
      return DUMMY_HANDLER;
    }
    return { filterHandler, handlerNameOrCallback: doesFilterPass ?? handlerName };
  }
  createHandler(column2, filterDef, defaultFilter) {
    const handlerFunc = this.createHandlerFunc(column2, filterDef, defaultFilter);
    if (!handlerFunc) {
      return void 0;
    }
    const filterParams = _mergeFilterParamsWithApplicationProvidedParams(
      this.beans.userCompFactory,
      filterDef,
      this.createFilterCompParams(column2, true, "init")
    );
    const { handlerNameOrCallback, filterHandler } = handlerFunc;
    const { handler, handlerParams } = this.createHandlerFromFunc(column2, filterHandler, filterParams);
    return {
      handler,
      handlerParams,
      handlerGenerator: handlerNameOrCallback ?? filterHandler
    };
  }
  createHandlerFromFunc(column2, filterHandler, filterParams) {
    const colDef = column2.getColDef();
    const handler = filterHandler(_addGridCommonParams(this.gos, { column: column2, colDef }));
    const handlerParams = this.createHandlerParams(column2, filterParams);
    return { handler, handlerParams };
  }
  createHandlerParams(column2, filterParams) {
    const colDef = column2.getColDef();
    const colId = column2.getColId();
    const filterChangedCallback = this.filterChangedCallbackFactory(column2);
    return _addGridCommonParams(this.gos, {
      colDef,
      column: column2,
      getValue: this.createGetValue(column2),
      doesRowPassOtherFilter: (node2) => this.beans.filterManager?.doesRowPassOtherFilters(colId, node2) ?? true,
      onModelChange: (newModel, additionalEventAttributes) => {
        this.updateStoredModel(colId, newModel);
        this.refreshHandlerAndUi(column2, newModel, "handler", false, additionalEventAttributes).then(() => {
          filterChangedCallback({ ...additionalEventAttributes, source: "columnFilter" });
        });
      },
      filterParams
    });
  }
  onColumnsChanged() {
    const columns2 = [];
    const { colModel, filterManager, groupFilter } = this.beans;
    this.allColumnFilters.forEach((wrapper2, colId) => {
      let currentColumn;
      if (wrapper2.column.isPrimary()) {
        currentColumn = colModel.getColDefCol(colId);
      } else {
        currentColumn = colModel.getCol(colId);
      }
      if (currentColumn && currentColumn === wrapper2.column) {
        return;
      }
      columns2.push(wrapper2.column);
      this.disposeFilterWrapper(wrapper2, "columnChanged");
      this.disposeColumnListener(colId);
    });
    const allFiltersAreGroupFilters = groupFilter && columns2.every((col) => groupFilter.isGroupFilter(col));
    if (columns2.length > 0 && !allFiltersAreGroupFilters) {
      filterManager?.onFilterChanged({ columns: columns2, source: "api" });
    }
  }
  isFilterAllowed(column2) {
    const isFilterAllowed = column2.isFilterAllowed();
    if (!isFilterAllowed) {
      return false;
    }
    const groupFilter = this.beans.groupFilter;
    if (groupFilter?.isGroupFilter(column2)) {
      return groupFilter.isFilterAllowed(column2);
    }
    return true;
  }
  getFloatingFilterCompDetails(column2, showParentFilter) {
    const { userCompFactory, frameworkOverrides, selectableFilter } = this.beans;
    const parentFilterInstance = (callback) => {
      const filterComponent = this.getOrCreateFilterUi(column2);
      if (filterComponent == null) {
        return;
      }
      filterComponent.then((instance2) => {
        callback(_unwrapUserComp(instance2));
      });
    };
    const colDef = column2.getColDef();
    const filterDef = selectableFilter?.isSelectable(colDef) ? selectableFilter.getFilterDef(column2, colDef) : colDef;
    const defaultFloatingFilterType = _getDefaultFloatingFilterType(frameworkOverrides, filterDef, () => this.getDefaultFloatingFilter(column2)) ?? "agReadOnlyFloatingFilter";
    const isReactive = this.gos.get("enableFilterHandlers");
    const filterParams = _mergeFilterParamsWithApplicationProvidedParams(
      userCompFactory,
      filterDef,
      this.createFilterCompParams(column2, isReactive, "init", true)
    );
    const params = _addGridCommonParams(this.gos, {
      column: column2,
      filterParams,
      currentParentModel: () => this.getCurrentFloatingFilterParentModel(column2),
      parentFilterInstance,
      showParentFilter
    });
    if (isReactive) {
      const displayParams = params;
      const colId = column2.getColId();
      const filterChangedCallback = this.filterChangedCallbackFactory(column2);
      displayParams.onUiChange = (additionalEventAttributes) => this.floatingFilterUiChanged(column2, additionalEventAttributes);
      displayParams.model = _getFilterModel(this.model, colId);
      displayParams.onModelChange = (model2, additionalEventAttributes) => {
        this.updateStoredModel(colId, model2);
        this.refreshHandlerAndUi(column2, model2, "floating", true, additionalEventAttributes).then(() => {
          filterChangedCallback({ ...additionalEventAttributes, source: "columnFilter" });
        });
      };
      displayParams.getHandler = () => this.getHandler(column2, true);
      displayParams.source = "init";
    }
    return _getFloatingFilterCompDetails(userCompFactory, colDef, params, defaultFloatingFilterType);
  }
  getCurrentFloatingFilterParentModel(column2) {
    return this.getModelFromFilterWrapper(this.cachedFilter(column2) ?? { column: column2 });
  }
  destroyFilterUi(filterWrapper, column2, compDetails, createFilterUi) {
    const source2 = "paramsUpdated";
    if (filterWrapper.isHandler) {
      const colId = column2.getColId();
      delete this.initialModel[colId];
      this.state.delete(colId);
      const filterUi = filterWrapper.filterUi;
      const newFilterUi = this.createFilterUiForHandler(compDetails, createFilterUi);
      filterWrapper.filterUi = newFilterUi;
      const eventSvc = this.eventSvc;
      if (filterUi?.created) {
        filterUi.promise.then((filter2) => {
          this.destroyBean(filter2);
          eventSvc.dispatchEvent({
            type: "filterDestroyed",
            source: source2,
            column: column2
          });
        });
      } else {
        eventSvc.dispatchEvent({
          type: "filterHandlerDestroyed",
          source: source2,
          column: column2
        });
      }
    } else {
      this.destroyFilter(column2, source2);
    }
  }
  // destroys the filter, so it no longer takes part
  destroyFilter(column2, source2 = "api") {
    const colId = column2.getColId();
    const filterWrapper = this.allColumnFilters.get(colId);
    this.disposeColumnListener(colId);
    delete this.initialModel[colId];
    if (filterWrapper) {
      this.disposeFilterWrapper(filterWrapper, source2).then((wasActive) => {
        if (wasActive && this.isAlive()) {
          this.beans.filterManager?.onFilterChanged({
            columns: [column2],
            source: "api"
          });
        }
      });
    }
  }
  disposeColumnListener(colId) {
    const columnListener = this.allColumnListeners.get(colId);
    if (columnListener) {
      this.allColumnListeners.delete(colId);
      columnListener();
    }
  }
  disposeFilterWrapper(filterWrapper, source2) {
    let isActive = false;
    const { column: column2, isHandler, filterUi } = filterWrapper;
    const colId = column2.getColId();
    if (isHandler) {
      isActive = this.isHandlerActive(column2);
      this.destroyBean(filterWrapper.handler);
      delete this.model[colId];
      this.state.delete(colId);
    }
    const removeFilter = () => {
      this.setColFilterActive(column2, false, "filterDestroyed");
      this.allColumnFilters.delete(colId);
      this.eventSvc.dispatchEvent({
        type: "filterDestroyed",
        source: source2,
        column: column2
      });
    };
    if (filterUi) {
      if (filterUi.created) {
        return filterUi.promise.then((filter2) => {
          isActive = isHandler ? isActive : !!filter2?.isFilterActive();
          this.destroyBean(filter2);
          removeFilter();
          return isActive;
        });
      } else {
        removeFilter();
      }
    }
    return AgPromise.resolve(isActive);
  }
  filterChangedCallbackFactory(column2) {
    return (additionalEventAttributes) => {
      this.callOnFilterChangedOutsideRenderCycle({
        additionalEventAttributes,
        columns: [column2],
        column: column2,
        source: additionalEventAttributes?.source ?? "columnFilter"
      });
    };
  }
  filterParamsChanged(colId, source2 = "api") {
    const filterWrapper = this.allColumnFilters.get(colId);
    if (!filterWrapper) {
      return;
    }
    const beans = this.beans;
    const column2 = filterWrapper.column;
    const colDef = column2.getColDef();
    const isFilterAllowed = column2.isFilterAllowed();
    const defaultFilter = this.getDefaultFilter(column2);
    const selectableFilter = beans.selectableFilter;
    const filterDef = selectableFilter?.isSelectable(colDef) ? selectableFilter.getFilterDef(column2, colDef) : colDef;
    const handlerFunc = isFilterAllowed ? this.createHandlerFunc(column2, filterDef, this.getDefaultFilter(column2)) : void 0;
    const isHandler = !!handlerFunc;
    const wasHandler = filterWrapper.isHandler;
    if (wasHandler != isHandler) {
      this.destroyFilter(column2, "paramsUpdated");
      return;
    }
    const { compDetails, createFilterUi } = (isFilterAllowed ? this.createFilterComp(column2, filterDef, defaultFilter, (params) => params, isHandler, "colDef") : null) ?? { compDetails: null, createFilterUi: null };
    const newFilterParams = compDetails?.params ?? _mergeFilterParamsWithApplicationProvidedParams(
      beans.userCompFactory,
      filterDef,
      this.createFilterCompParams(column2, isHandler, "colDef")
    );
    if (wasHandler) {
      const handlerGenerator = handlerFunc?.handlerNameOrCallback ?? handlerFunc?.filterHandler;
      const existingModel = _getFilterModel(this.model, colId);
      if (filterWrapper.handlerGenerator != handlerGenerator) {
        const oldHandler = filterWrapper.handler;
        const { handler, handlerParams } = this.createHandlerFromFunc(
          column2,
          handlerFunc.filterHandler,
          newFilterParams
        );
        filterWrapper.handler = handler;
        filterWrapper.handlerParams = handlerParams;
        filterWrapper.handlerGenerator = handlerGenerator;
        delete this.model[colId];
        handler.init?.({ ...handlerParams, source: "init", model: null });
        this.destroyBean(oldHandler);
        if (existingModel != null) {
          this.beans.filterManager?.onFilterChanged({
            columns: [column2],
            source: source2
          });
        }
      } else {
        const handlerParams = this.createHandlerParams(column2, compDetails?.params);
        filterWrapper.handlerParams = handlerParams;
        filterWrapper.handler.refresh?.({
          ...handlerParams,
          source: "colDef",
          model: existingModel
        });
      }
    }
    if (this.areFilterCompsDifferent(filterWrapper.filterUi?.compDetails ?? null, compDetails) || !filterWrapper.filterUi || !compDetails) {
      this.destroyFilterUi(filterWrapper, column2, compDetails, createFilterUi);
      return;
    }
    filterWrapper.filterUi.filterParams = newFilterParams;
    getFilterUiFromWrapper(filterWrapper, wasHandler)?.then((filter2) => {
      const shouldRefreshFilter = filter2?.refresh ? filter2.refresh(newFilterParams) : true;
      if (shouldRefreshFilter === false) {
        this.destroyFilterUi(filterWrapper, column2, compDetails, createFilterUi);
      } else {
        this.dispatchLocalEvent({
          type: "filterParamsChanged",
          column: column2,
          params: newFilterParams
        });
      }
    });
  }
  refreshHandlerAndUi(column2, model2, source2, createIfMissing, additionalEventAttributes) {
    const filterWrapper = this.cachedFilter(column2);
    if (!filterWrapper) {
      if (createIfMissing) {
        this.getOrCreateFilterWrapper(column2, true);
      }
      return AgPromise.resolve();
    }
    if (!filterWrapper.isHandler) {
      return AgPromise.resolve();
    }
    const { filterUi, handler, handlerParams } = filterWrapper;
    return _refreshHandlerAndUi(
      () => {
        if (filterUi) {
          const { created, filterParams } = filterUi;
          if (created) {
            return filterUi.promise.then((filter2) => {
              return filter2 ? { filter: filter2, filterParams } : void 0;
            });
          } else {
            filterUi.refreshed = true;
          }
        }
        return AgPromise.resolve(void 0);
      },
      handler,
      handlerParams,
      model2,
      this.state.get(column2.getColId()) ?? { model: model2 },
      source2,
      additionalEventAttributes
    );
  }
  setColumnFilterWrapper(column2, filterWrapper) {
    const colId = column2.getColId();
    this.allColumnFilters.set(colId, filterWrapper);
    this.allColumnListeners.set(
      colId,
      this.addManagedListeners(column2, { colDefChanged: () => this.filterParamsChanged(colId) })[0]
    );
  }
  areFilterCompsDifferent(oldCompDetails, newCompDetails) {
    if (!newCompDetails || !oldCompDetails) {
      return true;
    }
    const { componentClass: oldComponentClass } = oldCompDetails;
    const { componentClass: newComponentClass } = newCompDetails;
    const isSameComponentClass = oldComponentClass === newComponentClass || // react hooks returns new wrappers, so check nested render method
    oldComponentClass?.render && newComponentClass?.render && oldComponentClass.render === newComponentClass.render;
    return !isSameComponentClass;
  }
  hasFloatingFilters() {
    const gridColumns = this.beans.colModel.getCols();
    return gridColumns.some((col) => col.getColDef().floatingFilter);
  }
  getFilterInstance(key2) {
    const column2 = this.beans.colModel.getColDefCol(key2);
    if (!column2) {
      return Promise.resolve(void 0);
    }
    const filterPromise = this.getOrCreateFilterUi(column2);
    if (!filterPromise) {
      return Promise.resolve(null);
    }
    return new Promise((resolve2) => {
      filterPromise.then((filter2) => {
        resolve2(_unwrapUserComp(filter2));
      });
    });
  }
  processFilterModelUpdateQueue() {
    this.modelUpdates.forEach(({ model: model2, source: source2 }) => this.setModel(model2, source2));
    this.modelUpdates = [];
    this.columnModelUpdates.forEach(({ key: key2, model: model2, resolve: resolve2 }) => {
      this.setModelForColumn(key2, model2).then(() => resolve2());
    });
    this.columnModelUpdates = [];
  }
  getModelForColumn(column2, useUnapplied) {
    if (useUnapplied) {
      const { state, model: model2 } = this;
      const colId = column2.getColId();
      const colState = state.get(colId);
      if (colState) {
        return colState.model ?? null;
      }
      return _getFilterModel(model2, colId);
    }
    const filterWrapper = this.cachedFilter(column2);
    return filterWrapper ? this.getModelFromFilterWrapper(filterWrapper) : null;
  }
  setModelForColumn(key2, model2) {
    if (this.beans.dataTypeSvc?.isPendingInference) {
      let resolve2 = () => {
      };
      const promise = new Promise((res) => {
        resolve2 = res;
      });
      this.columnModelUpdates.push({ key: key2, model: model2, resolve: resolve2 });
      return promise;
    }
    return new Promise((resolve2) => {
      this.setModelForColumnLegacy(key2, model2).then((result2) => resolve2(result2));
    });
  }
  getStateForColumn(colId) {
    return this.state.get(colId) ?? {
      model: _getFilterModel(this.model, colId)
    };
  }
  setModelForColumnLegacy(key2, model2) {
    const column2 = this.beans.colModel.getColDefCol(key2);
    const filterWrapper = column2 ? this.getOrCreateFilterWrapper(column2, true) : null;
    return filterWrapper ? this.setModelOnFilterWrapper(filterWrapper, model2) : AgPromise.resolve();
  }
  setColDefPropsForDataType(colDef, dataTypeDefinition, formatValue2) {
    const providedFilter = colDef.filter;
    const filter2 = providedFilter === true ? this.getDefaultFilterFromDataType(() => dataTypeDefinition.baseDataType) : providedFilter;
    if (typeof filter2 !== "string") {
      return;
    }
    let filterParams;
    let filterValueGetter;
    const beans = this.beans;
    const { filterParams: colDefFilterParams, filterValueGetter: colDefFilterValueGetter } = colDef;
    if (filter2 === "agMultiColumnFilter") {
      ({ filterParams, filterValueGetter } = beans.multiFilter?.getParamsForDataType(
        colDefFilterParams,
        colDefFilterValueGetter,
        dataTypeDefinition,
        formatValue2
      ) ?? {});
    } else {
      ({ filterParams, filterValueGetter } = _getFilterParamsForDataType(
        filter2,
        colDefFilterParams,
        colDefFilterValueGetter,
        dataTypeDefinition,
        formatValue2,
        beans,
        this.getLocaleTextFunc()
      ));
    }
    colDef.filterParams = filterParams;
    if (filterValueGetter) {
      colDef.filterValueGetter = filterValueGetter;
    }
  }
  // additionalEventAttributes is used by provided simple floating filter, so it can add 'floatingFilter=true' to the event
  setColFilterActive(column2, active, source2, additionalEventAttributes) {
    if (column2.filterActive !== active) {
      column2.filterActive = active;
      column2.dispatchColEvent("filterActiveChanged", source2);
    }
    column2.dispatchColEvent("filterChanged", source2, additionalEventAttributes);
  }
  setModelOnFilterWrapper(filterWrapper, newModel, justCreated) {
    return new AgPromise((resolve2) => {
      if (filterWrapper.isHandler) {
        const column2 = filterWrapper.column;
        const colId = column2.getColId();
        const existingModel = this.model[colId];
        this.updateStoredModel(colId, newModel);
        if (justCreated && newModel === existingModel) {
          resolve2();
          return;
        }
        this.refreshHandlerAndUi(column2, newModel, "api").then(() => resolve2());
        return;
      }
      const uiPromise = getFilterUiFromWrapper(filterWrapper);
      if (uiPromise) {
        uiPromise.then((filter2) => {
          if (typeof filter2?.setModel !== "function") {
            _warn(65);
            resolve2();
            return;
          }
          (filter2.setModel(newModel) || AgPromise.resolve()).then(() => resolve2());
        });
        return;
      }
      resolve2();
    });
  }
  /** for handlers only */
  updateStoredModel(colId, model2) {
    if (_exists(model2)) {
      this.model[colId] = model2;
    } else {
      delete this.model[colId];
    }
    const oldState = this.state.get(colId);
    const newState = {
      model: model2,
      state: oldState?.state
    };
    this.state.set(colId, newState);
  }
  filterModified(column2, additionalEventAttributes) {
    this.getOrCreateFilterUi(column2)?.then((filterInstance) => {
      this.eventSvc.dispatchEvent({
        type: "filterModified",
        column: column2,
        filterInstance,
        ...additionalEventAttributes
      });
    });
  }
  filterUiChanged(column2, additionalEventAttributes) {
    if (this.gos.get("enableFilterHandlers")) {
      this.eventSvc.dispatchEvent({
        type: "filterUiChanged",
        column: column2,
        ...additionalEventAttributes
      });
    }
  }
  floatingFilterUiChanged(column2, additionalEventAttributes) {
    if (this.gos.get("enableFilterHandlers")) {
      this.eventSvc.dispatchEvent({
        type: "floatingFilterUiChanged",
        column: column2,
        ...additionalEventAttributes
      });
    }
  }
  updateModel(column2, action, additionalEventAttributes) {
    const colId = column2.getColId();
    const filterWrapper = this.cachedFilter(column2);
    const getFilterUi = () => filterWrapper?.filterUi;
    _updateFilterModel(
      action,
      getFilterUi,
      () => _getFilterModel(this.model, colId),
      () => this.state.get(colId),
      (state) => this.updateState(column2, state),
      (model2) => getFilterUi()?.filterParams?.onModelChange(model2, additionalEventAttributes),
      filterWrapper?.isHandler ? filterWrapper.handler.processModelToApply?.bind(filterWrapper.handler) : void 0
    );
  }
  updateAllModels(action, additionalEventAttributes) {
    const promises = [];
    this.allColumnFilters.forEach((filter2, colId) => {
      const column2 = this.beans.colModel.getColDefCol(colId);
      if (column2) {
        _updateFilterModel(
          action,
          () => filter2.filterUi,
          () => _getFilterModel(this.model, colId),
          () => this.state.get(colId),
          (state) => this.updateState(column2, state),
          (model2) => {
            this.updateStoredModel(colId, model2);
            this.dispatchLocalEvent({
              type: "filterAction",
              column: column2,
              action
            });
            promises.push(this.refreshHandlerAndUi(column2, model2, "ui"));
          },
          filter2?.isHandler ? filter2.handler.processModelToApply?.bind(filter2.handler) : void 0
        );
      }
    });
    if (promises.length) {
      AgPromise.all(promises).then(() => {
        this.callOnFilterChangedOutsideRenderCycle({
          source: "columnFilter",
          additionalEventAttributes,
          columns: []
        });
      });
    }
  }
  updateOrRefreshFilterUi(column2) {
    const colId = column2.getColId();
    getAndRefreshFilterUi(
      () => this.cachedFilter(column2)?.filterUi,
      () => _getFilterModel(this.model, colId),
      () => this.state.get(colId)
    );
  }
  updateState(column2, state) {
    this.state.set(column2.getColId(), state);
    this.dispatchLocalEvent({
      type: "filterStateChanged",
      column: column2,
      state
    });
  }
  // for tool panel only
  canApplyAll() {
    const { state, model: model2, activeFilterComps } = this;
    for (const comp of activeFilterComps) {
      if (comp.source === "COLUMN_MENU") {
        return false;
      }
    }
    let hasChanges = false;
    for (const colId of state.keys()) {
      const colState = state.get(colId);
      if (colState.valid === false) {
        return false;
      }
      if ((colState.model ?? null) !== _getFilterModel(model2, colId)) {
        hasChanges = true;
      }
    }
    return hasChanges;
  }
  hasUnappliedModel(colId) {
    const { model: model2, state } = this;
    return (state.get(colId)?.model ?? null) !== _getFilterModel(model2, colId);
  }
  setGlobalButtons(isGlobal) {
    this.isGlobalButtons = isGlobal;
    this.dispatchLocalEvent({
      type: "filterGlobalButtons",
      isGlobal
    });
  }
  shouldKeepStateOnDetach(column2, lastContainerType) {
    if (lastContainerType === "newFiltersToolPanel") {
      return true;
    }
    const filterPanelSvc = this.beans.filterPanelSvc;
    if (filterPanelSvc?.isActive) {
      return !!filterPanelSvc.getState(column2.getColId());
    }
    return false;
  }
  destroy() {
    super.destroy();
    this.allColumnFilters.forEach((filterWrapper) => this.disposeFilterWrapper(filterWrapper, "gridDestroyed"));
    this.allColumnListeners.clear();
    this.state.clear();
    this.activeFilterComps.clear();
  }
};
function isAnyFilterPresent(beans) {
  return !!beans.filterManager?.isAnyFilterPresent();
}
function onFilterChanged(beans, source2 = "api") {
  beans.filterManager?.onFilterChanged({ source: source2 });
}
var FilterManager = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "filterManager";
    this.advFilterModelUpdateQueue = [];
  }
  wireBeans(beans) {
    this.quickFilter = beans.quickFilter;
    this.advancedFilter = beans.advancedFilter;
    this.colFilter = beans.colFilter;
  }
  postConstruct() {
    const refreshFiltersForAggregations = this.refreshFiltersForAggregations.bind(this);
    const updateAdvFilterColumns = this.updateAdvFilterColumns.bind(this);
    this.addManagedEventListeners({
      columnValueChanged: refreshFiltersForAggregations,
      columnPivotChanged: refreshFiltersForAggregations,
      columnPivotModeChanged: refreshFiltersForAggregations,
      newColumnsLoaded: updateAdvFilterColumns,
      columnVisible: updateAdvFilterColumns,
      advancedFilterEnabledChanged: ({ enabled }) => this.onAdvFilterEnabledChanged(enabled),
      dataTypesInferred: this.processFilterModelUpdateQueue.bind(this)
    });
    this.externalFilterPresent = this.isExternalFilterPresentCallback();
    this.addManagedPropertyListeners(["isExternalFilterPresent", "doesExternalFilterPass"], () => {
      this.onFilterChanged({ source: "api" });
    });
    this.updateAggFiltering();
    this.addManagedPropertyListener("groupAggFiltering", () => {
      this.updateAggFiltering();
      this.onFilterChanged();
    });
    if (this.quickFilter) {
      this.addManagedListeners(this.quickFilter, {
        quickFilterChanged: () => this.onFilterChanged({ source: "quickFilter" })
      });
    }
    const { gos } = this;
    this.alwaysPassFilter = gos.get("alwaysPassFilter");
    this.addManagedPropertyListener("alwaysPassFilter", () => {
      this.alwaysPassFilter = gos.get("alwaysPassFilter");
      this.onFilterChanged({ source: "api" });
    });
  }
  isExternalFilterPresentCallback() {
    const isFilterPresent = this.gos.getCallback("isExternalFilterPresent");
    return typeof isFilterPresent === "function" && isFilterPresent({});
  }
  doesExternalFilterPass(node2) {
    const doesFilterPass = this.gos.get("doesExternalFilterPass");
    return typeof doesFilterPass === "function" && doesFilterPass(node2);
  }
  setFilterState(model2, state, source2 = "api") {
    if (this.isAdvFilterEnabled()) {
      return;
    }
    this.colFilter?.setState(model2, state, source2);
  }
  setFilterModel(model2, source2 = "api", skipWarning) {
    if (this.isAdvFilterEnabled()) {
      if (!skipWarning) {
        this.warnAdvFilters();
      }
      return;
    }
    this.colFilter?.setModel(model2, source2);
  }
  getFilterModel() {
    return this.colFilter?.getModel() ?? {};
  }
  getFilterState() {
    return this.colFilter?.getState();
  }
  isColumnFilterPresent() {
    return !!this.colFilter?.isFilterPresent();
  }
  isAggregateFilterPresent() {
    return !!this.colFilter?.isAggFilterPresent();
  }
  isChildFilterPresent() {
    return this.isColumnFilterPresent() || this.isQuickFilterPresent() || this.externalFilterPresent || this.isAdvFilterPresent();
  }
  isAnyFilterPresent() {
    return this.isChildFilterPresent() || this.isAggregateFilterPresent();
  }
  isAdvFilterPresent() {
    return this.isAdvFilterEnabled() && this.advancedFilter.isFilterPresent();
  }
  onAdvFilterEnabledChanged(enabled) {
    if (enabled) {
      if (this.colFilter?.disableFilters()) {
        this.onFilterChanged({ source: "advancedFilter" });
      }
    } else if (this.advancedFilter?.isFilterPresent()) {
      this.advancedFilter.setModel(null);
      this.onFilterChanged({ source: "advancedFilter" });
    }
  }
  isAdvFilterEnabled() {
    return !!this.advancedFilter?.isEnabled();
  }
  isAdvFilterHeaderActive() {
    return this.isAdvFilterEnabled() && this.advancedFilter.isHeaderActive();
  }
  refreshFiltersForAggregations() {
    if (_getGroupAggFiltering(this.gos) && this.isAnyFilterPresent()) {
      this.onFilterChanged();
    }
  }
  onFilterChanged(params = {}) {
    const { source: source2, additionalEventAttributes, columns: columns2 = [] } = params;
    this.externalFilterPresent = this.isExternalFilterPresentCallback();
    (this.colFilter ? this.colFilter.updateBeforeFilterChanged(params) : AgPromise.resolve()).then(() => {
      const filterChangedEvent = {
        source: source2,
        type: "filterChanged",
        columns: columns2
      };
      if (additionalEventAttributes) {
        _mergeDeep(filterChangedEvent, additionalEventAttributes);
      }
      this.eventSvc.dispatchEvent(filterChangedEvent);
      this.colFilter?.updateAfterFilterChanged();
    });
  }
  isSuppressFlashingCellsBecauseFiltering() {
    return !!this.colFilter?.isSuppressFlashingCellsBecauseFiltering();
  }
  isQuickFilterPresent() {
    return !!this.quickFilter?.isFilterPresent();
  }
  updateAggFiltering() {
    this.aggFiltering = !!_getGroupAggFiltering(this.gos);
  }
  isAggregateQuickFilterPresent() {
    return this.isQuickFilterPresent() && this.shouldApplyQuickFilterAfterAgg();
  }
  isNonAggregateQuickFilterPresent() {
    return this.isQuickFilterPresent() && !this.shouldApplyQuickFilterAfterAgg();
  }
  shouldApplyQuickFilterAfterAgg() {
    return (this.aggFiltering || this.beans.colModel.isPivotMode()) && !this.gos.get("applyQuickFilterBeforePivotOrAgg");
  }
  doesRowPassOtherFilters(colIdToSkip, rowNode) {
    return this.doesRowPassFilter({ rowNode, colIdToSkip });
  }
  doesRowPassAggregateFilters(params) {
    const { rowNode } = params;
    if (this.alwaysPassFilter?.(rowNode)) {
      return true;
    }
    if (this.isAggregateQuickFilterPresent() && !this.quickFilter.doesRowPass(rowNode)) {
      return false;
    }
    if (this.isAggregateFilterPresent() && !this.colFilter.doFiltersPass(rowNode, params.colIdToSkip, true)) {
      return false;
    }
    return true;
  }
  doesRowPassFilter(params) {
    const { rowNode } = params;
    if (this.alwaysPassFilter?.(rowNode)) {
      return true;
    }
    if (this.isNonAggregateQuickFilterPresent() && !this.quickFilter.doesRowPass(rowNode)) {
      return false;
    }
    if (this.externalFilterPresent && !this.doesExternalFilterPass(rowNode)) {
      return false;
    }
    if (this.isColumnFilterPresent() && !this.colFilter.doFiltersPass(rowNode, params.colIdToSkip)) {
      return false;
    }
    if (this.isAdvFilterPresent() && !this.advancedFilter.doesFilterPass(rowNode)) {
      return false;
    }
    return true;
  }
  // for group filters, can change dynamically whether they are allowed or not
  isFilterAllowed(column2) {
    if (this.isAdvFilterEnabled()) {
      return false;
    }
    return !!this.colFilter?.isFilterAllowed(column2);
  }
  getAdvFilterModel() {
    return this.isAdvFilterEnabled() ? this.advancedFilter.getModel() : null;
  }
  setAdvFilterModel(expression, source2 = "api") {
    if (!this.isAdvFilterEnabled()) {
      return;
    }
    if (this.beans.dataTypeSvc?.isPendingInference) {
      this.advFilterModelUpdateQueue.push(expression);
      return;
    }
    this.advancedFilter.setModel(expression ?? null);
    this.onFilterChanged({ source: source2 });
  }
  toggleAdvFilterBuilder(show, source2) {
    if (!this.isAdvFilterEnabled()) {
      return;
    }
    this.advancedFilter.getCtrl().toggleFilterBuilder({ source: source2, force: show });
  }
  updateAdvFilterColumns() {
    if (!this.isAdvFilterEnabled()) {
      return;
    }
    if (this.advancedFilter.updateValidity()) {
      this.onFilterChanged({ source: "advancedFilter" });
    }
  }
  hasFloatingFilters() {
    if (this.isAdvFilterEnabled()) {
      return false;
    }
    return !!this.colFilter?.hasFloatingFilters();
  }
  getColumnFilterInstance(key2) {
    if (this.isAdvFilterEnabled()) {
      this.warnAdvFilters();
      return Promise.resolve(void 0);
    }
    return this.colFilter?.getFilterInstance(key2) ?? Promise.resolve(void 0);
  }
  warnAdvFilters() {
    _warn(68);
  }
  setupAdvFilterHeaderComp(eCompToInsertBefore) {
    this.advancedFilter?.getCtrl().setupHeaderComp(eCompToInsertBefore);
  }
  getHeaderRowCount() {
    return this.isAdvFilterHeaderActive() ? 1 : 0;
  }
  getHeaderHeight() {
    return this.isAdvFilterHeaderActive() ? this.advancedFilter.getCtrl().getHeaderHeight() : 0;
  }
  processFilterModelUpdateQueue() {
    for (const model2 of this.advFilterModelUpdateQueue) {
      this.setAdvFilterModel(model2);
    }
    this.advFilterModelUpdateQueue = [];
  }
  setColumnFilterModel(key2, model2) {
    if (this.isAdvFilterEnabled()) {
      this.warnAdvFilters();
      return Promise.resolve();
    }
    return this.colFilter?.setModelForColumn(key2, model2) ?? Promise.resolve();
  }
};
var FilterMenuFactory = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "filterMenuFactory";
  }
  wireBeans(beans) {
    this.popupSvc = beans.popupSvc;
  }
  hideActiveMenu() {
    this.hidePopup?.();
  }
  showMenuAfterMouseEvent(column2, mouseEvent, containerType, onClosedCallback) {
    if (column2 && !column2.isColumn) {
      return;
    }
    this.showPopup(
      column2,
      (eMenu) => {
        this.popupSvc?.positionPopupUnderMouseEvent({
          column: column2,
          type: containerType,
          mouseEvent,
          ePopup: eMenu
        });
      },
      containerType,
      mouseEvent.target,
      _isLegacyMenuEnabled(this.gos),
      onClosedCallback
    );
  }
  showMenuAfterButtonClick(column2, eventSource, containerType, onClosedCallback) {
    if (column2 && !column2.isColumn) {
      return;
    }
    let multiplier = -1;
    let alignSide = "left";
    const isLegacyMenuEnabled = _isLegacyMenuEnabled(this.gos);
    if (!isLegacyMenuEnabled && this.gos.get("enableRtl")) {
      multiplier = 1;
      alignSide = "right";
    }
    const nudgeX = isLegacyMenuEnabled ? void 0 : 4 * multiplier;
    const nudgeY = isLegacyMenuEnabled ? void 0 : 4;
    this.showPopup(
      column2,
      (eMenu) => {
        this.popupSvc?.positionPopupByComponent({
          type: containerType,
          eventSource,
          ePopup: eMenu,
          nudgeX,
          nudgeY,
          alignSide,
          keepWithinBounds: true,
          position: "under",
          column: column2
        });
      },
      containerType,
      eventSource,
      isLegacyMenuEnabled,
      onClosedCallback
    );
  }
  showPopup(column2, positionCallback, containerType, eventSource, isLegacyMenuEnabled, onClosedCallback) {
    const comp = column2 ? this.createBean(new FilterComp(column2, "COLUMN_MENU")) : void 0;
    this.activeMenu = comp;
    if (!comp?.hasFilter() || !column2) {
      _error(57);
      return;
    }
    const eMenu = _createElement({
      tag: "div",
      cls: `ag-menu${!isLegacyMenuEnabled ? " ag-filter-menu" : ""}`,
      role: "presentation"
    });
    [this.tabListener] = this.addManagedElementListeners(eMenu, {
      keydown: (e) => this.trapFocusWithin(e, eMenu)
    });
    eMenu.appendChild(comp?.getGui());
    let hidePopup;
    const afterGuiDetached = () => comp?.afterGuiDetached();
    const anchorToElement = _isColumnMenuAnchoringEnabled(this.gos) ? eventSource ?? this.beans.ctrlsSvc.getGridBodyCtrl().eGridBody : void 0;
    const closedCallback = (e) => {
      _setColMenuVisible(column2, false, "contextMenu");
      const isKeyboardEvent = e instanceof KeyboardEvent;
      if (this.tabListener) {
        this.tabListener = this.tabListener();
      }
      if (isKeyboardEvent && eventSource && _isVisible(eventSource)) {
        const focusableEl = _findTabbableParent(eventSource);
        focusableEl?.focus({ preventScroll: true });
      }
      afterGuiDetached();
      this.destroyBean(this.activeMenu);
      this.dispatchVisibleChangedEvent(false, containerType, column2);
      onClosedCallback?.();
    };
    const translate = this.getLocaleTextFunc();
    const ariaLabel = isLegacyMenuEnabled && containerType !== "columnFilter" ? translate("ariaLabelColumnMenu", "Column Menu") : translate("ariaLabelColumnFilter", "Column Filter");
    const addPopupRes = this.popupSvc?.addPopup({
      modal: true,
      eChild: eMenu,
      closeOnEsc: true,
      closedCallback,
      positionCallback: () => positionCallback(eMenu),
      anchorToElement,
      ariaLabel
    });
    if (addPopupRes) {
      this.hidePopup = hidePopup = addPopupRes.hideFunc;
    }
    comp.afterInit().then(() => {
      positionCallback(eMenu);
      comp.afterGuiAttached({ container: containerType, hidePopup });
    });
    _setColMenuVisible(column2, true, "contextMenu");
    this.dispatchVisibleChangedEvent(true, containerType, column2);
  }
  trapFocusWithin(e, menu) {
    if (e.key !== KeyCode.TAB || e.defaultPrevented || _findNextFocusableElement(this.beans, menu, false, e.shiftKey)) {
      return;
    }
    e.preventDefault();
    _focusInto(menu, e.shiftKey);
  }
  dispatchVisibleChangedEvent(visible2, containerType, column2) {
    this.eventSvc.dispatchEvent({
      type: "columnMenuVisibleChanged",
      visible: visible2,
      switchingTab: false,
      key: containerType,
      column: column2 ?? null,
      columnGroup: null
    });
  }
  isMenuEnabled(column2) {
    return column2.isFilterAllowed() && (column2.getColDef().menuTabs ?? ["filterMenuTab"]).includes("filterMenuTab");
  }
  showMenuAfterContextMenuEvent() {
  }
  destroy() {
    this.destroyBean(this.activeMenu);
    super.destroy();
  }
};
var FilterValueService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "filterValueSvc";
  }
  getValue(column2, rowNode, filterValueGetterOverride) {
    if (!rowNode) {
      return;
    }
    const colDef = column2.getColDef();
    const { selectableFilter, valueSvc } = this.beans;
    const filterValueGetter = filterValueGetterOverride ?? selectableFilter?.getFilterValueGetter(column2.getColId()) ?? colDef.filterValueGetter;
    if (filterValueGetter) {
      return this.executeFilterValueGetter(filterValueGetter, rowNode.data, column2, rowNode, colDef);
    }
    return valueSvc.getValue(column2, rowNode);
  }
  executeFilterValueGetter(valueGetter, data2, column2, node2, colDef) {
    const { expressionSvc, valueSvc } = this.beans;
    const params = _addGridCommonParams(this.gos, {
      data: data2,
      node: node2,
      column: column2,
      colDef,
      getValue: valueSvc.getValueCallback.bind(valueSvc, node2)
    });
    if (typeof valueGetter === "function") {
      return valueGetter(params);
    }
    return expressionSvc?.evaluate(valueGetter, params);
  }
};
var ReadOnlyFloatingFilterElement = {
  tag: "div",
  cls: "ag-floating-filter-input",
  role: "presentation",
  children: [
    {
      tag: "ag-input-text-field",
      ref: "eFloatingFilterText"
    }
  ]
};
var ReadOnlyFloatingFilter = class extends Component {
  constructor() {
    super(ReadOnlyFloatingFilterElement, [AgInputTextFieldSelector]);
    this.eFloatingFilterText = RefPlaceholder;
  }
  init(params) {
    this.params = params;
    const displayName = this.beans.colNames.getDisplayNameForColumn(params.column, "header", true);
    this.eFloatingFilterText.setDisabled(true).setInputAriaLabel(`${displayName} ${this.getLocaleTextFunc()("ariaFilterInput", "Filter Input")}`);
    if (this.gos.get("enableFilterHandlers")) {
      const reactiveParams = params;
      const handler = reactiveParams.getHandler();
      if (handler.getModelAsString) {
        const modelAsString = handler.getModelAsString(reactiveParams.model);
        this.eFloatingFilterText.setValue(modelAsString);
      }
    }
  }
  onParentModelChanged(parentModel) {
    if (parentModel == null) {
      this.eFloatingFilterText.setValue("");
      return;
    }
    this.params.parentFilterInstance((filterInstance) => {
      if (filterInstance.getModelAsString) {
        const modelAsString = filterInstance.getModelAsString(parentModel);
        this.eFloatingFilterText.setValue(modelAsString);
      }
    });
  }
  refresh(params) {
    this.init(params);
  }
};
var OptionsFactory = class {
  constructor() {
    this.customFilterOptions = {};
  }
  init(params, defaultOptions2) {
    this.filterOptions = params.filterOptions ?? defaultOptions2;
    this.mapCustomOptions();
    this.defaultOption = this.getDefaultItem(params.defaultOption);
  }
  refresh(params, defaultOptions2) {
    const filterOptions = params.filterOptions ?? defaultOptions2;
    if (this.filterOptions !== filterOptions) {
      this.filterOptions = filterOptions;
      this.customFilterOptions = {};
      this.mapCustomOptions();
    }
    this.defaultOption = this.getDefaultItem(params.defaultOption);
  }
  mapCustomOptions() {
    const { filterOptions } = this;
    if (!filterOptions) {
      return;
    }
    for (const filterOption of filterOptions) {
      if (typeof filterOption === "string") {
        continue;
      }
      const requiredProperties = [["displayKey"], ["displayName"], ["predicate", "test"]];
      const propertyCheck = (keys2) => {
        if (!keys2.some((key2) => filterOption[key2] != null)) {
          _warn(72, { keys: keys2 });
          return false;
        }
        return true;
      };
      if (!requiredProperties.every(propertyCheck)) {
        this.filterOptions = filterOptions.filter((v) => v === filterOption) || [];
        continue;
      }
      this.customFilterOptions[filterOption.displayKey] = filterOption;
    }
  }
  getDefaultItem(defaultOption) {
    const { filterOptions } = this;
    if (defaultOption) {
      return defaultOption;
    } else if (filterOptions.length >= 1) {
      const firstFilterOption = filterOptions[0];
      if (typeof firstFilterOption === "string") {
        return firstFilterOption;
      } else if (firstFilterOption.displayKey) {
        return firstFilterOption.displayKey;
      } else {
        _warn(73);
      }
    } else {
      _warn(74);
    }
    return void 0;
  }
  getCustomOption(name2) {
    return this.customFilterOptions[name2];
  }
};
function removeItems(items, startPosition, deleteCount) {
  return deleteCount == null ? items.splice(startPosition) : items.splice(startPosition, deleteCount);
}
function isBlank(cellValue) {
  return cellValue == null || typeof cellValue === "string" && cellValue.trim().length === 0;
}
function getDefaultJoinOperator(defaultJoinOperator) {
  return defaultJoinOperator === "AND" || defaultJoinOperator === "OR" ? defaultJoinOperator : "AND";
}
function evaluateCustomFilter(customFilterOption, values2, cellValue) {
  if (customFilterOption == null) {
    return;
  }
  const { predicate } = customFilterOption;
  if (predicate != null && !values2.some((v) => v == null)) {
    return predicate(values2, cellValue);
  }
}
function validateAndUpdateConditions(conditions, maxNumConditions) {
  let numConditions = conditions.length;
  if (numConditions > maxNumConditions) {
    conditions.splice(maxNumConditions);
    _warn(78);
    numConditions = maxNumConditions;
  }
  return numConditions;
}
function getNumberOfInputs(type, optionsFactory) {
  const customOpts = optionsFactory.getCustomOption(type);
  if (customOpts) {
    const { numberOfInputs } = customOpts;
    return numberOfInputs != null ? numberOfInputs : 1;
  }
  const zeroInputTypes = ["empty", "notBlank", "blank"];
  if (type && zeroInputTypes.indexOf(type) >= 0) {
    return 0;
  } else if (type === "inRange") {
    return 2;
  }
  return 1;
}
var SimpleFilter = class extends ProvidedFilter {
  constructor(filterNameKey, mapValuesFromModel, defaultOptions2) {
    super(filterNameKey, "simple-filter");
    this.mapValuesFromModel = mapValuesFromModel;
    this.defaultOptions = defaultOptions2;
    this.eTypes = [];
    this.eJoinPanels = [];
    this.eJoinAnds = [];
    this.eJoinOrs = [];
    this.eConditionBodies = [];
    this.listener = () => this.onUiChanged();
    this.lastUiCompletePosition = null;
    this.joinOperatorId = 0;
  }
  setParams(params) {
    super.setParams(params);
    const optionsFactory = new OptionsFactory();
    this.optionsFactory = optionsFactory;
    optionsFactory.init(params, this.defaultOptions);
    this.commonUpdateSimpleParams(params);
    this.createOption();
    this.createMissingConditionsAndOperators();
  }
  updateParams(newParams, oldParams) {
    this.optionsFactory.refresh(newParams, this.defaultOptions);
    super.updateParams(newParams, oldParams);
    this.commonUpdateSimpleParams(newParams);
  }
  commonUpdateSimpleParams(params) {
    this.setNumConditions(params);
    this.defaultJoinOperator = getDefaultJoinOperator(params.defaultJoinOperator);
    this.filterPlaceholder = params.filterPlaceholder;
    this.createFilterListOptions();
    const eGui = this.getGui();
    if (this.isReadOnly()) {
      eGui.setAttribute("tabindex", "-1");
    } else {
      eGui.removeAttribute("tabindex");
    }
  }
  // floating filter calls this when user applies filter from floating filter
  onFloatingFilterChanged(type, value2) {
    this.setTypeFromFloatingFilter(type);
    this.setValueFromFloatingFilter(value2);
    this.onUiChanged("immediately", true);
  }
  setTypeFromFloatingFilter(type) {
    this.eTypes.forEach((eType, position) => {
      const value2 = position === 0 ? type : this.optionsFactory.defaultOption;
      eType.setValue(value2, true);
    });
  }
  getModelFromUi() {
    const conditions = this.getUiCompleteConditions();
    if (conditions.length === 0) {
      return null;
    }
    if (this.maxNumConditions > 1 && conditions.length > 1) {
      return {
        filterType: this.filterType,
        operator: this.getJoinOperator(),
        conditions
      };
    }
    return conditions[0];
  }
  getConditionTypes() {
    return this.eTypes.map((eType) => eType.getValue());
  }
  getConditionType(position) {
    return this.eTypes[position].getValue();
  }
  getJoinOperator() {
    const { eJoinOrs: eJoinOperatorsOr, defaultJoinOperator } = this;
    return eJoinOperatorsOr.length === 0 ? defaultJoinOperator : eJoinOperatorsOr[0].getValue() === true ? "OR" : "AND";
  }
  areNonNullModelsEqual(a2, b) {
    const aIsSimple = !a2.operator;
    const bIsSimple = !b.operator;
    const oneSimpleOneCombined = !aIsSimple && bIsSimple || aIsSimple && !bIsSimple;
    if (oneSimpleOneCombined) {
      return false;
    }
    let res;
    if (aIsSimple) {
      const aSimple = a2;
      const bSimple = b;
      res = this.areSimpleModelsEqual(aSimple, bSimple);
    } else {
      const aCombined = a2;
      const bCombined = b;
      res = aCombined.operator === bCombined.operator && _areEqual(
        aCombined.conditions,
        bCombined.conditions,
        (aModel, bModel) => this.areSimpleModelsEqual(aModel, bModel)
      );
    }
    return res;
  }
  setModelIntoUi(model2, isInitialLoad) {
    if (model2 == null) {
      this.resetUiToDefaults(isInitialLoad);
      return AgPromise.resolve();
    }
    const isCombined = model2.operator;
    if (isCombined) {
      const combinedModel = model2;
      let conditions = combinedModel.conditions;
      if (conditions == null) {
        conditions = [];
        _warn(77);
      }
      const numConditions = validateAndUpdateConditions(conditions, this.maxNumConditions);
      const numPrevConditions = this.getNumConditions();
      if (numConditions < numPrevConditions) {
        this.removeConditionsAndOperators(numConditions);
      } else if (numConditions > numPrevConditions) {
        for (let i2 = numPrevConditions; i2 < numConditions; i2++) {
          this.createJoinOperatorPanel();
          this.createOption();
        }
      }
      const orChecked = combinedModel.operator === "OR";
      this.eJoinAnds.forEach((eJoinOperatorAnd) => eJoinOperatorAnd.setValue(!orChecked, true));
      this.eJoinOrs.forEach((eJoinOperatorOr) => eJoinOperatorOr.setValue(orChecked, true));
      conditions.forEach((condition, position) => {
        this.eTypes[position].setValue(condition.type, true);
        this.setConditionIntoUi(condition, position);
      });
    } else {
      const simpleModel = model2;
      if (this.getNumConditions() > 1) {
        this.removeConditionsAndOperators(1);
      }
      this.eTypes[0].setValue(simpleModel.type, true);
      this.setConditionIntoUi(simpleModel, 0);
    }
    this.lastUiCompletePosition = this.getNumConditions() - 1;
    this.createMissingConditionsAndOperators();
    this.updateUiVisibility();
    if (!isInitialLoad) {
      this.params.onUiChange(this.getUiChangeEventParams());
    }
    return AgPromise.resolve();
  }
  setNumConditions(params) {
    let maxNumConditions = params.maxNumConditions ?? 2;
    if (maxNumConditions < 1) {
      _warn(79);
      maxNumConditions = 1;
    }
    this.maxNumConditions = maxNumConditions;
    let numAlwaysVisibleConditions = params.numAlwaysVisibleConditions ?? 1;
    if (numAlwaysVisibleConditions < 1) {
      _warn(80);
      numAlwaysVisibleConditions = 1;
    }
    if (numAlwaysVisibleConditions > maxNumConditions) {
      _warn(81);
      numAlwaysVisibleConditions = maxNumConditions;
    }
    this.numAlwaysVisibleConditions = numAlwaysVisibleConditions;
  }
  createOption() {
    const eGui = this.getGui();
    const eType = this.createManagedBean(new AgSelect());
    this.eTypes.push(eType);
    eType.addCss("ag-filter-select");
    eGui.appendChild(eType.getGui());
    const eConditionBody = this.createEValue();
    this.eConditionBodies.push(eConditionBody);
    eGui.appendChild(eConditionBody);
    this.putOptionsIntoDropdown(eType);
    this.resetType(eType);
    const position = this.getNumConditions() - 1;
    this.forEachPositionInput(position, (element) => this.resetInput(element));
    this.addChangedListeners(eType, position);
  }
  createJoinOperatorPanel() {
    const eJoinOperatorPanel = _createElement({ tag: "div", cls: "ag-filter-condition" });
    this.eJoinPanels.push(eJoinOperatorPanel);
    const eJoinOperatorAnd = this.createJoinOperator(this.eJoinAnds, eJoinOperatorPanel, "and");
    const eJoinOperatorOr = this.createJoinOperator(this.eJoinOrs, eJoinOperatorPanel, "or");
    this.getGui().appendChild(eJoinOperatorPanel);
    const index = this.eJoinPanels.length - 1;
    const uniqueGroupId = this.joinOperatorId++;
    this.resetJoinOperatorAnd(eJoinOperatorAnd, index, uniqueGroupId);
    this.resetJoinOperatorOr(eJoinOperatorOr, index, uniqueGroupId);
    if (!this.isReadOnly()) {
      eJoinOperatorAnd.onValueChange(this.listener);
      eJoinOperatorOr.onValueChange(this.listener);
    }
  }
  createJoinOperator(eJoinOperators, eJoinOperatorPanel, andOr) {
    const eJoinOperator = this.createManagedBean(new AgRadioButton());
    eJoinOperators.push(eJoinOperator);
    const baseClass = "ag-filter-condition-operator";
    eJoinOperator.addCss(baseClass);
    eJoinOperator.addCss(`${baseClass}-${andOr}`);
    eJoinOperatorPanel.appendChild(eJoinOperator.getGui());
    return eJoinOperator;
  }
  createFilterListOptions() {
    this.filterListOptions = this.optionsFactory.filterOptions.map(
      (option) => typeof option === "string" ? this.createBoilerplateListOption(option) : this.createCustomListOption(option)
    );
  }
  putOptionsIntoDropdown(eType) {
    const { filterListOptions } = this;
    for (const listOption of filterListOptions) {
      eType.addOption(listOption);
    }
    eType.setDisabled(filterListOptions.length <= 1);
  }
  createBoilerplateListOption(option) {
    return { value: option, text: this.translate(option) };
  }
  createCustomListOption(option) {
    const { displayKey } = option;
    const customOption = this.optionsFactory.getCustomOption(option.displayKey);
    return {
      value: displayKey,
      text: customOption ? this.getLocaleTextFunc()(customOption.displayKey, customOption.displayName) : this.translate(displayKey)
    };
  }
  createBodyTemplate() {
    return null;
  }
  getAgComponents() {
    return [];
  }
  updateUiVisibility() {
    const joinOperator = this.getJoinOperator();
    this.updateNumConditions();
    this.updateConditionStatusesAndValues(this.lastUiCompletePosition, joinOperator);
  }
  updateNumConditions() {
    let lastUiCompletePosition = -1;
    let areAllConditionsUiComplete = true;
    for (let position = 0; position < this.getNumConditions(); position++) {
      if (this.isConditionUiComplete(position)) {
        lastUiCompletePosition = position;
      } else {
        areAllConditionsUiComplete = false;
      }
    }
    if (this.shouldAddNewConditionAtEnd(areAllConditionsUiComplete)) {
      this.createJoinOperatorPanel();
      this.createOption();
    } else {
      const activePosition = this.lastUiCompletePosition ?? this.getNumConditions() - 2;
      if (lastUiCompletePosition < activePosition) {
        this.removeConditionsAndOperators(activePosition + 1);
        const removeStartPosition = lastUiCompletePosition + 1;
        const numConditionsToRemove = activePosition - removeStartPosition;
        if (numConditionsToRemove > 0) {
          this.removeConditionsAndOperators(removeStartPosition, numConditionsToRemove);
        }
        this.createMissingConditionsAndOperators();
      }
    }
    this.lastUiCompletePosition = lastUiCompletePosition;
  }
  updateConditionStatusesAndValues(lastUiCompletePosition, joinOperator) {
    this.eTypes.forEach((eType, position) => {
      const disabled2 = this.isConditionDisabled(position, lastUiCompletePosition);
      eType.setDisabled(disabled2 || this.filterListOptions.length <= 1);
      if (position === 1) {
        _setDisabled(this.eJoinPanels[0], disabled2);
        this.eJoinAnds[0].setDisabled(disabled2);
        this.eJoinOrs[0].setDisabled(disabled2);
      }
    });
    this.eConditionBodies.forEach((element, index) => {
      _setDisplayed(element, this.isConditionBodyVisible(index));
    });
    const orChecked = (joinOperator ?? this.getJoinOperator()) === "OR";
    for (const eJoinOperatorAnd of this.eJoinAnds) {
      eJoinOperatorAnd.setValue(!orChecked, true);
    }
    for (const eJoinOperatorOr of this.eJoinOrs) {
      eJoinOperatorOr.setValue(orChecked, true);
    }
    this.forEachInput((element, index, position, numberOfInputs) => {
      this.setElementDisplayed(element, index < numberOfInputs);
      this.setElementDisabled(element, this.isConditionDisabled(position, lastUiCompletePosition));
    });
    this.resetPlaceholder();
  }
  shouldAddNewConditionAtEnd(areAllConditionsUiComplete) {
    return areAllConditionsUiComplete && this.getNumConditions() < this.maxNumConditions && !this.isReadOnly();
  }
  removeConditionsAndOperators(startPosition, deleteCount) {
    if (startPosition >= this.getNumConditions()) {
      return;
    }
    const {
      eTypes,
      eConditionBodies,
      eJoinPanels: eJoinOperatorPanels,
      eJoinAnds: eJoinOperatorsAnd,
      eJoinOrs: eJoinOperatorsOr
    } = this;
    this.removeComponents(eTypes, startPosition, deleteCount);
    this.removeElements(eConditionBodies, startPosition, deleteCount);
    this.removeEValues(startPosition, deleteCount);
    const joinOperatorIndex = Math.max(startPosition - 1, 0);
    this.removeElements(eJoinOperatorPanels, joinOperatorIndex, deleteCount);
    this.removeComponents(eJoinOperatorsAnd, joinOperatorIndex, deleteCount);
    this.removeComponents(eJoinOperatorsOr, joinOperatorIndex, deleteCount);
  }
  removeElements(elements, startPosition, deleteCount) {
    const removedElements = removeItems(elements, startPosition, deleteCount);
    for (const element of removedElements) {
      _removeFromParent(element);
    }
  }
  removeComponents(components, startPosition, deleteCount) {
    const removedComponents = removeItems(components, startPosition, deleteCount);
    for (const comp of removedComponents) {
      _removeFromParent(comp.getGui());
      this.destroyBean(comp);
    }
  }
  afterGuiAttached(params) {
    super.afterGuiAttached(params);
    this.resetPlaceholder();
    if (!params?.suppressFocus) {
      let elementToFocus;
      if (!this.isReadOnly()) {
        const firstInput = this.getInputs(0)[0];
        if (firstInput instanceof AgAbstractInputField && this.isConditionBodyVisible(0)) {
          elementToFocus = firstInput.getInputElement();
        } else {
          elementToFocus = this.eTypes[0]?.getFocusableElement();
        }
      }
      (elementToFocus ?? this.getGui()).focus({ preventScroll: true });
    }
  }
  afterGuiDetached() {
    super.afterGuiDetached();
    const params = this.params;
    if (this.beans.colFilter?.shouldKeepStateOnDetach(params.column)) {
      return;
    }
    params.onStateChange({
      model: params.model
    });
    let lastUiCompletePosition = -1;
    let updatedLastUiCompletePosition = -1;
    let conditionsRemoved = false;
    const joinOperator = this.getJoinOperator();
    for (let position = this.getNumConditions() - 1; position >= 0; position--) {
      if (this.isConditionUiComplete(position)) {
        if (lastUiCompletePosition === -1) {
          lastUiCompletePosition = position;
          updatedLastUiCompletePosition = position;
        }
      } else {
        const shouldRemovePositionAtEnd = position >= this.numAlwaysVisibleConditions && !this.isConditionUiComplete(position - 1);
        const positionBeforeLastUiCompletePosition = position < lastUiCompletePosition;
        if (shouldRemovePositionAtEnd || positionBeforeLastUiCompletePosition) {
          this.removeConditionsAndOperators(position, 1);
          conditionsRemoved = true;
          if (positionBeforeLastUiCompletePosition) {
            updatedLastUiCompletePosition--;
          }
        }
      }
    }
    let shouldUpdateConditionStatusesAndValues = false;
    if (this.getNumConditions() < this.numAlwaysVisibleConditions) {
      this.createMissingConditionsAndOperators();
      shouldUpdateConditionStatusesAndValues = true;
    }
    if (this.shouldAddNewConditionAtEnd(updatedLastUiCompletePosition === this.getNumConditions() - 1)) {
      this.createJoinOperatorPanel();
      this.createOption();
      shouldUpdateConditionStatusesAndValues = true;
    }
    if (shouldUpdateConditionStatusesAndValues) {
      this.updateConditionStatusesAndValues(updatedLastUiCompletePosition, joinOperator);
    }
    if (conditionsRemoved) {
      this.updateJoinOperatorsDisabled();
    }
    this.lastUiCompletePosition = updatedLastUiCompletePosition;
  }
  getModelAsString(model2) {
    return this.params.getHandler()?.getModelAsString?.(model2) ?? "";
  }
  getPlaceholderText(defaultPlaceholder, position) {
    let placeholder = this.translate(defaultPlaceholder);
    if (typeof this.filterPlaceholder === "function") {
      const filterOptionKey = this.eTypes[position].getValue();
      const filterOption = this.translate(filterOptionKey);
      placeholder = this.filterPlaceholder({
        filterOptionKey,
        filterOption,
        placeholder
      });
    } else if (typeof this.filterPlaceholder === "string") {
      placeholder = this.filterPlaceholder;
    }
    return placeholder;
  }
  // allow sub-classes to reset HTML placeholders after UI update.
  resetPlaceholder() {
    const globalTranslate = this.getLocaleTextFunc();
    this.forEachInput((element, index, position, numberOfInputs) => {
      if (!(element instanceof AgAbstractInputField)) {
        return;
      }
      const placeholder = index === 0 && numberOfInputs > 1 ? "inRangeStart" : index === 0 ? "filterOoo" : "inRangeEnd";
      const ariaLabel = index === 0 && numberOfInputs > 1 ? globalTranslate("ariaFilterFromValue", "Filter from value") : index === 0 ? globalTranslate("ariaFilterValue", "Filter Value") : globalTranslate("ariaFilterToValue", "Filter to Value");
      element.setInputPlaceholder(this.getPlaceholderText(placeholder, position));
      element.setInputAriaLabel(ariaLabel);
    });
  }
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  setElementValue(element, value2, fromFloatingFilter) {
    if (element instanceof AgAbstractInputField) {
      element.setValue(value2 != null ? String(value2) : null, true);
    }
  }
  setElementDisplayed(element, displayed) {
    if (_isComponent(element)) {
      _setDisplayed(element.getGui(), displayed);
    }
  }
  setElementDisabled(element, disabled2) {
    if (_isComponent(element)) {
      _setDisabled(element.getGui(), disabled2);
    }
  }
  attachElementOnChange(element, listener) {
    if (element instanceof AgAbstractInputField) {
      element.onValueChange(listener);
    }
  }
  forEachInput(cb) {
    this.getConditionTypes().forEach((type, position) => {
      this.forEachPositionTypeInput(position, type, cb);
    });
  }
  forEachPositionInput(position, cb) {
    const type = this.getConditionType(position);
    this.forEachPositionTypeInput(position, type, cb);
  }
  forEachPositionTypeInput(position, type, cb) {
    const numberOfInputs = getNumberOfInputs(type, this.optionsFactory);
    const inputs = this.getInputs(position);
    for (let index = 0; index < inputs.length; index++) {
      const input2 = inputs[index];
      if (input2 != null) {
        cb(input2, index, position, numberOfInputs);
      }
    }
  }
  isConditionDisabled(position, lastUiCompletePosition) {
    if (this.isReadOnly()) {
      return true;
    }
    if (position === 0) {
      return false;
    }
    return position > lastUiCompletePosition + 1;
  }
  isConditionBodyVisible(position) {
    const type = this.getConditionType(position);
    const numberOfInputs = getNumberOfInputs(type, this.optionsFactory);
    return numberOfInputs > 0;
  }
  // returns true if the UI represents a working filter, eg all parts are filled out.
  // eg if text filter and textfield blank then returns false.
  isConditionUiComplete(position) {
    if (position >= this.getNumConditions()) {
      return false;
    }
    const type = this.getConditionType(position);
    if (type === "empty") {
      return false;
    }
    if (this.getValues(position).some((v) => v == null)) {
      return false;
    }
    return true;
  }
  getNumConditions() {
    return this.eTypes.length;
  }
  getUiCompleteConditions() {
    const conditions = [];
    for (let position = 0; position < this.getNumConditions(); position++) {
      if (this.isConditionUiComplete(position)) {
        conditions.push(this.createCondition(position));
      }
    }
    return conditions;
  }
  createMissingConditionsAndOperators() {
    if (this.isReadOnly()) {
      return;
    }
    for (let i2 = this.getNumConditions(); i2 < this.numAlwaysVisibleConditions; i2++) {
      this.createJoinOperatorPanel();
      this.createOption();
    }
  }
  resetUiToDefaults(silent) {
    this.removeConditionsAndOperators(this.isReadOnly() ? 1 : this.numAlwaysVisibleConditions);
    this.eTypes.forEach((eType) => this.resetType(eType));
    this.eJoinAnds.forEach(
      (eJoinOperatorAnd, index) => this.resetJoinOperatorAnd(eJoinOperatorAnd, index, this.joinOperatorId + index)
    );
    this.eJoinOrs.forEach(
      (eJoinOperatorOr, index) => this.resetJoinOperatorOr(eJoinOperatorOr, index, this.joinOperatorId + index)
    );
    this.joinOperatorId++;
    this.forEachInput((element) => this.resetInput(element));
    this.resetPlaceholder();
    this.createMissingConditionsAndOperators();
    this.lastUiCompletePosition = null;
    this.updateUiVisibility();
    if (!silent) {
      this.params.onUiChange(this.getUiChangeEventParams());
    }
  }
  resetType(eType) {
    const translate = this.getLocaleTextFunc();
    const filteringLabel = translate("ariaFilteringOperator", "Filtering operator");
    eType.setValue(this.optionsFactory.defaultOption, true).setAriaLabel(filteringLabel).setDisabled(this.isReadOnly() || this.filterListOptions.length <= 1);
  }
  resetJoinOperatorAnd(eJoinOperatorAnd, index, uniqueGroupId) {
    this.resetJoinOperator(
      eJoinOperatorAnd,
      index,
      this.defaultJoinOperator === "AND",
      this.translate("andCondition"),
      uniqueGroupId
    );
  }
  resetJoinOperatorOr(eJoinOperatorOr, index, uniqueGroupId) {
    this.resetJoinOperator(
      eJoinOperatorOr,
      index,
      this.defaultJoinOperator === "OR",
      this.translate("orCondition"),
      uniqueGroupId
    );
  }
  resetJoinOperator(eJoinOperator, index, value2, label2, uniqueGroupId) {
    this.updateJoinOperatorDisabled(
      eJoinOperator.setValue(value2, true).setName(`ag-simple-filter-and-or-${this.getCompId()}-${uniqueGroupId}`).setLabel(label2),
      index
    );
  }
  updateJoinOperatorsDisabled() {
    const updater = (eJoinOperator, index) => this.updateJoinOperatorDisabled(eJoinOperator, index);
    this.eJoinAnds.forEach(updater);
    this.eJoinOrs.forEach(updater);
  }
  updateJoinOperatorDisabled(eJoinOperator, index) {
    eJoinOperator.setDisabled(this.isReadOnly() || index > 0);
  }
  resetInput(element) {
    this.setElementValue(element, null);
    this.setElementDisabled(element, this.isReadOnly());
  }
  // puts model values into the UI
  setConditionIntoUi(model2, position) {
    const values2 = this.mapValuesFromModel(model2, this.optionsFactory);
    this.forEachInput((element, index, elPosition) => {
      if (elPosition !== position) {
        return;
      }
      this.setElementValue(element, values2[index] != null ? values2[index] : null);
    });
  }
  // after floating filter changes, this sets the 'value' section. this is implemented by the base class
  // (as that's where value is controlled), the 'type' part from the floating filter is dealt with in this class.
  setValueFromFloatingFilter(value2) {
    this.forEachInput((element, index, position) => {
      this.setElementValue(element, index === 0 && position === 0 ? value2 : null, true);
    });
  }
  addChangedListeners(eType, position) {
    if (this.isReadOnly()) {
      return;
    }
    eType.onValueChange(this.listener);
    this.forEachPositionInput(position, (element) => {
      this.attachElementOnChange(element, this.listener);
    });
  }
  hasInvalidInputs() {
    return false;
  }
  isReadOnly() {
    return !!this.params.readOnly;
  }
};
var DateCompWrapper = class {
  constructor(context, userCompFactory, colDef, dateComponentParams, eParent, onReady) {
    this.alive = true;
    this.context = context;
    this.eParent = eParent;
    const compDetails = _getDateCompDetails(userCompFactory, colDef, dateComponentParams);
    if (!compDetails) {
      return;
    }
    compDetails.newAgStackInstance().then((dateComp) => {
      if (!this.alive) {
        context.destroyBean(dateComp);
        return;
      }
      this.dateComp = dateComp;
      if (!dateComp) {
        return;
      }
      eParent.appendChild(dateComp.getGui());
      dateComp?.afterGuiAttached?.();
      const { tempValue, disabled: disabled2 } = this;
      if (tempValue) {
        dateComp.setDate(tempValue);
      }
      if (disabled2 != null) {
        dateComp.setDisabled?.(disabled2);
      }
      onReady?.(this);
    });
  }
  destroy() {
    this.alive = false;
    this.dateComp = this.context.destroyBean(this.dateComp);
  }
  getDate() {
    return this.dateComp ? this.dateComp.getDate() : this.tempValue;
  }
  setDate(value2) {
    const dateComp = this.dateComp;
    if (dateComp) {
      dateComp.setDate(value2);
    } else {
      this.tempValue = value2;
    }
  }
  setDisabled(disabled2) {
    const dateComp = this.dateComp;
    if (dateComp) {
      dateComp.setDisabled?.(disabled2);
    } else {
      this.disabled = disabled2;
    }
  }
  setDisplayed(displayed) {
    _setDisplayed(this.eParent, displayed);
  }
  setInputPlaceholder(placeholder) {
    this.dateComp?.setInputPlaceholder?.(placeholder);
  }
  setInputAriaLabel(label2) {
    this.dateComp?.setInputAriaLabel?.(label2);
  }
  afterGuiAttached(params) {
    this.dateComp?.afterGuiAttached?.(params);
  }
  updateParams(params) {
    this.dateComp?.refresh?.(params);
  }
};
var DEFAULT_DATE_FILTER_OPTIONS = [
  "equals",
  "notEqual",
  "lessThan",
  "greaterThan",
  "inRange",
  "blank",
  "notBlank"
];
function mapValuesFromDateFilterModel(filterModel, optionsFactory) {
  const { dateFrom, dateTo, type } = filterModel || {};
  return [
    dateFrom && _parseDateTimeFromString(dateFrom, void 0, true) || null,
    dateTo && _parseDateTimeFromString(dateTo, void 0, true) || null
  ].slice(0, getNumberOfInputs(type, optionsFactory));
}
var DEFAULT_MIN_YEAR = 1e3;
var DEFAULT_MAX_YEAR = Infinity;
var DateFilter = class extends SimpleFilter {
  constructor() {
    super("dateFilter", mapValuesFromDateFilterModel, DEFAULT_DATE_FILTER_OPTIONS);
    this.eConditionPanelsFrom = [];
    this.eConditionPanelsTo = [];
    this.dateConditionFromComps = [];
    this.dateConditionToComps = [];
    this.minValidYear = DEFAULT_MIN_YEAR;
    this.maxValidYear = DEFAULT_MAX_YEAR;
    this.minValidDate = null;
    this.maxValidDate = null;
    this.filterType = "date";
  }
  afterGuiAttached(params) {
    super.afterGuiAttached(params);
    this.dateConditionFromComps[0].afterGuiAttached(params);
  }
  commonUpdateSimpleParams(params) {
    super.commonUpdateSimpleParams(params);
    const yearParser = (param, fallback) => {
      const value2 = params[param];
      if (value2 != null) {
        if (!isNaN(value2)) {
          return value2 == null ? fallback : Number(value2);
        } else {
          _warn(82, { param });
        }
      }
      return fallback;
    };
    const minValidYear = yearParser("minValidYear", DEFAULT_MIN_YEAR);
    const maxValidYear = yearParser("maxValidYear", DEFAULT_MAX_YEAR);
    this.minValidYear = minValidYear;
    this.maxValidYear = maxValidYear;
    if (minValidYear > maxValidYear) {
      _warn(83);
    }
    const { minValidDate, maxValidDate } = params;
    const parsedMinValidDate = minValidDate instanceof Date ? minValidDate : _parseDateTimeFromString(minValidDate);
    this.minValidDate = parsedMinValidDate;
    const parsedMaxValidDate = maxValidDate instanceof Date ? maxValidDate : _parseDateTimeFromString(maxValidDate);
    this.maxValidDate = parsedMaxValidDate;
    if (parsedMinValidDate && parsedMaxValidDate && parsedMinValidDate > parsedMaxValidDate) {
      _warn(84);
    }
  }
  createDateCompWrapper(element) {
    const {
      beans: { userCompFactory, context, gos },
      params
    } = this;
    const dateCompWrapper = new DateCompWrapper(
      context,
      userCompFactory,
      params.colDef,
      _addGridCommonParams(gos, {
        onDateChanged: () => this.onUiChanged(),
        filterParams: params,
        location: "filter"
      }),
      element
    );
    this.addDestroyFunc(() => dateCompWrapper.destroy());
    return dateCompWrapper;
  }
  setElementValue(element, value2) {
    element.setDate(value2);
  }
  setElementDisplayed(element, displayed) {
    element.setDisplayed(displayed);
  }
  setElementDisabled(element, disabled2) {
    element.setDisabled(disabled2);
  }
  createEValue() {
    const eCondition = _createElement({ tag: "div", cls: "ag-filter-body" });
    this.createFromToElement(eCondition, this.eConditionPanelsFrom, this.dateConditionFromComps, "from");
    this.createFromToElement(eCondition, this.eConditionPanelsTo, this.dateConditionToComps, "to");
    return eCondition;
  }
  createFromToElement(eCondition, eConditionPanels, dateConditionComps, fromTo) {
    const eConditionPanel = _createElement({ tag: "div", cls: `ag-filter-${fromTo} ag-filter-date-${fromTo}` });
    eConditionPanels.push(eConditionPanel);
    eCondition.appendChild(eConditionPanel);
    dateConditionComps.push(this.createDateCompWrapper(eConditionPanel));
  }
  removeEValues(startPosition, deleteCount) {
    this.removeDateComps(this.dateConditionFromComps, startPosition, deleteCount);
    this.removeDateComps(this.dateConditionToComps, startPosition, deleteCount);
    removeItems(this.eConditionPanelsFrom, startPosition, deleteCount);
    removeItems(this.eConditionPanelsTo, startPosition, deleteCount);
  }
  removeDateComps(components, startPosition, deleteCount) {
    const removedComponents = removeItems(components, startPosition, deleteCount);
    for (const comp of removedComponents) {
      comp.destroy();
    }
  }
  isValidDateValue(value2) {
    if (value2 === null) {
      return false;
    }
    const { minValidDate, maxValidDate, minValidYear, maxValidYear } = this;
    if (minValidDate) {
      if (value2 < minValidDate) {
        return false;
      }
    } else if (value2.getUTCFullYear() < minValidYear) {
      return false;
    }
    if (maxValidDate) {
      if (value2 > maxValidDate) {
        return false;
      }
    } else if (value2.getUTCFullYear() > maxValidYear) {
      return false;
    }
    return true;
  }
  isConditionUiComplete(position) {
    if (!super.isConditionUiComplete(position)) {
      return false;
    }
    let valid = true;
    this.forEachInput((element, index, elPosition, numberOfInputs) => {
      if (elPosition !== position || !valid || index >= numberOfInputs) {
        return;
      }
      valid = valid && this.isValidDateValue(element.getDate());
    });
    return valid;
  }
  areSimpleModelsEqual(aSimple, bSimple) {
    return aSimple.dateFrom === bSimple.dateFrom && aSimple.dateTo === bSimple.dateTo && aSimple.type === bSimple.type;
  }
  createCondition(position) {
    const type = this.getConditionType(position);
    const model2 = {};
    const values2 = this.getValues(position);
    const separator2 = this.params.useIsoSeparator ? "T" : " ";
    if (values2.length > 0) {
      model2.dateFrom = _serialiseDate(values2[0], true, separator2);
    }
    if (values2.length > 1) {
      model2.dateTo = _serialiseDate(values2[1], true, separator2);
    }
    return {
      dateFrom: null,
      dateTo: null,
      filterType: this.filterType,
      type,
      ...model2
    };
  }
  resetPlaceholder() {
    const globalTranslate = this.getLocaleTextFunc();
    const placeholder = this.translate("dateFormatOoo");
    const ariaLabel = globalTranslate("ariaFilterValue", "Filter Value");
    this.forEachInput((element) => {
      element.setInputPlaceholder(placeholder);
      element.setInputAriaLabel(ariaLabel);
    });
  }
  getInputs(position) {
    const { dateConditionFromComps, dateConditionToComps } = this;
    if (position >= dateConditionFromComps.length) {
      return [null, null];
    }
    return [dateConditionFromComps[position], dateConditionToComps[position]];
  }
  getValues(position) {
    const result2 = [];
    this.forEachPositionInput(position, (element, index, _elPosition, numberOfInputs) => {
      if (index < numberOfInputs) {
        result2.push(element.getDate());
      }
    });
    return result2;
  }
  translate(key2) {
    if (key2 === "lessThan") {
      return super.translate("before");
    }
    if (key2 === "greaterThan") {
      return super.translate("after");
    }
    return super.translate(key2);
  }
};
var SimpleFilterHandler = class extends BeanStub {
  constructor(mapValuesFromModel, defaultOptions2) {
    super();
    this.mapValuesFromModel = mapValuesFromModel;
    this.defaultOptions = defaultOptions2;
  }
  init(params) {
    const filterParams = params.filterParams;
    const optionsFactory = new OptionsFactory();
    this.optionsFactory = optionsFactory;
    optionsFactory.init(filterParams, this.defaultOptions);
    this.filterModelFormatter = this.createManagedBean(
      new this.FilterModelFormatterClass(optionsFactory, filterParams)
    );
    this.updateParams(params);
    this.validateModel(params);
  }
  refresh(params) {
    if (params.source === "colDef") {
      const filterParams = params.filterParams;
      const optionsFactory = this.optionsFactory;
      optionsFactory.refresh(filterParams, this.defaultOptions);
      this.filterModelFormatter.updateParams({ optionsFactory, filterParams });
      this.updateParams(params);
    }
    this.validateModel(params);
  }
  updateParams(params) {
    this.params = params;
  }
  doesFilterPass(params) {
    const model2 = params.model;
    if (model2 == null) {
      return true;
    }
    const { operator } = model2;
    const models = [];
    if (operator) {
      const combinedModel = model2;
      models.push(...combinedModel.conditions ?? []);
    } else {
      models.push(model2);
    }
    const combineFunction = operator && operator === "OR" ? "some" : "every";
    const cellValue = this.params.getValue(params.node);
    return models[combineFunction]((m) => this.individualConditionPasses(params, m, cellValue));
  }
  getModelAsString(model2, source2) {
    return this.filterModelFormatter.getModelAsString(model2, source2) ?? "";
  }
  validateModel(params) {
    const {
      model: model2,
      filterParams: { filterOptions, maxNumConditions }
    } = params;
    if (model2 == null) {
      return;
    }
    const isCombined = isCombinedFilterModel(model2);
    let conditions = isCombined ? model2.conditions : [model2];
    const newOptionsList = filterOptions?.map((option) => typeof option === "string" ? option : option.displayKey) ?? this.defaultOptions;
    const allConditionsExistInNewOptionsList = !conditions || conditions.every((condition) => newOptionsList.find((option) => option === condition.type) !== void 0);
    if (!allConditionsExistInNewOptionsList) {
      this.params = {
        ...params,
        model: null
      };
      params.onModelChange(null);
      return;
    }
    let needsUpdate = false;
    const filterType = this.filterType;
    if (conditions && !conditions.every((condition) => condition.filterType === filterType) || model2.filterType !== filterType) {
      conditions = conditions.map((condition) => ({ ...condition, filterType }));
      needsUpdate = true;
    }
    if (typeof maxNumConditions === "number" && conditions && conditions.length > maxNumConditions) {
      conditions = conditions.slice(0, maxNumConditions);
      needsUpdate = true;
    }
    if (needsUpdate) {
      const updatedModel = conditions.length > 1 ? {
        ...model2,
        filterType,
        conditions
      } : {
        ...conditions[0],
        filterType
      };
      this.params = {
        ...params,
        model: updatedModel
      };
      params.onModelChange(updatedModel);
    }
  }
  /** returns true if the row passes the said condition */
  individualConditionPasses(params, filterModel, cellValue) {
    const optionsFactory = this.optionsFactory;
    const values2 = this.mapValuesFromModel(filterModel, optionsFactory);
    const customFilterOption = optionsFactory.getCustomOption(filterModel.type);
    const customFilterResult = evaluateCustomFilter(customFilterOption, values2, cellValue);
    if (customFilterResult != null) {
      return customFilterResult;
    }
    if (cellValue == null) {
      return this.evaluateNullValue(filterModel.type);
    }
    return this.evaluateNonNullValue(values2, cellValue, filterModel, params);
  }
};
var ScalarFilterHandler = class extends SimpleFilterHandler {
  evaluateNullValue(filterType) {
    const {
      includeBlanksInEquals,
      includeBlanksInNotEqual,
      includeBlanksInGreaterThan,
      includeBlanksInLessThan,
      includeBlanksInRange
    } = this.params.filterParams;
    switch (filterType) {
      case "equals":
        if (includeBlanksInEquals) {
          return true;
        }
        break;
      case "notEqual":
        if (includeBlanksInNotEqual) {
          return true;
        }
        break;
      case "greaterThan":
      case "greaterThanOrEqual":
        if (includeBlanksInGreaterThan) {
          return true;
        }
        break;
      case "lessThan":
      case "lessThanOrEqual":
        if (includeBlanksInLessThan) {
          return true;
        }
        break;
      case "inRange":
        if (includeBlanksInRange) {
          return true;
        }
        break;
      case "blank":
        return true;
      case "notBlank":
        return false;
    }
    return false;
  }
  evaluateNonNullValue(values2, cellValue, filterModel) {
    const type = filterModel.type;
    if (!this.isValid(cellValue)) {
      return type === "notEqual" || type === "notBlank";
    }
    const comparator = this.comparator();
    const compareResult = values2[0] != null ? comparator(values2[0], cellValue) : 0;
    switch (type) {
      case "equals":
        return compareResult === 0;
      case "notEqual":
        return compareResult !== 0;
      case "greaterThan":
        return compareResult > 0;
      case "greaterThanOrEqual":
        return compareResult >= 0;
      case "lessThan":
        return compareResult < 0;
      case "lessThanOrEqual":
        return compareResult <= 0;
      case "inRange": {
        const compareToResult = comparator(values2[1], cellValue);
        return this.params.filterParams.inRangeInclusive ? compareResult >= 0 && compareToResult <= 0 : compareResult > 0 && compareToResult < 0;
      }
      case "blank":
        return isBlank(cellValue);
      case "notBlank":
        return !isBlank(cellValue);
      default:
        _warn(76, { filterModelType: type });
        return true;
    }
  }
};
var SCALAR_FILTER_TYPE_KEYS = {
  equals: "Equals",
  notEqual: "NotEqual",
  greaterThan: "GreaterThan",
  greaterThanOrEqual: "GreaterThanOrEqual",
  lessThan: "LessThan",
  lessThanOrEqual: "LessThanOrEqual",
  inRange: "InRange"
};
var TEXT_FILTER_TYPE_KEYS = {
  contains: "Contains",
  notContains: "NotContains",
  equals: "TextEquals",
  notEqual: "TextNotEqual",
  startsWith: "StartsWith",
  endsWith: "EndsWith",
  inRange: "InRange"
};
var SimpleFilterModelFormatter = class extends BeanStub {
  constructor(optionsFactory, filterParams, valueFormatter) {
    super();
    this.optionsFactory = optionsFactory;
    this.filterParams = filterParams;
    this.valueFormatter = valueFormatter;
  }
  // used by:
  // 1) NumberFloatingFilter & TextFloatingFilter: Always, for both when editable and read only.
  // 2) DateFloatingFilter: Only when read only (as we show text rather than a date picker when read only)
  getModelAsString(model2, source2) {
    const translate = this.getLocaleTextFunc();
    const forToolPanel = source2 === "filterToolPanel";
    if (!model2) {
      return forToolPanel ? translateForFilter(this, "filterSummaryInactive") : null;
    }
    const isCombined = model2.operator != null;
    if (isCombined) {
      const combinedModel = model2;
      const conditions = combinedModel.conditions ?? [];
      const customOptions = conditions.map((condition) => this.getModelAsString(condition, source2));
      const joinOperatorTranslateKey = combinedModel.operator === "AND" ? "andCondition" : "orCondition";
      return customOptions.join(` ${translateForFilter(this, joinOperatorTranslateKey)} `);
    } else if (model2.type === "blank" || model2.type === "notBlank") {
      return forToolPanel ? translateForFilter(this, model2.type === "blank" ? "filterSummaryBlank" : "filterSummaryNotBlank") : translate(model2.type, model2.type);
    } else {
      const condition = model2;
      const customOption = this.optionsFactory.getCustomOption(condition.type);
      const { displayKey, displayName, numberOfInputs } = customOption || {};
      if (displayKey && displayName && numberOfInputs === 0) {
        return translate(displayKey, displayName);
      }
      return this.conditionToString(
        condition,
        forToolPanel,
        condition.type === "inRange" || numberOfInputs === 2,
        displayKey,
        displayName
      );
    }
  }
  updateParams(params) {
    const { optionsFactory, filterParams } = params;
    this.optionsFactory = optionsFactory;
    this.filterParams = filterParams;
  }
  conditionForToolPanel(type, isRange, getFilter, getFilterTo, customDisplayKey, customDisplayName) {
    let typeValue;
    const typeKey = this.getTypeKey(type);
    if (typeKey) {
      typeValue = translateForFilter(this, typeKey);
    }
    if (customDisplayKey && customDisplayName) {
      typeValue = this.getLocaleTextFunc()(customDisplayKey, customDisplayName);
    }
    if (typeValue != null) {
      if (isRange) {
        return `${typeValue} ${translateForFilter(this, "filterSummaryInRangeValues", [getFilter(), getFilterTo()])}`;
      } else {
        return `${typeValue} ${getFilter()}`;
      }
    }
    return null;
  }
  getTypeKey(type) {
    const suffix = this.filterTypeKeys[type];
    return suffix ? `filterSummary${suffix}` : null;
  }
  formatValue(value2) {
    const valueFormatter = this.valueFormatter;
    return valueFormatter ? valueFormatter(value2 ?? null) ?? "" : String(value2);
  }
};
var DateFilterModelFormatter = class extends SimpleFilterModelFormatter {
  constructor(optionsFactory, filterParams) {
    super(optionsFactory, filterParams, (value2) => {
      const { dataTypeSvc, valueSvc } = this.beans;
      const column2 = filterParams.column;
      const dateFormatFn = dataTypeSvc?.getDateFormatterFunction(column2);
      const valueToFormat = dateFormatFn ? dateFormatFn(value2 ?? void 0) : value2;
      return valueSvc.formatValue(column2, null, valueToFormat);
    });
    this.filterTypeKeys = SCALAR_FILTER_TYPE_KEYS;
  }
  conditionToString(condition, forToolPanel, isRange, customDisplayKey, customDisplayName) {
    const { type } = condition;
    const dateFrom = _parseDateTimeFromString(condition.dateFrom);
    const dateTo = _parseDateTimeFromString(condition.dateTo);
    const format2 = this.filterParams.inRangeFloatingFilterDateFormat;
    const formatDate2 = forToolPanel ? this.formatValue.bind(this) : (value2) => _dateToFormattedString(value2, format2);
    const formattedFrom = () => dateFrom !== null ? formatDate2(dateFrom) : "null";
    const formattedTo = () => dateTo !== null ? formatDate2(dateTo) : "null";
    if (forToolPanel) {
      const valueForToolPanel = this.conditionForToolPanel(
        type,
        isRange,
        formattedFrom,
        formattedTo,
        customDisplayKey,
        customDisplayName
      );
      if (valueForToolPanel != null) {
        return valueForToolPanel;
      }
    }
    if (isRange) {
      return `${formattedFrom()}-${formattedTo()}`;
    }
    if (dateFrom != null) {
      return formatDate2(dateFrom);
    }
    return `${type}`;
  }
};
function defaultDateComparator(filterDate, cellValue) {
  const cellAsDate = cellValue;
  if (cellAsDate < filterDate) {
    return -1;
  }
  if (cellAsDate > filterDate) {
    return 1;
  }
  return 0;
}
var DateFilterHandler = class extends ScalarFilterHandler {
  constructor() {
    super(mapValuesFromDateFilterModel, DEFAULT_DATE_FILTER_OPTIONS);
    this.filterType = "date";
    this.FilterModelFormatterClass = DateFilterModelFormatter;
  }
  comparator() {
    return this.params.filterParams.comparator ?? defaultDateComparator;
  }
  isValid(value2) {
    const isValidDate2 = this.params.filterParams.isValidDate;
    return !isValidDate2 || isValidDate2(value2);
  }
};
var SimpleFloatingFilter = class extends Component {
  constructor() {
    super(...arguments);
    this.defaultDebounceMs = 0;
  }
  setLastTypeFromModel(model2) {
    if (!model2) {
      this.lastType = this.optionsFactory.defaultOption;
      return;
    }
    const isCombined = model2.operator;
    let condition;
    if (isCombined) {
      const combinedModel = model2;
      condition = combinedModel.conditions[0];
    } else {
      condition = model2;
    }
    this.lastType = condition.type;
  }
  canWeEditAfterModelFromParentFilter(model2) {
    if (!model2) {
      return this.isTypeEditable(this.lastType);
    }
    const isCombined = model2.operator;
    if (isCombined) {
      return false;
    }
    const simpleModel = model2;
    return this.isTypeEditable(simpleModel.type);
  }
  init(params) {
    this.params = params;
    const reactive = this.gos.get("enableFilterHandlers");
    this.reactive = reactive;
    this.setParams(params);
    if (reactive) {
      const reactiveParams = params;
      this.onModelUpdated(reactiveParams.model);
    }
  }
  setParams(params) {
    const optionsFactory = new OptionsFactory();
    this.optionsFactory = optionsFactory;
    optionsFactory.init(params.filterParams, this.defaultOptions);
    this.filterModelFormatter = this.createManagedBean(
      new this.FilterModelFormatterClass(optionsFactory, params.filterParams)
    );
    this.setSimpleParams(params, false);
  }
  setSimpleParams(params, update2 = true) {
    const defaultOption = this.optionsFactory.defaultOption;
    if (!update2) {
      this.lastType = defaultOption;
    }
    this.readOnly = !!params.filterParams.readOnly;
    const editable = this.isTypeEditable(defaultOption);
    this.setEditable(editable);
  }
  refresh(params) {
    this.params = params;
    const reactiveParams = params;
    const reactive = this.reactive;
    if (!reactive || reactiveParams.source === "colDef") {
      this.updateParams(params);
    }
    if (reactive) {
      const { source: source2, model: model2 } = reactiveParams;
      if (source2 === "dataChanged" || source2 === "ui") {
        return;
      }
      this.onModelUpdated(model2);
    }
  }
  updateParams(params) {
    const optionsFactory = this.optionsFactory;
    optionsFactory.refresh(params.filterParams, this.defaultOptions);
    this.setSimpleParams(params);
    this.filterModelFormatter.updateParams({
      optionsFactory,
      filterParams: params.filterParams
    });
  }
  onParentModelChanged(model2, event) {
    if (event?.afterFloatingFilter || event?.afterDataChange) {
      return;
    }
    this.onModelUpdated(model2);
  }
  hasSingleInput(filterType) {
    const numberOfInputs = this.optionsFactory.getCustomOption(filterType)?.numberOfInputs;
    return numberOfInputs == null || numberOfInputs == 1;
  }
  isTypeEditable(type) {
    const uneditableTypes = ["inRange", "empty", "blank", "notBlank"];
    return !!type && !this.readOnly && this.hasSingleInput(type) && uneditableTypes.indexOf(type) < 0;
  }
  getAriaLabel(params) {
    const displayName = this.beans.colNames.getDisplayNameForColumn(params.column, "header", true);
    return `${displayName} ${this.getLocaleTextFunc()("ariaFilterInput", "Filter Input")}`;
  }
};
var DateFloatingFilterElement = {
  tag: "div",
  cls: "ag-floating-filter-input",
  role: "presentation",
  children: [
    {
      tag: "ag-input-text-field",
      ref: "eReadOnlyText"
    },
    { tag: "div", ref: "eDateWrapper", cls: "ag-date-floating-filter-wrapper" }
  ]
};
var DateFloatingFilter = class extends SimpleFloatingFilter {
  constructor() {
    super(DateFloatingFilterElement, [AgInputTextFieldSelector]);
    this.eReadOnlyText = RefPlaceholder;
    this.eDateWrapper = RefPlaceholder;
    this.FilterModelFormatterClass = DateFilterModelFormatter;
    this.filterType = "date";
    this.defaultOptions = DEFAULT_DATE_FILTER_OPTIONS;
  }
  setParams(params) {
    super.setParams(params);
    this.createDateComponent();
    const translate = this.getLocaleTextFunc();
    this.eReadOnlyText.setDisabled(true).setInputAriaLabel(translate("ariaDateFilterInput", "Date Filter Input"));
  }
  updateParams(params) {
    super.updateParams(params);
    this.dateComp.updateParams(this.getDateComponentParams());
    this.updateCompOnModelChange(params.currentParentModel());
  }
  updateCompOnModelChange(model2) {
    const allowEditing = !this.readOnly && this.canWeEditAfterModelFromParentFilter(model2);
    this.setEditable(allowEditing);
    if (allowEditing) {
      const dateModel = model2 ? _parseDateTimeFromString(model2.dateFrom) : null;
      this.dateComp.setDate(dateModel);
      this.eReadOnlyText.setValue("");
    } else {
      this.eReadOnlyText.setValue(this.filterModelFormatter.getModelAsString(model2));
      this.dateComp.setDate(null);
    }
  }
  setEditable(editable) {
    _setDisplayed(this.eDateWrapper, editable);
    _setDisplayed(this.eReadOnlyText.getGui(), !editable);
  }
  onModelUpdated(model2) {
    super.setLastTypeFromModel(model2);
    this.updateCompOnModelChange(model2);
  }
  onDateChanged() {
    const filterValueDate = this.dateComp.getDate();
    if (this.reactive) {
      const reactiveParams = this.params;
      reactiveParams.onUiChange();
      const model2 = reactiveParams.model;
      const filterValueText = _serialiseDate(filterValueDate);
      const newModel = filterValueText == null ? null : {
        ...model2 ?? {
          filterType: this.filterType,
          type: this.lastType ?? this.optionsFactory.defaultOption
        },
        dateFrom: filterValueText
      };
      reactiveParams.onModelChange(newModel, { afterFloatingFilter: true });
    } else {
      this.params.parentFilterInstance((filterInstance) => {
        filterInstance?.onFloatingFilterChanged(this.lastType || null, filterValueDate);
      });
    }
  }
  getDateComponentParams() {
    const { filterParams } = this.params;
    const debounceMs = getDebounceMs(filterParams, this.defaultDebounceMs);
    return _addGridCommonParams(this.gos, {
      onDateChanged: _debounce(this, this.onDateChanged.bind(this), debounceMs),
      filterParams,
      location: "floatingFilter"
    });
  }
  createDateComponent() {
    const {
      beans: { context, userCompFactory },
      eDateWrapper,
      params
    } = this;
    this.dateComp = new DateCompWrapper(
      context,
      userCompFactory,
      params.column.getColDef(),
      this.getDateComponentParams(),
      eDateWrapper,
      (dateComp) => {
        dateComp.setInputAriaLabel(this.getAriaLabel(params));
      }
    );
    this.addDestroyFunc(() => this.dateComp.destroy());
  }
};
var DefaultDateElement = {
  tag: "div",
  cls: "ag-filter-filter",
  children: [
    {
      tag: "ag-input-text-field",
      ref: "eDateInput",
      cls: "ag-date-filter"
    }
  ]
};
var DefaultDateComponent = class extends Component {
  constructor() {
    super(DefaultDateElement, [AgInputTextFieldSelector]);
    this.eDateInput = RefPlaceholder;
    this.isApply = false;
    this.applyOnFocusOut = false;
  }
  init(params) {
    this.params = params;
    this.setParams(params);
    const inputElement = this.eDateInput.getInputElement();
    this.addManagedListeners(inputElement, {
      // ensures that the input element is focussed when a clear button is clicked,
      // unless using safari as there is no clear button and focus does not work properly
      mouseDown: () => {
        if (this.eDateInput.isDisabled() || this.usingSafariDatePicker) {
          return;
        }
        inputElement.focus({ preventScroll: true });
      },
      input: this.handleInput.bind(this, false),
      change: this.handleInput.bind(this, true),
      focusout: this.handleFocusOut.bind(this)
    });
  }
  handleInput(isChange) {
    if (this.eDateInput.isDisabled()) {
      return;
    }
    if (this.isApply) {
      this.applyOnFocusOut = !isChange;
      if (isChange) {
        this.params.onDateChanged();
      }
      return;
    }
    if (!isChange) {
      this.params.onDateChanged();
    }
  }
  handleFocusOut() {
    if (this.applyOnFocusOut) {
      this.applyOnFocusOut = false;
      this.params.onDateChanged();
    }
  }
  setParams(params) {
    const inputElement = this.eDateInput.getInputElement();
    const shouldUseBrowserDatePicker = this.shouldUseBrowserDatePicker(params);
    this.usingSafariDatePicker = shouldUseBrowserDatePicker && _isBrowserSafari();
    const { minValidYear, maxValidYear, minValidDate, maxValidDate, buttons, includeTime, colDef } = params.filterParams || {};
    const dataTypeSvc = this.beans.dataTypeSvc;
    const shouldUseDateTimeLocal = includeTime ?? dataTypeSvc?.getDateIncludesTimeFlag?.(colDef.cellDataType) ?? false;
    if (shouldUseBrowserDatePicker) {
      if (shouldUseDateTimeLocal) {
        inputElement.type = "datetime-local";
        inputElement.step = "1";
      } else {
        inputElement.type = "date";
      }
    } else {
      inputElement.type = "text";
    }
    if (minValidDate && minValidYear) {
      _warn(85);
    }
    if (maxValidDate && maxValidYear) {
      _warn(86);
    }
    if (minValidDate && maxValidDate) {
      const [parsedMinValidDate, parsedMaxValidDate] = [minValidDate, maxValidDate].map(
        (v) => v instanceof Date ? v : _parseDateTimeFromString(v)
      );
      if (parsedMinValidDate && parsedMaxValidDate && parsedMinValidDate.getTime() > parsedMaxValidDate.getTime()) {
        _warn(87);
      }
    }
    if (minValidDate) {
      if (minValidDate instanceof Date) {
        inputElement.min = _dateToFormattedString(minValidDate);
      } else {
        inputElement.min = minValidDate;
      }
    } else if (minValidYear) {
      inputElement.min = `${minValidYear}-01-01`;
    }
    if (maxValidDate) {
      if (maxValidDate instanceof Date) {
        inputElement.max = _dateToFormattedString(maxValidDate);
      } else {
        inputElement.max = maxValidDate;
      }
    } else if (maxValidYear) {
      inputElement.max = `${maxValidYear}-12-31`;
    }
    this.isApply = params.location === "floatingFilter" && !!buttons?.includes("apply");
  }
  refresh(params) {
    this.params = params;
    this.setParams(params);
  }
  getDate() {
    return _parseDateTimeFromString(this.eDateInput.getValue());
  }
  setDate(date2) {
    const colType = this.params.filterParams.colDef.cellDataType;
    const includeTime = this.beans.dataTypeSvc?.getDateIncludesTimeFlag(colType) ?? false;
    this.eDateInput.setValue(_serialiseDate(date2, includeTime));
  }
  setInputPlaceholder(placeholder) {
    this.eDateInput.setInputPlaceholder(placeholder);
  }
  setInputAriaLabel(ariaLabel) {
    this.eDateInput.setAriaLabel(ariaLabel);
  }
  setDisabled(disabled2) {
    this.eDateInput.setDisabled(disabled2);
  }
  afterGuiAttached(params) {
    if (!params?.suppressFocus) {
      this.eDateInput.getInputElement().focus({ preventScroll: true });
    }
  }
  shouldUseBrowserDatePicker(params) {
    return params?.filterParams?.browserDatePicker ?? true;
  }
};
var DEFAULT_NUMBER_FILTER_OPTIONS = [
  "equals",
  "notEqual",
  "greaterThan",
  "greaterThanOrEqual",
  "lessThan",
  "lessThanOrEqual",
  "inRange",
  "blank",
  "notBlank"
];
function getAllowedCharPattern(filterParams) {
  const { allowedCharPattern } = filterParams ?? {};
  return allowedCharPattern ?? null;
}
function processNumberFilterValue(value2) {
  if (value2 == null) {
    return null;
  }
  return isNaN(value2) ? null : value2;
}
function mapValuesFromNumberFilterModel(filterModel, optionsFactory) {
  const { filter: filter2, filterTo, type } = filterModel || {};
  return [processNumberFilterValue(filter2), processNumberFilterValue(filterTo)].slice(
    0,
    getNumberOfInputs(type, optionsFactory)
  );
}
var NumberFilter = class extends SimpleFilter {
  constructor() {
    super("numberFilter", mapValuesFromNumberFilterModel, DEFAULT_NUMBER_FILTER_OPTIONS);
    this.eValuesFrom = [];
    this.eValuesTo = [];
    this.filterType = "number";
    this.defaultDebounceMs = 500;
  }
  setElementValue(element, value2, fromFloatingFilter) {
    const { numberFormatter } = this.params;
    const valueToSet = !fromFloatingFilter && numberFormatter ? numberFormatter(value2 ?? null) : value2;
    super.setElementValue(element, valueToSet);
  }
  createEValue() {
    const allowedCharPattern = getAllowedCharPattern(this.params);
    const eCondition = _createElement({ tag: "div", cls: "ag-filter-body", role: "presentation" });
    this.createFromToElement(eCondition, this.eValuesFrom, "from", allowedCharPattern);
    this.createFromToElement(eCondition, this.eValuesTo, "to", allowedCharPattern);
    return eCondition;
  }
  createFromToElement(eCondition, eValues, fromTo, allowedCharPattern) {
    const eValue = this.createManagedBean(
      allowedCharPattern ? new AgInputTextField({ allowedCharPattern }) : new AgInputNumberField()
    );
    eValue.addCss(`ag-filter-${fromTo}`);
    eValue.addCss("ag-filter-filter");
    eValues.push(eValue);
    eCondition.appendChild(eValue.getGui());
  }
  removeEValues(startPosition, deleteCount) {
    const removeComps = (eGui) => this.removeComponents(eGui, startPosition, deleteCount);
    removeComps(this.eValuesFrom);
    removeComps(this.eValuesTo);
  }
  getValues(position) {
    const result2 = [];
    this.forEachPositionInput(position, (element, index, _elPosition, numberOfInputs) => {
      if (index < numberOfInputs) {
        result2.push(processNumberFilterValue(this.stringToFloat(element.getValue())));
      }
    });
    return result2;
  }
  areSimpleModelsEqual(aSimple, bSimple) {
    return aSimple.filter === bSimple.filter && aSimple.filterTo === bSimple.filterTo && aSimple.type === bSimple.type;
  }
  stringToFloat(value2) {
    if (typeof value2 === "number") {
      return value2;
    }
    let filterText = _makeNull(value2);
    if (filterText != null && filterText.trim() === "") {
      filterText = null;
    }
    const numberParser = this.params.numberParser;
    if (numberParser) {
      return numberParser(filterText);
    }
    return filterText == null || filterText.trim() === "-" ? null : Number.parseFloat(filterText);
  }
  createCondition(position) {
    const type = this.getConditionType(position);
    const model2 = {
      filterType: this.filterType,
      type
    };
    const values2 = this.getValues(position);
    if (values2.length > 0) {
      model2.filter = values2[0];
    }
    if (values2.length > 1) {
      model2.filterTo = values2[1];
    }
    return model2;
  }
  getInputs(position) {
    const { eValuesFrom, eValuesTo } = this;
    if (position >= eValuesFrom.length) {
      return [null, null];
    }
    return [eValuesFrom[position], eValuesTo[position]];
  }
  hasInvalidInputs() {
    let invalidInputs = false;
    this.forEachInput((element) => {
      if (!element.getInputElement().validity.valid) {
        invalidInputs = true;
      }
    });
    return invalidInputs;
  }
};
var NumberFilterModelFormatter = class extends SimpleFilterModelFormatter {
  constructor(optionsFactory, filterParams) {
    super(optionsFactory, filterParams, filterParams.numberFormatter);
    this.filterTypeKeys = SCALAR_FILTER_TYPE_KEYS;
  }
  conditionToString(condition, forToolPanel, isRange, customDisplayKey, customDisplayName) {
    const { filter: filter2, filterTo, type } = condition;
    const formatValue2 = this.formatValue.bind(this);
    if (forToolPanel) {
      const valueForToolPanel = this.conditionForToolPanel(
        type,
        isRange,
        () => formatValue2(filter2),
        () => formatValue2(filterTo),
        customDisplayKey,
        customDisplayName
      );
      if (valueForToolPanel != null) {
        return valueForToolPanel;
      }
    }
    if (isRange) {
      return `${formatValue2(filter2)}-${formatValue2(filterTo)}`;
    }
    if (filter2 != null) {
      return formatValue2(filter2);
    }
    return `${type}`;
  }
};
var NumberFilterHandler = class extends ScalarFilterHandler {
  constructor() {
    super(mapValuesFromNumberFilterModel, DEFAULT_NUMBER_FILTER_OPTIONS);
    this.filterType = "number";
    this.FilterModelFormatterClass = NumberFilterModelFormatter;
  }
  comparator() {
    return (left2, right2) => {
      if (left2 === right2) {
        return 0;
      }
      return left2 < right2 ? 1 : -1;
    };
  }
  isValid(value2) {
    return !isNaN(value2);
  }
};
var FloatingFilterTextInputService = class extends BeanStub {
  constructor(params) {
    super();
    this.params = params;
    this.eInput = RefPlaceholder;
    this.onValueChanged = () => {
    };
  }
  setupGui(parentElement) {
    this.eInput = this.createManagedBean(new AgInputTextField(this.params?.config));
    const eInput = this.eInput.getGui();
    parentElement.appendChild(eInput);
    const listener = (e) => this.onValueChanged(e);
    this.addManagedListeners(eInput, {
      input: listener,
      keydown: listener
    });
  }
  setEditable(editable) {
    this.eInput.setDisabled(!editable);
  }
  getValue() {
    return this.eInput.getValue();
  }
  setValue(value2, silent) {
    this.eInput.setValue(value2, silent);
  }
  setValueChangedListener(listener) {
    this.onValueChanged = listener;
  }
  setParams({ ariaLabel, autoComplete }) {
    const { eInput } = this;
    eInput.setInputAriaLabel(ariaLabel);
    if (autoComplete !== void 0) {
      eInput.setAutoComplete(autoComplete);
    }
  }
};
function trimInputForFilter(value2) {
  const trimmedInput = value2?.trim();
  return trimmedInput === "" ? value2 : trimmedInput;
}
function mapValuesFromTextFilterModel(filterModel, optionsFactory) {
  const { filter: filter2, filterTo, type } = filterModel || {};
  return [filter2 || null, filterTo || null].slice(0, getNumberOfInputs(type, optionsFactory));
}
var TextInputFloatingFilterElement = {
  tag: "div",
  ref: "eFloatingFilterInputContainer",
  cls: "ag-floating-filter-input",
  role: "presentation"
};
var TextInputFloatingFilter = class extends SimpleFloatingFilter {
  constructor() {
    super(...arguments);
    this.eFloatingFilterInputContainer = RefPlaceholder;
    this.defaultDebounceMs = 500;
  }
  postConstruct() {
    this.setTemplate(TextInputFloatingFilterElement);
  }
  onModelUpdated(model2) {
    this.setLastTypeFromModel(model2);
    this.setEditable(this.canWeEditAfterModelFromParentFilter(model2));
    this.inputSvc.setValue(this.filterModelFormatter.getModelAsString(model2));
  }
  setParams(params) {
    this.setupFloatingFilterInputService(params);
    super.setParams(params);
    this.setTextInputParams(params);
  }
  setupFloatingFilterInputService(params) {
    this.inputSvc = this.createFloatingFilterInputService(params);
    this.inputSvc.setupGui(this.eFloatingFilterInputContainer);
  }
  setTextInputParams(params) {
    const autoComplete = params.browserAutoComplete ?? false;
    const { inputSvc, defaultDebounceMs, readOnly } = this;
    inputSvc.setParams({
      ariaLabel: this.getAriaLabel(params),
      autoComplete
    });
    this.applyActive = _isUseApplyButton(params.filterParams);
    if (!readOnly) {
      const debounceMs = getDebounceMs(params.filterParams, defaultDebounceMs);
      const toDebounce = _debounce(
        this,
        this.syncUpWithParentFilter.bind(this),
        debounceMs
      );
      inputSvc.setValueChangedListener(toDebounce);
    }
  }
  updateParams(params) {
    super.updateParams(params);
    this.setTextInputParams(params);
  }
  recreateFloatingFilterInputService(params) {
    const { inputSvc } = this;
    const value2 = inputSvc.getValue();
    _clearElement(this.eFloatingFilterInputContainer);
    this.destroyBean(inputSvc);
    this.setupFloatingFilterInputService(params);
    inputSvc.setValue(value2, true);
  }
  syncUpWithParentFilter(e) {
    const isEnterKey = e.key === KeyCode.ENTER;
    const reactive = this.reactive;
    if (reactive) {
      const reactiveParams = this.params;
      reactiveParams.onUiChange();
    }
    if (this.applyActive && !isEnterKey) {
      return;
    }
    const { inputSvc, params, lastType } = this;
    let value2 = inputSvc.getValue();
    if (params.filterParams.trimInput) {
      value2 = trimInputForFilter(value2);
      inputSvc.setValue(value2, true);
    }
    if (reactive) {
      const reactiveParams = params;
      const model2 = reactiveParams.model;
      const parsedValue = this.convertValue(value2);
      const newModel = parsedValue == null ? null : {
        ...model2 ?? {
          filterType: this.filterType,
          type: lastType ?? this.optionsFactory.defaultOption
        },
        filter: parsedValue
      };
      reactiveParams.onModelChange(newModel, { afterFloatingFilter: true });
    } else {
      params.parentFilterInstance((filterInstance) => {
        filterInstance?.onFloatingFilterChanged(lastType || null, value2 || null);
      });
    }
  }
  convertValue(value2) {
    return value2 || null;
  }
  setEditable(editable) {
    this.inputSvc.setEditable(editable);
  }
};
var FloatingFilterNumberInputService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.onValueChanged = () => {
    };
    this.numberInputActive = true;
  }
  setupGui(parentElement) {
    this.eNumberInput = this.createManagedBean(new AgInputNumberField());
    this.eTextInput = this.createManagedBean(new AgInputTextField());
    this.eTextInput.setDisabled(true);
    const eNumberInput = this.eNumberInput.getGui();
    const eTextInput = this.eTextInput.getGui();
    parentElement.appendChild(eNumberInput);
    parentElement.appendChild(eTextInput);
    this.setupListeners(eNumberInput, (e) => this.onValueChanged(e));
    this.setupListeners(eTextInput, (e) => this.onValueChanged(e));
  }
  setEditable(editable) {
    this.numberInputActive = editable;
    this.eNumberInput.setDisplayed(this.numberInputActive);
    this.eTextInput.setDisplayed(!this.numberInputActive);
  }
  setAutoComplete(autoComplete) {
    this.eNumberInput.setAutoComplete(autoComplete);
    this.eTextInput.setAutoComplete(autoComplete);
  }
  getValue() {
    return this.getActiveInputElement().getValue();
  }
  setValue(value2, silent) {
    this.getActiveInputElement().setValue(value2, silent);
  }
  getActiveInputElement() {
    return this.numberInputActive ? this.eNumberInput : this.eTextInput;
  }
  setValueChangedListener(listener) {
    this.onValueChanged = listener;
  }
  setupListeners(element, listener) {
    this.addManagedListeners(element, {
      input: listener,
      keydown: listener
    });
  }
  setParams(params) {
    this.setAriaLabel(params.ariaLabel);
    if (params.autoComplete !== void 0) {
      this.setAutoComplete(params.autoComplete);
    }
  }
  setAriaLabel(ariaLabel) {
    this.eNumberInput.setInputAriaLabel(ariaLabel);
    this.eTextInput.setInputAriaLabel(ariaLabel);
  }
};
var NumberFloatingFilter = class extends TextInputFloatingFilter {
  constructor() {
    super(...arguments);
    this.FilterModelFormatterClass = NumberFilterModelFormatter;
    this.filterType = "number";
    this.defaultOptions = DEFAULT_NUMBER_FILTER_OPTIONS;
  }
  updateParams(params) {
    const allowedCharPattern = getAllowedCharPattern(params.filterParams);
    if (allowedCharPattern !== this.allowedCharPattern) {
      this.recreateFloatingFilterInputService(params);
    }
    super.updateParams(params);
  }
  createFloatingFilterInputService(params) {
    this.allowedCharPattern = getAllowedCharPattern(params.filterParams);
    if (this.allowedCharPattern) {
      return this.createManagedBean(
        new FloatingFilterTextInputService({
          config: { allowedCharPattern: this.allowedCharPattern }
        })
      );
    }
    return this.createManagedBean(new FloatingFilterNumberInputService());
  }
  convertValue(value2) {
    return value2 ? Number(value2) : null;
  }
};
var DEFAULT_TEXT_FILTER_OPTIONS = [
  "contains",
  "notContains",
  "equals",
  "notEqual",
  "startsWith",
  "endsWith",
  "blank",
  "notBlank"
];
var TextFilter = class extends SimpleFilter {
  constructor() {
    super("textFilter", mapValuesFromTextFilterModel, DEFAULT_TEXT_FILTER_OPTIONS);
    this.filterType = "text";
    this.eValuesFrom = [];
    this.eValuesTo = [];
    this.defaultDebounceMs = 500;
  }
  createCondition(position) {
    const type = this.getConditionType(position);
    const model2 = {
      filterType: this.filterType,
      type
    };
    const values2 = this.getValues(position);
    if (values2.length > 0) {
      model2.filter = values2[0];
    }
    if (values2.length > 1) {
      model2.filterTo = values2[1];
    }
    return model2;
  }
  areSimpleModelsEqual(aSimple, bSimple) {
    return aSimple.filter === bSimple.filter && aSimple.filterTo === bSimple.filterTo && aSimple.type === bSimple.type;
  }
  getInputs(position) {
    const { eValuesFrom, eValuesTo } = this;
    if (position >= eValuesFrom.length) {
      return [null, null];
    }
    return [eValuesFrom[position], eValuesTo[position]];
  }
  getValues(position) {
    const result2 = [];
    this.forEachPositionInput(position, (element, index, _elPosition, numberOfInputs) => {
      if (index < numberOfInputs) {
        result2.push(_makeNull(element.getValue()));
      }
    });
    return result2;
  }
  createEValue() {
    const eCondition = _createElement({ tag: "div", cls: "ag-filter-body", role: "presentation" });
    const { eValuesFrom, eValuesTo } = this;
    this.createFromToElement(eCondition, eValuesFrom, "from");
    this.createFromToElement(eCondition, eValuesTo, "to");
    return eCondition;
  }
  createFromToElement(eCondition, eValues, fromTo) {
    const eValue = this.createManagedBean(new AgInputTextField());
    eValue.addCss(`ag-filter-${fromTo}`);
    eValue.addCss("ag-filter-filter");
    eValues.push(eValue);
    eCondition.appendChild(eValue.getGui());
  }
  removeEValues(startPosition, deleteCount) {
    const removeComps = (eGui) => this.removeComponents(eGui, startPosition, deleteCount);
    const { eValuesFrom, eValuesTo } = this;
    removeComps(eValuesFrom);
    removeComps(eValuesTo);
  }
};
var TextFilterModelFormatter = class extends SimpleFilterModelFormatter {
  constructor() {
    super(...arguments);
    this.filterTypeKeys = TEXT_FILTER_TYPE_KEYS;
  }
  conditionToString(condition, forToolPanel, isRange, customDisplayKey, customDisplayName) {
    const { filter: filter2, filterTo, type } = condition;
    if (forToolPanel) {
      const getValueFunc = (value2) => () => translateForFilter(this, "filterSummaryTextQuote", [value2]);
      const valueForToolPanel = this.conditionForToolPanel(
        type,
        isRange,
        getValueFunc(filter2),
        getValueFunc(filterTo),
        customDisplayKey,
        customDisplayName
      );
      if (valueForToolPanel != null) {
        return valueForToolPanel;
      }
    }
    if (isRange) {
      return `${filter2}-${filterTo}`;
    }
    if (filter2 != null) {
      return `${filter2}`;
    }
    return `${type}`;
  }
};
var defaultMatcher = ({ filterOption, value: value2, filterText }) => {
  if (filterText == null) {
    return false;
  }
  switch (filterOption) {
    case "contains":
      return value2.includes(filterText);
    case "notContains":
      return !value2.includes(filterText);
    case "equals":
      return value2 === filterText;
    case "notEqual":
      return value2 != filterText;
    case "startsWith":
      return value2.indexOf(filterText) === 0;
    case "endsWith": {
      const index = value2.lastIndexOf(filterText);
      return index >= 0 && index === value2.length - filterText.length;
    }
    default:
      return false;
  }
};
var defaultFormatter = (from2) => from2;
var defaultLowercaseFormatter = (from2) => from2 == null ? null : from2.toString().toLowerCase();
var TextFilterHandler = class extends SimpleFilterHandler {
  constructor() {
    super(mapValuesFromTextFilterModel, DEFAULT_TEXT_FILTER_OPTIONS);
    this.filterType = "text";
    this.FilterModelFormatterClass = TextFilterModelFormatter;
  }
  updateParams(params) {
    super.updateParams(params);
    const filterParams = params.filterParams;
    this.matcher = filterParams.textMatcher ?? defaultMatcher;
    this.formatter = filterParams.textFormatter ?? (filterParams.caseSensitive ? defaultFormatter : defaultLowercaseFormatter);
  }
  evaluateNullValue(filterType) {
    const filterTypesAllowNulls = ["notEqual", "notContains", "blank"];
    return filterType ? filterTypesAllowNulls.indexOf(filterType) >= 0 : false;
  }
  evaluateNonNullValue(values2, cellValue, filterModel, params) {
    const formattedValues = values2.map((v) => this.formatter(v)) || [];
    const cellValueFormatted = this.formatter(cellValue);
    const {
      api: api2,
      colDef,
      column: column2,
      context,
      filterParams: { textFormatter }
    } = this.params;
    if (filterModel.type === "blank") {
      return isBlank(cellValue);
    } else if (filterModel.type === "notBlank") {
      return !isBlank(cellValue);
    }
    const matcherParams = {
      api: api2,
      colDef,
      column: column2,
      context,
      node: params.node,
      data: params.data,
      filterOption: filterModel.type,
      value: cellValueFormatted,
      textFormatter
    };
    return formattedValues.some((v) => this.matcher({ ...matcherParams, filterText: v }));
  }
  processModelToApply(model2) {
    if (model2 && this.params.filterParams.trimInput) {
      const processCondition = (condition) => {
        const newCondition = {
          ...condition
        };
        const { filter: filter2, filterTo } = condition;
        if (filter2) {
          newCondition.filter = trimInputForFilter(filter2) ?? null;
        }
        if (filterTo) {
          newCondition.filterTo = trimInputForFilter(filterTo) ?? null;
        }
        return newCondition;
      };
      if (isCombinedFilterModel(model2)) {
        return {
          ...model2,
          conditions: model2.conditions.map(processCondition)
        };
      }
      return processCondition(model2);
    }
    return model2;
  }
};
var TextFloatingFilter = class extends TextInputFloatingFilter {
  constructor() {
    super(...arguments);
    this.FilterModelFormatterClass = TextFilterModelFormatter;
    this.filterType = "text";
    this.defaultOptions = DEFAULT_TEXT_FILTER_OPTIONS;
  }
  createFloatingFilterInputService() {
    return this.createManagedBean(new FloatingFilterTextInputService());
  }
};
function isQuickFilterPresent(beans) {
  return !!beans.quickFilter?.isFilterPresent();
}
function getQuickFilter(beans) {
  return beans.quickFilter?.getText();
}
function resetQuickFilter(beans) {
  beans.quickFilter?.resetCache();
}
var QuickFilterService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "quickFilter";
    this.quickFilter = null;
    this.quickFilterParts = null;
  }
  postConstruct() {
    const resetListener = this.resetCache.bind(this);
    const gos = this.gos;
    this.addManagedEventListeners({
      columnPivotModeChanged: resetListener,
      newColumnsLoaded: resetListener,
      columnRowGroupChanged: resetListener,
      columnVisible: () => {
        if (!gos.get("includeHiddenColumnsInQuickFilter")) {
          this.resetCache();
        }
      }
    });
    this.addManagedPropertyListener("quickFilterText", (e) => this.setFilter(e.currentValue));
    this.addManagedPropertyListeners(
      ["includeHiddenColumnsInQuickFilter", "applyQuickFilterBeforePivotOrAgg"],
      () => this.onColumnConfigChanged()
    );
    this.quickFilter = this.parseFilter(gos.get("quickFilterText"));
    this.parser = gos.get("quickFilterParser");
    this.matcher = gos.get("quickFilterMatcher");
    this.setFilterParts();
    this.addManagedPropertyListeners(["quickFilterMatcher", "quickFilterParser"], () => this.setParserAndMatcher());
  }
  // if we are using autoGroupCols, then they should be included for quick filter. this covers the
  // following scenarios:
  // a) user provides 'field' into autoGroupCol of normal grid, so now because a valid col to filter leafs on
  // b) using tree data and user depends on autoGroupCol for first col, and we also want to filter on this
  //    (tree data is a bit different, as parent rows can be filtered on, unlike row grouping)
  refreshCols() {
    const { autoColSvc, colModel, gos, pivotResultCols } = this.beans;
    const pivotMode = colModel.isPivotMode();
    const groupAutoCols = autoColSvc?.getColumns();
    const providedCols = colModel.getColDefCols();
    let columnsForQuickFilter = (pivotMode && !gos.get("applyQuickFilterBeforePivotOrAgg") ? pivotResultCols?.getPivotResultCols()?.list : providedCols) ?? [];
    if (groupAutoCols) {
      columnsForQuickFilter = columnsForQuickFilter.concat(groupAutoCols);
    }
    this.colsToUse = gos.get("includeHiddenColumnsInQuickFilter") ? columnsForQuickFilter : columnsForQuickFilter.filter((col) => col.isVisible() || col.isRowGroupActive());
  }
  isFilterPresent() {
    return this.quickFilter !== null;
  }
  doesRowPass(node2) {
    const usingCache = this.gos.get("cacheQuickFilter");
    if (this.matcher) {
      return this.doesRowPassMatcher(usingCache, node2);
    }
    return this.quickFilterParts.every(
      (part) => usingCache ? this.doesRowPassCache(node2, part) : this.doesRowPassNoCache(node2, part)
    );
  }
  resetCache() {
    this.beans.rowModel.forEachNode((node2) => node2.quickFilterAggregateText = null);
  }
  getText() {
    return this.gos.get("quickFilterText");
  }
  setFilterParts() {
    const { quickFilter, parser } = this;
    if (quickFilter) {
      this.quickFilterParts = parser ? parser(quickFilter) : quickFilter.split(" ");
    } else {
      this.quickFilterParts = null;
    }
  }
  parseFilter(newFilter) {
    if (!_exists(newFilter)) {
      return null;
    }
    return newFilter.toUpperCase();
  }
  setFilter(newFilter) {
    if (newFilter != null && typeof newFilter !== "string") {
      _warn(70, { newFilter });
      return;
    }
    const parsedFilter = this.parseFilter(newFilter);
    if (this.quickFilter !== parsedFilter) {
      this.quickFilter = parsedFilter;
      this.setFilterParts();
      this.dispatchLocalEvent({ type: "quickFilterChanged" });
    }
  }
  setParserAndMatcher() {
    const parser = this.gos.get("quickFilterParser");
    const matcher = this.gos.get("quickFilterMatcher");
    const hasChanged = parser !== this.parser || matcher !== this.matcher;
    this.parser = parser;
    this.matcher = matcher;
    if (hasChanged) {
      this.setFilterParts();
      this.dispatchLocalEvent({ type: "quickFilterChanged" });
    }
  }
  onColumnConfigChanged() {
    this.refreshCols();
    this.resetCache();
    if (this.isFilterPresent()) {
      this.dispatchLocalEvent({ type: "quickFilterChanged" });
    }
  }
  doesRowPassNoCache(node2, filterPart) {
    return this.colsToUse.some((column2) => {
      const part = this.getTextForColumn(column2, node2);
      return _exists(part) && part.includes(filterPart);
    });
  }
  doesRowPassCache(node2, filterPart) {
    this.checkGenerateAggText(node2);
    return node2.quickFilterAggregateText.includes(filterPart);
  }
  doesRowPassMatcher(usingCache, node2) {
    let quickFilterAggregateText;
    if (usingCache) {
      this.checkGenerateAggText(node2);
      quickFilterAggregateText = node2.quickFilterAggregateText;
    } else {
      quickFilterAggregateText = this.getAggText(node2);
    }
    const { quickFilterParts, matcher } = this;
    return matcher(quickFilterParts, quickFilterAggregateText);
  }
  checkGenerateAggText(node2) {
    if (!node2.quickFilterAggregateText) {
      node2.quickFilterAggregateText = this.getAggText(node2);
    }
  }
  getTextForColumn(column2, node2) {
    let value2 = this.beans.filterValueSvc.getValue(column2, node2);
    const colDef = column2.getColDef();
    if (colDef.getQuickFilterText) {
      const params = _addGridCommonParams(this.gos, {
        value: value2,
        node: node2,
        data: node2.data,
        column: column2,
        colDef
      });
      value2 = colDef.getQuickFilterText(params);
    }
    return _exists(value2) ? value2.toString().toUpperCase() : null;
  }
  getAggText(node2) {
    const stringParts = [];
    for (const column2 of this.colsToUse) {
      const part = this.getTextForColumn(column2, node2);
      if (_exists(part)) {
        stringParts.push(part);
      }
    }
    return stringParts.join("\n");
  }
};
var ClientSideRowModelFilterModule = {
  moduleName: "ClientSideRowModelFilter",
  version: VERSION,
  rowModels: ["clientSide"],
  beans: [FilterStage]
};
var FilterCoreModule = {
  moduleName: "FilterCore",
  version: VERSION,
  beans: [FilterManager],
  apiFunctions: {
    isAnyFilterPresent,
    onFilterChanged
  },
  css: [columnFiltersCSS],
  dependsOn: [ClientSideRowModelFilterModule]
};
var FilterValueModule = {
  moduleName: "FilterValue",
  version: VERSION,
  beans: [FilterValueService]
};
var ColumnFilterModule = {
  moduleName: "ColumnFilter",
  version: VERSION,
  beans: [ColumnFilterService, FilterMenuFactory],
  dynamicBeans: { headerFilterCellCtrl: HeaderFilterCellCtrl },
  icons: {
    // open filter button - header, floating filter, menu
    filter: "filter",
    // filter is applied - header (legacy column menu), filter tool panel
    filterActive: "filter"
  },
  apiFunctions: {
    isColumnFilterPresent,
    getColumnFilterInstance,
    destroyFilter,
    setFilterModel,
    getFilterModel,
    getColumnFilterModel,
    setColumnFilterModel,
    showColumnFilter,
    hideColumnFilter,
    getColumnFilterHandler,
    doFilterAction
  },
  dependsOn: [FilterCoreModule, PopupModule, FilterValueModule, SharedMenuModule]
};
var CustomFilterModule = {
  moduleName: "CustomFilter",
  version: VERSION,
  userComponents: { agReadOnlyFloatingFilter: ReadOnlyFloatingFilter },
  dependsOn: [ColumnFilterModule]
};
var TextFilterModule = {
  moduleName: "TextFilter",
  version: VERSION,
  dependsOn: [ColumnFilterModule],
  userComponents: {
    agTextColumnFilter: {
      classImp: TextFilter,
      params: {
        useForm: true
      }
    },
    agTextColumnFloatingFilter: TextFloatingFilter
  },
  dynamicBeans: {
    agTextColumnFilterHandler: TextFilterHandler
  }
};
var NumberFilterModule = {
  moduleName: "NumberFilter",
  version: VERSION,
  dependsOn: [ColumnFilterModule],
  userComponents: {
    agNumberColumnFilter: {
      classImp: NumberFilter,
      params: {
        useForm: true
      }
    },
    agNumberColumnFloatingFilter: NumberFloatingFilter
  },
  dynamicBeans: {
    agNumberColumnFilterHandler: NumberFilterHandler
  }
};
var DateFilterModule = {
  moduleName: "DateFilter",
  version: VERSION,
  dependsOn: [ColumnFilterModule],
  userComponents: {
    agDateColumnFilter: {
      classImp: DateFilter,
      params: {
        useForm: true
      }
    },
    agDateInput: DefaultDateComponent,
    agDateColumnFloatingFilter: DateFloatingFilter
  },
  dynamicBeans: {
    agDateColumnFilterHandler: DateFilterHandler
  }
};
var QuickFilterCoreModule = {
  moduleName: "QuickFilterCore",
  version: VERSION,
  rowModels: ["clientSide"],
  beans: [QuickFilterService],
  dependsOn: [FilterCoreModule, FilterValueModule]
};
var QuickFilterModule = {
  moduleName: "QuickFilter",
  version: VERSION,
  apiFunctions: {
    isQuickFilterPresent,
    getQuickFilter,
    resetQuickFilter
  },
  dependsOn: [QuickFilterCoreModule]
};
var ExternalFilterModule = {
  moduleName: "ExternalFilter",
  version: VERSION,
  dependsOn: [FilterCoreModule]
};
var tooltipCSS = (
  /*css*/
  `.ag-tooltip{background-color:var(--ag-tooltip-background-color);border:var(--ag-tooltip-border);border-radius:var(--ag-border-radius);color:var(--ag-tooltip-text-color);padding:var(--ag-widget-container-vertical-padding) var(--ag-widget-container-horizontal-padding);position:absolute;white-space:normal;z-index:99999;&:where(.ag-cell-editor-tooltip){background-color:var(--ag-tooltip-error-background-color);border:var(--ag-tooltip-error-border);color:var(--ag-tooltip-error-text-color);font-weight:500}}.ag-tooltip-custom{position:absolute;z-index:99999}.ag-tooltip-custom:where(:not(.ag-tooltip-interactive)),.ag-tooltip:where(:not(.ag-tooltip-interactive)){pointer-events:none}.ag-tooltip-animate{transition:opacity 1s;&:where(.ag-tooltip-hiding){opacity:0}}`
);
var getEditErrorsForPosition = (beans, cellCtrl, translate) => {
  const { editModelSvc } = beans;
  const cellValidationErrors = editModelSvc?.getCellValidationModel()?.getCellValidation(cellCtrl)?.errorMessages;
  const rowValidationErrors = editModelSvc?.getRowValidationModel().getRowValidation(cellCtrl)?.errorMessages;
  const errors2 = cellValidationErrors || rowValidationErrors;
  return errors2?.length ? errors2.join(translate("tooltipValidationErrorSeparator", ". ")) : void 0;
};
var TooltipService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "tooltipSvc";
  }
  setupHeaderTooltip(existingTooltipFeature, ctrl, passedValue, shouldDisplayTooltip) {
    if (existingTooltipFeature) {
      ctrl.destroyBean(existingTooltipFeature);
    }
    const gos = this.gos;
    const isTooltipWhenTruncated = _isShowTooltipWhenTruncated(gos);
    const { column: column2, eGui } = ctrl;
    const colDef = column2.getColDef();
    if (!shouldDisplayTooltip && isTooltipWhenTruncated && !colDef.headerComponent) {
      shouldDisplayTooltip = _isElementOverflowingCallback(
        () => eGui.querySelector(".ag-header-cell-text")
      );
    }
    const location = "header";
    const headerLocation = "header";
    const valueFormatted = this.beans.colNames.getDisplayNameForColumn(column2, headerLocation, true);
    const value2 = passedValue ?? valueFormatted;
    const tooltipCtrl = {
      getGui: () => eGui,
      getLocation: () => location,
      getTooltipValue: () => passedValue ?? colDef?.headerTooltipValueGetter?.(
        _addGridCommonParams(gos, { location, colDef, column: column2, value: value2, valueFormatted })
      ) ?? colDef?.headerTooltip,
      shouldDisplayTooltip,
      getAdditionalParams: () => ({
        column: column2,
        colDef: column2.getColDef()
      })
    };
    let tooltipFeature = this.createTooltipFeature(tooltipCtrl);
    if (tooltipFeature) {
      tooltipFeature = ctrl.createBean(tooltipFeature);
      ctrl.setRefreshFunction("tooltip", () => tooltipFeature.refreshTooltip());
    }
    return tooltipFeature;
  }
  setupHeaderGroupTooltip(existingTooltipFeature, ctrl, passedValue, shouldDisplayTooltip) {
    if (existingTooltipFeature) {
      ctrl.destroyBean(existingTooltipFeature);
    }
    const gos = this.gos;
    const isTooltipWhenTruncated = _isShowTooltipWhenTruncated(gos);
    const { column: column2, eGui } = ctrl;
    const colDef = column2.getColGroupDef();
    if (!shouldDisplayTooltip && isTooltipWhenTruncated && !colDef?.headerGroupComponent) {
      shouldDisplayTooltip = _isElementOverflowingCallback(
        () => eGui.querySelector(".ag-header-group-text")
      );
    }
    const location = "headerGroup";
    const headerLocation = "header";
    const valueFormatted = this.beans.colNames.getDisplayNameForColumnGroup(column2, headerLocation);
    const value2 = passedValue ?? valueFormatted;
    const tooltipCtrl = {
      getGui: () => eGui,
      getLocation: () => location,
      getTooltipValue: () => passedValue ?? colDef?.headerTooltipValueGetter?.(
        _addGridCommonParams(gos, { location, colDef, column: column2, value: value2, valueFormatted })
      ) ?? colDef?.headerTooltip,
      shouldDisplayTooltip,
      getAdditionalParams: () => {
        const additionalParams = {
          column: column2
        };
        if (colDef) {
          additionalParams.colDef = colDef;
        }
        return additionalParams;
      }
    };
    const tooltipFeature = this.createTooltipFeature(tooltipCtrl);
    return tooltipFeature ? ctrl.createBean(tooltipFeature) : tooltipFeature;
  }
  enableCellTooltipFeature(ctrl, value2, shouldDisplayTooltip) {
    const { beans } = this;
    const { gos, editSvc } = beans;
    const { column: column2, rowNode } = ctrl;
    let location = "cell";
    const getTooltipValue = () => {
      const isEditing2 = !!editSvc?.isEditing(ctrl);
      const errorMessages = !isEditing2 && getEditErrorsForPosition(beans, ctrl, this.getLocaleTextFunc());
      if (errorMessages) {
        location = "cellEditor";
        return errorMessages;
      }
      location = "cell";
      const colDef = column2.getColDef();
      const data2 = rowNode.data;
      if (colDef.tooltipField && _exists(data2)) {
        return _getValueUsingField(data2, colDef.tooltipField, column2.isTooltipFieldContainsDots());
      }
      const valueGetter = colDef.tooltipValueGetter;
      if (valueGetter) {
        return valueGetter(
          _addGridCommonParams(gos, {
            location: "cell",
            colDef: column2.getColDef(),
            column: column2,
            rowIndex: ctrl.cellPosition.rowIndex,
            node: rowNode,
            data: rowNode.data,
            value: ctrl.value,
            valueFormatted: ctrl.valueFormatted
          })
        );
      }
      return null;
    };
    const isTooltipWhenTruncated = _isShowTooltipWhenTruncated(gos);
    if (!shouldDisplayTooltip) {
      if (isTooltipWhenTruncated && !ctrl.isCellRenderer()) {
        shouldDisplayTooltip = () => {
          const isEditing2 = !!editSvc?.isEditing(ctrl);
          const errorMessages = !isEditing2 && getEditErrorsForPosition(beans, ctrl, this.getLocaleTextFunc());
          if (errorMessages) {
            return true;
          }
          const isTooltipEnabled = column2.isTooltipEnabled();
          if (!isTooltipEnabled) {
            return false;
          }
          const isElementOverflowing = _isElementOverflowingCallback(() => {
            const eCell = ctrl.eGui;
            return eCell.children.length === 0 ? eCell : eCell.querySelector(".ag-cell-value");
          });
          return !isEditing2 && isElementOverflowing();
        };
      } else {
        shouldDisplayTooltip = () => !editSvc?.isEditing(ctrl);
      }
    }
    const tooltipCtrl = {
      getGui: () => ctrl.eGui,
      getLocation: () => location,
      getTooltipValue: value2 != null ? () => value2 : getTooltipValue,
      shouldDisplayTooltip,
      getAdditionalParams: () => ({
        column: column2,
        colDef: column2.getColDef(),
        rowIndex: ctrl.cellPosition.rowIndex,
        node: rowNode,
        data: rowNode.data,
        valueFormatted: ctrl.valueFormatted
      })
    };
    return this.createTooltipFeature(tooltipCtrl, beans);
  }
  setupFullWidthRowTooltip(existingTooltipFeature, ctrl, value2, shouldDisplayTooltip) {
    const tooltipParams = {
      getGui: () => ctrl.getFullWidthElement(),
      getTooltipValue: () => value2,
      getLocation: () => "fullWidthRow",
      shouldDisplayTooltip
    };
    const beans = this.beans;
    const context = beans.context;
    if (existingTooltipFeature) {
      ctrl.destroyBean(existingTooltipFeature, context);
    }
    const tooltipFeature = this.createTooltipFeature(tooltipParams, beans);
    if (!tooltipFeature) {
      return;
    }
    return ctrl.createBean(tooltipFeature, context);
  }
  setupCellEditorTooltip(cellCtrl, editor) {
    const { beans } = this;
    const { context } = beans;
    const el = editor.getValidationElement?.(true) || !editor.isPopup?.() && cellCtrl.eGui;
    if (!el) {
      return;
    }
    const tooltipParams = {
      getGui: () => el,
      getTooltipValue: () => getEditErrorsForPosition(beans, cellCtrl, this.getLocaleTextFunc()),
      getLocation: () => "cellEditor",
      shouldDisplayTooltip: () => {
        const { editModelSvc } = beans;
        const rowValidationMap = editModelSvc?.getRowValidationModel()?.getRowValidationMap();
        const cellValidationMap = editModelSvc?.getCellValidationModel()?.getCellValidationMap();
        const hasRowValidationErrors = !!rowValidationMap && rowValidationMap.size > 0;
        const hasCellValidationErrors = !!cellValidationMap && cellValidationMap.size > 0;
        return hasRowValidationErrors || hasCellValidationErrors;
      }
    };
    const tooltipFeature = this.createTooltipFeature(tooltipParams, beans);
    if (!tooltipFeature) {
      return;
    }
    return cellCtrl.createBean(tooltipFeature, context);
  }
  initCol(column2) {
    const { colDef } = column2;
    column2.tooltipEnabled = _exists(colDef.tooltipField) || _exists(colDef.tooltipValueGetter) || _exists(colDef.tooltipComponent);
  }
  createTooltipFeature(tooltipCtrl, beans) {
    return this.beans.registry.createDynamicBean("tooltipFeature", false, tooltipCtrl, beans);
  }
};
var TooltipStateManager = class extends BaseTooltipStateManager {
  createTooltipComp(params, callback) {
    const userDetails = _getTooltipCompDetails(this.beans.userCompFactory, params);
    userDetails?.newAgStackInstance().then(callback);
  }
  setEventHandlers(listener) {
    [this.onColumnMovedEventCallback] = this.addManagedEventListeners({
      columnMoved: listener
    });
  }
  clearEventHandlers() {
    this.onColumnMovedEventCallback?.();
    this.onColumnMovedEventCallback = void 0;
  }
};
var TooltipModule = {
  moduleName: "Tooltip",
  version: VERSION,
  beans: [TooltipService],
  dynamicBeans: {
    tooltipFeature: AgTooltipFeature,
    highlightTooltipFeature: AgHighlightTooltipFeature,
    tooltipStateManager: TooltipStateManager
  },
  userComponents: {
    agTooltipComponent: AgTooltipComponent
  },
  dependsOn: [PopupModule],
  css: [tooltipCSS]
};
var UndoRedoAction = class {
  constructor(cellValueChanges) {
    this.cellValueChanges = cellValueChanges;
  }
};
var RangeUndoRedoAction = class extends UndoRedoAction {
  constructor(cellValueChanges, initialRange, finalRange, ranges) {
    super(cellValueChanges);
    this.initialRange = initialRange;
    this.finalRange = finalRange;
    this.ranges = ranges;
  }
};
var DEFAULT_STACK_SIZE = 10;
var UndoRedoStack = class {
  constructor(maxStackSize) {
    this.actionStack = [];
    this.maxStackSize = maxStackSize ? maxStackSize : DEFAULT_STACK_SIZE;
    this.actionStack = new Array(this.maxStackSize);
  }
  pop() {
    return this.actionStack.pop();
  }
  push(item2) {
    const shouldAddActions = item2.cellValueChanges && item2.cellValueChanges.length > 0;
    if (!shouldAddActions) {
      return;
    }
    if (this.actionStack.length === this.maxStackSize) {
      this.actionStack.shift();
    }
    this.actionStack.push(item2);
  }
  clear() {
    this.actionStack = [];
  }
  getCurrentStackSize() {
    return this.actionStack.length;
  }
};
var UndoRedoService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "undoRedo";
    this.cellValueChanges = [];
    this.activeCellEdit = null;
    this.activeRowEdit = null;
    this.isPasting = false;
    this.isRangeInAction = false;
    this.batchEditing = false;
    this.bulkEditing = false;
    this.onCellValueChanged = (event) => {
      const eventCell = { column: event.column, rowIndex: event.rowIndex, rowPinned: event.rowPinned };
      const isCellEditing = this.activeCellEdit !== null && _areCellsEqual(this.activeCellEdit, eventCell);
      const isRowEditing = this.activeRowEdit !== null && _isSameRow(this.activeRowEdit, eventCell);
      const shouldCaptureAction = isCellEditing || isRowEditing || this.isPasting || this.isRangeInAction;
      if (!shouldCaptureAction) {
        return;
      }
      const { rowPinned, rowIndex, column: column2, oldValue, value: value2 } = event;
      const cellValueChange = {
        rowPinned,
        rowIndex,
        columnId: column2.getColId(),
        newValue: value2,
        oldValue
      };
      this.cellValueChanges.push(cellValueChange);
    };
    this.clearStacks = () => {
      this.undoStack.clear();
      this.redoStack.clear();
    };
  }
  postConstruct() {
    const { gos, ctrlsSvc } = this.beans;
    if (!gos.get("undoRedoCellEditing")) {
      return;
    }
    const undoRedoLimit = gos.get("undoRedoCellEditingLimit");
    if (undoRedoLimit <= 0) {
      return;
    }
    this.undoStack = new UndoRedoStack(undoRedoLimit);
    this.redoStack = new UndoRedoStack(undoRedoLimit);
    this.addListeners();
    const listener = this.clearStacks.bind(this);
    this.addManagedEventListeners({
      cellValueChanged: this.onCellValueChanged.bind(this),
      // undo / redo is restricted to actual editing so we clear the stacks when other operations are
      // performed that change the order of the row / cols.
      modelUpdated: (e) => {
        if (!e.keepUndoRedoStack) {
          this.clearStacks();
        }
      },
      columnPivotModeChanged: listener,
      newColumnsLoaded: listener,
      columnGroupOpened: listener,
      columnRowGroupChanged: listener,
      columnMoved: listener,
      columnPinned: listener,
      columnVisible: listener,
      rowDragEnd: listener
    });
    ctrlsSvc.whenReady(this, (p) => {
      this.gridBodyCtrl = p.gridBodyCtrl;
    });
  }
  getCurrentUndoStackSize() {
    return this.undoStack?.getCurrentStackSize() ?? 0;
  }
  getCurrentRedoStackSize() {
    return this.redoStack?.getCurrentStackSize() ?? 0;
  }
  undo(source2) {
    const { eventSvc, undoStack, redoStack } = this;
    eventSvc.dispatchEvent({
      type: "undoStarted",
      source: source2
    });
    const operationPerformed = this.undoRedo(undoStack, redoStack, "initialRange", "oldValue", "undo");
    eventSvc.dispatchEvent({
      type: "undoEnded",
      source: source2,
      operationPerformed
    });
  }
  redo(source2) {
    const { eventSvc, undoStack, redoStack } = this;
    eventSvc.dispatchEvent({
      type: "redoStarted",
      source: source2
    });
    const operationPerformed = this.undoRedo(redoStack, undoStack, "finalRange", "newValue", "redo");
    eventSvc.dispatchEvent({
      type: "redoEnded",
      source: source2,
      operationPerformed
    });
  }
  undoRedo(undoRedoStack, opposingUndoRedoStack, rangeProperty, cellValueChangeProperty, source2) {
    if (!undoRedoStack) {
      return false;
    }
    const undoRedoAction = undoRedoStack.pop();
    if (!undoRedoAction?.cellValueChanges) {
      return false;
    }
    this.processAction(
      undoRedoAction,
      (cellValueChange) => cellValueChange[cellValueChangeProperty],
      source2
    );
    if (undoRedoAction instanceof RangeUndoRedoAction) {
      this.processRange(undoRedoAction.ranges || [undoRedoAction[rangeProperty]]);
    } else {
      this.processCell(undoRedoAction.cellValueChanges);
    }
    opposingUndoRedoStack.push(undoRedoAction);
    return true;
  }
  processAction(action, valueExtractor, source2) {
    for (const cellValueChange of action.cellValueChanges) {
      const { rowIndex, rowPinned, columnId } = cellValueChange;
      const rowPosition = { rowIndex, rowPinned };
      const currentRow = _getRowNode(this.beans, rowPosition);
      if (!currentRow.displayed) {
        continue;
      }
      currentRow.setDataValue(columnId, valueExtractor(cellValueChange), source2);
    }
  }
  processRange(ranges) {
    let lastFocusedCell;
    const rangeSvc = this.beans.rangeSvc;
    rangeSvc.removeAllCellRanges(true);
    ranges.forEach((range, idx) => {
      if (!range) {
        return;
      }
      const startRow = range.startRow;
      const endRow = range.endRow;
      if (idx === ranges.length - 1) {
        lastFocusedCell = {
          rowPinned: startRow.rowPinned,
          rowIndex: startRow.rowIndex,
          columnId: range.startColumn.getColId()
        };
        this.setLastFocusedCell(lastFocusedCell);
      }
      const cellRangeParams = {
        rowStartIndex: startRow.rowIndex,
        rowStartPinned: startRow.rowPinned,
        rowEndIndex: endRow.rowIndex,
        rowEndPinned: endRow.rowPinned,
        columnStart: range.startColumn,
        columns: range.columns
      };
      rangeSvc.addCellRange(cellRangeParams);
    });
  }
  processCell(cellValueChanges) {
    const cellValueChange = cellValueChanges[0];
    const { rowIndex, rowPinned } = cellValueChange;
    const rowPosition = { rowIndex, rowPinned };
    const row2 = _getRowNode(this.beans, rowPosition);
    const lastFocusedCell = {
      rowPinned: cellValueChange.rowPinned,
      rowIndex: row2.rowIndex,
      columnId: cellValueChange.columnId
    };
    this.setLastFocusedCell(lastFocusedCell);
  }
  setLastFocusedCell(lastFocusedCell) {
    const { rowIndex, columnId, rowPinned } = lastFocusedCell;
    const { colModel, focusSvc, rangeSvc } = this.beans;
    const column2 = colModel.getCol(columnId);
    if (!column2) {
      return;
    }
    const { scrollFeature } = this.gridBodyCtrl;
    scrollFeature.ensureIndexVisible(rowIndex);
    scrollFeature.ensureColumnVisible(column2);
    const cellPosition = { rowIndex, column: column2, rowPinned };
    focusSvc.setFocusedCell({ ...cellPosition, forceBrowserFocus: true });
    rangeSvc?.setRangeToCell(cellPosition);
  }
  addListeners() {
    this.addManagedEventListeners({
      rowEditingStarted: (e) => {
        this.activeRowEdit = { rowIndex: e.rowIndex, rowPinned: e.rowPinned };
      },
      rowEditingStopped: () => {
        const action = new UndoRedoAction(this.cellValueChanges);
        this.pushActionsToUndoStack(action);
        this.activeRowEdit = null;
      },
      cellEditingStarted: (e) => {
        this.activeCellEdit = { column: e.column, rowIndex: e.rowIndex, rowPinned: e.rowPinned };
      },
      cellEditingStopped: (e) => {
        this.activeCellEdit = null;
        const shouldPushAction = e.valueChanged && !this.activeRowEdit && !this.isPasting && !this.isRangeInAction;
        if (shouldPushAction) {
          const action = new UndoRedoAction(this.cellValueChanges);
          this.pushActionsToUndoStack(action);
        }
      },
      pasteStart: () => {
        this.isPasting = true;
      },
      pasteEnd: () => {
        const action = new UndoRedoAction(this.cellValueChanges);
        this.pushActionsToUndoStack(action);
        this.isPasting = false;
      },
      fillStart: () => {
        this.isRangeInAction = true;
      },
      fillEnd: (event) => {
        const action = new RangeUndoRedoAction(this.cellValueChanges, event.initialRange, event.finalRange);
        this.pushActionsToUndoStack(action);
        this.isRangeInAction = false;
      },
      keyShortcutChangedCellStart: () => {
        this.isRangeInAction = true;
      },
      keyShortcutChangedCellEnd: () => {
        let action;
        const { rangeSvc, gos } = this.beans;
        if (rangeSvc && _isCellSelectionEnabled(gos)) {
          action = new RangeUndoRedoAction(this.cellValueChanges, void 0, void 0, [
            ...rangeSvc.getCellRanges()
          ]);
        } else {
          action = new UndoRedoAction(this.cellValueChanges);
        }
        this.pushActionsToUndoStack(action);
        this.isRangeInAction = false;
      },
      batchEditingStarted: () => this.startBigChange("batchEditing"),
      batchEditingStopped: ({ changes }) => this.stopBigChange("batchEditing", changes),
      bulkEditingStarted: () => this.startBigChange("bulkEditing"),
      bulkEditingStopped: ({ changes }) => this.stopBigChange("bulkEditing", changes)
    });
  }
  startBigChange(key2) {
    this.updateBigChange(key2, true);
  }
  updateBigChange(key2, value2) {
    if (key2 === "bulkEditing") {
      this.bulkEditing = value2;
    } else {
      this.batchEditing = value2;
    }
  }
  stopBigChange(key2, changes) {
    if (key2 === "bulkEditing" && !this.bulkEditing || key2 === "batchEditing" && !this.batchEditing) {
      return;
    }
    this.updateBigChange(key2, false);
    if (changes?.length === 0) {
      return;
    }
    const action = new UndoRedoAction(changes ?? []);
    this.pushActionsToUndoStack(action);
    this.cellValueChanges = [];
  }
  pushActionsToUndoStack(action) {
    this.undoStack.push(action);
    this.cellValueChanges = [];
    this.redoStack.clear();
  }
};
var cellEditingCSS = (
  /*css*/
  `.ag-cell-inline-editing{border:var(--ag-cell-editing-border)!important;border-radius:var(--ag-border-radius);box-shadow:var(--ag-cell-editing-shadow);padding:0;z-index:1;.ag-cell-edit-wrapper,.ag-cell-editor,.ag-cell-wrapper,:where(.ag-cell-editor) .ag-input-field-input,:where(.ag-cell-editor) .ag-wrapper{height:100%;line-height:normal;min-height:100%;width:100%}&.ag-cell-editing-error{border-color:var(--ag-invalid-color)!important}}:where(.ag-popup-editor) .ag-large-text{background-color:var(--ag-background-color);border-radius:var(--ag-border-radius);box-shadow:var(--ag-dropdown-shadow);padding:0}.ag-large-text-input{display:block;height:auto;padding:var(--ag-cell-horizontal-padding)}:where(.ag-rtl .ag-large-text-input) textarea{resize:none}:where(.ag-ltr) .ag-checkbox-edit{padding-left:var(--ag-cell-horizontal-padding)}:where(.ag-rtl) .ag-checkbox-edit{padding-right:var(--ag-cell-horizontal-padding)}:where(.ag-row.ag-row-editing-invalid .ag-cell-inline-editing){opacity:.8}.ag-popup-editor{position:absolute;-webkit-user-select:none;-moz-user-select:none;user-select:none}`
);
var CheckboxCellEditorElement = {
  tag: "div",
  cls: "ag-cell-wrapper ag-cell-edit-wrapper ag-checkbox-edit",
  children: [
    {
      tag: "ag-checkbox",
      ref: "eEditor",
      role: "presentation"
    }
  ]
};
var CheckboxCellEditor = class extends AgAbstractCellEditor {
  constructor() {
    super(CheckboxCellEditorElement, [AgCheckboxSelector]);
    this.eEditor = RefPlaceholder;
  }
  initialiseEditor(params) {
    const isSelected = params.value ?? void 0;
    const eEditor = this.eEditor;
    eEditor.setValue(isSelected);
    const inputEl = eEditor.getInputElement();
    inputEl.setAttribute("tabindex", "-1");
    this.setAriaLabel(isSelected);
    this.addManagedListeners(eEditor, {
      fieldValueChanged: (event) => this.setAriaLabel(event.selected)
    });
  }
  getValue() {
    return this.eEditor.getValue();
  }
  focusIn() {
    this.eEditor.getFocusableElement().focus();
  }
  afterGuiAttached() {
    if (this.params.cellStartedEdit) {
      this.focusIn();
    }
  }
  isPopup() {
    return false;
  }
  setAriaLabel(isSelected) {
    const translate = this.getLocaleTextFunc();
    const stateName = _getAriaCheckboxStateName(translate, isSelected);
    const ariaLabel = translate("ariaToggleCellValue", "Press SPACE to toggle cell value");
    this.eEditor.setInputAriaLabel(`${ariaLabel} (${stateName})`);
  }
  getValidationElement(tooltip) {
    return tooltip ? this.params.eGridCell : this.eEditor.getInputElement();
  }
  getValidationErrors() {
    const { params } = this;
    const { getValidationErrors } = params;
    const value2 = this.getValue();
    if (!getValidationErrors) {
      return null;
    }
    return getValidationErrors({
      value: value2,
      internalErrors: null,
      cellEditorParams: params
    });
  }
};
var SimpleCellEditor = class extends AgAbstractCellEditor {
  constructor(cellEditorInput) {
    super();
    this.cellEditorInput = cellEditorInput;
    this.eEditor = RefPlaceholder;
  }
  initialiseEditor(params) {
    const { cellEditorInput } = this;
    this.setTemplate(
      { tag: "div", cls: "ag-cell-edit-wrapper", children: [cellEditorInput.getTemplate()] },
      cellEditorInput.getAgComponents()
    );
    const { eEditor } = this;
    const { cellStartedEdit, eventKey, suppressPreventDefault } = params;
    eEditor.getInputElement().setAttribute("title", "");
    cellEditorInput.init(eEditor, params);
    let startValue;
    let shouldSetStartValue = true;
    if (cellStartedEdit) {
      this.focusAfterAttached = true;
      if (eventKey === KeyCode.BACKSPACE || eventKey === KeyCode.DELETE) {
        startValue = "";
      } else if (eventKey && eventKey.length === 1) {
        if (suppressPreventDefault) {
          shouldSetStartValue = false;
        } else {
          startValue = eventKey;
        }
      } else {
        startValue = cellEditorInput.getStartValue();
        if (eventKey !== KeyCode.F2) {
          this.highlightAllOnFocus = true;
        }
      }
    } else {
      this.focusAfterAttached = false;
      startValue = cellEditorInput.getStartValue();
    }
    if (shouldSetStartValue && startValue != null) {
      eEditor.setStartValue(startValue);
    }
    this.addGuiEventListener("keydown", (event) => {
      const { key: key2 } = event;
      if (key2 === KeyCode.PAGE_UP || key2 === KeyCode.PAGE_DOWN) {
        event.preventDefault();
      }
    });
  }
  afterGuiAttached() {
    const translate = this.getLocaleTextFunc();
    const eInput = this.eEditor;
    eInput.setInputAriaLabel(translate("ariaInputEditor", "Input Editor"));
    if (!this.focusAfterAttached) {
      return;
    }
    if (!_isBrowserSafari()) {
      eInput.getFocusableElement().focus();
    }
    const inputEl = eInput.getInputElement();
    if (this.highlightAllOnFocus) {
      inputEl.select();
    } else {
      this.cellEditorInput.setCaret?.();
    }
  }
  // gets called when tabbing through cells and in full row edit mode
  focusIn() {
    const { eEditor } = this;
    const focusEl = eEditor.getFocusableElement();
    const inputEl = eEditor.getInputElement();
    focusEl.focus();
    inputEl.select();
  }
  getValue() {
    return this.cellEditorInput.getValue();
  }
  isPopup() {
    return false;
  }
  getValidationElement() {
    return this.eEditor.getInputElement();
  }
  getValidationErrors() {
    return this.cellEditorInput.getValidationErrors();
  }
};
var DateCellElement = {
  tag: "ag-input-date-field",
  ref: "eEditor",
  cls: "ag-cell-editor"
};
var DateCellEditorInput = class {
  constructor(getDataTypeService, getLocaleTextFunc) {
    this.getDataTypeService = getDataTypeService;
    this.getLocaleTextFunc = getLocaleTextFunc;
  }
  getTemplate() {
    return DateCellElement;
  }
  getAgComponents() {
    return [AgInputDateFieldSelector];
  }
  init(eEditor, params) {
    this.eEditor = eEditor;
    this.params = params;
    const { min: min2, max: max2, step, colDef } = params;
    if (min2 != null) {
      eEditor.setMin(min2);
    }
    if (max2 != null) {
      eEditor.setMax(max2);
    }
    if (step != null) {
      eEditor.setStep(step);
    }
    this.includeTime = params.includeTime ?? this.getDataTypeService()?.getDateIncludesTimeFlag?.(colDef.cellDataType);
    if (this.includeTime != null) {
      eEditor.setIncludeTime(this.includeTime);
    }
  }
  getValidationErrors() {
    const eInput = this.eEditor.getInputElement();
    const value2 = eInput.valueAsDate;
    const { params } = this;
    const { min: min2, max: max2, getValidationErrors } = params;
    let internalErrors = [];
    const translate = this.getLocaleTextFunc();
    if (value2 instanceof Date && !isNaN(value2.getTime())) {
      if (min2) {
        const minValue = min2 instanceof Date ? min2 : new Date(min2);
        if (value2 < minValue) {
          const minDateString = minValue.toLocaleDateString();
          internalErrors.push(
            translate("minDateValidation", `Date must be after ${minDateString}`, [minDateString])
          );
        }
      }
      if (max2) {
        const maxValue = max2 instanceof Date ? max2 : new Date(max2);
        if (value2 > maxValue) {
          const maxDateString = maxValue.toLocaleDateString();
          internalErrors.push(
            translate("maxDateValidation", `Date must be before ${maxDateString}`, [maxDateString])
          );
        }
      }
    }
    if (!internalErrors.length) {
      internalErrors = null;
    }
    if (getValidationErrors) {
      return getValidationErrors({ value: value2, cellEditorParams: params, internalErrors });
    }
    return internalErrors;
  }
  getValue() {
    const { eEditor, params } = this;
    const value2 = eEditor.getDate();
    if (!_exists(value2) && !_exists(params.value)) {
      return params.value;
    }
    return value2 ?? null;
  }
  getStartValue() {
    const { value: value2 } = this.params;
    if (!(value2 instanceof Date)) {
      return void 0;
    }
    return _serialiseDate(value2, this.includeTime ?? false);
  }
};
var DateCellEditor = class extends SimpleCellEditor {
  constructor() {
    super(
      new DateCellEditorInput(
        () => this.beans.dataTypeSvc,
        () => this.getLocaleTextFunc()
      )
    );
  }
};
var DateStringCellElement = {
  tag: "ag-input-date-field",
  ref: "eEditor",
  cls: "ag-cell-editor"
};
var DateStringCellEditorInput = class {
  constructor(getDataTypeService, getLocaleTextFunc) {
    this.getDataTypeService = getDataTypeService;
    this.getLocaleTextFunc = getLocaleTextFunc;
  }
  getTemplate() {
    return DateStringCellElement;
  }
  getAgComponents() {
    return [AgInputDateFieldSelector];
  }
  init(eEditor, params) {
    this.eEditor = eEditor;
    this.params = params;
    const { min: min2, max: max2, step, colDef } = params;
    if (min2 != null) {
      eEditor.setMin(min2);
    }
    if (max2 != null) {
      eEditor.setMax(max2);
    }
    if (step != null) {
      eEditor.setStep(step);
    }
    this.includeTime = params.includeTime ?? this.getDataTypeService()?.getDateIncludesTimeFlag?.(colDef.cellDataType);
    if (this.includeTime != null) {
      eEditor.setIncludeTime(this.includeTime);
    }
  }
  getValidationErrors() {
    const { eEditor, params } = this;
    const raw = eEditor.getInputElement().value;
    const value2 = this.formatDate(this.parseDate(raw ?? void 0));
    const { min: min2, max: max2, getValidationErrors } = params;
    let internalErrors = [];
    if (value2) {
      const date2 = new Date(value2);
      const translate = this.getLocaleTextFunc();
      if (min2) {
        const minDate = new Date(min2);
        if (date2 < minDate) {
          const minDateString = minDate.toLocaleDateString();
          internalErrors.push(
            translate("minDateValidation", `Date must be after ${minDateString}`, [minDateString])
          );
        }
      }
      if (max2) {
        const maxDate = new Date(max2);
        if (date2 > maxDate) {
          const maxDateString = maxDate.toLocaleDateString();
          internalErrors.push(
            translate("maxDateValidation", `Date must be before ${maxDateString}`, [maxDateString])
          );
        }
      }
    }
    if (!internalErrors.length) {
      internalErrors = null;
    }
    if (getValidationErrors) {
      return getValidationErrors({
        value: this.getValue(),
        cellEditorParams: params,
        internalErrors
      });
    }
    return internalErrors;
  }
  getValue() {
    const { params, eEditor } = this;
    const value2 = this.formatDate(eEditor.getDate());
    if (!_exists(value2) && !_exists(params.value)) {
      return params.value;
    }
    return params.parseValue(value2 ?? "");
  }
  getStartValue() {
    return _serialiseDate(this.parseDate(this.params.value ?? void 0) ?? null, this.includeTime ?? false);
  }
  parseDate(value2) {
    const dataTypeSvc = this.getDataTypeService();
    return dataTypeSvc ? dataTypeSvc.getDateParserFunction(this.params.column)(value2) : _parseDateTimeFromString(value2) ?? void 0;
  }
  formatDate(value2) {
    const dataTypeSvc = this.getDataTypeService();
    return dataTypeSvc ? dataTypeSvc.getDateFormatterFunction(this.params.column)(value2) : _serialiseDate(value2 ?? null, this.includeTime ?? false) ?? void 0;
  }
};
var DateStringCellEditor = class extends SimpleCellEditor {
  constructor() {
    super(
      new DateStringCellEditorInput(
        () => this.beans.dataTypeSvc,
        () => this.getLocaleTextFunc()
      )
    );
  }
};
var LargeTextCellElement = {
  tag: "div",
  cls: "ag-large-text",
  children: [
    {
      tag: "ag-input-text-area",
      ref: "eEditor",
      cls: "ag-large-text-input"
    }
  ]
};
var LargeTextCellEditor = class extends AgAbstractCellEditor {
  constructor() {
    super(LargeTextCellElement, [AgInputTextAreaSelector]);
    this.eEditor = RefPlaceholder;
  }
  initialiseEditor(params) {
    const { eEditor } = this;
    const { cellStartedEdit, eventKey, maxLength, cols, rows } = params;
    this.focusAfterAttached = cellStartedEdit;
    eEditor.getInputElement().setAttribute("title", "");
    eEditor.setMaxLength(maxLength || 200).setCols(cols || 60).setRows(rows || 10);
    let startValue;
    if (cellStartedEdit) {
      this.focusAfterAttached = true;
      if (eventKey === KeyCode.BACKSPACE || eventKey === KeyCode.DELETE) {
        startValue = "";
      } else if (eventKey && eventKey.length === 1) {
        startValue = eventKey;
      } else {
        startValue = this.getStartValue(params);
        if (eventKey !== KeyCode.F2) {
          this.highlightAllOnFocus = true;
        }
      }
    } else {
      this.focusAfterAttached = false;
      startValue = this.getStartValue(params);
    }
    if (startValue != null) {
      eEditor.setValue(startValue, true);
    }
    this.addGuiEventListener("keydown", this.onKeyDown.bind(this));
    this.activateTabIndex();
  }
  getStartValue(params) {
    const { value: value2 } = params;
    return value2?.toString() ?? value2;
  }
  onKeyDown(event) {
    const key2 = event.key;
    if (key2 === KeyCode.LEFT || key2 === KeyCode.UP || key2 === KeyCode.RIGHT || key2 === KeyCode.DOWN || event.shiftKey && key2 === KeyCode.ENTER) {
      event.stopPropagation();
    }
  }
  afterGuiAttached() {
    const { eEditor, focusAfterAttached, highlightAllOnFocus } = this;
    const translate = this.getLocaleTextFunc();
    eEditor.setInputAriaLabel(translate("ariaInputEditor", "Input Editor"));
    if (focusAfterAttached) {
      eEditor.getFocusableElement().focus();
      if (highlightAllOnFocus) {
        eEditor.getInputElement().select();
      }
    }
  }
  getValue() {
    const { eEditor, params } = this;
    const { value: value2 } = params;
    const editorValue = eEditor.getValue();
    if (!_exists(editorValue) && !_exists(value2)) {
      return value2;
    }
    return params.parseValue(editorValue);
  }
  getValidationElement() {
    return this.eEditor.getInputElement();
  }
  getValidationErrors() {
    const { params } = this;
    const { maxLength, getValidationErrors } = params;
    const translate = this.getLocaleTextFunc();
    const value2 = this.getValue();
    let internalErrors = [];
    if (typeof value2 === "string" && maxLength != null && value2.length > maxLength) {
      internalErrors.push(
        translate("maxLengthValidation", `Must be ${maxLength} characters or fewer.`, [String(maxLength)])
      );
    }
    if (!internalErrors.length) {
      internalErrors = null;
    }
    if (getValidationErrors) {
      return getValidationErrors({
        value: value2,
        internalErrors,
        cellEditorParams: params
      });
    }
    return internalErrors;
  }
};
var NumberCellElement = {
  tag: "ag-input-number-field",
  ref: "eEditor",
  cls: "ag-cell-editor"
};
var NumberCellEditorInput = class {
  constructor(getLocaleTextFunc) {
    this.getLocaleTextFunc = getLocaleTextFunc;
  }
  getTemplate() {
    return NumberCellElement;
  }
  getAgComponents() {
    return [AgInputNumberFieldSelector];
  }
  init(eEditor, params) {
    this.eEditor = eEditor;
    this.params = params;
    const { max: max2, min: min2, precision, step } = params;
    if (max2 != null) {
      eEditor.setMax(max2);
    }
    if (min2 != null) {
      eEditor.setMin(min2);
    }
    if (precision != null) {
      eEditor.setPrecision(precision);
    }
    if (step != null) {
      eEditor.setStep(step);
    }
    const editorEl = eEditor.getInputElement();
    if (params.preventStepping) {
      eEditor.addManagedElementListeners(editorEl, { keydown: this.preventStepping });
    } else if (params.showStepperButtons) {
      editorEl.classList.add("ag-number-field-input-stepper");
    }
  }
  getValidationErrors() {
    const { params } = this;
    const { min: min2, max: max2, getValidationErrors } = params;
    const eInput = this.eEditor.getInputElement();
    const value2 = eInput.valueAsNumber;
    const translate = this.getLocaleTextFunc();
    let internalErrors = [];
    if (typeof value2 === "number") {
      if (min2 != null && value2 < min2) {
        internalErrors.push(
          translate("minValueValidation", `Must be greater than or equal to ${min2}.`, [String(min2)])
        );
      }
      if (max2 != null && value2 > max2) {
        internalErrors.push(
          translate("maxValueValidation", `Must be less than or equal to ${max2}.`, [String(max2)])
        );
      }
    }
    if (!internalErrors.length) {
      internalErrors = null;
    }
    if (getValidationErrors) {
      return getValidationErrors({
        value: value2,
        cellEditorParams: params,
        internalErrors
      });
    }
    return internalErrors;
  }
  preventStepping(e) {
    if (e.key === KeyCode.UP || e.key === KeyCode.DOWN) {
      e.preventDefault();
    }
  }
  getValue() {
    const { eEditor, params } = this;
    const value2 = eEditor.getValue();
    if (!_exists(value2) && !_exists(params.value)) {
      return params.value;
    }
    let parsedValue = params.parseValue(value2);
    if (parsedValue == null) {
      return parsedValue;
    }
    if (typeof parsedValue === "string") {
      if (parsedValue === "") {
        return null;
      }
      parsedValue = Number(parsedValue);
    }
    return isNaN(parsedValue) ? null : parsedValue;
  }
  getStartValue() {
    return this.params.value;
  }
  setCaret() {
    if (_isBrowserSafari()) {
      this.eEditor.getInputElement().focus({ preventScroll: true });
    }
  }
};
var NumberCellEditor = class extends SimpleCellEditor {
  constructor() {
    super(new NumberCellEditorInput(() => this.getLocaleTextFunc()));
  }
};
var SelectCellElement = {
  tag: "div",
  cls: "ag-cell-edit-wrapper",
  children: [
    {
      tag: "ag-select",
      ref: "eEditor",
      cls: "ag-cell-editor"
    }
  ]
};
var SelectCellEditor = class extends AgAbstractCellEditor {
  constructor() {
    super(SelectCellElement, [AgSelectSelector]);
    this.eEditor = RefPlaceholder;
    this.startedByEnter = false;
  }
  wireBeans(beans) {
    this.valueSvc = beans.valueSvc;
  }
  initialiseEditor(params) {
    this.focusAfterAttached = params.cellStartedEdit;
    const { eEditor, valueSvc, gos } = this;
    const { values: values2, value: value2, eventKey } = params;
    if (_missing(values2)) {
      _warn(58);
      return;
    }
    this.startedByEnter = eventKey != null ? eventKey === KeyCode.ENTER : false;
    let hasValue = false;
    values2.forEach((currentValue) => {
      const option = { value: currentValue };
      const valueFormatted = valueSvc.formatValue(params.column, null, currentValue);
      const valueFormattedExits = valueFormatted !== null && valueFormatted !== void 0;
      option.text = valueFormattedExits ? valueFormatted : currentValue;
      eEditor.addOption(option);
      hasValue = hasValue || value2 === currentValue;
    });
    if (hasValue) {
      eEditor.setValue(params.value, true);
    } else if (params.values.length) {
      eEditor.setValue(params.values[0], true);
    }
    const { valueListGap, valueListMaxWidth, valueListMaxHeight } = params;
    if (valueListGap != null) {
      eEditor.setPickerGap(valueListGap);
    }
    if (valueListMaxHeight != null) {
      eEditor.setPickerMaxHeight(valueListMaxHeight);
    }
    if (valueListMaxWidth != null) {
      eEditor.setPickerMaxWidth(valueListMaxWidth);
    }
    if (gos.get("editType") !== "fullRow") {
      this.addManagedListeners(this.eEditor, { selectedItem: () => params.stopEditing() });
    }
  }
  afterGuiAttached() {
    if (this.focusAfterAttached) {
      this.eEditor.getFocusableElement().focus();
    }
    if (this.startedByEnter) {
      setTimeout(() => {
        if (this.isAlive()) {
          this.eEditor.showPicker();
        }
      });
    }
  }
  focusIn() {
    this.eEditor.getFocusableElement().focus();
  }
  getValue() {
    return this.eEditor.getValue();
  }
  isPopup() {
    return false;
  }
  getValidationElement() {
    return this.eEditor.getAriaElement();
  }
  getValidationErrors() {
    const { params } = this;
    const { values: values2, getValidationErrors } = params;
    const value2 = this.getValue();
    let internalErrors = [];
    if (values2 && !values2.includes(value2)) {
      const translate = this.getLocaleTextFunc();
      internalErrors.push(translate("invalidSelectionValidation", "Invalid selection."));
    } else {
      internalErrors = null;
    }
    if (getValidationErrors) {
      return getValidationErrors({
        value: value2,
        internalErrors,
        cellEditorParams: params
      });
    }
    return internalErrors;
  }
};
var TextCellEditorElement = {
  tag: "ag-input-text-field",
  ref: "eEditor",
  cls: "ag-cell-editor"
};
var TextCellEditorInput = class {
  constructor(getLocaleTextFunc) {
    this.getLocaleTextFunc = getLocaleTextFunc;
  }
  getTemplate() {
    return TextCellEditorElement;
  }
  getAgComponents() {
    return [AgInputTextFieldSelector];
  }
  init(eEditor, params) {
    this.eEditor = eEditor;
    this.params = params;
    const maxLength = params.maxLength;
    if (maxLength != null) {
      eEditor.setMaxLength(maxLength);
    }
  }
  getValidationErrors() {
    const { params } = this;
    const { maxLength, getValidationErrors } = params;
    const value2 = this.getValue();
    const translate = this.getLocaleTextFunc();
    let internalErrors = [];
    if (maxLength != null && typeof value2 === "string" && value2.length > maxLength) {
      internalErrors.push(
        translate("maxLengthValidation", `Must be ${maxLength} characters or fewer.`, [String(maxLength)])
      );
    }
    if (!internalErrors.length) {
      internalErrors = null;
    }
    if (getValidationErrors) {
      return getValidationErrors({ value: value2, cellEditorParams: params, internalErrors });
    }
    return internalErrors;
  }
  getValue() {
    const { eEditor, params } = this;
    const value2 = eEditor.getValue();
    if (!_exists(value2) && !_exists(params.value)) {
      return params.value;
    }
    return params.parseValue(value2);
  }
  getStartValue() {
    const params = this.params;
    const formatValue2 = params.useFormatter || params.column.getColDef().refData;
    return formatValue2 ? params.formatValue(params.value) : params.value;
  }
  setCaret() {
    if (_isBrowserSafari()) {
      this.eEditor.getInputElement().focus({ preventScroll: true });
    }
    const eInput = this.eEditor;
    const value2 = eInput.getValue();
    const len = _exists(value2) && value2.length || 0;
    if (len) {
      eInput.getInputElement().setSelectionRange(len, len);
    }
  }
};
var TextCellEditor = class extends SimpleCellEditor {
  constructor() {
    super(new TextCellEditorInput(() => this.getLocaleTextFunc()));
  }
};
function getVerticalPixelRange(beans) {
  return beans.ctrlsSvc.getScrollFeature().getVScrollPosition();
}
function getHorizontalPixelRange(beans) {
  return beans.ctrlsSvc.getScrollFeature().getHScrollPosition();
}
function ensureColumnVisible(beans, key2, position = "auto") {
  beans.frameworkOverrides.wrapIncoming(
    () => beans.ctrlsSvc.getScrollFeature().ensureColumnVisible(key2, position),
    "ensureVisible"
  );
}
function ensureIndexVisible(beans, index, position) {
  beans.frameworkOverrides.wrapIncoming(
    () => beans.ctrlsSvc.getScrollFeature().ensureIndexVisible(index, position),
    "ensureVisible"
  );
}
function ensureNodeVisible(beans, nodeSelector, position = null) {
  beans.frameworkOverrides.wrapIncoming(
    () => beans.ctrlsSvc.getScrollFeature().ensureNodeVisible(nodeSelector, position),
    "ensureVisible"
  );
}
function undoCellEditing(beans) {
  beans.undoRedo?.undo("api");
}
function redoCellEditing(beans) {
  beans.undoRedo?.redo("api");
}
function getEditRowValues(beans, rowNode) {
  return beans.editModelSvc?.getEditRowDataValue(rowNode, { checkSiblings: true });
}
function getEditingCells(beans) {
  const edits = beans.editModelSvc?.getEditMap();
  const positions = [];
  edits?.forEach((editRow, rowNode) => {
    const { rowIndex, rowPinned } = rowNode;
    editRow.forEach((editValue, column2) => {
      const { editorValue, pendingValue, sourceValue: oldValue, state } = editValue;
      const diff2 = _sourceAndPendingDiffer(editValue);
      let newValue = editorValue ?? pendingValue;
      if (newValue === UNEDITED) {
        newValue = void 0;
      }
      const edit = {
        newValue,
        oldValue,
        state,
        column: column2,
        colId: column2.getColId(),
        colKey: column2.getColId(),
        rowIndex,
        rowPinned
      };
      const changed = state === "changed" && diff2;
      const editing = state === "editing";
      if (editing || changed) {
        positions.push(edit);
      }
    });
  });
  return positions;
}
function stopEditing(beans, cancel = false) {
  const { editSvc } = beans;
  if (editSvc?.isBatchEditing()) {
    if (cancel) {
      for (const cellPosition of beans.editModelSvc?.getEditPositions() ?? []) {
        if (cellPosition.state === "editing") {
          editSvc.revertSingleCellEdit(cellPosition);
        }
      }
    } else {
      _syncFromEditors(beans, { persist: true });
    }
    _destroyEditors(beans, void 0, { cancel });
  } else {
    editSvc?.stopEditing(void 0, { cancel, source: "edit", forceStop: !cancel, forceCancel: cancel });
  }
}
function isEditing(beans, cellPosition) {
  const cellCtrl = _getCellCtrl(beans, cellPosition);
  return beans.editSvc?.isEditing(cellCtrl) ?? false;
}
function startEditingCell(beans, params) {
  const { key: key2, colKey, rowIndex, rowPinned } = params;
  const { editSvc, colModel } = beans;
  const column2 = colModel.getCol(colKey);
  if (!column2) {
    _warn(12, { colKey });
    return;
  }
  const cellPosition = {
    rowIndex,
    rowPinned: rowPinned || null
  };
  const rowNode = _getRowNode(beans, cellPosition);
  if (!rowNode) {
    _warn(290, { rowIndex, rowPinned });
    return;
  }
  if (!column2.isCellEditable(rowNode)) {
    return;
  }
  const notPinned = rowPinned == null;
  if (notPinned) {
    ensureIndexVisible(beans, rowIndex);
  }
  ensureColumnVisible(beans, colKey);
  editSvc?.startEditing(
    {
      rowNode,
      column: column2
    },
    {
      event: key2 ? new KeyboardEvent("keydown", { key: key2 }) : void 0,
      source: "api"
    }
  );
}
function validateEdit(beans) {
  return beans.editSvc?.validateEdit() || null;
}
function getCurrentUndoSize(beans) {
  return beans.undoRedo?.getCurrentUndoStackSize() ?? 0;
}
function getCurrentRedoSize(beans) {
  return beans.undoRedo?.getCurrentRedoStackSize() ?? 0;
}
var PopupEditorElement = { tag: "div", cls: "ag-popup-editor", attrs: { tabindex: "-1" } };
var PopupEditorWrapper = class extends AgPopupComponent {
  constructor(params) {
    super(PopupEditorElement);
    this.params = params;
  }
  postConstruct() {
    _setDomData(this.gos, this.getGui(), "popupEditorWrapper", true);
    this.addKeyDownListener();
  }
  addKeyDownListener() {
    const eGui = this.getGui();
    const params = this.params;
    const listener = (event) => {
      if (!_isUserSuppressingKeyboardEvent(this.gos, event, params.node, params.column, true)) {
        params.onKeyDown(event);
      }
    };
    this.addManagedElementListeners(eGui, { keydown: listener });
  }
};
function shouldStartEditing(beans, { column: column2 }, event, cellStartedEdit, source2 = "ui") {
  if (event instanceof KeyboardEvent && (event.key === KeyCode.TAB || event.key === KeyCode.ENTER || event.key === KeyCode.F2 || event.key === KeyCode.BACKSPACE && cellStartedEdit)) {
    return true;
  }
  const extendingRange = event?.shiftKey && beans.rangeSvc?.getCellRanges().length != 0;
  if (extendingRange) {
    return false;
  }
  const colDef = column2?.getColDef();
  const clickCount = deriveClickCount(beans.gos, colDef);
  const type = event?.type;
  if (type === "click" && event?.detail === 1 && clickCount === 1) {
    return true;
  }
  if (type === "dblclick" && event?.detail === 2 && clickCount === 2) {
    return true;
  }
  if (source2 === "api") {
    return cellStartedEdit ?? false;
  }
  return false;
}
function deriveClickCount(gos, colDef) {
  if (gos.get("suppressClickEdit") === true) {
    return 0;
  }
  if (gos.get("singleClickEdit") === true) {
    return 1;
  }
  if (colDef?.singleClickEdit) {
    return 1;
  }
  return 2;
}
function isCellEditable(beans, { rowNode, column: column2 }, _source = "ui") {
  const editable = column2.getColDef().editable;
  const editModelSvc = beans.editModelSvc;
  return column2.isColumnFunc(rowNode, editable) || !!editModelSvc && editModelSvc.hasEdits({ rowNode, column: column2 }, { withOpenEditor: true });
}
function isFullRowCellEditable(beans, position, source2 = "ui") {
  const editable = isCellEditable(beans, position, source2);
  if (editable === true || source2 === "ui") {
    return editable;
  }
  const columns2 = beans.colModel.getCols();
  return columns2.some((col) => isCellEditable(beans, { rowNode: position.rowNode, column: col }, source2));
}
var editHighlightFn = (edit, includeEditing = false) => {
  if (edit !== void 0) {
    return _sourceAndPendingDiffer(edit) || includeEditing && edit.state === "editing";
  }
};
function _hasEdits(beans, position, includeEditing = false) {
  return editHighlightFn(beans.editModelSvc?.getEdit(position), includeEditing);
}
var nodeHasLeafEdit = (children2, editModelSvc, column2) => {
  if (!children2) {
    return;
  }
  for (let i2 = 0, len = children2.length; i2 < len; ++i2) {
    const child = children2[i2];
    if (child.data) {
      const highlight2 = editHighlightFn(editModelSvc?.getEdit({ rowNode: child, column: column2 })) || editHighlightFn(editModelSvc?.getEdit({ rowNode: child.pinnedSibling, column: column2 }));
      if (highlight2) {
        return true;
      }
    }
    if (nodeHasLeafEdit(child.childrenAfterGroup, editModelSvc, column2)) {
      return true;
    }
  }
};
function _hasLeafEdits(beans, position) {
  const { column: column2, rowNode } = position;
  if (beans.gos.get("groupTotalRow") && !rowNode?.footer) {
    return false;
  }
  return nodeHasLeafEdit(rowNode?.childrenAfterGroup, beans.editModelSvc, column2);
}
function _hasPinnedEdits(beans, { rowNode, column: column2 }) {
  rowNode = rowNode.pinnedSibling;
  if (!rowNode) {
    return;
  }
  return editHighlightFn(
    beans.editModelSvc?.getEdit({
      rowNode,
      column: column2
    })
  );
}
var CellEditStyleFeature = class extends BeanStub {
  constructor(cellCtrl, beans) {
    super();
    this.cellCtrl = cellCtrl;
    this.beans = beans;
    this.editSvc = beans.editSvc;
    this.editModelSvc = beans.editModelSvc;
  }
  setComp(comp) {
    this.cellComp = comp;
    this.applyCellStyles();
  }
  applyCellStyles() {
    const { cellCtrl, editSvc, beans } = this;
    if (editSvc?.isBatchEditing() && editSvc.isEditing()) {
      const state = _hasEdits(beans, cellCtrl) || _hasLeafEdits(beans, cellCtrl) || _hasPinnedEdits(beans, cellCtrl);
      this.applyBatchingStyle(state);
    } else {
      this.applyBatchingStyle(false);
    }
    const hasErrors = !!this.editModelSvc?.getCellValidationModel().hasCellValidation(this.cellCtrl);
    this.cellComp.toggleCss("ag-cell-editing-error", hasErrors);
  }
  applyBatchingStyle(newState) {
    this.cellComp.toggleCss("ag-cell-editing", newState ?? false);
    this.cellComp.toggleCss("ag-cell-batch-edit", (newState && this.editSvc?.isBatchEditing()) ?? false);
  }
};
var RowEditStyleFeature = class extends BeanStub {
  constructor(rowCtrl, beans) {
    super();
    this.rowCtrl = rowCtrl;
    this.beans = beans;
    this.gos = beans.gos;
    this.editSvc = beans.editSvc;
    this.editModelSvc = beans.editModelSvc;
  }
  applyRowStyles() {
    const { rowCtrl, editModelSvc, beans } = this;
    let rowNode = rowCtrl.rowNode;
    let edits = editModelSvc?.getEditRow(rowNode);
    const hasErrors = this.editModelSvc?.getRowValidationModel().hasRowValidation({ rowNode });
    if (!edits && rowNode.pinnedSibling) {
      rowNode = rowNode.pinnedSibling;
      edits = editModelSvc?.getEditRow(rowNode);
    }
    if (edits) {
      const editing = Array.from(edits.keys()).some((column2) => {
        const position = { rowNode, column: column2 };
        return _hasEdits(beans, position, true) || _hasLeafEdits(beans, position) || _hasPinnedEdits(beans, position);
      });
      this.applyStyle(hasErrors, editing);
      return;
    }
    this.applyStyle(hasErrors);
  }
  applyStyle(hasErrors = false, editing = false) {
    const batchEdit = this.editSvc?.isBatchEditing() ?? false;
    const fullRow = this.gos.get("editType") === "fullRow";
    this.rowCtrl?.forEachGui(void 0, ({ rowComp }) => {
      rowComp.toggleCss("ag-row-editing", fullRow && editing);
      rowComp.toggleCss("ag-row-batch-edit", fullRow && editing && batchEdit);
      rowComp.toggleCss("ag-row-inline-editing", editing);
      rowComp.toggleCss("ag-row-not-inline-editing", !editing);
      rowComp.toggleCss("ag-row-editing-invalid", fullRow && editing && hasErrors);
    });
  }
};
var purgeRows = ({ rowModel, pinnedRowModel, editModelSvc }, rowNodes) => {
  const found = /* @__PURE__ */ new Set();
  rowModel.forEachNode((node2) => rowNodes.has(node2) && found.add(node2));
  pinnedRowModel?.forEachPinnedRow("top", (node2) => rowNodes.has(node2) && found.add(node2));
  pinnedRowModel?.forEachPinnedRow("bottom", (node2) => rowNodes.has(node2) && found.add(node2));
  for (const rowNode of rowNodes) {
    if (!found.has(rowNode)) {
      editModelSvc.removeEdits({ rowNode });
    }
  }
  return found;
};
var purgeCells = ({ editModelSvc }, rowNodes, columns2) => {
  for (const rowNode of rowNodes) {
    editModelSvc?.getEditRow(rowNode)?.forEach((_, column2) => !columns2.has(column2) && editModelSvc.removeEdits({ rowNode, column: column2 }));
  }
};
var _refreshEditCells = (beans) => () => {
  const columns2 = new Set(beans.colModel.getCols());
  const updates = beans.editModelSvc.getEditMap(true);
  const rowNodes = new Set(updates.keys());
  purgeCells(beans, purgeRows(beans, rowNodes), columns2);
};
var KEEP_EDITOR_SOURCES = /* @__PURE__ */ new Set(["undo", "redo", "paste", "bulk", "rangeSvc"]);
var INTERNAL_EDITOR_SOURCES = /* @__PURE__ */ new Set(["ui", "api"]);
var STOP_EDIT_SOURCE_TRANSFORM = {
  paste: "api",
  rangeSvc: "api",
  fillHandle: "api",
  cellClear: "api",
  bulk: "api"
};
var STOP_EDIT_SOURCE_TRANSFORM_KEYS = new Set(Object.keys(STOP_EDIT_SOURCE_TRANSFORM));
var SET_DATA_SOURCE_AS_API = /* @__PURE__ */ new Set([
  "paste",
  "rangeSvc",
  "renderer",
  "cellClear",
  "redo",
  "undo"
]);
var CANCEL_PARAMS = { cancel: true, source: "api" };
var COMMIT_PARAMS = { cancel: false, source: "api" };
var CHECK_SIBLING = { checkSiblings: true };
var FORCE_REFRESH = { force: true, suppressFlash: true };
var EditService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "editSvc";
    this.batch = false;
    this.stopping = false;
    this.committing = false;
  }
  postConstruct() {
    const { beans } = this;
    this.model = beans.editModelSvc;
    this.valueSvc = beans.valueSvc;
    this.rangeSvc = beans.rangeSvc;
    this.addManagedPropertyListener("editType", ({ currentValue }) => {
      this.stopEditing(void 0, CANCEL_PARAMS);
      this.createStrategy(currentValue);
    });
    const handler = _refreshEditCells(beans);
    const stopInvalidEdits = () => {
      const hasCellValidation = this.model.getCellValidationModel().getCellValidationMap().size > 0;
      const hasRowValidation = this.model.getRowValidationModel().getRowValidationMap().size > 0;
      if (hasCellValidation || hasRowValidation) {
        this.stopEditing(void 0, CANCEL_PARAMS);
      } else if (this.isEditing()) {
        if (this.isBatchEditing()) {
          _destroyEditors(beans, this.model.getEditPositions());
        } else {
          this.stopEditing(void 0, COMMIT_PARAMS);
        }
      }
      return false;
    };
    this.addManagedEventListeners({
      columnPinned: handler,
      columnVisible: handler,
      columnRowGroupChanged: handler,
      rowExpansionStateChanged: handler,
      pinnedRowsChanged: handler,
      displayedRowsChanged: handler,
      sortChanged: stopInvalidEdits,
      filterChanged: stopInvalidEdits,
      cellFocused: this.onCellFocused.bind(this)
    });
  }
  isBatchEditing() {
    return this.batch;
  }
  setBatchEditing(enabled) {
    if (enabled) {
      this.batch = true;
      this.stopEditing(void 0, CANCEL_PARAMS);
    } else {
      this.stopEditing(void 0, CANCEL_PARAMS);
      this.batch = false;
    }
  }
  createStrategy(editType) {
    const { beans, gos, strategy } = this;
    const name2 = getEditType(gos, editType);
    if (strategy) {
      if (strategy.beanName === name2) {
        return strategy;
      }
      this.destroyStrategy();
    }
    return this.strategy = this.createOptionalManagedBean(
      beans.registry.createDynamicBean(name2, true)
    );
  }
  destroyStrategy() {
    if (!this.strategy) {
      return;
    }
    this.strategy.destroy();
    this.strategy = this.destroyBean(this.strategy);
  }
  shouldStartEditing(position, event, cellStartedEdit, source2 = "ui") {
    const shouldStart = shouldStartEditing(this.beans, position, event, cellStartedEdit, source2);
    if (shouldStart) {
      this.strategy ?? (this.strategy = this.createStrategy());
    }
    return shouldStart;
  }
  shouldStopEditing(position, event, source2 = "ui") {
    return this.strategy?.shouldStop(position, event, source2) ?? null;
  }
  shouldCancelEditing(position, event, source2 = "ui") {
    return this.strategy?.shouldCancel(position, event, source2) ?? null;
  }
  validateEdit() {
    return _validateEdit(this.beans);
  }
  isEditing(position, params) {
    return this.model.hasEdits(position, params ?? CHECK_SIBLING);
  }
  isRowEditing(rowNode, params) {
    return (rowNode && this.model.hasRowEdits(rowNode, params)) ?? false;
  }
  /** @returns whether to prevent default on event */
  startEditing(position, params) {
    const { startedEdit = true, event = null, source: source2 = "ui", ignoreEventKey = false, silent } = params;
    this.strategy ?? (this.strategy = this.createStrategy());
    if (!this.isCellEditable(position, "api")) {
      return;
    }
    const cellCtrl = _getCellCtrl(this.beans, position);
    if (cellCtrl && !cellCtrl.comp) {
      cellCtrl.onCompAttachedFuncs.push(() => this.startEditing(position, params));
      return;
    }
    const res = this.shouldStartEditing(position, event, startedEdit, source2);
    if (res === false && source2 !== "api") {
      this.isEditing(position) && this.stopEditing();
      return;
    }
    if (!this.batch && this.shouldStopEditing(position, void 0, source2) && !params.continueEditing) {
      this.stopEditing(void 0, { source: source2 });
    }
    if (res && this.isBatchEditing()) {
      this.dispatchBatchEvent("batchEditingStarted", /* @__PURE__ */ new Map());
    }
    this.strategy.start({
      position,
      event,
      source: source2,
      ignoreEventKey,
      startedEdit,
      silent
    });
  }
  stopEditing(position, params) {
    const { event, cancel, source: source2 = "ui", forceCancel, forceStop } = params || {};
    const { beans, model: model2 } = this;
    if (STOP_EDIT_SOURCE_TRANSFORM_KEYS.has(source2)) {
      if (this.isBatchEditing()) {
        this.bulkRefresh(position);
        return false;
      }
    }
    const treatAsSource = this.committing ? STOP_EDIT_SOURCE_TRANSFORM[source2] : source2;
    const isEditingOrBatchWithEdits = this.committing || this.isEditing(position) || this.isBatchEditing() && model2.hasEdits(position, CHECK_SIBLING);
    if (!isEditingOrBatchWithEdits || !this.strategy || this.stopping) {
      return false;
    }
    this.stopping = true;
    const cellCtrl = _getCellCtrl(beans, position);
    if (cellCtrl) {
      cellCtrl.onEditorAttachedFuncs = [];
    }
    let edits = model2.getEditMap(true);
    let res = false;
    const willStop = !cancel && (!!this.shouldStopEditing(position, event, treatAsSource) || this.committing && !this.batch) || (forceStop ?? false);
    const willCancel = cancel && !!this.shouldCancelEditing(position, event, treatAsSource) || (forceCancel ?? false);
    if (willStop || willCancel) {
      _syncFromEditors(beans, { persist: true, isCancelling: willCancel || cancel, isStopping: willStop });
      const freshEdits = model2.getEditMap();
      const editsToDelete = this.processEdits(freshEdits, cancel, source2);
      this.strategy?.stop(cancel, event);
      for (const position2 of editsToDelete) {
        model2.clearEditValue(position2);
      }
      this.bulkRefresh(void 0, edits);
      for (const pos2 of model2.getEditPositions(freshEdits)) {
        const cellCtrl2 = _getCellCtrl(beans, pos2);
        const valueChanged = _sourceAndPendingDiffer(pos2);
        cellCtrl2?.refreshCell({ force: true, suppressFlash: !valueChanged });
      }
      edits = freshEdits;
      res || (res = willStop);
    } else if (event instanceof KeyboardEvent && this.batch && this.strategy?.midBatchInputsAllowed(position) && this.isEditing(position, { withOpenEditor: true })) {
      const { key: key2 } = event;
      const isEnter = key2 === KeyCode.ENTER;
      const isEscape = key2 === KeyCode.ESCAPE;
      const isTab = key2 === KeyCode.TAB;
      if (isEnter || isTab || isEscape) {
        if (isEnter || isTab) {
          _syncFromEditors(beans, { persist: true });
        } else if (isEscape) {
          this.revertSingleCellEdit(cellCtrl);
        }
        if (this.isBatchEditing()) {
          this.strategy?.cleanupEditors();
        } else {
          _destroyEditors(beans, model2.getEditPositions(), { event, cancel: isEscape });
        }
        event.preventDefault();
        this.bulkRefresh(position, edits, { suppressFlash: true });
        edits = model2.getEditMap();
      }
    } else {
      _syncFromEditors(beans, { persist: true });
      edits = model2.getEditMap();
    }
    if (res && position) {
      this.model.removeEdits(position);
    }
    this.navigateAfterEdit(params, cellCtrl?.cellPosition);
    _purgeUnchangedEdits(beans);
    if (!this.model.hasEdits()) {
      this.model.getCellValidationModel().clearCellValidationMap();
      this.model.getRowValidationModel().clearRowValidationMap();
    }
    this.bulkRefresh();
    if (willCancel) {
      this.beans.rowRenderer.refreshRows({ rowNodes: Array.from(edits.keys()) });
    }
    if (this.isBatchEditing()) {
      this.beans.rowRenderer.refreshRows({ suppressFlash: true, force: true });
      if (res && willStop) {
        this.dispatchBatchEvent("batchEditingStopped", edits);
      }
    }
    this.stopping = false;
    return res;
  }
  navigateAfterEdit(params, cellPosition) {
    if (!params || !cellPosition) {
      return;
    }
    const { event, suppressNavigateAfterEdit } = params;
    const isKeyBoardEvent = event instanceof KeyboardEvent;
    if (!isKeyBoardEvent || suppressNavigateAfterEdit) {
      return;
    }
    const { key: key2, shiftKey } = event;
    const navAfterEdit = this.gos.get("enterNavigatesVerticallyAfterEdit");
    if (key2 !== KeyCode.ENTER || !navAfterEdit) {
      return;
    }
    const direction = shiftKey ? KeyCode.UP : KeyCode.DOWN;
    this.beans.navigation?.navigateToNextCell(null, direction, cellPosition, false);
  }
  processEdits(edits, cancel = false, source2) {
    const rowNodes = Array.from(edits.keys());
    const hasValidationErrors = this.model.getCellValidationModel().getCellValidationMap().size > 0 || this.model.getRowValidationModel().getRowValidationMap().size > 0;
    const editsToDelete = [];
    for (const rowNode of rowNodes) {
      const editRow = edits.get(rowNode);
      for (const column2 of editRow.keys()) {
        const editValue = editRow.get(column2);
        const position = { rowNode, column: column2 };
        const valueChanged = _sourceAndPendingDiffer(editValue);
        if (!cancel && valueChanged && !hasValidationErrors) {
          const success = this.setNodeDataValue(rowNode, column2, editValue.pendingValue, void 0, source2);
          if (!success) {
            editsToDelete.push(position);
          }
        }
      }
    }
    return editsToDelete;
  }
  setNodeDataValue(rowNode, column2, newValue, refreshCell, originalSource = "edit") {
    const { beans } = this;
    const cellCtrl = _getCellCtrl(beans, { rowNode, column: column2 });
    const translatedSource = INTERNAL_EDITOR_SOURCES.has(originalSource) ? "edit" : originalSource;
    if (cellCtrl) {
      cellCtrl.suppressRefreshCell = true;
    }
    this.commitNextEdit();
    const success = rowNode.setDataValue(column2, newValue, translatedSource);
    if (cellCtrl) {
      cellCtrl.suppressRefreshCell = false;
    }
    if (refreshCell) {
      cellCtrl?.refreshCell(FORCE_REFRESH);
    }
    return success;
  }
  setEditMap(edits, params) {
    this.strategy ?? (this.strategy = this.createStrategy());
    this.strategy?.setEditMap(edits, params);
    this.bulkRefresh();
    let refreshParams = FORCE_REFRESH;
    if (params?.forceRefreshOfEditCellsOnly) {
      refreshParams = {
        ...getRowColumnsFromMap(edits),
        ...FORCE_REFRESH
      };
    }
    this.beans.rowRenderer.refreshCells(refreshParams);
  }
  dispatchEditValuesChanged({ rowNode, column: column2 }, edit = {}) {
    if (!rowNode || !column2 || !edit) {
      return;
    }
    const { pendingValue, sourceValue } = edit;
    const { rowIndex, rowPinned, data: data2 } = rowNode;
    this.beans.eventSvc.dispatchEvent({
      type: "cellEditValuesChanged",
      node: rowNode,
      rowIndex,
      rowPinned,
      column: column2,
      source: "api",
      data: data2,
      newValue: pendingValue,
      oldValue: sourceValue,
      value: pendingValue,
      colDef: column2.getColDef()
    });
  }
  bulkRefresh(position = {}, editMap, params = {}) {
    const { beans, gos } = this;
    const { editModelSvc, rowModel } = beans;
    if (_isClientSideRowModel(gos)) {
      if (position.rowNode && position.column) {
        this.refCell(position, this.model.getEdit(position), params);
      } else if (editMap) {
        editModelSvc?.getEditMap(false)?.forEach((editRow, rowNode) => {
          for (const column2 of editRow.keys()) {
            this.refCell({ rowNode, column: column2 }, editRow.get(column2), params);
          }
        });
      }
    }
  }
  refCell({ rowNode, column: column2 }, edit, params = {}) {
    const { beans, gos } = this;
    const updatedNodes = /* @__PURE__ */ new Set([rowNode]);
    const refreshNodes = /* @__PURE__ */ new Set();
    const pinnedSibling = rowNode.pinnedSibling;
    if (pinnedSibling) {
      updatedNodes.add(pinnedSibling);
    }
    const sibling2 = rowNode.sibling;
    if (sibling2) {
      refreshNodes.add(sibling2);
    }
    let parent = rowNode.parent;
    while (parent) {
      if (parent.sibling?.footer && gos.get("groupTotalRow")) {
        refreshNodes.add(parent.sibling);
      } else if (!parent.parent && parent.sibling && gos.get("grandTotalRow")) {
        refreshNodes.add(parent.sibling);
      } else {
        refreshNodes.add(parent);
      }
      parent = parent.parent;
    }
    for (const node2 of updatedNodes) {
      this.dispatchEditValuesChanged({ rowNode: node2, column: column2 }, edit);
    }
    for (const node2 of updatedNodes) {
      _getCellCtrl(beans, { rowNode: node2, column: column2 })?.refreshCell(params);
    }
    for (const node2 of refreshNodes) {
      _getCellCtrl(beans, { rowNode: node2, column: column2 })?.refreshCell(params);
    }
  }
  stopAllEditing(cancel = false, source2 = "ui") {
    if (this.isEditing()) {
      this.stopEditing(void 0, { cancel, source: source2 });
    }
  }
  isCellEditable(position, source2 = "ui") {
    const { rowNode } = position;
    const { gos, beans } = this;
    if (rowNode.group) {
      if (gos.get("treeData")) {
        if (!rowNode.data && !gos.get("enableGroupEdit")) {
          return false;
        }
      } else if (!gos.get("enableGroupEdit")) {
        return false;
      }
    }
    const isEditable = getEditType(gos) === "fullRow" ? isFullRowCellEditable(beans, position, source2) : isCellEditable(beans, position, source2);
    if (isEditable) {
      this.strategy ?? (this.strategy = this.createStrategy());
    }
    return isEditable;
  }
  cellEditingInvalidCommitBlocks() {
    return this.gos.get("invalidEditValueMode") === "block";
  }
  checkNavWithValidation(position, event, focus = true) {
    if (this.hasValidationErrors(position)) {
      const cellCtrl = _getCellCtrl(this.beans, position);
      if (this.cellEditingInvalidCommitBlocks()) {
        event?.preventDefault?.();
        if (focus) {
          !cellCtrl?.hasBrowserFocus() && cellCtrl?.focusCell();
          cellCtrl?.comp?.getCellEditor()?.focusIn?.();
        }
        return "block-stop";
      }
      cellCtrl && this.revertSingleCellEdit(cellCtrl);
      return "revert-continue";
    }
    return "continue";
  }
  revertSingleCellEdit(cellPosition, focus = false) {
    const cellCtrl = _getCellCtrl(this.beans, cellPosition);
    if (!cellCtrl?.comp?.getCellEditor()) {
      return;
    }
    _destroyEditors(this.beans, [cellPosition], { silent: true });
    this.model.clearEditValue(cellPosition);
    _setupEditor(this.beans, cellPosition, { silent: true });
    _populateModelValidationErrors(this.beans);
    cellCtrl?.refreshCell(FORCE_REFRESH);
    if (!focus) {
      return;
    }
    cellCtrl?.focusCell();
    cellCtrl?.comp?.getCellEditor()?.focusIn?.();
  }
  hasValidationErrors(position) {
    _populateModelValidationErrors(this.beans);
    const cellCtrl = _getCellCtrl(this.beans, position);
    if (cellCtrl) {
      cellCtrl.refreshCell(FORCE_REFRESH);
      cellCtrl.rowCtrl.rowEditStyleFeature?.applyRowStyles();
    }
    let invalid = false;
    if (position?.rowNode) {
      invalid || (invalid = this.model.getRowValidationModel().hasRowValidation({ rowNode: position.rowNode }));
      if (position.column) {
        invalid || (invalid = this.model.getCellValidationModel().hasCellValidation({ rowNode: position.rowNode, column: position.column }));
      }
    } else {
      invalid || (invalid = this.model.getCellValidationModel().getCellValidationMap().size > 0);
      invalid || (invalid = this.model.getRowValidationModel().getRowValidationMap().size > 0);
    }
    return invalid;
  }
  moveToNextCell(prev, backwards, event, source2 = "ui") {
    let res;
    const editing = this.isEditing();
    const preventNavigation = editing && this.checkNavWithValidation(void 0, event) === "block-stop";
    if (prev instanceof CellCtrl && editing) {
      res = this.strategy?.moveToNextEditingCell(prev, backwards, event, source2, preventNavigation);
    }
    if (res === null) {
      return res;
    }
    res = res || !!this.beans.focusSvc.focusedHeader;
    if (res === false && !preventNavigation) {
      this.stopEditing();
    }
    return res;
  }
  getCellDataValue({ rowNode, column: column2 }, preferEditor = true) {
    if (!rowNode || !column2) {
      return void 0;
    }
    let edit = this.model.getEdit({ rowNode, column: column2 });
    const pinnedSibling = rowNode.pinnedSibling;
    if (pinnedSibling) {
      const siblingEdit = this.model.getEdit({ rowNode: pinnedSibling, column: column2 });
      if (siblingEdit) {
        edit = siblingEdit;
      }
    }
    const newValue = preferEditor ? edit?.editorValue ?? edit?.pendingValue : edit?.pendingValue;
    return newValue === UNEDITED || !edit ? edit?.sourceValue ?? this.valueSvc.getValue(column2, rowNode, false, "api") : newValue;
  }
  addStopEditingWhenGridLosesFocus(viewports) {
    _addStopEditingWhenGridLosesFocus(this, this.beans, viewports);
  }
  createPopupEditorWrapper(params) {
    return new PopupEditorWrapper(params);
  }
  commitNextEdit() {
    this.committing = true;
  }
  setDataValue(position, newValue, eventSource) {
    try {
      if ((!this.isEditing() || this.committing) && !SET_DATA_SOURCE_AS_API.has(eventSource)) {
        return;
      }
      const { beans } = this;
      this.strategy ?? (this.strategy = this.createStrategy());
      const source2 = this.isBatchEditing() ? "ui" : this.committing ? eventSource ?? "api" : "api";
      if (!eventSource || KEEP_EDITOR_SOURCES.has(eventSource)) {
        _syncFromEditor(beans, position, newValue, eventSource, void 0, { persist: true });
        return this.setNodeDataValue(position.rowNode, position.column, newValue, true, eventSource);
      }
      const existing = this.model.getEdit(position);
      if (existing) {
        if (existing.pendingValue === newValue) {
          return false;
        }
        if (existing.sourceValue !== newValue) {
          _syncFromEditor(beans, position, newValue, eventSource, void 0, { persist: true });
          this.stopEditing(position, { source: source2, suppressNavigateAfterEdit: true });
          return true;
        }
        if (existing.sourceValue === newValue) {
          beans.editModelSvc?.removeEdits(position);
          this.dispatchEditValuesChanged(position, {
            ...existing,
            pendingValue: newValue
          });
          return true;
        }
      }
      _syncFromEditor(beans, position, newValue, eventSource, void 0, { persist: true });
      this.stopEditing(position, { source: source2, suppressNavigateAfterEdit: true });
      return true;
    } finally {
      this.committing = false;
    }
  }
  handleColDefChanged(cellCtrl) {
    _refreshEditorOnColDefChanged(this.beans, cellCtrl);
  }
  destroy() {
    this.model.clear();
    this.destroyStrategy();
    super.destroy();
  }
  prepDetailsDuringBatch(position, params) {
    if (!this.batch) {
      return;
    }
    const hasEdits = this.model.hasRowEdits(position.rowNode, CHECK_SIBLING);
    if (!hasEdits) {
      return;
    }
    const { rowNode, column: column2 } = position;
    const { compDetails, valueToDisplay } = params;
    if (compDetails) {
      const { params: params2 } = compDetails;
      params2.data = this.model.getEditRowDataValue(rowNode, CHECK_SIBLING);
      return { compDetails };
    }
    const editRow = this.model.getEditRow(position.rowNode, CHECK_SIBLING);
    if (valueToDisplay !== void 0 && editRow?.has(column2)) {
      return { valueToDisplay: this.valueSvc.getValue(column2, rowNode) };
    }
  }
  cleanupEditors() {
    this.strategy?.cleanupEditors();
  }
  dispatchCellEvent(position, event, type, payload) {
    this.strategy?.dispatchCellEvent(position, event, type, payload);
  }
  dispatchBatchEvent(type, edits) {
    this.eventSvc.dispatchEvent(this.createBatchEditEvent(type, edits));
  }
  createBatchEditEvent(type, edits) {
    return _addGridCommonParams(this.gos, {
      type,
      ...type === "batchEditingStopped" ? {
        changes: this.toEventChangeList(edits)
      } : {}
    });
  }
  toEventChangeList(edits) {
    return this.model.getEditPositions(edits).map((edit) => ({
      rowIndex: edit.rowNode.rowIndex,
      rowPinned: edit.rowNode.rowPinned,
      columnId: edit.column.getColId(),
      newValue: edit.pendingValue,
      oldValue: edit.sourceValue
    }));
  }
  applyBulkEdit({ rowNode, column: column2 }, ranges) {
    if (!ranges || ranges.length === 0) {
      return;
    }
    const { beans, rangeSvc, valueSvc } = this;
    _syncFromEditors(beans, { persist: true });
    const edits = this.model.getEditMap(true);
    const editValue = edits.get(rowNode)?.get(column2)?.pendingValue;
    if (!this.batch) {
      this.eventSvc.dispatchEvent({ type: "bulkEditingStarted" });
    }
    ranges.forEach((range) => {
      rangeSvc?.forEachRowInRange(range, (position) => {
        const rowNode2 = _getRowNode(beans, position);
        if (rowNode2 === void 0) {
          return;
        }
        const editRow = edits.get(rowNode2) ?? /* @__PURE__ */ new Map();
        for (const column22 of range.columns) {
          if (!column22) {
            continue;
          }
          if (this.isCellEditable({ rowNode: rowNode2, column: column22 }, "api")) {
            const sourceValue = valueSvc.getValue(column22, rowNode2, true, "api");
            let pendingValue = valueSvc.parseValue(
              column22,
              rowNode2 ?? null,
              editValue,
              sourceValue
            );
            if (Number.isNaN(pendingValue)) {
              pendingValue = null;
            }
            editRow.set(column22, {
              editorValue: void 0,
              pendingValue,
              sourceValue,
              state: "changed",
              editorState: {
                isCancelAfterEnd: void 0,
                isCancelBeforeStart: void 0
              }
            });
          }
        }
        if (editRow.size > 0) {
          edits.set(rowNode2, editRow);
        }
      });
      this.setEditMap(edits);
      if (this.batch) {
        this.cleanupEditors();
        _purgeUnchangedEdits(beans);
        this.bulkRefresh();
        return;
      }
      this.commitNextEdit();
      this.stopEditing(void 0, { source: "bulk" });
      this.eventSvc.dispatchEvent({ type: "bulkEditingStopped", changes: this.toEventChangeList(edits) });
    });
    this.bulkRefresh();
    const cellCtrl = _getCellCtrl(beans, { rowNode, column: column2 });
    if (cellCtrl) {
      cellCtrl.focusCell(true);
    }
  }
  createCellStyleFeature(cellCtrl, beans) {
    return new CellEditStyleFeature(cellCtrl, beans);
  }
  createRowStyleFeature(rowCtrl, beans) {
    return new RowEditStyleFeature(rowCtrl, beans);
  }
  setEditingCells(cells, params) {
    const { beans } = this;
    const { colModel, valueSvc } = beans;
    const edits = /* @__PURE__ */ new Map();
    for (let { colId, column: column2, colKey, rowIndex, rowPinned, newValue: pendingValue, state } of cells) {
      const col = colId ? colModel.getCol(colId) : colKey ? colModel.getCol(colKey) : column2;
      if (!col) {
        continue;
      }
      const rowNode = _getRowNode(beans, { rowIndex, rowPinned });
      if (!rowNode) {
        continue;
      }
      const sourceValue = valueSvc.getValue(col, rowNode, true, "api");
      if (!params?.forceRefreshOfEditCellsOnly && !_sourceAndPendingDiffer({ pendingValue, sourceValue }) && state !== "editing") {
        continue;
      }
      let editRow = edits.get(rowNode);
      if (!editRow) {
        editRow = /* @__PURE__ */ new Map();
        edits.set(rowNode, editRow);
      }
      if (pendingValue === void 0) {
        pendingValue = UNEDITED;
      }
      editRow.set(col, {
        editorValue: void 0,
        pendingValue,
        sourceValue,
        state: state ?? "changed",
        editorState: {
          isCancelAfterEnd: void 0,
          isCancelBeforeStart: void 0
        }
      });
    }
    this.setEditMap(edits, params);
  }
  onCellFocused(event) {
    const cellCtrl = _getCellCtrl(this.beans, event);
    if (!cellCtrl || !this.isEditing(cellCtrl, CHECK_SIBLING)) {
      return;
    }
    const edit = this.model.getEdit(cellCtrl);
    if (!edit || !_sourceAndPendingDiffer(edit)) {
      return;
    }
    const translate = this.getLocaleTextFunc();
    const label2 = translate("ariaPendingChange", "Pending Change");
    this.beans.ariaAnnounce?.announceValue(label2, "pendingChange");
  }
  allowedFocusTargetOnValidation(cellPosition) {
    return _getCellCtrl(this.beans, cellPosition);
  }
};
function getRowColumnsFromMap(edits) {
  return {
    rowNodes: edits ? Array.from(edits.keys()) : void 0,
    columns: edits ? [...new Set(Array.from(edits.values()).flatMap((er2) => Array.from(er2.keys())))] : void 0
  };
}
function getEditType(gos, editType) {
  return editType ?? gos.get("editType") ?? "singleCell";
}
var BaseEditStrategy = class extends BeanStub {
  postConstruct() {
    this.model = this.beans.editModelSvc;
    this.editSvc = this.beans.editSvc;
    this.addManagedEventListeners({
      cellFocused: this.onCellFocusChanged?.bind(this),
      cellFocusCleared: this.onCellFocusChanged?.bind(this)
    });
  }
  clearEdits(position) {
    this.model.clearEditValue(position);
  }
  onCellFocusChanged(event) {
    let cellCtrl;
    const previous = event["previousParams"];
    const { editSvc, beans } = this;
    const sourceEvent = event.type === "cellFocused" ? event.sourceEvent : null;
    if (previous) {
      cellCtrl = _getCellCtrl(beans, previous);
    }
    const { gos, editModelSvc } = beans;
    const isFocusCleared = event.type === "cellFocusCleared";
    if (editSvc.isEditing(void 0, { withOpenEditor: true })) {
      const { column: column2, rowIndex, rowPinned } = event;
      const cellPositionFromEvent = {
        column: column2,
        rowNode: _getRowNode(beans, { rowIndex, rowPinned })
      };
      const isBlock = gos.get("invalidEditValueMode") === "block";
      if (isBlock) {
        return;
      }
      const shouldRevert = !isBlock;
      const hasError = !!editModelSvc?.getCellValidationModel().hasCellValidation(cellPositionFromEvent);
      const shouldCancel = shouldRevert && hasError;
      const result2 = previous || isFocusCleared ? editSvc.stopEditing(void 0, {
        cancel: shouldCancel,
        source: isFocusCleared && shouldRevert ? "api" : void 0,
        event: sourceEvent
      }) : true;
      if (!result2) {
        if (editSvc.isBatchEditing()) {
          editSvc.cleanupEditors();
        } else {
          editSvc.stopEditing(void 0, { source: "api" });
        }
      }
    }
    cellCtrl?.refreshCell({ suppressFlash: true, force: true });
  }
  stop(cancel, event) {
    const editingCells = this.model.getEditPositions();
    const results = { all: [], pass: [], fail: [] };
    for (const cell2 of editingCells) {
      results.all.push(cell2);
      const validation2 = this.model.getCellValidationModel().getCellValidation(cell2);
      if ((validation2?.errorMessages?.length ?? 0) > 0) {
        results.fail.push(cell2);
        continue;
      }
      results.pass.push(cell2);
    }
    if (cancel) {
      for (const cell2 of editingCells) {
        _destroyEditor(this.beans, cell2, { cancel });
        this.model.stop(cell2);
      }
    } else {
      const actions = this.processValidationResults(results);
      if (actions.destroy.length > 0) {
        for (const cell2 of actions.destroy) {
          _destroyEditor(this.beans, cell2, { event, cancel });
          this.model.stop(cell2);
        }
      }
      if (actions.keep.length > 0) {
        for (const cell2 of actions.keep) {
          const cellCtrl = _getCellCtrl(this.beans, cell2);
          if (!this.editSvc?.cellEditingInvalidCommitBlocks()) {
            cellCtrl && this.editSvc.revertSingleCellEdit(cellCtrl);
          }
        }
      }
    }
    return true;
  }
  cleanupEditors({ rowNode } = {}, includeEditing) {
    _syncFromEditors(this.beans, { persist: false });
    const positions = this.model.getEditPositions();
    const discard = [];
    if (rowNode) {
      for (const pos2 of positions) {
        if (pos2.rowNode !== rowNode) {
          discard.push(pos2);
        }
      }
    } else {
      for (const pos2 of positions) {
        discard.push(pos2);
      }
    }
    _destroyEditors(this.beans, discard);
    _purgeUnchangedEdits(this.beans, includeEditing);
  }
  setFocusOutOnEditor(cellCtrl) {
    cellCtrl.comp?.getCellEditor()?.focusOut?.();
  }
  setFocusInOnEditor(cellCtrl) {
    const comp = cellCtrl.comp;
    const editor = comp?.getCellEditor();
    if (editor?.focusIn) {
      editor.focusIn();
    } else {
      const isFullRow = this.beans.gos.get("editType") === "fullRow";
      cellCtrl.focusCell(isFullRow);
      cellCtrl.onEditorAttachedFuncs.push(() => comp?.getCellEditor()?.focusIn?.());
    }
  }
  setupEditors(params) {
    const { event, ignoreEventKey = false, startedEdit, position, cells = this.model.getEditPositions() } = params;
    const key2 = event instanceof KeyboardEvent && !ignoreEventKey && event.key || void 0;
    _setupEditors(this.beans, cells, position, key2, event, startedEdit);
  }
  dispatchCellEvent(position, event, type, payload) {
    const cellCtrl = _getCellCtrl(this.beans, position);
    if (cellCtrl) {
      this.eventSvc.dispatchEvent({ ...cellCtrl.createEvent(event ?? null, type), ...payload });
    }
  }
  dispatchRowEvent(position, type, silent) {
    if (silent) {
      return;
    }
    const rowCtrl = _getRowCtrl(this.beans, position);
    if (rowCtrl) {
      this.eventSvc.dispatchEvent(rowCtrl.createRowEvent(type));
    }
  }
  shouldStop(_position, event, source2 = "ui") {
    const batch2 = this.editSvc.isBatchEditing();
    if (batch2 && source2 === "api") {
      return true;
    }
    if (batch2 && (source2 === "ui" || source2 === "edit")) {
      return false;
    }
    if (source2 === "api") {
      return true;
    }
    if (event instanceof KeyboardEvent && !batch2) {
      return event.key === KeyCode.ENTER;
    }
    return null;
  }
  shouldCancel(_position, event, source2 = "ui") {
    const batch2 = this.editSvc.isBatchEditing();
    if (event instanceof KeyboardEvent && !batch2) {
      const result2 = event.key === KeyCode.ESCAPE;
      if (result2) {
        return true;
      }
    }
    if (batch2 && source2 === "api") {
      return true;
    }
    if (source2 === "api") {
      return true;
    }
    return false;
  }
  setEditMap(edits, params) {
    if (!params?.update) {
      this.editSvc.stopEditing(void 0, { cancel: true, source: "api" });
    }
    const cells = [];
    edits.forEach((editRow, rowNode) => {
      editRow.forEach((cellData, column2) => {
        if (cellData.state === "editing") {
          cells.push({ ...cellData, rowNode, column: column2 });
        }
      });
    });
    if (params?.update) {
      edits = new Map([...this.model.getEditMap(), ...edits]);
    }
    this.model?.setEditMap(edits);
    if (cells.length > 0) {
      const position = cells.at(-1);
      const key2 = position.pendingValue === UNEDITED ? void 0 : position.pendingValue;
      this.start({ position, event: new KeyboardEvent("keydown", { key: key2 }), source: "api" });
      const cellCtrl = _getCellCtrl(this.beans, position);
      if (cellCtrl) {
        this.setFocusInOnEditor(cellCtrl);
      }
    }
  }
  destroy() {
    this.cleanupEditors();
    super.destroy();
  }
};
var FullRowEditStrategy = class extends BaseEditStrategy {
  constructor() {
    super(...arguments);
    this.beanName = "fullRow";
    this.startedRows = [];
  }
  shouldStop(position, event, _source = "ui") {
    const { rowNode } = position || {};
    const oldRowCtrl = _getRowCtrl(this.beans, {
      rowNode: this.rowNode
    });
    if (!oldRowCtrl) {
      return true;
    }
    const res = super.shouldStop({ rowNode: this.rowNode }, event, _source);
    if (res !== null) {
      return res;
    }
    if (!this.rowNode) {
      return false;
    }
    return rowNode !== this.rowNode;
  }
  midBatchInputsAllowed({ rowNode }) {
    if (!rowNode) {
      return false;
    }
    return this.model.hasEdits({ rowNode });
  }
  clearEdits(position) {
    this.model.clearEditValue(position);
  }
  start(params) {
    const { position, silent, startedEdit, event, ignoreEventKey } = params;
    const { rowNode } = position;
    if (this.rowNode !== rowNode) {
      super.cleanupEditors(position);
    }
    const columns2 = this.beans.visibleCols.allCols;
    const cells = [];
    const editableColumns = [];
    for (const column2 of columns2) {
      if (column2.isCellEditable(rowNode)) {
        editableColumns.push(column2);
      }
    }
    if (editableColumns.length == 0) {
      return;
    }
    this.dispatchRowEvent({ rowNode }, "rowEditingStarted", silent);
    this.startedRows.push(rowNode);
    for (const column2 of editableColumns) {
      const position2 = {
        rowNode,
        column: column2
      };
      cells.push(position2);
      if (!this.model.hasEdits(position2)) {
        this.model.start(position2);
      }
    }
    this.rowNode = rowNode;
    this.setupEditors({ cells, position, startedEdit, event, ignoreEventKey });
  }
  processValidationResults(results) {
    const anyFailed = results.fail.length > 0;
    if (anyFailed && this.editSvc.cellEditingInvalidCommitBlocks()) {
      return {
        destroy: [],
        keep: results.all
      };
    }
    return {
      destroy: results.all,
      keep: []
    };
  }
  stop(cancel, event) {
    const { rowNode } = this;
    if (rowNode && !this.model.hasRowEdits(rowNode)) {
      return false;
    }
    const changedRows = [];
    if (!cancel) {
      this.model.getEditMap().forEach((rowEdits, rowNode2) => {
        if (!rowEdits || rowEdits.size === 0) {
          return;
        }
        for (const edit of rowEdits.values()) {
          if (_sourceAndPendingDiffer(edit)) {
            changedRows.push(rowNode2);
            break;
          }
        }
      });
    }
    _populateModelValidationErrors(this.beans);
    if (!cancel && this.editSvc?.checkNavWithValidation({ rowNode }) === "block-stop") {
      return false;
    }
    super.stop(cancel, event);
    for (const rowNode2 of changedRows) {
      this.dispatchRowEvent({ rowNode: rowNode2 }, "rowValueChanged");
    }
    this.cleanupEditors({ rowNode }, true);
    this.rowNode = void 0;
    return true;
  }
  onCellFocusChanged(event) {
    const { rowIndex } = event;
    const prev = event["previousParams"];
    if (prev?.rowIndex === rowIndex || event.sourceEvent instanceof KeyboardEvent) {
      return;
    }
    const prevCell = _getCellCtrl(this.beans, prev);
    const isBlock = this.gos.get("invalidEditValueMode") === "block";
    if (isBlock && prevCell && (this.model.getCellValidationModel().getCellValidation(prevCell) || this.model.getRowValidationModel().getRowValidation(prevCell))) {
      return;
    }
    super.onCellFocusChanged(event);
  }
  cleanupEditors(position = {}, includeEditing) {
    super.cleanupEditors(position, includeEditing);
    for (const rowNode of this.startedRows) {
      this.dispatchRowEvent({ rowNode }, "rowEditingStopped");
    }
    this.startedRows.length = 0;
  }
  // returns null if no navigation should be performed
  moveToNextEditingCell(prevCell, backwards, event, source2 = "ui", preventNavigation = false) {
    const prevPos = prevCell.cellPosition;
    let nextCell;
    this.model.suspend(true);
    try {
      nextCell = this.beans.navigation?.findNextCellToFocusOn(prevPos, {
        backwards,
        startEditing: true,
        // Default behaviour for fullRow is skip to the next cell,
        // editable or not. FullRow editing might have some editable
        // and some not editable cells in the row.
        // More complex logic needed to skip to the
        // next FullRow editable cell,
        skipToNextEditableCell: false
      });
    } finally {
      this.model.suspend(false);
    }
    if (nextCell === false) {
      return null;
    }
    if (nextCell == null) {
      return false;
    }
    const nextPos = nextCell.cellPosition;
    const prevEditable = prevCell.isCellEditable();
    const nextEditable = nextCell.isCellEditable();
    const rowsMatch = nextPos && prevPos.rowIndex === nextPos.rowIndex && prevPos.rowPinned === nextPos.rowPinned;
    if (prevEditable) {
      this.setFocusOutOnEditor(prevCell);
    }
    this.restoreEditors();
    const suppressStartEditOnTab = this.gos.get("suppressStartEditOnTab");
    if (nextEditable && !preventNavigation) {
      if (suppressStartEditOnTab) {
        nextCell.focusCell(true, event);
      } else {
        if (!nextCell.comp?.getCellEditor()) {
          _setupEditor(this.beans, nextCell, { event, cellStartedEdit: true });
        }
        this.setFocusInOnEditor(nextCell);
        nextCell.focusCell(false, event);
      }
    } else {
      if (nextEditable && preventNavigation) {
        this.setFocusInOnEditor(nextCell);
      }
      nextCell.focusCell(true, event);
    }
    if (!rowsMatch && !preventNavigation) {
      this.editSvc?.stopEditing({ rowNode: prevCell.rowNode }, { event });
      this.cleanupEditors(nextCell, true);
      if (suppressStartEditOnTab) {
        nextCell.focusCell(true, event);
      } else {
        this.editSvc.startEditing(nextCell, { startedEdit: true, event, source: source2, ignoreEventKey: true });
      }
    }
    prevCell.rowCtrl?.refreshRow({ suppressFlash: true, force: true });
    return true;
  }
  restoreEditors() {
    this.model.getEditMap().forEach(
      (rowEdits, rowNode) => rowEdits.forEach(({ state }, column2) => {
        if (state !== "editing") {
          return;
        }
        const cellCtrl = _getCellCtrl(this.beans, {
          rowNode,
          column: column2
        });
        if (cellCtrl && !cellCtrl.comp?.getCellEditor()) {
          _setupEditor(this.beans, cellCtrl, { silent: true });
        }
      })
    );
  }
  destroy() {
    super.destroy();
    this.rowNode = void 0;
    this.startedRows.length = 0;
  }
};
var SingleCellEditStrategy = class extends BaseEditStrategy {
  constructor() {
    super(...arguments);
    this.beanName = "singleCell";
  }
  shouldStop(position, event, source2 = "ui") {
    const res = super.shouldStop(position, event, source2);
    if (res !== null) {
      return res;
    }
    const { rowNode, column: column2 } = position || {};
    if ((!this.rowNode || !this.column) && rowNode && column2) {
      return null;
    }
    return this.rowNode !== rowNode || this.column !== column2;
  }
  midBatchInputsAllowed(position) {
    return this.model.hasEdits(position);
  }
  start(params) {
    const { position, startedEdit, event, ignoreEventKey } = params;
    if (this.rowNode !== position.rowNode || this.column !== position.column) {
      super.cleanupEditors();
    }
    this.rowNode = position.rowNode;
    this.column = position.column;
    this.model.start(position);
    this.setupEditors({ cells: [position], position, startedEdit, event, ignoreEventKey });
  }
  dispatchRowEvent(_position, _type, _silent) {
  }
  processValidationResults(results) {
    const anyFailed = results.fail.length > 0;
    if (anyFailed && this.editSvc.cellEditingInvalidCommitBlocks()) {
      return {
        destroy: [],
        keep: results.all
      };
    }
    return {
      destroy: results.all,
      keep: []
    };
  }
  stop(cancel, event) {
    super.stop(cancel, event);
    this.rowNode = void 0;
    this.column = void 0;
    return true;
  }
  onCellFocusChanged(event) {
    const { colModel, editSvc } = this.beans;
    const { rowIndex, column: column2, rowPinned } = event;
    const rowNode = _getRowNode(this.beans, { rowIndex, rowPinned });
    const curColId = _getColId(column2);
    const curCol = colModel.getCol(curColId);
    const previous = event["previousParams"];
    if (previous) {
      const prevColId = _getColId(previous.column);
      if (previous?.rowIndex === rowIndex && prevColId === curColId && previous?.rowPinned === rowPinned) {
        return;
      }
    }
    if (editSvc?.isEditing({ rowNode, column: curCol }, { withOpenEditor: true }) && event.type === "cellFocused") {
      return;
    }
    super.onCellFocusChanged(event);
  }
  // returns null if no navigation should be performed
  moveToNextEditingCell(prevCell, backwards, event, source2 = "ui", preventNavigation = false) {
    const focusedCell = this.beans.focusSvc.getFocusedCell();
    if (focusedCell) {
      prevCell = _getCellByPosition(this.beans, focusedCell) ?? prevCell;
    }
    const prevPos = prevCell.cellPosition;
    let nextCell;
    const shouldSuspend = this.beans.gos.get("editType") === "fullRow";
    if (shouldSuspend) {
      this.model.suspend(true);
    }
    if (!preventNavigation) {
      prevCell.eGui.focus();
      this.editSvc?.stopEditing(prevCell, { source: this.editSvc?.isBatchEditing() ? "ui" : "api", event });
    }
    try {
      nextCell = this.beans.navigation?.findNextCellToFocusOn(prevPos, {
        backwards,
        startEditing: true
        // Default behaviour for fullRow is skip to the next cell,
        // editable or not. FullRow editing might have some editable
        // and some not editable cells in the row.
        // More complex logic needed to skip to the
        // next FullRow editable cell,
        // skipToNextEditableCell: false,
      });
    } finally {
      if (shouldSuspend) {
        this.model.suspend(false);
      }
    }
    if (nextCell === false) {
      return null;
    }
    if (nextCell == null) {
      return false;
    }
    const nextPos = nextCell.cellPosition;
    const prevEditable = prevCell.isCellEditable();
    const nextEditable = nextCell.isCellEditable();
    const rowsMatch = nextPos && prevPos.rowIndex === nextPos.rowIndex && prevPos.rowPinned === nextPos.rowPinned;
    if (prevEditable && !preventNavigation) {
      this.setFocusOutOnEditor(prevCell);
    }
    const suppressStartEditOnTab = this.gos.get("suppressStartEditOnTab");
    if (!rowsMatch && !preventNavigation) {
      super.cleanupEditors(nextCell, true);
      if (suppressStartEditOnTab) {
        nextCell.focusCell(true, event);
      } else {
        this.editSvc.startEditing(nextCell, { startedEdit: true, event, source: source2, ignoreEventKey: true });
      }
    }
    if (nextEditable && !preventNavigation) {
      nextCell.focusCell(false, event);
      if (suppressStartEditOnTab) {
        nextCell.focusCell(true, event);
      } else if (!nextCell.comp?.getCellEditor()) {
        const alreadyEditing = this.editSvc?.isEditing(nextCell, { withOpenEditor: true });
        _setupEditor(this.beans, nextCell, { event, cellStartedEdit: true, silent: alreadyEditing });
        this.setFocusInOnEditor(nextCell);
        this.cleanupEditors(nextCell);
      }
    } else {
      if (nextEditable && preventNavigation) {
        this.setFocusInOnEditor(nextCell);
      }
      nextCell.focusCell(true, event);
    }
    prevCell.rowCtrl?.refreshRow({ suppressFlash: true, force: true });
    return true;
  }
  destroy() {
    super.destroy();
    this.rowNode = void 0;
    this.column = void 0;
  }
};
var EditCoreModule = {
  moduleName: "EditCore",
  version: VERSION,
  beans: [EditModelService, EditService],
  apiFunctions: {
    getEditingCells,
    getEditRowValues,
    getCellEditorInstances,
    startEditingCell,
    stopEditing,
    isEditing,
    validateEdit
  },
  dynamicBeans: {
    singleCell: SingleCellEditStrategy,
    fullRow: FullRowEditStrategy
  },
  dependsOn: [PopupModule, TooltipModule],
  css: [cellEditingCSS]
};
var UndoRedoEditModule = {
  moduleName: "UndoRedoEdit",
  version: VERSION,
  beans: [UndoRedoService],
  apiFunctions: {
    undoCellEditing,
    redoCellEditing,
    getCurrentUndoSize,
    getCurrentRedoSize
  },
  dependsOn: [EditCoreModule]
};
var TextEditorModule = {
  moduleName: "TextEditor",
  version: VERSION,
  userComponents: { agCellEditor: TextCellEditor, agTextCellEditor: TextCellEditor },
  dependsOn: [EditCoreModule]
};
var NumberEditorModule = {
  moduleName: "NumberEditor",
  version: VERSION,
  userComponents: {
    agNumberCellEditor: {
      classImp: NumberCellEditor
    }
  },
  dependsOn: [EditCoreModule]
};
var DateEditorModule = {
  moduleName: "DateEditor",
  version: VERSION,
  userComponents: {
    agDateCellEditor: DateCellEditor,
    agDateStringCellEditor: DateStringCellEditor
  },
  dependsOn: [EditCoreModule]
};
var CheckboxEditorModule = {
  moduleName: "CheckboxEditor",
  version: VERSION,
  userComponents: {
    agCheckboxCellEditor: CheckboxCellEditor
  },
  dependsOn: [EditCoreModule]
};
var SelectEditorModule = {
  moduleName: "SelectEditor",
  version: VERSION,
  userComponents: { agSelectCellEditor: SelectCellEditor },
  dependsOn: [EditCoreModule]
};
var LargeTextEditorModule = {
  moduleName: "LargeTextEditor",
  version: VERSION,
  userComponents: { agLargeTextCellEditor: LargeTextCellEditor },
  dependsOn: [EditCoreModule]
};
var CustomEditorModule = {
  moduleName: "CustomEditor",
  version: VERSION,
  dependsOn: [EditCoreModule]
};
var SelectionColService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "selectionColSvc";
  }
  postConstruct() {
    this.addManagedPropertyListener("rowSelection", (event) => {
      this.onSelectionOptionsChanged(
        event.currentValue,
        event.previousValue,
        _convertColumnEventSourceType(event.source)
      );
    });
    this.addManagedPropertyListener("selectionColumnDef", this.updateColumns.bind(this));
  }
  addColumns(cols) {
    const selectionCols = this.columns;
    if (selectionCols == null) {
      return;
    }
    cols.list = selectionCols.list.concat(cols.list);
    cols.tree = selectionCols.tree.concat(cols.tree);
    _updateColsMap(cols);
  }
  createColumns(cols, updateOrders) {
    const destroyCollection = () => {
      _destroyColumnTree(this.beans, this.columns?.tree);
      this.columns = null;
    };
    const newTreeDepth = cols.treeDepth;
    const oldTreeDepth = this.columns?.treeDepth ?? -1;
    const treeDepthSame = oldTreeDepth == newTreeDepth;
    const list2 = this.generateSelectionCols();
    const areSame = _areColIdsEqual(list2, this.columns?.list ?? []);
    if (areSame && treeDepthSame) {
      return;
    }
    destroyCollection();
    const { colGroupSvc } = this.beans;
    const treeDepth = colGroupSvc?.findDepth(cols.tree) ?? 0;
    const tree = colGroupSvc?.balanceTreeForAutoCols(list2, treeDepth) ?? [];
    this.columns = {
      list: list2,
      tree,
      treeDepth,
      map: {}
    };
    const putSelectionColsFirstInList = (cols2) => {
      if (!cols2) {
        return null;
      }
      const colsFiltered = cols2.filter((col) => !isColumnSelectionCol(col));
      return [...list2, ...colsFiltered];
    };
    updateOrders(putSelectionColsFirstInList);
  }
  updateColumns(event) {
    const source2 = _convertColumnEventSourceType(event.source);
    for (const col of this.columns?.list ?? []) {
      const newColDef = this.createSelectionColDef(event.currentValue);
      col.setColDef(newColDef, null, source2);
      _applyColumnState(this.beans, { state: [{ ...newColDef, colId: col.getColId() }] }, source2);
    }
  }
  getColumn(key2) {
    return this.columns?.list.find((col) => _columnsMatch(col, key2)) ?? null;
  }
  getColumns() {
    return this.columns?.list ?? null;
  }
  isSelectionColumnEnabled() {
    const { gos, beans } = this;
    const rowSelection = gos.get("rowSelection");
    if (typeof rowSelection !== "object" || !_isRowSelection(gos)) {
      return false;
    }
    const hasAutoCols = (beans.autoColSvc?.getColumns()?.length ?? 0) > 0;
    if (rowSelection.checkboxLocation === "autoGroupColumn" && hasAutoCols) {
      return false;
    }
    const checkboxes = !!_getCheckboxes(rowSelection);
    const headerCheckbox = _getHeaderCheckbox(rowSelection);
    return checkboxes || headerCheckbox;
  }
  createSelectionColDef(def) {
    const { gos } = this;
    const selectionColumnDef = def ?? gos.get("selectionColumnDef");
    const enableRTL = gos.get("enableRtl");
    const { rowSpan: _, spanRows: __, ...filteredSelColDef } = selectionColumnDef ?? {};
    return {
      // overridable properties
      width: 50,
      resizable: false,
      suppressHeaderMenuButton: true,
      sortable: false,
      suppressMovable: true,
      lockPosition: enableRTL ? "right" : "left",
      comparator(valueA, valueB, nodeA, nodeB) {
        const aSelected = nodeA.isSelected();
        const bSelected = nodeB.isSelected();
        return aSelected === bSelected ? 0 : aSelected ? 1 : -1;
      },
      editable: false,
      suppressFillHandle: true,
      pinned: null,
      // overrides
      ...filteredSelColDef,
      // non-overridable properties
      colId: SELECTION_COLUMN_ID,
      chartDataType: "excluded"
    };
  }
  generateSelectionCols() {
    if (!this.isSelectionColumnEnabled()) {
      return [];
    }
    const colDef = this.createSelectionColDef();
    const colId = colDef.colId;
    this.gos.validateColDef(colDef, colId, true);
    const col = new AgColumn(colDef, null, colId, false);
    this.createBean(col);
    return [col];
  }
  onSelectionOptionsChanged(current3, prev, source2) {
    const prevCheckbox = prev && typeof prev !== "string" ? _getCheckboxes(prev) : void 0;
    const currCheckbox = current3 && typeof current3 !== "string" ? _getCheckboxes(current3) : void 0;
    const checkboxHasChanged = prevCheckbox !== currCheckbox;
    const prevHeaderCheckbox = prev && typeof prev !== "string" ? _getHeaderCheckbox(prev) : void 0;
    const currHeaderCheckbox = current3 && typeof current3 !== "string" ? _getHeaderCheckbox(current3) : void 0;
    const headerCheckboxHasChanged = prevHeaderCheckbox !== currHeaderCheckbox;
    const currLocation = _getCheckboxLocation(current3);
    const prevLocation = _getCheckboxLocation(prev);
    const locationChanged = currLocation !== prevLocation;
    if (checkboxHasChanged || headerCheckboxHasChanged || locationChanged) {
      this.beans.colModel.refreshAll(source2);
    }
  }
  destroy() {
    _destroyColumnTree(this.beans, this.columns?.tree);
    super.destroy();
  }
  /**
   * Refreshes visibility of the selection column based on which columns are currently visible.
   * Called by the VisibleColsService with the columns that are currently visible in left/center/right
   * containers. This method *MUTATES* those arrays directly.
   *
   * The selection column should be visible if all of the following are true
   * - The selection column is not disabled
   * - The number of visible columns excluding the selection column and row numbers column is greater than 0
   * @param leftCols Visible columns in the left-pinned container
   * @param centerCols Visible columns in the center viewport
   * @param rightCols Visible columns in the right-pinned container
   */
  refreshVisibility(leftCols, centerCols, rightCols) {
    if (!this.columns?.list.length) {
      return;
    }
    const numVisibleCols = leftCols.length + centerCols.length + rightCols.length;
    if (numVisibleCols === 0) {
      return;
    }
    const column2 = this.columns.list[0];
    if (!column2.isVisible()) {
      return;
    }
    const hideSelectionCol = () => {
      let cols;
      switch (column2.pinned) {
        case "left":
        case true:
          cols = leftCols;
          break;
        case "right":
          cols = rightCols;
          break;
        default:
          cols = centerCols;
      }
      cols && _removeFromArray(cols, column2);
    };
    const rowNumbersCol = this.beans.rowNumbersSvc?.getColumn(ROW_NUMBERS_COLUMN_ID);
    const expectedNumCols = rowNumbersCol ? 2 : 1;
    if (expectedNumCols === numVisibleCols) {
      hideSelectionCol();
    }
  }
};
function setNodesSelected(beans, params) {
  const allNodesValid = params.nodes.every((node2) => {
    if (node2.rowPinned && !_isManualPinnedRow(node2)) {
      _warn(59);
      return false;
    }
    if (node2.id === void 0) {
      _warn(60);
      return false;
    }
    return true;
  });
  if (!allNodesValid) {
    return;
  }
  const { nodes, source: source2, newValue } = params;
  beans.selectionSvc?.setNodesSelected({ nodes, source: source2 ?? "api", newValue });
}
function selectAll(beans, selectAll2, source2 = "apiSelectAll") {
  beans.selectionSvc?.selectAllRowNodes({ source: source2, selectAll: selectAll2 });
}
function deselectAll(beans, selectAll2, source2 = "apiSelectAll") {
  beans.selectionSvc?.deselectAllRowNodes({ source: source2, selectAll: selectAll2 });
}
function selectAllFiltered(beans, source2 = "apiSelectAllFiltered") {
  beans.selectionSvc?.selectAllRowNodes({ source: source2, selectAll: "filtered" });
}
function deselectAllFiltered(beans, source2 = "apiSelectAllFiltered") {
  beans.selectionSvc?.deselectAllRowNodes({ source: source2, selectAll: "filtered" });
}
function selectAllOnCurrentPage(beans, source2 = "apiSelectAllCurrentPage") {
  beans.selectionSvc?.selectAllRowNodes({ source: source2, selectAll: "currentPage" });
}
function deselectAllOnCurrentPage(beans, source2 = "apiSelectAllCurrentPage") {
  beans.selectionSvc?.deselectAllRowNodes({ source: source2, selectAll: "currentPage" });
}
function getSelectedNodes(beans) {
  return beans.selectionSvc?.getSelectedNodes() ?? [];
}
function getSelectedRows(beans) {
  return beans.selectionSvc?.getSelectedRows() ?? [];
}
var SelectionService = class extends BaseSelectionService {
  constructor() {
    super(...arguments);
    this.beanName = "selectionSvc";
    this.selectedNodes = /* @__PURE__ */ new Map();
    this.detailSelection = /* @__PURE__ */ new Map();
    this.masterSelectsDetail = false;
  }
  postConstruct() {
    super.postConstruct();
    const { gos } = this;
    this.mode = _getRowSelectionMode(gos);
    this.groupSelectsDescendants = _getGroupSelectsDescendants(gos);
    this.groupSelectsFiltered = _getGroupSelection(gos) === "filteredDescendants";
    this.masterSelectsDetail = _getMasterSelects(gos) === "detail";
    this.addManagedPropertyListeners(["groupSelectsChildren", "groupSelectsFiltered", "rowSelection"], () => {
      const groupSelectsDescendants = _getGroupSelectsDescendants(gos);
      const selectionMode = _getRowSelectionMode(gos);
      const groupSelectsFiltered = _getGroupSelection(gos) === "filteredDescendants";
      this.masterSelectsDetail = _getMasterSelects(gos) === "detail";
      if (groupSelectsDescendants !== this.groupSelectsDescendants || groupSelectsFiltered !== this.groupSelectsFiltered || selectionMode !== this.mode) {
        this.deselectAllRowNodes({ source: "api" });
        this.groupSelectsDescendants = groupSelectsDescendants;
        this.groupSelectsFiltered = groupSelectsFiltered;
        this.mode = selectionMode;
      }
    });
    this.addManagedEventListeners({ rowSelected: this.onRowSelected.bind(this) });
  }
  destroy() {
    super.destroy();
    this.resetNodes();
  }
  handleSelectionEvent(event, rowNode, source2) {
    if (this.isRowSelectionBlocked(rowNode)) {
      return 0;
    }
    const selection = this.inferNodeSelections(rowNode, event.shiftKey, event.metaKey || event.ctrlKey, source2);
    if (selection == null) {
      return 0;
    }
    this.selectionCtx.selectAll = false;
    if ("select" in selection) {
      if (selection.reset) {
        this.resetNodes();
      } else {
        this.selectRange(selection.deselect, false, source2);
      }
      return this.selectRange(selection.select, true, source2);
    } else {
      const newValue = selection.checkFilteredNodes ? recursiveCanNodesBeSelected(selection.node) : selection.newValue;
      return this.setNodesSelected({
        nodes: [selection.node],
        newValue,
        clearSelection: selection.clearSelection,
        keepDescendants: selection.keepDescendants,
        event,
        source: source2
      });
    }
  }
  setNodesSelected({
    newValue,
    clearSelection,
    suppressFinishActions,
    nodes,
    event,
    source: source2,
    keepDescendants = false
  }) {
    if (nodes.length === 0) {
      return 0;
    }
    const { gos } = this;
    if (!_isRowSelection(gos) && newValue) {
      _warn(132);
      return 0;
    }
    if (nodes.length > 1 && !this.isMultiSelect()) {
      _warn(130);
      return 0;
    }
    let updatedCount = 0;
    for (let i2 = 0; i2 < nodes.length; i2++) {
      const rowNode = nodes[i2];
      const node2 = _normaliseSiblingRef(rowNode);
      if (node2.rowPinned && !_isManualPinnedRow(node2)) {
        _warn(59);
        continue;
      }
      if (node2.id === void 0) {
        _warn(60);
        continue;
      }
      const skipThisNode2 = this.groupSelectsFiltered && node2.group && !gos.get("treeData");
      if (!skipThisNode2) {
        const thisNodeWasSelected = this.selectRowNode(node2, newValue, event, source2);
        if (thisNodeWasSelected) {
          this.detailSelection.delete(node2.id);
          updatedCount++;
        }
      }
      if (this.groupSelectsDescendants && node2.childrenAfterGroup?.length) {
        updatedCount += this.selectChildren(node2, newValue, source2);
      }
    }
    if (!suppressFinishActions) {
      if (nodes.length === 1 && source2 === "api") {
        this.selectionCtx.setRoot(_normaliseSiblingRef(nodes[0]));
      }
      const clearOtherNodes = newValue && (clearSelection || !this.isMultiSelect());
      if (clearOtherNodes) {
        updatedCount += this.clearOtherNodes(_normaliseSiblingRef(nodes[0]), keepDescendants, source2);
      }
      if (updatedCount > 0) {
        this.updateGroupsFromChildrenSelections(source2);
        this.dispatchSelectionChanged(source2);
      }
    }
    return updatedCount;
  }
  // not to be mixed up with 'cell range selection' where you drag the mouse, this is row range selection, by
  // holding down 'shift'.
  selectRange(nodesToSelect, value2, source2) {
    let updatedCount = 0;
    nodesToSelect.forEach((node2) => {
      const rowNode = _normaliseSiblingRef(node2);
      if (rowNode.group && this.groupSelectsDescendants) {
        return;
      }
      const nodeWasSelected = this.selectRowNode(rowNode, value2, void 0, source2);
      if (nodeWasSelected) {
        updatedCount++;
      }
    });
    if (updatedCount > 0) {
      this.updateGroupsFromChildrenSelections(source2);
      this.dispatchSelectionChanged(source2);
    }
    return updatedCount;
  }
  selectChildren(node2, newValue, source2) {
    const children2 = this.groupSelectsFiltered ? node2.childrenAfterAggFilter : node2.childrenAfterGroup;
    if (!children2) {
      return 0;
    }
    return this.setNodesSelected({
      newValue,
      clearSelection: false,
      suppressFinishActions: true,
      source: source2,
      nodes: children2
    });
  }
  getSelectedNodes() {
    return Array.from(this.selectedNodes.values());
  }
  getSelectedRows() {
    const selectedRows = [];
    this.selectedNodes.forEach((rowNode) => rowNode.data && selectedRows.push(rowNode.data));
    return selectedRows;
  }
  getSelectionCount() {
    return this.selectedNodes.size;
  }
  /**
   * This method is used by the CSRM to remove groups which are being disposed of,
   * events do not need fired in this case
   */
  filterFromSelection(predicate) {
    const newSelectedNodes = /* @__PURE__ */ new Map();
    this.selectedNodes.forEach((rowNode, key2) => {
      if (predicate(rowNode)) {
        newSelectedNodes.set(key2, rowNode);
      }
    });
    this.selectedNodes = newSelectedNodes;
  }
  updateGroupsFromChildrenSelections(source2, changedPath) {
    if (!this.groupSelectsDescendants) {
      return false;
    }
    const { gos, rowModel } = this.beans;
    if (!_isClientSideRowModel(gos)) {
      return false;
    }
    const rootNode = rowModel.rootNode;
    if (!rootNode) {
      return false;
    }
    if (!changedPath) {
      changedPath = new ChangedPath(true, rootNode);
      changedPath.active = false;
    }
    let selectionChanged = false;
    changedPath.forEachChangedNodeDepthFirst((rowNode) => {
      if (rowNode !== rootNode) {
        const selected2 = this.calculateSelectedFromChildren(rowNode);
        selectionChanged = this.selectRowNode(rowNode, selected2 === null ? false : selected2, void 0, source2) || selectionChanged;
      }
    });
    return selectionChanged;
  }
  clearOtherNodes(rowNodeToKeepSelected, keepDescendants, source2) {
    const groupsToRefresh = /* @__PURE__ */ new Map();
    let updatedCount = 0;
    this.selectedNodes.forEach((otherRowNode) => {
      const isNodeToKeep = otherRowNode.id == rowNodeToKeepSelected.id;
      const shouldClearDescendant = keepDescendants ? !isDescendantOf(rowNodeToKeepSelected, otherRowNode) : true;
      if (shouldClearDescendant && !isNodeToKeep) {
        const rowNode = this.selectedNodes.get(otherRowNode.id);
        updatedCount += this.setNodesSelected({
          nodes: [rowNode],
          newValue: false,
          clearSelection: false,
          suppressFinishActions: true,
          source: source2
        });
        if (this.groupSelectsDescendants && otherRowNode.parent) {
          groupsToRefresh.set(otherRowNode.parent.id, otherRowNode.parent);
        }
      }
    });
    groupsToRefresh.forEach((group) => {
      const selected2 = this.calculateSelectedFromChildren(group);
      this.selectRowNode(group, selected2 === null ? false : selected2, void 0, source2);
    });
    return updatedCount;
  }
  onRowSelected(event) {
    const rowNode = event.node;
    if (this.groupSelectsDescendants && rowNode.group) {
      return;
    }
    if (rowNode.isSelected()) {
      this.selectedNodes.set(rowNode.id, rowNode);
    } else {
      this.selectedNodes.delete(rowNode.id);
    }
  }
  syncInRowNode(rowNode, oldNode) {
    this.syncInOldRowNode(rowNode, oldNode);
    this.syncInNewRowNode(rowNode);
  }
  createDaemonNode(rowNode) {
    if (!rowNode.id) {
      return void 0;
    }
    const oldNode = new RowNode(this.beans);
    oldNode.id = rowNode.id;
    oldNode.data = rowNode.data;
    oldNode.__selected = rowNode.__selected;
    oldNode.level = rowNode.level;
    return oldNode;
  }
  // if the id has changed for the node, then this means the rowNode
  // is getting used for a different data item, which breaks
  // our selectedNodes, as the node now is mapped by the old id
  // which is inconsistent. so to keep the old node as selected,
  // we swap in the clone (with the old id and old data). this means
  // the oldNode is effectively a daemon we keep a reference to,
  // so if client calls api.getSelectedNodes(), it gets the daemon
  // in the result. when the client un-selects, the reference to the
  // daemon is removed. the daemon, because it's an oldNode, is not
  // used by the grid for rendering, it's a copy of what the node used
  // to be like before the id was changed.
  syncInOldRowNode(rowNode, oldNode) {
    if (oldNode && rowNode.id !== oldNode.id) {
      const oldNodeSelected = this.selectedNodes.get(oldNode.id) == rowNode;
      if (oldNodeSelected) {
        this.selectedNodes.set(oldNode.id, oldNode);
      }
    }
  }
  syncInNewRowNode(rowNode) {
    if (this.selectedNodes.has(rowNode.id)) {
      rowNode.__selected = true;
      this.selectedNodes.set(rowNode.id, rowNode);
    } else {
      rowNode.__selected = false;
    }
  }
  reset(source2) {
    const selectionCount = this.getSelectionCount();
    this.resetNodes();
    if (selectionCount) {
      this.dispatchSelectionChanged(source2);
    }
  }
  resetNodes() {
    this.selectedNodes.forEach((node2) => {
      this.selectRowNode(node2, false);
    });
    this.selectedNodes.clear();
  }
  // returns a list of all nodes at 'best cost' - a feature to be used
  // with groups / trees. if a group has all it's children selected,
  // then the group appears in the result, but not the children.
  // Designed for use with 'children' as the group selection type,
  // where groups don't actually appear in the selection normally.
  getBestCostNodeSelection() {
    const { gos, rowModel } = this.beans;
    if (!_isClientSideRowModel(gos)) {
      return;
    }
    const topLevelNodes = rowModel.getTopLevelNodes();
    if (topLevelNodes === null) {
      return;
    }
    const result2 = [];
    function traverse(nodes) {
      for (let i2 = 0, l2 = nodes.length; i2 < l2; i2++) {
        const node2 = nodes[i2];
        if (node2.isSelected()) {
          result2.push(node2);
        } else if (node2.group && node2.childrenAfterGroup) {
          traverse(node2.childrenAfterGroup);
        }
      }
    }
    traverse(topLevelNodes);
    return result2;
  }
  isEmpty() {
    return this.getSelectionCount() === 0;
  }
  deselectAllRowNodes({ source: source2, selectAll: selectAll2 }) {
    const rowModelClientSide = _isClientSideRowModel(this.gos);
    let updatedNodes = false;
    const callback = (rowNode) => {
      const updated = this.selectRowNode(_normaliseSiblingRef(rowNode), false, void 0, source2);
      updatedNodes || (updatedNodes = updated);
    };
    if (selectAll2 === "currentPage" || selectAll2 === "filtered") {
      if (!rowModelClientSide) {
        _error(102);
        return;
      }
      this.getNodesToSelect(selectAll2).forEach(callback);
    } else {
      this.selectedNodes.forEach(callback);
      this.reset(source2);
    }
    this.selectionCtx.selectAll = false;
    if (rowModelClientSide && this.groupSelectsDescendants) {
      const updated = this.updateGroupsFromChildrenSelections(source2);
      updatedNodes || (updatedNodes = updated);
    }
    if (updatedNodes) {
      this.dispatchSelectionChanged(source2);
    }
  }
  getSelectedCounts(selectAll2) {
    let selectedCount = 0;
    let notSelectedCount = 0;
    this.getNodesToSelect(selectAll2).forEach((node2) => {
      if (this.groupSelectsDescendants && node2.group) {
        return;
      }
      if (node2.isSelected()) {
        selectedCount++;
      } else if (node2.selectable) {
        notSelectedCount++;
      }
    });
    return { selectedCount, notSelectedCount };
  }
  getSelectAllState(selectAll2) {
    const { selectedCount, notSelectedCount } = this.getSelectedCounts(selectAll2);
    return _calculateSelectAllState(selectedCount, notSelectedCount) ?? null;
  }
  hasNodesToSelect(selectAll2) {
    return this.getNodesToSelect(selectAll2).filter((node2) => node2.selectable).length > 0;
  }
  /**
   * @param selectAll See `MultiRowSelectionOptions.selectAll`
   * @returns all nodes including unselectable nodes which are the target of this selection attempt
   */
  getNodesToSelect(selectAll2) {
    if (!this.canSelectAll()) {
      return [];
    }
    const nodes = [];
    const addToResult = (node2) => nodes.push(node2);
    if (selectAll2 === "currentPage") {
      this.forEachNodeOnPage((node2) => {
        if (!node2.group) {
          addToResult(node2);
          return;
        }
        if (!node2.expanded && !node2.footer) {
          const recursivelyAddChildren = (child) => {
            addToResult(child);
            child.childrenAfterFilter?.forEach(recursivelyAddChildren);
          };
          recursivelyAddChildren(node2);
          return;
        }
        if (!this.groupSelectsDescendants) {
          addToResult(node2);
        }
      });
      return nodes;
    }
    const clientSideRowModel = this.beans.rowModel;
    if (selectAll2 === "filtered") {
      clientSideRowModel.forEachNodeAfterFilter(addToResult);
      return nodes;
    }
    clientSideRowModel.forEachNode(addToResult);
    return nodes;
  }
  forEachNodeOnPage(callback) {
    const { pageBounds, rowModel } = this.beans;
    const firstRow = pageBounds.getFirstRow();
    const lastRow = pageBounds.getLastRow();
    for (let i2 = firstRow; i2 <= lastRow; i2++) {
      const node2 = rowModel.getRow(i2);
      if (node2) {
        callback(node2);
      }
    }
  }
  selectAllRowNodes(params) {
    const { gos, selectionCtx } = this;
    if (!_isRowSelection(gos)) {
      _warn(132);
      return;
    }
    if (_isUsingNewRowSelectionAPI(gos) && !_isMultiRowSelection(gos)) {
      _warn(130);
      return;
    }
    if (!this.canSelectAll()) {
      return;
    }
    const { source: source2, selectAll: selectAll2 } = params;
    let updatedNodes = false;
    this.getNodesToSelect(selectAll2).forEach((rowNode) => {
      const updated = this.selectRowNode(_normaliseSiblingRef(rowNode), true, void 0, source2);
      updatedNodes || (updatedNodes = updated);
    });
    selectionCtx.selectAll = true;
    if (_isClientSideRowModel(gos) && this.groupSelectsDescendants) {
      const updated = this.updateGroupsFromChildrenSelections(source2);
      updatedNodes || (updatedNodes = updated);
    }
    if (updatedNodes) {
      this.dispatchSelectionChanged(source2);
    }
  }
  getSelectionState() {
    return this.isEmpty() ? null : Array.from(this.selectedNodes.keys());
  }
  setSelectionState(state, source2, clearSelection) {
    if (!state) {
      state = [];
    }
    if (!Array.isArray(state)) {
      _error(103);
      return;
    }
    const rowIds = new Set(state);
    const nodes = [];
    this.beans.rowModel.forEachNode((node2) => {
      if (rowIds.has(node2.id)) {
        nodes.push(node2);
      }
    });
    if (clearSelection) {
      this.resetNodes();
    }
    this.setNodesSelected({
      newValue: true,
      nodes,
      source: source2
    });
  }
  canSelectAll() {
    return _isClientSideRowModel(this.beans.gos);
  }
  /**
   * Updates the selectable state for a node by invoking isRowSelectable callback.
   * If the node is not selectable, it will be deselected.
   *
   * Callers:
   *  - property isRowSelectable changed
   *  - after grouping / treeData via `updateSelectableAfterGrouping`
   */
  updateSelectable(changedPath) {
    const { gos, rowModel } = this.beans;
    if (!_isRowSelection(gos)) {
      return;
    }
    const source2 = "selectableChanged";
    const skipLeafNodes = changedPath !== void 0;
    const isCSRMGroupSelectsDescendants = _isClientSideRowModel(gos) && this.groupSelectsDescendants;
    const nodesToDeselect = [];
    const nodeCallback = (node2) => {
      if (skipLeafNodes && !node2.group) {
        return;
      }
      if (isCSRMGroupSelectsDescendants && node2.group) {
        const hasSelectableChild = node2.childrenAfterGroup?.some((rowNode) => rowNode.selectable) ?? false;
        this.setRowSelectable(node2, hasSelectableChild, true);
        return;
      }
      const rowSelectable = this.updateRowSelectable(node2, true);
      if (!rowSelectable && node2.isSelected()) {
        nodesToDeselect.push(node2);
      }
    };
    if (isCSRMGroupSelectsDescendants) {
      if (changedPath === void 0) {
        const rootNode = rowModel.rootNode;
        changedPath = rootNode ? new ChangedPath(false, rootNode) : void 0;
      }
      changedPath?.forEachChangedNodeDepthFirst(nodeCallback, !skipLeafNodes, !skipLeafNodes);
    } else {
      rowModel.forEachNode(nodeCallback);
    }
    if (nodesToDeselect.length) {
      this.setNodesSelected({
        nodes: nodesToDeselect,
        newValue: false,
        source: source2
      });
    }
    if (!skipLeafNodes && isCSRMGroupSelectsDescendants) {
      this.updateGroupsFromChildrenSelections?.(source2);
    }
  }
  // only called by CSRM
  updateSelectableAfterGrouping(changedPath) {
    this.updateSelectable(changedPath);
    if (this.groupSelectsDescendants) {
      const selectionChanged = this.updateGroupsFromChildrenSelections?.("rowGroupChanged", changedPath);
      if (selectionChanged) {
        this.dispatchSelectionChanged("rowGroupChanged");
      }
    }
  }
  refreshMasterNodeState(node2, e) {
    if (!this.masterSelectsDetail) {
      return;
    }
    const detailApi = node2.detailNode?.detailGridInfo?.api;
    if (!detailApi) {
      return;
    }
    const isSelectAll = _isAllSelected(detailApi);
    const current3 = node2.isSelected();
    if (current3 !== isSelectAll) {
      const selectionChanged = this.selectRowNode(node2, isSelectAll, e, "masterDetail");
      if (selectionChanged) {
        this.dispatchSelectionChanged("masterDetail");
      }
    }
    if (!isSelectAll) {
      const detailSelected = this.detailSelection.get(node2.id) ?? /* @__PURE__ */ new Set();
      for (const n2 of detailApi.getSelectedNodes()) {
        detailSelected.add(n2.id);
      }
      this.detailSelection.set(node2.id, detailSelected);
    }
  }
  setDetailSelectionState(masterNode, detailGridOptions, detailApi) {
    if (!this.masterSelectsDetail) {
      return;
    }
    if (!_isMultiRowSelection(detailGridOptions)) {
      _warn(269);
      return;
    }
    switch (masterNode.isSelected()) {
      case true: {
        detailApi.selectAll();
        break;
      }
      case false: {
        detailApi.deselectAll();
        break;
      }
      case void 0: {
        const selectedIds = this.detailSelection.get(masterNode.id);
        if (selectedIds) {
          const nodes = [];
          for (const id2 of selectedIds) {
            const n2 = detailApi.getRowNode(id2);
            if (n2) {
              nodes.push(n2);
            }
          }
          detailApi.setNodesSelected({ nodes, newValue: true, source: "masterDetail" });
        }
        break;
      }
    }
  }
  dispatchSelectionChanged(source2) {
    this.eventSvc.dispatchEvent({
      type: "selectionChanged",
      source: source2,
      selectedNodes: this.getSelectedNodes(),
      serverSideState: null
    });
  }
};
function _normaliseSiblingRef(node2) {
  return _isManualPinnedRow(node2) ? node2.pinnedSibling : node2.footer ? node2.sibling : node2;
}
function _isAllSelected(api2) {
  let selectedCount = 0;
  let notSelectedCount = 0;
  api2.forEachNode((node2) => {
    if (node2.isSelected()) {
      selectedCount++;
    } else if (node2.selectable) {
      notSelectedCount++;
    }
  });
  return _calculateSelectAllState(selectedCount, notSelectedCount);
}
function _calculateSelectAllState(selected2, notSelected) {
  if (selected2 === 0 && notSelected === 0) {
    return false;
  }
  if (selected2 > 0 && notSelected > 0) {
    return;
  }
  return selected2 > 0;
}
function isDescendantOf(root2, child) {
  let parent = child.parent;
  while (parent) {
    if (parent === root2) {
      return true;
    }
    parent = parent.parent;
  }
  return false;
}
function recursiveCanNodesBeSelected(root2) {
  const rootCanBeSelected = root2.isSelected() === false;
  const childrenCanBeSelected = root2.childrenAfterFilter?.some(recursiveCanNodesBeSelected) ?? false;
  return rootCanBeSelected || childrenCanBeSelected;
}
var SharedRowSelectionModule = {
  moduleName: "SharedRowSelection",
  version: VERSION,
  beans: [SelectionColService],
  apiFunctions: {
    setNodesSelected,
    selectAll,
    deselectAll,
    selectAllFiltered,
    deselectAllFiltered,
    selectAllOnCurrentPage,
    deselectAllOnCurrentPage,
    getSelectedNodes,
    getSelectedRows
  }
};
var RowSelectionModule = {
  moduleName: "RowSelection",
  version: VERSION,
  rowModels: ["clientSide", "infinite", "viewport"],
  beans: [SelectionService],
  dependsOn: [SharedRowSelectionModule]
};
function expandAll(beans) {
  beans.expansionSvc?.expandAll(true);
}
function collapseAll(beans) {
  beans.expansionSvc?.expandAll(false);
}
function onRowHeightChanged(beans) {
  beans.rowModel?.onRowHeightChanged();
}
function resetRowHeights(beans) {
  if (beans.rowAutoHeight?.active) {
    _warn(3);
    return;
  }
  beans.rowModel?.resetRowHeights();
}
function setRowCount(beans, rowCount, maxRowFound) {
  const serverSideRowModel = _getServerSideRowModel(beans);
  if (serverSideRowModel) {
    if (beans.rowGroupColsSvc?.columns.length === 0) {
      if (rowCount < 0) {
        _error(238);
        return;
      }
      serverSideRowModel.setRowCount(rowCount, maxRowFound);
      return;
    }
    _error(28);
    return;
  }
  _getInfiniteRowModel(beans)?.setRowCount(rowCount, maxRowFound);
}
function getCacheBlockState(beans) {
  if (_isServerSideRowModel(beans.gos)) {
    const ssrm = beans.rowModel;
    return ssrm.getBlockStates();
  }
  return beans.rowNodeBlockLoader?.getBlockState() ?? {};
}
function isLastRowIndexKnown(beans) {
  return beans.rowModel.isLastRowIndexKnown();
}
var CsrmSsrmSharedApiModule = {
  moduleName: "CsrmSsrmSharedApi",
  version: VERSION,
  apiFunctions: { expandAll, collapseAll }
};
var RowModelSharedApiModule = {
  moduleName: "RowModelSharedApi",
  version: VERSION,
  apiFunctions: { onRowHeightChanged, resetRowHeights }
};
var SsrmInfiniteSharedApiModule = {
  moduleName: "SsrmInfiniteSharedApi",
  version: VERSION,
  apiFunctions: {
    setRowCount,
    getCacheBlockState,
    isLastRowIndexKnown
  }
};
var AlignedGridsService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "alignedGridsSvc";
    this.consuming = false;
  }
  getAlignedGridApis() {
    let alignedGrids = this.gos.get("alignedGrids") ?? [];
    const isCallbackConfig = typeof alignedGrids === "function";
    if (typeof alignedGrids === "function") {
      alignedGrids = alignedGrids();
    }
    const apis = alignedGrids.map((alignedGrid) => {
      if (!alignedGrid) {
        _error(18);
        if (!isCallbackConfig) {
          _error(20);
        }
        return;
      }
      if (this.isGridApi(alignedGrid)) {
        return alignedGrid;
      }
      const refOrComp = alignedGrid;
      if ("current" in refOrComp) {
        return refOrComp.current?.api;
      }
      if (!refOrComp.api) {
        _error(19);
      }
      return refOrComp.api;
    }).filter((api2) => !!api2 && !api2.isDestroyed());
    return apis;
  }
  isGridApi(ref2) {
    return !!ref2 && !!ref2.dispatchEvent;
  }
  postConstruct() {
    const fireColumnEvent = this.fireColumnEvent.bind(this);
    this.addManagedEventListeners({
      columnMoved: fireColumnEvent,
      columnVisible: fireColumnEvent,
      columnPinned: fireColumnEvent,
      columnGroupOpened: fireColumnEvent,
      columnResized: fireColumnEvent,
      bodyScroll: this.fireScrollEvent.bind(this),
      alignedGridColumn: ({ event }) => this.onColumnEvent(event),
      alignedGridScroll: ({ event }) => this.onScrollEvent(event)
    });
  }
  // common logic across all the fire methods
  fireEvent(event) {
    if (this.consuming) {
      return;
    }
    for (const api2 of this.getAlignedGridApis()) {
      if (api2.isDestroyed()) {
        continue;
      }
      api2.dispatchEvent(event);
    }
  }
  // common logic across all consume methods. very little common logic, however extracting
  // guarantees consistency across the methods.
  onEvent(callback) {
    this.consuming = true;
    callback();
    this.consuming = false;
  }
  fireColumnEvent(columnEvent) {
    this.fireEvent({
      type: "alignedGridColumn",
      event: columnEvent
    });
  }
  fireScrollEvent(scrollEvent) {
    if (scrollEvent.direction !== "horizontal") {
      return;
    }
    this.fireEvent({
      type: "alignedGridScroll",
      event: scrollEvent
    });
  }
  onScrollEvent(event) {
    this.onEvent(() => {
      this.beans.ctrlsSvc.getScrollFeature().setHorizontalScrollPosition(event.left, true);
    });
  }
  extractDataFromEvent(event, func2) {
    const result2 = [];
    if (event.columns) {
      event.columns.forEach((column2) => {
        result2.push(func2(column2));
      });
    } else if (event.column) {
      result2.push(func2(event.column));
    }
    return result2;
  }
  getMasterColumns(event) {
    return this.extractDataFromEvent(event, (col) => col);
  }
  getColumnIds(event) {
    return this.extractDataFromEvent(event, (col) => col.getColId());
  }
  onColumnEvent(event) {
    this.onEvent(() => {
      switch (event.type) {
        case "columnMoved":
        case "columnVisible":
        case "columnPinned":
        case "columnResized": {
          this.processColumnEvent(event);
          break;
        }
        case "columnGroupOpened": {
          this.processGroupOpenedEvent(event);
          break;
        }
        case "columnPivotChanged":
          _warn(21);
          break;
      }
    });
  }
  processGroupOpenedEvent(groupOpenedEvent) {
    const { colGroupSvc } = this.beans;
    if (!colGroupSvc) {
      return;
    }
    for (const masterGroup of groupOpenedEvent.columnGroups) {
      let otherColumnGroup = null;
      if (masterGroup) {
        otherColumnGroup = colGroupSvc.getProvidedColGroup(masterGroup.getGroupId());
      }
      if (masterGroup && !otherColumnGroup) {
        continue;
      }
      colGroupSvc.setColumnGroupOpened(otherColumnGroup, masterGroup.isExpanded(), "alignedGridChanged");
    }
  }
  processColumnEvent(colEvent) {
    const masterColumn = colEvent.column;
    let otherColumn = null;
    const beans = this.beans;
    const { colResize, ctrlsSvc, colModel } = beans;
    if (masterColumn) {
      otherColumn = colModel.getColDefCol(masterColumn.getColId());
    }
    if (masterColumn && !otherColumn) {
      return;
    }
    const masterColumns = this.getMasterColumns(colEvent);
    switch (colEvent.type) {
      case "columnMoved":
        {
          const srcColState = colEvent.api.getColumnState();
          const destColState = srcColState.map((s) => ({ colId: s.colId }));
          _applyColumnState(beans, { state: destColState, applyOrder: true }, "alignedGridChanged");
        }
        break;
      case "columnVisible":
        {
          const srcColState = colEvent.api.getColumnState();
          const destColState = srcColState.map((s) => ({ colId: s.colId, hide: s.hide }));
          _applyColumnState(beans, { state: destColState }, "alignedGridChanged");
        }
        break;
      case "columnPinned":
        {
          const srcColState = colEvent.api.getColumnState();
          const destColState = srcColState.map((s) => ({ colId: s.colId, pinned: s.pinned }));
          _applyColumnState(beans, { state: destColState }, "alignedGridChanged");
        }
        break;
      case "columnResized": {
        const resizedEvent = colEvent;
        const columnWidths = {};
        for (const column2 of masterColumns) {
          columnWidths[column2.getId()] = { key: column2.getColId(), newWidth: column2.getActualWidth() };
        }
        for (const col of resizedEvent.flexColumns ?? []) {
          if (columnWidths[col.getId()]) {
            delete columnWidths[col.getId()];
          }
        }
        colResize?.setColumnWidths(
          Object.values(columnWidths),
          false,
          resizedEvent.finished,
          "alignedGridChanged"
        );
        break;
      }
    }
    const gridBodyCon = ctrlsSvc.getGridBodyCtrl();
    const isVerticalScrollShowing = gridBodyCon.isVerticalScrollShowing();
    for (const api2 of this.getAlignedGridApis()) {
      api2.setGridOption("alwaysShowVerticalScroll", isVerticalScrollShowing);
    }
  }
};
var AlignedGridsModule = {
  moduleName: "AlignedGrids",
  version: VERSION,
  beans: [AlignedGridsService],
  dependsOn: [ColumnApiModule]
};
var ClientSideNodeManager = class extends BeanStub {
  constructor(rootNode) {
    super();
    this.rootNode = rootNode;
    this.nextId = 0;
    this.allNodesMap = {};
    initRootNode(rootNode);
  }
  getRowNode(id2) {
    return this.allNodesMap[id2];
  }
  setNewRowData(rowData) {
    const { selectionSvc, pinnedRowModel, groupStage } = this.beans;
    selectionSvc?.reset("rowDataChanged");
    if (pinnedRowModel?.isManual()) {
      pinnedRowModel.reset();
    }
    this.dispatchRowDataUpdateStarted(rowData);
    this.allNodesMap = /* @__PURE__ */ Object.create(null);
    this.nextId = 0;
    const rootNode = initRootNode(this.rootNode);
    const allLeafs = new Array(rowData.length);
    rootNode._leafs = allLeafs;
    let writeIdx = 0;
    const nestedDataGetter = groupStage?.getNestedDataGetter();
    const processedNested = nestedDataGetter ? /* @__PURE__ */ new Set() : null;
    const processChildren = (parent, childrenData) => {
      const level = parent.level + 1;
      for (let i2 = 0, len = childrenData.length; i2 < len; ++i2) {
        const data2 = childrenData[i2];
        if (!data2) {
          continue;
        }
        const node2 = this.createRowNode(data2, level);
        node2.sourceRowIndex = writeIdx;
        allLeafs[writeIdx++] = node2;
        if (processedNested && !processedNested.has(data2)) {
          processedNested.add(data2);
          node2.treeParent = parent;
          const children2 = nestedDataGetter(data2);
          if (children2) {
            processChildren(node2, children2);
          }
        }
      }
    };
    processChildren(rootNode, rowData);
    allLeafs.length = writeIdx;
  }
  setImmutableRowData(params, rowData) {
    const { rootNode, gos } = this;
    this.dispatchRowDataUpdateStarted(rowData);
    const getRowIdFunc = _getRowIdCallback(gos);
    const changedRowNodes = params.changedRowNodes;
    const { adds, updates } = changedRowNodes;
    const processedNodes = /* @__PURE__ */ new Set();
    const nodesToUnselect = [];
    const nestedDataGetter = this.beans.groupStage?.getNestedDataGetter();
    let reorder = gos.get("suppressMaintainUnsortedOrder") ? void 0 : false;
    let prevIndex = -1;
    let treeUpdated = false;
    const updateNode = (node2, data2) => {
      if (!reorder && reorder !== void 0) {
        const oldIndex = node2.sourceRowIndex;
        reorder = oldIndex <= prevIndex;
        prevIndex = oldIndex;
      }
      if (node2.data !== data2) {
        node2.updateData(data2);
        if (!adds.has(node2)) {
          updates.add(node2);
        }
        if (!node2.selectable && node2.isSelected()) {
          nodesToUnselect.push(node2);
        }
      }
    };
    const processChildren = (parent, childrenData, level) => {
      for (let i2 = 0, len = childrenData.length; i2 < len; ++i2) {
        const data2 = childrenData[i2];
        if (!data2) {
          continue;
        }
        let node2 = this.getRowNode(getRowIdFunc({ data: data2, level }));
        if (node2) {
          updateNode(node2, data2);
          treeUpdated || (treeUpdated = !!nestedDataGetter && node2.treeParent !== parent);
        } else {
          node2 = this.createRowNode(data2, level);
          adds.add(node2);
        }
        if (!nestedDataGetter || processedNodes.has(node2)) {
          processedNodes.add(node2);
          continue;
        }
        processedNodes.add(node2);
        node2.treeParent = parent;
        const children2 = nestedDataGetter(data2);
        if (children2) {
          processChildren(node2, children2, level + 1);
        }
      }
    };
    processChildren(rootNode, rowData, 0);
    const changed = this.deleteUnusedNodes(processedNodes, changedRowNodes, nodesToUnselect) || reorder || adds.size > 0;
    if (changed) {
      const allLeafs = rootNode._leafs ?? (rootNode._leafs = []);
      if (reorder === void 0) {
        updateRootLeafsKeepOrder(allLeafs, processedNodes, changedRowNodes);
      } else if (updateRootLeafsOrdered(allLeafs, processedNodes)) {
        changedRowNodes.reordered = true;
      }
    }
    if (changed || treeUpdated || updates.size) {
      params.rowDataUpdated = true;
      this.deselect(nodesToUnselect);
    }
  }
  deleteUnusedNodes(processedNodes, { removals }, nodesToUnselect) {
    const allLeafs = this.rootNode._leafs;
    for (let i2 = 0, len = allLeafs.length; i2 < len; i2++) {
      const node2 = allLeafs[i2];
      if (!processedNodes.has(node2)) {
        removals.add(node2);
        if (node2.isSelected()) {
          nodesToUnselect.push(node2);
        }
        this.deleteNode(node2);
      }
    }
    return removals.size > 0;
  }
  updateRowData(rowDataTran, changedRowNodes) {
    this.dispatchRowDataUpdateStarted(rowDataTran.add);
    if (this.beans.groupStage?.getNestedDataGetter()) {
      _warn(268);
      return { remove: [], update: [], add: [] };
    }
    const nodesToUnselect = [];
    const getRowIdFunc = _getRowIdCallback(this.gos);
    const remove = this.executeRemove(getRowIdFunc, rowDataTran, changedRowNodes, nodesToUnselect);
    const update2 = this.executeUpdate(getRowIdFunc, rowDataTran, changedRowNodes, nodesToUnselect);
    const add2 = this.executeAdd(rowDataTran, changedRowNodes);
    this.deselect(nodesToUnselect);
    return { remove, update: update2, add: add2 };
  }
  executeRemove(getRowIdFunc, { remove }, { adds, updates, removals }, nodesToUnselect) {
    const allLeafs = this.rootNode._leafs;
    const allLeafsLen = allLeafs?.length;
    const removeLen = remove?.length;
    if (!removeLen || !allLeafsLen) {
      return [];
    }
    let removeCount = 0;
    let filterIdx = allLeafsLen;
    let filterEndIdx = 0;
    let nodesNeverAdded;
    const removedResult = new Array(removeLen);
    for (let i2 = 0; i2 < removeLen; ++i2) {
      const rowNode = this.lookupNode(getRowIdFunc, remove[i2]);
      if (!rowNode) {
        continue;
      }
      const sourceRowIndex = rowNode.sourceRowIndex;
      if (sourceRowIndex < filterIdx) {
        filterIdx = sourceRowIndex;
      }
      if (sourceRowIndex > filterEndIdx) {
        filterEndIdx = sourceRowIndex;
      }
      if (rowNode.isSelected()) {
        nodesToUnselect.push(rowNode);
      }
      this.deleteNode(rowNode);
      if (adds.delete(rowNode)) {
        nodesNeverAdded ?? (nodesNeverAdded = /* @__PURE__ */ new Set());
        nodesNeverAdded.add(rowNode);
      } else {
        updates.delete(rowNode);
        removals.add(rowNode);
      }
      removedResult[removeCount++] = rowNode;
    }
    removedResult.length = removeCount;
    if (removeCount) {
      filterRemovedRowNodes(allLeafs, filterIdx, filterEndIdx, removals, nodesNeverAdded);
    }
    return removedResult;
  }
  executeUpdate(getRowIdFunc, { update: update2 }, { adds, updates }, nodesToUnselect) {
    const updateLen = update2?.length;
    if (!updateLen) {
      return [];
    }
    const updateResult = new Array(updateLen);
    let writeIdx = 0;
    for (let i2 = 0; i2 < updateLen; i2++) {
      const item2 = update2[i2];
      const rowNode = this.lookupNode(getRowIdFunc, item2);
      if (rowNode) {
        rowNode.updateData(item2);
        if (!rowNode.selectable && rowNode.isSelected()) {
          nodesToUnselect.push(rowNode);
        }
        updateResult[writeIdx++] = rowNode;
        if (!adds.has(rowNode)) {
          updates.add(rowNode);
        }
      }
    }
    updateResult.length = writeIdx;
    return updateResult;
  }
  executeAdd(rowDataTran, changedRowNodes) {
    var _a2;
    const allLeafs = (_a2 = this.rootNode)._leafs ?? (_a2._leafs = []);
    const allLeafsLen = allLeafs.length;
    const add2 = rowDataTran.add;
    const addLength = add2?.length;
    if (!addLength) {
      return [];
    }
    const newLen = allLeafsLen + addLength;
    let addIndex = this.sanitizeAddIndex(allLeafs, rowDataTran.addIndex);
    if (addIndex < allLeafsLen) {
      for (let readIdx = allLeafsLen - 1, writeIdx = newLen - 1; readIdx >= addIndex; --readIdx) {
        const node2 = allLeafs[readIdx];
        node2.sourceRowIndex = writeIdx;
        allLeafs[writeIdx--] = node2;
      }
      changedRowNodes.reordered = true;
    }
    allLeafs.length = newLen;
    const addedNodes = new Array(addLength);
    const adds = changedRowNodes.adds;
    for (let i2 = 0; i2 < addLength; i2++) {
      const node2 = this.createRowNode(add2[i2], 0);
      adds.add(node2);
      node2.sourceRowIndex = addIndex;
      allLeafs[addIndex] = node2;
      addedNodes[i2] = node2;
      addIndex++;
    }
    return addedNodes;
  }
  dispatchRowDataUpdateStarted(data2) {
    this.eventSvc.dispatchEvent({ type: "rowDataUpdateStarted", firstRowData: data2?.length ? data2[0] : null });
  }
  deselect(nodes) {
    const source2 = "rowDataChanged";
    const selectionSvc = this.beans.selectionSvc;
    if (nodes.length) {
      selectionSvc?.setNodesSelected({ newValue: false, nodes, suppressFinishActions: true, source: source2 });
    }
    selectionSvc?.updateGroupsFromChildrenSelections?.(source2);
    if (nodes.length) {
      this.eventSvc.dispatchEvent({
        type: "selectionChanged",
        source: source2,
        selectedNodes: selectionSvc?.getSelectedNodes() ?? null,
        serverSideState: null
      });
    }
  }
  createRowNode(data2, level) {
    const node2 = new RowNode(this.beans);
    node2.parent = this.rootNode;
    node2.level = level;
    node2.group = false;
    node2.expanded = false;
    node2.setDataAndId(data2, String(this.nextId++));
    const id2 = node2.id;
    const allNodesMap = this.allNodesMap;
    if (allNodesMap[id2]) {
      _warn(2, { nodeId: id2 });
    }
    allNodesMap[id2] = node2;
    return node2;
  }
  /** Called when a node needs to be deleted */
  deleteNode(node2) {
    node2.clearRowTopAndRowIndex();
    const id2 = node2.id;
    const allNodesMap = this.allNodesMap;
    if (allNodesMap[id2] === node2) {
      delete allNodesMap[id2];
    }
    const pinnedSibling = node2.pinnedSibling;
    if (pinnedSibling) {
      this.beans.pinnedRowModel?.pinRow(pinnedSibling, null);
    }
  }
  lookupNode(getRowIdFunc, data2) {
    if (!getRowIdFunc) {
      return lookupNodeByData(this.rootNode._leafs, data2);
    }
    const id2 = getRowIdFunc({ data: data2, level: 0 });
    const rowNode = this.allNodesMap[id2];
    if (!rowNode) {
      _error(4, { id: id2 });
      return null;
    }
    return rowNode;
  }
  sanitizeAddIndex(allLeafs, addIndex) {
    const allLeafsLen = allLeafs.length;
    if (typeof addIndex !== "number") {
      return allLeafsLen;
    }
    if (addIndex < 0 || addIndex >= allLeafsLen || Number.isNaN(addIndex)) {
      return allLeafsLen;
    }
    addIndex = Math.ceil(addIndex);
    const gos = this.gos;
    if (addIndex > 0 && gos.get("treeData") && gos.get("getDataPath")) {
      addIndex = adjustAddIndexForDataPath(allLeafs, addIndex);
    }
    return addIndex;
  }
};
var adjustAddIndexForDataPath = (allLeafs, addIndex) => {
  for (let i2 = 0, len = allLeafs.length; i2 < len; i2++) {
    const node2 = allLeafs[i2];
    if (node2?.rowIndex == addIndex - 1) {
      return i2 + 1;
    }
  }
  return addIndex;
};
var initRootNode = (rootNode) => {
  rootNode.group = true;
  rootNode.level = -1;
  rootNode.id = "ROOT_NODE_ID";
  if (rootNode._leafs?.length !== 0) {
    rootNode._leafs = [];
  }
  const childrenAfterGroup = [];
  const childrenAfterSort = [];
  const childrenAfterAggFilter = [];
  const childrenAfterFilter = [];
  rootNode.childrenAfterGroup = childrenAfterGroup;
  rootNode.childrenAfterSort = childrenAfterSort;
  rootNode.childrenAfterAggFilter = childrenAfterAggFilter;
  rootNode.childrenAfterFilter = childrenAfterFilter;
  const sibling2 = rootNode.sibling;
  if (sibling2) {
    sibling2.childrenAfterGroup = childrenAfterGroup;
    sibling2.childrenAfterSort = childrenAfterSort;
    sibling2.childrenAfterAggFilter = childrenAfterAggFilter;
    sibling2.childrenAfterFilter = childrenAfterFilter;
    sibling2.childrenMapped = rootNode.childrenMapped;
  }
  rootNode.updateHasChildren();
  return rootNode;
};
var lookupNodeByData = (nodes, data2) => {
  if (nodes) {
    for (let i2 = 0, len = nodes.length; i2 < len; i2++) {
      const node2 = nodes[i2];
      if (node2.data === data2) {
        return node2;
      }
    }
  }
  _error(5, { data: data2 });
  return null;
};
var filterRemovedRowNodes = (allLeafs, filterIdx, filterEndIdx, removals, nodesNeverAdded) => {
  filterIdx = Math.max(0, filterIdx);
  for (let readIdx = filterIdx, len = allLeafs.length; readIdx < len; ++readIdx) {
    const node2 = allLeafs[readIdx];
    if (readIdx <= filterEndIdx && (removals.has(node2) || nodesNeverAdded?.has(node2))) {
      continue;
    }
    node2.sourceRowIndex = filterIdx;
    allLeafs[filterIdx++] = node2;
  }
  allLeafs.length = filterIdx;
};
var updateRootLeafsOrdered = (allLeafs, processedNodes) => {
  const newSize = processedNodes.size;
  allLeafs.length = newSize;
  let writeIdx = 0;
  let added = false;
  let reordered = false;
  for (const node2 of processedNodes) {
    const sourceRowIndex = node2.sourceRowIndex;
    if (sourceRowIndex === writeIdx) {
      reordered || (reordered = added);
    } else {
      if (sourceRowIndex >= 0) {
        reordered = true;
      } else {
        added = true;
      }
      node2.sourceRowIndex = writeIdx;
      allLeafs[writeIdx] = node2;
    }
    ++writeIdx;
  }
  return reordered;
};
var updateRootLeafsKeepOrder = (allLeafs, processedNodes, { removals, adds }) => {
  const allLeafsLen = allLeafs.length;
  allLeafs.length = processedNodes.size;
  let writeIdx = 0;
  for (let readIdx = 0; readIdx < allLeafsLen; ++readIdx) {
    const node2 = allLeafs[readIdx];
    if (!removals.has(node2)) {
      if (writeIdx !== readIdx) {
        node2.sourceRowIndex = writeIdx;
        allLeafs[writeIdx] = node2;
      }
      ++writeIdx;
    }
  }
  for (const node2 of adds) {
    if (node2.sourceRowIndex < 0) {
      node2.sourceRowIndex = writeIdx;
      allLeafs[writeIdx++] = node2;
    }
  }
  allLeafs.length = writeIdx;
};
var updateRowNodeAfterSort = (rowNode) => {
  const childrenAfterSort = rowNode.childrenAfterSort;
  const sibling2 = rowNode.sibling;
  if (sibling2) {
    sibling2.childrenAfterSort = childrenAfterSort;
  }
  if (!childrenAfterSort) {
    return;
  }
  for (let i2 = 0, lastIdx = childrenAfterSort.length - 1; i2 <= lastIdx; i2++) {
    const child = childrenAfterSort[i2];
    const first2 = i2 === 0;
    const last2 = i2 === lastIdx;
    if (child.firstChild !== first2) {
      child.firstChild = first2;
      child.dispatchRowEvent("firstChildChanged");
    }
    if (child.lastChild !== last2) {
      child.lastChild = last2;
      child.dispatchRowEvent("lastChildChanged");
    }
    if (child.childIndex !== i2) {
      child.childIndex = i2;
      child.dispatchRowEvent("childIndexChanged");
    }
  }
};
var SortStage = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "sortStage";
    this.step = "sort";
    this.refreshProps = ["postSortRows", "groupDisplayType", "accentedSort"];
  }
  execute(params) {
    const sortOptions = this.beans.sortSvc.getSortOptions();
    const deltaSort = sortOptions.length > 0 && !!params.changedRowNodes && // in time we can remove this check, so that delta sort is always
    // on if transactions are present. it's off for now so that we can
    // selectively turn it on and test it with some select users before
    // rolling out to everyone.
    this.gos.get("deltaSort");
    this.sort(sortOptions, deltaSort, params.changedRowNodes, params.changedPath);
  }
  sort(sortOptions, useDeltaSort, changedRowNodes, changedPath) {
    const { gos, colModel, rowGroupColsSvc, rowNodeSorter, rowRenderer, showRowGroupCols } = this.beans;
    const groupMaintainOrder = gos.get("groupMaintainOrder");
    const groupColumnsPresent = colModel.getCols().some((c2) => c2.isRowGroupActive());
    const groupCols = rowGroupColsSvc?.columns;
    const isPivotMode = colModel.isPivotMode();
    const postSortFunc = gos.getCallback("postSortRows");
    let hasAnyFirstChildChanged = false;
    let sortContainsGroupColumns;
    const callback = (rowNode) => {
      const skipSortingPivotLeafs = isPivotMode && rowNode.leafGroup;
      let skipSortingGroups = groupMaintainOrder && groupColumnsPresent && !rowNode.leafGroup;
      if (skipSortingGroups) {
        sortContainsGroupColumns ?? (sortContainsGroupColumns = this.shouldSortContainsGroupCols(sortOptions));
        skipSortingGroups && (skipSortingGroups = !sortContainsGroupColumns);
      }
      let newChildrenAfterSort = null;
      if (skipSortingGroups) {
        let wasSortExplicitlyRemoved = false;
        if (groupCols) {
          const nextGroupIndex = rowNode.level + 1;
          if (nextGroupIndex < groupCols.length) {
            wasSortExplicitlyRemoved = groupCols[nextGroupIndex].getSort() === null;
          }
        }
        if (!wasSortExplicitlyRemoved) {
          newChildrenAfterSort = preserveGroupOrder(rowNode);
        }
      } else if (!sortOptions.length || skipSortingPivotLeafs) ;
      else if (useDeltaSort && changedRowNodes) {
        newChildrenAfterSort = doDeltaSort(rowNodeSorter, rowNode, changedRowNodes, changedPath, sortOptions);
      } else {
        newChildrenAfterSort = rowNodeSorter.doFullSort(rowNode.childrenAfterAggFilter, sortOptions);
      }
      newChildrenAfterSort || (newChildrenAfterSort = rowNode.childrenAfterAggFilter?.slice(0) ?? []);
      hasAnyFirstChildChanged || (hasAnyFirstChildChanged = rowNode.childrenAfterSort?.[0] !== newChildrenAfterSort[0]);
      rowNode.childrenAfterSort = newChildrenAfterSort;
      updateRowNodeAfterSort(rowNode);
      if (postSortFunc) {
        const params = { nodes: rowNode.childrenAfterSort };
        postSortFunc(params);
      }
    };
    changedPath?.forEachChangedNodeDepthFirst(callback);
    if (hasAnyFirstChildChanged && gos.get("groupHideOpenParents")) {
      const columns2 = showRowGroupCols?.getShowRowGroupCols();
      if (columns2?.length) {
        rowRenderer.refreshCells({ columns: columns2, force: true });
      }
    }
  }
  shouldSortContainsGroupCols(sortOptions) {
    const sortOptionsLen = sortOptions.length;
    if (!sortOptionsLen) {
      return false;
    }
    if (_isColumnsSortingCoupledToGroup(this.gos)) {
      for (let i2 = 0; i2 < sortOptionsLen; ++i2) {
        const column2 = sortOptions[i2].column;
        if (column2.isPrimary() && column2.isRowGroupActive()) {
          return true;
        }
      }
      return false;
    }
    for (let i2 = 0; i2 < sortOptionsLen; ++i2) {
      if (sortOptions[i2].column.getColDef().showRowGroup) {
        return true;
      }
    }
    return false;
  }
};
var doDeltaSort = (rowNodeSorter, rowNode, changedRowNodes, changedPath, sortOptions) => {
  const unsortedRows = rowNode.childrenAfterAggFilter;
  const oldSortedRows = rowNode.childrenAfterSort;
  if (!oldSortedRows) {
    return rowNodeSorter.doFullSort(unsortedRows, sortOptions);
  }
  const untouchedRows = /* @__PURE__ */ new Set();
  const touchedRows = [];
  const { updates, adds } = changedRowNodes;
  for (let i2 = 0, len = unsortedRows.length; i2 < len; ++i2) {
    const row2 = unsortedRows[i2];
    if (updates.has(row2) || adds.has(row2) || changedPath && !changedPath.canSkip(row2)) {
      touchedRows.push({
        currentPos: touchedRows.length,
        rowNode: row2
      });
    } else {
      untouchedRows.add(row2);
    }
  }
  const sortedUntouchedRows = oldSortedRows.filter((child) => untouchedRows.has(child)).map((rowNode2, currentPos) => ({ currentPos, rowNode: rowNode2 }));
  touchedRows.sort((a2, b) => rowNodeSorter.compareRowNodes(sortOptions, a2, b));
  return mergeSortedArrays(rowNodeSorter, sortOptions, touchedRows, sortedUntouchedRows);
};
var mergeSortedArrays = (rowNodeSorter, sortOptions, arr1, arr2) => {
  let i2 = 0;
  let j2 = 0;
  const arr1Length = arr1.length;
  const arr2Length = arr2.length;
  const res = new Array(arr1Length + arr2Length);
  let k = 0;
  while (i2 < arr1Length && j2 < arr2Length) {
    const a2 = arr1[i2];
    const b = arr2[j2];
    if (rowNodeSorter.compareRowNodes(sortOptions, a2, b) < 0) {
      res[k++] = a2.rowNode;
      ++i2;
    } else {
      res[k++] = b.rowNode;
      ++j2;
    }
  }
  while (i2 < arr1Length) {
    res[k++] = arr1[i2++].rowNode;
  }
  while (j2 < arr2Length) {
    res[k++] = arr2[j2++].rowNode;
  }
  return res;
};
var preserveGroupOrder = (node2) => {
  const childrenAfterSort = node2.childrenAfterSort;
  const childrenAfterAggFilter = node2.childrenAfterAggFilter;
  const childrenAfterSortLen = childrenAfterSort?.length;
  const childrenAfterAggFilterLen = childrenAfterAggFilter?.length;
  if (!childrenAfterSortLen || !childrenAfterAggFilterLen) {
    return null;
  }
  const result2 = new Array(childrenAfterAggFilterLen);
  const processed = /* @__PURE__ */ new Set();
  for (let i2 = 0; i2 < childrenAfterAggFilterLen; ++i2) {
    processed.add(childrenAfterAggFilter[i2]);
  }
  let writeIdx = 0;
  for (let i2 = 0; i2 < childrenAfterSortLen; ++i2) {
    const node22 = childrenAfterSort[i2];
    if (processed.delete(node22)) {
      result2[writeIdx++] = node22;
    }
  }
  if (processed.size === 0 && writeIdx === childrenAfterSortLen) {
    return childrenAfterSort;
  }
  for (const newNode of processed) {
    result2[writeIdx++] = newNode;
  }
  result2.length = writeIdx;
  return result2;
};
var ClientSideRowModel = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "rowModel";
    this.rootNode = null;
    this.rowCountReady = false;
    this.nodeManager = void 0;
    this.rowsToDisplay = [];
    this.rowDataUpdatedPending = false;
    this.asyncTransactions = null;
    this.asyncTransactionsTimer = 0;
    this.started = false;
    this.refreshingModel = false;
    this.rowNodesCountReady = false;
    this.stages = [];
    this.stagesRefreshProps = /* @__PURE__ */ new Map();
    this.onRowHeightChanged_debounced = _debounce(this, this.onRowHeightChanged.bind(this), 100);
  }
  postConstruct() {
    const beans = this.beans;
    const rootNode = new RowNode(beans);
    this.rootNode = rootNode;
    this.nodeManager = this.createBean(new ClientSideNodeManager(rootNode));
    const refreshEverythingFunc = this.refreshModel.bind(this, { step: "group" });
    const refreshEverythingAfterColsChangedFunc = this.refreshModel.bind(this, {
      step: "group",
      // after cols change, row grouping (the first stage) could of changed
      afterColumnsChanged: true,
      keepRenderedRows: true,
      // we want animations cos sorting or filtering could be applied
      animate: !this.gos.get("suppressAnimationFrame")
    });
    this.addManagedEventListeners({
      newColumnsLoaded: refreshEverythingAfterColsChangedFunc,
      columnRowGroupChanged: refreshEverythingFunc,
      columnValueChanged: this.onValueChanged.bind(this),
      columnPivotChanged: this.refreshModel.bind(this, { step: "pivot" }),
      filterChanged: this.onFilterChanged.bind(this),
      sortChanged: this.onSortChanged.bind(this),
      columnPivotModeChanged: refreshEverythingFunc,
      gridStylesChanged: this.onGridStylesChanges.bind(this),
      gridReady: this.onGridReady.bind(this),
      rowExpansionStateChanged: this.onRowGroupOpened.bind(this)
    });
    this.addPropertyListeners();
  }
  addPropertyListeners() {
    const { beans, stagesRefreshProps } = this;
    const orderedStages = [
      beans.groupStage,
      beans.filterStage,
      beans.pivotStage,
      beans.aggStage,
      beans.sortStage,
      beans.filterAggStage,
      beans.flattenStage
    ].filter((stage) => !!stage);
    this.stages = orderedStages;
    for (let i2 = orderedStages.length - 1; i2 >= 0; --i2) {
      for (const prop of orderedStages[i2].refreshProps) {
        stagesRefreshProps.set(prop, i2);
      }
    }
    this.addManagedPropertyListeners([...stagesRefreshProps.keys()], (params) => {
      const properties = params.changeSet?.properties;
      if (properties) {
        this.onPropChange(properties);
      }
    });
    this.addManagedPropertyListener("rowData", () => this.onPropChange(["rowData"]));
    this.addManagedPropertyListener("rowHeight", () => this.resetRowHeights());
  }
  start() {
    this.started = true;
    if (this.rowNodesCountReady) {
      this.refreshModel({ step: "group", rowDataUpdated: true, newData: true });
    } else {
      this.setInitialData();
    }
  }
  setInitialData() {
    const rowData = this.gos.get("rowData");
    if (rowData) {
      this.onPropChange(["rowData"]);
    }
  }
  ensureRowHeightsValid(startPixel, endPixel, startLimitIndex, endLimitIndex) {
    let atLeastOneChange;
    let res = false;
    do {
      atLeastOneChange = false;
      const rowAtStartPixel = this.getRowIndexAtPixel(startPixel);
      const rowAtEndPixel = this.getRowIndexAtPixel(endPixel);
      const firstRow = Math.max(rowAtStartPixel, startLimitIndex);
      const lastRow = Math.min(rowAtEndPixel, endLimitIndex);
      for (let rowIndex = firstRow; rowIndex <= lastRow; rowIndex++) {
        const rowNode = this.getRow(rowIndex);
        if (rowNode.rowHeightEstimated) {
          const rowHeight = _getRowHeightForNode(this.beans, rowNode);
          rowNode.setRowHeight(rowHeight.height);
          atLeastOneChange = true;
          res = true;
        }
      }
      if (atLeastOneChange) {
        this.setRowTopAndRowIndex();
      }
    } while (atLeastOneChange);
    return res;
  }
  onPropChange(properties) {
    const { nodeManager, gos, beans } = this;
    const groupStage = beans.groupStage;
    if (!nodeManager) {
      return;
    }
    const changedProps = new Set(properties);
    const extractData = groupStage?.onPropChange(changedProps);
    let newRowData;
    if (changedProps.has("rowData")) {
      newRowData = gos.get("rowData");
    } else if (extractData) {
      newRowData = groupStage?.extractData();
    }
    if (newRowData && !Array.isArray(newRowData)) {
      newRowData = null;
      _warn(1);
    }
    const params = { step: "nothing", changedProps };
    if (newRowData) {
      const immutable = !extractData && !this.isEmpty() && newRowData.length > 0 && gos.exists("getRowId") && // backward compatibility - for who want old behaviour of Row IDs but NOT Immutable Data.
      !gos.get("resetRowDataOnUpdate");
      if (immutable) {
        params.keepRenderedRows = true;
        params.animate = !gos.get("suppressAnimationFrame");
        params.changedRowNodes = new ChangedRowNodes();
        nodeManager.setImmutableRowData(params, newRowData);
      } else {
        params.rowDataUpdated = true;
        params.newData = true;
        nodeManager.setNewRowData(newRowData);
        this.rowNodesCountReady = true;
      }
    }
    const step = params.rowDataUpdated ? "group" : this.getRefreshedStage(properties);
    if (step) {
      params.step = step;
      this.refreshModel(params);
    }
  }
  getRefreshedStage(properties) {
    const { stages, stagesRefreshProps } = this;
    const stagesLen = stages.length;
    let minIndex = stagesLen;
    for (let i2 = 0, len = properties.length; i2 < len && minIndex; ++i2) {
      minIndex = Math.min(minIndex, stagesRefreshProps.get(properties[i2]) ?? minIndex);
    }
    return minIndex < stagesLen ? stages[minIndex].step : null;
  }
  setRowTopAndRowIndex(outputDisplayedRowsMapped) {
    const { beans, rowsToDisplay } = this;
    const defaultRowHeight = beans.environment.getDefaultRowHeight();
    let nextRowTop = 0;
    const allowEstimate = _isDomLayout(this.gos, "normal");
    for (let i2 = 0, len = rowsToDisplay.length; i2 < len; ++i2) {
      const rowNode = rowsToDisplay[i2];
      const id2 = rowNode.id;
      if (id2 != null) {
        outputDisplayedRowsMapped?.add(id2);
      }
      if (rowNode.rowHeight == null) {
        const rowHeight = _getRowHeightForNode(beans, rowNode, allowEstimate, defaultRowHeight);
        rowNode.setRowHeight(rowHeight.height, rowHeight.estimated);
      }
      rowNode.setRowTop(nextRowTop);
      rowNode.setRowIndex(i2);
      nextRowTop += rowNode.rowHeight;
    }
  }
  clearRowTopAndRowIndex(changedPath, displayedRowsMapped) {
    const changedPathActive = changedPath.active;
    const clearIfNotDisplayed = (rowNode) => {
      if (rowNode?.id != null && !displayedRowsMapped.has(rowNode.id)) {
        rowNode.clearRowTopAndRowIndex();
      }
    };
    const recurse = (rowNode) => {
      clearIfNotDisplayed(rowNode);
      clearIfNotDisplayed(rowNode.detailNode);
      clearIfNotDisplayed(rowNode.sibling);
      const childrenAfterGroup = rowNode.childrenAfterGroup;
      if (!rowNode.hasChildren() || !childrenAfterGroup) {
        return;
      }
      const isRootNode = rowNode.level == -1;
      const skipChildren = changedPathActive && !isRootNode && !rowNode.expanded;
      if (skipChildren) {
        return;
      }
      for (let i2 = 0, len = childrenAfterGroup.length; i2 < len; ++i2) {
        recurse(childrenAfterGroup[i2]);
      }
    };
    const rootNode = this.rootNode;
    if (rootNode) {
      recurse(rootNode);
    }
  }
  isLastRowIndexKnown() {
    return true;
  }
  getRowCount() {
    return this.rowsToDisplay.length;
  }
  /**
   * Returns the number of rows with level === 1
   */
  getTopLevelRowCount() {
    const { rootNode, rowsToDisplay } = this;
    if (!rootNode || !rowsToDisplay.length) {
      return 0;
    }
    const showingRootNode = rowsToDisplay[0] === rootNode;
    if (showingRootNode) {
      return 1;
    }
    const totalFooterInc = rootNode.sibling?.displayed ? 1 : 0;
    return (rootNode.childrenAfterSort?.length ?? 0) + totalFooterInc;
  }
  /**
   * Get the row display index by the top level index
   * top level index is the index of rows with level === 1
   */
  getTopLevelRowDisplayedIndex(topLevelIndex) {
    const { beans, rootNode, rowsToDisplay } = this;
    const showingRootNode = !rootNode || !rowsToDisplay.length || rowsToDisplay[0] === rootNode;
    if (showingRootNode) {
      return topLevelIndex;
    }
    const childrenAfterSort = rootNode.childrenAfterSort;
    const getDefaultIndex = (adjustedIndex) => {
      let rowNode = childrenAfterSort[adjustedIndex];
      if (this.gos.get("groupHideOpenParents")) {
        while (rowNode.expanded && rowNode.childrenAfterSort && rowNode.childrenAfterSort.length > 0) {
          rowNode = rowNode.childrenAfterSort[0];
        }
      }
      return rowNode.rowIndex;
    };
    const footerSvc = beans.footerSvc;
    if (footerSvc) {
      return footerSvc?.getTopDisplayIndex(rowsToDisplay, topLevelIndex, childrenAfterSort, getDefaultIndex);
    }
    return getDefaultIndex(topLevelIndex);
  }
  /**
   * The opposite of `getTopLevelRowDisplayedIndex`
   */
  getTopLevelIndexFromDisplayedIndex(displayedIndex) {
    const { rootNode, rowsToDisplay } = this;
    const showingRootNode = !rootNode || !rowsToDisplay.length || rowsToDisplay[0] === rootNode;
    if (showingRootNode) {
      return displayedIndex;
    }
    let node2 = this.getRow(displayedIndex);
    if (node2.footer) {
      node2 = node2.sibling;
    }
    let parent = node2.parent;
    while (parent && parent !== rootNode) {
      node2 = parent;
      parent = node2.parent;
    }
    const topLevelIndex = rootNode.childrenAfterSort?.indexOf(node2) ?? -1;
    return topLevelIndex >= 0 ? topLevelIndex : displayedIndex;
  }
  getRowBounds(index) {
    const rowNode = this.rowsToDisplay[index];
    return rowNode ? { rowTop: rowNode.rowTop, rowHeight: rowNode.rowHeight } : null;
  }
  onRowGroupOpened() {
    this.refreshModel({ step: "map", keepRenderedRows: true, animate: _isAnimateRows(this.gos) });
  }
  onFilterChanged({ afterDataChange, columns: columns2 }) {
    if (!afterDataChange) {
      const primaryOrQuickFilterChanged = columns2.length === 0 || columns2.some((col) => col.isPrimary());
      const step = primaryOrQuickFilterChanged ? "filter" : "filter_aggregates";
      this.refreshModel({ step, keepRenderedRows: true, animate: _isAnimateRows(this.gos) });
    }
  }
  onSortChanged() {
    this.refreshModel({
      step: "sort",
      keepRenderedRows: true,
      animate: _isAnimateRows(this.gos)
    });
  }
  getType() {
    return "clientSide";
  }
  onValueChanged() {
    this.refreshModel({ step: this.beans.colModel.isPivotActive() ? "pivot" : "aggregate" });
  }
  createChangePath(enabled) {
    const changedPath = new ChangedPath(false, this.rootNode);
    changedPath.active = enabled;
    return changedPath;
  }
  isSuppressModelUpdateAfterUpdateTransaction(params) {
    if (!this.gos.get("suppressModelUpdateAfterUpdateTransaction")) {
      return false;
    }
    const { changedRowNodes, newData, rowDataUpdated } = params;
    if (!changedRowNodes || newData || !rowDataUpdated) {
      return false;
    }
    if (changedRowNodes.removals.size || changedRowNodes.adds.size) {
      return false;
    }
    return true;
  }
  refreshModel(params) {
    const { nodeManager, beans, eventSvc, started, refreshingModel } = this;
    if (!nodeManager) {
      return;
    }
    const rowDataUpdated = !!params.rowDataUpdated;
    const changedPath = params.changedPath ?? (params.changedPath = this.createChangePath(!params.newData && rowDataUpdated));
    if (started && rowDataUpdated) {
      eventSvc.dispatchEvent({ type: "rowDataUpdated" });
    }
    if (!started || refreshingModel || beans.colModel.changeEventsDispatching || this.isSuppressModelUpdateAfterUpdateTransaction(params)) {
      this.rowDataUpdatedPending || (this.rowDataUpdatedPending = rowDataUpdated);
      return;
    }
    if (this.rowDataUpdatedPending) {
      this.rowDataUpdatedPending = false;
      params.step = "group";
    }
    this.refreshingModel = true;
    beans.masterDetailSvc?.refreshModel(params);
    if (rowDataUpdated && params.step !== "group") {
      beans.colFilter?.refreshModel();
    }
    switch (params.step) {
      case "group":
        this.doGrouping(params);
      case "filter":
        this.doFilter(changedPath);
      case "pivot":
        this.doPivot(changedPath);
      case "aggregate":
        this.doAggregate(changedPath);
      case "filter_aggregates":
        this.doFilterAggregates(changedPath);
      case "sort":
        this.doSort(params.changedRowNodes, changedPath);
      case "map":
        this.doRowsToDisplay();
    }
    const displayedNodesMapped = /* @__PURE__ */ new Set();
    this.setRowTopAndRowIndex(displayedNodesMapped);
    this.clearRowTopAndRowIndex(changedPath, displayedNodesMapped);
    this.refreshingModel = false;
    eventSvc.dispatchEvent({
      type: "modelUpdated",
      animate: params.animate,
      keepRenderedRows: params.keepRenderedRows,
      newData: params.newData,
      newPage: false,
      keepUndoRedoStack: params.keepUndoRedoStack
    });
  }
  isEmpty() {
    return !this.rootNode?._leafs?.length || !this.beans.colModel?.ready;
  }
  isRowsToRender() {
    return this.rowsToDisplay.length > 0;
  }
  getNodesInRangeForSelection(firstInRange, lastInRange) {
    let started = false;
    let finished = false;
    const result2 = [];
    const groupsSelectChildren = _getGroupSelectsDescendants(this.gos);
    this.forEachNodeAfterFilterAndSort((rowNode) => {
      if (finished) {
        return;
      }
      if (started) {
        if (rowNode === lastInRange || rowNode === firstInRange) {
          finished = true;
          if (groupsSelectChildren && rowNode.group) {
            addAllLeafs(result2, rowNode);
            return;
          }
        }
      }
      if (!started) {
        if (rowNode !== lastInRange && rowNode !== firstInRange) {
          return;
        }
        started = true;
        if (lastInRange === firstInRange) {
          finished = true;
        }
      }
      const includeThisNode = !rowNode.group || !groupsSelectChildren;
      if (includeThisNode) {
        result2.push(rowNode);
      }
    });
    return result2;
  }
  getTopLevelNodes() {
    return this.rootNode?.childrenAfterGroup ?? null;
  }
  getRow(index) {
    return this.rowsToDisplay[index];
  }
  isRowPresent(rowNode) {
    return this.rowsToDisplay.indexOf(rowNode) >= 0;
  }
  getRowIndexAtPixel(pixelToMatch) {
    const rowsToDisplay = this.rowsToDisplay;
    const rowsToDisplayLen = rowsToDisplay.length;
    if (this.isEmpty() || rowsToDisplayLen === 0) {
      return -1;
    }
    let bottomPointer = 0;
    let topPointer = rowsToDisplayLen - 1;
    if (pixelToMatch <= 0) {
      return 0;
    }
    const lastNode = rowsToDisplay[topPointer];
    if (lastNode.rowTop <= pixelToMatch) {
      return topPointer;
    }
    let oldBottomPointer = -1;
    let oldTopPointer = -1;
    while (true) {
      const midPointer = Math.floor((bottomPointer + topPointer) / 2);
      const currentRowNode = rowsToDisplay[midPointer];
      if (this.isRowInPixel(currentRowNode, pixelToMatch)) {
        return midPointer;
      }
      if (currentRowNode.rowTop < pixelToMatch) {
        bottomPointer = midPointer + 1;
      } else if (currentRowNode.rowTop > pixelToMatch) {
        topPointer = midPointer - 1;
      }
      const caughtInInfiniteLoop = oldBottomPointer === bottomPointer && oldTopPointer === topPointer;
      if (caughtInInfiniteLoop) {
        return midPointer;
      }
      oldBottomPointer = bottomPointer;
      oldTopPointer = topPointer;
    }
  }
  isRowInPixel(rowNode, pixelToMatch) {
    const topPixel = rowNode.rowTop;
    const bottomPixel = topPixel + rowNode.rowHeight;
    return topPixel <= pixelToMatch && bottomPixel > pixelToMatch;
  }
  forEachLeafNode(callback) {
    const allLeafs = this.rootNode?._leafs;
    if (allLeafs) {
      for (let i2 = 0, len = allLeafs.length; i2 < len; ++i2) {
        callback(allLeafs[i2], i2);
      }
    }
  }
  forEachNode(callback, includeFooterNodes = false) {
    this.depthFirstSearchRowNodes(callback, includeFooterNodes);
  }
  forEachDisplayedNode(callback) {
    const rowsToDisplay = this.rowsToDisplay;
    for (let i2 = 0, len = rowsToDisplay.length; i2 < len; ++i2) {
      callback(rowsToDisplay[i2], i2);
    }
  }
  forEachNodeAfterFilter(callback, includeFooterNodes = false) {
    this.depthFirstSearchRowNodes(callback, includeFooterNodes, (node2) => node2.childrenAfterAggFilter);
  }
  forEachNodeAfterFilterAndSort(callback, includeFooterNodes = false) {
    this.depthFirstSearchRowNodes(callback, includeFooterNodes, (node2) => node2.childrenAfterSort);
  }
  forEachPivotNode(callback, includeFooterNodes, afterSort) {
    const { colModel, rowGroupColsSvc } = this.beans;
    if (!colModel.isPivotMode()) {
      return;
    }
    if (!rowGroupColsSvc?.columns.length) {
      callback(this.rootNode, 0);
      return;
    }
    const childrenField = afterSort ? "childrenAfterSort" : "childrenAfterGroup";
    this.depthFirstSearchRowNodes(
      callback,
      includeFooterNodes,
      (node2) => !node2.leafGroup ? node2[childrenField] : null
    );
  }
  /**
   * Iterate through each node and all of its children
   * @param callback the function to execute for each node
   * @param includeFooterNodes whether to also iterate over footer nodes
   * @param nodes the nodes to start iterating over
   * @param getChildren a function to determine the recursion strategy
   * @param startIndex the index to start from
   * @returns the index ended at
   */
  depthFirstSearchRowNodes(callback, includeFooterNodes = false, getChildren = (node22) => node22.childrenAfterGroup, node2 = this.rootNode, startIndex = 0) {
    let index = startIndex;
    if (!node2) {
      return index;
    }
    const isRootNode = node2 === this.rootNode;
    if (!isRootNode) {
      callback(node2, index++);
    }
    if (node2.hasChildren() && !node2.footer) {
      const children2 = getChildren(node2);
      if (children2) {
        const footerSvc = this.beans.footerSvc;
        index = footerSvc?.addTotalRows(index, node2, callback, includeFooterNodes, isRootNode, "top") ?? index;
        for (const node22 of children2) {
          index = this.depthFirstSearchRowNodes(callback, includeFooterNodes, getChildren, node22, index);
        }
        return footerSvc?.addTotalRows(index, node2, callback, includeFooterNodes, isRootNode, "bottom") ?? index;
      }
    }
    return index;
  }
  // it's possible to recompute the aggregate without doing the other parts + api.refreshClientSideRowModel('aggregate')
  doAggregate(changedPath) {
    const rootNode = this.rootNode;
    if (rootNode) {
      this.beans.aggStage?.execute({ rowNode: rootNode, changedPath });
    }
  }
  doFilterAggregates(changedPath) {
    const rootNode = this.rootNode;
    const filterAggStage = this.beans.filterAggStage;
    if (filterAggStage) {
      filterAggStage.execute({ rowNode: rootNode, changedPath });
      return;
    }
    rootNode.childrenAfterAggFilter = rootNode.childrenAfterFilter;
  }
  doSort(changedRowNodes, changedPath) {
    const sortStage = this.beans.sortStage;
    if (sortStage) {
      sortStage.execute({
        rowNode: this.rootNode,
        changedRowNodes,
        changedPath
      });
      return;
    }
    changedPath.forEachChangedNodeDepthFirst((rowNode) => {
      rowNode.childrenAfterSort = rowNode.childrenAfterAggFilter.slice(0);
      updateRowNodeAfterSort(rowNode);
    });
  }
  doGrouping(params) {
    const rootNode = this.rootNode;
    const groupStage = this.beans.groupStage;
    const groupingChanged = groupStage?.execute({
      rowNode: rootNode,
      changedRowNodes: params.changedRowNodes,
      changedPath: params.changedPath,
      afterColumnsChanged: !!params.afterColumnsChanged
    });
    if (groupingChanged === void 0) {
      const allLeafs = rootNode._leafs;
      rootNode.childrenAfterGroup = allLeafs;
      rootNode.updateHasChildren();
      const sibling2 = rootNode.sibling;
      if (sibling2) {
        sibling2.childrenAfterGroup = allLeafs;
      }
    }
    if (groupingChanged || params.rowDataUpdated) {
      this.beans.colFilter?.refreshModel();
    }
    if (!this.rowCountReady && this.rowNodesCountReady) {
      this.rowCountReady = true;
      this.eventSvc.dispatchEventOnce({ type: "rowCountReady" });
    }
  }
  doFilter(changedPath) {
    const filterStage = this.beans.filterStage;
    if (filterStage) {
      filterStage.execute({ rowNode: this.rootNode, changedPath });
      return;
    }
    changedPath.forEachChangedNodeDepthFirst((rowNode) => {
      rowNode.childrenAfterFilter = rowNode.childrenAfterGroup;
      updateRowNodeAfterFilter(rowNode);
    }, true);
  }
  doPivot(changedPath) {
    this.beans.pivotStage?.execute({ rowNode: this.rootNode, changedPath });
  }
  getRowNode(id2) {
    const found = this.nodeManager?.getRowNode(id2);
    if (typeof found === "object") {
      return found;
    }
    const idIsGroup = typeof id2 == "string" && id2.indexOf(ROW_ID_PREFIX_ROW_GROUP) === 0;
    return idIsGroup ? this.beans.groupStage?.getNode(id2) : void 0;
  }
  batchUpdateRowData(rowDataTransaction, callback) {
    if (!this.asyncTransactionsTimer) {
      this.asyncTransactions = [];
      const waitMilliseconds = this.gos.get("asyncTransactionWaitMillis");
      this.asyncTransactionsTimer = setTimeout(() => this.executeBatchUpdateRowData(), waitMilliseconds);
    }
    this.asyncTransactions.push({ rowDataTransaction, callback });
  }
  flushAsyncTransactions() {
    const asyncTransactionsTimer = this.asyncTransactionsTimer;
    if (asyncTransactionsTimer) {
      clearTimeout(asyncTransactionsTimer);
      this.executeBatchUpdateRowData();
    }
  }
  executeBatchUpdateRowData() {
    const { nodeManager, beans, eventSvc, asyncTransactions } = this;
    if (!nodeManager) {
      return;
    }
    beans.valueCache?.onDataChanged();
    const rowNodeTrans = [];
    const callbackFuncsBound = [];
    const changedRowNodes = new ChangedRowNodes();
    for (const { rowDataTransaction, callback } of asyncTransactions ?? []) {
      this.rowNodesCountReady = true;
      const rowNodeTransaction = nodeManager.updateRowData(rowDataTransaction, changedRowNodes);
      rowNodeTrans.push(rowNodeTransaction);
      if (callback) {
        callbackFuncsBound.push(callback.bind(null, rowNodeTransaction));
      }
    }
    this.commitTransactions(changedRowNodes);
    if (callbackFuncsBound.length > 0) {
      setTimeout(() => {
        for (let i2 = 0, len = callbackFuncsBound.length; i2 < len; i2++) {
          callbackFuncsBound[i2]();
        }
      }, 0);
    }
    if (rowNodeTrans.length > 0) {
      eventSvc.dispatchEvent({ type: "asyncTransactionsFlushed", results: rowNodeTrans });
    }
    this.asyncTransactionsTimer = 0;
    this.asyncTransactions = null;
  }
  /**
   * Used to apply transaction changes.
   * Called by gridApi & rowDragFeature
   */
  updateRowData(rowDataTran) {
    const nodeManager = this.nodeManager;
    if (!nodeManager) {
      return null;
    }
    this.beans.valueCache?.onDataChanged();
    this.rowNodesCountReady = true;
    const changedRowNodes = new ChangedRowNodes();
    const rowNodeTransaction = nodeManager.updateRowData(rowDataTran, changedRowNodes);
    this.commitTransactions(changedRowNodes);
    return rowNodeTransaction;
  }
  /**
   * Common to:
   * - executeBatchUpdateRowData (batch transactions)
   * - updateRowData (single transaction)
   * - setImmutableRowData (generated transaction)
   *
   * @param rowNodeTrans - the transactions to apply
   * @param orderChanged - whether the order of the rows has changed, either via generated transaction or user provided addIndex
   */
  commitTransactions(changedRowNodes) {
    this.refreshModel({
      step: "group",
      rowDataUpdated: true,
      keepRenderedRows: true,
      animate: !this.gos.get("suppressAnimationFrame"),
      changedRowNodes,
      changedPath: this.createChangePath(true)
    });
  }
  doRowsToDisplay() {
    const { beans, rootNode } = this;
    const flattenStage = beans.flattenStage;
    if (flattenStage) {
      this.rowsToDisplay = flattenStage.execute({ rowNode: rootNode });
      return;
    }
    const rowsToDisplay = this.rootNode.childrenAfterSort ?? [];
    for (const row2 of rowsToDisplay) {
      row2.setUiLevel(0);
    }
    this.rowsToDisplay = rowsToDisplay;
  }
  onRowHeightChanged() {
    this.refreshModel({ step: "map", keepRenderedRows: true, keepUndoRedoStack: true });
  }
  resetRowHeights() {
    const rootNode = this.rootNode;
    if (!rootNode) {
      return;
    }
    const atLeastOne = this.resetRowHeightsForAllRowNodes();
    rootNode.setRowHeight(rootNode.rowHeight, true);
    const sibling2 = rootNode.sibling;
    sibling2?.setRowHeight(sibling2.rowHeight, true);
    if (atLeastOne) {
      this.onRowHeightChanged();
    }
  }
  resetRowHeightsForAllRowNodes() {
    let atLeastOne = false;
    this.forEachNode((rowNode) => {
      rowNode.setRowHeight(rowNode.rowHeight, true);
      const detailNode = rowNode.detailNode;
      detailNode?.setRowHeight(detailNode.rowHeight, true);
      const sibling2 = rowNode.sibling;
      sibling2?.setRowHeight(sibling2.rowHeight, true);
      atLeastOne = true;
    });
    return atLeastOne;
  }
  onGridStylesChanges(e) {
    if (e.rowHeightChanged && !this.beans.rowAutoHeight?.active) {
      this.resetRowHeights();
    }
  }
  onGridReady() {
    if (!this.started) {
      this.setInitialData();
    }
  }
  destroy() {
    super.destroy();
    this.nodeManager = this.destroyBean(this.nodeManager);
    this.started = false;
    this.rootNode = null;
    this.rowsToDisplay = [];
    this.asyncTransactions = null;
    clearTimeout(this.asyncTransactionsTimer);
  }
  /**
   * @deprecated v33.1
   */
  onRowHeightChangedDebounced() {
    this.onRowHeightChanged_debounced();
  }
};
var addAllLeafs = (result2, node2) => {
  const childrenAfterGroup = node2.childrenAfterGroup;
  if (childrenAfterGroup) {
    for (let i2 = 0, len = childrenAfterGroup.length; i2 < len; ++i2) {
      const child = childrenAfterGroup[i2];
      if (child.data) {
        result2.push(child);
      }
      if (child.group) {
        addAllLeafs(result2, child);
      }
    }
  }
};
function onGroupExpandedOrCollapsed(beans) {
  beans.expansionSvc?.onGroupExpandedOrCollapsed();
}
function refreshClientSideRowModel(beans, step) {
  const clientSideRowModel = _getClientSideRowModel(beans);
  if (clientSideRowModel) {
    if (!step || step === "everything") {
      step = "group";
    }
    clientSideRowModel.refreshModel({
      step,
      keepRenderedRows: true,
      animate: !beans.gos.get("suppressAnimationFrame")
    });
  }
}
function isRowDataEmpty(beans) {
  return _getClientSideRowModel(beans)?.isEmpty() ?? true;
}
function forEachLeafNode(beans, callback) {
  _getClientSideRowModel(beans)?.forEachLeafNode(callback);
}
function forEachNodeAfterFilter(beans, callback) {
  _getClientSideRowModel(beans)?.forEachNodeAfterFilter(callback);
}
function forEachNodeAfterFilterAndSort(beans, callback) {
  _getClientSideRowModel(beans)?.forEachNodeAfterFilterAndSort(callback);
}
function applyTransaction(beans, rowDataTransaction) {
  return beans.frameworkOverrides.wrapIncoming(
    () => _getClientSideRowModel(beans)?.updateRowData(rowDataTransaction)
  );
}
function applyTransactionAsync(beans, rowDataTransaction, callback) {
  beans.frameworkOverrides.wrapIncoming(
    () => _getClientSideRowModel(beans)?.batchUpdateRowData(rowDataTransaction, callback)
  );
}
function flushAsyncTransactions(beans) {
  beans.frameworkOverrides.wrapIncoming(() => _getClientSideRowModel(beans)?.flushAsyncTransactions());
}
function getBestCostNodeSelection(beans) {
  return beans.selectionSvc?.getBestCostNodeSelection();
}
var ClientSideRowModelModule = {
  moduleName: "ClientSideRowModel",
  version: VERSION,
  rowModels: ["clientSide"],
  beans: [ClientSideRowModel, SortStage],
  dependsOn: [SortModule]
};
var ClientSideRowModelApiModule = {
  moduleName: "ClientSideRowModelApi",
  version: VERSION,
  apiFunctions: {
    onGroupExpandedOrCollapsed,
    refreshClientSideRowModel,
    isRowDataEmpty,
    forEachLeafNode,
    forEachNodeAfterFilter,
    forEachNodeAfterFilterAndSort,
    applyTransaction,
    applyTransactionAsync,
    flushAsyncTransactions,
    getBestCostNodeSelection,
    resetRowHeights,
    onRowHeightChanged
  },
  dependsOn: [CsrmSsrmSharedApiModule, RowModelSharedApiModule]
};
var GridSerializer = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "gridSerializer";
  }
  wireBeans(beans) {
    this.visibleCols = beans.visibleCols;
    this.colModel = beans.colModel;
    this.rowModel = beans.rowModel;
    this.pinnedRowModel = beans.pinnedRowModel;
  }
  serialize(gridSerializingSession, params = {}) {
    const { allColumns, columnKeys, skipRowGroups, exportRowNumbers } = params;
    const columnsToExport = this.getColumnsToExport({
      allColumns,
      skipRowGroups,
      columnKeys,
      exportRowNumbers
    });
    return [
      // first pass, put in the header names of the cols
      this.prepareSession(columnsToExport),
      this.prependContent(params),
      this.exportColumnGroups(params, columnsToExport),
      this.exportHeaders(params, columnsToExport),
      this.processPinnedTopRows(params, columnsToExport),
      this.processRows(params, columnsToExport),
      this.processPinnedBottomRows(params, columnsToExport),
      this.appendContent(params)
    ].reduce((composed, f) => f(composed), gridSerializingSession).parse();
  }
  processRow(gridSerializingSession, params, columnsToExport, node2) {
    const rowSkipper = params.shouldRowBeSkipped || (() => false);
    const isClipboardExport = params.rowPositions != null;
    const isExplicitExportSelection = isClipboardExport || !!params.onlySelected;
    const hideOpenParents = this.gos.get("groupHideOpenParents") && !isExplicitExportSelection;
    const isLeafNode = this.colModel.isPivotMode() ? node2.leafGroup : !node2.group;
    const isFooter = !!node2.footer;
    const shouldSkipCurrentGroup = node2.allChildrenCount === 1 && node2.childrenAfterGroup?.length === 1 && _canSkipShowingRowGroup(this.gos, node2);
    if (!isLeafNode && !isFooter && (params.skipRowGroups || shouldSkipCurrentGroup || hideOpenParents) || params.onlySelected && !node2.isSelected() || params.skipPinnedTop && node2.rowPinned === "top" || params.skipPinnedBottom && node2.rowPinned === "bottom" || node2.stub) {
      return;
    }
    const nodeIsRootNode = node2.level === -1;
    if (nodeIsRootNode && !isLeafNode && !isFooter) {
      return;
    }
    const shouldRowBeSkipped = rowSkipper(_addGridCommonParams(this.gos, { node: node2 }));
    if (shouldRowBeSkipped) {
      return;
    }
    const rowAccumulator = gridSerializingSession.onNewBodyRow(node2);
    columnsToExport.forEach((column2, index) => {
      rowAccumulator.onColumn(column2, index, node2);
    });
    if (params.getCustomContentBelowRow) {
      const content2 = params.getCustomContentBelowRow(_addGridCommonParams(this.gos, { node: node2 }));
      if (content2) {
        gridSerializingSession.addCustomContent(content2);
      }
    }
  }
  appendContent(params) {
    return (gridSerializingSession) => {
      const appendContent = params.appendContent;
      if (appendContent) {
        gridSerializingSession.addCustomContent(appendContent);
      }
      return gridSerializingSession;
    };
  }
  prependContent(params) {
    return (gridSerializingSession) => {
      const prependContent = params.prependContent;
      if (prependContent) {
        gridSerializingSession.addCustomContent(prependContent);
      }
      return gridSerializingSession;
    };
  }
  prepareSession(columnsToExport) {
    return (gridSerializingSession) => {
      gridSerializingSession.prepare(columnsToExport);
      return gridSerializingSession;
    };
  }
  exportColumnGroups(params, columnsToExport) {
    return (gridSerializingSession) => {
      if (!params.skipColumnGroupHeaders) {
        const idCreator = new GroupInstanceIdCreator();
        const { colGroupSvc } = this.beans;
        const displayedGroups = colGroupSvc ? colGroupSvc.createColumnGroups({
          columns: columnsToExport,
          idCreator,
          pinned: null,
          isStandaloneStructure: true
        }) : columnsToExport;
        this.recursivelyAddHeaderGroups(
          displayedGroups,
          gridSerializingSession,
          params.processGroupHeaderCallback
        );
      }
      return gridSerializingSession;
    };
  }
  exportHeaders(params, columnsToExport) {
    return (gridSerializingSession) => {
      if (!params.skipColumnHeaders) {
        const gridRowIterator = gridSerializingSession.onNewHeaderRow();
        columnsToExport.forEach((column2, index) => {
          gridRowIterator.onColumn(column2, index, void 0);
        });
      }
      return gridSerializingSession;
    };
  }
  processPinnedTopRows(params, columnsToExport) {
    return (gridSerializingSession) => {
      const processRow = this.processRow.bind(this, gridSerializingSession, params, columnsToExport);
      if (params.rowPositions) {
        params.rowPositions.filter((position) => position.rowPinned === "top").sort((a2, b) => a2.rowIndex - b.rowIndex).map((position) => this.pinnedRowModel?.getPinnedTopRow(position.rowIndex)).forEach(processRow);
      } else if (!this.pinnedRowModel?.isManual()) {
        this.pinnedRowModel?.forEachPinnedRow("top", processRow);
      }
      return gridSerializingSession;
    };
  }
  processRows(params, columnsToExport) {
    return (gridSerializingSession) => {
      const rowModel = this.rowModel;
      const usingCsrm = _isClientSideRowModel(this.gos);
      const usingSsrm = _isServerSideRowModel(this.gos);
      const onlySelectedNonStandardModel = !usingCsrm && params.onlySelected;
      const processRow = this.processRow.bind(this, gridSerializingSession, params, columnsToExport);
      const { exportedRows = "filteredAndSorted" } = params;
      if (params.rowPositions) {
        params.rowPositions.filter((position) => position.rowPinned == null).sort((a2, b) => a2.rowIndex - b.rowIndex).map((position) => rowModel.getRow(position.rowIndex)).forEach(processRow);
      } else if (this.colModel.isPivotMode()) {
        if (usingCsrm) {
          rowModel.forEachPivotNode(processRow, true, exportedRows === "filteredAndSorted");
        } else if (usingSsrm) {
          rowModel.forEachNodeAfterFilterAndSort(processRow, true);
        } else {
          rowModel.forEachNode(processRow);
        }
      } else if (params.onlySelectedAllPages || onlySelectedNonStandardModel) {
        const selectedNodes = this.beans.selectionSvc?.getSelectedNodes() ?? [];
        this.replicateSortedOrder(selectedNodes);
        selectedNodes.forEach(processRow);
      } else if (exportedRows === "all") {
        rowModel.forEachNode(processRow);
      } else if (usingCsrm || usingSsrm) {
        rowModel.forEachNodeAfterFilterAndSort(processRow, true);
      } else {
        rowModel.forEachNode(processRow);
      }
      return gridSerializingSession;
    };
  }
  replicateSortedOrder(rows) {
    const { sortSvc, rowNodeSorter } = this.beans;
    if (!sortSvc || !rowNodeSorter) {
      return;
    }
    const sortOptions = sortSvc.getSortOptions();
    const compareNodes = (rowA, rowB) => {
      if (rowA.rowIndex != null && rowB.rowIndex != null) {
        return rowA.rowIndex - rowB.rowIndex;
      }
      if (rowA.level === rowB.level) {
        if (rowA.parent?.id === rowB.parent?.id) {
          return rowNodeSorter.compareRowNodes(
            sortOptions,
            {
              rowNode: rowA,
              currentPos: rowA.rowIndex ?? -1
            },
            {
              rowNode: rowB,
              currentPos: rowB.rowIndex ?? -1
            }
          );
        }
        return compareNodes(rowA.parent, rowB.parent);
      }
      if (rowA.level > rowB.level) {
        return compareNodes(rowA.parent, rowB);
      }
      return compareNodes(rowA, rowB.parent);
    };
    rows.sort(compareNodes);
  }
  processPinnedBottomRows(params, columnsToExport) {
    return (gridSerializingSession) => {
      const processRow = this.processRow.bind(this, gridSerializingSession, params, columnsToExport);
      if (params.rowPositions) {
        params.rowPositions.filter((position) => position.rowPinned === "bottom").sort((a2, b) => a2.rowIndex - b.rowIndex).map((position) => this.pinnedRowModel?.getPinnedBottomRow(position.rowIndex)).forEach(processRow);
      } else if (!this.pinnedRowModel?.isManual()) {
        this.pinnedRowModel?.forEachPinnedRow("bottom", processRow);
      }
      return gridSerializingSession;
    };
  }
  getColumnsToExport(params) {
    const { allColumns = false, skipRowGroups = false, exportRowNumbers = false, columnKeys } = params;
    const { colModel, gos, visibleCols } = this;
    const isPivotMode = colModel.isPivotMode();
    const filterSpecialColumns = (col) => {
      if (isColumnSelectionCol(col)) {
        return false;
      }
      return !isRowNumberCol(col) || exportRowNumbers;
    };
    if (columnKeys?.length) {
      return colModel.getColsForKeys(columnKeys).filter(filterSpecialColumns);
    }
    const isTreeData = gos.get("treeData");
    let columnsToExport = [];
    if (allColumns && !isPivotMode) {
      columnsToExport = colModel.getCols();
    } else {
      columnsToExport = visibleCols.allCols;
    }
    columnsToExport = columnsToExport.filter(
      (column2) => filterSpecialColumns(column2) && (skipRowGroups && !isTreeData ? !isColumnGroupAutoCol(column2) : true)
    );
    return columnsToExport;
  }
  recursivelyAddHeaderGroups(displayedGroups, gridSerializingSession, processGroupHeaderCallback) {
    const directChildrenHeaderGroups = [];
    for (const columnGroupChild of displayedGroups) {
      const columnGroup = columnGroupChild;
      if (!columnGroup.getChildren) {
        continue;
      }
      for (const it of columnGroup.getChildren() ?? []) {
        directChildrenHeaderGroups.push(it);
      }
    }
    if (displayedGroups.length > 0 && isColumnGroup(displayedGroups[0])) {
      this.doAddHeaderHeader(gridSerializingSession, displayedGroups, processGroupHeaderCallback);
    }
    if (directChildrenHeaderGroups && directChildrenHeaderGroups.length > 0) {
      this.recursivelyAddHeaderGroups(
        directChildrenHeaderGroups,
        gridSerializingSession,
        processGroupHeaderCallback
      );
    }
  }
  doAddHeaderHeader(gridSerializingSession, displayedGroups, processGroupHeaderCallback) {
    const gridRowIterator = gridSerializingSession.onNewHeaderGroupingRow();
    let columnIndex = 0;
    for (const columnGroupChild of displayedGroups) {
      const columnGroup = columnGroupChild;
      let name2;
      if (processGroupHeaderCallback) {
        name2 = processGroupHeaderCallback(
          _addGridCommonParams(this.gos, {
            columnGroup
          })
        );
      } else {
        name2 = this.beans.colNames.getDisplayNameForColumnGroup(columnGroup, "header");
      }
      const columnsToCalculateRange = columnGroup.isExpandable() ? columnGroup.getLeafColumns() : [];
      const collapsibleGroupRanges = columnsToCalculateRange.reduce(
        (collapsibleGroups, currentColumn, currentIdx, arr) => {
          let lastGroup = _last(collapsibleGroups);
          const groupShow = currentColumn.getColumnGroupShow() === "open";
          if (!groupShow) {
            if (lastGroup && lastGroup[1] == null) {
              lastGroup[1] = currentIdx - 1;
            }
          } else if (!lastGroup || lastGroup[1] != null) {
            lastGroup = [currentIdx];
            collapsibleGroups.push(lastGroup);
          }
          if (currentIdx === arr.length - 1 && lastGroup && lastGroup[1] == null) {
            lastGroup[1] = currentIdx;
          }
          return collapsibleGroups;
        },
        []
      );
      gridRowIterator.onColumn(
        columnGroup,
        name2 || "",
        columnIndex++,
        columnGroup.getLeafColumns().length - 1,
        collapsibleGroupRanges
      );
    }
  }
};
var SharedExportModule = {
  moduleName: "SharedExport",
  version: VERSION,
  beans: [GridSerializer]
};
var LINE_SEPARATOR = "\r\n";
var CsvSerializingSession = class extends BaseGridSerializingSession {
  constructor(config2) {
    super(config2);
    this.config = config2;
    this.isFirstLine = true;
    this.result = "";
    const { suppressQuotes, columnSeparator } = config2;
    this.suppressQuotes = suppressQuotes;
    this.columnSeparator = columnSeparator;
  }
  addCustomContent(content2) {
    if (!content2) {
      return;
    }
    if (typeof content2 === "string") {
      if (!/^\s*\n/.test(content2)) {
        this.beginNewLine();
      }
      content2 = content2.replace(/\r?\n/g, LINE_SEPARATOR);
      this.result += content2;
    } else {
      content2.forEach((row2) => {
        this.beginNewLine();
        row2.forEach((cell2, index) => {
          if (index !== 0) {
            this.result += this.columnSeparator;
          }
          this.result += this.putInQuotes(cell2.data.value || "");
          if (cell2.mergeAcross) {
            this.appendEmptyCells(cell2.mergeAcross);
          }
        });
      });
    }
  }
  onNewHeaderGroupingRow() {
    this.beginNewLine();
    return {
      onColumn: this.onNewHeaderGroupingRowColumn.bind(this)
    };
  }
  onNewHeaderGroupingRowColumn(columnGroup, header2, index, span) {
    if (index != 0) {
      this.result += this.columnSeparator;
    }
    this.result += this.putInQuotes(header2);
    this.appendEmptyCells(span);
  }
  appendEmptyCells(count2) {
    for (let i2 = 1; i2 <= count2; i2++) {
      this.result += this.columnSeparator + this.putInQuotes("");
    }
  }
  onNewHeaderRow() {
    this.beginNewLine();
    return {
      onColumn: this.onNewHeaderRowColumn.bind(this)
    };
  }
  onNewHeaderRowColumn(column2, index) {
    if (index != 0) {
      this.result += this.columnSeparator;
    }
    this.result += this.putInQuotes(this.extractHeaderValue(column2));
  }
  onNewBodyRow() {
    this.beginNewLine();
    return {
      onColumn: this.onNewBodyRowColumn.bind(this)
    };
  }
  onNewBodyRowColumn(column2, index, node2) {
    if (index != 0) {
      this.result += this.columnSeparator;
    }
    const rowCellValue = this.extractRowCellValue(column2, index, index, "csv", node2);
    this.result += this.putInQuotes(rowCellValue.valueFormatted ?? rowCellValue.value);
  }
  putInQuotes(value2) {
    if (this.suppressQuotes) {
      return value2;
    }
    if (value2 === null || value2 === void 0) {
      return '""';
    }
    let stringValue;
    if (typeof value2 === "string") {
      stringValue = value2;
    } else if (typeof value2.toString === "function") {
      stringValue = value2.toString();
    } else {
      _warn(53);
      stringValue = "";
    }
    const valueEscaped = stringValue.replace(/"/g, '""');
    return '"' + valueEscaped + '"';
  }
  parse() {
    return this.result;
  }
  beginNewLine() {
    if (!this.isFirstLine) {
      this.result += LINE_SEPARATOR;
    }
    this.isFirstLine = false;
  }
};
var CsvCreator = class extends BaseCreator {
  constructor() {
    super(...arguments);
    this.beanName = "csvCreator";
  }
  wireBeans(beans) {
    this.colModel = beans.colModel;
    this.colNames = beans.colNames;
    this.rowGroupColsSvc = beans.rowGroupColsSvc;
    this.valueSvc = beans.valueSvc;
  }
  getMergedParams(params) {
    const baseParams5 = this.gos.get("defaultCsvExportParams");
    return Object.assign({}, baseParams5, params);
  }
  export(userParams) {
    if (this.isExportSuppressed()) {
      _warn(51);
      return;
    }
    const mergedParams = this.getMergedParams(userParams);
    const data2 = this.getData(mergedParams);
    const packagedFile = new Blob(["\uFEFF", data2], { type: "text/plain" });
    const fileName = typeof mergedParams.fileName === "function" ? mergedParams.fileName(_addGridCommonParams(this.gos, {})) : mergedParams.fileName;
    _downloadFile(this.getFileName(fileName), packagedFile);
  }
  exportDataAsCsv(params) {
    this.export(params);
  }
  getDataAsCsv(params, skipDefaultParams = false) {
    const mergedParams = skipDefaultParams ? Object.assign({}, params) : this.getMergedParams(params);
    return this.getData(mergedParams);
  }
  getDefaultFileExtension() {
    return "csv";
  }
  createSerializingSession(params) {
    const { colModel, colNames, rowGroupColsSvc, valueSvc, gos } = this;
    const {
      processCellCallback,
      processHeaderCallback,
      processGroupHeaderCallback,
      processRowGroupCallback,
      suppressQuotes,
      columnSeparator
    } = params;
    return new CsvSerializingSession({
      colModel,
      colNames,
      valueSvc,
      gos,
      processCellCallback: processCellCallback || void 0,
      processHeaderCallback: processHeaderCallback || void 0,
      processGroupHeaderCallback: processGroupHeaderCallback || void 0,
      processRowGroupCallback: processRowGroupCallback || void 0,
      suppressQuotes: suppressQuotes || false,
      columnSeparator: columnSeparator || ",",
      rowGroupColsSvc
    });
  }
  isExportSuppressed() {
    return this.gos.get("suppressCsvExport");
  }
};
function getDataAsCsv(beans, params) {
  return beans.csvCreator?.getDataAsCsv(params);
}
function exportDataAsCsv(beans, params) {
  beans.csvCreator?.exportDataAsCsv(params);
}
var CsvExportModule = {
  moduleName: "CsvExport",
  version: VERSION,
  beans: [CsvCreator],
  apiFunctions: {
    getDataAsCsv,
    exportDataAsCsv
  },
  dependsOn: [SharedExportModule]
};
var InfiniteBlock = class extends BeanStub {
  constructor(id2, parentCache, params) {
    super();
    this.id = id2;
    this.parentCache = parentCache;
    this.params = params;
    this.state = "needsLoading";
    this.version = 0;
    this.startRow = id2 * params.blockSize;
    this.endRow = this.startRow + params.blockSize;
  }
  load() {
    this.state = "loading";
    this.loadFromDatasource();
  }
  setStateWaitingToLoad() {
    this.version++;
    this.state = "needsLoading";
  }
  pageLoadFailed(version2) {
    const requestMostRecentAndLive = this.isRequestMostRecentAndLive(version2);
    if (requestMostRecentAndLive) {
      this.state = "failed";
    }
    this.dispatchLocalEvent({ type: "loadComplete" });
  }
  pageLoaded(version2, rows, lastRow) {
    this.successCommon(version2, { rowData: rows, rowCount: lastRow });
  }
  isRequestMostRecentAndLive(version2) {
    const thisIsMostRecentRequest = version2 === this.version;
    const weAreNotDestroyed = this.isAlive();
    return thisIsMostRecentRequest && weAreNotDestroyed;
  }
  successCommon(version2, params) {
    this.dispatchLocalEvent({ type: "loadComplete" });
    const requestMostRecentAndLive = this.isRequestMostRecentAndLive(version2);
    if (requestMostRecentAndLive) {
      this.state = "loaded";
      this.processServerResult(params);
    }
  }
  postConstruct() {
    this.rowNodes = [];
    const {
      params: { blockSize, rowHeight },
      startRow,
      beans,
      rowNodes
    } = this;
    for (let i2 = 0; i2 < blockSize; i2++) {
      const rowIndex = startRow + i2;
      const rowNode = new RowNode(beans);
      rowNode.setRowHeight(rowHeight);
      rowNode.uiLevel = 0;
      rowNode.setRowIndex(rowIndex);
      rowNode.setRowTop(rowHeight * rowIndex);
      rowNodes.push(rowNode);
    }
  }
  getBlockStateJson() {
    const { id: id2, startRow, endRow, state: pageStatus } = this;
    return {
      id: "" + id2,
      state: {
        blockNumber: id2,
        startRow,
        endRow,
        pageStatus
      }
    };
  }
  setDataAndId(rowNode, data2, index) {
    if (_exists(data2)) {
      rowNode.setDataAndId(data2, index.toString());
    } else {
      rowNode.setDataAndId(void 0, void 0);
    }
  }
  loadFromDatasource() {
    const params = this.createLoadParams();
    if (_missing(this.params.datasource.getRows)) {
      _warn(90);
      return;
    }
    window.setTimeout(() => {
      this.params.datasource.getRows(params);
    }, 0);
  }
  createLoadParams() {
    const {
      startRow,
      endRow,
      version: version2,
      params: { sortModel, filterModel },
      gos
    } = this;
    const params = {
      startRow,
      endRow,
      successCallback: this.pageLoaded.bind(this, version2),
      failCallback: this.pageLoadFailed.bind(this, version2),
      sortModel,
      filterModel,
      context: _addGridCommonParams(gos, {}).context
    };
    return params;
  }
  forEachNode(callback, sequence2, rowCount) {
    this.rowNodes.forEach((rowNode, index) => {
      const rowIndex = this.startRow + index;
      if (rowIndex < rowCount) {
        callback(rowNode, sequence2.value++);
      }
    });
  }
  getRow(rowIndex, dontTouchLastAccessed = false) {
    if (!dontTouchLastAccessed) {
      this.lastAccessed = this.params.lastAccessedSequence.value++;
    }
    const localIndex = rowIndex - this.startRow;
    return this.rowNodes[localIndex];
  }
  processServerResult(params) {
    const { rowNodes, beans } = this;
    rowNodes.forEach((rowNode, index) => {
      const data2 = params.rowData ? params.rowData[index] : void 0;
      if (!rowNode.id && rowNode.alreadyRendered && data2) {
        rowNodes[index] = new RowNode(beans);
        rowNodes[index].setRowIndex(rowNode.rowIndex);
        rowNodes[index].setRowTop(rowNode.rowTop);
        rowNodes[index].setRowHeight(rowNode.rowHeight);
        rowNode.clearRowTopAndRowIndex();
      }
      this.setDataAndId(rowNodes[index], data2, this.startRow + index);
    });
    const finalRowCount = params.rowCount != null && params.rowCount >= 0 ? params.rowCount : void 0;
    this.parentCache.pageLoaded(this, finalRowCount);
  }
  destroy() {
    for (const rowNode of this.rowNodes) {
      rowNode.clearRowTopAndRowIndex();
    }
    super.destroy();
  }
};
var MAX_EMPTY_BLOCKS_TO_KEEP = 2;
var InfiniteCache = class extends BeanStub {
  constructor(params) {
    super();
    this.params = params;
    this.lastRowIndexKnown = false;
    this.blocks = {};
    this.blockCount = 0;
    this.rowCount = params.initialRowCount;
  }
  // the rowRenderer will not pass dontCreatePage, meaning when rendering the grid,
  // it will want new pages in the cache as it asks for rows. only when we are inserting /
  // removing rows via the api is dontCreatePage set, where we move rows between the pages.
  getRow(rowIndex, dontCreatePage = false) {
    const blockId = Math.floor(rowIndex / this.params.blockSize);
    let block2 = this.blocks[blockId];
    if (!block2) {
      if (dontCreatePage) {
        return void 0;
      }
      block2 = this.createBlock(blockId);
    }
    return block2.getRow(rowIndex);
  }
  createBlock(blockNumber) {
    const params = this.params;
    const newBlock = this.createBean(new InfiniteBlock(blockNumber, this, params));
    this.blocks[newBlock.id] = newBlock;
    this.blockCount++;
    this.purgeBlocksIfNeeded(newBlock);
    params.rowNodeBlockLoader.addBlock(newBlock);
    return newBlock;
  }
  // we have this on infinite row model only, not server side row model,
  // because for server side, it would leave the children in inconsistent
  // state - eg if a node had children, but after the refresh it had data
  // for a different row, then the children would be with the wrong row node.
  refreshCache() {
    const nothingToRefresh = this.blockCount == 0;
    if (nothingToRefresh) {
      this.purgeCache();
      return;
    }
    for (const block2 of this.getBlocksInOrder()) {
      block2.setStateWaitingToLoad();
    }
    this.params.rowNodeBlockLoader.checkBlockToLoad();
  }
  destroy() {
    for (const block2 of this.getBlocksInOrder()) {
      this.destroyBlock(block2);
    }
    super.destroy();
  }
  getRowCount() {
    return this.rowCount;
  }
  isLastRowIndexKnown() {
    return this.lastRowIndexKnown;
  }
  // block calls this, when page loaded
  pageLoaded(block2, lastRow) {
    if (!this.isAlive()) {
      return;
    }
    _logIfDebug(this.gos, `InfiniteCache - onPageLoaded: page = ${block2.id}, lastRow = ${lastRow}`);
    this.checkRowCount(block2, lastRow);
    this.onCacheUpdated();
  }
  purgeBlocksIfNeeded(blockToExclude) {
    const blocksForPurging = this.getBlocksInOrder().filter((b) => b != blockToExclude);
    const lastAccessedComparator = (a2, b) => b.lastAccessed - a2.lastAccessed;
    blocksForPurging.sort(lastAccessedComparator);
    const maxBlocksProvided = this.params.maxBlocksInCache > 0;
    const blocksToKeep = maxBlocksProvided ? this.params.maxBlocksInCache - 1 : null;
    const emptyBlocksToKeep = MAX_EMPTY_BLOCKS_TO_KEEP - 1;
    blocksForPurging.forEach((block2, index) => {
      const purgeBecauseBlockEmpty = block2.state === "needsLoading" && index >= emptyBlocksToKeep;
      const purgeBecauseCacheFull = maxBlocksProvided ? index >= blocksToKeep : false;
      if (purgeBecauseBlockEmpty || purgeBecauseCacheFull) {
        if (this.isBlockCurrentlyDisplayed(block2)) {
          return;
        }
        if (this.isBlockFocused(block2)) {
          return;
        }
        this.removeBlockFromCache(block2);
      }
    });
  }
  isBlockFocused(block2) {
    const focusedCell = this.beans.focusSvc.getFocusCellToUseAfterRefresh();
    if (!focusedCell) {
      return false;
    }
    if (focusedCell.rowPinned != null) {
      return false;
    }
    const { startRow, endRow } = block2;
    const hasFocus = focusedCell.rowIndex >= startRow && focusedCell.rowIndex < endRow;
    return hasFocus;
  }
  isBlockCurrentlyDisplayed(block2) {
    const { startRow, endRow } = block2;
    return this.beans.rowRenderer.isRangeInRenderedViewport(startRow, endRow - 1);
  }
  removeBlockFromCache(blockToRemove) {
    if (!blockToRemove) {
      return;
    }
    this.destroyBlock(blockToRemove);
  }
  checkRowCount(block2, lastRow) {
    if (typeof lastRow === "number" && lastRow >= 0) {
      this.rowCount = lastRow;
      this.lastRowIndexKnown = true;
    } else if (!this.lastRowIndexKnown) {
      const { blockSize, overflowSize } = this.params;
      const lastRowIndex = (block2.id + 1) * blockSize;
      const lastRowIndexPlusOverflow = lastRowIndex + overflowSize;
      if (this.rowCount < lastRowIndexPlusOverflow) {
        this.rowCount = lastRowIndexPlusOverflow;
      }
    }
  }
  setRowCount(rowCount, lastRowIndexKnown) {
    this.rowCount = rowCount;
    if (_exists(lastRowIndexKnown)) {
      this.lastRowIndexKnown = lastRowIndexKnown;
    }
    if (!this.lastRowIndexKnown) {
      if (this.rowCount % this.params.blockSize === 0) {
        this.rowCount++;
      }
    }
    this.onCacheUpdated();
  }
  forEachNodeDeep(callback) {
    const sequence2 = { value: 0 };
    for (const block2 of this.getBlocksInOrder()) {
      block2.forEachNode(callback, sequence2, this.rowCount);
    }
  }
  getBlocksInOrder() {
    const blockComparator = (a2, b) => a2.id - b.id;
    const blocks = Object.values(this.blocks).sort(blockComparator);
    return blocks;
  }
  destroyBlock(block2) {
    delete this.blocks[block2.id];
    this.destroyBean(block2);
    this.blockCount--;
    this.params.rowNodeBlockLoader.removeBlock(block2);
  }
  // gets called 1) row count changed 2) cache purged 3) items inserted
  onCacheUpdated() {
    if (this.isAlive()) {
      this.destroyAllBlocksPastVirtualRowCount();
      this.eventSvc.dispatchEvent({
        type: "storeUpdated"
      });
    }
  }
  destroyAllBlocksPastVirtualRowCount() {
    const blocksToDestroy = [];
    for (const block2 of this.getBlocksInOrder()) {
      const startRow = block2.id * this.params.blockSize;
      if (startRow >= this.rowCount) {
        blocksToDestroy.push(block2);
      }
    }
    if (blocksToDestroy.length > 0) {
      for (const block2 of blocksToDestroy) {
        this.destroyBlock(block2);
      }
    }
  }
  purgeCache() {
    for (const block2 of this.getBlocksInOrder()) {
      this.removeBlockFromCache(block2);
    }
    this.lastRowIndexKnown = false;
    if (this.rowCount === 0) {
      this.rowCount = this.params.initialRowCount;
    }
    this.onCacheUpdated();
  }
  getRowNodesInRange(firstInRange, lastInRange) {
    const result2 = [];
    let lastBlockId = -1;
    let inActiveRange = false;
    const numberSequence = { value: 0 };
    let foundGapInSelection = false;
    for (const block2 of this.getBlocksInOrder()) {
      if (foundGapInSelection) {
        continue;
      }
      if (inActiveRange && lastBlockId + 1 !== block2.id) {
        foundGapInSelection = true;
        continue;
      }
      lastBlockId = block2.id;
      block2.forEachNode(
        (rowNode) => {
          const hitFirstOrLast = rowNode === firstInRange || rowNode === lastInRange;
          if (inActiveRange || hitFirstOrLast) {
            result2.push(rowNode);
          }
          if (hitFirstOrLast) {
            inActiveRange = !inActiveRange;
          }
        },
        numberSequence,
        this.rowCount
      );
    }
    const invalidRange = foundGapInSelection || inActiveRange;
    return invalidRange ? [] : result2;
  }
};
var InfiniteRowModel = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "rowModel";
    this.rootNode = null;
  }
  getRowBounds(index) {
    return {
      rowHeight: this.rowHeight,
      rowTop: this.rowHeight * index
    };
  }
  // we don't implement as lazy row heights is not supported in this row model
  ensureRowHeightsValid() {
    return false;
  }
  postConstruct() {
    if (this.gos.get("rowModelType") !== "infinite") {
      return;
    }
    const beans = this.beans;
    const rootNode = new RowNode(beans);
    this.rootNode = rootNode;
    rootNode.level = -1;
    this.rowHeight = _getRowHeightAsNumber(beans);
    this.addEventListeners();
    this.addDestroyFunc(() => this.destroyCache());
  }
  start() {
    this.setDatasource(this.gos.get("datasource"));
  }
  destroy() {
    this.destroyDatasource();
    super.destroy();
    this.rootNode = null;
  }
  destroyDatasource() {
    if (this.datasource) {
      this.destroyBean(this.datasource);
      this.beans.rowRenderer.datasourceChanged();
      this.datasource = null;
    }
  }
  addEventListeners() {
    this.addManagedEventListeners({
      filterChanged: this.reset.bind(this),
      sortChanged: this.reset.bind(this),
      newColumnsLoaded: this.onColumnEverything.bind(this),
      storeUpdated: this.dispatchModelUpdatedEvent.bind(this)
    });
    this.addManagedPropertyListener("datasource", () => this.setDatasource(this.gos.get("datasource")));
    this.addManagedPropertyListener("cacheBlockSize", () => this.resetCache());
    this.addManagedPropertyListener("rowHeight", () => {
      this.rowHeight = _getRowHeightAsNumber(this.beans);
      this.cacheParams.rowHeight = this.rowHeight;
      this.updateRowHeights();
    });
  }
  onColumnEverything() {
    let resetRequired;
    if (this.cacheParams) {
      resetRequired = !_jsonEquals(this.cacheParams.sortModel, this.beans.sortSvc?.getSortModel() ?? []);
    } else {
      resetRequired = true;
    }
    if (resetRequired) {
      this.reset();
    }
  }
  getType() {
    return "infinite";
  }
  setDatasource(datasource) {
    this.destroyDatasource();
    this.datasource = datasource;
    if (datasource) {
      this.reset();
    }
  }
  isEmpty() {
    return !this.infiniteCache;
  }
  isRowsToRender() {
    return !!this.infiniteCache;
  }
  getNodesInRangeForSelection(firstInRange, lastInRange) {
    return this.infiniteCache?.getRowNodesInRange(firstInRange, lastInRange) ?? [];
  }
  reset() {
    if (!this.datasource) {
      return;
    }
    const getRowIdFunc = _getRowIdCallback(this.gos);
    const userGeneratingIds = getRowIdFunc != null;
    if (!userGeneratingIds) {
      this.beans.selectionSvc?.reset("rowDataChanged");
    }
    this.resetCache();
  }
  dispatchModelUpdatedEvent() {
    this.eventSvc.dispatchEvent({
      type: "modelUpdated",
      // not sure if these should all be false - noticed if after implementing,
      // maybe they should be true?
      newPage: false,
      newPageSize: false,
      newData: false,
      keepRenderedRows: true,
      animate: false
    });
  }
  resetCache() {
    this.destroyCache();
    const beans = this.beans;
    const { filterManager, sortSvc, rowNodeBlockLoader, eventSvc, gos } = beans;
    this.cacheParams = {
      // the user provided datasource
      datasource: this.datasource,
      // sort and filter model
      filterModel: filterManager?.getFilterModel() ?? {},
      sortModel: sortSvc?.getSortModel() ?? [],
      rowNodeBlockLoader,
      // properties - this way we take a snapshot of them, so if user changes any, they will be
      // used next time we create a new cache, which is generally after a filter or sort change,
      // or a new datasource is set
      initialRowCount: gos.get("infiniteInitialRowCount"),
      maxBlocksInCache: gos.get("maxBlocksInCache"),
      rowHeight: _getRowHeightAsNumber(beans),
      // if user doesn't provide overflow, we use default overflow of 1, so user can scroll past
      // the current page and request first row of next page
      overflowSize: gos.get("cacheOverflowSize"),
      // page size needs to be 1 or greater. having it at 1 would be silly, as you would be hitting the
      // server for one page at a time. so the default if not specified is 100.
      blockSize: gos.get("cacheBlockSize"),
      // the cache could create this, however it is also used by the pages, so handy to create it
      // here as the settings are also passed to the pages
      lastAccessedSequence: { value: 0 }
    };
    this.infiniteCache = this.createBean(new InfiniteCache(this.cacheParams));
    eventSvc.dispatchEventOnce({
      type: "rowCountReady"
    });
    this.dispatchModelUpdatedEvent();
  }
  updateRowHeights() {
    this.forEachNode((node2) => {
      node2.setRowHeight(this.rowHeight);
      node2.setRowTop(this.rowHeight * node2.rowIndex);
    });
    this.dispatchModelUpdatedEvent();
  }
  destroyCache() {
    this.infiniteCache = this.destroyBean(this.infiniteCache);
  }
  getRow(rowIndex) {
    const infiniteCache = this.infiniteCache;
    if (!infiniteCache) {
      return void 0;
    }
    if (rowIndex >= infiniteCache.getRowCount()) {
      return void 0;
    }
    return infiniteCache.getRow(rowIndex);
  }
  getRowNode(id2) {
    let result2;
    this.forEachNode((rowNode) => {
      if (rowNode.id === id2) {
        result2 = rowNode;
      }
    });
    return result2;
  }
  forEachNode(callback) {
    this.infiniteCache?.forEachNodeDeep(callback);
  }
  getTopLevelRowCount() {
    return this.getRowCount();
  }
  getTopLevelRowDisplayedIndex(topLevelIndex) {
    return topLevelIndex;
  }
  getRowIndexAtPixel(pixel) {
    if (this.rowHeight !== 0) {
      const rowIndexForPixel = Math.floor(pixel / this.rowHeight);
      const lastRowIndex = this.getRowCount() - 1;
      if (rowIndexForPixel > lastRowIndex) {
        return lastRowIndex;
      }
      return rowIndexForPixel;
    }
    return 0;
  }
  getRowCount() {
    return this.infiniteCache ? this.infiniteCache.getRowCount() : 0;
  }
  isRowPresent(rowNode) {
    return !!this.getRowNode(rowNode.id);
  }
  refreshCache() {
    this.infiniteCache?.refreshCache();
  }
  purgeCache() {
    this.infiniteCache?.purgeCache();
  }
  // for iRowModel
  isLastRowIndexKnown() {
    return this.infiniteCache?.isLastRowIndexKnown() ?? false;
  }
  setRowCount(rowCount, lastRowIndexKnown) {
    this.infiniteCache?.setRowCount(rowCount, lastRowIndexKnown);
  }
  resetRowHeights() {
  }
  onRowHeightChanged() {
  }
};
function refreshInfiniteCache(beans) {
  _getInfiniteRowModel(beans)?.refreshCache();
}
function purgeInfiniteCache(beans) {
  _getInfiniteRowModel(beans)?.purgeCache();
}
function getInfiniteRowCount(beans) {
  return _getInfiniteRowModel(beans)?.getRowCount();
}
var RowNodeBlockLoader = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "rowNodeBlockLoader";
    this.activeBlockLoadsCount = 0;
    this.blocks = [];
    this.active = true;
  }
  postConstruct() {
    this.maxConcurrentRequests = _getMaxConcurrentDatasourceRequests(this.gos);
    const blockLoadDebounceMillis = this.gos.get("blockLoadDebounceMillis");
    if (blockLoadDebounceMillis && blockLoadDebounceMillis > 0) {
      this.checkBlockToLoadDebounce = _debounce(
        this,
        this.performCheckBlocksToLoad.bind(this),
        blockLoadDebounceMillis
      );
    }
  }
  addBlock(block2) {
    this.blocks.push(block2);
    block2.addEventListener("loadComplete", this.loadComplete.bind(this));
    this.checkBlockToLoad();
  }
  removeBlock(block2) {
    _removeFromArray(this.blocks, block2);
  }
  destroy() {
    super.destroy();
    this.active = false;
  }
  loadComplete() {
    this.activeBlockLoadsCount--;
    this.checkBlockToLoad();
  }
  checkBlockToLoad() {
    if (this.checkBlockToLoadDebounce) {
      this.checkBlockToLoadDebounce();
    } else {
      this.performCheckBlocksToLoad();
    }
  }
  performCheckBlocksToLoad() {
    if (!this.active) {
      return;
    }
    this.printCacheStatus();
    if (this.maxConcurrentRequests != null && this.activeBlockLoadsCount >= this.maxConcurrentRequests) {
      _logIfDebug(this.gos, `RowNodeBlockLoader - checkBlockToLoad: max loads exceeded`);
      return;
    }
    const loadAvailability = this.maxConcurrentRequests != null ? this.maxConcurrentRequests - this.activeBlockLoadsCount : 1;
    const blocksToLoad = this.blocks.filter((block2) => block2.state === "needsLoading").slice(0, loadAvailability);
    this.activeBlockLoadsCount += blocksToLoad.length;
    for (const block2 of blocksToLoad) {
      block2.load();
    }
    this.printCacheStatus();
  }
  getBlockState() {
    const result2 = {};
    this.blocks.forEach((block2) => {
      const { id: id2, state } = block2.getBlockStateJson();
      result2[id2] = state;
    });
    return result2;
  }
  printCacheStatus() {
    _logIfDebug(
      this.gos,
      `RowNodeBlockLoader - printCacheStatus: activePageLoadsCount = ${this.activeBlockLoadsCount}, blocks = ${JSON.stringify(this.getBlockState())}`
    );
  }
};
var InfiniteRowModelCoreModule = {
  moduleName: "InfiniteRowModelCore",
  version: VERSION,
  rowModels: ["infinite"],
  beans: [InfiniteRowModel, RowNodeBlockLoader]
};
var InfiniteRowModelModule = {
  moduleName: "InfiniteRowModel",
  version: VERSION,
  apiFunctions: {
    refreshInfiniteCache,
    purgeInfiniteCache,
    getInfiniteRowCount
  },
  dependsOn: [InfiniteRowModelCoreModule, SsrmInfiniteSharedApiModule]
};
var ARROW_UP = "↑";
var ARROW_DOWN = "↓";
var AnimateShowChangeCellRendererElement = {
  tag: "span",
  children: [
    { tag: "span", ref: "eDelta", cls: "ag-value-change-delta" },
    { tag: "span", ref: "eValue", cls: "ag-value-change-value" }
  ]
};
var AnimateShowChangeCellRenderer = class extends Component {
  constructor() {
    super(AnimateShowChangeCellRendererElement);
    this.eValue = RefPlaceholder;
    this.eDelta = RefPlaceholder;
    this.refreshCount = 0;
  }
  init(params) {
    this.refresh(params, true);
  }
  showDelta(params, delta) {
    const absDelta = Math.abs(delta);
    const valueFormatted = params.formatValue(absDelta);
    const valueToUse = _exists(valueFormatted) ? valueFormatted : absDelta;
    const deltaUp = delta >= 0;
    const eDelta = this.eDelta;
    if (deltaUp) {
      eDelta.textContent = ARROW_UP + valueToUse;
    } else {
      eDelta.textContent = ARROW_DOWN + valueToUse;
    }
    eDelta.classList.toggle("ag-value-change-delta-up", deltaUp);
    eDelta.classList.toggle("ag-value-change-delta-down", !deltaUp);
  }
  setTimerToRemoveDelta() {
    this.refreshCount++;
    const refreshCountCopy = this.refreshCount;
    this.beans.frameworkOverrides.wrapIncoming(() => {
      window.setTimeout(() => {
        if (refreshCountCopy === this.refreshCount) {
          this.hideDeltaValue();
        }
      }, 2e3);
    });
  }
  hideDeltaValue() {
    this.eValue.classList.remove("ag-value-change-value-highlight");
    _clearElement(this.eDelta);
  }
  refresh(params, isInitialRender = false) {
    const { value: value2, valueFormatted } = params;
    const { eValue, lastValue, beans } = this;
    if (value2 === lastValue) {
      return false;
    }
    if (_exists(valueFormatted)) {
      eValue.textContent = valueFormatted;
    } else if (_exists(value2)) {
      eValue.textContent = value2;
    } else {
      _clearElement(eValue);
    }
    if (beans.filterManager?.isSuppressFlashingCellsBecauseFiltering()) {
      return false;
    }
    const numericValue = value2 && typeof value2 === "object" && "toNumber" in value2 ? value2.toNumber() : value2;
    const numericLastValue = lastValue && typeof lastValue === "object" && "toNumber" in lastValue ? lastValue.toNumber() : lastValue;
    if (numericValue === numericLastValue) {
      return false;
    }
    if (typeof numericValue === "number" && typeof numericLastValue === "number") {
      const delta = numericValue - numericLastValue;
      this.showDelta(params, delta);
    }
    if (lastValue) {
      eValue.classList.add("ag-value-change-value-highlight");
    }
    if (!isInitialRender) {
      this.setTimerToRemoveDelta();
    }
    this.lastValue = value2;
    return true;
  }
};
var animateSlideCellRendererCSS = (
  /*css*/
  `.ag-value-slide-out{opacity:1}:where(.ag-ltr) .ag-value-slide-out{margin-right:5px;transition:opacity 3s,margin-right 3s}:where(.ag-rtl) .ag-value-slide-out{margin-left:5px;transition:opacity 3s,margin-left 3s}:where(.ag-ltr,.ag-rtl) .ag-value-slide-out{transition-timing-function:linear}.ag-value-slide-out-end{opacity:0}:where(.ag-ltr) .ag-value-slide-out-end{margin-right:10px}:where(.ag-rtl) .ag-value-slide-out-end{margin-left:10px}`
);
var AnimateSlideCellRendererElement = {
  tag: "span",
  children: [{ tag: "span", ref: "eCurrent", cls: "ag-value-slide-current" }]
};
var AnimateSlideCellRenderer = class extends Component {
  constructor() {
    super(AnimateSlideCellRendererElement);
    this.eCurrent = RefPlaceholder;
    this.refreshCount = 0;
    this.registerCSS(animateSlideCellRendererCSS);
  }
  init(params) {
    this.refresh(params, true);
  }
  addSlideAnimation() {
    this.refreshCount++;
    const refreshCountCopy = this.refreshCount;
    this.ePrevious?.remove();
    const { beans, eCurrent } = this;
    const prevElement = _createElement({ tag: "span", cls: "ag-value-slide-previous ag-value-slide-out" });
    this.ePrevious = prevElement;
    prevElement.textContent = eCurrent.textContent;
    this.getGui().insertBefore(prevElement, eCurrent);
    beans.frameworkOverrides.wrapIncoming(() => {
      window.setTimeout(() => {
        if (refreshCountCopy !== this.refreshCount) {
          return;
        }
        this.ePrevious.classList.add("ag-value-slide-out-end");
      }, 50);
      window.setTimeout(() => {
        if (refreshCountCopy !== this.refreshCount) {
          return;
        }
        this.ePrevious?.remove();
        this.ePrevious = null;
      }, 3e3);
    });
  }
  refresh(params, isInitialRender = false) {
    let value2 = params.value;
    if (_missing(value2)) {
      value2 = "";
    }
    if (value2 === this.lastValue) {
      return false;
    }
    if (this.beans.filterManager?.isSuppressFlashingCellsBecauseFiltering()) {
      return false;
    }
    if (!isInitialRender) {
      this.addSlideAnimation();
    }
    this.lastValue = value2;
    const eCurrent = this.eCurrent;
    if (_exists(params.valueFormatted)) {
      eCurrent.textContent = params.valueFormatted;
    } else if (_exists(params.value)) {
      eCurrent.textContent = value2;
    } else {
      _clearElement(eCurrent);
    }
    return true;
  }
};
var CellFlashService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "cellFlashSvc";
    this.nextAnimationTime = null;
    this.nextAnimationCycle = null;
    this.animations = {
      highlight: /* @__PURE__ */ new Map(),
      "data-changed": /* @__PURE__ */ new Map()
    };
  }
  animateCell(cellCtrl, cssName, flashDuration = this.beans.gos.get("cellFlashDuration"), fadeDuration = this.beans.gos.get("cellFadeDuration")) {
    const animations = this.animations[cssName];
    animations.delete(cellCtrl);
    const time2 = Date.now();
    const flashEndTime = time2 + flashDuration;
    const fadeEndTime = time2 + flashDuration + fadeDuration;
    const animState = {
      phase: "flash",
      flashEndTime,
      fadeEndTime
    };
    animations.set(cellCtrl, animState);
    const cssBase = `ag-cell-${cssName}`;
    const cssAnimation = `${cssBase}-animation`;
    const {
      comp,
      eGui: { style: style2 }
    } = cellCtrl;
    comp.toggleCss(cssBase, true);
    comp.toggleCss(cssAnimation, false);
    style2.removeProperty("transition");
    style2.removeProperty("transition-delay");
    if (this.nextAnimationTime && flashEndTime + 15 < this.nextAnimationTime) {
      clearTimeout(this.nextAnimationCycle);
      this.nextAnimationCycle = null;
      this.nextAnimationTime = null;
    }
    if (!this.nextAnimationCycle) {
      this.beans.frameworkOverrides.wrapIncoming(() => {
        this.nextAnimationCycle = setTimeout(this.advanceAnimations.bind(this), flashDuration);
      });
      this.nextAnimationTime = flashEndTime;
    }
  }
  advanceAnimations() {
    const time2 = Date.now();
    let nextAnimationTime = null;
    for (const cssName of Object.keys(this.animations)) {
      const animations = this.animations[cssName];
      const cssBase = `ag-cell-${cssName}`;
      const cssAnimation = `${cssBase}-animation`;
      for (const [cell2, animState] of animations) {
        if (!cell2.isAlive() || !cell2.comp) {
          animations.delete(cell2);
          continue;
        }
        const { phase, flashEndTime, fadeEndTime } = animState;
        const nextActionableTime = phase === "flash" ? flashEndTime : fadeEndTime;
        const requiresAction = time2 + 15 >= nextActionableTime;
        if (!requiresAction) {
          nextAnimationTime = Math.min(nextActionableTime, nextAnimationTime ?? Infinity);
          continue;
        }
        const {
          comp,
          eGui: { style: style2 }
        } = cell2;
        switch (phase) {
          case "flash":
            comp.toggleCss(cssBase, false);
            comp.toggleCss(cssAnimation, true);
            style2.transition = `background-color ${fadeEndTime - flashEndTime}ms`;
            style2.transitionDelay = `${flashEndTime - time2}ms`;
            nextAnimationTime = Math.min(fadeEndTime, nextAnimationTime ?? Infinity);
            animState.phase = "fade";
            break;
          case "fade":
            comp.toggleCss(cssBase, false);
            comp.toggleCss(cssAnimation, false);
            style2.removeProperty("transition");
            style2.removeProperty("transition-delay");
            animations.delete(cell2);
            break;
        }
      }
    }
    if (nextAnimationTime == null) {
      this.nextAnimationTime = null;
      this.nextAnimationCycle = null;
    } else if (nextAnimationTime) {
      this.nextAnimationCycle = setTimeout(this.advanceAnimations.bind(this), nextAnimationTime - time2);
      this.nextAnimationTime = nextAnimationTime;
    }
  }
  onFlashCells(cellCtrl, event) {
    if (!cellCtrl.comp) {
      return;
    }
    const cellId = _createCellId(cellCtrl.cellPosition);
    const shouldFlash = event.cells[cellId];
    if (shouldFlash) {
      this.animateCell(cellCtrl, "highlight");
    }
  }
  flashCell(cellCtrl, delays) {
    this.animateCell(cellCtrl, "data-changed", delays?.flashDuration, delays?.fadeDuration);
  }
  destroy() {
    for (const cssName of Object.keys(this.animations)) {
      const animations = this.animations[cssName];
      animations.clear();
    }
  }
};
function flashCells(beans, params = {}) {
  const { cellFlashSvc } = beans;
  if (!cellFlashSvc) {
    return;
  }
  beans.frameworkOverrides.wrapIncoming(() => {
    for (const cellCtrl of beans.rowRenderer.getCellCtrls(params.rowNodes, params.columns)) {
      cellFlashSvc.flashCell(cellCtrl, params);
    }
  });
}
var HighlightChangesModule = {
  moduleName: "HighlightChanges",
  version: VERSION,
  beans: [CellFlashService],
  userComponents: {
    agAnimateShowChangeCellRenderer: AnimateShowChangeCellRenderer,
    agAnimateSlideCellRenderer: AnimateSlideCellRenderer
  },
  apiFunctions: {
    flashCells
  }
};
function getState(beans) {
  return beans.stateSvc?.getState() ?? {};
}
function setState(beans, state, propertiesToIgnore) {
  return beans.stateSvc?.setState(state, propertiesToIgnore);
}
function migrateGridStateModel(state) {
  state = { ...state };
  if (!state.version) {
    state.version = "32.1.0";
  }
  if (state.version === "32.1.0") {
    state = migrateV32_1(state);
  }
  state.version = VERSION;
  return state;
}
function migrateV32_1(state) {
  state.cellSelection = jsonGet(state, "rangeSelection");
  return state;
}
function jsonGet(json2, key2) {
  if (json2 && typeof json2 === "object") {
    return json2[key2];
  }
}
var StateService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "stateSvc";
    this.updateRowGroupExpansionStateTimer = 0;
    this.suppressEvents = true;
    this.queuedUpdateSources = /* @__PURE__ */ new Set();
    this.dispatchStateUpdateEventDebounced = _debounce(
      this,
      () => this.dispatchQueuedStateUpdateEvents(),
      0
    );
    this.onRowGroupOpenedDebounced = _debounce(
      this,
      () => {
        if (this.beans.gos.get("ssrmExpandAllAffectsAllRows")) {
          this.updateCachedState("ssrmRowGroupExpansion", this.getRowGroupExpansionState());
          this.updateCachedState("rowGroupExpansion", void 0);
        } else {
          this.updateCachedState("rowGroupExpansion", this.getRowGroupExpansionState());
          this.updateCachedState("ssrmRowGroupExpansion", void 0);
        }
      },
      0
    );
    this.onRowSelectedDebounced = _debounce(
      this,
      () => {
        this.staleStateKeys.delete("rowSelection");
        this.updateCachedState("rowSelection", this.getRowSelectionState());
      },
      0
    );
    this.staleStateKeys = /* @__PURE__ */ new Set();
  }
  postConstruct() {
    const { gos, ctrlsSvc, colDelayRenderSvc } = this.beans;
    this.isClientSideRowModel = _isClientSideRowModel(gos);
    const initialState = migrateGridStateModel(gos.get("initialState") ?? {});
    const partialColumnState = initialState.partialColumnState;
    delete initialState.partialColumnState;
    this.cachedState = initialState;
    const suppressEventsAndDispatchInitEvent = this.suppressEventsAndDispatchInitEvent.bind(this);
    ctrlsSvc.whenReady(
      this,
      () => suppressEventsAndDispatchInitEvent(() => this.setupStateOnGridReady(initialState))
    );
    if (initialState.columnOrder || initialState.columnVisibility || initialState.columnSizing || initialState.columnPinning || initialState.columnGroup) {
      colDelayRenderSvc?.hideColumns("columnState");
    }
    const [newColumnsLoadedDestroyFunc, rowCountReadyDestroyFunc, firstDataRenderedDestroyFunc] = this.addManagedEventListeners({
      newColumnsLoaded: ({ source: source2 }) => {
        if (source2 === "gridInitializing") {
          newColumnsLoadedDestroyFunc();
          suppressEventsAndDispatchInitEvent(() => {
            this.setupStateOnColumnsInitialised(initialState, !!partialColumnState);
            colDelayRenderSvc?.revealColumns("columnState");
          });
        }
      },
      rowCountReady: () => {
        rowCountReadyDestroyFunc?.();
        suppressEventsAndDispatchInitEvent(() => this.setupStateOnRowCountReady(initialState));
      },
      firstDataRendered: () => {
        firstDataRenderedDestroyFunc?.();
        suppressEventsAndDispatchInitEvent(() => this.setupStateOnFirstDataRendered(initialState));
      }
    });
  }
  destroy() {
    super.destroy();
    clearTimeout(this.updateRowGroupExpansionStateTimer);
    this.queuedUpdateSources.clear();
  }
  getState() {
    if (this.staleStateKeys.size) {
      this.refreshStaleState();
    }
    return this.cachedState;
  }
  setState(providedState, propertiesToIgnore) {
    const state = migrateGridStateModel(providedState);
    delete state.partialColumnState;
    this.cachedState = state;
    this.startSuppressEvents();
    const source2 = "api";
    const ignoreSet = propertiesToIgnore ? new Set(propertiesToIgnore) : void 0;
    this.setGridReadyState(state, source2, ignoreSet);
    this.setColumnsInitialisedState(state, source2, !!ignoreSet, ignoreSet);
    this.setRowCountState(state, source2, ignoreSet);
    setTimeout(() => {
      if (this.isAlive()) {
        this.setFirstDataRenderedState(state, source2, ignoreSet);
      }
      this.stopSuppressEvents(source2);
    });
  }
  setGridReadyState(state, source2, ignoreSet) {
    if (source2 === "api" && !ignoreSet?.has("sideBar")) {
      this.beans.sideBar?.comp?.setState(state.sideBar);
    }
    this.updateCachedState("sideBar", this.getSideBarState());
  }
  setupStateOnGridReady(initialState) {
    this.setGridReadyState(initialState, "gridInitializing");
    const stateUpdater = () => this.updateCachedState("sideBar", this.getSideBarState());
    this.addManagedEventListeners({
      toolPanelVisibleChanged: stateUpdater,
      sideBarUpdated: stateUpdater
    });
  }
  updateColumnAndGroupState() {
    this.updateColumnState([
      "aggregation",
      "columnOrder",
      "columnPinning",
      "columnSizing",
      "columnVisibility",
      "pivot",
      "rowGroup",
      "sort"
    ]);
    this.updateCachedState("columnGroup", this.getColumnGroupState());
  }
  setColumnsInitialisedState(state, source2, partialColumnState, ignoreSet) {
    this.setColumnState(state, source2, partialColumnState, ignoreSet);
    this.setColumnGroupState(state, source2, ignoreSet);
    this.updateColumnAndGroupState();
  }
  setupStateOnColumnsInitialised(initialState, partialColumnState) {
    this.setColumnsInitialisedState(initialState, "gridInitializing", partialColumnState);
    const onUpdate = (state) => () => this.updateColumnState([state]);
    this.addManagedEventListeners({
      columnValueChanged: onUpdate("aggregation"),
      columnMoved: onUpdate("columnOrder"),
      columnPinned: onUpdate("columnPinning"),
      columnResized: onUpdate("columnSizing"),
      columnVisible: onUpdate("columnVisibility"),
      columnPivotChanged: onUpdate("pivot"),
      columnPivotModeChanged: onUpdate("pivot"),
      columnRowGroupChanged: onUpdate("rowGroup"),
      sortChanged: onUpdate("sort"),
      newColumnsLoaded: this.updateColumnAndGroupState.bind(this),
      columnGroupOpened: () => this.updateCachedState("columnGroup", this.getColumnGroupState())
    });
  }
  setRowCountState(state, source2, ignoreSet) {
    const {
      filter: filterState,
      rowGroupExpansion: rowGroupExpansionState,
      ssrmRowGroupExpansion,
      rowSelection: rowSelectionState,
      pagination: paginationState
    } = state;
    const shouldSetState = (prop, propState) => !ignoreSet?.has(prop) && (propState || source2 === "api");
    if (shouldSetState("filter", filterState)) {
      this.setFilterState(filterState);
    }
    if (shouldSetState("rowGroupExpansion", rowGroupExpansionState)) {
      this.setRowGroupExpansionState(ssrmRowGroupExpansion, rowGroupExpansionState, source2);
    }
    if (shouldSetState("rowSelection", rowSelectionState)) {
      this.setRowSelectionState(rowSelectionState, source2);
    }
    if (shouldSetState("pagination", paginationState)) {
      this.setPaginationState(paginationState, source2);
    }
    const updateCachedState = this.updateCachedState.bind(this);
    updateCachedState("filter", this.getFilterState());
    if (this.beans.gos.get("ssrmExpandAllAffectsAllRows")) {
      updateCachedState("ssrmRowGroupExpansion", this.getRowGroupExpansionState());
      updateCachedState("rowGroupExpansion", void 0);
    } else {
      updateCachedState("rowGroupExpansion", this.getRowGroupExpansionState());
      updateCachedState("ssrmRowGroupExpansion", void 0);
    }
    updateCachedState("rowSelection", this.getRowSelectionState());
    updateCachedState("pagination", this.getPaginationState());
  }
  setupStateOnRowCountReady(initialState) {
    this.setRowCountState(initialState, "gridInitializing");
    const updateCachedState = this.updateCachedState.bind(this);
    const updateRowGroupExpansionState = () => {
      this.updateRowGroupExpansionStateTimer = 0;
      if (this.beans.gos.get("ssrmExpandAllAffectsAllRows")) {
        updateCachedState("ssrmRowGroupExpansion", this.getRowGroupExpansionState());
        updateCachedState("rowGroupExpansion", void 0);
      } else {
        updateCachedState("rowGroupExpansion", this.getRowGroupExpansionState());
        updateCachedState("ssrmRowGroupExpansion", void 0);
      }
    };
    const updateFilterState = () => updateCachedState("filter", this.getFilterState());
    const { gos, colFilter } = this.beans;
    this.addManagedEventListeners({
      filterChanged: updateFilterState,
      rowExpansionStateChanged: this.onRowGroupOpenedDebounced,
      expandOrCollapseAll: updateRowGroupExpansionState,
      // `groupDefaultExpanded`/`isGroupOpenByDefault` updates expansion state without an expansion event
      columnRowGroupChanged: updateRowGroupExpansionState,
      rowDataUpdated: () => {
        if (gos.get("groupDefaultExpanded") !== 0 || gos.get("isGroupOpenByDefault")) {
          this.updateRowGroupExpansionStateTimer || (this.updateRowGroupExpansionStateTimer = setTimeout(updateRowGroupExpansionState));
        }
      },
      selectionChanged: () => {
        this.staleStateKeys.add("rowSelection");
        this.onRowSelectedDebounced();
      },
      paginationChanged: (event) => {
        if (event.newPage || event.newPageSize) {
          updateCachedState("pagination", this.getPaginationState());
        }
      }
    });
    if (colFilter) {
      this.addManagedListeners(colFilter, {
        filterStateChanged: updateFilterState
      });
    }
  }
  setFirstDataRenderedState(state, source2, ignoreSet) {
    const {
      scroll: scrollState,
      cellSelection: cellSelectionState,
      focusedCell: focusedCellState,
      columnOrder: columnOrderState,
      rowPinning
    } = state;
    const shouldSetState = (prop, propState) => !ignoreSet?.has(prop) && (propState || source2 === "api");
    if (shouldSetState("focusedCell", focusedCellState)) {
      this.setFocusedCellState(focusedCellState);
    }
    if (shouldSetState("cellSelection", cellSelectionState)) {
      this.setCellSelectionState(cellSelectionState);
    }
    if (shouldSetState("scroll", scrollState)) {
      this.setScrollState(scrollState);
    }
    if (shouldSetState("rowPinning", rowPinning)) {
      this.setRowPinningState(rowPinning);
    }
    this.setColumnPivotState(!!columnOrderState?.orderedColIds, source2);
    const updateCachedState = this.updateCachedState.bind(this);
    updateCachedState("sideBar", this.getSideBarState());
    updateCachedState("focusedCell", this.getFocusedCellState());
    const cellSelection = this.getRangeSelectionState();
    updateCachedState("rangeSelection", cellSelection);
    updateCachedState("cellSelection", cellSelection);
    updateCachedState("scroll", this.getScrollState());
  }
  setupStateOnFirstDataRendered(initialState) {
    this.setFirstDataRenderedState(initialState, "gridInitializing");
    const updateCachedState = this.updateCachedState.bind(this);
    const updateFocusState = () => updateCachedState("focusedCell", this.getFocusedCellState());
    this.addManagedEventListeners({
      cellFocused: updateFocusState,
      cellFocusCleared: updateFocusState,
      cellSelectionChanged: (event) => {
        if (event.finished) {
          const cellSelection = this.getRangeSelectionState();
          updateCachedState("rangeSelection", cellSelection);
          updateCachedState("cellSelection", cellSelection);
        }
      },
      bodyScrollEnd: () => updateCachedState("scroll", this.getScrollState()),
      pinnedRowsChanged: () => updateCachedState("rowPinning", this.getRowPinningState())
    });
  }
  getColumnState() {
    const beans = this.beans;
    return convertColumnState(_getColumnState(beans), beans.colModel.isPivotMode());
  }
  setColumnState(state, source2, partialColumnState, ignoreSet) {
    const {
      sort: sortState,
      rowGroup: groupState,
      aggregation: aggregationState,
      pivot: pivotState,
      columnPinning: columnPinningState,
      columnVisibility: columnVisibilityState,
      columnSizing: columnSizingState,
      columnOrder: columnOrderState
    } = state;
    let forceSetState = false;
    const shouldSetState = (prop, propState) => {
      const shouldSet = !ignoreSet?.has(prop) && !!(propState || source2 === "api");
      forceSetState || (forceSetState = shouldSet);
      return shouldSet;
    };
    const columnStateMap = {};
    const getColumnState2 = (colId) => {
      let columnState = columnStateMap[colId];
      if (columnState) {
        return columnState;
      }
      columnState = { colId };
      columnStateMap[colId] = columnState;
      return columnState;
    };
    const defaultState = {};
    const shouldSetSortState = shouldSetState("sort", sortState);
    if (shouldSetSortState) {
      sortState?.sortModel.forEach(({ colId, sort }, sortIndex) => {
        const columnState = getColumnState2(colId);
        columnState.sort = sort;
        columnState.sortIndex = sortIndex;
      });
    }
    if (shouldSetSortState || !partialColumnState) {
      defaultState.sort = null;
      defaultState.sortIndex = null;
    }
    const shouldSetGroupState = shouldSetState("rowGroup", groupState);
    if (shouldSetGroupState) {
      groupState?.groupColIds.forEach((colId, rowGroupIndex) => {
        const columnState = getColumnState2(colId);
        columnState.rowGroup = true;
        columnState.rowGroupIndex = rowGroupIndex;
      });
    }
    if (shouldSetGroupState || !partialColumnState) {
      defaultState.rowGroup = null;
      defaultState.rowGroupIndex = null;
    }
    const shouldSetAggregationState = shouldSetState("aggregation", aggregationState);
    if (shouldSetAggregationState) {
      aggregationState?.aggregationModel.forEach(({ colId, aggFunc }) => {
        getColumnState2(colId).aggFunc = aggFunc;
      });
    }
    if (shouldSetAggregationState || !partialColumnState) {
      defaultState.aggFunc = null;
    }
    const shouldSetPivotState = shouldSetState("pivot", pivotState);
    if (shouldSetPivotState) {
      pivotState?.pivotColIds.forEach((colId, pivotIndex) => {
        const columnState = getColumnState2(colId);
        columnState.pivot = true;
        columnState.pivotIndex = pivotIndex;
      });
      this.gos.updateGridOptions({
        options: { pivotMode: !!pivotState?.pivotMode },
        source: source2
      });
    }
    if (shouldSetPivotState || !partialColumnState) {
      defaultState.pivot = null;
      defaultState.pivotIndex = null;
    }
    const shouldSetColumnPinningState = shouldSetState("columnPinning", columnPinningState);
    if (shouldSetColumnPinningState) {
      for (const colId of columnPinningState?.leftColIds ?? []) {
        getColumnState2(colId).pinned = "left";
      }
      for (const colId of columnPinningState?.rightColIds ?? []) {
        getColumnState2(colId).pinned = "right";
      }
    }
    if (shouldSetColumnPinningState || !partialColumnState) {
      defaultState.pinned = null;
    }
    const shouldSetColumnVisibilityState = shouldSetState("columnVisibility", columnVisibilityState);
    if (shouldSetColumnVisibilityState) {
      for (const colId of columnVisibilityState?.hiddenColIds ?? []) {
        getColumnState2(colId).hide = true;
      }
    }
    if (shouldSetColumnVisibilityState || !partialColumnState) {
      defaultState.hide = null;
    }
    const shouldSetColumnSizingState = shouldSetState("columnSizing", columnSizingState);
    if (shouldSetColumnSizingState) {
      for (const { colId, flex: flex2, width } of columnSizingState?.columnSizingModel ?? []) {
        const columnState = getColumnState2(colId);
        columnState.flex = flex2 ?? null;
        columnState.width = width;
      }
    }
    if (shouldSetColumnSizingState || !partialColumnState) {
      defaultState.flex = null;
    }
    const columns2 = columnOrderState?.orderedColIds;
    const applyOrder = !!columns2?.length && !ignoreSet?.has("columnOrder");
    const columnStates = applyOrder ? columns2.map((colId) => getColumnState2(colId)) : Object.values(columnStateMap);
    if (columnStates.length || forceSetState) {
      this.columnStates = columnStates;
      _applyColumnState(
        this.beans,
        {
          state: columnStates,
          applyOrder,
          defaultState
        },
        source2
      );
    }
  }
  setColumnPivotState(applyOrder, source2) {
    const columnStates = this.columnStates;
    this.columnStates = void 0;
    const columnGroupStates = this.columnGroupStates;
    this.columnGroupStates = void 0;
    const beans = this.beans;
    const { pivotResultCols, colGroupSvc } = beans;
    if (!pivotResultCols?.isPivotResultColsPresent()) {
      return;
    }
    if (columnStates) {
      const secondaryColumnStates = [];
      for (const columnState of columnStates) {
        if (pivotResultCols.getPivotResultCol(columnState.colId)) {
          secondaryColumnStates.push(columnState);
        }
      }
      _applyColumnState(
        beans,
        {
          state: secondaryColumnStates,
          applyOrder
        },
        source2
      );
    }
    if (columnGroupStates) {
      colGroupSvc?.setColumnGroupState(columnGroupStates, source2);
    }
  }
  getColumnGroupState() {
    const colGroupSvc = this.beans.colGroupSvc;
    if (!colGroupSvc) {
      return void 0;
    }
    const columnGroupState = colGroupSvc.getColumnGroupState();
    return _convertColumnGroupState(columnGroupState);
  }
  setColumnGroupState(state, source2, ignoreSet) {
    const colGroupSvc = this.beans.colGroupSvc;
    if (!colGroupSvc || ignoreSet?.has("columnGroup") || source2 !== "api" && !Object.prototype.hasOwnProperty.call(state, "columnGroup")) {
      return;
    }
    const openColumnGroups = new Set(state.columnGroup?.openColumnGroupIds);
    const existingColumnGroupState = colGroupSvc.getColumnGroupState();
    const stateItems = existingColumnGroupState.map(({ groupId }) => {
      const open = openColumnGroups.has(groupId);
      if (open) {
        openColumnGroups.delete(groupId);
      }
      return {
        groupId,
        open
      };
    });
    for (const groupId of openColumnGroups) {
      stateItems.push({
        groupId,
        open: true
      });
    }
    if (stateItems.length) {
      this.columnGroupStates = stateItems;
    }
    colGroupSvc.setColumnGroupState(stateItems, source2);
  }
  getFilterState() {
    const filterManager = this.beans.filterManager;
    let filterModel = filterManager?.getFilterModel();
    if (filterModel && Object.keys(filterModel).length === 0) {
      filterModel = void 0;
    }
    const columnFilterState = filterManager?.getFilterState();
    const advancedFilterModel = filterManager?.getAdvFilterModel() ?? void 0;
    return filterModel || advancedFilterModel || columnFilterState ? { filterModel, columnFilterState, advancedFilterModel } : void 0;
  }
  setFilterState(filterState) {
    const filterManager = this.beans.filterManager;
    const { filterModel, columnFilterState, advancedFilterModel } = filterState ?? {
      filterModel: null,
      columnFilterState: null,
      advancedFilterModel: null
    };
    if (filterModel !== void 0 || columnFilterState !== void 0) {
      filterManager?.setFilterState(filterModel ?? null, columnFilterState ?? null, "columnFilter");
    }
    if (advancedFilterModel !== void 0) {
      filterManager?.setAdvFilterModel(advancedFilterModel ?? null, "advancedFilter");
    }
  }
  getRangeSelectionState() {
    const cellRanges = this.beans.rangeSvc?.getCellRanges().map((cellRange) => {
      const { id: id2, type, startRow, endRow, columns: columns2, startColumn } = cellRange;
      return {
        id: id2,
        type,
        startRow,
        endRow,
        colIds: columns2.map((column2) => column2.getColId()),
        startColId: startColumn.getColId()
      };
    });
    return cellRanges?.length ? { cellRanges } : void 0;
  }
  setCellSelectionState(cellSelectionState) {
    const { gos, rangeSvc, colModel, visibleCols } = this.beans;
    if (!_isCellSelectionEnabled(gos) || !rangeSvc) {
      return;
    }
    const cellRanges = [];
    for (const cellRange of cellSelectionState?.cellRanges ?? []) {
      const columns2 = [];
      for (const colId of cellRange.colIds) {
        const column2 = colModel.getCol(colId);
        if (column2) {
          columns2.push(column2);
        }
      }
      if (!columns2.length) {
        continue;
      }
      let startColumn = colModel.getCol(cellRange.startColId);
      if (!startColumn) {
        const allColumns = visibleCols.allCols;
        const columnSet2 = new Set(columns2);
        startColumn = allColumns.find((column2) => columnSet2.has(column2));
      }
      cellRanges.push({
        ...cellRange,
        columns: columns2,
        startColumn
      });
    }
    rangeSvc.setCellRanges(cellRanges);
  }
  getScrollState() {
    if (!this.isClientSideRowModel) {
      return void 0;
    }
    const scrollFeature = this.beans.ctrlsSvc.getScrollFeature();
    const { left: left2 } = scrollFeature?.getHScrollPosition() ?? { left: 0 };
    const { top: top2 } = scrollFeature?.getVScrollPosition() ?? { top: 0 };
    return top2 || left2 ? {
      top: top2,
      left: left2
    } : void 0;
  }
  setScrollState(scrollState) {
    if (!this.isClientSideRowModel) {
      return;
    }
    const { top: top2, left: left2 } = scrollState ?? { top: 0, left: 0 };
    const { frameworkOverrides, rowRenderer, animationFrameSvc, ctrlsSvc } = this.beans;
    frameworkOverrides.wrapIncoming(() => {
      ctrlsSvc.get("center").setCenterViewportScrollLeft(left2);
      ctrlsSvc.getScrollFeature()?.setVerticalScrollPosition(top2);
      rowRenderer.redraw({ afterScroll: true });
      animationFrameSvc?.flushAllFrames();
    });
  }
  getSideBarState() {
    return this.beans.sideBar?.comp?.getState();
  }
  getFocusedCellState() {
    if (!this.isClientSideRowModel) {
      return void 0;
    }
    const focusedCell = this.beans.focusSvc.getFocusedCell();
    if (focusedCell) {
      const { column: column2, rowIndex, rowPinned } = focusedCell;
      return {
        colId: column2.getColId(),
        rowIndex,
        rowPinned
      };
    }
    return void 0;
  }
  setFocusedCellState(focusedCellState) {
    if (!this.isClientSideRowModel) {
      return;
    }
    const { focusSvc, colModel } = this.beans;
    if (!focusedCellState) {
      focusSvc.clearFocusedCell();
      return;
    }
    const { colId, rowIndex, rowPinned } = focusedCellState;
    focusSvc.setFocusedCell({
      column: colModel.getCol(colId),
      rowIndex,
      rowPinned,
      forceBrowserFocus: true,
      preventScrollOnBrowserFocus: true
    });
  }
  getPaginationState() {
    const { pagination, gos } = this.beans;
    if (!pagination) {
      return void 0;
    }
    const page = pagination.getCurrentPage();
    const pageSize = !gos.get("paginationAutoPageSize") ? pagination.getPageSize() : void 0;
    if (!page && !pageSize) {
      return;
    }
    return { page, pageSize };
  }
  setPaginationState(paginationState, source2) {
    const { pagination, gos } = this.beans;
    if (!pagination) {
      return;
    }
    const { pageSize, page } = paginationState ?? { page: 0, pageSize: gos.get("paginationPageSize") };
    const isInit = source2 === "gridInitializing";
    if (pageSize && !gos.get("paginationAutoPageSize")) {
      pagination.setPageSize(pageSize, isInit ? "initialState" : "pageSizeSelector");
    }
    if (typeof page === "number") {
      if (isInit) {
        pagination.setPage(page);
      } else {
        pagination.goToPage(page);
      }
    }
  }
  getRowSelectionState() {
    const selectionSvc = this.beans.selectionSvc;
    if (!selectionSvc) {
      return void 0;
    }
    const selectionState = selectionSvc.getSelectionState();
    const noSelections = !selectionState || !Array.isArray(selectionState) && (selectionState.selectAll === false || selectionState.selectAllChildren === false) && !selectionState?.toggledNodes?.length;
    return noSelections ? void 0 : selectionState;
  }
  setRowSelectionState(rowSelectionState, source2) {
    this.beans.selectionSvc?.setSelectionState(rowSelectionState, source2, source2 === "api");
  }
  getRowGroupExpansionState() {
    const { expansionSvc } = this.beans;
    if (!expansionSvc) {
      return void 0;
    }
    return expansionSvc.getExpansionState();
  }
  getRowPinningState() {
    return this.beans.pinnedRowModel?.getPinnedState();
  }
  setRowPinningState(state) {
    const pinnedRowModel = this.beans.pinnedRowModel;
    if (state) {
      pinnedRowModel?.setPinnedState(state);
    } else {
      pinnedRowModel?.reset();
    }
  }
  setRowGroupExpansionState(ssrmRowGroupExpansionState, rowGroupExpansionState, source2) {
    const expansionSvc = this.beans.expansionSvc;
    if (!expansionSvc) {
      return;
    }
    const newExpansionState = rowGroupExpansionState ?? { expandedRowGroupIds: [], collapsedRowGroupIds: [] };
    expansionSvc.setExpansionState(newExpansionState, source2);
  }
  updateColumnState(features) {
    const newColumnState = this.getColumnState();
    let hasChanged = false;
    const cachedState = this.cachedState;
    for (const key2 of Object.keys(newColumnState)) {
      const value2 = newColumnState[key2];
      if (!_jsonEquals(value2, cachedState[key2])) {
        hasChanged = true;
      }
    }
    this.cachedState = {
      ...cachedState,
      ...newColumnState
    };
    if (hasChanged) {
      this.dispatchStateUpdateEvent(features);
    }
  }
  updateCachedState(key2, value2) {
    const existingValue = this.cachedState[key2];
    this.setCachedStateValue(key2, value2);
    if (!_jsonEquals(value2, existingValue)) {
      this.dispatchStateUpdateEvent([key2]);
    }
  }
  setCachedStateValue(key2, value2) {
    this.cachedState = {
      ...this.cachedState,
      [key2]: value2
    };
  }
  refreshStaleState() {
    const staleStateKeys = this.staleStateKeys;
    for (const key2 of staleStateKeys) {
      if (key2 === "rowSelection") {
        this.setCachedStateValue(key2, this.getRowSelectionState());
      }
    }
    staleStateKeys.clear();
  }
  dispatchStateUpdateEvent(sources) {
    if (this.suppressEvents) {
      return;
    }
    for (const source2 of sources) {
      this.queuedUpdateSources.add(source2);
    }
    this.dispatchStateUpdateEventDebounced();
  }
  dispatchQueuedStateUpdateEvents() {
    const queuedUpdateSources = this.queuedUpdateSources;
    const sources = Array.from(queuedUpdateSources);
    queuedUpdateSources.clear();
    this.eventSvc.dispatchEvent({
      type: "stateUpdated",
      sources,
      state: this.cachedState
    });
  }
  startSuppressEvents() {
    this.suppressEvents = true;
    this.beans.colAnimation?.setSuppressAnimation(true);
  }
  stopSuppressEvents(source2) {
    setTimeout(() => {
      this.suppressEvents = false;
      this.queuedUpdateSources.clear();
      if (!this.isAlive()) {
        return;
      }
      this.beans.colAnimation?.setSuppressAnimation(false);
      this.dispatchStateUpdateEvent([source2]);
    });
  }
  suppressEventsAndDispatchInitEvent(updateFunc) {
    this.startSuppressEvents();
    updateFunc();
    this.stopSuppressEvents("gridInitializing");
  }
};
var GridStateModule = {
  moduleName: "GridState",
  version: VERSION,
  beans: [StateService],
  apiFunctions: {
    getState,
    setState
  }
};
function paginationIsLastPageFound(beans) {
  return beans.rowModel.isLastRowIndexKnown();
}
function paginationGetPageSize(beans) {
  return beans.pagination?.getPageSize() ?? 100;
}
function paginationGetCurrentPage(beans) {
  return beans.pagination?.getCurrentPage() ?? 0;
}
function paginationGetTotalPages(beans) {
  return beans.pagination?.getTotalPages() ?? 1;
}
function paginationGetRowCount(beans) {
  return beans.pagination ? beans.pagination.getMasterRowCount() : beans.rowModel.getRowCount();
}
function paginationGoToNextPage(beans) {
  beans.pagination?.goToNextPage();
}
function paginationGoToPreviousPage(beans) {
  beans.pagination?.goToPreviousPage();
}
function paginationGoToFirstPage(beans) {
  beans.pagination?.goToFirstPage();
}
function paginationGoToLastPage(beans) {
  beans.pagination?.goToLastPage();
}
function paginationGoToPage(beans, page) {
  beans.pagination?.goToPage(page);
}
var PaginationAutoPageSizeService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "paginationAutoPageSizeSvc";
  }
  postConstruct() {
    this.beans.ctrlsSvc.whenReady(this, (p) => {
      this.centerRowsCtrl = p.center;
      const listener = this.checkPageSize.bind(this);
      this.addManagedEventListeners({
        bodyHeightChanged: listener,
        scrollVisibilityChanged: listener
      });
      this.addManagedPropertyListener("paginationAutoPageSize", this.onPaginationAutoSizeChanged.bind(this));
      this.checkPageSize();
    });
  }
  notActive() {
    return !this.gos.get("paginationAutoPageSize") || this.centerRowsCtrl == null;
  }
  onPaginationAutoSizeChanged() {
    if (this.notActive()) {
      this.beans.pagination.unsetAutoCalculatedPageSize();
    } else {
      this.checkPageSize();
    }
  }
  checkPageSize() {
    if (this.notActive()) {
      return;
    }
    const bodyHeight = this.centerRowsCtrl.viewportSizeFeature.getBodyHeight();
    if (bodyHeight > 0) {
      const beans = this.beans;
      const update2 = () => {
        const rowHeight = Math.max(_getRowHeightAsNumber(beans), 1);
        const newPageSize = Math.floor(bodyHeight / rowHeight);
        beans.pagination.setPageSize(newPageSize, "autoCalculated");
      };
      if (!this.isBodyRendered) {
        update2();
        this.isBodyRendered = true;
      } else {
        _debounce(this, update2, 50)();
      }
    } else {
      this.isBodyRendered = false;
    }
  }
};
var paginationPageSizeSelector = "paginationPageSizeSelector";
var PageSizeSelectorCompElement = { tag: "span", cls: "ag-paging-page-size" };
var PageSizeSelectorComp = class extends Component {
  constructor() {
    super(PageSizeSelectorCompElement);
    this.hasEmptyOption = false;
    this.handlePageSizeItemSelected = () => {
      if (!this.selectPageSizeComp) {
        return;
      }
      const newValue = this.selectPageSizeComp.getValue();
      if (!newValue) {
        return;
      }
      const paginationPageSize = Number(newValue);
      if (isNaN(paginationPageSize) || paginationPageSize < 1 || paginationPageSize === this.pagination.getPageSize()) {
        return;
      }
      this.pagination.setPageSize(paginationPageSize, "pageSizeSelector");
      if (this.hasEmptyOption) {
        this.toggleSelectDisplay(true);
      }
      this.selectPageSizeComp.getFocusableElement().focus();
    };
  }
  wireBeans(beans) {
    this.pagination = beans.pagination;
  }
  postConstruct() {
    this.addManagedPropertyListener(paginationPageSizeSelector, () => {
      this.onPageSizeSelectorValuesChange();
    });
    this.addManagedEventListeners({ paginationChanged: (event) => this.handlePaginationChanged(event) });
  }
  handlePaginationChanged(paginationChangedEvent) {
    if (!this.selectPageSizeComp || !paginationChangedEvent?.newPageSize) {
      return;
    }
    const paginationPageSize = this.pagination.getPageSize();
    if (this.getPageSizeSelectorValues().includes(paginationPageSize)) {
      this.selectPageSizeComp.setValue(paginationPageSize.toString());
    } else if (this.hasEmptyOption) {
      this.selectPageSizeComp.setValue("");
    } else {
      this.toggleSelectDisplay(true);
    }
  }
  toggleSelectDisplay(show) {
    if (this.selectPageSizeComp && !show) {
      this.reset();
    }
    if (!show) {
      return;
    }
    this.reloadPageSizesSelector();
    if (!this.selectPageSizeComp) {
      return;
    }
  }
  reset() {
    _clearElement(this.getGui());
    if (!this.selectPageSizeComp) {
      return;
    }
    this.selectPageSizeComp = this.destroyBean(this.selectPageSizeComp);
  }
  onPageSizeSelectorValuesChange() {
    if (!this.selectPageSizeComp) {
      return;
    }
    if (this.shouldShowPageSizeSelector()) {
      this.reloadPageSizesSelector();
    }
  }
  shouldShowPageSizeSelector() {
    return this.gos.get("pagination") && !this.gos.get("suppressPaginationPanel") && !this.gos.get("paginationAutoPageSize") && this.gos.get(paginationPageSizeSelector) !== false;
  }
  reloadPageSizesSelector() {
    const pageSizeOptions = this.getPageSizeSelectorValues();
    const paginationPageSizeOption = this.pagination.getPageSize();
    const shouldAddAndSelectEmptyOption = !paginationPageSizeOption || !pageSizeOptions.includes(paginationPageSizeOption);
    if (shouldAddAndSelectEmptyOption) {
      const pageSizeSet = this.gos.exists("paginationPageSize");
      const pageSizesSet = this.gos.get(paginationPageSizeSelector) !== true;
      _warn(94, { pageSizeSet, pageSizesSet, pageSizeOptions, paginationPageSizeOption });
      if (!pageSizesSet) {
        _warn(95, { paginationPageSizeOption, paginationPageSizeSelector });
      }
      pageSizeOptions.unshift("");
    }
    const value2 = String(shouldAddAndSelectEmptyOption ? "" : paginationPageSizeOption);
    if (this.selectPageSizeComp) {
      if (!_areEqual(this.pageSizeOptions, pageSizeOptions)) {
        this.selectPageSizeComp.clearOptions().addOptions(this.createPageSizeSelectOptions(pageSizeOptions));
        this.pageSizeOptions = pageSizeOptions;
      }
      this.selectPageSizeComp.setValue(value2, true);
    } else {
      this.createPageSizeSelectorComp(pageSizeOptions, value2);
    }
    this.hasEmptyOption = shouldAddAndSelectEmptyOption;
  }
  createPageSizeSelectOptions(pageSizeOptions) {
    return pageSizeOptions.map((value2) => ({
      value: String(value2)
    }));
  }
  createPageSizeSelectorComp(pageSizeOptions, value2) {
    const localeTextFunc = this.getLocaleTextFunc();
    const localisedLabel = localeTextFunc("pageSizeSelectorLabel", "Page Size:");
    const localisedAriaLabel = localeTextFunc("ariaPageSizeSelectorLabel", "Page Size");
    this.selectPageSizeComp = this.createManagedBean(new AgSelect()).addOptions(this.createPageSizeSelectOptions(pageSizeOptions)).setValue(value2).setAriaLabel(localisedAriaLabel).setLabel(localisedLabel).onValueChange(() => this.handlePageSizeItemSelected());
    this.appendChild(this.selectPageSizeComp);
  }
  getPageSizeSelectorValues() {
    const defaultValues = [20, 50, 100];
    const paginationPageSizeSelectorValues = this.gos.get(paginationPageSizeSelector);
    if (!Array.isArray(paginationPageSizeSelectorValues) || !paginationPageSizeSelectorValues?.length) {
      return defaultValues;
    }
    return [...paginationPageSizeSelectorValues].sort((a2, b) => a2 - b);
  }
  destroy() {
    this.toggleSelectDisplay(false);
    super.destroy();
  }
};
var PageSizeSelectorSelector = {
  selector: "AG-PAGE-SIZE-SELECTOR",
  component: PageSizeSelectorComp
};
var paginationCompCSS = (
  /*css*/
  `.ag-paging-panel{align-items:center;border-top:var(--ag-footer-row-border);display:flex;gap:calc(var(--ag-spacing)*4);height:var(--ag-pagination-panel-height);justify-content:flex-end;padding:0 var(--ag-cell-horizontal-padding)}:where(.ag-paging-page-size) .ag-wrapper{min-width:50px}.ag-paging-page-summary-panel{align-items:center;display:flex;gap:var(--ag-cell-widget-spacing);.ag-disabled &{pointer-events:none}}.ag-paging-button{cursor:pointer;position:relative;&.ag-disabled{cursor:default;opacity:.5}}.ag-paging-number,.ag-paging-row-summary-panel-number{font-weight:500}`
);
var PaginationComp = class extends TabGuardComp$1 {
  constructor() {
    super();
    this.btFirst = RefPlaceholder;
    this.btPrevious = RefPlaceholder;
    this.btNext = RefPlaceholder;
    this.btLast = RefPlaceholder;
    this.lbRecordCount = RefPlaceholder;
    this.lbFirstRowOnPage = RefPlaceholder;
    this.lbLastRowOnPage = RefPlaceholder;
    this.lbCurrent = RefPlaceholder;
    this.lbTotal = RefPlaceholder;
    this.pageSizeComp = RefPlaceholder;
    this.previousAndFirstButtonsDisabled = false;
    this.nextButtonDisabled = false;
    this.lastButtonDisabled = false;
    this.areListenersSetup = false;
    this.allowFocusInnerElement = false;
    this.registerCSS(paginationCompCSS);
  }
  wireBeans(beans) {
    this.rowModel = beans.rowModel;
    this.pagination = beans.pagination;
    this.ariaAnnounce = beans.ariaAnnounce;
  }
  postConstruct() {
    const isRtl = this.gos.get("enableRtl");
    this.setTemplate(this.getTemplate(), [PageSizeSelectorSelector]);
    const { btFirst, btPrevious, btNext, btLast } = this;
    this.activateTabIndex([btFirst, btPrevious, btNext, btLast]);
    btFirst.insertAdjacentElement("afterbegin", _createIconNoSpan(isRtl ? "last" : "first", this.beans));
    btPrevious.insertAdjacentElement("afterbegin", _createIconNoSpan(isRtl ? "next" : "previous", this.beans));
    btNext.insertAdjacentElement("afterbegin", _createIconNoSpan(isRtl ? "previous" : "next", this.beans));
    btLast.insertAdjacentElement("afterbegin", _createIconNoSpan(isRtl ? "first" : "last", this.beans));
    this.addManagedPropertyListener("pagination", this.onPaginationChanged.bind(this));
    this.addManagedPropertyListener("suppressPaginationPanel", this.onPaginationChanged.bind(this));
    this.addManagedPropertyListeners(
      ["paginationPageSizeSelector", "paginationAutoPageSize", "suppressPaginationPanel"],
      () => this.onPageSizeRelatedOptionsChange()
    );
    this.pageSizeComp.toggleSelectDisplay(this.pageSizeComp.shouldShowPageSizeSelector());
    this.initialiseTabGuard({
      // prevent tab guard default logic
      onTabKeyDown: () => {
      },
      focusInnerElement: (fromBottom) => {
        if (this.allowFocusInnerElement) {
          return this.tabGuardFeature.getTabGuardCtrl().focusInnerElement(fromBottom);
        } else {
          return _focusGridInnerElement(this.beans, fromBottom);
        }
      },
      forceFocusOutWhenTabGuardsAreEmpty: true
    });
    this.onPaginationChanged();
  }
  setAllowFocus(allowFocus) {
    this.allowFocusInnerElement = allowFocus;
  }
  onPaginationChanged() {
    const isPaging = this.gos.get("pagination");
    const paginationPanelEnabled = isPaging && !this.gos.get("suppressPaginationPanel");
    this.setDisplayed(paginationPanelEnabled);
    if (!paginationPanelEnabled) {
      return;
    }
    this.setupListeners();
    this.enableOrDisableButtons();
    this.updateLabels();
    this.onPageSizeRelatedOptionsChange();
  }
  onPageSizeRelatedOptionsChange() {
    this.pageSizeComp.toggleSelectDisplay(this.pageSizeComp.shouldShowPageSizeSelector());
  }
  setupListeners() {
    if (!this.areListenersSetup) {
      this.addManagedEventListeners({ paginationChanged: this.onPaginationChanged.bind(this) });
      for (const item2 of [
        { el: this.btFirst, fn: this.onBtFirst.bind(this) },
        { el: this.btPrevious, fn: this.onBtPrevious.bind(this) },
        { el: this.btNext, fn: this.onBtNext.bind(this) },
        { el: this.btLast, fn: this.onBtLast.bind(this) }
      ]) {
        const { el, fn: fn3 } = item2;
        this.addManagedListeners(el, {
          click: fn3,
          keydown: (e) => {
            if (e.key === KeyCode.ENTER || e.key === KeyCode.SPACE) {
              e.preventDefault();
              fn3();
            }
          }
        });
      }
      _addFocusableContainerListener(this.beans, this, this.getGui());
      this.areListenersSetup = true;
    }
  }
  onBtFirst() {
    if (!this.previousAndFirstButtonsDisabled) {
      this.pagination.goToFirstPage();
    }
  }
  formatNumber(value2) {
    const userFunc = this.gos.getCallback("paginationNumberFormatter");
    if (userFunc) {
      const params = { value: value2 };
      return userFunc(params);
    }
    return _formatNumberCommas(value2, this.getLocaleTextFunc.bind(this));
  }
  getTemplate() {
    const localeTextFunc = this.getLocaleTextFunc();
    const idPrefix = `ag-${this.getCompId()}`;
    return {
      tag: "div",
      cls: "ag-paging-panel ag-unselectable",
      attrs: { id: `${idPrefix}` },
      children: [
        {
          tag: "ag-page-size-selector",
          ref: "pageSizeComp"
        },
        {
          tag: "span",
          cls: "ag-paging-row-summary-panel",
          children: [
            {
              tag: "span",
              ref: "lbFirstRowOnPage",
              cls: "ag-paging-row-summary-panel-number",
              attrs: { id: `${idPrefix}-first-row` }
            },
            { tag: "span", attrs: { id: `${idPrefix}-to` }, children: localeTextFunc("to", "to") },
            {
              tag: "span",
              ref: "lbLastRowOnPage",
              cls: "ag-paging-row-summary-panel-number",
              attrs: { id: `${idPrefix}-last-row` }
            },
            { tag: "span", attrs: { id: `${idPrefix}-of` }, children: localeTextFunc("of", "of") },
            {
              tag: "span",
              ref: "lbRecordCount",
              cls: "ag-paging-row-summary-panel-number",
              attrs: { id: `${idPrefix}-row-count` }
            }
          ]
        },
        {
          tag: "span",
          cls: "ag-paging-page-summary-panel",
          role: "presentation",
          children: [
            {
              tag: "div",
              ref: "btFirst",
              cls: "ag-button ag-paging-button",
              role: "button",
              attrs: { "aria-label": localeTextFunc("firstPage", "First Page") }
            },
            {
              tag: "div",
              ref: "btPrevious",
              cls: "ag-button ag-paging-button",
              role: "button",
              attrs: { "aria-label": localeTextFunc("previousPage", "Previous Page") }
            },
            {
              tag: "span",
              cls: "ag-paging-description",
              children: [
                {
                  tag: "span",
                  attrs: {
                    id: `${idPrefix}-start-page`
                  },
                  children: localeTextFunc("page", "Page")
                },
                {
                  tag: "span",
                  ref: "lbCurrent",
                  cls: "ag-paging-number",
                  attrs: { id: `${idPrefix}-start-page-number` }
                },
                {
                  tag: "span",
                  attrs: {
                    id: `${idPrefix}-of-page`
                  },
                  children: localeTextFunc("of", "of")
                },
                {
                  tag: "span",
                  ref: "lbTotal",
                  cls: "ag-paging-number",
                  attrs: { id: `${idPrefix}-of-page-number` }
                }
              ]
            },
            {
              tag: "div",
              ref: "btNext",
              cls: "ag-button ag-paging-button",
              role: "button",
              attrs: { "aria-label": localeTextFunc("nextPage", "Next Page") }
            },
            {
              tag: "div",
              ref: "btLast",
              cls: "ag-button ag-paging-button",
              role: "button",
              attrs: { "aria-label": localeTextFunc("lastPage", "Last Page") }
            }
          ]
        }
      ]
    };
  }
  onBtNext() {
    if (!this.nextButtonDisabled) {
      this.pagination.goToNextPage();
    }
  }
  onBtPrevious() {
    if (!this.previousAndFirstButtonsDisabled) {
      this.pagination.goToPreviousPage();
    }
  }
  onBtLast() {
    if (!this.lastButtonDisabled) {
      this.pagination.goToLastPage();
    }
  }
  enableOrDisableButtons() {
    const currentPage = this.pagination.getCurrentPage();
    const maxRowFound = this.rowModel.isLastRowIndexKnown();
    const totalPages = this.pagination.getTotalPages();
    this.previousAndFirstButtonsDisabled = currentPage === 0;
    this.toggleButtonDisabled(this.btFirst, this.previousAndFirstButtonsDisabled);
    this.toggleButtonDisabled(this.btPrevious, this.previousAndFirstButtonsDisabled);
    const zeroPagesToDisplay = this.isZeroPagesToDisplay();
    const onLastPage = currentPage === totalPages - 1;
    this.nextButtonDisabled = onLastPage || zeroPagesToDisplay;
    this.lastButtonDisabled = !maxRowFound || zeroPagesToDisplay || currentPage === totalPages - 1;
    this.toggleButtonDisabled(this.btNext, this.nextButtonDisabled);
    this.toggleButtonDisabled(this.btLast, this.lastButtonDisabled);
  }
  toggleButtonDisabled(button, disabled2) {
    _setAriaDisabled(button, disabled2);
    button.classList.toggle("ag-disabled", disabled2);
  }
  isZeroPagesToDisplay() {
    const maxRowFound = this.rowModel.isLastRowIndexKnown();
    const totalPages = this.pagination.getTotalPages();
    return maxRowFound && totalPages === 0;
  }
  updateLabels() {
    const lastPageFound = this.rowModel.isLastRowIndexKnown();
    const totalPages = this.pagination.getTotalPages();
    const masterRowCount = this.pagination.getMasterRowCount();
    const rowCount = lastPageFound ? masterRowCount : null;
    const currentPage = this.pagination.getCurrentPage();
    const pageSize = this.pagination.getPageSize();
    let startRow;
    let endRow;
    if (this.isZeroPagesToDisplay()) {
      startRow = endRow = 0;
    } else {
      startRow = pageSize * currentPage + 1;
      endRow = startRow + pageSize - 1;
      if (lastPageFound && endRow > rowCount) {
        endRow = rowCount;
      }
    }
    const theoreticalEndRow = startRow + pageSize - 1;
    const isLoadingPageSize = !lastPageFound && masterRowCount < theoreticalEndRow;
    const lbFirstRowOnPage = this.formatNumber(startRow);
    this.lbFirstRowOnPage.textContent = lbFirstRowOnPage;
    let lbLastRowOnPage;
    const localeTextFunc = this.getLocaleTextFunc();
    if (isLoadingPageSize) {
      lbLastRowOnPage = localeTextFunc("pageLastRowUnknown", "?");
    } else {
      lbLastRowOnPage = this.formatNumber(endRow);
    }
    this.lbLastRowOnPage.textContent = lbLastRowOnPage;
    const pagesExist = totalPages > 0;
    const toDisplay = pagesExist ? currentPage + 1 : 0;
    const lbCurrent = this.formatNumber(toDisplay);
    this.lbCurrent.textContent = lbCurrent;
    let lbTotal;
    let lbRecordCount;
    if (lastPageFound) {
      lbTotal = this.formatNumber(totalPages);
      lbRecordCount = this.formatNumber(rowCount);
    } else {
      const moreText = localeTextFunc("more", "more");
      lbTotal = moreText;
      lbRecordCount = moreText;
    }
    this.lbTotal.textContent = lbTotal;
    this.lbRecordCount.textContent = lbRecordCount;
    this.announceAriaStatus(lbFirstRowOnPage, lbLastRowOnPage, lbRecordCount, lbCurrent, lbTotal);
  }
  announceAriaStatus(lbFirstRowOnPage, lbLastRowOnPage, lbRecordCount, lbCurrent, lbTotal) {
    const localeTextFunc = this.getLocaleTextFunc();
    const strPage = localeTextFunc("page", "Page");
    const strTo = localeTextFunc("to", "to");
    const strOf = localeTextFunc("of", "of");
    const ariaRowStatus = `${lbFirstRowOnPage} ${strTo} ${lbLastRowOnPage} ${strOf} ${lbRecordCount}`;
    const ariaPageStatus = `${strPage} ${lbCurrent} ${strOf} ${lbTotal}`;
    if (ariaRowStatus !== this.ariaRowStatus) {
      this.ariaRowStatus = ariaRowStatus;
      this.ariaAnnounce?.announceValue(ariaRowStatus, "paginationRow");
    }
    if (ariaPageStatus !== this.ariaPageStatus) {
      this.ariaPageStatus = ariaPageStatus;
      this.ariaAnnounce?.announceValue(ariaPageStatus, "paginationPage");
    }
  }
};
var PaginationSelector = {
  selector: "AG-PAGINATION",
  component: PaginationComp
};
var PaginationService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "pagination";
    this.currentPage = 0;
    this.topDisplayedRowIndex = 0;
    this.bottomDisplayedRowIndex = 0;
    this.masterRowCount = 0;
  }
  postConstruct() {
    const gos = this.gos;
    this.active = gos.get("pagination");
    this.pageSizeFromGridOptions = gos.get("paginationPageSize");
    this.paginateChildRows = this.isPaginateChildRows();
    this.addManagedPropertyListener("pagination", this.onPaginationGridOptionChanged.bind(this));
    this.addManagedPropertyListener("paginationPageSize", this.onPageSizeGridOptionChanged.bind(this));
  }
  getPaginationSelector() {
    return PaginationSelector;
  }
  isPaginateChildRows() {
    const gos = this.gos;
    const shouldPaginate = gos.get("groupHideParentOfSingleChild") || // following two properties deprecated v32.3.0
    gos.get("groupRemoveSingleChildren") || gos.get("groupRemoveLowestSingleChildren");
    if (shouldPaginate) {
      return true;
    }
    return gos.get("paginateChildRows");
  }
  onPaginationGridOptionChanged() {
    this.active = this.gos.get("pagination");
    this.calculatePages();
    this.dispatchPaginationChangedEvent({ keepRenderedRows: true });
  }
  onPageSizeGridOptionChanged() {
    this.setPageSize(this.gos.get("paginationPageSize"), "gridOptions");
  }
  goToPage(page) {
    const currentPage = this.currentPage;
    if (!this.active || currentPage === page || typeof currentPage !== "number") {
      return;
    }
    const { editSvc } = this.beans;
    if (editSvc?.isEditing()) {
      if (editSvc.isBatchEditing()) {
        editSvc.cleanupEditors();
      } else {
        editSvc.stopEditing(void 0, { source: "api" });
      }
    }
    this.currentPage = page;
    this.calculatePages();
    this.dispatchPaginationChangedEvent({ newPage: true });
  }
  goToPageWithIndex(index) {
    if (!this.active) {
      return;
    }
    let adjustedIndex = index;
    if (!this.paginateChildRows) {
      adjustedIndex = this.beans.rowModel.getTopLevelIndexFromDisplayedIndex?.(index) ?? index;
    }
    this.goToPage(Math.floor(adjustedIndex / this.pageSize));
  }
  isRowInPage(rowIndex) {
    if (!this.active) {
      return true;
    }
    return rowIndex >= this.topDisplayedRowIndex && rowIndex <= this.bottomDisplayedRowIndex;
  }
  getCurrentPage() {
    return this.currentPage;
  }
  goToNextPage() {
    this.goToPage(this.currentPage + 1);
  }
  goToPreviousPage() {
    this.goToPage(this.currentPage - 1);
  }
  goToFirstPage() {
    this.goToPage(0);
  }
  goToLastPage() {
    const rowCount = this.beans.rowModel.getRowCount();
    const lastPage = Math.floor(rowCount / this.pageSize);
    this.goToPage(lastPage);
  }
  getPageSize() {
    return this.pageSize;
  }
  getTotalPages() {
    return this.totalPages;
  }
  /** This is only for state setting before data has been loaded */
  setPage(page) {
    this.currentPage = page;
  }
  get pageSize() {
    if (_exists(this.pageSizeAutoCalculated) && this.gos.get("paginationAutoPageSize")) {
      return this.pageSizeAutoCalculated;
    }
    if (_exists(this.pageSizeFromPageSizeSelector)) {
      return this.pageSizeFromPageSizeSelector;
    }
    if (_exists(this.pageSizeFromInitialState)) {
      return this.pageSizeFromInitialState;
    }
    if (_exists(this.pageSizeFromGridOptions)) {
      return this.pageSizeFromGridOptions;
    }
    return this.defaultPageSize;
  }
  calculatePages() {
    if (this.active) {
      if (this.paginateChildRows) {
        this.calculatePagesAllRows();
      } else {
        this.calculatePagesMasterRowsOnly();
      }
    } else {
      this.calculatedPagesNotActive();
    }
    this.beans.pageBounds.calculateBounds(this.topDisplayedRowIndex, this.bottomDisplayedRowIndex);
  }
  unsetAutoCalculatedPageSize() {
    if (this.pageSizeAutoCalculated === void 0) {
      return;
    }
    const oldPageSize = this.pageSizeAutoCalculated;
    this.pageSizeAutoCalculated = void 0;
    if (this.pageSize === oldPageSize) {
      return;
    }
    this.calculatePages();
    this.dispatchPaginationChangedEvent({ newPageSize: true });
  }
  setPageSize(size, source2) {
    const currentSize = this.pageSize;
    switch (source2) {
      case "autoCalculated":
        this.pageSizeAutoCalculated = size;
        break;
      case "pageSizeSelector":
        this.pageSizeFromPageSizeSelector = size;
        if (this.currentPage !== 0) {
          this.goToFirstPage();
        }
        break;
      case "initialState":
        this.pageSizeFromInitialState = size;
        break;
      case "gridOptions":
        this.pageSizeFromGridOptions = size;
        this.pageSizeFromInitialState = void 0;
        this.pageSizeFromPageSizeSelector = void 0;
        if (this.currentPage !== 0) {
          this.goToFirstPage();
        }
        break;
    }
    if (currentSize !== this.pageSize) {
      this.calculatePages();
      this.dispatchPaginationChangedEvent({ newPageSize: true, keepRenderedRows: true });
    }
  }
  setZeroRows() {
    this.masterRowCount = 0;
    this.topDisplayedRowIndex = 0;
    this.bottomDisplayedRowIndex = -1;
    this.currentPage = 0;
    this.totalPages = 0;
  }
  adjustCurrentPageIfInvalid() {
    const totalPages = this.totalPages;
    if (this.currentPage >= totalPages) {
      this.currentPage = totalPages - 1;
    }
    const currentPage = this.currentPage;
    if (!isFinite(currentPage) || isNaN(currentPage) || currentPage < 0) {
      this.currentPage = 0;
    }
  }
  calculatePagesMasterRowsOnly() {
    const rowModel = this.beans.rowModel;
    const masterRowCount = rowModel.getTopLevelRowCount();
    this.masterRowCount = masterRowCount;
    if (masterRowCount <= 0) {
      this.setZeroRows();
      return;
    }
    const pageSize = this.pageSize;
    const masterLastRowIndex = masterRowCount - 1;
    this.totalPages = Math.floor(masterLastRowIndex / pageSize) + 1;
    this.adjustCurrentPageIfInvalid();
    const currentPage = this.currentPage;
    const masterPageStartIndex = pageSize * currentPage;
    let masterPageEndIndex = pageSize * (currentPage + 1) - 1;
    if (masterPageEndIndex > masterLastRowIndex) {
      masterPageEndIndex = masterLastRowIndex;
    }
    this.topDisplayedRowIndex = rowModel.getTopLevelRowDisplayedIndex(masterPageStartIndex);
    if (masterPageEndIndex === masterLastRowIndex) {
      this.bottomDisplayedRowIndex = rowModel.getRowCount() - 1;
    } else {
      const firstIndexNotToShow = rowModel.getTopLevelRowDisplayedIndex(masterPageEndIndex + 1);
      this.bottomDisplayedRowIndex = firstIndexNotToShow - 1;
    }
  }
  getMasterRowCount() {
    return this.masterRowCount;
  }
  calculatePagesAllRows() {
    const masterRowCount = this.beans.rowModel.getRowCount();
    this.masterRowCount = masterRowCount;
    if (masterRowCount === 0) {
      this.setZeroRows();
      return;
    }
    const { pageSize, currentPage } = this;
    const maxRowIndex = masterRowCount - 1;
    this.totalPages = Math.floor(maxRowIndex / pageSize) + 1;
    this.adjustCurrentPageIfInvalid();
    this.topDisplayedRowIndex = pageSize * currentPage;
    this.bottomDisplayedRowIndex = pageSize * (currentPage + 1) - 1;
    if (this.bottomDisplayedRowIndex > maxRowIndex) {
      this.bottomDisplayedRowIndex = maxRowIndex;
    }
  }
  calculatedPagesNotActive() {
    this.setPageSize(void 0, "autoCalculated");
    this.totalPages = 1;
    this.currentPage = 0;
    this.topDisplayedRowIndex = 0;
    this.bottomDisplayedRowIndex = this.beans.rowModel.getRowCount() - 1;
  }
  dispatchPaginationChangedEvent(params) {
    const { keepRenderedRows = false, newPage = false, newPageSize = false } = params;
    this.eventSvc.dispatchEvent({
      type: "paginationChanged",
      animate: false,
      newData: false,
      newPage,
      newPageSize,
      keepRenderedRows
    });
  }
};
var PaginationModule = {
  moduleName: "Pagination",
  version: VERSION,
  beans: [PaginationService, PaginationAutoPageSizeService],
  icons: {
    // "go to first" button in pagination controls
    first: "first",
    // "go to previous" button in pagination controls
    previous: "previous",
    // "go to next" button in pagination controls
    next: "next",
    // "go to last" button in pagination controls
    last: "last"
  },
  apiFunctions: {
    paginationIsLastPageFound,
    paginationGetPageSize,
    paginationGetCurrentPage,
    paginationGetTotalPages,
    paginationGetRowCount,
    paginationGoToNextPage,
    paginationGoToPreviousPage,
    paginationGoToFirstPage,
    paginationGoToLastPage,
    paginationGoToPage
  },
  dependsOn: [PopupModule]
};
function redrawRows(beans, params = {}) {
  const rowNodes = params ? params.rowNodes : void 0;
  beans.frameworkOverrides.wrapIncoming(() => beans.rowRenderer.redrawRows(rowNodes));
}
function setRowNodeExpanded(beans, rowNode, expanded, expandParents, forceSync) {
  if (rowNode) {
    if (expandParents && rowNode.parent && rowNode.parent.level !== -1) {
      setRowNodeExpanded(beans, rowNode.parent, expanded, expandParents, forceSync);
    }
    rowNode.setExpanded(expanded, void 0, forceSync);
  }
}
function getRowNode(beans, id2) {
  return beans.rowModel.getRowNode(id2);
}
function addRenderedRowListener(beans, eventName, rowIndex, callback) {
  beans.rowRenderer.addRenderedRowListener(eventName, rowIndex, callback);
}
function getRenderedNodes(beans) {
  return beans.rowRenderer.getRenderedNodes();
}
function forEachNode(beans, callback, includeFooterNodes) {
  beans.rowModel.forEachNode(callback, includeFooterNodes);
}
function getFirstDisplayedRowIndex(beans) {
  return beans.rowRenderer.firstRenderedRow;
}
function getLastDisplayedRowIndex(beans) {
  return beans.rowRenderer.lastRenderedRow;
}
function getDisplayedRowAtIndex(beans, index) {
  return beans.rowModel.getRow(index);
}
function getDisplayedRowCount(beans) {
  return beans.rowModel.getRowCount();
}
var RowApiModule = {
  moduleName: "RowApi",
  version: VERSION,
  apiFunctions: {
    redrawRows,
    setRowNodeExpanded,
    getRowNode,
    addRenderedRowListener,
    getRenderedNodes,
    forEachNode,
    getFirstDisplayedRowIndex,
    getLastDisplayedRowIndex,
    getDisplayedRowAtIndex,
    getDisplayedRowCount
  }
};
var ScrollApiModule = {
  moduleName: "ScrollApi",
  version: VERSION,
  apiFunctions: {
    getVerticalPixelRange,
    getHorizontalPixelRange,
    ensureColumnVisible,
    ensureIndexVisible,
    ensureNodeVisible
  }
};
function setGridAriaProperty(beans, property, value2) {
  if (!property) {
    return;
  }
  const eGrid = beans.ctrlsSvc.getGridBodyCtrl().eGridBody;
  const ariaProperty = `aria-${property}`;
  if (value2 === null) {
    eGrid.removeAttribute(ariaProperty);
  } else {
    eGrid.setAttribute(ariaProperty, value2);
  }
}
function refreshCells(beans, params = {}) {
  beans.frameworkOverrides.wrapIncoming(() => beans.rowRenderer.refreshCells(params));
}
function refreshHeader(beans) {
  beans.frameworkOverrides.wrapIncoming(() => {
    for (const c2 of beans.ctrlsSvc.getHeaderRowContainerCtrls()) {
      c2.refresh();
    }
  });
}
function isAnimationFrameQueueEmpty(beans) {
  return beans.animationFrameSvc?.isQueueEmpty() ?? true;
}
function flushAllAnimationFrames(beans) {
  beans.animationFrameSvc?.flushAllFrames();
}
function getSizesForCurrentTheme(beans) {
  return {
    rowHeight: _getRowHeightAsNumber(beans),
    headerHeight: getHeaderHeight(beans)
  };
}
function getCellRendererInstances(beans, params = {}) {
  const cellRenderers = [];
  for (const cellCtrl of beans.rowRenderer.getCellCtrls(params.rowNodes, params.columns)) {
    const cellRenderer = cellCtrl.getCellRenderer();
    if (cellRenderer != null) {
      cellRenderers.push(_unwrapUserComp(cellRenderer));
    }
  }
  if (params.columns?.length) {
    return cellRenderers;
  }
  const fullWidthRenderers = [];
  const rowIdMap = mapRowNodes(params.rowNodes);
  for (const rowCtrl of beans.rowRenderer.getAllRowCtrls()) {
    if (rowIdMap && !isRowInMap(rowCtrl.rowNode, rowIdMap)) {
      continue;
    }
    if (!rowCtrl.isFullWidth()) {
      continue;
    }
    const renderers = rowCtrl.getFullWidthCellRenderers();
    for (let i2 = 0; i2 < renderers.length; i2++) {
      const renderer = renderers[i2];
      if (renderer != null) {
        fullWidthRenderers.push(_unwrapUserComp(renderer));
      }
    }
  }
  return [...fullWidthRenderers, ...cellRenderers];
}
var RenderApiModule = {
  moduleName: "RenderApi",
  version: VERSION,
  apiFunctions: {
    setGridAriaProperty,
    refreshCells,
    refreshHeader,
    isAnimationFrameQueueEmpty,
    flushAllAnimationFrames,
    getSizesForCurrentTheme,
    getCellRendererInstances
  }
};
function sizeColumnsToFit(beans, paramsOrGridWidth) {
  if (typeof paramsOrGridWidth === "number") {
    beans.colAutosize?.sizeColumnsToFit(paramsOrGridWidth, "api");
  } else {
    beans.colAutosize?.sizeColumnsToFitGridBody(paramsOrGridWidth);
  }
}
function autoSizeColumns({ colAutosize, visibleCols }, keysOrParams, skipHeader) {
  if (Array.isArray(keysOrParams)) {
    colAutosize?.autoSizeCols({ colKeys: keysOrParams, skipHeader, source: "api" });
  } else {
    colAutosize?.autoSizeCols({
      ...keysOrParams,
      colKeys: keysOrParams.colIds ?? visibleCols.allCols,
      source: "api"
    });
  }
}
function autoSizeAllColumns(beans, paramsOrSkipHeader) {
  if (paramsOrSkipHeader && typeof paramsOrSkipHeader === "object") {
    autoSizeColumns(beans, paramsOrSkipHeader);
  } else {
    beans.colAutosize?.autoSizeAllColumns({ source: "api", skipHeader: paramsOrSkipHeader });
  }
}
var ColumnAutosizeService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "colAutosize";
    this.timesDelayed = 0;
    this.shouldQueueResizeOperations = false;
    this.resizeOperationQueue = [];
  }
  postConstruct() {
    const { gos } = this;
    const autoSizeStrategy = gos.get("autoSizeStrategy");
    if (autoSizeStrategy) {
      let shouldHideColumns = false;
      const type = autoSizeStrategy.type;
      if (type === "fitGridWidth" || type === "fitProvidedWidth") {
        shouldHideColumns = true;
      } else if (type === "fitCellContents") {
        this.addManagedEventListeners({ firstDataRendered: () => this.onFirstDataRendered(autoSizeStrategy) });
        const rowData = gos.get("rowData");
        shouldHideColumns = rowData != null && rowData.length > 0 && _isClientSideRowModel(gos);
      }
      if (shouldHideColumns) {
        this.beans.colDelayRenderSvc?.hideColumns(type);
      }
    }
  }
  autoSizeCols(params) {
    const { eventSvc, visibleCols } = this.beans;
    this.innerAutoSizeCols(params).then((columnsAutoSized) => {
      const dispatch = (cols) => dispatchColumnResizedEvent(eventSvc, Array.from(cols), true, "autosizeColumns");
      if (!params.scaleUpToFitGridWidth) {
        return dispatch(columnsAutoSized);
      }
      const availableGridWidth = getAvailableWidth(this.beans);
      const isLeftCol = (col) => visibleCols.leftCols.some((leftCol) => _columnsMatch(leftCol, col));
      const isRightCol = (col) => visibleCols.rightCols.some((rightCol) => _columnsMatch(rightCol, col));
      const colKeys = params.colKeys.filter(
        (col) => !isColumnSelectionCol(col) && !isRowNumberCol(col) && !isLeftCol(col) && !isRightCol(col)
      );
      this.sizeColumnsToFit(availableGridWidth, params.source, true, {
        defaultMaxWidth: params.defaultMaxWidth,
        defaultMinWidth: params.defaultMinWidth,
        columnLimits: params.columnLimits?.map((limit) => ({ ...limit, key: limit.colId })),
        colKeys,
        onlyScaleUp: true
      });
      dispatch(columnsAutoSized);
    });
  }
  innerAutoSizeCols(params) {
    return new Promise((resolve2, reject) => {
      if (this.shouldQueueResizeOperations) {
        return this.pushResizeOperation(() => this.innerAutoSizeCols(params).then(resolve2, reject));
      }
      const {
        colKeys,
        skipHeader,
        skipHeaderGroups,
        stopAtGroup,
        defaultMaxWidth,
        defaultMinWidth,
        columnLimits = [],
        source: source2 = "api"
      } = params;
      const { animationFrameSvc, renderStatus, colModel, autoWidthCalc, visibleCols } = this.beans;
      animationFrameSvc?.flushAllFrames();
      if (this.timesDelayed < 5 && renderStatus && (!renderStatus.areHeaderCellsRendered() || !renderStatus.areCellsRendered())) {
        this.timesDelayed++;
        setTimeout(() => {
          if (this.isAlive()) {
            this.innerAutoSizeCols(params).then(resolve2, reject);
          }
        });
        return;
      }
      this.timesDelayed = 0;
      const columnsAutoSized = /* @__PURE__ */ new Set();
      let changesThisTimeAround = -1;
      const columnLimitsIndex = Object.fromEntries(
        columnLimits.map(({ colId, ...dimensions }) => [colId, dimensions])
      );
      const shouldSkipHeader = skipHeader ?? this.gos.get("skipHeaderOnAutoSize");
      const shouldSkipHeaderGroups = skipHeaderGroups ?? shouldSkipHeader;
      while (changesThisTimeAround !== 0) {
        changesThisTimeAround = 0;
        const updatedColumns = [];
        for (const key2 of colKeys) {
          if (!key2 || isSpecialCol(key2)) {
            continue;
          }
          const column2 = colModel.getCol(key2);
          if (!column2 || columnsAutoSized.has(column2)) {
            continue;
          }
          const preferredWidth = autoWidthCalc.getPreferredWidthForColumn(column2, shouldSkipHeader);
          if (preferredWidth > 0) {
            const columnLimit = columnLimitsIndex[column2.colId] ?? {};
            columnLimit.minWidth ?? (columnLimit.minWidth = defaultMinWidth);
            columnLimit.maxWidth ?? (columnLimit.maxWidth = defaultMaxWidth);
            const newWidth = normaliseColumnWidth(column2, preferredWidth, columnLimit);
            column2.setActualWidth(newWidth, source2);
            columnsAutoSized.add(column2);
            changesThisTimeAround++;
          }
          updatedColumns.push(column2);
        }
        if (updatedColumns.length) {
          visibleCols.refresh(source2);
        }
      }
      if (!shouldSkipHeaderGroups) {
        this.autoSizeColumnGroupsByColumns(colKeys, source2, stopAtGroup);
      }
      resolve2(columnsAutoSized);
    });
  }
  autoSizeColumn(key2, source2, skipHeader) {
    this.autoSizeCols({ colKeys: [key2], skipHeader, skipHeaderGroups: true, source: source2 });
  }
  autoSizeColumnGroupsByColumns(keys2, source2, stopAtGroup) {
    const { colModel, ctrlsSvc } = this.beans;
    const columnGroups = /* @__PURE__ */ new Set();
    const columns2 = colModel.getColsForKeys(keys2);
    for (const col of columns2) {
      let parent = col.getParent();
      while (parent && parent != stopAtGroup) {
        if (!parent.isPadding()) {
          columnGroups.add(parent);
        }
        parent = parent.getParent();
      }
    }
    let headerGroupCtrl;
    for (const columnGroup of columnGroups) {
      for (const headerContainerCtrl of ctrlsSvc.getHeaderRowContainerCtrls()) {
        headerGroupCtrl = headerContainerCtrl.getHeaderCtrlForColumn(columnGroup);
        if (headerGroupCtrl) {
          break;
        }
      }
      headerGroupCtrl?.resizeLeafColumnsToFit(source2);
    }
  }
  autoSizeAllColumns(params) {
    if (this.shouldQueueResizeOperations) {
      this.pushResizeOperation(() => this.autoSizeAllColumns(params));
      return;
    }
    this.autoSizeCols({ colKeys: this.beans.visibleCols.allCols, ...params });
  }
  addColumnAutosizeListeners(element, column2) {
    const skipHeaderOnAutoSize = this.gos.get("skipHeaderOnAutoSize");
    const autoSizeColListener = () => {
      this.autoSizeColumn(column2, "uiColumnResized", skipHeaderOnAutoSize);
    };
    element.addEventListener("dblclick", autoSizeColListener);
    const touchListener = new TouchListener(element);
    touchListener.addEventListener("doubleTap", autoSizeColListener);
    return () => {
      element.removeEventListener("dblclick", autoSizeColListener);
      touchListener.destroy();
    };
  }
  addColumnGroupResize(element, columnGroup, callback) {
    const skipHeaderOnAutoSize = this.gos.get("skipHeaderOnAutoSize");
    const listener = () => {
      const keys2 = [];
      const leafCols = columnGroup.getDisplayedLeafColumns();
      for (const column2 of leafCols) {
        if (!column2.getColDef().suppressAutoSize) {
          keys2.push(column2.getColId());
        }
      }
      if (keys2.length > 0) {
        this.autoSizeCols({
          colKeys: keys2,
          skipHeader: skipHeaderOnAutoSize,
          stopAtGroup: columnGroup,
          source: "uiColumnResized"
        });
      }
      callback();
    };
    element.addEventListener("dblclick", listener);
    return () => element.removeEventListener("dblclick", listener);
  }
  // method will call itself if no available width. this covers if the grid
  // isn't visible, but is just about to be visible.
  sizeColumnsToFitGridBody(params, nextTimeout) {
    if (!this.isAlive()) {
      return;
    }
    const availableWidth = getAvailableWidth(this.beans);
    if (availableWidth > 0) {
      this.sizeColumnsToFit(availableWidth, "sizeColumnsToFit", false, params);
      return;
    }
    if (nextTimeout === void 0) {
      window.setTimeout(() => {
        this.sizeColumnsToFitGridBody(params, 100);
      }, 0);
    } else if (nextTimeout === 100) {
      window.setTimeout(() => {
        this.sizeColumnsToFitGridBody(params, 500);
      }, 100);
    } else if (nextTimeout === 500) {
      window.setTimeout(() => {
        this.sizeColumnsToFitGridBody(params, -1);
      }, 500);
    } else {
      _warn(29);
    }
  }
  // called from api
  sizeColumnsToFit(gridWidth, source2 = "sizeColumnsToFit", silent, params) {
    if (this.shouldQueueResizeOperations) {
      this.pushResizeOperation(() => this.sizeColumnsToFit(gridWidth, source2, silent, params));
      return;
    }
    const limitsMap = {};
    for (const { key: key2, ...dimensions } of params?.columnLimits ?? []) {
      limitsMap[typeof key2 === "string" ? key2 : key2.getColId()] = dimensions;
    }
    const allDisplayedColumns = this.beans.visibleCols.allCols;
    if (gridWidth <= 0 || !allDisplayedColumns.length) {
      return;
    }
    const currentTotalColumnWidth = getWidthOfColsInList(allDisplayedColumns);
    if (params?.onlyScaleUp && currentTotalColumnWidth > gridWidth) {
      return;
    }
    const doColumnsAlreadyFit = gridWidth === currentTotalColumnWidth;
    if (doColumnsAlreadyFit) {
      const doAllColumnsSatisfyConstraints = allDisplayedColumns.every((column2) => {
        if (column2.colDef.suppressSizeToFit) {
          return true;
        }
        const widthOverride = limitsMap?.[column2.getId()];
        const minWidth = widthOverride?.minWidth ?? params?.defaultMinWidth;
        const maxWidth = widthOverride?.maxWidth ?? params?.defaultMaxWidth;
        const colWidth = column2.getActualWidth();
        return (minWidth == null || colWidth >= minWidth) && (maxWidth == null || colWidth <= maxWidth);
      });
      if (doAllColumnsSatisfyConstraints) {
        return;
      }
    }
    const colsToSpread = [];
    const colsToNotSpread = [];
    for (const column2 of allDisplayedColumns) {
      const isIncluded = params?.colKeys?.some((key2) => _columnsMatch(column2, key2)) ?? true;
      if (column2.getColDef().suppressSizeToFit || !isIncluded) {
        colsToNotSpread.push(column2);
      } else {
        colsToSpread.push(column2);
      }
    }
    const colsToDispatchEventFor = colsToSpread.slice(0);
    let finishedResizing = false;
    const moveToNotSpread = (column2) => {
      _removeFromArray(colsToSpread, column2);
      colsToNotSpread.push(column2);
    };
    for (const column2 of colsToSpread) {
      column2.resetActualWidth(source2);
      const widthOverride = limitsMap?.[column2.getId()];
      const minOverride = widthOverride?.minWidth ?? params?.defaultMinWidth;
      const maxOverride = widthOverride?.maxWidth ?? params?.defaultMaxWidth;
      const colWidth = column2.getActualWidth();
      if (typeof minOverride === "number" && colWidth < minOverride) {
        column2.setActualWidth(minOverride, source2, true);
      } else if (typeof maxOverride === "number" && colWidth > maxOverride) {
        column2.setActualWidth(maxOverride, source2, true);
      }
    }
    while (!finishedResizing) {
      finishedResizing = true;
      const availablePixels = gridWidth - getWidthOfColsInList(colsToNotSpread);
      if (availablePixels <= 0) {
        for (const column2 of colsToSpread) {
          const newWidth = limitsMap?.[column2.getId()]?.minWidth ?? params?.defaultMinWidth ?? column2.minWidth;
          column2.setActualWidth(newWidth, source2, true);
        }
      } else {
        const scale = availablePixels / getWidthOfColsInList(colsToSpread);
        let pixelsForLastCol = availablePixels;
        for (let i2 = colsToSpread.length - 1; i2 >= 0; i2--) {
          const column2 = colsToSpread[i2];
          const widthOverride = limitsMap?.[column2.getId()];
          const minOverride = widthOverride?.minWidth ?? params?.defaultMinWidth;
          const maxOverride = widthOverride?.maxWidth ?? params?.defaultMaxWidth;
          const colMinWidth = column2.getMinWidth();
          const colMaxWidth = column2.getMaxWidth();
          const minWidth = typeof minOverride === "number" && minOverride > colMinWidth ? minOverride : colMinWidth;
          const maxWidth = typeof maxOverride === "number" && maxOverride < colMaxWidth ? maxOverride : colMaxWidth;
          let newWidth = Math.round(column2.getActualWidth() * scale);
          if (newWidth < minWidth) {
            newWidth = minWidth;
            moveToNotSpread(column2);
            finishedResizing = false;
          } else if (newWidth > maxWidth) {
            newWidth = maxWidth;
            moveToNotSpread(column2);
            finishedResizing = false;
          } else if (i2 === 0) {
            newWidth = pixelsForLastCol;
          }
          column2.setActualWidth(newWidth, source2, true);
          pixelsForLastCol -= newWidth;
        }
      }
    }
    for (const col of colsToDispatchEventFor) {
      col.fireColumnWidthChangedEvent(source2);
    }
    const visibleCols = this.beans.visibleCols;
    visibleCols.setLeftValues(source2);
    visibleCols.updateBodyWidths();
    if (silent) {
      return;
    }
    dispatchColumnResizedEvent(this.eventSvc, colsToDispatchEventFor, true, source2);
  }
  applyAutosizeStrategy() {
    const { gos, colDelayRenderSvc } = this.beans;
    const autoSizeStrategy = gos.get("autoSizeStrategy");
    if (autoSizeStrategy?.type !== "fitGridWidth" && autoSizeStrategy?.type !== "fitProvidedWidth") {
      return;
    }
    setTimeout(() => {
      if (!this.isAlive()) {
        return;
      }
      const type = autoSizeStrategy.type;
      if (type === "fitGridWidth") {
        const { columnLimits: propColumnLimits, defaultMinWidth, defaultMaxWidth } = autoSizeStrategy;
        const columnLimits = propColumnLimits?.map(({ colId: key2, minWidth, maxWidth }) => ({
          key: key2,
          minWidth,
          maxWidth
        }));
        this.sizeColumnsToFitGridBody({
          defaultMinWidth,
          defaultMaxWidth,
          columnLimits
        });
      } else if (type === "fitProvidedWidth") {
        this.sizeColumnsToFit(autoSizeStrategy.width, "sizeColumnsToFit");
      }
      colDelayRenderSvc?.revealColumns(type);
    });
  }
  onFirstDataRendered({ colIds: colKeys, ...params }) {
    setTimeout(() => {
      if (!this.isAlive()) {
        return;
      }
      const source2 = "autosizeColumns";
      if (colKeys) {
        this.autoSizeCols({ ...params, source: source2, colKeys });
      } else {
        this.autoSizeAllColumns({ ...params, source: source2 });
      }
      this.beans.colDelayRenderSvc?.revealColumns(params.type);
    });
  }
  processResizeOperations() {
    this.shouldQueueResizeOperations = false;
    for (const resizeOperation of this.resizeOperationQueue) {
      resizeOperation();
    }
    this.resizeOperationQueue = [];
  }
  pushResizeOperation(func2) {
    this.resizeOperationQueue.push(func2);
  }
  destroy() {
    this.resizeOperationQueue.length = 0;
    super.destroy();
  }
};
function normaliseColumnWidth(column2, newWidth, limits = {}) {
  const minWidth = limits.minWidth ?? column2.getMinWidth();
  if (newWidth < minWidth) {
    newWidth = minWidth;
  }
  const maxWidth = limits.maxWidth ?? column2.getMaxWidth();
  if (newWidth > maxWidth) {
    newWidth = maxWidth;
  }
  return newWidth;
}
function getAvailableWidth({ ctrlsSvc, scrollVisibleSvc }) {
  const gridBodyCtrl = ctrlsSvc.getGridBodyCtrl();
  const removeScrollWidth = gridBodyCtrl.isVerticalScrollShowing();
  const scrollWidthToRemove = removeScrollWidth ? scrollVisibleSvc.getScrollbarWidth() : 0;
  const bodyViewportWidth = _getInnerWidth(gridBodyCtrl.eGridBody);
  return bodyViewportWidth - scrollWidthToRemove;
}
var ColumnAutoSizeModule = {
  moduleName: "ColumnAutoSize",
  version: VERSION,
  beans: [ColumnAutosizeService],
  apiFunctions: {
    sizeColumnsToFit,
    autoSizeColumns,
    autoSizeAllColumns
  },
  dependsOn: [AutoWidthModule]
};
var manualPinnedRowCSS = (
  /*css*/
  `.ag-row-pinned-source{background-color:var(--ag-pinned-source-row-background-color);color:var(--ag-pinned-source-row-text-color);font-weight:var(--ag-pinned-source-row-font-weight)}.ag-row-pinned-manual{background-color:var(--ag-pinned-row-background-color);color:var(--ag-pinned-row-text-color);font-weight:var(--ag-pinned-row-font-weight)}`
);
function getPinnedTopRowCount(beans) {
  return beans.pinnedRowModel?.getPinnedTopRowCount() ?? 0;
}
function getPinnedBottomRowCount(beans) {
  return beans.pinnedRowModel?.getPinnedBottomRowCount() ?? 0;
}
function getPinnedTopRow(beans, index) {
  return beans.pinnedRowModel?.getPinnedTopRow(index);
}
function getPinnedBottomRow(beans, index) {
  return beans.pinnedRowModel?.getPinnedBottomRow(index);
}
function forEachPinnedRow(beans, floating, callback) {
  return beans.pinnedRowModel?.forEachPinnedRow(floating, callback);
}
var PinnedRowModule = {
  moduleName: "PinnedRow",
  version: VERSION,
  beans: [PinnedRowModel],
  css: [manualPinnedRowCSS],
  apiFunctions: {
    getPinnedTopRowCount,
    getPinnedBottomRowCount,
    getPinnedTopRow,
    getPinnedBottomRow,
    forEachPinnedRow
  },
  icons: {
    rowPin: "pin",
    rowPinTop: "pinned-top",
    rowPinBottom: "pinned-bottom",
    rowUnpin: "un-pin"
  }
};
var CellSpan = class {
  constructor(col, firstNode) {
    this.col = col;
    this.firstNode = firstNode;
    this.cellSpan = true;
    this.spannedNodes = /* @__PURE__ */ new Set();
    this.addSpannedNode(firstNode);
  }
  /**
   * Reset the span leaving only the head.
   * Head is used as a comparison as this is the row used to render this cell
   * Even if the row data changes, the cell will properly reflect the correct value.
   */
  reset() {
    this.spannedNodes.clear();
    this.addSpannedNode(this.firstNode);
  }
  addSpannedNode(node2) {
    this.spannedNodes.add(node2);
    this.lastNode = node2;
  }
  getLastNode() {
    return this.lastNode;
  }
  getCellHeight() {
    return this.lastNode.rowTop + this.lastNode.rowHeight - this.firstNode.rowTop - 1;
  }
  doesSpanContain(cellPosition) {
    if (cellPosition.column !== this.col) {
      return false;
    }
    if (cellPosition.rowPinned != this.firstNode.rowPinned) {
      return false;
    }
    return this.firstNode.rowIndex <= cellPosition.rowIndex && cellPosition.rowIndex <= this.lastNode.rowIndex;
  }
  /**
   * Gets the auto height value for last node in the spanned cell.
   * The first node is used to store the auto height for the cell, but the additional height for this cell
   * needs applied to the last row in the span.
   */
  getLastNodeAutoHeight() {
    const autoHeight = this.firstNode.__autoHeights?.[this.col.getColId()];
    if (autoHeight == null) {
      return void 0;
    }
    let allButLastHeights = 0;
    for (const node2 of this.spannedNodes) {
      if (node2 === this.lastNode) {
        continue;
      }
      allButLastHeights += node2.rowHeight;
    }
    return autoHeight - allButLastHeights;
  }
};
var RowSpanCache = class extends BeanStub {
  constructor(column2) {
    super();
    this.column = column2;
  }
  buildCache(pinned) {
    const {
      column: column2,
      beans: { gos, pinnedRowModel, rowModel, valueSvc, pagination }
    } = this;
    const { colDef } = column2;
    const oldMap = this.getNodeMap(pinned);
    const newMap = /* @__PURE__ */ new Map();
    const isFullWidthCellFunc = gos.getCallback("isFullWidthRow");
    const equalsFnc = colDef.equals;
    const customCompare = colDef.spanRows;
    const isCustomCompare = typeof customCompare === "function";
    let lastNode = null;
    let spanData = null;
    let lastValue;
    const setNewHead = (node2, value2) => {
      lastNode = node2;
      spanData = null;
      lastValue = value2;
    };
    const checkNodeForCache = (node2) => {
      const doesNodeSupportSpanning = !node2.isExpandable() && !node2.group && !node2.detail && (isFullWidthCellFunc ? !isFullWidthCellFunc({ rowNode: node2 }) : true);
      if (node2.rowIndex == null || !doesNodeSupportSpanning) {
        setNewHead(null, null);
        return;
      }
      if (lastNode == null || node2.level !== lastNode.level || // no span across groups
      node2.footer || spanData && node2.rowIndex - 1 !== spanData?.getLastNode().rowIndex) {
        setNewHead(node2, valueSvc.getValue(column2, node2));
        return;
      }
      const value2 = valueSvc.getValue(column2, node2);
      if (isCustomCompare) {
        const params = _addGridCommonParams(gos, {
          valueA: lastValue,
          nodeA: lastNode,
          valueB: value2,
          nodeB: node2,
          column: column2,
          colDef
        });
        if (!customCompare(params)) {
          setNewHead(node2, value2);
          return;
        }
      } else if (equalsFnc ? !equalsFnc(lastValue, value2) : lastValue !== value2) {
        setNewHead(node2, value2);
        return;
      }
      if (!spanData) {
        const oldSpan = oldMap?.get(lastNode);
        if (oldSpan?.firstNode === lastNode) {
          oldSpan.reset();
          spanData = oldSpan;
        } else {
          spanData = new CellSpan(column2, lastNode);
        }
        newMap.set(lastNode, spanData);
      }
      spanData.addSpannedNode(node2);
      newMap.set(node2, spanData);
    };
    switch (pinned) {
      case "center":
        rowModel.forEachDisplayedNode?.((node2) => {
          const isNodeInPage = !pagination || pagination.isRowInPage(node2.rowIndex);
          if (!isNodeInPage) {
            return;
          }
          checkNodeForCache(node2);
        });
        this.centerValueNodeMap = newMap;
        break;
      case "top":
        pinnedRowModel?.forEachPinnedRow("top", checkNodeForCache);
        this.topValueNodeMap = newMap;
        break;
      case "bottom":
        pinnedRowModel?.forEachPinnedRow("bottom", checkNodeForCache);
        this.bottomValueNodeMap = newMap;
        break;
    }
  }
  isCellSpanning(node2) {
    return !!this.getCellSpan(node2);
  }
  getCellSpan(node2) {
    return this.getNodeMap(node2.rowPinned).get(node2);
  }
  getNodeMap(container2) {
    switch (container2) {
      case "top":
        return this.topValueNodeMap;
      case "bottom":
        return this.bottomValueNodeMap;
      default:
        return this.centerValueNodeMap;
    }
  }
};
var RowSpanService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "rowSpanSvc";
    this.spanningColumns = /* @__PURE__ */ new Map();
    this.debouncePinnedEvent = _debounce(this, this.dispatchCellsUpdatedEvent.bind(this, true), 0);
    this.debounceModelEvent = _debounce(this, this.dispatchCellsUpdatedEvent.bind(this, false), 0);
    this.pinnedTimeout = null;
    this.modelTimeout = null;
  }
  postConstruct() {
    const onRowDataUpdated = this.onRowDataUpdated.bind(this);
    const buildPinnedCaches = this.buildPinnedCaches.bind(this);
    this.addManagedEventListeners({
      paginationChanged: this.buildModelCaches.bind(this),
      pinnedRowDataChanged: buildPinnedCaches,
      pinnedRowsChanged: buildPinnedCaches,
      rowNodeDataChanged: onRowDataUpdated,
      cellValueChanged: onRowDataUpdated
    });
  }
  /**
   * When a new column is created with spanning (or spanning changes for a column)
   * @param column column that is now spanning
   */
  register(column2) {
    const { gos } = this.beans;
    if (!gos.get("enableCellSpan")) {
      return;
    }
    if (this.spanningColumns.has(column2)) {
      return;
    }
    const cache = this.createManagedBean(new RowSpanCache(column2));
    this.spanningColumns.set(column2, cache);
    cache.buildCache("top");
    cache.buildCache("bottom");
    cache.buildCache("center");
    this.debouncePinnedEvent();
    this.debounceModelEvent();
  }
  dispatchCellsUpdatedEvent(pinned) {
    this.dispatchLocalEvent({ type: "spannedCellsUpdated", pinned });
  }
  /**
   * When a new column is destroyed with spanning (or spanning changes for a column)
   * @param column column that is now spanning
   */
  deregister(column2) {
    this.spanningColumns.delete(column2);
  }
  // called when data changes, as this could be a hot path it's debounced
  // it uses timeouts instead of debounce so that it can be cancelled by `modelUpdated`
  // which is expected to run immediately (to exec before the rowRenderer)
  onRowDataUpdated({ node: node2 }) {
    const { spannedRowRenderer } = this.beans;
    if (node2.rowPinned) {
      if (this.pinnedTimeout != null) {
        return;
      }
      this.pinnedTimeout = window.setTimeout(() => {
        this.pinnedTimeout = null;
        this.buildPinnedCaches();
        spannedRowRenderer?.createCtrls("top");
        spannedRowRenderer?.createCtrls("bottom");
      }, 0);
      return;
    }
    if (this.modelTimeout != null) {
      return;
    }
    this.modelTimeout = window.setTimeout(() => {
      this.modelTimeout = null;
      this.buildModelCaches();
      spannedRowRenderer?.createCtrls("center");
    }, 0);
  }
  buildModelCaches() {
    if (this.modelTimeout != null) {
      clearTimeout(this.modelTimeout);
    }
    this.spanningColumns.forEach((cache) => cache.buildCache("center"));
    this.debounceModelEvent();
  }
  buildPinnedCaches() {
    if (this.pinnedTimeout != null) {
      clearTimeout(this.pinnedTimeout);
    }
    this.spanningColumns.forEach((cache) => {
      cache.buildCache("top");
      cache.buildCache("bottom");
    });
    this.debouncePinnedEvent();
  }
  isCellSpanning(col, rowNode) {
    const cache = this.spanningColumns.get(col);
    if (!cache) {
      return false;
    }
    return cache.isCellSpanning(rowNode);
  }
  getCellSpanByPosition(position) {
    const { pinnedRowModel, rowModel } = this.beans;
    const col = position.column;
    const index = position.rowIndex;
    const cache = this.spanningColumns.get(col);
    if (!cache) {
      return void 0;
    }
    let node2;
    switch (position.rowPinned) {
      case "top":
        node2 = pinnedRowModel?.getPinnedTopRow(index);
        break;
      case "bottom":
        node2 = pinnedRowModel?.getPinnedBottomRow(index);
        break;
      default:
        node2 = rowModel.getRow(index);
    }
    if (!node2) {
      return void 0;
    }
    return cache.getCellSpan(node2);
  }
  getCellStart(position) {
    const span = this.getCellSpanByPosition(position);
    if (!span) {
      return position;
    }
    return { ...position, rowIndex: span.firstNode.rowIndex };
  }
  getCellEnd(position) {
    const span = this.getCellSpanByPosition(position);
    if (!span) {
      return position;
    }
    return { ...position, rowIndex: span.getLastNode().rowIndex };
  }
  /**
   * Look-up a spanned cell given a col and node as position indicators
   *
   * @param col a column to lookup a span at this position
   * @param rowNode a node that may be spanned at this position
   * @returns the CellSpan object if one exists
   */
  getCellSpan(col, rowNode) {
    const cache = this.spanningColumns.get(col);
    if (!cache) {
      return void 0;
    }
    return cache.getCellSpan(rowNode);
  }
  forEachSpannedColumn(rowNode, callback) {
    for (const [col, cache] of this.spanningColumns) {
      if (cache.isCellSpanning(rowNode)) {
        const spanningNode = cache.getCellSpan(rowNode);
        callback(col, spanningNode);
      }
    }
  }
  destroy() {
    super.destroy();
    this.spanningColumns.clear();
  }
};
var SpannedCellCtrl = class extends CellCtrl {
  constructor(cellSpan, rowCtrl, beans) {
    super(cellSpan.col, cellSpan.firstNode, beans, rowCtrl);
    this.cellSpan = cellSpan;
    this.SPANNED_CELL_CSS_CLASS = "ag-spanned-cell";
  }
  setComp(comp, eCell, eWrapper, eCellWrapper, printLayout, startEditing, compBean) {
    this.eWrapper = eWrapper;
    super.setComp(comp, eCell, eWrapper, eCellWrapper, printLayout, startEditing, compBean);
    this.setAriaRowSpan();
    this.refreshAriaRowIndex();
  }
  isCellSpanning() {
    return true;
  }
  getCellSpan() {
    return this.cellSpan;
  }
  /**
   * When cell is spanning, ensure row index is also available on the cell
   */
  refreshAriaRowIndex() {
    const { eGui, rowNode } = this;
    if (!eGui || rowNode.rowIndex == null) {
      return;
    }
    _setAriaRowIndex(eGui, rowNode.rowIndex);
  }
  /**
   * When cell is spanning, ensure row index is also available on the cell
   */
  setAriaRowSpan() {
    _setAriaRowSpan(this.eGui, this.cellSpan.spannedNodes.size);
  }
  // not ideal, for tabbing need to force the focused position
  setFocusedCellPosition(cellPos) {
    this.focusedCellPosition = cellPos;
  }
  getFocusedCellPosition() {
    return this.focusedCellPosition ?? this.cellPosition;
  }
  checkCellFocused() {
    const focusedCell = this.beans.focusSvc.getFocusedCell();
    return !!focusedCell && this.cellSpan.doesSpanContain(focusedCell);
  }
  applyStaticCssClasses() {
    super.applyStaticCssClasses();
    this.comp.toggleCss(this.SPANNED_CELL_CSS_CLASS, true);
  }
  onCellFocused(event) {
    const { beans } = this;
    if (_isCellFocusSuppressed(beans)) {
      this.focusedCellPosition = void 0;
      return;
    }
    const cellFocused = this.isCellFocused();
    if (!cellFocused) {
      this.focusedCellPosition = void 0;
    }
    if (event && cellFocused) {
      this.focusedCellPosition = {
        rowIndex: event.rowIndex,
        rowPinned: event.rowPinned,
        column: event.column
        // fix
      };
    }
    super.onCellFocused(event);
  }
  getRootElement() {
    return this.eWrapper;
  }
};
var SpannedRowCtrl = class extends RowCtrl {
  onRowIndexChanged() {
    super.onRowIndexChanged();
    for (const c2 of this.getAllCellCtrls()) {
      c2.refreshAriaRowIndex();
    }
  }
  getInitialRowClasses(_rowContainerType) {
    return ["ag-spanned-row"];
  }
  getNewCellCtrl(col) {
    const cellSpan = this.beans.rowSpanSvc?.getCellSpan(col, this.rowNode);
    if (!cellSpan) {
      return;
    }
    const firstRowOfSpan = cellSpan.firstNode !== this.rowNode;
    if (firstRowOfSpan) {
      return;
    }
    return new SpannedCellCtrl(cellSpan, this, this.beans);
  }
  isCorrectCtrlForSpan(cell2) {
    const cellSpan = this.beans.rowSpanSvc?.getCellSpan(cell2.column, this.rowNode);
    if (!cellSpan) {
      return false;
    }
    const firstRowOfSpan = cellSpan.firstNode !== this.rowNode;
    if (firstRowOfSpan) {
      return false;
    }
    return cell2.getCellSpan() === cellSpan;
  }
  /**
   * Below overrides are explicitly disabling styling and other unwanted behaviours for spannedRowCtrl
   */
  // row height should be 0 in spanned row - they're only included for purpose of aria
  onRowHeightChanged() {
  }
  // no styling spanned rows
  refreshFirstAndLastRowStyles() {
  }
  // no hover functionality for spanned rows
  addHoverFunctionality() {
  }
  resetHoveredStatus() {
  }
};
var SpannedRowRenderer = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "spannedRowRenderer";
    this.topCtrls = /* @__PURE__ */ new Map();
    this.bottomCtrls = /* @__PURE__ */ new Map();
    this.centerCtrls = /* @__PURE__ */ new Map();
  }
  postConstruct() {
    this.addManagedEventListeners({
      displayedRowsChanged: this.createAllCtrls.bind(this)
    });
  }
  createAllCtrls() {
    this.createCtrls("top");
    this.createCtrls("bottom");
    this.createCtrls("center");
  }
  /**
   * When displayed rows or cols change, the spanned cell ctrls need to update
   */
  createCtrls(ctrlsKey) {
    const { rowSpanSvc } = this.beans;
    const previousCtrls = this.getCtrlsMap(ctrlsKey);
    const previousCtrlsSize = previousCtrls.size;
    const rowCtrls = this.getAllRelevantRowControls(ctrlsKey);
    const newRowCtrls = /* @__PURE__ */ new Map();
    let hasNewSpans = false;
    for (const ctrl of rowCtrls) {
      if (!ctrl.isAlive()) {
        continue;
      }
      rowSpanSvc?.forEachSpannedColumn(ctrl.rowNode, (col, cellSpan) => {
        if (newRowCtrls.has(cellSpan.firstNode)) {
          return;
        }
        const existingCtrl = previousCtrls.get(cellSpan.firstNode);
        if (existingCtrl) {
          newRowCtrls.set(cellSpan.firstNode, existingCtrl);
          previousCtrls.delete(cellSpan.firstNode);
          return;
        }
        hasNewSpans = true;
        const newCtrl = new SpannedRowCtrl(cellSpan.firstNode, this.beans, false, false, false);
        newRowCtrls.set(cellSpan.firstNode, newCtrl);
      });
    }
    this.setCtrlsMap(ctrlsKey, newRowCtrls);
    const sameCount = newRowCtrls.size === previousCtrlsSize;
    if (!hasNewSpans && sameCount) {
      return;
    }
    for (const oldCtrl of previousCtrls.values()) {
      oldCtrl.destroyFirstPass(true);
      oldCtrl.destroySecondPass();
    }
    this.dispatchLocalEvent({
      type: `spannedRowsUpdated`,
      ctrlsKey
    });
  }
  // cannot use getAllRowCtrls as it returns this services row ctrls.
  getAllRelevantRowControls(ctrlsKey) {
    const { rowRenderer } = this.beans;
    switch (ctrlsKey) {
      case "top":
        return rowRenderer.topRowCtrls;
      case "bottom":
        return rowRenderer.bottomRowCtrls;
      case "center":
        return rowRenderer.allRowCtrls;
    }
  }
  getCellByPosition(cellPosition) {
    const { rowSpanSvc } = this.beans;
    const cellSpan = rowSpanSvc?.getCellSpanByPosition(cellPosition);
    if (!cellSpan) {
      return void 0;
    }
    const ctrl = this.getCtrlsMap(cellPosition.rowPinned).get(cellSpan.firstNode);
    if (!ctrl) {
      return void 0;
    }
    return ctrl.getAllCellCtrls().find((cellCtrl) => cellCtrl.column === cellPosition.column);
  }
  getCtrls(container2) {
    return [...this.getCtrlsMap(container2).values()];
  }
  destroyRowCtrls(container2) {
    for (const ctrl of this.getCtrlsMap(container2).values()) {
      ctrl.destroyFirstPass(true);
      ctrl.destroySecondPass();
    }
    this.setCtrlsMap(container2, /* @__PURE__ */ new Map());
  }
  getCtrlsMap(container2) {
    switch (container2) {
      case "top":
        return this.topCtrls;
      case "bottom":
        return this.bottomCtrls;
      default:
        return this.centerCtrls;
    }
  }
  setCtrlsMap(container2, map2) {
    switch (container2) {
      case "top":
        this.topCtrls = map2;
        break;
      case "bottom":
        this.bottomCtrls = map2;
        break;
      default:
        this.centerCtrls = map2;
        break;
    }
  }
  destroy() {
    super.destroy();
    this.destroyRowCtrls("top");
    this.destroyRowCtrls("bottom");
    this.destroyRowCtrls("center");
  }
};
var CellSpanModule = {
  moduleName: "CellSpan",
  version: VERSION,
  beans: [RowSpanService, SpannedRowRenderer]
};
var CellCustomStyleFeature = class extends BeanStub {
  constructor(cellCtrl, beans) {
    super();
    this.cellCtrl = cellCtrl;
    this.staticClasses = [];
    this.beans = beans;
    this.column = cellCtrl.column;
  }
  setComp(comp) {
    this.cellComp = comp;
    this.applyUserStyles();
    this.applyCellClassRules();
    this.applyClassesFromColDef();
  }
  applyCellClassRules() {
    const { column: column2, cellComp } = this;
    const colDef = column2.colDef;
    const cellClassRules = colDef.cellClassRules;
    const cellClassParams = this.getCellClassParams(column2, colDef);
    processClassRules(
      this.beans.expressionSvc,
      // if current was previous, skip
      cellClassRules === this.cellClassRules ? void 0 : this.cellClassRules,
      cellClassRules,
      cellClassParams,
      (className2) => cellComp.toggleCss(className2, true),
      (className2) => cellComp.toggleCss(className2, false)
    );
    this.cellClassRules = cellClassRules;
  }
  applyUserStyles() {
    const column2 = this.column;
    const colDef = column2.colDef;
    const cellStyle = colDef.cellStyle;
    if (!cellStyle) {
      return;
    }
    let styles2;
    if (typeof cellStyle === "function") {
      const cellStyleParams = this.getCellClassParams(column2, colDef);
      styles2 = cellStyle(cellStyleParams);
    } else {
      styles2 = cellStyle;
    }
    if (styles2) {
      this.cellComp.setUserStyles(styles2);
    }
  }
  applyClassesFromColDef() {
    const { column: column2, cellComp } = this;
    const colDef = column2.colDef;
    const cellClassParams = this.getCellClassParams(column2, colDef);
    for (const className2 of this.staticClasses) {
      cellComp.toggleCss(className2, false);
    }
    const newStaticClasses = this.beans.cellStyles.getStaticCellClasses(colDef, cellClassParams);
    this.staticClasses = newStaticClasses;
    for (const className2 of newStaticClasses) {
      cellComp.toggleCss(className2, true);
    }
  }
  getCellClassParams(column2, colDef) {
    const { value: value2, rowNode } = this.cellCtrl;
    return _addGridCommonParams(this.beans.gos, {
      value: value2,
      data: rowNode.data,
      node: rowNode,
      colDef,
      column: column2,
      rowIndex: rowNode.rowIndex
    });
  }
};
var CellStyleService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "cellStyles";
  }
  processAllCellClasses(colDef, params, onApplicableClass, onNotApplicableClass) {
    processClassRules(
      this.beans.expressionSvc,
      void 0,
      colDef.cellClassRules,
      params,
      onApplicableClass,
      onNotApplicableClass
    );
    this.processStaticCellClasses(colDef, params, onApplicableClass);
  }
  getStaticCellClasses(colDef, params) {
    const { cellClass } = colDef;
    if (!cellClass) {
      return [];
    }
    let classOrClasses;
    if (typeof cellClass === "function") {
      const cellClassFunc = cellClass;
      classOrClasses = cellClassFunc(params);
    } else {
      classOrClasses = cellClass;
    }
    if (typeof classOrClasses === "string") {
      classOrClasses = [classOrClasses];
    }
    return classOrClasses || [];
  }
  createCellCustomStyleFeature(ctrl, beans) {
    return new CellCustomStyleFeature(ctrl, beans);
  }
  processStaticCellClasses(colDef, params, onApplicableClass) {
    const classOrClasses = this.getStaticCellClasses(colDef, params);
    classOrClasses.forEach((cssClassItem) => {
      onApplicableClass(cssClassItem);
    });
  }
};
var CellStyleModule = {
  moduleName: "CellStyle",
  version: VERSION,
  beans: [CellStyleService]
};
var RowStyleModule = {
  moduleName: "RowStyle",
  version: VERSION,
  beans: [RowStyleService]
};
function isColumnHovered(beans, column2) {
  return !!beans.colHover?.isHovered(column2);
}
var HoverFeature = class extends BeanStub {
  constructor(columns2, element) {
    super();
    this.columns = columns2;
    this.element = element;
    this.destroyManagedListeners = [];
    this.enableFeature = (enabled) => {
      const { beans, gos, element: element2, columns: columns3 } = this;
      const colHover = beans.colHover;
      const active = enabled ?? !!gos.get("columnHoverHighlight");
      if (active) {
        this.destroyManagedListeners = this.addManagedElementListeners(element2, {
          mouseover: colHover.setMouseOver.bind(colHover, columns3),
          mouseout: colHover.clearMouseOver.bind(colHover)
        });
      } else {
        for (const fn3 of this.destroyManagedListeners) {
          fn3();
        }
        this.destroyManagedListeners = [];
      }
    };
  }
  postConstruct() {
    this.addManagedPropertyListener("columnHoverHighlight", ({ currentValue }) => {
      this.enableFeature(currentValue);
    });
    this.enableFeature();
  }
  destroy() {
    super.destroy();
    this.destroyManagedListeners = null;
  }
};
var CSS_COLUMN_HOVER = "ag-column-hover";
var ColumnHoverService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "colHover";
  }
  postConstruct() {
    this.addManagedPropertyListener("columnHoverHighlight", ({ currentValue }) => {
      if (!currentValue) {
        this.clearMouseOver();
      }
    });
  }
  setMouseOver(columns2) {
    this.updateState(columns2);
  }
  clearMouseOver() {
    this.updateState(null);
  }
  isHovered(column2) {
    if (!this.gos.get("columnHoverHighlight")) {
      return false;
    }
    const selectedColumns = this.selectedColumns;
    return !!selectedColumns && selectedColumns.indexOf(column2) >= 0;
  }
  addHeaderColumnHoverListener(compBean, comp, column2) {
    const listener = () => {
      const isHovered = this.isHovered(column2);
      comp.toggleCss("ag-column-hover", isHovered);
    };
    compBean.addManagedEventListeners({ columnHoverChanged: listener });
    listener();
  }
  onCellColumnHover(column2, cellComp) {
    if (!cellComp) {
      return;
    }
    const isHovered = this.isHovered(column2);
    cellComp.toggleCss(CSS_COLUMN_HOVER, isHovered);
  }
  addHeaderFilterColumnHoverListener(compBean, comp, column2, eGui) {
    this.createHoverFeature(compBean, [column2], eGui);
    const listener = () => {
      const hovered = this.isHovered(column2);
      comp.toggleCss("ag-column-hover", hovered);
    };
    compBean.addManagedEventListeners({ columnHoverChanged: listener });
    listener();
  }
  createHoverFeature(compBean, columns2, eGui) {
    compBean.createManagedBean(new HoverFeature(columns2, eGui));
  }
  updateState(columns2) {
    this.selectedColumns = columns2;
    this.eventSvc.dispatchEvent({
      type: "columnHoverChanged"
    });
  }
};
var ColumnHoverModule = {
  moduleName: "ColumnHover",
  version: VERSION,
  beans: [ColumnHoverService],
  apiFunctions: {
    isColumnHovered
  }
};
var ApiEventService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "apiEventSvc";
    this.syncListeners = /* @__PURE__ */ new Map();
    this.asyncListeners = /* @__PURE__ */ new Map();
    this.syncGlobalListeners = /* @__PURE__ */ new Set();
    this.globalListenerPairs = /* @__PURE__ */ new Map();
  }
  postConstruct() {
    this.wrapSvc = this.beans.frameworkOverrides.createGlobalEventListenerWrapper?.();
  }
  addListener(eventType, userListener) {
    const listener = this.wrapSvc?.wrap(eventType, userListener) ?? userListener;
    const async = !ALWAYS_SYNC_GLOBAL_EVENTS.has(eventType);
    const listeners = async ? this.asyncListeners : this.syncListeners;
    if (!listeners.has(eventType)) {
      listeners.set(eventType, /* @__PURE__ */ new Set());
    }
    listeners.get(eventType).add(listener);
    this.eventSvc.addListener(eventType, listener, async);
  }
  removeListener(eventType, userListener) {
    const listener = this.wrapSvc?.unwrap(eventType, userListener) ?? userListener;
    const asyncListeners = this.asyncListeners.get(eventType);
    const hasAsync = !!asyncListeners?.delete(listener);
    if (!hasAsync) {
      this.syncListeners.get(eventType)?.delete(listener);
    }
    this.eventSvc.removeListener(eventType, listener, hasAsync);
  }
  addGlobalListener(userListener) {
    const listener = this.wrapSvc?.wrapGlobal(userListener) ?? userListener;
    const syncListener = (eventType, event) => {
      if (ALWAYS_SYNC_GLOBAL_EVENTS.has(eventType)) {
        listener(eventType, event);
      }
    };
    const asyncListener = (eventType, event) => {
      if (!ALWAYS_SYNC_GLOBAL_EVENTS.has(eventType)) {
        listener(eventType, event);
      }
    };
    this.globalListenerPairs.set(userListener, { syncListener, asyncListener });
    const eventSvc = this.eventSvc;
    eventSvc.addGlobalListener(syncListener, false);
    eventSvc.addGlobalListener(asyncListener, true);
  }
  removeGlobalListener(userListener) {
    const { eventSvc, wrapSvc, globalListenerPairs } = this;
    const listener = wrapSvc?.unwrapGlobal(userListener) ?? userListener;
    const hasAsync = globalListenerPairs.has(listener);
    if (hasAsync) {
      const { syncListener, asyncListener } = globalListenerPairs.get(listener);
      eventSvc.removeGlobalListener(syncListener, false);
      eventSvc.removeGlobalListener(asyncListener, true);
      globalListenerPairs.delete(userListener);
    } else {
      this.syncGlobalListeners.delete(listener);
      eventSvc.removeGlobalListener(listener, false);
    }
  }
  destroyEventListeners(map2, async) {
    map2.forEach((listeners, eventType) => {
      listeners.forEach((listener) => this.eventSvc.removeListener(eventType, listener, async));
      listeners.clear();
    });
    map2.clear();
  }
  destroyGlobalListeners(set3, async) {
    for (const listener of set3) {
      this.eventSvc.removeGlobalListener(listener, async);
    }
    set3.clear();
  }
  destroy() {
    super.destroy();
    this.destroyEventListeners(this.syncListeners, false);
    this.destroyEventListeners(this.asyncListeners, true);
    this.destroyGlobalListeners(this.syncGlobalListeners, false);
    const { globalListenerPairs, eventSvc } = this;
    globalListenerPairs.forEach(({ syncListener, asyncListener }) => {
      eventSvc.removeGlobalListener(syncListener, false);
      eventSvc.removeGlobalListener(asyncListener, true);
    });
    globalListenerPairs.clear();
  }
};
function addEventListener(beans, eventType, listener) {
  beans.apiEventSvc?.addListener(eventType, listener);
}
function removeEventListener(beans, eventType, listener) {
  beans.apiEventSvc?.removeListener(eventType, listener);
}
function addGlobalListener(beans, listener) {
  beans.apiEventSvc?.addGlobalListener(listener);
}
function removeGlobalListener(beans, listener) {
  beans.apiEventSvc?.removeGlobalListener(listener);
}
var EventApiModule = {
  moduleName: "EventApi",
  version: VERSION,
  apiFunctions: {
    addEventListener,
    addGlobalListener,
    removeEventListener,
    removeGlobalListener
  },
  beans: [ApiEventService]
};
var LocaleModule = {
  moduleName: "Locale",
  version: VERSION,
  beans: [LocaleService]
};
var RowAutoHeightService = class extends BeanStub {
  constructor() {
    super(...arguments);
    this.beanName = "rowAutoHeight";
    this.wasEverActive = false;
    this._debouncedCalculateRowHeights = _debounce(this, this.calculateRowHeights.bind(this), 1);
  }
  /**
   * If row height has been active, request a refresh of the row heights.
   */
  requestCheckAutoHeight() {
    if (!this.wasEverActive) {
      return;
    }
    this._debouncedCalculateRowHeights();
  }
  calculateRowHeights() {
    const { visibleCols, rowModel, rowSpanSvc, pinnedRowModel } = this.beans;
    const displayedAutoHeightCols = visibleCols.autoHeightCols;
    let anyNodeChanged = false;
    const updateDisplayedRowHeights = (row2) => {
      const autoHeights = row2.__autoHeights;
      let newRowHeight = _getRowHeightForNode(this.beans, row2).height;
      for (const col of displayedAutoHeightCols) {
        let cellHeight = autoHeights?.[col.getColId()];
        const spannedCell = rowSpanSvc?.getCellSpan(col, row2);
        if (spannedCell) {
          if (spannedCell.getLastNode() !== row2) {
            continue;
          }
          cellHeight = rowSpanSvc?.getCellSpan(col, row2)?.getLastNodeAutoHeight();
          if (!cellHeight) {
            return;
          }
        }
        if (cellHeight == null) {
          if (this.colSpanSkipCell(col, row2)) {
            continue;
          }
          return;
        }
        newRowHeight = Math.max(cellHeight, newRowHeight);
      }
      if (newRowHeight !== row2.rowHeight) {
        row2.setRowHeight(newRowHeight);
        anyNodeChanged = true;
      }
    };
    pinnedRowModel?.forEachPinnedRow?.("top", updateDisplayedRowHeights);
    pinnedRowModel?.forEachPinnedRow?.("bottom", updateDisplayedRowHeights);
    rowModel.forEachDisplayedNode?.(updateDisplayedRowHeights);
    if (anyNodeChanged) {
      rowModel.onRowHeightChanged?.();
    }
  }
  /**
   * Set the cell height into the row node, and request a refresh of the row heights if there's been a change.
   * @param rowNode the node to set the auto height on
   * @param cellHeight the height to set, undefined if the cell has just been destroyed
   * @param column the column of the cell
   */
  setRowAutoHeight(rowNode, cellHeight, column2) {
    rowNode.__autoHeights ?? (rowNode.__autoHeights = {});
    if (cellHeight == void 0) {
      delete rowNode.__autoHeights[column2.getId()];
      return;
    }
    const previousCellHeight = rowNode.__autoHeights[column2.getId()];
    rowNode.__autoHeights[column2.getId()] = cellHeight;
    if (previousCellHeight !== cellHeight) {
      this.requestCheckAutoHeight();
    }
  }
  /**
   * If using col span, then cells which have been spanned over do not need an auto height value
   * @param col the column of the cell
   * @param node the node of the cell
   * @returns whether the row needs auto height value for that column
   */
  colSpanSkipCell(col, node2) {
    const { colModel, colViewport, visibleCols } = this.beans;
    if (!colModel.colSpanActive) {
      return false;
    }
    let activeColsForRow = [];
    switch (col.getPinned()) {
      case "left":
        activeColsForRow = visibleCols.getLeftColsForRow(node2);
        break;
      case "right":
        activeColsForRow = visibleCols.getRightColsForRow(node2);
        break;
      case null:
        activeColsForRow = colViewport.getColsWithinViewport(node2);
        break;
    }
    return !activeColsForRow.includes(col);
  }
  /**
   * If required, sets up observers to continuously measure changes in the cell height.
   * @param cellCtrl the cellCtrl of the cell
   * @param eCellWrapper the HTMLElement to track the height of
   * @param compBean the component bean to add the destroy/cleanup function to
   * @returns whether or not auto height has been set up on this cell
   */
  setupCellAutoHeight(cellCtrl, eCellWrapper, compBean) {
    if (!cellCtrl.column.isAutoHeight() || !eCellWrapper) {
      return false;
    }
    this.wasEverActive = true;
    const eParentCell = eCellWrapper.parentElement;
    const { rowNode, column: column2 } = cellCtrl;
    const beans = this.beans;
    const measureHeight = (timesCalled) => {
      if (this.beans.editSvc?.isEditing(cellCtrl)) {
        return;
      }
      if (!cellCtrl.isAlive() || !compBean.isAlive()) {
        return;
      }
      const { paddingTop, paddingBottom, borderBottomWidth, borderTopWidth } = _getElementSize(eParentCell);
      const extraHeight = paddingTop + paddingBottom + borderBottomWidth + borderTopWidth;
      const wrapperHeight = eCellWrapper.offsetHeight;
      const autoHeight = wrapperHeight + extraHeight;
      if (timesCalled < 5) {
        const doc = _getDocument(beans);
        const notYetInDom = !doc?.contains(eCellWrapper);
        const possiblyNoContentYet = autoHeight == 0;
        if (notYetInDom || possiblyNoContentYet) {
          window.setTimeout(() => measureHeight(timesCalled + 1), 0);
          return;
        }
      }
      this.setRowAutoHeight(rowNode, autoHeight, column2);
    };
    const listener = () => measureHeight(0);
    listener();
    const destroyResizeObserver = _observeResize(beans, eCellWrapper, listener);
    compBean.addDestroyFunc(() => {
      destroyResizeObserver();
      this.setRowAutoHeight(rowNode, void 0, column2);
    });
    return true;
  }
  setAutoHeightActive(cols) {
    this.active = cols.list.some((col) => col.isVisible() && col.isAutoHeight());
  }
  /**
   * Determines if the row auto height service has cells to grow.
   * @returns true if all of the rendered rows are at least as tall as their rendered cells.
   */
  areRowsMeasured() {
    if (!this.active) {
      return true;
    }
    const rowCtrls = this.beans.rowRenderer.getAllRowCtrls();
    let renderedAutoHeightCols = null;
    for (const { rowNode } of rowCtrls) {
      if (!renderedAutoHeightCols || this.beans.colModel.colSpanActive) {
        const renderedCols = this.beans.colViewport.getColsWithinViewport(rowNode);
        renderedAutoHeightCols = renderedCols.filter((col) => col.isAutoHeight());
      }
      if (renderedAutoHeightCols.length === 0) {
        continue;
      }
      if (!rowNode.__autoHeights) {
        return false;
      }
      for (const col of renderedAutoHeightCols) {
        const cellHeight = rowNode.__autoHeights[col.getColId()];
        if (!cellHeight || rowNode.rowHeight < cellHeight) {
          return false;
        }
      }
    }
    return true;
  }
};
var RowAutoHeightModule = {
  moduleName: "RowAutoHeight",
  version: VERSION,
  beans: [RowAutoHeightService]
};
var AllCommunityModule = {
  moduleName: "AllCommunity",
  version: VERSION,
  dependsOn: [
    ClientSideRowModelModule,
    CsvExportModule,
    InfiniteRowModelModule,
    ValidationModule,
    TextEditorModule,
    NumberEditorModule,
    DateEditorModule,
    CheckboxEditorModule,
    SelectEditorModule,
    LargeTextEditorModule,
    CustomEditorModule,
    UndoRedoEditModule,
    TextFilterModule,
    NumberFilterModule,
    DateFilterModule,
    CustomFilterModule,
    QuickFilterModule,
    ExternalFilterModule,
    GridStateModule,
    AlignedGridsModule,
    PaginationModule,
    ColumnApiModule,
    RowApiModule,
    ScrollApiModule,
    RenderApiModule,
    ColumnAutoSizeModule,
    RowDragModule,
    PinnedRowModule,
    RowSelectionModule,
    ValueCacheModule,
    CellStyleModule,
    ColumnHoverModule,
    RowStyleModule,
    EventApiModule,
    CellApiModule,
    HighlightChangesModule,
    TooltipModule,
    LocaleModule,
    RowAutoHeightModule,
    DragAndDropModule,
    ClientSideRowModelApiModule,
    CellSpanModule
  ]
};
var BeansContext = React20.createContext({});
var RenderModeContext = React20.createContext("default");
var showJsComp = (compDetails, context, eParent, ref2) => {
  const doNothing = !compDetails || compDetails.componentFromFramework || context.isDestroyed();
  if (doNothing) {
    return;
  }
  const promise = compDetails.newAgStackInstance();
  let comp;
  let compGui;
  let destroyed = false;
  promise.then((c2) => {
    if (destroyed) {
      context.destroyBean(c2);
      return;
    }
    comp = c2;
    compGui = comp.getGui();
    eParent.appendChild(compGui);
    setRef(ref2, comp);
  });
  return () => {
    destroyed = true;
    if (!comp) {
      return;
    }
    compGui?.remove();
    context.destroyBean(comp);
    if (ref2) {
      setRef(ref2, void 0);
    }
  };
};
var setRef = (ref2, value2) => {
  if (!ref2) {
    return;
  }
  if (ref2 instanceof Function) {
    const refCallback = ref2;
    refCallback(value2);
  } else {
    const refObj = ref2;
    refObj.current = value2;
  }
};
var classesList = (...list2) => {
  const filtered = list2.filter((s) => s != null && s !== "");
  return filtered.join(" ");
};
var CssClasses = class _CssClasses {
  constructor(...initialClasses) {
    this.classesMap = {};
    for (const className2 of initialClasses) {
      this.classesMap[className2] = true;
    }
  }
  setClass(className2, on) {
    const nothingHasChanged = !!this.classesMap[className2] == on;
    if (nothingHasChanged) {
      return this;
    }
    const res = new _CssClasses();
    res.classesMap = { ...this.classesMap };
    res.classesMap[className2] = on;
    return res;
  }
  toString() {
    const res = Object.keys(this.classesMap).filter((key2) => this.classesMap[key2]).join(" ");
    return res;
  }
};
var isComponentStateless = (Component2) => {
  const hasSymbol = () => typeof Symbol === "function" && Symbol.for;
  const getMemoType = () => hasSymbol() ? Symbol.for("react.memo") : 60115;
  return typeof Component2 === "function" && !(Component2.prototype && Component2.prototype.isReactComponent) || typeof Component2 === "object" && Component2.$$typeof === getMemoType();
};
var reactVersion = React20.version?.split(".")[0];
var isReactVersion17Minus = reactVersion === "16" || reactVersion === "17";
function isReact19() {
  return reactVersion === "19";
}
var disableFlushSync = false;
function runWithoutFlushSync(func2) {
  if (!disableFlushSync) {
    setTimeout(() => disableFlushSync = false, 0);
  }
  disableFlushSync = true;
  return func2();
}
var agFlushSync = (useFlushSync, fn3) => {
  if (!isReactVersion17Minus && useFlushSync && !disableFlushSync) {
    ReactDOM.flushSync(fn3);
  } else {
    fn3();
  }
};
var agStartTransition = (fn3) => {
  if (!isReactVersion17Minus) {
    React20.startTransition(fn3);
  } else {
    fn3();
  }
};
function agUseSyncExternalStore(subscribe, getSnapshot, defaultSnapshot) {
  if (React20.useSyncExternalStore) {
    return React20.useSyncExternalStore(subscribe, getSnapshot);
  } else {
    return defaultSnapshot;
  }
}
function getNextValueIfDifferent(prev, next, maintainOrder) {
  if (next == null || prev == null) {
    return next;
  }
  if (prev === next || next.length === 0 && prev.length === 0) {
    return prev;
  }
  if (maintainOrder || prev.length === 0 && next.length > 0 || prev.length > 0 && next.length === 0) {
    return next;
  }
  const oldValues = [];
  const newValues = [];
  const prevMap = /* @__PURE__ */ new Map();
  const nextMap = /* @__PURE__ */ new Map();
  for (let i2 = 0; i2 < next.length; i2++) {
    const c2 = next[i2];
    nextMap.set(c2.instanceId, c2);
  }
  for (let i2 = 0; i2 < prev.length; i2++) {
    const c2 = prev[i2];
    prevMap.set(c2.instanceId, c2);
    if (nextMap.has(c2.instanceId)) {
      oldValues.push(c2);
    }
  }
  for (let i2 = 0; i2 < next.length; i2++) {
    const c2 = next[i2];
    const instanceId = c2.instanceId;
    if (!prevMap.has(instanceId)) {
      newValues.push(c2);
    }
  }
  if (oldValues.length === prev.length && newValues.length === 0) {
    return prev;
  }
  if (oldValues.length === 0 && newValues.length === next.length) {
    return next;
  }
  if (oldValues.length === 0) {
    return newValues;
  }
  if (newValues.length === 0) {
    return oldValues;
  }
  return [...oldValues, ...newValues];
}
var GroupCellRenderer = reactExports.forwardRef((props, ref2) => {
  const { registry, context } = reactExports.useContext(BeansContext);
  const eGui = reactExports.useRef(null);
  const eValueRef = reactExports.useRef(null);
  const eCheckboxRef = reactExports.useRef(null);
  const eExpandedRef = reactExports.useRef(null);
  const eContractedRef = reactExports.useRef(null);
  const ctrlRef = reactExports.useRef();
  const [innerCompDetails, setInnerCompDetails] = reactExports.useState();
  const [childCount, setChildCount] = reactExports.useState();
  const [value2, setValue] = reactExports.useState();
  const [cssClasses, setCssClasses] = reactExports.useState(() => new CssClasses());
  const [expandedCssClasses, setExpandedCssClasses] = reactExports.useState(() => new CssClasses("ag-hidden"));
  const [contractedCssClasses, setContractedCssClasses] = reactExports.useState(() => new CssClasses("ag-hidden"));
  const [checkboxCssClasses, setCheckboxCssClasses] = reactExports.useState(() => new CssClasses("ag-invisible"));
  reactExports.useImperativeHandle(ref2, () => {
    return {
      // force new instance when grid tries to refresh
      refresh() {
        return false;
      }
    };
  });
  reactExports.useLayoutEffect(() => {
    return showJsComp(innerCompDetails, context, eValueRef.current);
  }, [innerCompDetails]);
  const setRef2 = reactExports.useCallback((eRef) => {
    eGui.current = eRef;
    if (!eRef || context.isDestroyed()) {
      ctrlRef.current = context.destroyBean(ctrlRef.current);
      return;
    }
    const compProxy = {
      setInnerRenderer: (details, valueToDisplay) => {
        setInnerCompDetails(details);
        setValue(valueToDisplay);
      },
      setChildCount: (count2) => setChildCount(count2),
      toggleCss: (name2, on) => setCssClasses((prev) => prev.setClass(name2, on)),
      setContractedDisplayed: (displayed) => setContractedCssClasses((prev) => prev.setClass("ag-hidden", !displayed)),
      setExpandedDisplayed: (displayed) => setExpandedCssClasses((prev) => prev.setClass("ag-hidden", !displayed)),
      setCheckboxVisible: (visible2) => setCheckboxCssClasses((prev) => prev.setClass("ag-invisible", !visible2)),
      setCheckboxSpacing: (add2) => setCheckboxCssClasses((prev) => prev.setClass("ag-group-checkbox-spacing", add2))
    };
    const groupCellRendererCtrl = registry.createDynamicBean("groupCellRendererCtrl", true);
    if (groupCellRendererCtrl) {
      ctrlRef.current = context.createBean(groupCellRendererCtrl);
      ctrlRef.current.init(
        compProxy,
        eRef,
        eCheckboxRef.current,
        eExpandedRef.current,
        eContractedRef.current,
        GroupCellRenderer,
        props
      );
    }
  }, []);
  const className2 = reactExports.useMemo(() => `ag-cell-wrapper ${cssClasses.toString()}`, [cssClasses]);
  const expandedClassName = reactExports.useMemo(() => `ag-group-expanded ${expandedCssClasses.toString()}`, [expandedCssClasses]);
  const contractedClassName = reactExports.useMemo(
    () => `ag-group-contracted ${contractedCssClasses.toString()}`,
    [contractedCssClasses]
  );
  const checkboxClassName = reactExports.useMemo(() => `ag-group-checkbox ${checkboxCssClasses.toString()}`, [checkboxCssClasses]);
  const useFwRenderer = innerCompDetails?.componentFromFramework;
  const FwRenderer = useFwRenderer ? innerCompDetails.componentClass : void 0;
  const useValue = innerCompDetails == null && value2 != null;
  const escapedValue = _toString(value2);
  return /* @__PURE__ */ React20.createElement(
    "span",
    {
      className: className2,
      ref: setRef2,
      ...!props.colDef ? { role: ctrlRef.current?.getCellAriaRole() } : {}
    },
    /* @__PURE__ */ React20.createElement("span", { className: expandedClassName, ref: eExpandedRef }),
    /* @__PURE__ */ React20.createElement("span", { className: contractedClassName, ref: eContractedRef }),
    /* @__PURE__ */ React20.createElement("span", { className: checkboxClassName, ref: eCheckboxRef }),
    /* @__PURE__ */ React20.createElement("span", { className: "ag-group-value", ref: eValueRef }, useValue ? escapedValue : useFwRenderer ? /* @__PURE__ */ React20.createElement(FwRenderer, { ...innerCompDetails.params }) : null),
    /* @__PURE__ */ React20.createElement("span", { className: "ag-group-child-count" }, childCount)
  );
});
var groupCellRenderer_default = GroupCellRenderer;
var CustomContext = reactExports.createContext({
  setMethods: () => {
  }
});
var CustomWrapperComp = (params) => {
  const { initialProps, addUpdateCallback, CustomComponentClass, setMethods } = params;
  const [{ key: key2, ...props }, setProps] = reactExports.useState(initialProps);
  reactExports.useEffect(() => {
    addUpdateCallback((newProps) => setProps(newProps));
  }, []);
  return /* @__PURE__ */ React20.createElement(CustomContext.Provider, { value: { setMethods } }, /* @__PURE__ */ React20.createElement(CustomComponentClass, { key: key2, ...props }));
};
var customWrapperComp_default = reactExports.memo(CustomWrapperComp);
var counter = 0;
function generateNewKey() {
  return `agPortalKey_${++counter}`;
}
var ReactComponent = class {
  constructor(reactComponent, portalManager, componentType, suppressFallbackMethods) {
    this.portal = null;
    this.oldPortal = null;
    this.reactComponent = reactComponent;
    this.portalManager = portalManager;
    this.componentType = componentType;
    this.suppressFallbackMethods = !!suppressFallbackMethods;
    this.statelessComponent = this.isStateless(this.reactComponent);
    this.key = generateNewKey();
    this.portalKey = generateNewKey();
    this.instanceCreated = this.isStatelessComponent() ? AgPromise.resolve(false) : new AgPromise((resolve2) => {
      this.resolveInstanceCreated = resolve2;
    });
  }
  getGui() {
    return this.eParentElement;
  }
  /** `getGui()` returns the parent element. This returns the actual root element. */
  getRootElement() {
    const firstChild = this.eParentElement.firstChild;
    return firstChild;
  }
  destroy() {
    if (this.componentInstance && typeof this.componentInstance.destroy == "function") {
      this.componentInstance.destroy();
    }
    const portal = this.portal;
    if (portal) {
      this.portalManager.destroyPortal(portal);
    }
  }
  createParentElement(params) {
    const componentWrappingElement = this.portalManager.getComponentWrappingElement();
    const eParentElement = document.createElement(componentWrappingElement || "div");
    eParentElement.classList.add("ag-react-container");
    params.reactContainer = eParentElement;
    return eParentElement;
  }
  statelessComponentRendered() {
    return this.eParentElement.childElementCount > 0 || this.eParentElement.childNodes.length > 0;
  }
  getFrameworkComponentInstance() {
    return this.componentInstance;
  }
  isStatelessComponent() {
    return this.statelessComponent;
  }
  getReactComponentName() {
    return this.reactComponent.name;
  }
  getMemoType() {
    return this.hasSymbol() ? Symbol.for("react.memo") : 60115;
  }
  hasSymbol() {
    return typeof Symbol === "function" && Symbol.for;
  }
  isStateless(Component2) {
    return typeof Component2 === "function" && !(Component2.prototype && Component2.prototype.isReactComponent) || typeof Component2 === "object" && Component2.$$typeof === this.getMemoType();
  }
  hasMethod(name2) {
    const frameworkComponentInstance = this.getFrameworkComponentInstance();
    return !!frameworkComponentInstance && frameworkComponentInstance[name2] != null || this.fallbackMethodAvailable(name2);
  }
  callMethod(name2, args2) {
    const frameworkComponentInstance = this.getFrameworkComponentInstance();
    if (this.isStatelessComponent()) {
      return this.fallbackMethod(name2, !!args2 && args2[0] ? args2[0] : {});
    } else if (!frameworkComponentInstance) {
      setTimeout(() => this.callMethod(name2, args2));
      return;
    }
    const method = frameworkComponentInstance[name2];
    if (method) {
      return method.apply(frameworkComponentInstance, args2);
    }
    if (this.fallbackMethodAvailable(name2)) {
      return this.fallbackMethod(name2, !!args2 && args2[0] ? args2[0] : {});
    }
  }
  addMethod(name2, callback) {
    this[name2] = callback;
  }
  init(params) {
    this.eParentElement = this.createParentElement(params);
    this.createOrUpdatePortal(params);
    return new AgPromise((resolve2) => this.createReactComponent(resolve2));
  }
  createOrUpdatePortal(params) {
    if (!this.isStatelessComponent()) {
      this.ref = (element) => {
        this.componentInstance = element;
        this.resolveInstanceCreated?.(true);
        this.resolveInstanceCreated = void 0;
      };
      params.ref = this.ref;
    }
    this.reactElement = this.createElement(this.reactComponent, { ...params, key: this.key });
    this.portal = reactDomExports.createPortal(
      this.reactElement,
      this.eParentElement,
      this.portalKey
      // fixed deltaRowModeRefreshCompRenderer
    );
  }
  createElement(reactComponent, props) {
    return reactExports.createElement(reactComponent, props);
  }
  createReactComponent(resolve2) {
    this.portalManager.mountReactPortal(this.portal, this, resolve2);
  }
  rendered() {
    return this.isStatelessComponent() && this.statelessComponentRendered() || !!(!this.isStatelessComponent() && this.getFrameworkComponentInstance());
  }
  /*
   * fallback methods - these will be invoked if a corresponding instance method is not present
   * for example if refresh is called and is not available on the component instance, then refreshComponent on this
   * class will be invoked instead
   *
   * Currently only refresh is supported
   */
  refreshComponent(args2) {
    this.oldPortal = this.portal;
    this.createOrUpdatePortal(args2);
    this.portalManager.updateReactPortal(this.oldPortal, this.portal);
  }
  fallbackMethod(name2, params) {
    const method = this[`${name2}Component`];
    if (!this.suppressFallbackMethods && !!method) {
      return method.bind(this)(params);
    }
  }
  fallbackMethodAvailable(name2) {
    if (this.suppressFallbackMethods) {
      return false;
    }
    const method = this[`${name2}Component`];
    return !!method;
  }
};
function addOptionalMethods(optionalMethodNames, providedMethods, component) {
  for (const methodName of optionalMethodNames) {
    const providedMethod = providedMethods[methodName];
    if (providedMethod) {
      component[methodName] = providedMethod;
    }
  }
}
var CustomComponentWrapper = class extends ReactComponent {
  constructor() {
    super(...arguments);
    this.awaitUpdateCallback = new AgPromise((resolve2) => {
      this.resolveUpdateCallback = resolve2;
    });
    this.wrapperComponent = customWrapperComp_default;
  }
  init(params) {
    this.sourceParams = params;
    return super.init(this.getProps());
  }
  addMethod() {
  }
  getInstance() {
    return this.instanceCreated.then(() => this.componentInstance);
  }
  getFrameworkComponentInstance() {
    return this;
  }
  createElement(reactComponent, props) {
    return super.createElement(this.wrapperComponent, {
      initialProps: props,
      CustomComponentClass: reactComponent,
      setMethods: (methods) => this.setMethods(methods),
      addUpdateCallback: (callback) => {
        this.updateCallback = () => {
          callback(this.getProps());
          return new AgPromise((resolve2) => {
            setTimeout(() => {
              resolve2();
            });
          });
        };
        this.resolveUpdateCallback();
      }
    });
  }
  setMethods(methods) {
    this.providedMethods = methods;
    addOptionalMethods(this.getOptionalMethods(), this.providedMethods, this);
  }
  getOptionalMethods() {
    return [];
  }
  getProps() {
    return {
      ...this.sourceParams,
      key: this.key,
      ref: this.ref
    };
  }
  refreshProps() {
    if (this.updateCallback) {
      return this.updateCallback();
    }
    return new AgPromise(
      (resolve2) => this.awaitUpdateCallback.then(() => {
        this.updateCallback().then(() => resolve2());
      })
    );
  }
};
var CellRendererComponentWrapper = class extends CustomComponentWrapper {
  refresh(params) {
    this.sourceParams = params;
    this.refreshProps();
    return true;
  }
};
var DateComponentWrapper = class extends CustomComponentWrapper {
  constructor() {
    super(...arguments);
    this.date = null;
    this.onDateChange = (date2) => this.updateDate(date2);
  }
  getDate() {
    return this.date;
  }
  setDate(date2) {
    this.date = date2;
    this.refreshProps();
  }
  refresh(params) {
    this.sourceParams = params;
    this.refreshProps();
  }
  getOptionalMethods() {
    return ["afterGuiAttached", "setInputPlaceholder", "setInputAriaLabel", "setDisabled"];
  }
  updateDate(date2) {
    this.setDate(date2);
    this.sourceParams.onDateChanged();
  }
  getProps() {
    const props = super.getProps();
    props.date = this.date;
    props.onDateChange = this.onDateChange;
    delete props.onDateChanged;
    return props;
  }
};
var DragAndDropImageComponentWrapper = class extends CustomComponentWrapper {
  constructor() {
    super(...arguments);
    this.label = "";
    this.icon = null;
    this.shake = false;
  }
  setIcon(iconName, shake) {
    this.icon = iconName;
    this.shake = shake;
    this.refreshProps();
  }
  setLabel(label2) {
    this.label = label2;
    this.refreshProps();
  }
  getProps() {
    const props = super.getProps();
    const { label: label2, icon: icon2, shake } = this;
    props.label = label2;
    props.icon = icon2;
    props.shake = shake;
    return props;
  }
};
var FilterComponentWrapper = class extends CustomComponentWrapper {
  constructor() {
    super(...arguments);
    this.model = null;
    this.onModelChange = (model2) => this.updateModel(model2);
    this.onUiChange = () => this.sourceParams.filterModifiedCallback();
    this.expectingNewMethods = true;
    this.hasBeenActive = false;
    this.awaitSetMethodsCallback = new AgPromise((resolve2) => {
      this.resolveSetMethodsCallback = resolve2;
    });
  }
  isFilterActive() {
    return this.model != null;
  }
  doesFilterPass(params) {
    return this.providedMethods.doesFilterPass(params);
  }
  getModel() {
    return this.model;
  }
  setModel(model2) {
    this.expectingNewMethods = true;
    this.model = model2;
    this.hasBeenActive || (this.hasBeenActive = this.isFilterActive());
    return this.refreshProps();
  }
  refresh(newParams) {
    this.sourceParams = newParams;
    this.refreshProps();
    return true;
  }
  afterGuiAttached(params) {
    const providedMethods = this.providedMethods;
    if (!providedMethods) {
      this.awaitSetMethodsCallback.then(() => this.providedMethods?.afterGuiAttached?.(params));
    } else {
      providedMethods.afterGuiAttached?.(params);
    }
  }
  getOptionalMethods() {
    return ["afterGuiDetached", "onNewRowsLoaded", "getModelAsString", "onAnyFilterChanged"];
  }
  setMethods(methods) {
    if (this.expectingNewMethods === false && this.hasBeenActive && this.providedMethods?.doesFilterPass !== methods?.doesFilterPass) {
      setTimeout(() => {
        this.sourceParams.filterChangedCallback();
      });
    }
    this.expectingNewMethods = false;
    super.setMethods(methods);
    this.resolveSetMethodsCallback();
    this.resolveFilterPassCallback?.();
    this.resolveFilterPassCallback = void 0;
  }
  updateModel(model2) {
    this.resolveFilterPassCallback?.();
    const awaitFilterPassCallback = new AgPromise((resolve2) => {
      this.resolveFilterPassCallback = resolve2;
    });
    this.setModel(model2).then(() => {
      awaitFilterPassCallback.then(() => {
        this.sourceParams.filterChangedCallback();
      });
    });
  }
  getProps() {
    const props = super.getProps();
    props.model = this.model;
    props.onModelChange = this.onModelChange;
    props.onUiChange = this.onUiChange;
    delete props.filterChangedCallback;
    return props;
  }
};
var FilterDisplayComponentWrapper = class extends CustomComponentWrapper {
  constructor() {
    super(...arguments);
    this.awaitSetMethodsCallback = new AgPromise((resolve2) => {
      this.resolveSetMethodsCallback = resolve2;
    });
  }
  refresh(newParams) {
    this.sourceParams = newParams;
    this.refreshProps();
    return true;
  }
  afterGuiAttached(params) {
    const providedMethods = this.providedMethods;
    if (!providedMethods) {
      this.awaitSetMethodsCallback.then(() => this.providedMethods?.afterGuiAttached?.(params));
    } else {
      providedMethods.afterGuiAttached?.(params);
    }
  }
  getOptionalMethods() {
    return ["afterGuiDetached", "onNewRowsLoaded", "onAnyFilterChanged"];
  }
  setMethods(methods) {
    super.setMethods(methods);
    this.resolveSetMethodsCallback();
  }
};
function updateFloatingFilterParent(params, model2) {
  params.parentFilterInstance((instance2) => {
    (instance2.setModel(model2) || AgPromise.resolve()).then(() => {
      params.filterParams.filterChangedCallback();
    });
  });
}
var FloatingFilterComponentProxy = class {
  constructor(floatingFilterParams, refreshProps) {
    this.floatingFilterParams = floatingFilterParams;
    this.refreshProps = refreshProps;
    this.model = null;
    this.onModelChange = (model2) => this.updateModel(model2);
  }
  getProps() {
    return {
      ...this.floatingFilterParams,
      model: this.model,
      onModelChange: this.onModelChange
    };
  }
  onParentModelChanged(parentModel) {
    this.model = parentModel;
    this.refreshProps();
  }
  refresh(params) {
    this.floatingFilterParams = params;
    this.refreshProps();
  }
  setMethods(methods) {
    addOptionalMethods(this.getOptionalMethods(), methods, this);
  }
  getOptionalMethods() {
    return ["afterGuiAttached"];
  }
  updateModel(model2) {
    this.model = model2;
    this.refreshProps();
    updateFloatingFilterParent(this.floatingFilterParams, model2);
  }
};
var FloatingFilterComponentWrapper = class extends CustomComponentWrapper {
  constructor() {
    super(...arguments);
    this.model = null;
    this.onModelChange = (model2) => this.updateModel(model2);
  }
  onParentModelChanged(parentModel) {
    this.model = parentModel;
    this.refreshProps();
  }
  refresh(newParams) {
    this.sourceParams = newParams;
    this.refreshProps();
  }
  getOptionalMethods() {
    return ["afterGuiAttached"];
  }
  updateModel(model2) {
    this.model = model2;
    this.refreshProps();
    updateFloatingFilterParent(this.sourceParams, model2);
  }
  getProps() {
    const props = super.getProps();
    props.model = this.model;
    props.onModelChange = this.onModelChange;
    return props;
  }
};
var FloatingFilterDisplayComponentWrapper = class extends CustomComponentWrapper {
  refresh(newParams) {
    this.sourceParams = newParams;
    this.refreshProps();
  }
  getOptionalMethods() {
    return ["afterGuiAttached"];
  }
};
var InnerHeaderComponentWrapper = class extends CustomComponentWrapper {
  refresh(params) {
    this.sourceParams = params;
    this.refreshProps();
    return true;
  }
};
var LoadingOverlayComponentWrapper = class extends CustomComponentWrapper {
  refresh(params) {
    this.sourceParams = params;
    this.refreshProps();
  }
};
var MenuItemComponentWrapper = class extends CustomComponentWrapper {
  constructor() {
    super(...arguments);
    this.active = false;
    this.expanded = false;
    this.onActiveChange = (active) => this.updateActive(active);
  }
  setActive(active) {
    this.awaitSetActive(active);
  }
  setExpanded(expanded) {
    this.expanded = expanded;
    this.refreshProps();
  }
  getOptionalMethods() {
    return ["select", "configureDefaults"];
  }
  awaitSetActive(active) {
    this.active = active;
    return this.refreshProps();
  }
  updateActive(active) {
    const result2 = this.awaitSetActive(active);
    if (active) {
      result2.then(() => this.sourceParams.onItemActivated());
    }
  }
  getProps() {
    const props = super.getProps();
    props.active = this.active;
    props.expanded = this.expanded;
    props.onActiveChange = this.onActiveChange;
    delete props.onItemActivated;
    return props;
  }
};
var NoRowsOverlayComponentWrapper = class extends CustomComponentWrapper {
  refresh(params) {
    this.sourceParams = params;
    this.refreshProps();
  }
};
var StatusPanelComponentWrapper = class extends CustomComponentWrapper {
  refresh(params) {
    this.sourceParams = params;
    this.refreshProps();
    return true;
  }
};
var ToolPanelComponentWrapper = class extends CustomComponentWrapper {
  constructor() {
    super(...arguments);
    this.onStateChange = (state) => this.updateState(state);
  }
  refresh(params) {
    this.sourceParams = params;
    this.refreshProps();
    return true;
  }
  getState() {
    return this.state;
  }
  updateState(state) {
    this.state = state;
    this.refreshProps();
    this.sourceParams.onStateUpdated();
  }
  getProps() {
    const props = super.getProps();
    props.state = this.state;
    props.onStateChange = this.onStateChange;
    return props;
  }
};
function warnReactiveCustomComponents() {
  _warn(231);
}
var MAX_COMPONENT_CREATION_TIME_IN_MS = 1e3;
var PortalManager = class {
  constructor(refresher, wrappingElement, maxComponentCreationTimeMs) {
    this.destroyed = false;
    this.portals = [];
    this.hasPendingPortalUpdate = false;
    this.wrappingElement = wrappingElement ? wrappingElement : "div";
    this.refresher = refresher;
    this.maxComponentCreationTimeMs = maxComponentCreationTimeMs ? maxComponentCreationTimeMs : MAX_COMPONENT_CREATION_TIME_IN_MS;
  }
  getPortals() {
    return this.portals;
  }
  destroy() {
    this.destroyed = true;
  }
  destroyPortal(portal) {
    this.portals = this.portals.filter((curPortal) => curPortal !== portal);
    this.batchUpdate();
  }
  getComponentWrappingElement() {
    return this.wrappingElement;
  }
  mountReactPortal(portal, reactComponent, resolve2) {
    this.portals = [...this.portals, portal];
    this.waitForInstance(reactComponent, resolve2);
    this.batchUpdate();
  }
  updateReactPortal(oldPortal, newPortal) {
    this.portals[this.portals.indexOf(oldPortal)] = newPortal;
    this.batchUpdate();
  }
  batchUpdate() {
    if (this.hasPendingPortalUpdate) {
      return;
    }
    setTimeout(() => {
      if (!this.destroyed) {
        this.refresher();
        this.hasPendingPortalUpdate = false;
      }
    });
    this.hasPendingPortalUpdate = true;
  }
  waitForInstance(reactComponent, resolve2, startTime = Date.now()) {
    if (this.destroyed) {
      resolve2(null);
      return;
    }
    if (reactComponent.rendered()) {
      resolve2(reactComponent);
    } else {
      if (Date.now() - startTime >= this.maxComponentCreationTimeMs && !this.hasPendingPortalUpdate) {
        agFlushSync(true, () => this.refresher());
        if (reactComponent.rendered()) {
          resolve2(reactComponent);
        }
        return;
      }
      window.setTimeout(() => {
        this.waitForInstance(reactComponent, resolve2, startTime);
      });
    }
  }
};
var HeaderCellComp = ({ ctrl }) => {
  const isAlive = ctrl.isAlive();
  const { context } = reactExports.useContext(BeansContext);
  const [userCompDetails, setUserCompDetails] = reactExports.useState();
  const [userStyles, setUserStyles] = reactExports.useState();
  const compBean = reactExports.useRef();
  const eGui = reactExports.useRef(null);
  const eResize = reactExports.useRef(null);
  const eHeaderCompWrapper = reactExports.useRef(null);
  const userCompRef = reactExports.useRef();
  const cssManager = reactExports.useRef();
  if (isAlive && !cssManager.current) {
    cssManager.current = new CssClassManager(() => eGui.current);
  }
  const setRef2 = reactExports.useCallback((eRef) => {
    eGui.current = eRef;
    if (!eRef || !ctrl.isAlive() || context.isDestroyed()) {
      compBean.current = context.destroyBean(compBean.current);
      return;
    }
    compBean.current = context.createBean(new EmptyBean());
    const refreshSelectAllGui = () => {
      const selectAllGui = ctrl.getSelectAllGui();
      if (selectAllGui) {
        eResize.current?.insertAdjacentElement("afterend", selectAllGui);
        compBean.current.addDestroyFunc(() => selectAllGui.remove());
      }
    };
    const compProxy = {
      setWidth: (width) => {
        if (eGui.current) {
          eGui.current.style.width = width;
        }
      },
      toggleCss: (name2, on) => cssManager.current.toggleCss(name2, on),
      setUserStyles: (styles2) => setUserStyles(styles2),
      setAriaSort: (sort) => {
        if (eGui.current) {
          sort ? _setAriaSort(eGui.current, sort) : _removeAriaSort(eGui.current);
        }
      },
      setUserCompDetails: (compDetails) => setUserCompDetails(compDetails),
      getUserCompInstance: () => userCompRef.current || void 0,
      refreshSelectAllGui,
      removeSelectAllGui: () => ctrl.getSelectAllGui()?.remove()
    };
    ctrl.setComp(compProxy, eRef, eResize.current, eHeaderCompWrapper.current, compBean.current);
    refreshSelectAllGui();
  }, []);
  reactExports.useLayoutEffect(
    () => showJsComp(userCompDetails, context, eHeaderCompWrapper.current, userCompRef),
    [userCompDetails]
  );
  reactExports.useEffect(() => {
    ctrl.setDragSource(eGui.current);
  }, [userCompDetails]);
  const userCompStateless = reactExports.useMemo(() => {
    const res = userCompDetails?.componentFromFramework && isComponentStateless(userCompDetails.componentClass);
    return !!res;
  }, [userCompDetails]);
  const reactUserComp = userCompDetails?.componentFromFramework;
  const UserCompClass = userCompDetails?.componentClass;
  return /* @__PURE__ */ React20.createElement("div", { ref: setRef2, style: userStyles, className: "ag-header-cell", role: "columnheader" }, /* @__PURE__ */ React20.createElement("div", { ref: eResize, className: "ag-header-cell-resize", role: "presentation" }), /* @__PURE__ */ React20.createElement("div", { ref: eHeaderCompWrapper, className: "ag-header-cell-comp-wrapper", role: "presentation" }, reactUserComp ? userCompStateless ? /* @__PURE__ */ React20.createElement(UserCompClass, { ...userCompDetails.params }) : /* @__PURE__ */ React20.createElement(UserCompClass, { ...userCompDetails.params, ref: userCompRef }) : null));
};
var headerCellComp_default = reactExports.memo(HeaderCellComp);
var FloatingFilterDisplayComponentProxy = class {
  constructor(floatingFilterParams, refreshProps) {
    this.floatingFilterParams = floatingFilterParams;
    this.refreshProps = refreshProps;
  }
  getProps() {
    return this.floatingFilterParams;
  }
  refresh(params) {
    this.floatingFilterParams = params;
    this.refreshProps();
  }
  setMethods(methods) {
    addOptionalMethods(this.getOptionalMethods(), methods, this);
  }
  getOptionalMethods() {
    return ["afterGuiAttached"];
  }
};
var HeaderFilterCellComp = ({ ctrl }) => {
  const { context, gos } = reactExports.useContext(BeansContext);
  const [userStyles, setUserStyles] = reactExports.useState();
  const [cssClasses, setCssClasses] = reactExports.useState(
    () => new CssClasses("ag-header-cell", "ag-floating-filter")
  );
  const [cssBodyClasses, setBodyCssClasses] = reactExports.useState(() => new CssClasses());
  const [cssButtonWrapperClasses, setButtonWrapperCssClasses] = reactExports.useState(
    () => new CssClasses("ag-floating-filter-button", "ag-hidden")
  );
  const [buttonWrapperAriaHidden, setButtonWrapperAriaHidden] = reactExports.useState("false");
  const [userCompDetails, setUserCompDetails] = reactExports.useState();
  const [, setRenderKey] = reactExports.useState(1);
  const compBean = reactExports.useRef();
  const eGui = reactExports.useRef(null);
  const eFloatingFilterBody = reactExports.useRef(null);
  const eButtonWrapper = reactExports.useRef(null);
  const eButtonShowMainFilter = reactExports.useRef(null);
  const userCompResolve = reactExports.useRef();
  const userCompPromise = reactExports.useRef();
  const userCompRef = (value2) => {
    if (value2 == null) {
      return;
    }
    userCompResolve.current && userCompResolve.current(value2);
  };
  const setRef2 = reactExports.useCallback((eRef) => {
    eGui.current = eRef;
    if (!eRef || !ctrl.isAlive() || context.isDestroyed()) {
      compBean.current = context.destroyBean(compBean.current);
      return;
    }
    compBean.current = context.createBean(new EmptyBean());
    userCompPromise.current = new AgPromise((resolve2) => {
      userCompResolve.current = resolve2;
    });
    const compProxy = {
      toggleCss: (name2, on) => setCssClasses((prev) => prev.setClass(name2, on)),
      setUserStyles: (styles2) => setUserStyles(styles2),
      addOrRemoveBodyCssClass: (name2, on) => setBodyCssClasses((prev) => prev.setClass(name2, on)),
      setButtonWrapperDisplayed: (displayed) => {
        setButtonWrapperCssClasses((prev) => prev.setClass("ag-hidden", !displayed));
        setButtonWrapperAriaHidden(!displayed ? "true" : "false");
      },
      setWidth: (width) => {
        if (eGui.current) {
          eGui.current.style.width = width;
        }
      },
      setCompDetails: (compDetails) => setUserCompDetails(compDetails),
      getFloatingFilterComp: () => userCompPromise.current ? userCompPromise.current : null,
      setMenuIcon: (eIcon) => eButtonShowMainFilter.current?.appendChild(eIcon)
    };
    ctrl.setComp(compProxy, eRef, eButtonShowMainFilter.current, eFloatingFilterBody.current, compBean.current);
  }, []);
  reactExports.useLayoutEffect(
    () => showJsComp(userCompDetails, context, eFloatingFilterBody.current, userCompRef),
    [userCompDetails]
  );
  const className2 = reactExports.useMemo(() => cssClasses.toString(), [cssClasses]);
  const bodyClassName = reactExports.useMemo(() => cssBodyClasses.toString(), [cssBodyClasses]);
  const buttonWrapperClassName = reactExports.useMemo(() => cssButtonWrapperClasses.toString(), [cssButtonWrapperClasses]);
  const userCompStateless = reactExports.useMemo(() => {
    const res = userCompDetails && userCompDetails.componentFromFramework && isComponentStateless(userCompDetails.componentClass);
    return !!res;
  }, [userCompDetails]);
  const reactiveCustomComponents = reactExports.useMemo(() => gos.get("reactiveCustomComponents"), []);
  const enableFilterHandlers = reactExports.useMemo(() => gos.get("enableFilterHandlers"), []);
  const [floatingFilterCompProxy, setFloatingFilterCompProxy] = reactExports.useState();
  reactExports.useEffect(() => {
    if (userCompDetails?.componentFromFramework) {
      if (reactiveCustomComponents) {
        const ProxyClass = enableFilterHandlers ? FloatingFilterDisplayComponentProxy : FloatingFilterComponentProxy;
        const compProxy = new ProxyClass(userCompDetails.params, () => setRenderKey((prev) => prev + 1));
        userCompRef(compProxy);
        setFloatingFilterCompProxy(compProxy);
      } else {
        warnReactiveCustomComponents();
      }
    }
  }, [userCompDetails]);
  const floatingFilterProps = floatingFilterCompProxy?.getProps();
  const reactUserComp = userCompDetails?.componentFromFramework;
  const UserCompClass = userCompDetails?.componentClass;
  return /* @__PURE__ */ React20.createElement("div", { ref: setRef2, style: userStyles, className: className2, role: "gridcell" }, /* @__PURE__ */ React20.createElement("div", { ref: eFloatingFilterBody, className: bodyClassName, role: "presentation" }, reactUserComp ? reactiveCustomComponents ? floatingFilterProps && /* @__PURE__ */ React20.createElement(
    CustomContext.Provider,
    {
      value: {
        setMethods: (methods) => floatingFilterCompProxy.setMethods(methods)
      }
    },
    /* @__PURE__ */ React20.createElement(UserCompClass, { ...floatingFilterProps })
  ) : /* @__PURE__ */ React20.createElement(UserCompClass, { ...userCompDetails.params, ref: userCompStateless ? () => {
  } : userCompRef }) : null), /* @__PURE__ */ React20.createElement(
    "div",
    {
      ref: eButtonWrapper,
      "aria-hidden": buttonWrapperAriaHidden,
      className: buttonWrapperClassName,
      role: "presentation"
    },
    /* @__PURE__ */ React20.createElement(
      "button",
      {
        ref: eButtonShowMainFilter,
        type: "button",
        className: "ag-button ag-floating-filter-button-button",
        tabIndex: -1
      }
    )
  ));
};
var headerFilterCellComp_default = reactExports.memo(HeaderFilterCellComp);
var HeaderGroupCellComp = ({ ctrl }) => {
  const { context } = reactExports.useContext(BeansContext);
  const [userStyles, setUserStyles] = reactExports.useState();
  const [cssClasses, setCssClasses] = reactExports.useState(() => new CssClasses());
  const [cssResizableClasses, setResizableCssClasses] = reactExports.useState(() => new CssClasses());
  const [resizableAriaHidden, setResizableAriaHidden] = reactExports.useState("false");
  const [ariaExpanded, setAriaExpanded] = reactExports.useState();
  const [userCompDetails, setUserCompDetails] = reactExports.useState();
  const compBean = reactExports.useRef();
  const eGui = reactExports.useRef(null);
  const eResize = reactExports.useRef(null);
  const eHeaderCompWrapper = reactExports.useRef(null);
  const userCompRef = reactExports.useRef();
  const setRef2 = reactExports.useCallback((eRef) => {
    eGui.current = eRef;
    if (!eRef || !ctrl.isAlive() || context.isDestroyed()) {
      compBean.current = context.destroyBean(compBean.current);
      return;
    }
    compBean.current = context.createBean(new EmptyBean());
    const compProxy = {
      setWidth: (width) => {
        if (eGui.current) {
          eGui.current.style.width = width;
        }
      },
      toggleCss: (name2, on) => setCssClasses((prev) => prev.setClass(name2, on)),
      setUserStyles: (styles2) => setUserStyles(styles2),
      setHeaderWrapperHidden: (hidden2) => {
        const headerCompWrapper = eHeaderCompWrapper.current;
        if (!headerCompWrapper) {
          return;
        }
        if (hidden2) {
          headerCompWrapper.style.setProperty("display", "none");
        } else {
          headerCompWrapper.style.removeProperty("display");
        }
      },
      setHeaderWrapperMaxHeight: (value2) => {
        const headerCompWrapper = eHeaderCompWrapper.current;
        if (!headerCompWrapper) {
          return;
        }
        if (value2 != null) {
          headerCompWrapper.style.setProperty("max-height", `${value2}px`);
        } else {
          headerCompWrapper.style.removeProperty("max-height");
        }
        headerCompWrapper.classList.toggle("ag-header-cell-comp-wrapper-limited-height", value2 != null);
      },
      setUserCompDetails: (compDetails) => setUserCompDetails(compDetails),
      setResizableDisplayed: (displayed) => {
        setResizableCssClasses((prev) => prev.setClass("ag-hidden", !displayed));
        setResizableAriaHidden(!displayed ? "true" : "false");
      },
      setAriaExpanded: (expanded) => setAriaExpanded(expanded),
      getUserCompInstance: () => userCompRef.current || void 0
    };
    ctrl.setComp(compProxy, eRef, eResize.current, eHeaderCompWrapper.current, compBean.current);
  }, []);
  reactExports.useLayoutEffect(() => showJsComp(userCompDetails, context, eHeaderCompWrapper.current), [userCompDetails]);
  reactExports.useEffect(() => {
    if (eGui.current) {
      ctrl.setDragSource(eGui.current);
    }
  }, [userCompDetails]);
  const userCompStateless = reactExports.useMemo(() => {
    const res = userCompDetails?.componentFromFramework && isComponentStateless(userCompDetails.componentClass);
    return !!res;
  }, [userCompDetails]);
  const className2 = reactExports.useMemo(() => "ag-header-group-cell " + cssClasses.toString(), [cssClasses]);
  const resizableClassName = reactExports.useMemo(
    () => "ag-header-cell-resize " + cssResizableClasses.toString(),
    [cssResizableClasses]
  );
  const reactUserComp = userCompDetails?.componentFromFramework;
  const UserCompClass = userCompDetails?.componentClass;
  return /* @__PURE__ */ React20.createElement("div", { ref: setRef2, style: userStyles, className: className2, role: "columnheader", "aria-expanded": ariaExpanded }, /* @__PURE__ */ React20.createElement("div", { ref: eHeaderCompWrapper, className: "ag-header-cell-comp-wrapper", role: "presentation" }, reactUserComp ? userCompStateless ? /* @__PURE__ */ React20.createElement(UserCompClass, { ...userCompDetails.params }) : /* @__PURE__ */ React20.createElement(UserCompClass, { ...userCompDetails.params, ref: userCompRef }) : null), /* @__PURE__ */ React20.createElement("div", { ref: eResize, "aria-hidden": resizableAriaHidden, className: resizableClassName }));
};
var headerGroupCellComp_default = reactExports.memo(HeaderGroupCellComp);
var HeaderRowComp = ({ ctrl }) => {
  const { gos, context } = reactExports.useContext(BeansContext);
  const { topOffset, rowHeight } = reactExports.useMemo(() => ctrl.getTopAndHeight(), []);
  const tabIndex = reactExports.useMemo(() => gos.get("tabIndex"), []);
  const [ariaRowIndex, setAriaRowIndex] = reactExports.useState(() => ctrl.getAriaRowIndex());
  const className2 = ctrl.headerRowClass;
  const [height, setHeight] = reactExports.useState(() => rowHeight + "px");
  const [top2, setTop] = reactExports.useState(() => topOffset + "px");
  const cellCtrlsRef = reactExports.useRef(null);
  const [cellCtrls, setCellCtrls] = reactExports.useState(() => ctrl.getUpdatedHeaderCtrls());
  const compBean = reactExports.useRef();
  const eGui = reactExports.useRef(null);
  const setRef2 = reactExports.useCallback((eRef) => {
    eGui.current = eRef;
    if (!eRef || !ctrl.isAlive() || context.isDestroyed()) {
      compBean.current = context.destroyBean(compBean.current);
      return;
    }
    compBean.current = context.createBean(new EmptyBean());
    const compProxy = {
      setHeight: (height2) => setHeight(height2),
      setTop: (top22) => setTop(top22),
      setHeaderCtrls: (ctrls, forceOrder, afterScroll) => {
        const prevCellCtrls = cellCtrlsRef.current;
        const nextCells = getNextValueIfDifferent(prevCellCtrls, ctrls, forceOrder);
        if (nextCells !== prevCellCtrls) {
          cellCtrlsRef.current = nextCells;
          agFlushSync(afterScroll, () => setCellCtrls(nextCells));
        }
      },
      setWidth: (width) => {
        if (eGui.current) {
          eGui.current.style.width = width;
        }
      },
      setRowIndex: (rowIndex) => {
        setAriaRowIndex(rowIndex);
      }
    };
    ctrl.setComp(compProxy, compBean.current, false);
  }, []);
  const style2 = reactExports.useMemo(
    () => ({
      height,
      top: top2
    }),
    [height, top2]
  );
  const createCellJsx = reactExports.useCallback((cellCtrl) => {
    switch (ctrl.type) {
      case "group":
        return /* @__PURE__ */ React20.createElement(headerGroupCellComp_default, { ctrl: cellCtrl, key: cellCtrl.instanceId });
      case "filter":
        return /* @__PURE__ */ React20.createElement(headerFilterCellComp_default, { ctrl: cellCtrl, key: cellCtrl.instanceId });
      default:
        return /* @__PURE__ */ React20.createElement(headerCellComp_default, { ctrl: cellCtrl, key: cellCtrl.instanceId });
    }
  }, []);
  return /* @__PURE__ */ React20.createElement(
    "div",
    {
      ref: setRef2,
      className: className2,
      role: "row",
      style: style2,
      tabIndex,
      "aria-rowindex": ariaRowIndex
    },
    cellCtrls.map(createCellJsx)
  );
};
var headerRowComp_default = reactExports.memo(HeaderRowComp);
var HeaderRowContainerComp = ({ pinned }) => {
  const [displayed, setDisplayed] = reactExports.useState(true);
  const [headerRowCtrls, setHeaderRowCtrls] = reactExports.useState([]);
  const { context } = reactExports.useContext(BeansContext);
  const eGui = reactExports.useRef(null);
  const eCenterContainer = reactExports.useRef(null);
  const headerRowCtrlRef = reactExports.useRef();
  const pinnedLeft = pinned === "left";
  const pinnedRight = pinned === "right";
  const centre = !pinnedLeft && !pinnedRight;
  const setRef2 = reactExports.useCallback((eRef) => {
    eGui.current = eRef;
    if (!eRef || context.isDestroyed()) {
      headerRowCtrlRef.current = context.destroyBean(headerRowCtrlRef.current);
      return;
    }
    headerRowCtrlRef.current = context.createBean(new HeaderRowContainerCtrl(pinned));
    const compProxy = {
      setDisplayed,
      setCtrls: (ctrls) => setHeaderRowCtrls(ctrls),
      // centre only
      setCenterWidth: (width) => {
        if (eCenterContainer.current) {
          eCenterContainer.current.style.width = width;
        }
      },
      setViewportScrollLeft: (left2) => {
        if (eGui.current) {
          eGui.current.scrollLeft = left2;
        }
      },
      // pinned only
      setPinnedContainerWidth: (width) => {
        if (eGui.current) {
          eGui.current.style.width = width;
          eGui.current.style.minWidth = width;
          eGui.current.style.maxWidth = width;
        }
      }
    };
    headerRowCtrlRef.current.setComp(compProxy, eGui.current);
  }, []);
  const className2 = !displayed ? "ag-hidden" : "";
  const insertRowsJsx = () => headerRowCtrls.map((ctrl) => /* @__PURE__ */ React20.createElement(headerRowComp_default, { ctrl, key: ctrl.instanceId }));
  return pinnedLeft ? /* @__PURE__ */ React20.createElement("div", { ref: setRef2, className: "ag-pinned-left-header " + className2, "aria-hidden": !displayed, role: "rowgroup" }, insertRowsJsx()) : pinnedRight ? /* @__PURE__ */ React20.createElement("div", { ref: setRef2, className: "ag-pinned-right-header " + className2, "aria-hidden": !displayed, role: "rowgroup" }, insertRowsJsx()) : centre ? /* @__PURE__ */ React20.createElement("div", { ref: setRef2, className: "ag-header-viewport " + className2, role: "rowgroup", tabIndex: -1 }, /* @__PURE__ */ React20.createElement("div", { ref: eCenterContainer, className: "ag-header-container", role: "presentation" }, insertRowsJsx())) : null;
};
var headerRowContainerComp_default = reactExports.memo(HeaderRowContainerComp);
var GridHeaderComp = () => {
  const [cssClasses, setCssClasses] = reactExports.useState(() => new CssClasses());
  const [height, setHeight] = reactExports.useState();
  const { context } = reactExports.useContext(BeansContext);
  const eGui = reactExports.useRef(null);
  const gridCtrlRef = reactExports.useRef();
  const setRef2 = reactExports.useCallback((eRef) => {
    eGui.current = eRef;
    if (!eRef || context.isDestroyed()) {
      gridCtrlRef.current = context.destroyBean(gridCtrlRef.current);
      return;
    }
    gridCtrlRef.current = context.createBean(new GridHeaderCtrl());
    const compProxy = {
      toggleCss: (name2, on) => setCssClasses((prev) => prev.setClass(name2, on)),
      setHeightAndMinHeight: (height2) => setHeight(height2)
    };
    gridCtrlRef.current.setComp(compProxy, eRef, eRef);
  }, []);
  const className2 = reactExports.useMemo(() => {
    const res = cssClasses.toString();
    return "ag-header " + res;
  }, [cssClasses]);
  const style2 = reactExports.useMemo(
    () => ({
      height,
      minHeight: height
    }),
    [height]
  );
  return /* @__PURE__ */ React20.createElement("div", { ref: setRef2, className: className2, style: style2, role: "presentation" }, /* @__PURE__ */ React20.createElement(headerRowContainerComp_default, { pinned: "left" }), /* @__PURE__ */ React20.createElement(headerRowContainerComp_default, { pinned: null }), /* @__PURE__ */ React20.createElement(headerRowContainerComp_default, { pinned: "right" }));
};
var gridHeaderComp_default = reactExports.memo(GridHeaderComp);
var useReactCommentEffect = (comment2, eForCommentRef) => {
  reactExports.useEffect(() => {
    const eForComment = eForCommentRef.current;
    if (eForComment) {
      const eParent = eForComment.parentElement;
      if (eParent) {
        const eComment = document.createComment(comment2);
        eParent.insertBefore(eComment, eForComment);
        return () => {
          eComment.remove();
        };
      }
    }
  }, [comment2]);
};
var reactComment_default = useReactCommentEffect;
var CellEditorComponentProxy = class {
  constructor(cellEditorParams, refreshProps) {
    this.cellEditorParams = cellEditorParams;
    this.refreshProps = refreshProps;
    this.instanceCreated = new AgPromise((resolve2) => {
      this.resolveInstanceCreated = resolve2;
    });
    this.onValueChange = (value2) => this.updateValue(value2);
    this.value = cellEditorParams.value;
  }
  getProps() {
    return {
      ...this.cellEditorParams,
      initialValue: this.cellEditorParams.value,
      value: this.value,
      onValueChange: this.onValueChange
    };
  }
  getValue() {
    return this.value;
  }
  refresh(params) {
    this.cellEditorParams = params;
    this.refreshProps();
  }
  setMethods(methods) {
    addOptionalMethods(this.getOptionalMethods(), methods, this);
  }
  getInstance() {
    return this.instanceCreated.then(() => this.componentInstance);
  }
  setRef(componentInstance) {
    this.componentInstance = componentInstance;
    this.resolveInstanceCreated?.();
    this.resolveInstanceCreated = void 0;
  }
  getOptionalMethods() {
    return [
      "isCancelBeforeStart",
      "isCancelAfterEnd",
      "focusIn",
      "focusOut",
      "afterGuiAttached",
      "getValidationErrors",
      "getValidationElement"
    ];
  }
  updateValue(value2) {
    this.value = value2;
    this.refreshProps();
  }
};
var useEffectOnce = (effect2) => {
  const effectFn = reactExports.useRef(effect2);
  const destroyFn = reactExports.useRef();
  const effectCalled = reactExports.useRef(false);
  const rendered = reactExports.useRef(false);
  const [, setVal] = reactExports.useState(0);
  if (effectCalled.current) {
    rendered.current = true;
  }
  reactExports.useEffect(() => {
    if (!effectCalled.current) {
      destroyFn.current = effectFn.current();
      effectCalled.current = true;
    }
    setVal((val) => val + 1);
    return () => {
      if (!rendered.current) {
        return;
      }
      destroyFn.current?.();
    };
  }, []);
};
var PopupEditorComp = (props) => {
  const [popupEditorWrapper, setPopupEditorWrapper] = reactExports.useState();
  const beans = reactExports.useContext(BeansContext);
  const { context, popupSvc, gos, editSvc } = beans;
  const { editDetails, cellCtrl, eParentCell } = props;
  useEffectOnce(() => {
    const { compDetails } = editDetails;
    const useModelPopup = gos.get("stopEditingWhenCellsLoseFocus");
    let hideEditorPopup = void 0;
    let wrapper2;
    if (!context.isDestroyed()) {
      wrapper2 = context.createBean(editSvc.createPopupEditorWrapper(compDetails.params));
      const ePopupGui = wrapper2.getGui();
      if (props.jsChildComp) {
        const eChildGui = props.jsChildComp.getGui();
        if (eChildGui) {
          ePopupGui.appendChild(eChildGui);
        }
      }
      const { column: column2, rowNode } = cellCtrl;
      const positionParams = {
        column: column2,
        rowNode,
        type: "popupCellEditor",
        eventSource: eParentCell,
        ePopup: ePopupGui,
        position: editDetails.popupPosition,
        keepWithinBounds: true
      };
      const positionCallback = popupSvc?.positionPopupByComponent.bind(popupSvc, positionParams);
      const addPopupRes = popupSvc?.addPopup({
        modal: useModelPopup,
        eChild: ePopupGui,
        closeOnEsc: true,
        closedCallback: () => {
          cellCtrl.onPopupEditorClosed();
        },
        anchorToElement: eParentCell,
        positionCallback,
        ariaOwns: eParentCell
      });
      hideEditorPopup = addPopupRes ? addPopupRes.hideFunc : void 0;
      setPopupEditorWrapper(wrapper2);
      props.jsChildComp?.afterGuiAttached?.();
    }
    return () => {
      hideEditorPopup?.();
      context.destroyBean(wrapper2);
    };
  });
  reactExports.useLayoutEffect(() => {
    return () => {
      if (cellCtrl.isCellFocused() && popupEditorWrapper?.getGui().contains(_getActiveDomElement(beans))) {
        eParentCell.focus({ preventScroll: true });
      }
    };
  }, [popupEditorWrapper]);
  return popupEditorWrapper && props.wrappedContent ? reactDomExports.createPortal(props.wrappedContent, popupEditorWrapper.getGui()) : null;
};
var popupEditorComp_default = reactExports.memo(PopupEditorComp);
var jsxEditorProxy = (editDetails, CellEditorClass, setRef2) => {
  const { compProxy } = editDetails;
  setRef2(compProxy);
  const props = compProxy.getProps();
  const isStateless = isComponentStateless(CellEditorClass);
  return /* @__PURE__ */ React20.createElement(
    CustomContext.Provider,
    {
      value: {
        setMethods: (methods) => compProxy.setMethods(methods)
      }
    },
    isStateless ? /* @__PURE__ */ React20.createElement(CellEditorClass, { ...props }) : /* @__PURE__ */ React20.createElement(CellEditorClass, { ...props, ref: (ref2) => compProxy.setRef(ref2) })
  );
};
var jsxEditor = (editDetails, CellEditorClass, setRef2) => {
  const newFormat = editDetails.compProxy;
  return newFormat ? jsxEditorProxy(editDetails, CellEditorClass, setRef2) : /* @__PURE__ */ React20.createElement(CellEditorClass, { ...editDetails.compDetails.params, ref: setRef2 });
};
var jsxEditValue = (editDetails, setCellEditorRef, eGui, cellCtrl, jsEditorComp) => {
  const compDetails = editDetails.compDetails;
  const CellEditorClass = compDetails.componentClass;
  const reactInlineEditor = compDetails.componentFromFramework && !editDetails.popup;
  const reactPopupEditor = compDetails.componentFromFramework && editDetails.popup;
  const jsPopupEditor = !compDetails.componentFromFramework && editDetails.popup;
  return reactInlineEditor ? jsxEditor(editDetails, CellEditorClass, setCellEditorRef) : reactPopupEditor ? /* @__PURE__ */ React20.createElement(
    popupEditorComp_default,
    {
      editDetails,
      cellCtrl,
      eParentCell: eGui,
      wrappedContent: jsxEditor(editDetails, CellEditorClass, setCellEditorRef)
    }
  ) : jsPopupEditor && jsEditorComp ? /* @__PURE__ */ React20.createElement(popupEditorComp_default, { editDetails, cellCtrl, eParentCell: eGui, jsChildComp: jsEditorComp }) : null;
};
var useJsCellRenderer = (showDetails, showTools, eCellValue, cellValueVersion, jsCellRendererRef, eGui) => {
  const { context } = reactExports.useContext(BeansContext);
  const destroyCellRenderer = reactExports.useCallback(() => {
    const comp = jsCellRendererRef.current;
    if (!comp) {
      return;
    }
    const compGui = comp.getGui();
    if (compGui && compGui.parentElement) {
      compGui.remove();
    }
    context.destroyBean(comp);
    jsCellRendererRef.current = void 0;
  }, []);
  reactExports.useEffect(() => {
    const showValue = showDetails != null;
    const jsCompDetails = showDetails?.compDetails && !showDetails.compDetails.componentFromFramework;
    const waitingForToolsSetup = showTools && eCellValue == null;
    const showComp = showValue && jsCompDetails && !waitingForToolsSetup;
    if (!showComp) {
      destroyCellRenderer();
      return;
    }
    const compDetails = showDetails.compDetails;
    if (jsCellRendererRef.current) {
      const comp = jsCellRendererRef.current;
      const attemptRefresh = comp.refresh != null && showDetails.force == false;
      const refreshResult = attemptRefresh ? comp.refresh(compDetails.params) : false;
      const refreshWorked = refreshResult === true || refreshResult === void 0;
      if (refreshWorked) {
        return;
      }
      destroyCellRenderer();
    }
    const promise = compDetails.newAgStackInstance();
    promise.then((comp) => {
      if (!comp) {
        return;
      }
      const compGui = comp.getGui();
      if (!compGui) {
        return;
      }
      const parent = showTools ? eCellValue : eGui.current;
      parent.appendChild(compGui);
      jsCellRendererRef.current = comp;
    });
  }, [showDetails, showTools, cellValueVersion]);
  reactExports.useEffect(() => {
    return destroyCellRenderer;
  }, []);
};
var showJsRenderer_default = useJsCellRenderer;
var SkeletonCellRenderer2 = ({
  cellCtrl,
  parent
}) => {
  const jsCellRendererRef = reactExports.useRef();
  const renderDetails = reactExports.useMemo(() => {
    const { loadingComp } = cellCtrl.getDeferLoadingCellRenderer();
    return loadingComp ? {
      value: void 0,
      compDetails: loadingComp,
      force: false
    } : void 0;
  }, [cellCtrl]);
  showJsRenderer_default(renderDetails, false, void 0, 1, jsCellRendererRef, parent);
  if (renderDetails?.compDetails?.componentFromFramework) {
    const CellRendererClass = renderDetails.compDetails.componentClass;
    return /* @__PURE__ */ React20.createElement(CellRendererClass, { ...renderDetails.compDetails.params });
  }
  return /* @__PURE__ */ React20.createElement(React20.Fragment, null);
};
var CellComp = ({
  cellCtrl,
  printLayout,
  editingCell
}) => {
  const beans = reactExports.useContext(BeansContext);
  const { context } = beans;
  const {
    column: { colIdSanitised },
    instanceId
  } = cellCtrl;
  const compBean = reactExports.useRef();
  const [renderDetails, setRenderDetails] = reactExports.useState(
    () => cellCtrl.isCellRenderer() ? void 0 : { compDetails: void 0, value: cellCtrl.getValueToDisplay(), force: false }
  );
  const [editDetails, setEditDetails] = reactExports.useState();
  const [renderKey, setRenderKey] = reactExports.useState(1);
  const [userStyles, setUserStyles] = reactExports.useState();
  const [includeSelection, setIncludeSelection] = reactExports.useState(false);
  const [includeRowDrag, setIncludeRowDrag] = reactExports.useState(false);
  const [includeDndSource, setIncludeDndSource] = reactExports.useState(false);
  const [jsEditorComp, setJsEditorComp] = reactExports.useState();
  const forceWrapper = reactExports.useMemo(() => cellCtrl.isForceWrapper(), [cellCtrl]);
  const cellAriaRole = reactExports.useMemo(() => cellCtrl.getCellAriaRole(), [cellCtrl]);
  const eGui = reactExports.useRef(null);
  const eWrapper = reactExports.useRef(null);
  const cellRendererRef = reactExports.useRef(null);
  const jsCellRendererRef = reactExports.useRef();
  const cellEditorRef = reactExports.useRef();
  const eCellWrapper = reactExports.useRef();
  const cellWrapperDestroyFuncs = reactExports.useRef([]);
  const rowDragCompRef = reactExports.useRef();
  const eCellValue = reactExports.useRef();
  const [cellValueVersion, setCellValueVersion] = reactExports.useState(0);
  const setCellValueRef = reactExports.useCallback((ref2) => {
    eCellValue.current = ref2;
    setCellValueVersion((v) => v + 1);
  }, []);
  const showTools = renderDetails != null && (includeSelection || includeDndSource || includeRowDrag) && (editDetails == null || !!editDetails.popup);
  const showCellWrapper = forceWrapper || showTools;
  const cellValueClass = reactExports.useMemo(() => {
    return cellCtrl.getCellValueClass();
  }, [cellCtrl]);
  const setCellEditorRef = reactExports.useCallback(
    (cellEditor) => {
      cellEditorRef.current = cellEditor;
      if (cellEditor) {
        const editingCancelledByUserComp = cellEditor.isCancelBeforeStart && cellEditor.isCancelBeforeStart();
        setTimeout(() => {
          if (editingCancelledByUserComp) {
            cellCtrl.stopEditing(true);
            cellCtrl.focusCell(true);
          } else {
            cellCtrl.cellEditorAttached();
            cellCtrl.enableEditorTooltipFeature(cellEditor);
          }
        });
      }
    },
    [cellCtrl]
  );
  const cssManager = reactExports.useRef();
  if (!cssManager.current) {
    cssManager.current = new CssClassManager(() => eGui.current);
  }
  showJsRenderer_default(renderDetails, showCellWrapper, eCellValue.current, cellValueVersion, jsCellRendererRef, eGui);
  const lastRenderDetails = reactExports.useRef();
  reactExports.useLayoutEffect(() => {
    const oldDetails = lastRenderDetails.current;
    const newDetails = renderDetails;
    lastRenderDetails.current = renderDetails;
    if (oldDetails == null || oldDetails.compDetails == null || newDetails == null || newDetails.compDetails == null) {
      return;
    }
    rowDragCompRef.current?.refreshVisibility();
    const oldCompDetails = oldDetails.compDetails;
    const newCompDetails = newDetails.compDetails;
    if (oldCompDetails.componentClass != newCompDetails.componentClass) {
      return;
    }
    if (cellRendererRef.current?.refresh == null) {
      return;
    }
    const result2 = cellRendererRef.current.refresh(newCompDetails.params);
    if (result2 != true) {
      setRenderKey((prev) => prev + 1);
    }
  }, [renderDetails]);
  reactExports.useLayoutEffect(() => {
    const doingJsEditor = editDetails && !editDetails.compDetails.componentFromFramework;
    if (!doingJsEditor || context.isDestroyed()) {
      return;
    }
    const compDetails = editDetails.compDetails;
    const isPopup = editDetails.popup === true;
    const cellEditorPromise = compDetails.newAgStackInstance();
    cellEditorPromise.then((cellEditor) => {
      if (!cellEditor) {
        return;
      }
      const compGui = cellEditor.getGui();
      setCellEditorRef(cellEditor);
      if (!isPopup) {
        const parentEl = (forceWrapper ? eCellWrapper : eGui).current;
        parentEl?.appendChild(compGui);
        cellEditor.afterGuiAttached?.();
      }
      setJsEditorComp(cellEditor);
    });
    return () => {
      cellEditorPromise.then((cellEditor) => {
        const compGui = cellEditor.getGui();
        cellCtrl.disableEditorTooltipFeature();
        context.destroyBean(cellEditor);
        setCellEditorRef(void 0);
        setJsEditorComp(void 0);
        compGui?.remove();
      });
    };
  }, [editDetails]);
  const setCellWrapperRef = reactExports.useCallback(
    (eRef) => {
      eCellWrapper.current = eRef;
      if (!eRef || context.isDestroyed() || !cellCtrl.isAlive()) {
        const callbacks = cellWrapperDestroyFuncs.current;
        cellWrapperDestroyFuncs.current = [];
        for (const cb of callbacks) {
          cb();
        }
        return;
      }
      let rowDragComp;
      const addComp = (comp) => {
        if (comp) {
          eRef.insertAdjacentElement("afterbegin", comp.getGui());
          cellWrapperDestroyFuncs.current.push(() => {
            _removeFromParent(comp.getGui());
            context.destroyBean(comp);
            if (rowDragCompRef.current === rowDragComp) {
              rowDragCompRef.current = void 0;
            }
          });
        }
      };
      if (includeSelection) {
        addComp(cellCtrl.createSelectionCheckbox());
      }
      if (includeDndSource) {
        addComp(cellCtrl.createDndSource());
      }
      if (includeRowDrag) {
        rowDragComp = cellCtrl.createRowDragComp();
        rowDragCompRef.current = rowDragComp;
        if (rowDragComp) {
          addComp(rowDragComp);
          rowDragComp.refreshVisibility();
        }
      }
    },
    [cellCtrl, context, includeDndSource, includeRowDrag, includeSelection]
  );
  const init = reactExports.useCallback(() => {
    const spanReady = !cellCtrl.isCellSpanning() || eWrapper.current;
    const eRef = eGui.current;
    if (!eRef || !spanReady || !cellCtrl || !cellCtrl.isAlive() || context.isDestroyed()) {
      compBean.current = context.destroyBean(compBean.current);
      return;
    }
    compBean.current = context.createBean(new EmptyBean());
    const compProxy = {
      toggleCss: (name2, on) => cssManager.current.toggleCss(name2, on),
      setUserStyles: (styles2) => setUserStyles(styles2),
      getFocusableElement: () => eGui.current,
      setIncludeSelection: (include) => setIncludeSelection(include),
      setIncludeRowDrag: (include) => setIncludeRowDrag(include),
      setIncludeDndSource: (include) => setIncludeDndSource(include),
      getCellEditor: () => cellEditorRef.current ?? null,
      getCellRenderer: () => cellRendererRef.current ?? jsCellRendererRef.current,
      getParentOfValue: () => eCellValue.current ?? eCellWrapper.current ?? eGui.current,
      setRenderDetails: (compDetails, value2, force) => {
        const setDetails = () => {
          setRenderDetails((prev) => {
            if (prev?.compDetails !== compDetails || prev?.value !== value2 || prev?.force !== force) {
              return {
                value: value2,
                compDetails,
                force
              };
            } else {
              return prev;
            }
          });
        };
        if (compDetails?.params?.deferRender && !cellCtrl.rowNode.group) {
          const { loadingComp, onReady } = cellCtrl.getDeferLoadingCellRenderer();
          if (loadingComp) {
            setRenderDetails({
              value: void 0,
              compDetails: loadingComp,
              force: false
            });
            onReady.then(() => agStartTransition(setDetails));
            return;
          }
        }
        setDetails();
      },
      setEditDetails: (compDetails, popup, popupPosition, reactiveCustomComponents) => {
        if (compDetails) {
          let compProxy2 = void 0;
          if (compDetails.componentFromFramework) {
            if (reactiveCustomComponents) {
              compProxy2 = new CellEditorComponentProxy(
                compDetails.params,
                () => setRenderKey((prev) => prev + 1)
              );
            } else {
              warnReactiveCustomComponents();
            }
          }
          setEditDetails({
            compDetails,
            popup,
            popupPosition,
            compProxy: compProxy2
          });
          if (!popup) {
            setRenderDetails(void 0);
          }
        } else {
          const recoverFocus = cellCtrl.hasBrowserFocus();
          if (recoverFocus) {
            compProxy.getFocusableElement().focus({ preventScroll: true });
          }
          cellEditorRef.current = void 0;
          setEditDetails(void 0);
        }
      },
      refreshEditStyles: (editing, isPopup) => {
        if (!eGui.current) {
          return;
        }
        const { current: current3 } = cssManager;
        current3.toggleCss("ag-cell-value", !showCellWrapper);
        current3.toggleCss("ag-cell-inline-editing", !!editing && !isPopup);
        current3.toggleCss("ag-cell-popup-editing", !!editing && !!isPopup);
        current3.toggleCss("ag-cell-not-inline-editing", !editing || !!isPopup);
      }
    };
    const cellWrapperOrUndefined = eCellWrapper.current || void 0;
    cellCtrl.setComp(
      compProxy,
      eRef,
      eWrapper.current ?? void 0,
      cellWrapperOrUndefined,
      printLayout,
      editingCell,
      compBean.current
    );
  }, []);
  const setGuiRef = reactExports.useCallback((ref2) => {
    eGui.current = ref2;
    init();
  }, []);
  const setWrapperRef = reactExports.useCallback((ref2) => {
    eWrapper.current = ref2;
    init();
  }, []);
  const reactCellRendererStateless = reactExports.useMemo(() => {
    const res = renderDetails?.compDetails?.componentFromFramework && isComponentStateless(renderDetails.compDetails.componentClass);
    return !!res;
  }, [renderDetails]);
  reactExports.useLayoutEffect(() => {
    if (!eGui.current) {
      return;
    }
    const { current: current3 } = cssManager;
    current3.toggleCss("ag-cell-value", !showCellWrapper);
    current3.toggleCss("ag-cell-inline-editing", !!editDetails && !editDetails.popup);
    current3.toggleCss("ag-cell-popup-editing", !!editDetails && !!editDetails.popup);
    current3.toggleCss("ag-cell-not-inline-editing", !editDetails || !!editDetails.popup);
  });
  const valueOrCellComp = () => {
    const { compDetails, value: value2 } = renderDetails;
    if (!compDetails) {
      return value2?.toString?.() ?? value2;
    }
    if (compDetails.componentFromFramework) {
      const CellRendererClass = compDetails.componentClass;
      return /* @__PURE__ */ React20.createElement(reactExports.Suspense, { fallback: /* @__PURE__ */ React20.createElement(SkeletonCellRenderer2, { cellCtrl, parent: eGui }) }, reactCellRendererStateless ? /* @__PURE__ */ React20.createElement(CellRendererClass, { ...compDetails.params, key: renderKey }) : /* @__PURE__ */ React20.createElement(CellRendererClass, { ...compDetails.params, key: renderKey, ref: cellRendererRef }));
    }
  };
  const showCellOrEditor = () => {
    const showCellValue = () => {
      if (renderDetails == null) {
        return null;
      }
      return showCellWrapper ? /* @__PURE__ */ React20.createElement("span", { role: "presentation", id: `cell-${instanceId}`, className: cellValueClass, ref: setCellValueRef }, valueOrCellComp()) : valueOrCellComp();
    };
    const showEditValue = (details) => jsxEditValue(details, setCellEditorRef, eGui.current, cellCtrl, jsEditorComp);
    if (editDetails != null) {
      if (editDetails.popup) {
        return /* @__PURE__ */ React20.createElement(React20.Fragment, null, showCellValue(), showEditValue(editDetails));
      }
      return showEditValue(editDetails);
    }
    return showCellValue();
  };
  const renderCell = () => /* @__PURE__ */ React20.createElement("div", { ref: setGuiRef, style: userStyles, role: cellAriaRole, "col-id": colIdSanitised }, showCellWrapper ? /* @__PURE__ */ React20.createElement("div", { className: "ag-cell-wrapper", role: "presentation", ref: setCellWrapperRef }, showCellOrEditor()) : showCellOrEditor());
  if (cellCtrl.isCellSpanning()) {
    return /* @__PURE__ */ React20.createElement("div", { ref: setWrapperRef, className: "ag-spanned-cell-wrapper", role: "presentation" }, renderCell());
  }
  return renderCell();
};
var cellComp_default = reactExports.memo(CellComp);
var RowComp = ({ rowCtrl, containerType }) => {
  const { context, gos, editSvc } = reactExports.useContext(BeansContext);
  const enableUses = reactExports.useContext(RenderModeContext) === "default";
  const compBean = reactExports.useRef();
  const domOrderRef = reactExports.useRef(rowCtrl.getDomOrder());
  const isFullWidth = rowCtrl.isFullWidth();
  const isDisplayed = rowCtrl.rowNode.displayed;
  const [rowIndex, setRowIndex] = reactExports.useState(
    () => isDisplayed ? rowCtrl.rowNode.getRowIndexString() : null
  );
  const [rowId, setRowId] = reactExports.useState(() => rowCtrl.rowId);
  const [rowBusinessKey, setRowBusinessKey] = reactExports.useState(() => rowCtrl.businessKey);
  const [userStyles, setUserStyles] = reactExports.useState(() => rowCtrl.rowStyles);
  const cellCtrlsRef = reactExports.useRef(null);
  const [cellCtrlsFlushSync, setCellCtrlsFlushSync] = reactExports.useState(() => null);
  const [fullWidthCompDetails, setFullWidthCompDetails] = reactExports.useState();
  const [top2, setTop] = reactExports.useState(
    () => isDisplayed ? rowCtrl.getInitialRowTop(containerType) : void 0
  );
  const [transform, setTransform] = reactExports.useState(
    () => isDisplayed ? rowCtrl.getInitialTransform(containerType) : void 0
  );
  const eGui = reactExports.useRef(null);
  const fullWidthCompRef = reactExports.useRef();
  const fullWidthParamsRef = reactExports.useRef();
  const autoHeightSetup = reactExports.useRef(false);
  const [autoHeightSetupAttempt, setAutoHeightSetupAttempt] = reactExports.useState(0);
  reactExports.useEffect(() => {
    if (autoHeightSetup.current || !fullWidthCompDetails || autoHeightSetupAttempt > 10) {
      return;
    }
    const eChild = eGui.current?.firstChild;
    if (eChild) {
      rowCtrl.setupDetailRowAutoHeight(eChild);
      autoHeightSetup.current = true;
    } else {
      setAutoHeightSetupAttempt((prev) => prev + 1);
    }
  }, [fullWidthCompDetails, autoHeightSetupAttempt]);
  const cssManager = reactExports.useRef();
  if (!cssManager.current) {
    cssManager.current = new CssClassManager(() => eGui.current);
  }
  const cellsChanged = reactExports.useRef(() => {
  });
  const sub = reactExports.useCallback((onStoreChange) => {
    cellsChanged.current = onStoreChange;
    return () => {
      cellsChanged.current = () => {
      };
    };
  }, []);
  const cellCtrlsUses = agUseSyncExternalStore(
    sub,
    () => {
      return cellCtrlsRef.current;
    },
    []
  );
  const cellCtrlsMerged = enableUses ? cellCtrlsUses : cellCtrlsFlushSync;
  const setRef2 = reactExports.useCallback((eRef) => {
    eGui.current = eRef;
    compBean.current = eRef ? context.createBean(new EmptyBean()) : context.destroyBean(compBean.current);
    if (!eRef) {
      rowCtrl.unsetComp(containerType);
      return;
    }
    if (!rowCtrl.isAlive() || context.isDestroyed()) {
      return;
    }
    const compProxy = {
      // the rowTop is managed by state, instead of direct style manipulation by rowCtrl (like all the other styles)
      // as we need to have an initial value when it's placed into he DOM for the first time, for animation to work.
      setTop,
      setTransform,
      // i found using React for managing classes at the row level was to slow, as modifying classes caused a lot of
      // React code to execute, so avoiding React for managing CSS Classes made the grid go much faster.
      toggleCss: (name2, on) => cssManager.current.toggleCss(name2, on),
      setDomOrder: (domOrder) => domOrderRef.current = domOrder,
      setRowIndex,
      setRowId,
      setRowBusinessKey,
      setUserStyles,
      // if we don't maintain the order, then cols will be ripped out and into the dom
      // when cols reordered, which would stop the CSS transitions from working
      setCellCtrls: (next, useFlushSync) => {
        const prevCellCtrls = cellCtrlsRef.current;
        const nextCells = getNextValueIfDifferent(prevCellCtrls, next, domOrderRef.current);
        if (nextCells !== prevCellCtrls) {
          cellCtrlsRef.current = nextCells;
          if (enableUses) {
            cellsChanged.current();
          } else {
            agFlushSync(useFlushSync, () => setCellCtrlsFlushSync(nextCells));
          }
        }
      },
      showFullWidth: (compDetails) => {
        fullWidthParamsRef.current = compDetails.params;
        setFullWidthCompDetails(compDetails);
      },
      getFullWidthCellRenderer: () => fullWidthCompRef.current,
      getFullWidthCellRendererParams: () => fullWidthParamsRef.current,
      refreshFullWidth: (getUpdatedParams) => {
        const fullWidthParams = getUpdatedParams();
        fullWidthParamsRef.current = fullWidthParams;
        if (canRefreshFullWidthRef.current) {
          setFullWidthCompDetails((prevFullWidthCompDetails) => ({
            ...prevFullWidthCompDetails,
            params: fullWidthParams
          }));
          return true;
        } else {
          if (!fullWidthCompRef.current || !fullWidthCompRef.current.refresh) {
            return false;
          }
          return fullWidthCompRef.current.refresh(fullWidthParams);
        }
      }
    };
    rowCtrl.setComp(compProxy, eRef, containerType, compBean.current);
  }, []);
  reactExports.useLayoutEffect(
    () => showJsComp(fullWidthCompDetails, context, eGui.current, fullWidthCompRef),
    [fullWidthCompDetails]
  );
  const rowStyles = reactExports.useMemo(() => {
    const res = { top: top2, transform };
    Object.assign(res, userStyles);
    return res;
  }, [top2, transform, userStyles]);
  const showFullWidthFramework = isFullWidth && fullWidthCompDetails?.componentFromFramework;
  const showCells = !isFullWidth && cellCtrlsMerged != null;
  const reactFullWidthCellRendererStateless = reactExports.useMemo(() => {
    const res = fullWidthCompDetails?.componentFromFramework && isComponentStateless(fullWidthCompDetails.componentClass);
    return !!res;
  }, [fullWidthCompDetails]);
  const canRefreshFullWidthRef = reactExports.useRef(false);
  reactExports.useEffect(() => {
    canRefreshFullWidthRef.current = reactFullWidthCellRendererStateless && !!fullWidthCompDetails && !!gos.get("reactiveCustomComponents");
  }, [reactFullWidthCellRendererStateless, fullWidthCompDetails]);
  const showCellsJsx = () => cellCtrlsMerged?.map((cellCtrl) => /* @__PURE__ */ React20.createElement(
    cellComp_default,
    {
      cellCtrl,
      editingCell: editSvc?.isEditing(cellCtrl, { withOpenEditor: true }) ?? false,
      printLayout: rowCtrl.printLayout,
      key: cellCtrl.instanceId
    }
  ));
  const showFullWidthFrameworkJsx = () => {
    const FullWidthComp = fullWidthCompDetails.componentClass;
    return reactFullWidthCellRendererStateless ? /* @__PURE__ */ React20.createElement(FullWidthComp, { ...fullWidthCompDetails.params }) : /* @__PURE__ */ React20.createElement(FullWidthComp, { ...fullWidthCompDetails.params, ref: fullWidthCompRef });
  };
  return /* @__PURE__ */ React20.createElement(
    "div",
    {
      ref: setRef2,
      role: "row",
      style: rowStyles,
      "row-index": rowIndex,
      "row-id": rowId,
      "row-business-key": rowBusinessKey
    },
    showCells ? showCellsJsx() : showFullWidthFramework ? showFullWidthFrameworkJsx() : null
  );
};
var rowComp_default = reactExports.memo(RowComp);
var RowContainerComp = ({ name: name2 }) => {
  const { context, gos } = reactExports.useContext(BeansContext);
  const containerOptions = reactExports.useMemo(() => _getRowContainerOptions(name2), [name2]);
  const eViewport = reactExports.useRef(null);
  const eContainer = reactExports.useRef(null);
  const eSpanContainer = reactExports.useRef(null);
  const rowCtrlsRef = reactExports.useRef([]);
  const prevRowCtrlsRef = reactExports.useRef([]);
  const [rowCtrlsOrdered, setRowCtrlsOrdered] = reactExports.useState(() => []);
  const isSpanning = !!gos.get("enableCellSpan") && !!containerOptions.getSpannedRowCtrls;
  const spannedRowCtrlsRef = reactExports.useRef([]);
  const prevSpannedRowCtrlsRef = reactExports.useRef([]);
  const [spannedRowCtrlsOrdered, setSpannedRowCtrlsOrdered] = reactExports.useState(() => []);
  const domOrderRef = reactExports.useRef(false);
  const rowContainerCtrlRef = reactExports.useRef();
  const viewportClasses = reactExports.useMemo(() => classesList("ag-viewport", _getRowViewportClass(name2)), [name2]);
  const containerClasses = reactExports.useMemo(() => classesList(_getRowContainerClass(name2)), [name2]);
  const spanClasses = reactExports.useMemo(() => classesList("ag-spanning-container", _getRowSpanContainerClass(name2)), [name2]);
  const shouldRenderViewport = containerOptions.type === "center" || isSpanning;
  const topLevelRef = shouldRenderViewport ? eViewport : eContainer;
  reactComment_default(" AG Row Container " + name2 + " ", topLevelRef);
  const areElementsReady = reactExports.useCallback(() => {
    const viewportReady = !shouldRenderViewport || eViewport.current != null;
    const containerReady = eContainer.current != null;
    const spanContainerReady = !isSpanning || eSpanContainer.current != null;
    return viewportReady && containerReady && spanContainerReady;
  }, []);
  const areElementsRemoved = reactExports.useCallback(() => {
    return eViewport.current == null && eContainer.current == null && eSpanContainer.current == null;
  }, []);
  const setRef2 = reactExports.useCallback(() => {
    if (areElementsRemoved()) {
      rowContainerCtrlRef.current = context.destroyBean(rowContainerCtrlRef.current);
    }
    if (context.isDestroyed()) {
      return;
    }
    if (areElementsReady()) {
      const updateRowCtrlsOrdered = (useFlushSync) => {
        const next = getNextValueIfDifferent(
          prevRowCtrlsRef.current,
          rowCtrlsRef.current,
          domOrderRef.current
        );
        if (next !== prevRowCtrlsRef.current) {
          prevRowCtrlsRef.current = next;
          agFlushSync(useFlushSync, () => setRowCtrlsOrdered(next));
        }
      };
      const updateSpannedRowCtrlsOrdered = (useFlushSync) => {
        const next = getNextValueIfDifferent(
          prevSpannedRowCtrlsRef.current,
          spannedRowCtrlsRef.current,
          domOrderRef.current
        );
        if (next !== prevSpannedRowCtrlsRef.current) {
          prevSpannedRowCtrlsRef.current = next;
          agFlushSync(useFlushSync, () => setSpannedRowCtrlsOrdered(next));
        }
      };
      const compProxy = {
        setHorizontalScroll: (offset3) => {
          if (eViewport.current) {
            eViewport.current.scrollLeft = offset3;
          }
        },
        setViewportHeight: (height) => {
          if (eViewport.current) {
            eViewport.current.style.height = height;
          }
        },
        setRowCtrls: ({ rowCtrls, useFlushSync }) => {
          const useFlush = !!useFlushSync && rowCtrlsRef.current.length > 0 && rowCtrls.length > 0;
          rowCtrlsRef.current = rowCtrls;
          updateRowCtrlsOrdered(useFlush);
        },
        setSpannedRowCtrls: (rowCtrls, useFlushSync) => {
          const useFlush = !!useFlushSync && spannedRowCtrlsRef.current.length > 0 && rowCtrls.length > 0;
          spannedRowCtrlsRef.current = rowCtrls;
          updateSpannedRowCtrlsOrdered(useFlush);
        },
        setDomOrder: (domOrder) => {
          if (domOrderRef.current != domOrder) {
            domOrderRef.current = domOrder;
            updateRowCtrlsOrdered(false);
          }
        },
        setContainerWidth: (width) => {
          if (eContainer.current) {
            eContainer.current.style.width = width;
          }
        },
        setOffsetTop: (offset3) => {
          if (eContainer.current) {
            eContainer.current.style.transform = `translateY(${offset3})`;
          }
        }
      };
      rowContainerCtrlRef.current = context.createBean(new RowContainerCtrl(name2));
      rowContainerCtrlRef.current.setComp(
        compProxy,
        eContainer.current,
        eSpanContainer.current ?? void 0,
        eViewport.current
      );
    }
  }, [areElementsReady, areElementsRemoved]);
  const setContainerRef = reactExports.useCallback(
    (e) => {
      eContainer.current = e;
      setRef2();
    },
    [setRef2]
  );
  const setSpanContainerRef = reactExports.useCallback(
    (e) => {
      eSpanContainer.current = e;
      setRef2();
    },
    [setRef2]
  );
  const setViewportRef = reactExports.useCallback(
    (e) => {
      eViewport.current = e;
      setRef2();
    },
    [setRef2]
  );
  const buildContainer = () => /* @__PURE__ */ React20.createElement(
    "div",
    {
      className: containerClasses,
      ref: setContainerRef,
      role: shouldRenderViewport ? "presentation" : "rowgroup"
    },
    rowCtrlsOrdered.map((rowCtrl) => /* @__PURE__ */ React20.createElement(rowComp_default, { rowCtrl, containerType: containerOptions.type, key: rowCtrl.instanceId }))
  );
  if (!shouldRenderViewport) {
    return buildContainer();
  }
  const buildSpanContainer = () => /* @__PURE__ */ React20.createElement("div", { className: spanClasses, ref: setSpanContainerRef, role: "presentation" }, spannedRowCtrlsOrdered.map((rowCtrl) => /* @__PURE__ */ React20.createElement(rowComp_default, { rowCtrl, containerType: containerOptions.type, key: rowCtrl.instanceId })));
  return /* @__PURE__ */ React20.createElement("div", { className: viewportClasses, ref: setViewportRef, role: "rowgroup" }, buildContainer(), isSpanning ? buildSpanContainer() : null);
};
var rowContainerComp_default = reactExports.memo(RowContainerComp);
var GridBodyComp = () => {
  const beans = reactExports.useContext(BeansContext);
  const { context, overlays } = beans;
  const [rowAnimationClass, setRowAnimationClass] = reactExports.useState("");
  const [topHeight, setTopHeight] = reactExports.useState(0);
  const [bottomHeight, setBottomHeight] = reactExports.useState(0);
  const [stickyTopHeight, setStickyTopHeight] = reactExports.useState("0px");
  const [stickyTopTop, setStickyTopTop] = reactExports.useState("0px");
  const [stickyTopWidth, setStickyTopWidth] = reactExports.useState("100%");
  const [stickyBottomHeight, setStickyBottomHeight] = reactExports.useState("0px");
  const [stickyBottomBottom, setStickyBottomBottom] = reactExports.useState("0px");
  const [stickyBottomWidth, setStickyBottomWidth] = reactExports.useState("100%");
  const [topInvisible, setTopInvisible] = reactExports.useState(true);
  const [bottomInvisible, setBottomInvisible] = reactExports.useState(true);
  const [forceVerticalScrollClass, setForceVerticalScrollClass] = reactExports.useState(null);
  const [topAndBottomOverflowY, setTopAndBottomOverflowY] = reactExports.useState("");
  const [cellSelectableCss, setCellSelectableCss] = reactExports.useState(null);
  const [layoutClass, setLayoutClass] = reactExports.useState("ag-layout-normal");
  const cssManager = reactExports.useRef();
  if (!cssManager.current) {
    cssManager.current = new CssClassManager(() => eRoot.current);
  }
  const eRoot = reactExports.useRef(null);
  const eTop = reactExports.useRef(null);
  const eStickyTop = reactExports.useRef(null);
  const eStickyBottom = reactExports.useRef(null);
  const eBody = reactExports.useRef(null);
  const eBodyViewport = reactExports.useRef(null);
  const eBottom = reactExports.useRef(null);
  const beansToDestroy = reactExports.useRef([]);
  const destroyFuncs = reactExports.useRef([]);
  reactComment_default(" AG Grid Body ", eRoot);
  reactComment_default(" AG Pinned Top ", eTop);
  reactComment_default(" AG Sticky Top ", eStickyTop);
  reactComment_default(" AG Middle ", eBodyViewport);
  reactComment_default(" AG Pinned Bottom ", eBottom);
  const setRef2 = reactExports.useCallback((eRef) => {
    eRoot.current = eRef;
    if (!eRef || context.isDestroyed()) {
      beansToDestroy.current = context.destroyBeans(beansToDestroy.current);
      for (const f of destroyFuncs.current) {
        f();
      }
      destroyFuncs.current = [];
      return;
    }
    const attachToDom = (eParent, eChild) => {
      eParent.appendChild(eChild);
      destroyFuncs.current.push(() => eChild.remove());
    };
    const newComp = (compClass) => {
      const comp = context.createBean(new compClass());
      beansToDestroy.current.push(comp);
      return comp;
    };
    const addComp = (eParent, compClass, comment2) => {
      attachToDom(eParent, document.createComment(comment2));
      attachToDom(eParent, newComp(compClass).getGui());
    };
    addComp(eRef, FakeHScrollComp, " AG Fake Horizontal Scroll ");
    const overlayComp = overlays?.getOverlayWrapperCompClass();
    if (overlayComp) {
      addComp(eRef, overlayComp, " AG Overlay Wrapper ");
    }
    if (eBody.current) {
      addComp(eBody.current, FakeVScrollComp, " AG Fake Vertical Scroll ");
    }
    const compProxy = {
      setRowAnimationCssOnBodyViewport: setRowAnimationClass,
      setColumnCount: (count2) => {
        if (eRoot.current) {
          _setAriaColCount(eRoot.current, count2);
        }
      },
      setRowCount: (count2) => {
        if (eRoot.current) {
          _setAriaRowCount(eRoot.current, count2);
        }
      },
      setTopHeight,
      setBottomHeight,
      setStickyTopHeight,
      setStickyTopTop,
      setStickyTopWidth,
      setTopInvisible,
      setBottomInvisible,
      setColumnMovingCss: (cssClass, flag) => cssManager.current.toggleCss(cssClass, flag),
      updateLayoutClasses: setLayoutClass,
      setAlwaysVerticalScrollClass: setForceVerticalScrollClass,
      setPinnedTopBottomOverflowY: setTopAndBottomOverflowY,
      setCellSelectableCss: (cssClass, flag) => setCellSelectableCss(flag ? cssClass : null),
      setBodyViewportWidth: (width) => {
        if (eBodyViewport.current) {
          eBodyViewport.current.style.width = width;
        }
      },
      registerBodyViewportResizeListener: (listener) => {
        if (eBodyViewport.current) {
          const unsubscribeFromResize = _observeResize(beans, eBodyViewport.current, listener);
          destroyFuncs.current.push(() => unsubscribeFromResize());
        }
      },
      setStickyBottomHeight,
      setStickyBottomBottom,
      setStickyBottomWidth,
      setGridRootRole: (role) => eRef.setAttribute("role", role)
    };
    const ctrl = context.createBean(new GridBodyCtrl());
    beansToDestroy.current.push(ctrl);
    ctrl.setComp(
      compProxy,
      eRef,
      eBodyViewport.current,
      eTop.current,
      eBottom.current,
      eStickyTop.current,
      eStickyBottom.current
    );
  }, []);
  const rootClasses = reactExports.useMemo(() => classesList("ag-root", "ag-unselectable", layoutClass), [layoutClass]);
  const bodyViewportClasses = reactExports.useMemo(
    () => classesList(
      "ag-body-viewport",
      rowAnimationClass,
      layoutClass,
      forceVerticalScrollClass,
      cellSelectableCss
    ),
    [rowAnimationClass, layoutClass, forceVerticalScrollClass, cellSelectableCss]
  );
  const bodyClasses = reactExports.useMemo(() => classesList("ag-body", layoutClass), [layoutClass]);
  const topClasses = reactExports.useMemo(
    () => classesList("ag-floating-top", topInvisible ? "ag-invisible" : null, cellSelectableCss),
    [cellSelectableCss, topInvisible]
  );
  const stickyTopClasses = reactExports.useMemo(() => classesList("ag-sticky-top", cellSelectableCss), [cellSelectableCss]);
  const stickyBottomClasses = reactExports.useMemo(
    () => classesList("ag-sticky-bottom", stickyBottomHeight === "0px" ? "ag-invisible" : null, cellSelectableCss),
    [cellSelectableCss, stickyBottomHeight]
  );
  const bottomClasses = reactExports.useMemo(
    () => classesList("ag-floating-bottom", bottomInvisible ? "ag-invisible" : null, cellSelectableCss),
    [cellSelectableCss, bottomInvisible]
  );
  const topStyle = reactExports.useMemo(
    () => ({
      height: topHeight,
      minHeight: topHeight,
      overflowY: topAndBottomOverflowY
    }),
    [topHeight, topAndBottomOverflowY]
  );
  const stickyTopStyle = reactExports.useMemo(
    () => ({
      height: stickyTopHeight,
      top: stickyTopTop,
      width: stickyTopWidth
    }),
    [stickyTopHeight, stickyTopTop, stickyTopWidth]
  );
  const stickyBottomStyle = reactExports.useMemo(
    () => ({
      height: stickyBottomHeight,
      bottom: stickyBottomBottom,
      width: stickyBottomWidth
    }),
    [stickyBottomHeight, stickyBottomBottom, stickyBottomWidth]
  );
  const bottomStyle = reactExports.useMemo(
    () => ({
      height: bottomHeight,
      minHeight: bottomHeight,
      overflowY: topAndBottomOverflowY
    }),
    [bottomHeight, topAndBottomOverflowY]
  );
  const createRowContainer = (container2) => /* @__PURE__ */ React20.createElement(rowContainerComp_default, { name: container2, key: `${container2}-container` });
  const createSection = ({
    section: section2,
    children: children2,
    className: className2,
    style: style2
  }) => /* @__PURE__ */ React20.createElement("div", { ref: section2, className: className2, role: "presentation", style: style2 }, children2.map(createRowContainer));
  return /* @__PURE__ */ React20.createElement("div", { ref: setRef2, className: rootClasses }, /* @__PURE__ */ React20.createElement(gridHeaderComp_default, null), createSection({
    section: eTop,
    className: topClasses,
    style: topStyle,
    children: ["topLeft", "topCenter", "topRight", "topFullWidth"]
  }), /* @__PURE__ */ React20.createElement("div", { className: bodyClasses, ref: eBody, role: "presentation" }, createSection({
    section: eBodyViewport,
    className: bodyViewportClasses,
    children: ["left", "center", "right", "fullWidth"]
  })), createSection({
    section: eStickyTop,
    className: stickyTopClasses,
    style: stickyTopStyle,
    children: ["stickyTopLeft", "stickyTopCenter", "stickyTopRight", "stickyTopFullWidth"]
  }), createSection({
    section: eStickyBottom,
    className: stickyBottomClasses,
    style: stickyBottomStyle,
    children: ["stickyBottomLeft", "stickyBottomCenter", "stickyBottomRight", "stickyBottomFullWidth"]
  }), createSection({
    section: eBottom,
    className: bottomClasses,
    style: bottomStyle,
    children: ["bottomLeft", "bottomCenter", "bottomRight", "bottomFullWidth"]
  }));
};
var gridBodyComp_default = reactExports.memo(GridBodyComp);
var TabGuardCompRef = (props, forwardRef4) => {
  const { children: children2, eFocusableElement, onTabKeyDown, gridCtrl, forceFocusOutWhenTabGuardsAreEmpty, isEmpty: isEmpty2 } = props;
  const { context } = reactExports.useContext(BeansContext);
  const topTabGuardRef = reactExports.useRef(null);
  const bottomTabGuardRef = reactExports.useRef(null);
  const tabGuardCtrlRef = reactExports.useRef();
  const setTabIndex = (value2) => {
    const processedValue = value2 == null ? void 0 : parseInt(value2, 10).toString();
    for (const tabGuard of [topTabGuardRef, bottomTabGuardRef]) {
      if (processedValue === void 0) {
        tabGuard.current?.removeAttribute("tabindex");
      } else {
        tabGuard.current?.setAttribute("tabindex", processedValue);
      }
    }
  };
  reactExports.useImperativeHandle(forwardRef4, () => ({
    forceFocusOutOfContainer(up) {
      tabGuardCtrlRef.current?.forceFocusOutOfContainer(up);
    }
  }));
  const setupCtrl = reactExports.useCallback(() => {
    const topTabGuard = topTabGuardRef.current;
    const bottomTabGuard = bottomTabGuardRef.current;
    if (!topTabGuard && !bottomTabGuard || context.isDestroyed()) {
      tabGuardCtrlRef.current = context.destroyBean(tabGuardCtrlRef.current);
      return;
    }
    if (topTabGuard && bottomTabGuard) {
      const compProxy = {
        setTabIndex
      };
      tabGuardCtrlRef.current = context.createBean(
        new TabGuardCtrl({
          comp: compProxy,
          eTopGuard: topTabGuard,
          eBottomGuard: bottomTabGuard,
          eFocusableElement,
          onTabKeyDown,
          forceFocusOutWhenTabGuardsAreEmpty,
          focusInnerElement: (fromBottom) => gridCtrl.focusInnerElement(fromBottom),
          isEmpty: isEmpty2
        })
      );
    }
  }, []);
  const setTopRef = reactExports.useCallback(
    (e) => {
      topTabGuardRef.current = e;
      setupCtrl();
    },
    [setupCtrl]
  );
  const setBottomRef = reactExports.useCallback(
    (e) => {
      bottomTabGuardRef.current = e;
      setupCtrl();
    },
    [setupCtrl]
  );
  const createTabGuard = (side) => {
    const className2 = side === "top" ? TabGuardClassNames.TAB_GUARD_TOP : TabGuardClassNames.TAB_GUARD_BOTTOM;
    return /* @__PURE__ */ React20.createElement(
      "div",
      {
        className: `${TabGuardClassNames.TAB_GUARD} ${className2}`,
        role: "presentation",
        ref: side === "top" ? setTopRef : setBottomRef
      }
    );
  };
  return /* @__PURE__ */ React20.createElement(React20.Fragment, null, createTabGuard("top"), children2, createTabGuard("bottom"));
};
var TabGuardComp2 = reactExports.forwardRef(TabGuardCompRef);
var tabGuardComp_default = reactExports.memo(TabGuardComp2);
var GridComp = ({ context }) => {
  const [rtlClass, setRtlClass] = reactExports.useState("");
  const [layoutClass, setLayoutClass] = reactExports.useState("");
  const [cursor, setCursor] = reactExports.useState(null);
  const [userSelect, setUserSelect] = reactExports.useState(null);
  const [initialised, setInitialised] = reactExports.useState(false);
  const [tabGuardReady, setTabGuardReady] = reactExports.useState();
  const gridCtrlRef = reactExports.useRef();
  const eRootWrapperRef = reactExports.useRef(null);
  const tabGuardRef = reactExports.useRef();
  const [eGridBodyParent, setGridBodyParent] = reactExports.useState(null);
  const focusInnerElementRef = reactExports.useRef(() => void 0);
  const paginationCompRef = reactExports.useRef();
  const focusableContainersRef = reactExports.useRef([]);
  const onTabKeyDown = reactExports.useCallback(() => void 0, []);
  reactComment_default(" AG Grid ", eRootWrapperRef);
  const setRef2 = reactExports.useCallback((eRef) => {
    eRootWrapperRef.current = eRef;
    gridCtrlRef.current = eRef ? context.createBean(new GridCtrl()) : context.destroyBean(gridCtrlRef.current);
    if (!eRef || context.isDestroyed()) {
      return;
    }
    const gridCtrl = gridCtrlRef.current;
    focusInnerElementRef.current = gridCtrl.focusInnerElement.bind(gridCtrl);
    const compProxy = {
      destroyGridUi: () => {
      },
      // do nothing, as framework users destroy grid by removing the comp
      setRtlClass,
      forceFocusOutOfContainer: (up) => {
        if (!up && paginationCompRef.current?.isDisplayed()) {
          paginationCompRef.current.forceFocusOutOfContainer(up);
          return;
        }
        tabGuardRef.current?.forceFocusOutOfContainer(up);
      },
      updateLayoutClasses: setLayoutClass,
      getFocusableContainers: () => {
        const comps = [];
        const gridBodyCompEl = eRootWrapperRef.current?.querySelector(".ag-root");
        if (gridBodyCompEl) {
          comps.push({ getGui: () => gridBodyCompEl });
        }
        for (const comp of focusableContainersRef.current) {
          if (comp.isDisplayed()) {
            comps.push(comp);
          }
        }
        return comps;
      },
      setCursor,
      setUserSelect
    };
    gridCtrl.setComp(compProxy, eRef, eRef);
    setInitialised(true);
  }, []);
  reactExports.useEffect(() => {
    const gridCtrl = gridCtrlRef.current;
    const eRootWrapper = eRootWrapperRef.current;
    if (!tabGuardReady || !gridCtrl || !eGridBodyParent || !eRootWrapper || context.isDestroyed()) {
      return;
    }
    const beansToDestroy = [];
    const {
      watermarkSelector,
      paginationSelector,
      sideBarSelector,
      statusBarSelector,
      gridHeaderDropZonesSelector
    } = gridCtrl.getOptionalSelectors();
    const additionalEls = [];
    if (gridHeaderDropZonesSelector) {
      const headerDropZonesComp = context.createBean(new gridHeaderDropZonesSelector.component());
      const eGui = headerDropZonesComp.getGui();
      eRootWrapper.insertAdjacentElement("afterbegin", eGui);
      additionalEls.push(eGui);
      beansToDestroy.push(headerDropZonesComp);
    }
    if (sideBarSelector) {
      const sideBarComp = context.createBean(new sideBarSelector.component());
      const eGui = sideBarComp.getGui();
      const bottomTabGuard = eGridBodyParent.querySelector(".ag-tab-guard-bottom");
      if (bottomTabGuard) {
        bottomTabGuard.insertAdjacentElement("beforebegin", eGui);
        additionalEls.push(eGui);
      }
      beansToDestroy.push(sideBarComp);
      focusableContainersRef.current.push(sideBarComp);
    }
    const addComponentToDom = (component) => {
      const comp = context.createBean(new component());
      const eGui = comp.getGui();
      eRootWrapper.insertAdjacentElement("beforeend", eGui);
      additionalEls.push(eGui);
      beansToDestroy.push(comp);
      return comp;
    };
    if (statusBarSelector) {
      addComponentToDom(statusBarSelector.component);
    }
    if (paginationSelector) {
      const paginationComp = addComponentToDom(paginationSelector.component);
      paginationCompRef.current = paginationComp;
      focusableContainersRef.current.push(paginationComp);
    }
    if (watermarkSelector) {
      addComponentToDom(watermarkSelector.component);
    }
    return () => {
      context.destroyBeans(beansToDestroy);
      for (const el of additionalEls) {
        el.remove();
      }
    };
  }, [tabGuardReady, eGridBodyParent, context]);
  const rootWrapperClasses = reactExports.useMemo(
    () => classesList("ag-root-wrapper", rtlClass, layoutClass),
    [rtlClass, layoutClass]
  );
  const rootWrapperBodyClasses = reactExports.useMemo(
    () => classesList("ag-root-wrapper-body", "ag-focus-managed", layoutClass),
    [layoutClass]
  );
  const topStyle = reactExports.useMemo(
    () => ({
      userSelect: userSelect != null ? userSelect : "",
      WebkitUserSelect: userSelect != null ? userSelect : "",
      cursor: cursor != null ? cursor : ""
    }),
    [userSelect, cursor]
  );
  const setTabGuardCompRef = reactExports.useCallback((ref2) => {
    tabGuardRef.current = ref2;
    setTabGuardReady(ref2 !== null);
  }, []);
  const isFocusable = reactExports.useCallback(() => !gridCtrlRef.current?.isFocusable(), []);
  return /* @__PURE__ */ React20.createElement("div", { ref: setRef2, className: rootWrapperClasses, style: topStyle, role: "presentation" }, /* @__PURE__ */ React20.createElement("div", { className: rootWrapperBodyClasses, ref: setGridBodyParent, role: "presentation" }, initialised && eGridBodyParent && !context.isDestroyed() && /* @__PURE__ */ React20.createElement(BeansContext.Provider, { value: context.getBeans() }, /* @__PURE__ */ React20.createElement(
    tabGuardComp_default,
    {
      ref: setTabGuardCompRef,
      eFocusableElement: eGridBodyParent,
      onTabKeyDown,
      gridCtrl: gridCtrlRef.current,
      forceFocusOutWhenTabGuardsAreEmpty: true,
      isEmpty: isFocusable
    },
    // we wait for initialised before rending the children, so GridComp has created and registered with it's
    // GridCtrl before we create the child GridBodyComp. Otherwise the GridBodyComp would initialise first,
    // before we have set the the Layout CSS classes, causing the GridBodyComp to render rows to a grid that
    // doesn't have it's height specified, which would result if all the rows getting rendered (and if many rows,
    // hangs the UI)
    /* @__PURE__ */ React20.createElement(gridBodyComp_default, null)
  ))));
};
var gridComp_default = reactExports.memo(GridComp);
var RenderStatusService = class extends BeanStub {
  postConstruct() {
    if (this.beans.colAutosize) {
      const queueResizeOperationsForTick = this.queueResizeOperationsForTick.bind(this);
      this.addManagedEventListeners({
        rowExpansionStateChanged: queueResizeOperationsForTick,
        expandOrCollapseAll: queueResizeOperationsForTick,
        // Enable devs to resize after they updated via the API
        cellValueChanged: queueResizeOperationsForTick,
        rowNodeDataChanged: queueResizeOperationsForTick,
        rowDataUpdated: queueResizeOperationsForTick
      });
    }
  }
  queueResizeOperationsForTick() {
    const colAutosize = this.beans.colAutosize;
    colAutosize.shouldQueueResizeOperations = true;
    setTimeout(() => {
      colAutosize.processResizeOperations();
    }, 0);
  }
  areHeaderCellsRendered() {
    return this.beans.ctrlsSvc.getHeaderRowContainerCtrls().every((container2) => container2.getAllCtrls().every((ctrl) => ctrl.areCellsRendered()));
  }
  areCellsRendered() {
    return this.beans.rowRenderer.getAllRowCtrls().every((row2) => row2.isRowRendered() && row2.getAllCellCtrls().every((cellCtrl) => !!cellCtrl.eGui));
  }
};
var deprecatedProps = {
  setGridApi: void 0,
  maxComponentCreationTimeMs: void 0,
  children: void 0
};
var reactPropsNotGridOptions = {
  gridOptions: void 0,
  modules: void 0,
  containerStyle: void 0,
  className: void 0,
  passGridApi: void 0,
  componentWrappingElement: void 0,
  ...deprecatedProps
};
var excludeReactCompProps = new Set(Object.keys(reactPropsNotGridOptions));
var deprecatedReactCompProps = new Set(Object.keys(deprecatedProps));
var AgGridReactUi = (props) => {
  const apiRef = reactExports.useRef();
  const eGui = reactExports.useRef(null);
  const portalManager = reactExports.useRef(null);
  const destroyFuncs = reactExports.useRef([]);
  const whenReadyFuncs = reactExports.useRef([]);
  const prevProps = reactExports.useRef(props);
  const frameworkOverridesRef = reactExports.useRef();
  const gridIdRef = reactExports.useRef();
  const ready = reactExports.useRef(false);
  const [context, setContext] = reactExports.useState(void 0);
  const [, setPortalRefresher] = reactExports.useState(0);
  const setRef2 = reactExports.useCallback((eRef) => {
    eGui.current = eRef;
    if (!eRef) {
      for (const f of destroyFuncs.current) {
        f();
      }
      destroyFuncs.current.length = 0;
      return;
    }
    const modules = props.modules || [];
    if (!portalManager.current) {
      portalManager.current = new PortalManager(
        () => setPortalRefresher((prev) => prev + 1),
        props.componentWrappingElement,
        props.maxComponentCreationTimeMs
      );
      destroyFuncs.current.push(() => {
        portalManager.current?.destroy();
        portalManager.current = null;
      });
    }
    const mergedGridOps = _combineAttributesAndGridOptions(
      props.gridOptions,
      props,
      Object.keys(props).filter((key2) => !excludeReactCompProps.has(key2))
    );
    const processQueuedUpdates = () => {
      if (ready.current) {
        const getFn = () => frameworkOverridesRef.current?.shouldQueueUpdates() ? void 0 : whenReadyFuncs.current.shift();
        let fn3 = getFn();
        while (fn3) {
          fn3();
          fn3 = getFn();
        }
      }
    };
    const frameworkOverrides = new ReactFrameworkOverrides(processQueuedUpdates);
    frameworkOverridesRef.current = frameworkOverrides;
    const renderStatus = new RenderStatusService();
    const gridParams = {
      providedBeanInstances: {
        frameworkCompWrapper: new ReactFrameworkComponentWrapper(portalManager.current, mergedGridOps),
        renderStatus
      },
      modules,
      frameworkOverrides,
      setThemeOnGridDiv: true
    };
    const createUiCallback = (ctx) => {
      setContext(ctx);
      ctx.createBean(renderStatus);
      destroyFuncs.current.push(() => {
        ctx.destroy();
      });
      ctx.getBean("ctrlsSvc").whenReady(
        {
          addDestroyFunc: (func2) => {
            destroyFuncs.current.push(func2);
          }
        },
        () => {
          if (ctx.isDestroyed()) {
            return;
          }
          const api2 = apiRef.current;
          if (api2) {
            props.passGridApi?.(api2);
          }
        }
      );
    };
    const acceptChangesCallback = (context2) => {
      context2.getBean("ctrlsSvc").whenReady(
        {
          addDestroyFunc: (func2) => {
            destroyFuncs.current.push(func2);
          }
        },
        () => {
          for (const f of whenReadyFuncs.current) {
            f();
          }
          whenReadyFuncs.current.length = 0;
          ready.current = true;
        }
      );
    };
    const gridCoreCreator = new GridCoreCreator();
    mergedGridOps.gridId ?? (mergedGridOps.gridId = gridIdRef.current);
    apiRef.current = gridCoreCreator.create(
      eRef,
      mergedGridOps,
      createUiCallback,
      acceptChangesCallback,
      gridParams
    );
    destroyFuncs.current.push(() => {
      apiRef.current = void 0;
    });
    if (apiRef.current) {
      gridIdRef.current = apiRef.current.getGridId();
    }
  }, []);
  const style2 = reactExports.useMemo(() => {
    return {
      height: "100%",
      ...props.containerStyle || {}
    };
  }, [props.containerStyle]);
  const processWhenReady = reactExports.useCallback((func2) => {
    if (ready.current && !frameworkOverridesRef.current?.shouldQueueUpdates()) {
      func2();
    } else {
      whenReadyFuncs.current.push(func2);
    }
  }, []);
  reactExports.useEffect(() => {
    const changes = extractGridPropertyChanges(prevProps.current, props);
    prevProps.current = props;
    processWhenReady(() => {
      if (apiRef.current) {
        _processOnChange(changes, apiRef.current);
      }
    });
  }, [props]);
  const renderMode = !React20.useSyncExternalStore || _getGridOption(props, "renderingMode") === "legacy" ? "legacy" : "default";
  return /* @__PURE__ */ React20.createElement("div", { style: style2, className: props.className, ref: setRef2 }, /* @__PURE__ */ React20.createElement(RenderModeContext.Provider, { value: renderMode }, context && !context.isDestroyed() ? /* @__PURE__ */ React20.createElement(gridComp_default, { key: context.instanceId, context }) : null, portalManager.current?.getPortals() ?? null));
};
function extractGridPropertyChanges(prevProps, nextProps) {
  const changes = {};
  for (const propKey of Object.keys(nextProps)) {
    if (excludeReactCompProps.has(propKey)) {
      if (deprecatedReactCompProps.has(propKey)) {
        _warn(274, { prop: propKey });
      }
      continue;
    }
    const propValue = nextProps[propKey];
    if (prevProps[propKey] !== propValue) {
      changes[propKey] = propValue;
    }
  }
  return changes;
}
var ReactFrameworkComponentWrapper = class extends BaseComponentWrapper {
  constructor(parent, gridOptions) {
    super();
    this.parent = parent;
    this.gridOptions = gridOptions;
  }
  createWrapper(UserReactComponent, componentType) {
    const gridOptions = this.gridOptions;
    const reactiveCustomComponents = _getGridOption(gridOptions, "reactiveCustomComponents");
    if (reactiveCustomComponents) {
      const getComponentClass = (propertyName) => {
        switch (propertyName) {
          case "filter":
            return _getGridOption(gridOptions, "enableFilterHandlers") ? FilterDisplayComponentWrapper : FilterComponentWrapper;
          case "floatingFilterComponent":
            return _getGridOption(gridOptions, "enableFilterHandlers") ? FloatingFilterDisplayComponentWrapper : FloatingFilterComponentWrapper;
          case "dateComponent":
            return DateComponentWrapper;
          case "dragAndDropImageComponent":
            return DragAndDropImageComponentWrapper;
          case "loadingOverlayComponent":
            return LoadingOverlayComponentWrapper;
          case "noRowsOverlayComponent":
            return NoRowsOverlayComponentWrapper;
          case "statusPanel":
            return StatusPanelComponentWrapper;
          case "toolPanel":
            return ToolPanelComponentWrapper;
          case "menuItem":
            return MenuItemComponentWrapper;
          case "cellRenderer":
            return CellRendererComponentWrapper;
          case "innerHeaderComponent":
            return InnerHeaderComponentWrapper;
        }
      };
      const ComponentClass = getComponentClass(componentType.name);
      if (ComponentClass) {
        return new ComponentClass(UserReactComponent, this.parent, componentType);
      }
    } else {
      switch (componentType.name) {
        case "filter":
        case "floatingFilterComponent":
        case "dateComponent":
        case "dragAndDropImageComponent":
        case "loadingOverlayComponent":
        case "noRowsOverlayComponent":
        case "statusPanel":
        case "toolPanel":
        case "menuItem":
        case "cellRenderer":
          warnReactiveCustomComponents();
          break;
      }
    }
    const suppressFallbackMethods = !componentType.cellRenderer && componentType.name !== "toolPanel";
    return new ReactComponent(UserReactComponent, this.parent, componentType, suppressFallbackMethods);
  }
};
var DetailCellRenderer = reactExports.forwardRef((props, ref2) => {
  const beans = reactExports.useContext(BeansContext);
  const { registry, context, gos, rowModel } = beans;
  const [cssClasses, setCssClasses] = reactExports.useState(() => new CssClasses());
  const [gridCssClasses, setGridCssClasses] = reactExports.useState(() => new CssClasses());
  const [detailGridOptions, setDetailGridOptions] = reactExports.useState();
  const [detailRowData, setDetailRowData] = reactExports.useState();
  const ctrlRef = reactExports.useRef();
  const eGuiRef = reactExports.useRef(null);
  const resizeObserverDestroyFunc = reactExports.useRef();
  const parentModules = reactExports.useMemo(
    () => _getGridRegisteredModules(props.api.getGridId(), detailGridOptions?.rowModelType ?? "clientSide"),
    [props]
  );
  const topClassName = reactExports.useMemo(() => cssClasses.toString() + " ag-details-row", [cssClasses]);
  const gridClassName = reactExports.useMemo(() => gridCssClasses.toString() + " ag-details-grid", [gridCssClasses]);
  if (ref2) {
    reactExports.useImperativeHandle(ref2, () => ({
      refresh() {
        return ctrlRef.current?.refresh() ?? false;
      }
    }));
  }
  if (props.template) {
    _warn(230);
  }
  const setRef2 = reactExports.useCallback((eRef) => {
    eGuiRef.current = eRef;
    if (!eRef || context.isDestroyed()) {
      ctrlRef.current = context.destroyBean(ctrlRef.current);
      resizeObserverDestroyFunc.current?.();
      return;
    }
    const compProxy = {
      toggleCss: (name2, on) => setCssClasses((prev) => prev.setClass(name2, on)),
      toggleDetailGridCss: (name2, on) => setGridCssClasses((prev) => prev.setClass(name2, on)),
      setDetailGrid: (gridOptions) => setDetailGridOptions(gridOptions),
      setRowData: (rowData) => setDetailRowData(rowData),
      getGui: () => eGuiRef.current
    };
    const ctrl = registry.createDynamicBean("detailCellRendererCtrl", true);
    if (!ctrl) {
      return;
    }
    context.createBean(ctrl);
    ctrl.init(compProxy, props);
    ctrlRef.current = ctrl;
    if (gos.get("detailRowAutoHeight")) {
      const checkRowSizeFunc = () => {
        if (eGuiRef.current == null) {
          return;
        }
        const clientHeight = eGuiRef.current.clientHeight;
        if (clientHeight != null && clientHeight > 0) {
          const updateRowHeightFunc = () => {
            props.node.setRowHeight(clientHeight);
            if (_isClientSideRowModel(gos) || _isServerSideRowModel(gos)) {
              rowModel.onRowHeightChanged();
            }
          };
          setTimeout(updateRowHeightFunc, 0);
        }
      };
      resizeObserverDestroyFunc.current = _observeResize(beans, eRef, checkRowSizeFunc);
      checkRowSizeFunc();
    }
  }, []);
  const registerGridApi = reactExports.useCallback((api2) => {
    ctrlRef.current?.registerDetailWithMaster(api2);
  }, []);
  return /* @__PURE__ */ React20.createElement("div", { className: topClassName, ref: setRef2 }, detailGridOptions && /* @__PURE__ */ React20.createElement(
    AgGridReactUi,
    {
      className: gridClassName,
      ...detailGridOptions,
      modules: parentModules,
      rowData: detailRowData,
      passGridApi: registerGridApi
    }
  ));
});
var ReactFrameworkOverrides = class extends VanillaFrameworkOverrides {
  constructor(processQueuedUpdates) {
    super("react");
    this.processQueuedUpdates = processQueuedUpdates;
    this.queueUpdates = false;
    this.renderingEngine = "react";
    this.frameworkComponents = {
      agGroupCellRenderer: groupCellRenderer_default,
      agGroupRowRenderer: groupCellRenderer_default,
      agDetailCellRenderer: DetailCellRenderer
    };
    this.wrapIncoming = (callback, source2) => {
      if (source2 === "ensureVisible") {
        return runWithoutFlushSync(callback);
      }
      return callback();
    };
  }
  frameworkComponent(name2) {
    return this.frameworkComponents[name2];
  }
  isFrameworkComponent(comp) {
    if (!comp) {
      return false;
    }
    const prototype = comp.prototype;
    const isJsComp = prototype && "getGui" in prototype;
    return !isJsComp;
  }
  getLockOnRefresh() {
    this.queueUpdates = true;
  }
  releaseLockOnRefresh() {
    this.queueUpdates = false;
    this.processQueuedUpdates();
  }
  shouldQueueUpdates() {
    return this.queueUpdates;
  }
  runWhenReadyAsync() {
    return isReact19();
  }
};
var AgGridReact = class extends reactExports.Component {
  constructor() {
    super(...arguments);
    this.apiListeners = [];
    this.setGridApi = (api2) => {
      this.api = api2;
      for (const listener of this.apiListeners) {
        listener(api2);
      }
    };
  }
  registerApiListener(listener) {
    this.apiListeners.push(listener);
  }
  componentWillUnmount() {
    this.apiListeners.length = 0;
  }
  render() {
    return /* @__PURE__ */ React20.createElement(AgGridReactUi, { ...this.props, passGridApi: this.setGridApi });
  }
};
const gridWrapper$1 = "_gridWrapper_1jp8e_1";
const row$3 = "_row_1jp8e_11";
const green = "_green_1jp8e_15";
const red = "_red_1jp8e_19";
const yellow = "_yellow_1jp8e_23";
const blue = "_blue_1jp8e_27";
const styles$k = {
  gridWrapper: gridWrapper$1,
  row: row$3,
  green,
  red,
  yellow,
  blue
};
ModuleRegistry.registerModules([AllCommunityModule]);
const GRID_STATE_NAME$1 = "ScanJobsGrid";
const ScanJobGrid = () => {
  const params = useParams();
  const paramsRelativePath = getRelativePathFromParams(params);
  const scans = useStore((state) => state.scans);
  const navigate = useNavigate();
  const gridStates = useStore((state) => state.gridStates);
  const setGridState = useStore((state) => state.setGridState);
  const setVisibleScanJobCount = useStore(
    (state) => state.setVisibleScanJobCount
  );
  const resultsDir = useStore((state) => state.resultsDir);
  const gridState = reactExports.useMemo(() => {
    const savedState = gridStates[GRID_STATE_NAME$1];
    if (!savedState?.sort) {
      return {
        sort: {
          sortModel: [
            { colId: "type", sort: "asc" },
            { colId: "timestamp", sort: "desc" }
          ]
        }
      };
    }
    return savedState;
  }, [gridStates]);
  const data2 = reactExports.useMemo(() => {
    const dirs = /* @__PURE__ */ new Set();
    const rows = [];
    scans.forEach((scan2) => {
      const relativeLocation = toRelativePath(scan2.location, resultsDir || "");
      const icon2 = scan2.complete ? ApplicationIcons.success : scan2.errors.length > 0 ? ApplicationIcons.error : ApplicationIcons.pendingTask;
      const color = scan2.complete ? "green" : scan2.errors.length > 0 ? "red" : "yellow";
      const dir = dirname(relativeLocation);
      if (dir === paramsRelativePath) {
        const row2 = {
          icon: icon2,
          color,
          type: "file",
          timestamp: scan2.spec.timestamp,
          location: scan2.location,
          relativeLocation,
          scanId: scan2.spec.scan_id,
          scanName: scan2.spec.scan_name,
          model: scan2.spec.model.model,
          status: scan2.errors.length > 1 ? "error" : scan2.complete ? "complete" : "incomplete",
          scanners: Object.keys(scan2.spec.scanners).map((s) => s)
        };
        rows.push(row2);
      }
      if (!dirs.has(dir) && dir !== "" && dir !== paramsRelativePath) {
        dirs.add(dir);
        const dirRow = {
          timestamp: "",
          location: "",
          icon: ApplicationIcons.folder,
          type: "directory",
          color: "blue",
          relativeLocation: dir,
          scanId: "",
          scanName: dir,
          model: "",
          status: "incomplete",
          scanners: []
        };
        rows.push(dirRow);
      }
    });
    return rows;
  }, [scans, resultsDir, paramsRelativePath]);
  reactExports.useEffect(() => {
    setVisibleScanJobCount(data2.length);
  }, [data2.length, setVisibleScanJobCount]);
  const columnDefs = reactExports.useMemo(() => {
    const baseColumns = [
      {
        field: "icon",
        headerName: "",
        initialWidth: 60,
        minWidth: 60,
        maxWidth: 60,
        sortable: true,
        filter: true,
        resizable: true,
        cellRenderer: (params2) => {
          const color = params2.data.color;
          return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("i", { className: clsx(params2.value, classNameForColor(color)) }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanJobs/ScanJobGrid.tsx",
            lineNumber: 161,
            columnNumber: 13
          }, void 0);
        }
      },
      {
        field: "scanName",
        headerName: "Name",
        initialWidth: 120,
        minWidth: 80,
        sortable: true,
        filter: true,
        resizable: true
      },
      {
        field: "scanners",
        headerName: "Scanners",
        initialWidth: 120,
        minWidth: 120,
        sortable: true,
        filter: true,
        resizable: true,
        valueGetter: (params2) => {
          const scanners = params2.data?.scanners;
          return Array.isArray(scanners) ? scanners.join(", ") : "";
        }
      },
      {
        field: "scanId",
        headerName: "Scan Id",
        initialWidth: 150,
        minWidth: 100,
        sortable: true,
        filter: true,
        resizable: true
      },
      {
        field: "model",
        headerName: "Model",
        initialWidth: 120,
        minWidth: 80,
        sortable: true,
        filter: true,
        resizable: true
      },
      {
        field: "timestamp",
        headerName: "Time",
        initialWidth: 150,
        minWidth: 100,
        sortable: true,
        filter: true,
        resizable: true,
        valueGetter: (params2) => {
          const timestamp2 = params2.data?.timestamp;
          return timestamp2 ? new Date(timestamp2).toLocaleString() : "";
        }
      }
    ];
    return baseColumns;
  }, []);
  const gridRef = reactExports.useRef(null);
  const resizeGridColumns = reactExports.useCallback(
    debounce$2(() => {
      gridRef.current?.api?.sizeColumnsToFit();
    }, 10),
    []
  );
  const onFilterChanged2 = reactExports.useCallback(
    (event) => {
      const displayedRowCount = event.api.getDisplayedRowCount();
      setVisibleScanJobCount(displayedRowCount);
    },
    [setVisibleScanJobCount]
  );
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: styles$k.gridWrapper, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    AgGridReact,
    {
      ref: gridRef,
      rowData: data2,
      columnDefs,
      defaultColDef: {
        sortable: true,
        filter: true,
        resizable: true
      },
      animateRows: false,
      suppressColumnMoveAnimation: true,
      suppressCellFocus: true,
      theme: themeBalham,
      enableCellTextSelection: true,
      autoSizeStrategy: { type: "fitGridWidth" },
      initialState: gridState,
      onStateUpdated: (e) => {
        setGridState(GRID_STATE_NAME$1, e.state);
      },
      rowClass: styles$k.row,
      onRowClicked: (e) => {
        if (e.data) {
          void navigate(`/scan/${e.data.relativeLocation}`);
        }
      },
      onGridSizeChanged: resizeGridColumns,
      onFilterChanged: onFilterChanged2
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanJobs/ScanJobGrid.tsx",
      lineNumber: 243,
      columnNumber: 7
    },
    void 0
  ) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanJobs/ScanJobGrid.tsx",
    lineNumber: 242,
    columnNumber: 5
  }, void 0);
};
const classNameForColor = (color) => {
  switch (color) {
    case "green":
      return styles$k.green;
    case "yellow":
      return styles$k.yellow;
    case "red":
      return styles$k.red;
    case "blue":
      return styles$k.blue;
    default:
      return "";
  }
};
const container$6 = "_container_18ufx_1";
const styles$j = {
  container: container$6
};
const ScanJobsPanel = () => {
  useServerScans();
  const loading = useStore((state) => state.loading);
  const error2 = useStore((state) => state.scopedErrors["scanjobs"]);
  const visibleScanJobCount = useStore((state) => state.visibleScanJobCount);
  const clearScansState = useStore((state) => state.clearScansState);
  reactExports.useEffect(() => {
    clearScansState();
  }, []);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$j.container), children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Navbar, { bordered: false }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanJobs/ScanJobsPanel.tsx",
      lineNumber: 30,
      columnNumber: 7
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ActivityBar, { animating: !!loading }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanJobs/ScanJobsPanel.tsx",
      lineNumber: 31,
      columnNumber: 7
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ExtendedFindProvider, { children: [
      error2 && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ErrorPanel, { title: "Error Loading Scans", error: { message: error2 } }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanJobs/ScanJobsPanel.tsx",
        lineNumber: 34,
        columnNumber: 11
      }, void 0),
      !error2 && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ScanJobGrid, {}, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanJobs/ScanJobsPanel.tsx",
        lineNumber: 36,
        columnNumber: 20
      }, void 0),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        Footer2,
        {
          id: "scan-job-footer",
          itemCount: visibleScanJobCount || 0,
          paginated: false
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanJobs/ScanJobsPanel.tsx",
          lineNumber: 37,
          columnNumber: 9
        },
        void 0
      )
    ] }, void 0, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanJobs/ScanJobsPanel.tsx",
      lineNumber: 32,
      columnNumber: 7
    }, void 0)
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanJobs/ScanJobsPanel.tsx",
    lineNumber: 29,
    columnNumber: 5
  }, void 0);
};
const root$1 = "_root_ke0e7_1";
const styles$i = {
  root: root$1
};
const gridWrapper = "_gridWrapper_bykj9_1";
const styles$h = {
  gridWrapper
};
ModuleRegistry.registerModules([AllCommunityModule]);
const GRID_STATE_NAME = "DataframeView";
const DataframeView = ({
  columnTable,
  sortedColumns,
  onRowDoubleClicked,
  onVisibleRowCountChanged,
  options,
  enableKeyboardNavigation = true,
  showRowNumbers = false,
  wrapText = false
}) => {
  const selectedDataframeRow = useStore((state) => state.selectedResultRow) || 0;
  const setSelectedDataframeRow = useStore(
    (state) => state.setSelectedResultRow
  );
  const setGridState = useStore((state) => state.setGridState);
  const gridState = useStore((state) => state.gridStates[GRID_STATE_NAME]);
  const { columnDefs, rowData } = reactExports.useMemo(() => {
    const columnNames = sortedColumns || columnTable?.columnNames() || [];
    const dataColumnDefs = columnTable ? columnNames.map((name2) => {
      const col = columnTable.column(name2);
      if (!col) {
        return void 0;
      }
      const sampleValue = col?.at(0);
      const valueFormatter = options ? (params) => {
        if (params.value === null || params.value === void 0) {
          return String(params.value);
        }
        if (typeof params.value === "string") {
          return centerTruncate(params.value, options.maxStrLen);
        }
        return String(params.value);
      } : void 0;
      return {
        field: name2,
        headerName: name2,
        sortable: true,
        filter: true,
        resizable: true,
        tooltipField: name2,
        maxWidth: 800,
        cellDataType: typeof sampleValue === "boolean" ? false : void 0,
        hide: !columnNames?.includes(name2) || false,
        valueFormatter,
        wrapText,
        autoHeight: wrapText
      };
    }).filter((c2) => c2 !== void 0) : [];
    const columnDefs2 = showRowNumbers ? [
      {
        headerName: "",
        valueGetter: (params) => {
          return params.node?.rowIndex !== void 0 && params.node?.rowIndex !== null ? params.node.rowIndex + 1 : "";
        },
        sortable: false,
        filter: false,
        resizable: false,
        width: 60,
        maxWidth: 60,
        minWidth: 60,
        pinned: "left",
        suppressMovable: true,
        cellClass: "row-number-cell",
        cellStyle: {
          textAlign: "right",
          paddingRight: "12px"
        },
        onCellClicked: (params) => {
          if (params.data && onRowDoubleClicked) {
            if (params.rowIndex !== null && params.rowIndex !== void 0) {
              setSelectedDataframeRow(params.rowIndex);
            }
            onRowDoubleClicked(params.data);
          }
        }
      },
      ...dataColumnDefs
    ] : dataColumnDefs;
    const rowData2 = columnTable?.objects();
    return { columnDefs: columnDefs2, rowData: rowData2 };
  }, [
    columnTable,
    sortedColumns,
    options,
    showRowNumbers,
    wrapText,
    onRowDoubleClicked,
    setSelectedDataframeRow
  ]);
  const gridRef = reactExports.useRef(null);
  reactExports.useEffect(() => {
    if (gridRef.current?.api && gridState && !gridState.filter) {
      const currentFilterModel = gridRef.current.api.getFilterModel();
      if (currentFilterModel && Object.keys(currentFilterModel).length > 0) {
        gridRef.current.api.setFilterModel(null);
      }
    }
  }, [gridState]);
  reactExports.useEffect(() => {
    if (gridRef.current?.api && selectedDataframeRow >= 0) {
      gridRef.current.api.forEachNode((node2) => {
        node2.setSelected(node2.rowIndex === selectedDataframeRow);
      });
      gridRef.current.api.ensureIndexVisible(selectedDataframeRow);
    }
  }, [selectedDataframeRow]);
  const handleNext = reactExports.useCallback(() => {
    const totalRows = rowData?.length ?? 0;
    if (selectedDataframeRow < totalRows - 1) {
      setSelectedDataframeRow(selectedDataframeRow + 1);
    }
  }, [selectedDataframeRow, rowData]);
  const handlePrevious = reactExports.useCallback(() => {
    if (selectedDataframeRow > 0) {
      setSelectedDataframeRow(selectedDataframeRow - 1);
    }
  }, [selectedDataframeRow]);
  const handleEnter = reactExports.useCallback(() => {
    if (gridRef.current?.api && selectedDataframeRow >= 0 && onRowDoubleClicked) {
      const selectedNode = gridRef.current.api.getDisplayedRowAtIndex(selectedDataframeRow);
      if (selectedNode?.data) {
        onRowDoubleClicked(selectedNode.data);
      }
    }
  }, [selectedDataframeRow, onRowDoubleClicked]);
  reactExports.useEffect(() => {
    if (!enableKeyboardNavigation) {
      return;
    }
    const handleGlobalKeyDown = (e) => {
      const activeElement = document.activeElement;
      const isInputFocused = activeElement && (activeElement.tagName === "INPUT" || activeElement.tagName === "TEXTAREA" || activeElement.tagName === "SELECT");
      if (!isInputFocused) {
        const totalRows = rowData?.length ?? 0;
        if (e.key === "ArrowUp") {
          if (e.metaKey || e.ctrlKey) {
            if (totalRows > 0) {
              e.preventDefault();
              setSelectedDataframeRow(0);
            }
          } else if (selectedDataframeRow > 0) {
            e.preventDefault();
            handlePrevious();
          }
        } else if (e.key === "ArrowDown") {
          if (e.metaKey || e.ctrlKey) {
            if (totalRows > 0) {
              e.preventDefault();
              setSelectedDataframeRow(totalRows - 1);
            }
          } else if (selectedDataframeRow < totalRows - 1) {
            e.preventDefault();
            handleNext();
          }
        } else if (e.key === "Enter") {
          if (selectedDataframeRow >= 0) {
            e.preventDefault();
            handleEnter();
          }
        }
      }
    };
    document.addEventListener("keydown", handleGlobalKeyDown, true);
    return () => {
      document.removeEventListener("keydown", handleGlobalKeyDown, true);
    };
  }, [
    enableKeyboardNavigation,
    selectedDataframeRow,
    rowData,
    handleNext,
    handlePrevious,
    handleEnter
  ]);
  const updateVisibleRowCount = reactExports.useCallback(
    (api2) => {
      const displayedRowCount = api2.getDisplayedRowCount();
      onVisibleRowCountChanged?.(displayedRowCount);
    },
    [onVisibleRowCountChanged]
  );
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: styles$h.gridWrapper, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    AgGridReact,
    {
      ref: gridRef,
      rowData,
      columnDefs,
      defaultColDef: {
        sortable: true,
        filter: true,
        resizable: true
      },
      rowSelection: {
        mode: "singleRow",
        enableClickSelection: true,
        checkboxes: false
      },
      animateRows: false,
      suppressColumnMoveAnimation: true,
      suppressCellFocus: true,
      theme: themeBalham,
      enableCellTextSelection: true,
      initialState: gridState,
      onFirstDataRendered: (e) => {
        e.api.sizeColumnsToFit();
        updateVisibleRowCount(e.api);
      },
      onStateUpdated: (e) => {
        setGridState(GRID_STATE_NAME, e.state);
      },
      onFilterChanged: (e) => {
        updateVisibleRowCount(e.api);
      },
      autoSizeStrategy: {
        type: "fitCellContents"
      },
      onRowDoubleClicked: (e) => {
        if (e.data) {
          if (e.rowIndex !== null) {
            setSelectedDataframeRow(e.rowIndex);
          }
          onRowDoubleClicked?.(e.data);
        }
      }
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/DataframeView.tsx",
      lineNumber: 282,
      columnNumber: 7
    },
    void 0
  ) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/DataframeView.tsx",
    lineNumber: 281,
    columnNumber: 5
  }, void 0);
};
const rootControl = "_rootControl_19z32_1";
const segment = "_segment_19z32_10";
const selected$3 = "_selected_19z32_10";
const styles$g = {
  rootControl,
  segment,
  selected: selected$3
};
const SegmentedControl = ({
  id: id2,
  segments,
  onSegmentChange,
  selectedId: selectedIdProp
}) => {
  const handleSegmentClick = reactExports.useCallback(
    (segmentId, index) => {
      onSegmentChange(segmentId, index);
    },
    [onSegmentChange]
  );
  const selectedId = selectedIdProp ?? segments[0]?.id ?? "";
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { id: id2, className: clsx(styles$g.rootControl), children: segments.map((segment2, index) => /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "button",
    {
      className: clsx(
        styles$g.segment,
        selectedId === segment2.id && styles$g.selected,
        "text-size-smallest",
        selectedId === segment2.id ? void 0 : "text-style-secondary"
      ),
      onClick: () => handleSegmentClick(segment2.id, index),
      "aria-pressed": selectedId === segment2.id,
      children: [
        segment2.icon && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("i", { className: segment2.icon }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/SegmentedControl.tsx",
          lineNumber: 49,
          columnNumber: 28
        }, void 0),
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("span", { children: segment2.label }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/SegmentedControl.tsx",
          lineNumber: 50,
          columnNumber: 11
        }, void 0)
      ]
    },
    segment2.id,
    true,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/SegmentedControl.tsx",
      lineNumber: 38,
      columnNumber: 9
    },
    void 0
  )) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/SegmentedControl.tsx",
    lineNumber: 36,
    columnNumber: 5
  }, void 0);
};
const container$5 = "_container_1q66p_1";
const styles$f = {
  container: container$5
};
const ScanInfo = () => {
  const selectedStatus = useStore((state) => state.selectedScanStatus);
  if (!selectedStatus) {
    return null;
  }
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(jsxDevRuntimeExports.Fragment, { children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      ScanInfoCard,
      {
        className: clsx(styles$f.container),
        selectedStatus
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/info/ScanInfo.tsx",
        lineNumber: 19,
        columnNumber: 7
      },
      void 0
    ),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      ScanMetadataCard,
      {
        className: clsx(styles$f.container),
        selectedStatus
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/info/ScanInfo.tsx",
        lineNumber: 23,
        columnNumber: 7
      },
      void 0
    ),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      ScannerInfoCard,
      {
        className: clsx(styles$f.container),
        selectedStatus
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/info/ScanInfo.tsx",
        lineNumber: 27,
        columnNumber: 7
      },
      void 0
    ),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      TranscriptsInfoCard,
      {
        className: clsx(styles$f.container),
        selectedStatus
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/info/ScanInfo.tsx",
        lineNumber: 31,
        columnNumber: 7
      },
      void 0
    )
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/info/ScanInfo.tsx",
    lineNumber: 18,
    columnNumber: 5
  }, void 0);
};
const ScanInfoCard = ({ selectedStatus, className: className2 }) => {
  const record = {
    ID: selectedStatus.spec.scan_id,
    Name: selectedStatus.spec.scan_name
  };
  if (selectedStatus.spec.scan_args) {
    record["Args"] = selectedStatus.spec.scan_args;
  }
  if (selectedStatus.spec.scan_file) {
    record["Source File"] = selectedStatus.spec.scan_file;
  }
  if (selectedStatus.spec.revision?.origin) {
    record["Origin"] = selectedStatus.spec.revision?.origin;
  }
  if (selectedStatus.spec.revision?.commit) {
    record["Commit"] = selectedStatus.spec.revision?.commit;
  }
  if (selectedStatus.spec.packages) {
    record["Packages"] = selectedStatus.spec.packages;
  }
  if (selectedStatus.spec.options) {
    record["Options"] = selectedStatus.spec.options;
  }
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    InfoCard,
    {
      title: `Scan: ${selectedStatus.spec.scan_name}`,
      className: clsx(className2, "text-size-small"),
      children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        MetaDataGrid,
        {
          className: "text-size-small",
          entries: record
        },
        `plan-md-task`,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/info/ScanInfo.tsx",
          lineNumber: 72,
          columnNumber: 7
        },
        void 0
      )
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/info/ScanInfo.tsx",
      lineNumber: 68,
      columnNumber: 5
    },
    void 0
  );
};
const ScanMetadataCard = ({
  selectedStatus,
  className: className2
}) => {
  if (!selectedStatus.spec.metadata || Object.keys(selectedStatus.spec.metadata).length === 0) {
    return null;
  }
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(InfoCard, { title: "Metadata", className: className2, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(RecordTree, { id: "scan-metadata", record: selectedStatus.spec.metadata }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/info/ScanInfo.tsx",
    lineNumber: 98,
    columnNumber: 7
  }, void 0) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/info/ScanInfo.tsx",
    lineNumber: 97,
    columnNumber: 5
  }, void 0);
};
const TranscriptsInfoCard = ({
  selectedStatus,
  className: className2
}) => {
  const fieldsDict = selectedStatus.spec.transcripts?.fields.reduce(
    (acc, curr) => {
      const name2 = curr["name"];
      const type = curr["type"];
      if (name2 && type) {
        acc[name2] = type;
      }
      return acc;
    },
    {}
  );
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(InfoCard, { title: "Transcripts", className: className2, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    MetaDataGrid,
    {
      className: "text-size-small",
      entries: {
        Type: selectedStatus.spec.transcripts?.type,
        Count: selectedStatus.spec.transcripts?.count,
        Fields: fieldsDict
      }
    },
    `plan-md-task`,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/info/ScanInfo.tsx",
      lineNumber: 126,
      columnNumber: 7
    },
    void 0
  ) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/info/ScanInfo.tsx",
    lineNumber: 125,
    columnNumber: 5
  }, void 0);
};
const ScannerInfoCard = ({
  selectedStatus,
  className: className2
}) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(InfoCard, { title: "Scanners", className: className2, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    MetaDataGrid,
    {
      className: "text-size-small",
      entries: {
        ...selectedStatus.spec.scanners
      }
    },
    `plan-md-task`,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/info/ScanInfo.tsx",
      lineNumber: 150,
      columnNumber: 7
    },
    void 0
  ) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/info/ScanInfo.tsx",
    lineNumber: 149,
    columnNumber: 5
  }, void 0);
};
const InfoCard = ({ title: title2, className: className2, children: children2 }) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Card, { className: className2, children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(CardHeader, { label: title2, type: "modern" }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/info/ScanInfo.tsx",
      lineNumber: 170,
      columnNumber: 7
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(CardBody, { children: children2 }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/info/ScanInfo.tsx",
      lineNumber: 171,
      columnNumber: 7
    }, void 0)
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/info/ScanInfo.tsx",
    lineNumber: 169,
    columnNumber: 5
  }, void 0);
};
const ScanDataframeClearFiltersButton = () => {
  const setGridState = useStore((state) => state.setGridState);
  const gridState = useStore((state) => state.gridStates[GRID_STATE_NAME]);
  const clearState = reactExports.useCallback(() => {
    const { filter: filter2, ...state } = gridState || {};
    setGridState(GRID_STATE_NAME, state);
  }, [gridState, setGridState]);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    ToolButton,
    {
      icon: ApplicationIcons.filter,
      label: "Clear Filters",
      onClick: clearState
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanDataframeClearFiltersButton.tsx",
      lineNumber: 18,
      columnNumber: 5
    },
    void 0
  );
};
const grid = "_grid_hbkjn_1";
const row$2 = "_row_hbkjn_8";
const links = "_links_hbkjn_22";
const selected$2 = "_selected_hbkjn_40";
const styles$e = {
  grid,
  row: row$2,
  links,
  selected: selected$2
};
const defaultColumns = [
  "transcript_id",
  "value",
  "explanation",
  "metadata",
  "transcript_source_id",
  "transcript_metadata",
  "input_ids",
  "input",
  "label",
  "uuid",
  "message_references",
  "validation_target",
  "validation_result",
  "scan_total_tokens",
  "scan_model_usage",
  "scan_events",
  "timestamp"
];
const columnsGroups = {
  Transcript: [
    "transcript_id",
    "transcript_source_type",
    "transcript_source_id",
    "transcript_source_uri",
    "transcript_metadata"
  ],
  Scan: [
    "scan_id",
    "scan_tags",
    "scan_metadata",
    "scan_git_origin",
    "scan_git_version",
    "scan_git_commit"
  ],
  Scanner: [
    "scanner_key",
    "scanner_name",
    "scanner_version",
    "scanner_package_version",
    "scanner_file",
    "scanner_params"
  ],
  Input: ["input_type", "input_ids", "input"],
  Validation: ["validation_target", "validation_result"],
  Result: [
    "uuid",
    "value",
    "explanation",
    "metadata",
    "label",
    "value_type",
    "answer",
    "scan_tokens_total",
    "scan_model_usage",
    "scan_events",
    "timestamp",
    "message_references",
    "event_references"
  ],
  Error: ["scan_error", "scan_error_traceback", "scan_error_type"]
};
const useDataframeColumns = () => {
  const allColumns = Object.values(columnsGroups).flat();
  const filteredColumns = useStore((state) => state.dataframeFilterColumns) || defaultColumns;
  const setFilteredColumns = useStore(
    (state) => state.setDataframeFilterColumns
  );
  const isDefaultFilter = filteredColumns?.length === defaultColumns.length && filteredColumns.every((col) => defaultColumns.includes(col));
  const isAllFilter = filteredColumns?.length === allColumns.length;
  const setDefaultFilter = () => {
    setFilteredColumns(defaultColumns);
  };
  const setAllFilter = () => {
    setFilteredColumns(allColumns);
  };
  const filterColumn = reactExports.useCallback(
    (column2, show) => {
      if (show && !filteredColumns?.includes(column2)) {
        setFilteredColumns([...filteredColumns || [], column2]);
      } else if (!show) {
        setFilteredColumns(filteredColumns?.filter((c2) => c2 !== column2) || []);
      }
    },
    [filteredColumns, setFilteredColumns]
  );
  const arrangedColumns = (cols) => {
    const groupOrder = [
      "Result",
      "Input",
      "---",
      "Transcript",
      "Validation",
      "Error",
      "---",
      "Scan",
      "Scanner"
    ];
    const groupedColumns = {};
    Object.entries(columnsGroups).forEach(([groupName, columns2]) => {
      const columnsInGroup = columns2.filter((col) => {
        if (col.endsWith("*")) {
          const prefix = col.slice(0, -1);
          return allColumns.some((c2) => c2.startsWith(prefix));
        }
        return allColumns.includes(col);
      });
      if (columnsInGroup.length > 0) {
        groupedColumns[groupName] = columnsInGroup;
      }
    });
    const result2 = [];
    let currentColumn = {};
    groupOrder.forEach((item2) => {
      if (item2 === "---") {
        if (Object.keys(currentColumn).length > 0) {
          result2.push(currentColumn);
          currentColumn = {};
        }
      } else if (groupedColumns[item2]) {
        currentColumn[item2] = groupedColumns[item2];
      }
    });
    if (Object.keys(currentColumn).length > 0) {
      result2.push(currentColumn);
    }
    while (result2.length < cols) {
      result2.push({});
    }
    return result2;
  };
  return {
    defaultFilter: defaultColumns,
    isDefaultFilter,
    isAllFilter,
    setDefaultFilter,
    setAllFilter,
    filterColumn,
    filtered: filteredColumns || [],
    arrangedColumns
  };
};
const ScanDataframeColumnsPopover = ({ positionEl }) => {
  const showFilter = useStore((state) => state.dataframeShowFilterColumns);
  const setShowFilter = useStore(
    (state) => state.setDataframeShowFilterColumns
  );
  const {
    isDefaultFilter,
    isAllFilter,
    setDefaultFilter,
    setAllFilter,
    filterColumn,
    filtered,
    arrangedColumns
  } = useDataframeColumns();
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    PopOver,
    {
      id: `scandata-choose-columns-popover`,
      positionEl,
      isOpen: !!showFilter,
      setIsOpen: setShowFilter,
      placement: "bottom-end",
      hoverDelay: -1,
      children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$e.links, "text-size-smaller"), children: [
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            "a",
            {
              className: clsx(
                styles$e.link,
                isDefaultFilter ? styles$e.selected : void 0
              ),
              onClick: () => setDefaultFilter(),
              children: "Default"
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanDataframeColumnsPopover.tsx",
              lineNumber: 191,
              columnNumber: 9
            },
            void 0
          ),
          "|",
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            "a",
            {
              className: clsx(
                styles$e.link,
                isAllFilter ? styles$e.selected : void 0
              ),
              onClick: () => setAllFilter(),
              children: "All"
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanDataframeColumnsPopover.tsx",
              lineNumber: 201,
              columnNumber: 9
            },
            void 0
          )
        ] }, void 0, true, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanDataframeColumnsPopover.tsx",
          lineNumber: 190,
          columnNumber: 7
        }, void 0),
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$e.grid, "text-size-smaller"), children: arrangedColumns(3).map((columnGroup, colIndex) => {
          return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: Object.entries(columnGroup).map(([groupName, columns2]) => /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: [
            /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
              "div",
              {
                style: {
                  fontWeight: 600,
                  marginTop: "0.5em",
                  marginBottom: "0.25em"
                },
                children: groupName
              },
              void 0,
              false,
              {
                fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanDataframeColumnsPopover.tsx",
                lineNumber: 218,
                columnNumber: 19
              },
              void 0
            ),
            columns2.map((column2) => /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
              "div",
              {
                className: clsx(styles$e.row),
                onClick: () => {
                  filterColumn(column2, !filtered.includes(column2));
                },
                children: [
                  /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
                    "input",
                    {
                      type: "checkbox",
                      checked: filtered.includes(column2),
                      onChange: (e) => {
                        filterColumn(column2, e.target.checked);
                      }
                    },
                    void 0,
                    false,
                    {
                      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanDataframeColumnsPopover.tsx",
                      lineNumber: 235,
                      columnNumber: 23
                    },
                    void 0
                  ),
                  column2
                ]
              },
              column2,
              true,
              {
                fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanDataframeColumnsPopover.tsx",
                lineNumber: 228,
                columnNumber: 21
              },
              void 0
            ))
          ] }, groupName, true, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanDataframeColumnsPopover.tsx",
            lineNumber: 217,
            columnNumber: 17
          }, void 0)) }, colIndex, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanDataframeColumnsPopover.tsx",
            lineNumber: 215,
            columnNumber: 13
          }, void 0);
        }) }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanDataframeColumnsPopover.tsx",
          lineNumber: 212,
          columnNumber: 7
        }, void 0)
      ]
    },
    void 0,
    true,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanDataframeColumnsPopover.tsx",
      lineNumber: 182,
      columnNumber: 5
    },
    void 0
  );
};
const ScanDataframeFilterColumnsButton = reactExports.forwardRef((_, ref2) => {
  const showFilter = useStore((state) => state.dataframeShowFilterColumns);
  const setShowFilter = useStore(
    (state) => state.setDataframeShowFilterColumns
  );
  const toggleShowFilter = reactExports.useCallback(() => {
    setShowFilter(!showFilter);
  }, [showFilter, setShowFilter]);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    ToolButton,
    {
      icon: ApplicationIcons.checkbox.checked,
      label: "Choose Columns",
      onClick: toggleShowFilter,
      latched: showFilter,
      ref: ref2
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanDataframeFilterColumnsButton.tsx",
      lineNumber: 21,
      columnNumber: 5
    },
    void 0
  );
});
const ScanDataframeWrapTextButton = () => {
  const wrapText = useStore((state) => state.dataframeWrapText);
  const setWrapText = useStore((state) => state.setDataframeWrapText);
  const toggleWrapText = reactExports.useCallback(() => {
    setWrapText(!wrapText);
  }, [wrapText, setWrapText]);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    ToolButton,
    {
      icon: ApplicationIcons.wrap,
      label: "Wrap Text",
      onClick: toggleWrapText,
      latched: wrapText
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanDataframeWrapTextButton.tsx",
      lineNumber: 16,
      columnNumber: 5
    },
    void 0
  );
};
const flex$1 = "_flex_1kye9_1";
const label$1 = "_label_1kye9_5";
const styles$d = {
  flex: flex$1,
  label: label$1
};
const kFilterPositiveResults = "positive_results";
const kFilterAllResults = "all_results";
const ScanResultsFilter = () => {
  const setSelectedFilter = useStore((state) => state.setSelectedFilter);
  const selectedFilter = useStore((state) => state.selectedFilter);
  const handleChange = reactExports.useCallback(
    (e) => {
      const sel = e.target;
      setSelectedFilter(sel.value);
    },
    [setSelectedFilter]
  );
  const options = [
    { label: "Positive", val: kFilterPositiveResults },
    { label: "All", val: kFilterAllResults }
  ];
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: styles$d.flex, children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "span",
      {
        className: clsx(
          "sort-filter-label",
          "text-size-smaller",
          "text-style-label",
          "text-style-secondary",
          styles$d.label
        ),
        children: "Results:"
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsFilter.tsx",
        lineNumber: 30,
        columnNumber: 7
      },
      void 0
    ),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "select",
      {
        id: "scan-result-filter",
        className: clsx("form-select", "form-select-sm", "text-size-smaller"),
        "aria-label": ".sort-filter-label",
        value: selectedFilter,
        onChange: handleChange,
        children: options.map((option) => {
          return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("option", { value: option.val, children: option.label }, option.val, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsFilter.tsx",
            lineNumber: 50,
            columnNumber: 13
          }, void 0);
        })
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsFilter.tsx",
        lineNumber: 41,
        columnNumber: 7
      },
      void 0
    )
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsFilter.tsx",
    lineNumber: 29,
    columnNumber: 5
  }, void 0);
};
const flex = "_flex_1kye9_1";
const label = "_label_1kye9_5";
const styles$c = {
  flex,
  label
};
const ScanResultsGroup = ({
  options = ["source", "label", "id"]
}) => {
  const setGroupResultsBy = useStore((state) => state.setGroupResultsBy);
  const groupResultsBy = useStore((state) => state.groupResultsBy);
  const handleChange = reactExports.useCallback(
    (e) => {
      const sel = e.target;
      setGroupResultsBy(sel.value);
    },
    [setGroupResultsBy]
  );
  const groupByOpts = [
    { label: "Source", value: "source" },
    { label: "Label", value: "label" },
    { label: "Id", value: "id" },
    { label: "Epoch", value: "epoch" }
  ].filter((opt2) => options.includes(toVal(opt2.value)));
  if (groupByOpts.length === 0) {
    return null;
  }
  groupByOpts.unshift({ label: "None", value: "none" });
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: styles$c.flex, children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "span",
      {
        className: clsx(
          "sort-filter-label",
          "text-size-smaller",
          "text-style-label",
          "text-style-secondary",
          styles$c.label
        ),
        children: "Group:"
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsGroup.tsx",
        lineNumber: 40,
        columnNumber: 7
      },
      void 0
    ),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "select",
      {
        id: "scan-result-filter",
        className: clsx("form-select", "form-select-sm", "text-size-smaller"),
        "aria-label": ".sort-filter-label",
        value: groupResultsBy || "none",
        onChange: handleChange,
        children: groupByOpts.map((option) => {
          return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("option", { value: option.value, children: option.label }, option.value, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsGroup.tsx",
            lineNumber: 60,
            columnNumber: 13
          }, void 0);
        })
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsGroup.tsx",
        lineNumber: 51,
        columnNumber: 7
      },
      void 0
    )
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsGroup.tsx",
    lineNumber: 39,
    columnNumber: 5
  }, void 0);
};
const toVal = (v) => {
  if (v === "source") {
    return "source";
  } else if (v === "label") {
    return "label";
  } else if (v === "id") {
    return "id";
  } else if (v === "epoch") {
    return "epoch";
  } else {
    return "none";
  }
};
const header = "_header_u9u40_1";
const clickable = "_clickable_u9u40_19";
const styles$b = {
  header,
  clickable
};
const ScanResultsHeader = ({
  gridDescriptor
}) => {
  const hasExplanation = gridDescriptor.columns.includes("explanation");
  const hasLabel = gridDescriptor.columns.includes("label");
  const hasError = gridDescriptor.columns.includes("error");
  const hasValidations = gridDescriptor.columns.includes("validations");
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "div",
    {
      style: gridDescriptor.gridStyle,
      className: clsx(
        styles$b.header,
        "text-size-smallest",
        "text-style-label",
        "text-style-secondary",
        hasExplanation ? "" : styles$b.noExplanation
      ),
      children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ColumnHeader, { label: "Id" }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanHeader.tsx",
          lineNumber: 33,
          columnNumber: 7
        }, void 0),
        hasExplanation && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ColumnHeader, { label: "Explanation" }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanHeader.tsx",
          lineNumber: 34,
          columnNumber: 26
        }, void 0),
        hasLabel && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ColumnHeader, { label: "Label" }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanHeader.tsx",
          lineNumber: 35,
          columnNumber: 20
        }, void 0),
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ColumnHeader, { label: "Value", className: clsx(styles$b.value) }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanHeader.tsx",
          lineNumber: 36,
          columnNumber: 7
        }, void 0),
        hasValidations && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ColumnHeader, { label: "Validation" }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanHeader.tsx",
          lineNumber: 37,
          columnNumber: 26
        }, void 0),
        hasError && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ColumnHeader, { label: "Error" }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanHeader.tsx",
          lineNumber: 38,
          columnNumber: 20
        }, void 0)
      ]
    },
    void 0,
    true,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanHeader.tsx",
      lineNumber: 23,
      columnNumber: 5
    },
    void 0
  );
};
const ColumnHeader = ({ label: label2, className: className2 }) => {
  const sortResults = useStore((state) => state.sortResults);
  const setSortResults = useStore((state) => state.setSortResults);
  const sort = sortResults?.find((s) => s.column === label2);
  const handleSort = reactExports.useCallback(
    (e) => {
      e.stopPropagation();
      e.preventDefault();
      const nextSortDirection = sort?.direction === void 0 ? "asc" : sort?.direction === "asc" ? "desc" : void 0;
      if (!nextSortDirection) {
        if (e.shiftKey) {
          const newSorts = sortResults ? sortResults.filter((s) => s.column !== label2) : [];
          setSortResults(newSorts.length > 0 ? newSorts : void 0);
        } else {
          setSortResults(void 0);
        }
        return;
      } else {
        if (e.shiftKey) {
          const newSorts = sortResults ? [...sortResults] : [];
          const existingIndex = newSorts.findIndex((s) => s.column === label2);
          if (existingIndex >= 0) {
            newSorts[existingIndex] = {
              column: label2,
              direction: nextSortDirection
            };
          } else {
            newSorts.push({ column: label2, direction: nextSortDirection });
          }
          setSortResults(newSorts);
        } else {
          setSortResults([{ column: label2, direction: nextSortDirection }]);
        }
      }
    },
    [sort, sortResults, setSortResults]
  );
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(className2, styles$b.clickable), onClick: handleSort, children: [
    label2,
    sort && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "i",
      {
        className: clsx(
          sort?.direction === "asc" ? ApplicationIcons.arrows.up : ApplicationIcons.arrows.down
        )
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanHeader.tsx",
        lineNumber: 101,
        columnNumber: 9
      },
      void 0
    )
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanHeader.tsx",
    lineNumber: 98,
    columnNumber: 5
  }, void 0);
};
const row$1 = "_row_q8zt3_1";
const styles$a = {
  row: row$1
};
const ScanResultGroup = ({ group }) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$a.row), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "div",
    {
      className: clsx(
        styles$a.label,
        "text-style-secondary",
        "text-size-smallest"
      ),
      children: group
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanResultsGroup.tsx",
      lineNumber: 13,
      columnNumber: 7
    },
    void 0
  ) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanResultsGroup.tsx",
    lineNumber: 12,
    columnNumber: 5
  }, void 0);
};
const container$4 = "_container_1quph_1";
const styles$9 = {
  container: container$4
};
const error$1 = "_error_1rpqv_1";
const refusal = "_refusal_1rpqv_6";
const styles$8 = {
  error: error$1,
  refusal
};
const Error$1 = ({ error: error2, refusal: refusal2 }) => {
  const icon2 = refusal2 ? ApplicationIcons.refuse : ApplicationIcons.error;
  const message2 = refusal2 ? "Refusal" : error2;
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$8.error, refusal2 && styles$8.refusal), children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("i", { className: clsx(icon2) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/values/Error.tsx",
      lineNumber: 18,
      columnNumber: 7
    }, void 0),
    message2
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/values/Error.tsx",
    lineNumber: 17,
    columnNumber: 5
  }, void 0);
};
const id = "_id_1a3zo_1";
const styles$7 = {
  id
};
const Identifier = ({ result: result2 }) => {
  const identifier = resultIdentifier(result2);
  if (identifier.epoch) {
    const id2 = identifier.id;
    const epoch = identifier.epoch;
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$7.id), children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: id2 }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/values/Identifier.tsx",
        lineNumber: 20,
        columnNumber: 9
      }, void 0),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("text-size-smallest", "text-style-secondary"), children: [
        identifier.secondaryId ? `${identifier.secondaryId} ` : "",
        "epoch",
        " ",
        epoch
      ] }, void 0, true, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/values/Identifier.tsx",
        lineNumber: 21,
        columnNumber: 9
      }, void 0)
    ] }, void 0, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/values/Identifier.tsx",
      lineNumber: 19,
      columnNumber: 7
    }, void 0);
  } else {
    return identifier.id;
  }
};
const row = "_row_diloz_1";
const noExplanation = "_noExplanation_diloz_7";
const disabled = "_disabled_diloz_15";
const explanation = "_explanation_diloz_23";
const selected$1 = "_selected_diloz_29";
const link = "_link_diloz_33";
const error = "_error_diloz_42";
const styles$6 = {
  row,
  noExplanation,
  disabled,
  explanation,
  selected: selected$1,
  link,
  error
};
const ScanResultsRowComponent = ({
  entry: entry2,
  gridDescriptor
}) => {
  const params = useParams();
  const relativePath = getRelativePathFromParams(params);
  const [searchParams] = useSearchParams();
  const selectedScanResult = useStore((state) => state.selectedScanResult);
  const setSelectedScanResult = useStore(
    (state) => state.setSelectedScanResult
  );
  const isNavigable = entry2.uuid !== void 0;
  const scanResultUrl = isNavigable ? scanResultRoute(relativePath, entry2.uuid, searchParams) : "";
  const hasExplanation = gridDescriptor.columns.includes("explanation");
  const hasLabel = gridDescriptor.columns.includes("label");
  const hasErrors = gridDescriptor.columns.includes("error");
  const hasValidations = gridDescriptor.columns.includes("validations");
  const grid2 = /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "div",
    {
      style: gridDescriptor.gridStyle,
      className: clsx(
        styles$6.row,
        !isNavigable ? styles$6.disabled : "",
        selectedScanResult === entry2.uuid ? styles$6.selected : "",
        hasExplanation ? "" : styles$6.noExplanation
      ),
      onClick: () => {
        if (entry2.uuid) {
          setSelectedScanResult(entry2.uuid);
        }
      },
      children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$6.id, "text-size-smaller"), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Identifier, { result: entry2 }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanResultsRow.tsx",
          lineNumber: 69,
          columnNumber: 9
        }, void 0) }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanResultsRow.tsx",
          lineNumber: 68,
          columnNumber: 7
        }, void 0),
        hasExplanation && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$6.explanation, "text-size-smaller"), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Explanation, { result: entry2 }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanResultsRow.tsx",
          lineNumber: 73,
          columnNumber: 11
        }, void 0) }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanResultsRow.tsx",
          lineNumber: 72,
          columnNumber: 9
        }, void 0),
        hasLabel && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "div",
          {
            className: clsx(
              styles$6.label,
              "text-size-smallest",
              "text-style-label",
              "text-style-secondary"
            ),
            children: entry2.label || /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("span", { className: clsx("text-style-secondary"), children: "—" }, void 0, false, {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanResultsRow.tsx",
              lineNumber: 86,
              columnNumber: 13
            }, void 0)
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanResultsRow.tsx",
            lineNumber: 77,
            columnNumber: 9
          },
          void 0
        ),
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$6.value, "text-size-smaller"), children: !entry2.scanError && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Value, { result: entry2, style: "inline" }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanResultsRow.tsx",
          lineNumber: 92,
          columnNumber: 30
        }, void 0) }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanResultsRow.tsx",
          lineNumber: 91,
          columnNumber: 7
        }, void 0),
        hasValidations && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("text-size-smaller"), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ValidationResult, { result: entry2.validationResult }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanResultsRow.tsx",
          lineNumber: 96,
          columnNumber: 11
        }, void 0) }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanResultsRow.tsx",
          lineNumber: 95,
          columnNumber: 9
        }, void 0),
        hasErrors && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$6.error, "text-size-smallest"), children: entry2.scanError && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          Error$1,
          {
            error: entry2.scanError || "unknown error",
            refusal: !!entry2.scanErrorRefusal
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanResultsRow.tsx",
            lineNumber: 102,
            columnNumber: 13
          },
          void 0
        ) }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanResultsRow.tsx",
          lineNumber: 100,
          columnNumber: 9
        }, void 0)
      ]
    },
    void 0,
    true,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanResultsRow.tsx",
      lineNumber: 54,
      columnNumber: 5
    },
    void 0
  );
  return isNavigable ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Link, { to: scanResultUrl, className: clsx(styles$6.link), onClick: () => {
  }, children: grid2 }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanResultsRow.tsx",
    lineNumber: 113,
    columnNumber: 5
  }, void 0) : grid2;
};
const ScanResultsRow$1 = reactExports.memo(ScanResultsRowComponent);
const ScanResultsList = ({
  id: id2,
  columnTable
}) => {
  const navigate = useNavigate();
  const params = useParams();
  const [searchParams] = useSearchParams();
  const relativePath = getRelativePathFromParams(params);
  const { scanPath } = parseScanResultPath(relativePath);
  const { data: scannerSummaries, isLoading } = useScannerPreviews(columnTable);
  const isLoadingData = useStore((state) => state.loadingData);
  const busy = isLoading || isLoadingData;
  const listHandle = reactExports.useRef(null);
  const selectedScanResult = useStore((state) => state.selectedScanResult);
  const selectedFilter = useStore((state) => state.selectedFilter);
  const groupResultsBy = useStore((state) => state.groupResultsBy);
  const scansSearchText = useStore((state) => state.scansSearchText);
  const selectedStatus = useStore((state) => state.selectedScanStatus);
  const setVisibleScannerResults = useStore(
    (state) => state.setVisibleScannerResults
  );
  const setVisibleScannerResultsCount = useStore(
    (state) => state.setVisibleScannerResultsCount
  );
  const setSelectedScanResult = useStore(
    (state) => state.setSelectedScanResult
  );
  const setSelectedFilter = useStore((state) => state.setSelectedFilter);
  const sortResults = useStore((state) => state.sortResults);
  const setSortResults = useStore((state) => state.setSortResults);
  reactExports.useEffect(() => {
    if (selectedFilter === void 0 && selectedStatus?.complete === false) {
      setSelectedFilter(kFilterAllResults);
    }
  }, [selectedStatus, selectedFilter, setSelectedFilter]);
  const filteredSummaries = reactExports.useMemo(() => {
    let textFiltered = scannerSummaries;
    if (scansSearchText && scansSearchText.length > 0) {
      const lowerSearch = scansSearchText.toLowerCase();
      textFiltered = scannerSummaries.filter((s) => {
        const idStr = resultIdentifierStr(s) || "";
        const logStr = resultLog(s) || "";
        const labelStr = s.label || "";
        return idStr.toLowerCase().includes(lowerSearch) || logStr.toLowerCase().includes(lowerSearch) || labelStr.toLowerCase().includes(lowerSearch);
      });
    }
    const resultsFiltered = selectedFilter === kFilterPositiveResults || selectedFilter === void 0 ? textFiltered.filter((s) => !!s.value) : textFiltered;
    if (sortResults === void 0 || sortResults.length === 0) {
      return resultsFiltered;
    } else {
      return [...resultsFiltered].sort(
        (a2, b) => sortByColumns(a2, b, sortResults)
      );
    }
  }, [scannerSummaries, selectedFilter, scansSearchText, sortResults]);
  reactExports.useEffect(() => {
    if (filteredSummaries.length === 0 || sortResults) {
      return;
    }
    if (selectedFilter === kFilterAllResults && filteredSummaries.some((s) => !!s.scanError)) {
      setSortResults([{ column: "Error", direction: "desc" }]);
    }
  }, [sortResults, selectedFilter, filteredSummaries]);
  const gridDescriptor = reactExports.useMemo(() => {
    const descriptor = optimalColumnLayout(filteredSummaries);
    return descriptor;
  }, [filteredSummaries]);
  const isResultGroup = (entry2) => {
    return "type" in entry2 && entry2.type === "group";
  };
  const rows = reactExports.useMemo(() => {
    if (!groupResultsBy || groupResultsBy === "none") {
      return filteredSummaries;
    }
    const groups = /* @__PURE__ */ new Map();
    for (const item2 of filteredSummaries) {
      const groupKey = groupResultsBy === "source" ? basename(resultLog(item2) || "") || "Unknown" : groupResultsBy === "label" ? item2.label || "Unlabeled" : groupResultsBy === "epoch" ? item2.transcriptMetadata.epoch : resultIdentifierStr(item2) || "Unknown";
      if (!groups.has(groupKey)) {
        groups.set(groupKey, []);
      }
      groups.get(groupKey)?.push(item2);
    }
    const sortedGroupKeys = Array.from(groups.keys()).sort((a2, b) => {
      if (typeof a2 === "number" && typeof b === "number") {
        return a2 - b;
      }
      return String(a2).localeCompare(String(b));
    });
    const result2 = [];
    for (const groupKey of sortedGroupKeys) {
      const label2 = groupResultsBy === "epoch" ? `Epoch ${groupKey}` : String(groupKey);
      result2.push({ type: "group", label: label2 });
      result2.push(...groups.get(groupKey) || []);
    }
    return result2;
  }, [filteredSummaries, groupResultsBy]);
  const currentIndex = reactExports.useMemo(() => {
    if (selectedScanResult) {
      return filteredSummaries.findIndex((s) => s.uuid === selectedScanResult);
    }
    return -1;
  }, [selectedScanResult, filteredSummaries]);
  const handleNext = reactExports.useCallback(() => {
    if (currentIndex >= 0 && currentIndex < filteredSummaries.length - 1) {
      const nextResult = filteredSummaries[currentIndex + 1];
      if (nextResult?.uuid) {
        setSelectedScanResult(nextResult.uuid);
      }
    }
  }, [currentIndex, filteredSummaries, setSelectedScanResult]);
  const handlePrevious = reactExports.useCallback(() => {
    if (currentIndex > 0) {
      const previousResult = filteredSummaries[currentIndex - 1];
      if (previousResult?.uuid) {
        setSelectedScanResult(previousResult.uuid);
      }
    }
  }, [currentIndex, filteredSummaries, setSelectedScanResult]);
  const handleEnter = reactExports.useCallback(
    (newWindow) => {
      const selectedResult = filteredSummaries[currentIndex];
      const route = scanResultRoute(
        scanPath,
        selectedResult?.uuid,
        searchParams
      );
      if (newWindow) {
        window.open(route, "_blank");
      } else {
        void navigate(route);
      }
    },
    [currentIndex, filteredSummaries, navigate, scanPath, searchParams]
  );
  const hasPrevious = currentIndex > 0;
  const hasNext = currentIndex >= 0 && currentIndex < filteredSummaries.length - 1;
  reactExports.useEffect(() => {
    const handleGlobalKeyDown = (e) => {
      const activeElement = document.activeElement;
      const isInputFocused = activeElement && (activeElement.tagName === "INPUT" || activeElement.tagName === "TEXTAREA" || activeElement.tagName === "SELECT");
      if (!isInputFocused) {
        if (e.key === "ArrowUp") {
          if (e.metaKey || e.ctrlKey) {
            if (filteredSummaries.length > 0 && filteredSummaries[0]?.uuid) {
              e.preventDefault();
              setSelectedScanResult(filteredSummaries[0].uuid);
            }
          } else if (hasPrevious) {
            e.preventDefault();
            handlePrevious();
          }
        } else if (e.key === "ArrowDown") {
          if (e.metaKey || e.ctrlKey) {
            if (filteredSummaries.length > 0) {
              e.preventDefault();
              const uuid = filteredSummaries[filteredSummaries.length - 1]?.uuid;
              if (uuid) {
                setSelectedScanResult(uuid);
              }
            }
          } else if (hasNext) {
            e.preventDefault();
            handleNext();
          }
        } else if (e.key === "Enter") {
          e.preventDefault();
          handleEnter(e.metaKey || e.ctrlKey);
        }
      }
    };
    document.addEventListener("keydown", handleGlobalKeyDown, true);
    return () => {
      document.removeEventListener("keydown", handleGlobalKeyDown, true);
    };
  }, [
    hasPrevious,
    hasNext,
    handlePrevious,
    handleNext,
    handleEnter,
    filteredSummaries,
    setSelectedScanResult
  ]);
  reactExports.useEffect(() => {
    if (!selectedScanResult && filteredSummaries.length > 0 && filteredSummaries[0]?.uuid) {
      setSelectedScanResult(filteredSummaries[0].uuid);
    }
  }, [filteredSummaries, selectedScanResult, setSelectedScanResult]);
  reactExports.useEffect(() => {
    setVisibleScannerResults(filteredSummaries);
    setVisibleScannerResultsCount(filteredSummaries.length);
  }, [
    filteredSummaries,
    setVisibleScannerResults,
    setVisibleScannerResultsCount
  ]);
  const selectedItemIndex = reactExports.useMemo(() => {
    if (selectedScanResult) {
      const selectedIndex = filteredSummaries.findIndex(
        (s) => s.uuid === selectedScanResult
      );
      if (selectedIndex >= 0) {
        return selectedIndex;
      }
    }
    return void 0;
  }, [selectedScanResult, filteredSummaries]);
  reactExports.useEffect(() => {
    setTimeout(() => {
      listHandle.current?.scrollToIndex({
        index: selectedItemIndex ?? 0,
        align: "center",
        behavior: "auto"
      });
    }, 5);
  }, [selectedItemIndex]);
  const renderRow = reactExports.useCallback(
    (index, entry2) => {
      if (isResultGroup(entry2)) {
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ScanResultGroup, { group: entry2.label }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanResultsList.tsx",
          lineNumber: 355,
          columnNumber: 16
        }, void 0);
      }
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        ScanResultsRow$1,
        {
          index,
          entry: entry2,
          gridDescriptor
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanResultsList.tsx",
          lineNumber: 360,
          columnNumber: 9
        },
        void 0
      );
    },
    [gridDescriptor, isResultGroup]
  );
  let noContentMessage = void 0;
  if (!busy && scannerSummaries.length === 0) {
    noContentMessage = "No scan results are available.";
  } else if (!busy && filteredSummaries.length === 0 && selectedFilter !== kFilterAllResults && !scansSearchText) {
    noContentMessage = "No positive scan results were found.";
  } else if (!busy && filteredSummaries.length === 0) {
    noContentMessage = "No scan results match the current filter.";
  }
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$9.container), children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ScanResultsHeader, { gridDescriptor }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanResultsList.tsx",
      lineNumber: 386,
      columnNumber: 7
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ActivityBar, { animating: isLoading }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanResultsList.tsx",
      lineNumber: 387,
      columnNumber: 7
    }, void 0),
    noContentMessage && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(NoContentsPanel, { text: noContentMessage }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanResultsList.tsx",
      lineNumber: 388,
      columnNumber: 28
    }, void 0),
    !busy && filteredSummaries.length > 0 && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      LiveVirtualList,
      {
        id: id2,
        listHandle,
        data: rows,
        renderRow,
        className: clsx(styles$9.list),
        animation: false
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanResultsList.tsx",
        lineNumber: 390,
        columnNumber: 9
      },
      void 0
    )
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/list/ScanResultsList.tsx",
    lineNumber: 385,
    columnNumber: 5
  }, void 0);
};
const sortByColumns = (a2, b, sortColumns2) => {
  for (const sortCol of sortColumns2) {
    let comparison = 0;
    switch (sortCol.column.toLowerCase()) {
      case "id": {
        const identifierA = resultIdentifier(a2);
        const identifierB = resultIdentifier(b);
        comparison = identifierA.id.localeCompare(identifierB.id);
        if (comparison === 0 && identifierA.epoch && identifierB.epoch) {
          comparison = identifierA.epoch.localeCompare(identifierB.epoch);
        }
        break;
      }
      case "explanation": {
        const explA = a2.explanation || "";
        const explB = b.explanation || "";
        comparison = explA.localeCompare(explB);
        break;
      }
      case "label": {
        const labelA = a2.label || "";
        const labelB = b.label || "";
        comparison = labelA.localeCompare(labelB);
        break;
      }
      case "value": {
        const valueA = a2.value !== null && a2.value !== void 0 ? String(a2.value) : "";
        const valueB = b.value !== null && b.value !== void 0 ? String(b.value) : "";
        comparison = valueA.localeCompare(valueB);
        break;
      }
      case "error": {
        const errorA = a2.scanError || "";
        const errorB = b.scanError || "";
        comparison = errorA.localeCompare(errorB);
        break;
      }
      case "validation": {
        const validationA = a2.validationResult ? 1 : 0;
        const validationB = b.validationResult ? 1 : 0;
        comparison = validationA - validationB;
        break;
      }
      default:
        continue;
    }
    if (comparison !== 0) {
      return sortCol.direction === "asc" ? comparison : -comparison;
    }
  }
  return 0;
};
const optimalColumnLayout = (scannerSummaries) => {
  const columns2 = [];
  const gridColParts = [];
  columns2.push("id");
  const maxIdLen = scannerSummaries.reduce((max2, s) => {
    return Math.max(max2, resultIdentifier(s).id.length);
  }, 0);
  gridColParts.push(
    `minmax(${Math.min(Math.max(maxIdLen * 8, 50), 250)}px, 1fr)`
  );
  const hasExplanation = scannerSummaries.some((s) => !!s.explanation);
  if (hasExplanation) {
    columns2.push("explanation");
    gridColParts.push("10fr");
  }
  const hasLabel = scannerSummaries.some((s) => !!s.label);
  if (hasLabel) {
    columns2.push("label");
    const maxlabelLen = scannerSummaries.reduce((max2, s) => {
      return Math.max(max2, resultIdentifier(s).id.length);
    }, 0);
    gridColParts.push(
      `minmax(${Math.min(Math.max(maxlabelLen * 5, 75), 250)}px, 1fr)`
    );
  }
  columns2.push("value");
  const hasValueObjs = scannerSummaries.some((s) => s.valueType === "object");
  if (hasValueObjs) {
    const obj = scannerSummaries[0]?.value;
    if (obj && typeof obj === "object" && !Array.isArray(obj)) {
      const maxKeyLen = Object.keys(obj).reduce((max2, key2) => {
        return Math.max(max2, key2.length);
      }, 0);
      const maxValueLen = Object.values(obj).reduce((max2, val) => {
        const valStr = val !== void 0 && val !== null ? String(val) : "";
        return Math.max(max2, valStr.length);
      }, 0);
      gridColParts.push(
        `minmax(${Math.min(Math.max((maxKeyLen + maxValueLen) * 10, 135), 400)}px, 2fr)`
      );
    } else {
      gridColParts.push("3fr");
    }
  } else {
    const maxValueLen = scannerSummaries.reduce((max2, s) => {
      if (s.valueType === "array") {
        const len = s.value.reduce((prev, val) => {
          const valStr = val !== void 0 && val !== null ? String(val) : "";
          return Math.max(prev, valStr.length);
        }, 0);
        return Math.max(max2, len);
      } else {
        const valStr = s.value !== void 0 && s.value !== null ? String(s.value) : "";
        return Math.max(max2, valStr.length);
      }
    }, 0);
    gridColParts.push(
      `minmax(${Math.min(Math.max(maxValueLen * 4, 50), 300)}px, 1fr)`
    );
  }
  const hasValidations = scannerSummaries.some(
    (s) => s.validationResult !== void 0
  );
  if (hasValidations) {
    columns2.push("validations");
    gridColParts.push("1fr");
  }
  const hasErrors = scannerSummaries.some((s) => !!s.scanError);
  if (hasErrors) {
    const maxErrorLen = scannerSummaries.reduce((max2, s) => {
      return Math.max(max2, s.scanError ? s.scanError.length : 0);
    }, 0);
    columns2.push("error");
    gridColParts.push(
      `minmax(${Math.min(Math.max(maxErrorLen * 4, 50), 250)}px, 1fr)`
    );
  }
  if (columns2.length === 2 && columns2[0] === "id" && columns2[1] === "value") {
    gridColParts[0] = "1fr";
    gridColParts[1] = "1fr";
  }
  return {
    gridStyle: {
      gridTemplateColumns: gridColParts.join(" "),
      display: "grid",
      columnGap: "0.5rem"
    },
    columns: columns2
  };
};
const scrollContainer = "_scrollContainer_94id2_15";
const styles$5 = {
  scrollContainer
};
const columnOrder = ["transcript_id", "value", "explanation", "metadata"];
ModuleRegistry.registerModules([AllCommunityModule]);
const ScanResultsBody = () => {
  const selectedScanner = useSelectedScanner();
  const selectedResultsView = useStore((state) => state.selectedResultsView) || kSegmentList;
  const getSelectedScanResultData = useStore(
    (state) => state.getSelectedScanResultData
  );
  const columnTable = getSelectedScanResultData(selectedScanner);
  const isLoadingData = useStore((state) => state.loadingData);
  const isLoading = useStore((state) => state.loading);
  const hasScanner = (columnTable?.numRows() || 0) > 0;
  const error2 = useStore((state) => state.scopedErrors["dataframe"]);
  const dataframeWrapText = useStore((state) => state.dataframeWrapText);
  const setVisibleScannerResultsCount = useStore(
    (state) => state.setVisibleScannerResultsCount
  );
  const navigate = useNavigate();
  const params = useParams();
  const [searchParams] = useSearchParams();
  const relativePath = getRelativePathFromParams(params);
  const { scanPath } = parseScanResultPath(relativePath);
  const dataframeFilterColumns = useStore(
    (state) => state.dataframeFilterColumns
  );
  const sortedColumns = reactExports.useMemo(() => {
    const cols = dataframeFilterColumns || defaultColumns;
    return [...cols].sort(sortColumns);
  }, [dataframeFilterColumns]);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$5.scrollContainer), children: [
    hasScanner && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { style: { height: "100%", width: "100%" }, children: [
      selectedResultsView === kSegmentList && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        ScanResultsList,
        {
          columnTable,
          id: `scan-list-${selectedScanner}`
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsBody.tsx",
          lineNumber: 67,
          columnNumber: 13
        },
        void 0
      ),
      selectedResultsView === kSegmentDataframe && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        DataframeView,
        {
          options: { maxStrLen: 1024 },
          columnTable,
          sortedColumns,
          showRowNumbers: true,
          wrapText: dataframeWrapText,
          onRowDoubleClicked: (row2) => {
            const uuid = row2.uuid;
            if (uuid) {
              const route = scanResultRoute(scanPath, uuid, searchParams);
              void navigate(route);
            }
          },
          onVisibleRowCountChanged: setVisibleScannerResultsCount
        },
        void 0,
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsBody.tsx",
          lineNumber: 73,
          columnNumber: 13
        },
        void 0
      )
    ] }, void 0, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsBody.tsx",
      lineNumber: 65,
      columnNumber: 9
    }, void 0),
    !hasScanner && !isLoadingData && !isLoading && !error2 && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(NoContentsPanel, { text: "No scanner data available." }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsBody.tsx",
      lineNumber: 93,
      columnNumber: 9
    }, void 0),
    error2 && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      ErrorPanel,
      {
        title: "Error Loading Dataframe",
        error: { message: error2 }
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsBody.tsx",
        lineNumber: 96,
        columnNumber: 9
      },
      void 0
    )
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsBody.tsx",
    lineNumber: 63,
    columnNumber: 5
  }, void 0);
};
const sortColumns = (a2, b) => {
  const indexA = columnOrder.indexOf(a2);
  const indexB = columnOrder.indexOf(b);
  if (indexA === -1 && indexB === -1) {
    return 0;
  } else if (indexA === -1) {
    return 1;
  } else if (indexB === -1) {
    return -1;
  } else {
    return indexA - indexB;
  }
};
const container$3 = "_container_1a0yr_1";
const entry = "_entry_1a0yr_5";
const selected = "_selected_1a0yr_9";
const titleBlock = "_titleBlock_1a0yr_13";
const subTitle = "_subTitle_1a0yr_17";
const title = "_title_1a0yr_13";
const validationTable = "_validationTable_1a0yr_36";
const styles$4 = {
  container: container$3,
  entry,
  selected,
  titleBlock,
  subTitle,
  title,
  validationTable
};
const ScanResultsOutline = () => {
  const selectedStatus = useStore((state) => state.selectedScanStatus);
  const entries2 = toEntries(selectedStatus);
  const scanListHandle = reactExports.useRef(null);
  const renderRow = reactExports.useCallback(
    (index, entry2) => {
      return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ScanResultsRow, { index, entry: entry2 }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsOutline.tsx",
        lineNumber: 24,
        columnNumber: 14
      }, void 0);
    },
    []
  );
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$4.container), children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    LiveVirtualList,
    {
      id: "scans-toc-list",
      listHandle: scanListHandle,
      data: entries2,
      renderRow
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsOutline.tsx",
      lineNumber: 31,
      columnNumber: 7
    },
    void 0
  ) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsOutline.tsx",
    lineNumber: 30,
    columnNumber: 5
  }, void 0);
};
const ScanResultsRow = ({
  index,
  entry: entry2
}) => {
  const selectedScanner = useSelectedScanner();
  const setSelectedScanner = useStore((state) => state.setSelectedScanner);
  const [searchParams, setSearchParams] = useSearchParams();
  const handleClick = reactExports.useCallback(
    (title2) => {
      setSelectedScanner(title2);
      setSearchParams(updateScannerParam(searchParams, title2), {
        replace: true
      });
    },
    [setSelectedScanner, searchParams, setSearchParams]
  );
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "div",
    {
      className: clsx(
        styles$4.entry,
        selectedScanner === entry2.title ? styles$4.selected : ""
      ),
      onClick: () => {
        handleClick(entry2.title);
      },
      children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$4.titleBlock), children: [
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("text-size-large", styles$4.title), children: entry2.title }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsOutline.tsx",
            lineNumber: 70,
            columnNumber: 9
          }, void 0),
          entry2.params && entry2.params.length > 0 && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx("text-size-smallest", styles$4.subTitle), children: entry2.params.join("") }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsOutline.tsx",
            lineNumber: 74,
            columnNumber: 11
          }, void 0)
        ] }, void 0, true, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsOutline.tsx",
          lineNumber: 69,
          columnNumber: 7
        }, void 0),
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          LabeledValue,
          {
            label: "Positive Results",
            layout: "row",
            className: clsx("text-size-smallest"),
            children: entry2.results
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsOutline.tsx",
            lineNumber: 80,
            columnNumber: 7
          },
          void 0
        ),
        !!entry2.errors && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          LabeledValue,
          {
            label: "Errors",
            layout: "row",
            className: clsx("text-size-smallest"),
            children: entry2.errors
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsOutline.tsx",
            lineNumber: 89,
            columnNumber: 9
          },
          void 0
        ),
        entry2.validations !== void 0 && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          LabeledValue,
          {
            label: "Validations",
            layout: typeof entry2.validations === "number" ? "row" : "column",
            className: clsx("text-size-smallest"),
            children: typeof entry2.validations === "number" ? formatPercent(entry2.validations) : /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ValidationTable, { validations: entry2.validations }, void 0, false, {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsOutline.tsx",
              lineNumber: 107,
              columnNumber: 13
            }, void 0)
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsOutline.tsx",
            lineNumber: 99,
            columnNumber: 9
          },
          void 0
        )
      ]
    },
    index,
    true,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsOutline.tsx",
      lineNumber: 59,
      columnNumber: 5
    },
    void 0
  );
};
const toEntries = (status) => {
  if (!status) {
    return [];
  }
  const entries2 = [];
  for (const scanner of Object.keys(status.summary.scanners)) {
    const summary2 = status.summary.scanners[scanner];
    const scanInfo2 = status.spec.scanners[scanner];
    const formattedParams = [];
    if (scanInfo2) {
      const params = scanInfo2.params || {};
      for (const [key2, value2] of Object.entries(params)) {
        formattedParams.push(`${key2}=${JSON.stringify(value2)}`);
      }
    }
    const validations = summary2?.validations ? resolveValidations(summary2.validations) : void 0;
    entries2.push({
      icon: ApplicationIcons.scorer,
      title: scanner,
      results: summary2?.results || 0,
      scans: summary2?.scans || 0,
      tokens: summary2?.tokens,
      errors: summary2?.errors,
      params: formattedParams,
      validations
    });
  }
  return entries2;
};
const resolveValidations = (validations) => {
  if (validations.length === 0) {
    return void 0;
  }
  const first2 = validations[0];
  if (typeof first2 === "boolean") {
    const correct = validations.reduce((count2, v) => count2 + (v ? 1 : 0), 0);
    const total = validations.length;
    return correct / total;
  } else {
    const counts = {};
    const total = validations.length;
    for (const validation2 of validations) {
      if (typeof validation2 === "object") {
        for (const [key2, value2] of Object.entries(validation2)) {
          if (value2) {
            counts[key2] = (counts[key2] || 0) + 1;
          }
        }
      }
    }
    for (const key2 of Object.keys(counts)) {
      counts[key2] = (counts[key2] || 0) / total;
    }
    return counts;
  }
};
const ValidationTable = ({ validations }) => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$4.validationTable), children: Object.entries(validations).map(([key2, value2]) => /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(reactExports.Fragment, { children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$4.validationKey), children: key2 }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsOutline.tsx",
      lineNumber: 206,
      columnNumber: 11
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$4.validationValue), children: formatPercent(value2) }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsOutline.tsx",
      lineNumber: 207,
      columnNumber: 11
    }, void 0)
  ] }, key2, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsOutline.tsx",
    lineNumber: 205,
    columnNumber: 9
  }, void 0)) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsOutline.tsx",
    lineNumber: 203,
    columnNumber: 5
  }, void 0);
};
const container$2 = "_container_1db6h_1";
const footer = "_footer_1db6h_8";
const styles$3 = {
  container: container$2,
  footer
};
const ScanResultsPanel = () => {
  const visibleItemsCount = useStore(
    (state) => state.visibleScannerResultsCount
  );
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$3.container), children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ScanResultsOutline, {}, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsPanel.tsx",
      lineNumber: 17,
      columnNumber: 7
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ScanResultsBody, {}, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsPanel.tsx",
      lineNumber: 18,
      columnNumber: 7
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      Footer2,
      {
        id: "",
        className: styles$3.footer,
        itemCount: visibleItemsCount,
        paginated: false,
        labels: {
          singular: "result",
          plural: "results"
        }
      },
      void 0,
      false,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsPanel.tsx",
        lineNumber: 19,
        columnNumber: 7
      },
      void 0
    )
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsPanel.tsx",
    lineNumber: 16,
    columnNumber: 5
  }, void 0);
};
const container$1 = "_container_e1pcq_1";
const input = "_input_e1pcq_16";
const withIcon = "_withIcon_e1pcq_23";
const icon = "_icon_e1pcq_27";
const clearText = "_clearText_e1pcq_31";
const hidden = "_hidden_e1pcq_40";
const styles$2 = {
  container: container$1,
  input,
  withIcon,
  icon,
  clearText,
  hidden
};
const TextInput = reactExports.forwardRef(
  ({ value: value2, onChange, onFocus, icon: icon2, placeholder, className: className2 }, ref2) => {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "div",
      {
        className: clsx(
          styles$2.container,
          className2,
          icon2 ? styles$2.withIcon : ""
        ),
        children: [
          icon2 && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("i", { className: clsx(icon2, styles$2.icon) }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/TextInput.tsx",
            lineNumber: 27,
            columnNumber: 18
          }, void 0),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            "input",
            {
              type: "text",
              value: value2,
              onChange,
              ref: ref2,
              placeholder,
              className: clsx(styles$2.input),
              onFocus
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/TextInput.tsx",
              lineNumber: 28,
              columnNumber: 9
            },
            void 0
          ),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            "i",
            {
              className: clsx(
                styles$2.clearText,
                value2 === "" ? styles$2.hidden : "",
                ApplicationIcons["clear-text"]
              ),
              onClick: () => {
                if (onChange && value2 !== "") {
                  onChange({
                    target: { value: "" }
                  });
                }
              },
              role: "button"
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/TextInput.tsx",
              lineNumber: 37,
              columnNumber: 9
            },
            void 0
          )
        ]
      },
      void 0,
      true,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/components/TextInput.tsx",
        lineNumber: 20,
        columnNumber: 7
      },
      void 0
    );
  }
);
const ScanResultsSearch = () => {
  const scansSearchText = useStore((state) => state.scansSearchText);
  const setScansSearchText = useStore((state) => state.setScansSearchText);
  const handleChange = reactExports.useCallback((e) => {
    setScansSearchText(e.target.value);
  }, []);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    TextInput,
    {
      icon: ApplicationIcons.search,
      value: scansSearchText,
      onChange: handleChange,
      placeholder: "Search"
    },
    void 0,
    false,
    {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/results/ScanResultsSearch.tsx",
      lineNumber: 16,
      columnNumber: 5
    },
    void 0
  );
};
const tabSet = "_tabSet_10t9t_1";
const tabs = "_tabs_10t9t_5";
const tabControl = "_tabControl_10t9t_10";
const styles$1 = {
  tabSet,
  tabs,
  tabControl
};
const kTabIdScans = "scan-detail-tabs-results";
const kTabIdInfo = "scan-detail-tabs-info";
const kTabIdJson = "scan-detail-tabs-json";
const kSegmentList = "list";
const kSegmentDataframe = "dataframe";
const ScannerPanelBody = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  const selectedTab = useStore((state) => state.selectedResultsTab);
  const setSelectedResultsTab = useStore(
    (state) => state.setSelectedResultsTab
  );
  const selectedStatus = useStore((state) => state.selectedScanStatus);
  const selectedScanner = useStore((state) => state.selectedScanner);
  const visibleScannerResults = useStore(
    (state) => state.visibleScannerResults
  );
  const chooseColumnnsRef = reactExports.useRef(null);
  const [buttonElement, setButtonElement] = reactExports.useState(
    null
  );
  const gridFilter = useStore(
    (state) => state.gridStates[GRID_STATE_NAME]?.filter
  );
  const buttonRefCallback = (element) => {
    chooseColumnnsRef.current = element;
    setButtonElement(element);
  };
  reactExports.useEffect(() => {
    const tabParam = searchParams.get("tab");
    if (tabParam) {
      const validTabs = [kTabIdScans, kTabIdInfo, kTabIdJson];
      if (validTabs.includes(tabParam)) {
        setSelectedResultsTab(tabParam);
      }
    }
  }, [searchParams, setSelectedResultsTab]);
  const handleTabChange = (tabId) => {
    setSelectedResultsTab(tabId);
    setSearchParams({ tab: tabId });
  };
  const selectedResultsView = useStore((state) => state.selectedResultsView) || kSegmentList;
  const setSelectedResultsView = useStore(
    (state) => state.setSelectedResultsView
  );
  const groupOptions = reactExports.useMemo(() => {
    if (!visibleScannerResults || visibleScannerResults.length === 0) {
      return [];
    }
    const hasLabel = visibleScannerResults.some(
      (summary2) => summary2.label !== void 0 && summary2.label !== null
    );
    const logCount = visibleScannerResults.reduce((logs, summary2) => {
      const log3 = resultLog(summary2);
      if (log3) {
        logs.add(log3);
        return logs;
      } else {
        return logs;
      }
    }, /* @__PURE__ */ new Set()).size;
    const hasManyLogs = logCount > 1;
    const idStrs = visibleScannerResults.map((summary2) => resultIdentifierStr(summary2)).filter((id2) => id2 !== void 0);
    const hasRepeatedIds = idStrs.length !== new Set(idStrs).size;
    const epochStrs = visibleScannerResults.map((summary2) => summary2.transcriptMetadata.epoch).filter((e) => e !== void 0);
    const hasEpochs = new Set(epochStrs).size > 1;
    const options = [];
    if (hasLabel) {
      options.push("label");
    }
    if (hasManyLogs) {
      options.push("source");
    }
    if (hasRepeatedIds) {
      options.push("id");
    }
    if (hasEpochs) {
      options.push("epoch");
    }
    return options;
  }, [selectedScanner, visibleScannerResults]);
  const tools2 = [];
  if (selectedTab === kTabIdScans || selectedTab === void 0) {
    if (selectedResultsView === kSegmentList) {
      tools2.push(/* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ScanResultsSearch, {}, "scan-results-search", false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanelBody.tsx",
        lineNumber: 134,
        columnNumber: 18
      }, void 0));
    }
    if (selectedResultsView === kSegmentList) {
      tools2.push(/* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ScanResultsFilter, {}, "scan-results-filtering", false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanelBody.tsx",
        lineNumber: 138,
        columnNumber: 18
      }, void 0));
    }
    if (selectedResultsView === kSegmentDataframe) {
      tools2.push(
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ScanDataframeWrapTextButton, {}, "scan-dataframe-wrap-text", false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanelBody.tsx",
          lineNumber: 143,
          columnNumber: 9
        }, void 0)
      );
    }
    if (selectedResultsView === kSegmentDataframe) {
      tools2.push(
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          ScanDataframeFilterColumnsButton,
          {
            ref: buttonRefCallback
          },
          "scan-dataframe-filter-columns",
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanelBody.tsx",
            lineNumber: 149,
            columnNumber: 9
          },
          void 0
        )
      );
    }
    if (selectedResultsView === kSegmentDataframe && gridFilter) {
      tools2.push(/* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ScanDataframeClearFiltersButton, {}, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanelBody.tsx",
        lineNumber: 157,
        columnNumber: 18
      }, void 0));
    }
    if (selectedResultsView === kSegmentList && groupOptions.length > 0) {
      tools2.push(
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          ScanResultsGroup,
          {
            options: groupOptions
          },
          "scan-results-grouping",
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanelBody.tsx",
            lineNumber: 162,
            columnNumber: 9
          },
          void 0
        )
      );
    }
    tools2.push(
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        SegmentedControl,
        {
          selectedId: selectedResultsView,
          segments: [
            {
              id: kSegmentList,
              label: kSegmentList,
              icon: ApplicationIcons.file
            },
            {
              icon: ApplicationIcons.samples,
              id: kSegmentDataframe,
              label: kSegmentDataframe
            }
          ],
          onSegmentChange: (segmentId, _index) => {
            setSelectedResultsView(segmentId);
          }
        },
        "scan-results-view-segmented-control",
        false,
        {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanelBody.tsx",
          lineNumber: 170,
          columnNumber: 7
        },
        void 0
      )
    );
  }
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(jsxDevRuntimeExports.Fragment, { children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      TabSet,
      {
        id: "scan-detail-tabs",
        type: "pills",
        tabPanelsClassName: clsx(styles$1.tabSet),
        tabControlsClassName: clsx(styles$1.tabControl),
        className: clsx(styles$1.tabs),
        tools: tools2,
        children: [
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            TabPanel,
            {
              id: kTabIdScans,
              selected: selectedTab === kTabIdScans || selectedTab === void 0,
              title: "Results",
              onSelected: () => {
                handleTabChange(kTabIdScans);
              },
              children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ScanResultsPanel, {}, void 0, false, {
                fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanelBody.tsx",
                lineNumber: 210,
                columnNumber: 11
              }, void 0)
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanelBody.tsx",
              lineNumber: 202,
              columnNumber: 9
            },
            void 0
          ),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            TabPanel,
            {
              id: kTabIdInfo,
              selected: selectedTab === kTabIdInfo,
              title: "Info",
              onSelected: () => {
                handleTabChange(kTabIdInfo);
              },
              children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ScanInfo, {}, void 0, false, {
                fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanelBody.tsx",
                lineNumber: 221,
                columnNumber: 11
              }, void 0)
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanelBody.tsx",
              lineNumber: 213,
              columnNumber: 9
            },
            void 0
          ),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            TabPanel,
            {
              id: kTabIdJson,
              selected: selectedTab === kTabIdJson,
              title: "JSON",
              onSelected: () => {
                handleTabChange(kTabIdJson);
              },
              scrollable: true,
              children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
                JSONPanel,
                {
                  id: "task-json-contents",
                  data: selectedStatus,
                  simple: true
                },
                void 0,
                false,
                {
                  fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanelBody.tsx",
                  lineNumber: 232,
                  columnNumber: 11
                },
                void 0
              )
            },
            void 0,
            false,
            {
              fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanelBody.tsx",
              lineNumber: 223,
              columnNumber: 9
            },
            void 0
          )
        ]
      },
      void 0,
      true,
      {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanelBody.tsx",
        lineNumber: 194,
        columnNumber: 7
      },
      void 0
    ),
    selectedResultsView === kSegmentDataframe && buttonElement && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ScanDataframeColumnsPopover, { positionEl: buttonElement }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanelBody.tsx",
      lineNumber: 240,
      columnNumber: 9
    }, void 0)
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanelBody.tsx",
    lineNumber: 193,
    columnNumber: 5
  }, void 0);
};
const scanTitleView = "_scanTitleView_1vka4_1";
const leftColumn = "_leftColumn_1vka4_10";
const rightColumn = "_rightColumn_1vka4_18";
const secondaryRow = "_secondaryRow_1vka4_34";
const subtitle = "_subtitle_1vka4_47";
const styles = {
  scanTitleView,
  leftColumn,
  rightColumn,
  secondaryRow,
  subtitle
};
const ScannerPanelTitle = () => {
  const selectedStatus = useStore((state) => state.selectedScanStatus);
  const resultsDir = useStore((state) => state.resultsDir);
  const errorCount = selectedStatus?.errors.length || 0;
  const status = selectedStatus === void 0 ? "" : selectedStatus.complete ? "Complete" : "Incomplete";
  const scanJobName = selectedStatus?.spec.scan_name === "job" ? "scan" : selectedStatus?.spec.scan_name;
  const transcriptCount = selectedStatus?.spec.transcripts?.count || 0;
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles.scanTitleView), children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles.leftColumn), children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("h1", { children: [
        scanJobName,
        ":"
      ] }, void 0, true, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanelTitle.tsx",
        lineNumber: 31,
        columnNumber: 9
      }, void 0),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles.secondaryRow), children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("h2", { children: toRelativePath(selectedStatus?.location || "", resultsDir || "") }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanelTitle.tsx",
          lineNumber: 33,
          columnNumber: 11
        }, void 0),
        selectedStatus?.location && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          CopyButton,
          {
            className: clsx("text-size-small"),
            value: prettyDirUri(selectedStatus?.location)
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanelTitle.tsx",
            lineNumber: 37,
            columnNumber: 13
          },
          void 0
        )
      ] }, void 0, true, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanelTitle.tsx",
        lineNumber: 32,
        columnNumber: 9
      }, void 0),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", {}, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanelTitle.tsx",
        lineNumber: 43,
        columnNumber: 9
      }, void 0),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("h3", { className: clsx(styles.subtitle, "text-style-secondary"), children: selectedStatus?.spec.timestamp ? formatDateTime(new Date(selectedStatus?.spec.timestamp)) : "" }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanelTitle.tsx",
        lineNumber: 44,
        columnNumber: 9
      }, void 0)
    ] }, void 0, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanelTitle.tsx",
      lineNumber: 30,
      columnNumber: 7
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles.rightColumn, "text-size-smaller"), children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: [
        transcriptCount,
        " Transcripts"
      ] }, void 0, true, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanelTitle.tsx",
        lineNumber: 52,
        columnNumber: 9
      }, void 0),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: status }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanelTitle.tsx",
        lineNumber: 54,
        columnNumber: 9
      }, void 0),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: errorCount === 1 ? `${errorCount} Error` : errorCount > 1 ? `${errorCount} Errors` : "" }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanelTitle.tsx",
        lineNumber: 55,
        columnNumber: 9
      }, void 0)
    ] }, void 0, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanelTitle.tsx",
      lineNumber: 51,
      columnNumber: 7
    }, void 0)
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanelTitle.tsx",
    lineNumber: 29,
    columnNumber: 5
  }, void 0);
};
const ScannerPanel = () => {
  useServerScans();
  useServerScanner();
  useServerScannerDataframe();
  const loading = useStore((state) => state.loading);
  const clearScanState = useStore((state) => state.clearScanState);
  reactExports.useEffect(() => {
    clearScanState();
  }, []);
  const [searchParams] = useSearchParams();
  const setSelectedScanner = useStore((state) => state.setSelectedScanner);
  reactExports.useEffect(() => {
    const scannerParam = getScannerParam(searchParams);
    if (scannerParam) {
      setSelectedScanner(scannerParam);
    }
  }, [searchParams, setSelectedScanner]);
  const selectedStatus = useStore((state) => state.selectedScanStatus);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: clsx(styles$i.root), children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Navbar, {}, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanel.tsx",
      lineNumber: 47,
      columnNumber: 7
    }, void 0),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ActivityBar, { animating: !!loading }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanel.tsx",
      lineNumber: 48,
      columnNumber: 7
    }, void 0),
    selectedStatus && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(jsxDevRuntimeExports.Fragment, { children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ScannerPanelTitle, {}, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanel.tsx",
        lineNumber: 51,
        columnNumber: 11
      }, void 0),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ExtendedFindProvider, { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ScannerPanelBody, {}, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanel.tsx",
        lineNumber: 53,
        columnNumber: 13
      }, void 0) }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanel.tsx",
        lineNumber: 52,
        columnNumber: 11
      }, void 0)
    ] }, void 0, true, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanel.tsx",
      lineNumber: 50,
      columnNumber: 9
    }, void 0)
  ] }, void 0, true, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/app/scanner/ScannerPanel.tsx",
    lineNumber: 46,
    columnNumber: 5
  }, void 0);
};
class AppErrorBoundary extends reactExports.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }
  static getDerivedStateFromError(error2) {
    return { hasError: true, error: error2 };
  }
  componentDidCatch(error2, errorInfo) {
    console.log({ error: error2, errorInfo });
  }
  render() {
    if (this.state.hasError) {
      console.error({ e: this.state.error });
      if (this.state.error) {
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          ErrorPanel,
          {
            title: "An unexpected error occurred.",
            error: this.state.error
          },
          void 0,
          false,
          {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/AppErrorBoundary.tsx",
            lineNumber: 35,
            columnNumber: 11
          },
          this
        );
      } else {
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { children: "An unknown error with no additional information occured." }, void 0, false, {
          fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/AppErrorBoundary.tsx",
          lineNumber: 42,
          columnNumber: 11
        }, this);
      }
    }
    return this.props.children;
  }
}
function getEmbeddedScanState() {
  const embeddedState = document.getElementById(
    "scanview-state"
  );
  if (!embeddedState || !embeddedState.textContent) {
    return null;
  }
  try {
    const state = lib$1.parse(
      embeddedState.textContent
    );
    if (state.type === "updateState" && state.url) {
      const url = state.url;
      const dir = dirname(url);
      const scan2 = basename(url);
      return { dir, scan: scan2, scanner: state.scanner };
    }
  } catch (error2) {
    console.error("Failed to parse embedded state:", error2);
  }
  return null;
}
const AppLayout = () => {
  const navigate = useNavigate();
  const setResultsDir = useStore((state) => state.setResultsDir);
  const resultsDir = useStore((state) => state.resultsDir);
  const selectedScanner = useStore((state) => state.selectedScanner);
  const setSingleFileMode = useStore((state) => state.setSingleFileMode);
  const hasInitializedEmbeddedData = useStore(
    (state) => state.hasInitializedEmbeddedData
  );
  const hasInitializedRouting = useStore(
    (state) => state.hasInitializedRouting
  );
  const selectedScanResult = useStore((state) => state.selectedScanResult);
  const selectedScanLocation = useStore((state) => state.selectedScanLocation);
  const setSelectedScanner = useStore((state) => state.setSelectedScanner);
  const setHasInitializedEmbeddedData = useStore(
    (state) => state.setHasInitializedEmbeddedData
  );
  const setHasInitializedRouting = useStore(
    (state) => state.setHasInitializedRouting
  );
  const hasRestoredState = resultsDir !== void 0 && selectedScanner !== void 0;
  reactExports.useEffect(() => {
    if (hasInitializedEmbeddedData) {
      return;
    }
    const embeddedState = getEmbeddedScanState();
    if (embeddedState && !hasRestoredState) {
      const { dir, scan: scan2, scanner } = embeddedState;
      setResultsDir(dir);
      setSingleFileMode(true);
      if (scanner) {
        setSelectedScanner(scanner);
      }
      void navigate(`/scan/${scan2}`, { replace: true });
    }
    setHasInitializedEmbeddedData(true);
  }, [
    navigate,
    hasInitializedEmbeddedData,
    setSingleFileMode,
    setHasInitializedEmbeddedData,
    setResultsDir,
    setSelectedScanner,
    hasRestoredState
  ]);
  reactExports.useEffect(() => {
    if (hasInitializedRouting) {
      return;
    }
    const currentPath = window.location.hash.slice(1);
    const isDefaultRoute = currentPath === "/" || currentPath === "/scans" || currentPath === "";
    if (isDefaultRoute && selectedScanLocation) {
      if (selectedScanResult) {
        void navigate(`/scan/${selectedScanLocation}/${selectedScanResult}`, {
          replace: true
        });
      } else {
        void navigate(`/scan/${selectedScanLocation}`, { replace: true });
      }
    }
    setHasInitializedRouting(true);
  }, [
    hasInitializedEmbeddedData,
    hasInitializedRouting,
    selectedScanner,
    selectedScanLocation,
    selectedScanResult,
    navigate,
    setHasInitializedRouting
  ]);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(AppErrorBoundary, { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Outlet, {}, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/AppRouter.tsx",
    lineNumber: 122,
    columnNumber: 7
  }, void 0) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/AppRouter.tsx",
    lineNumber: 121,
    columnNumber: 5
  }, void 0);
};
const ScanOrScanResultsRoute = () => {
  const params = useParams();
  const relativePath = getRelativePathFromParams(params);
  const { scanResultUuid } = parseScanResultPath(relativePath);
  if (scanResultUuid) {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ScanResultPanel, {}, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/AppRouter.tsx",
      lineNumber: 137,
      columnNumber: 12
    }, void 0);
  }
  if (!isValidScanPath(relativePath)) {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Navigate, { to: `/scans/${relativePath}`, replace: true }, void 0, false, {
      fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/AppRouter.tsx",
      lineNumber: 143,
      columnNumber: 12
    }, void 0);
  }
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ScannerPanel, {}, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/AppRouter.tsx",
    lineNumber: 146,
    columnNumber: 10
  }, void 0);
};
const AppRouter = createHashRouter(
  [
    {
      path: "/",
      element: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(AppLayout, {}, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/AppRouter.tsx",
        lineNumber: 153,
        columnNumber: 16
      }, void 0),
      children: [
        {
          index: true,
          element: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Navigate, { to: "/scans", replace: true }, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/AppRouter.tsx",
            lineNumber: 157,
            columnNumber: 20
          }, void 0)
        },
        {
          path: kScansRouteUrlPattern,
          element: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ScanJobsPanel, {}, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/AppRouter.tsx",
            lineNumber: 161,
            columnNumber: 20
          }, void 0)
        },
        {
          path: kScansWithPathRouteUrlPattern,
          element: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ScanJobsPanel, {}, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/AppRouter.tsx",
            lineNumber: 165,
            columnNumber: 20
          }, void 0)
        },
        {
          path: kScanRouteUrlPattern,
          element: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ScanOrScanResultsRoute, {}, void 0, false, {
            fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/AppRouter.tsx",
            lineNumber: 169,
            columnNumber: 20
          }, void 0)
        }
      ]
    },
    {
      path: "*",
      element: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Navigate, { to: "/scans", replace: true }, void 0, false, {
        fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/AppRouter.tsx",
        lineNumber: 175,
        columnNumber: 16
      }, void 0)
    }
  ],
  { basename: "" }
);
Prism.languages.clike = {
  "comment": [
    {
      pattern: /(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,
      lookbehind: true,
      greedy: true
    },
    {
      pattern: /(^|[^\\:])\/\/.*/,
      lookbehind: true,
      greedy: true
    }
  ],
  "string": {
    pattern: /(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,
    greedy: true
  },
  "class-name": {
    pattern: /(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+|\bcatch\s+\()[\w.\\]+/i,
    lookbehind: true,
    inside: {
      "punctuation": /[.\\]/
    }
  },
  "keyword": /\b(?:break|catch|continue|do|else|finally|for|function|if|in|instanceof|new|null|return|throw|try|while)\b/,
  "boolean": /\b(?:false|true)\b/,
  "function": /\b\w+(?=\()/,
  "number": /\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,
  "operator": /[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,
  "punctuation": /[{}[\];(),.:]/
};
Prism.languages.javascript = Prism.languages.extend("clike", {
  "class-name": [
    Prism.languages.clike["class-name"],
    {
      pattern: /(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,
      lookbehind: true
    }
  ],
  "keyword": [
    {
      pattern: /((?:^|\})\s*)catch\b/,
      lookbehind: true
    },
    {
      pattern: /(^|[^.]|\.\.\.\s*)\b(?:as|assert(?=\s*\{)|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally(?=\s*(?:\{|$))|for|from(?=\s*(?:['"]|$))|function|(?:get|set)(?=\s*(?:[#\[$\w\xA0-\uFFFF]|$))|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,
      lookbehind: true
    }
  ],
  // Allow for all non-ASCII characters (See http://stackoverflow.com/a/2008444)
  "function": /#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,
  "number": {
    pattern: RegExp(
      /(^|[^\w$])/.source + "(?:" + // constant
      (/NaN|Infinity/.source + "|" + // binary integer
      /0[bB][01]+(?:_[01]+)*n?/.source + "|" + // octal integer
      /0[oO][0-7]+(?:_[0-7]+)*n?/.source + "|" + // hexadecimal integer
      /0[xX][\dA-Fa-f]+(?:_[\dA-Fa-f]+)*n?/.source + "|" + // decimal bigint
      /\d+(?:_\d+)*n/.source + "|" + // decimal number (integer or float) but no bigint
      /(?:\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\.\d+(?:_\d+)*)(?:[Ee][+-]?\d+(?:_\d+)*)?/.source) + ")" + /(?![\w$])/.source
    ),
    lookbehind: true
  },
  "operator": /--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/
});
Prism.languages.javascript["class-name"][0].pattern = /(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/;
Prism.languages.insertBefore("javascript", "keyword", {
  "regex": {
    pattern: RegExp(
      // lookbehind
      // eslint-disable-next-line regexp/no-dupe-characters-character-class
      /((?:^|[^$\w\xA0-\uFFFF."'\])\s]|\b(?:return|yield))\s*)/.source + // Regex pattern:
      // There are 2 regex patterns here. The RegExp set notation proposal added support for nested character
      // classes if the `v` flag is present. Unfortunately, nested CCs are both context-free and incompatible
      // with the only syntax, so we have to define 2 different regex patterns.
      /\//.source + "(?:" + /(?:\[(?:[^\]\\\r\n]|\\.)*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}/.source + "|" + // `v` flag syntax. This supports 3 levels of nested character classes.
      /(?:\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.)*\])*\])*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}v[dgimyus]{0,7}/.source + ")" + // lookahead
      /(?=(?:\s|\/\*(?:[^*]|\*(?!\/))*\*\/)*(?:$|[\r\n,.;:})\]]|\/\/))/.source
    ),
    lookbehind: true,
    greedy: true,
    inside: {
      "regex-source": {
        pattern: /^(\/)[\s\S]+(?=\/[a-z]*$)/,
        lookbehind: true,
        alias: "language-regex",
        inside: Prism.languages.regex
      },
      "regex-delimiter": /^\/|\/$/,
      "regex-flags": /^[a-z]+$/
    }
  },
  // This must be declared before keyword because we use "function" inside the look-forward
  "function-variable": {
    pattern: /#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/,
    alias: "function"
  },
  "parameter": [
    {
      pattern: /(function(?:\s+(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)?\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\))/,
      lookbehind: true,
      inside: Prism.languages.javascript
    },
    {
      pattern: /(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,
      lookbehind: true,
      inside: Prism.languages.javascript
    },
    {
      pattern: /(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,
      lookbehind: true,
      inside: Prism.languages.javascript
    },
    {
      pattern: /((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*)\(\s*|\]\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*\{)/,
      lookbehind: true,
      inside: Prism.languages.javascript
    }
  ],
  "constant": /\b[A-Z](?:[A-Z_]|\dx?)*\b/
});
Prism.languages.insertBefore("javascript", "string", {
  "hashbang": {
    pattern: /^#!.*/,
    greedy: true,
    alias: "comment"
  },
  "template-string": {
    pattern: /`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,
    greedy: true,
    inside: {
      "template-punctuation": {
        pattern: /^`|`$/,
        alias: "string"
      },
      "interpolation": {
        pattern: /((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,
        lookbehind: true,
        inside: {
          "interpolation-punctuation": {
            pattern: /^\$\{|\}$/,
            alias: "punctuation"
          },
          rest: Prism.languages.javascript
        }
      },
      "string": /[\s\S]+/
    }
  },
  "string-property": {
    pattern: /((?:^|[,{])[ \t]*)(["'])(?:\\(?:\r\n|[\s\S])|(?!\2)[^\\\r\n])*\2(?=\s*:)/m,
    lookbehind: true,
    greedy: true,
    alias: "property"
  }
});
Prism.languages.insertBefore("javascript", "operator", {
  "literal-property": {
    pattern: /((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,
    lookbehind: true,
    alias: "property"
  }
});
if (Prism.languages.markup) {
  Prism.languages.markup.tag.addInlined("script", "javascript");
  Prism.languages.markup.tag.addAttribute(
    /on(?:abort|blur|change|click|composition(?:end|start|update)|dblclick|error|focus(?:in|out)?|key(?:down|up)|load|mouse(?:down|enter|leave|move|out|over|up)|reset|resize|scroll|select|slotchange|submit|unload|wheel)/.source,
    "javascript"
  );
}
Prism.languages.js = Prism.languages.javascript;
const App = () => {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(RouterProvider2, { router: AppRouter }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/App.tsx",
    lineNumber: 15,
    columnNumber: 10
  }, void 0);
};
let vscodeApi;
const getVscodeApi = () => {
  if (window.acquireVsCodeApi) {
    if (vscodeApi === void 0) {
      vscodeApi = window.acquireVsCodeApi();
    }
    return vscodeApi;
  } else {
    return void 0;
  }
};
const containerId = "app";
const container = document.getElementById(containerId);
if (!container) {
  console.error("Root container not found");
  throw new Error(
    `Expected a container element with Id '${containerId}' but no such container element was present.`
  );
}
const root = clientExports.createRoot(container);
const selectApi = () => {
  const vscodeApi2 = getVscodeApi();
  if (vscodeApi2) {
    const vscodeClient = webViewJsonRpcClient(vscodeApi2);
    return apiVscode(vscodeApi2, vscodeClient);
  } else {
    return apiScoutServer();
  }
};
const api = selectApi();
const store = createStore$1(api);
root.render(
  /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ApiProvider, { value: api, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(StoreProvider, { value: store, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(App, {}, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/main.tsx",
    lineNumber: 47,
    columnNumber: 7
  }, void 0) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/main.tsx",
    lineNumber: 46,
    columnNumber: 5
  }, void 0) }, void 0, false, {
    fileName: "/Users/charlesteague/Development/meridianlabs-ai/inspect_scout/src/inspect_scout/_view/www/src/main.tsx",
    lineNumber: 45,
    columnNumber: 3
  }, void 0)
);
//# sourceMappingURL=index.js.map
